Skip to content

Commit

Permalink
Merge pull request #61 from DenisKolodin/more-docs
Browse files Browse the repository at this point in the history
Add a documentation
  • Loading branch information
Penny Wing committed Dec 31, 2017
2 parents ed48aac + 381ab11 commit f422ce5
Show file tree
Hide file tree
Showing 16 changed files with 319 additions and 9 deletions.
44 changes: 44 additions & 0 deletions src/html.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
//! The main module which contents aliases to necessary items
//! to create a template and implement `update` and `view` functions.
use stdweb;

use std::rc::Rc;
Expand All @@ -7,42 +10,54 @@ use stdweb::web::{INode, EventListenerHandle, document};
use stdweb::web::event::{IMouseEvent, IKeyboardEvent};
use virtual_dom::{VNode, VTag, Messages, Listener};

/// Removes anything from the `body`.
fn clear_body() {
let body = document().query_selector("body").unwrap();
while body.has_child_nodes() {
body.remove_child(&body.last_child().unwrap()).unwrap();
}
}

/// This class keeps a sender to a context to send a messages to a loop
/// and to schedule the next update call.
pub struct ContextSender<MSG> {
tx: Sender<MSG>,
}

impl<MSG> ContextSender<MSG> {
/// Send the message and schedule an update.
pub fn send(&mut self, msg: MSG) {
self.tx.send(msg).expect("Context lost the receiver!");
schedule_update();
}
}

/// A context which contains a bridge to send a messages to a loop.
/// Mostly services uses it.
pub struct Context<MSG> {
tx: Sender<MSG>,
rx: Receiver<MSG>,
}

impl<MSG> Context<MSG> {
/// Creates a context with connected sender and receiver.
fn new() -> Self {
let (tx, rx) = channel();
Context { tx, rx }
}

/// Returs a cloned sender.
pub fn sender(&mut self) -> ContextSender<MSG> {
ContextSender {
tx: self.tx.clone(),
}
}
}

/// The main entrypoint of a yew program. It works similar as `program`
/// function in Elm. You should provide an initial model, `update` function
/// which will update the state of the model and a `view` function which
/// will render the model to a virtual DOM tree.
pub fn program<M, MSG, U, V>(mut model: M, update: U, view: V)
where
M: 'static,
Expand Down Expand Up @@ -83,17 +98,22 @@ where
stdweb::event_loop();
}

/// A type which expected as a result of `view` function implementation.
pub type Html<MSG> = VTag<MSG>;

macro_rules! impl_action {
($($action:ident($event:ident : $type:ident) -> $ret:ty => $convert:expr)*) => {$(
/// An abstract implementation of a listener.
pub mod $action {
use stdweb::web::{IEventTarget, Element};
use stdweb::web::event::{IEvent, $type};
use super::*;

/// A wrapper for a callback.
/// Listener extracted from here when attached.
pub struct Wrapper<F>(Option<F>);

/// And event type which keeps the returned type.
pub type Event = $ret;

impl<F, MSG> From<F> for Wrapper<F>
Expand Down Expand Up @@ -167,11 +187,28 @@ impl_action! {
}
}

/// A type representing data from `onclick` and `ondoubleclick` event.
#[derive(Debug)]
pub struct MouseData {
/// The screenX read-only property of the
/// [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/screenX)
/// property provides the horizontal coordinate (offset)
/// of the mouse pointer in global (screen) coordinates.
pub screen_x: f64,
/// The screenY read-only property of the
/// [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/screenY)
/// property provides the vertical coordinate (offset)
/// of the mouse pointer in global (screen) coordinates.
pub screen_y: f64,
/// The clientX read-only property of the
/// [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX)
/// interface provides the horizontal coordinate within
/// the application's client area at which the event occurred
pub client_x: f64,
/// The clientY read-only property of the
/// [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX)
/// interface provides the vertical coordinate within
/// the application's client area at which the event occurred
pub client_y: f64,
}

Expand All @@ -186,13 +223,19 @@ impl<T: IMouseEvent> From<T> for MouseData {
}
}

/// A type representing data from `oninput` event.
#[derive(Debug)]
pub struct InputData {
/// Inserted characters. Contains value from
/// [InputEvent](https://developer.mozilla.org/en-US/docs/Web/API/InputEvent/data).
pub value: String,
}

/// A type representing data from `onkeypress` event.
#[derive(Debug)]
pub struct KeyData {
/// Value of a pressed key. Contains key name from
/// [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).
pub key: String,
}

Expand All @@ -202,6 +245,7 @@ impl<T: IKeyboardEvent> From<T> for KeyData {
}
}

/// A bridging type for checking `href` attribute value.
#[derive(Debug)]
pub struct Href {
link: String,
Expand Down
50 changes: 50 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,53 @@
//! # Yew Framework - API Documentation
//!
//! Yew is a framework for web-client apps created with
//! a modern Rust-to-Wasm compilation feature.
//! This framework was highly inspired by
//! [Elm](http://elm-lang.org/) and [React](https://reactjs.org/).
//!
//! Minimal example:
//!
//! ```rust
//! extern crate yew;
//! use yew::html::*;
//!
//! struct Model {
//! value: i64,
//! }
//!
//! enum Msg {
//! DoIt,
//! }
//!
//! fn update(context: &mut Context<Msg>, model: &mut Model, msg: Msg) {
//! match msg {
//! Msg::DoIt => {
//! model.value = model.value + 1;
//! }
//! }
//! }
//!
//! fn view(model: &Model) -> Html<Msg> {
//! html! {
//! <div>
//! <button onclick=|_| Msg::Increment,>{ "Add +1" }</button>
//! <p>{ model.value }</p>
//! </div>
//! }
//! }
//!
//! fn main() {
//! let model = Model {
//! value: 0,
//! };
//! program(model, update, view);
//! }
//! ```
//!
#![deny(
missing_docs,
)]
#![recursion_limit="256"]

extern crate serde;
Expand Down
3 changes: 3 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
//! This module contains macros which implements `html!` macro
//! and JSX-like templates.
use virtual_dom::{VTag, VNode, Listener};

#[macro_export]
Expand Down
6 changes: 6 additions & 0 deletions src/services/alert.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
//! This module contains the implementation of a service
//! to show alerts in a browser.
use html::Context;

/// An abstract alert service.
pub trait AlertService {
/// Calls [alert](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert)
/// function.
fn alert(&mut self, message: &str);
}

Expand Down
54 changes: 54 additions & 0 deletions src/services/console.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,86 @@
//! This module contains a service implementation to use browser's console.
use html::Context;

/// A service to use methods of a
/// [Console](https://developer.mozilla.org/en-US/docs/Web/API/Console).
pub struct Console;

impl Console {
/// [console.log](https://developer.mozilla.org/en-US/docs/Web/API/Console/log)
/// method implementation.
pub fn log(&self, message: &str) { js! { console.log(@{message}); } }

/// [console.warn](https://developer.mozilla.org/en-US/docs/Web/API/Console/warn)
/// method implementation.
pub fn warn(&self, message: &str) { js! { console.warn(@{message}); } }

/// [console.info](https://developer.mozilla.org/en-US/docs/Web/API/Console/info)
/// method implementation.
pub fn info(&self, message: &str) { js! { console.info(@{message}); } }

/// [console.error](https://developer.mozilla.org/en-US/docs/Web/API/Console/error)
/// method implementation.
pub fn error(&self, message: &str) { js! { console.error(@{message}); } }

/// [console.debug](https://developer.mozilla.org/en-US/docs/Web/API/Console/debug)
/// method implementation.
pub fn debug(&self, message: &str) { js! { console.debug(@{message}); } }

/// [console.count_named](https://developer.mozilla.org/en-US/docs/Web/API/Console/count_named)
/// method implementation.
pub fn count_named(&self, name: &str) { js! { console.count(@{name}); } }

/// [console.count](https://developer.mozilla.org/en-US/docs/Web/API/Console/count)
/// method implementation.
pub fn count(&self) { js! { console.count(); } }


/// [console.time_named](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_named)
/// method implementation.
pub fn time_named(&self, name: &str) { js! { console.time(@{name}); } }

/// [console.time_named_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_named_end)
/// method implementation.
pub fn time_named_end(&self, name: &str) { js! { console.timeEnd(@{name}); } }


/// [console.time](https://developer.mozilla.org/en-US/docs/Web/API/Console/time)
/// method implementation.
pub fn time(&self) { js! { console.time(); } }
/// [console.time_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_end)
/// method implementation.
pub fn time_end(&self) { js! { console.timeEnd(); } }


/// [console.clear](https://developer.mozilla.org/en-US/docs/Web/API/Console/clear)
/// method implementation.
pub fn clear(&self) { js! { console.clear(); } }

/// [console.group](https://developer.mozilla.org/en-US/docs/Web/API/Console/group)
/// method implementation.
pub fn group(&self) { js! { console.group(); } }

/// [console.group_collapsed](https://developer.mozilla.org/en-US/docs/Web/API/Console/group_collapsed)
/// method implementation.
pub fn group_collapsed(&self) { js! { console.groupCollapsed(); } }

/// [console.group_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/group_end)
/// method implementation.
pub fn group_end(&self) { js! { console.groupEnd(); } }

/// [console.trace](https://developer.mozilla.org/en-US/docs/Web/API/Console/trace)
/// method implementation.
pub fn trace(&self) { js! { console.trace(); } }

/// [console.assert](https://developer.mozilla.org/en-US/docs/Web/API/Console/assert)
/// method implementation.
pub fn assert(&self, condition: bool, message: &str) { js! { console.assert(@{condition}, @{message}); } }
}

/// An abstract service which return a `Console` instance.
pub trait ConsoleService {
/// Returns console from a context.
fn get_console(&self) -> Console;
}

Expand Down
10 changes: 10 additions & 0 deletions src/services/fetch.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
//! Service to send HTTP-request to a server.
use stdweb::Value;
use html::Context;
use services::format::{Storable, Restorable};
use super::Task;

/// A handle to control sent request. Could be canceled by `Task::cancel` call.
pub struct FetchHandle(Option<Value>);

/// A method of HTTP-request of [HTTP protocol](https://tools.ietf.org/html/rfc7231).
pub enum Method {
/// `GET` method of a request.
Get,
/// `POST` method of a request.
Post,
}

impl Method {
/// Converts a method to `fetch` input argument.
fn to_argument(&self) -> &'static str {
match self {
&Method::Get => "GET",
Expand All @@ -19,7 +26,10 @@ impl Method {
}
}

/// An abstract service to fetch resources from a context.
pub trait FetchService<MSG> {
/// Sends request to a server. Could contains input data and
/// needs a fuction to convert returned data to a loop's message.
fn fetch<F, IN, OUT>(&mut self, method: Method, url: &str, data: IN, converter: F) -> FetchHandle
where
IN: Into<Storable>,
Expand Down
19 changes: 19 additions & 0 deletions src/services/format.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
//! Utility module to convert data to types and back by
//! specific formats like: JSON, BSON, TOML, YAML, XML.
//!
//! All types here are lazy and it's necessary to
//! use `Into` and `From` traits to get (convert) the data.
use serde::{Serialize, Deserialize};
use serde_json;

/// A representation of a value which can be stored.
pub type Storable = Option<String>;

/// A representation of a value which can be restored.
pub type Restorable = Result<String, String>;

/// A representation of an empty data. Nothing stored. Nothing restored.
pub struct Nothing;

impl Into<Storable> for Nothing {
Expand All @@ -19,6 +28,16 @@ impl From<Restorable> for Nothing {
}
}

/// A representation of a JSON data. Use it as wrapper to
/// set a format you want to use for conversion:
///
/// ```rust
/// // Converts (lazy) data to a Json
/// let dump = Json(&data);
///
/// // Converts JSON string to a data (lazy).
/// let Json(data) = dump;
/// ```
pub struct Json<T>(pub T);

impl<'a, T> Into<Storable> for Json<&'a T>
Expand Down
8 changes: 8 additions & 0 deletions src/services/interval.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
//! This module contains the implementation of a service for
//! periodic sending messages to a loop.
use std::time::Duration;
use stdweb::Value;
use html::Context;
use super::{Task, to_ms};

/// A handle which helps to cancel interval. Uses
/// [clearInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval).
pub struct IntervalHandle(Option<Value>);

/// An abstract service to send messages on every elapsed interval.
pub trait IntervalService<MSG> {
/// Sets interval which will call send a messages returned by a converter
/// on every intarval expiration.
fn interval<F>(&mut self, duration: Duration, converter: F) -> IntervalHandle
where
F: Fn() -> MSG + 'static;
Expand Down
Loading

0 comments on commit f422ce5

Please sign in to comment.