20

GitHub - yewstack/yew: Rust / Wasm framework for building client web apps

 4 years ago
source link: https://github.com/yewstack/yew
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md

yew.svg?sanitize=true

Yew   Build Status

Rust / Wasm client web app framework

Build Status Gitter Chat Rustc Version 1.39+

Website | API Docs | Examples | Changelog | Roadmap | Code of Conduct

Overview

Yew is a modern Rust framework inspired by Elm and React for creating multi-threaded frontend apps with WebAssembly.

The framework supports multi-threading & concurrency out of the box. It uses Web Workers API to spawn actors (agents) in separate threads and uses a local scheduler attached to a thread for concurrent tasks.

Become a sponsor on Patreon

Check out a live demo powered by yew-wasm-pack-template

Cutting Edge technologies

Rust to WASM compilation

This framework is designed to be compiled into modern browsers' runtimes: wasm, asm.js, emscripten.

Architecture inspired by Elm and Redux

Yew implements strict application state management based on message passing and updates:

src/main.rs

use yew::{html, Component, ComponentLink, Html, ShouldRender};

struct Model {
    link: ComponentLink<Self>,
}

enum Msg {
    DoIt,
}

impl Component for Model {
    // Some details omitted. Explore the examples to see more.

    type Message = Msg;
    type Properties = ();

    fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
        Model { link }
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        match msg {
            Msg::DoIt => {
                // Update your model on events
                true
            }
        }
    }

    fn view(&self) -> Html {
        let onclick = self.link.callback(|_| Msg::DoIt);
        html! {
            // Render your model here
            <button onclick=onclick>{ "Click me!" }</button>
        }
    }
}

fn main() {
    yew::start_app::<Model>();
}

Predictable mutability and lifetimes (thanks Rust!) make it possible to reuse a single instance of the model without a need to create a fresh one on every update. It also helps to reduce memory allocations.

JSX-like templates with html! macro

Feel free to put pure Rust code into HTML tags with all the compiler and borrow checker's benefits.

html! {
    <section class="todoapp">
        <header class="header">
            <h1>{ "todos" }</h1>
            { view_input(&model) }
        </header>
        <section class="main">
            <input class="toggle-all"
                   type="checkbox"
                   checked=model.is_all_completed()
                   onclick=|_| Msg::ToggleAll />
            { view_entries(&model) }
        </section>
    </section>
}

Agents - actor model inspired by Erlang and Actix

Every Component can spawn an agent and attach to it. Agents can coordinate global state, spawn long-running tasks, and offload tasks to a web worker. They run independently of components, but hook nicely into their update mechanism.

use yew::worker::*;

struct Worker {
    link: AgentLink<Worker>,
}

#[derive(Serialize, Deserialize, Debug)]
pub enum Request {
    Question(String),
}

#[derive(Serialize, Deserialize, Debug)]
pub enum Response {
    Answer(String),
}

impl Agent for Worker {
    // Available:
    // - `Job` (one per bridge on the main thread)
    // - `Context` (shared in the main thread)
    // - `Private` (one per bridge in a separate thread)
    // - `Public` (shared in a separate thread)
    type Reach = Context; // Spawn only one instance on the main thread (all components can share this agent)
    type Message = Msg;
    type Input = Request;
    type Output = Response;

    // Create an instance with a link to the agent.
    fn create(link: AgentLink<Self>) -> Self {
        Worker { link }
    }

    // Handle inner messages (from callbacks)
    fn update(&mut self, msg: Self::Message) { /* ... */ }

    // Handle incoming messages from components of other agents.
    fn handle_input(&mut self, msg: Self::Input, who: HandlerId) {
        match msg {
            Request::Question(_) => {
                self.link.respond(who, Response::Answer("That's cool!".into()));
            },
        }
    }
}

Build the bridge to an instance of this agent. It spawns a worker automatically or reuses an existing one, depending on the type of the agent:

struct Model {
    context: Box<Bridge<context::Worker>>,
}

enum Msg {
    ContextMsg(context::Response),
}

impl Component for Model {
    type Message = Msg;
    type Properties = ();

    fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
        let callback = link.callback(|message| Msg::ContextMsg(message));
        // `Worker::bridge` spawns an instance if no one is available
        let context = context::Worker::bridge(callback); // Connected! :tada:
        Model { context }
    }
}

You can use as many agents as you want. For example you could separate all interactions with a server to a separate thread (a real OS thread because Web Workers map to the native threads).

REMEMBER! Not every API is available for every environment. For example you can't use StorageService from a separate thread. It won't work with Public or Private agents, only with Job and Context ones.

Components

Yew supports components! You could create a new one by implementing a Component trait and including it directly into the html! template:

html! {
    <nav class="menu">
        <MyButton title="First Button" />
        <MyButton title="Second Button "/>
        <MyList name="Grocery List">
          <MyListItem text="Apples" />
        </MyList>
    </nav>
}

Scopes

Components live in an Angular-like scopes with parent-to-child (properties) and child-to-parent (events) interaction.

Properties are also pure Rust types with strict type-checking during the compilation.

// my_button.rs

#[derive(Clone, Properties, PartialEq)]
pub struct Properties {
    pub hidden: bool,
    #[props(required)]
    pub color: Color,
    #[props(required)]
    pub onclick: Callback<()>,
}
// confirm_dialog.rs

html! {
    <div class="confirm-dialog">
        <MyButton onclick=|_| DialogMsg::Cancel color=Color::Red hidden=true />
        <MyButton onclick=|_| DialogMsg::Submit color=Color::Blue />
    </div>
}

Fragments

Yew supports fragments: elements without a parent which can be attached to one somewhere else.

html! {
    <>
        <tr><td>{ "Row" }</td></tr>
        <tr><td>{ "Row" }</td></tr>
        <tr><td>{ "Row" }</td></tr>
    </>
}

Virtual DOM

Yew uses its own virtual-dom implementation. It updates the browser's DOM with tiny patches when properties of elements have changed. Every component can be interacted with using its (Scope) to pass messages and trigger updates.

The ShouldRender returns the value which informs the loop when the component should be re-rendered:

fn update(&mut self, msg: Self::Message) -> ShouldRender {
    match msg {
        Msg::UpdateValue(value) => {
            self.value = value;
            true
        }
        Msg::Ignore => {
            false
        }
    }
}

Using ShouldRender is more effective than comparing the model after every update because not every change to the model causes an update to the view. It allows the framework to only compare parts of the model essential to rendering the view.

Rust/JS/C-style comments in templates

Use single-line or multi-line Rust comments inside html-templates.

html! {
    <section>
   /* Write some ideas
    * in multiline comments
    */
    <p>{ "and tags can be placed between comments!" }</p>
    // <li>{ "or single-line comments" }</li>
    </section>
}

Third-party crates and pure Rust expressions inside

Use external crates and put values from them into the template:

extern crate chrono;
use chrono::prelude::*;

impl Renderable for Model {
    fn render(&self) -> Html {
        html! {
            <p>{ Local::now() }</p>
        }
    }
}

Some crates don't support the wasm32-unknown-unknown target yet.

Services

Yew has implemented pluggable services that allow you to call external APIs, such as: JavaScript alerts, timeout, storage, fetches and websockets. It's a handy alternative to subscriptions.

Implemented:

  • IntervalService
  • RenderService
  • ResizeService
  • TimeoutService
  • StorageService
  • DialogService
  • ConsoleService
  • FetchService
  • WebSocketService
  • KeyboardService
use yew::services::{ConsoleService, TimeoutService};

struct Model {
    link: ComponentLink<Model>,
    console: ConsoleService,
    timeout: TimeoutService,
}

impl Component for Model {
    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        match msg {
            Msg::Fire => {
                let timeout = self.link.callback(|_| Msg::Timeout);
                self.timeout.spawn(Duration::from_secs(5), timeout);
            }
            Msg::Timeout => {
                self.console.log("Timeout!");
            }
        }
    }
}

Can't find an essential service? Want to use a library from npm? You can wrap JavaScript libraries using stdweb and create your own service implementation. Here's an example below of how to wrap the ccxt library:

pub struct CcxtService(Option<Value>);

impl CcxtService {
    pub fn new() -> Self {
        let lib = js! {
            return ccxt;
        };
        CcxtService(Some(lib))
    }

    pub fn exchanges(&mut self) -> Vec<String> {
        let lib = self.0.as_ref().expect("ccxt library object lost");
        let v: Value = js! {
            var ccxt = @{lib};
            console.log(ccxt.exchanges);
            return ccxt.exchanges;
        };
        let v: Vec<String> = v.try_into().expect("can't extract exchanges");
        v
    }

    // Wrap more methods here!
}

Easy-to-use data conversion and destructuring

Yew allows for serialization (store/send and restore/receive) formats.

Implemented: JSON, TOML, YAML, MSGPACK, CBOR.

In development: BSON, XML.

use yew::format::Json;

#[derive(Serialize, Deserialize)]
struct Client {
    first_name: String,
    last_name: String,
}

struct Model {
    local_storage: StorageService,
    clients: Vec<Client>,
}

impl Component for Model {
    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        Msg::Store => {
            // Stores it, but in JSON format/layout
            self.local_storage.store(KEY, Json(&model.clients));
        }
        Msg::Restore => {
            // Tries to read and destructure it as JSON formatted data
            if let Json(Ok(clients)) = self.local_storage.restore(KEY) {
                model.clients = clients;
            }
        }
    }
}

Only JSON is available by default but you can activate the rest through features in your project's Cargo.toml:

[dependencies]
yew = { git = "https://github.com/yewstack/yew", features = ["toml", "yaml", "msgpack", "cbor"] }

Development setup

Clone or download this repository.

Install cargo-web

This is an optional tool that simplifies deploying web applications:

cargo install cargo-web

Add --force option to ensure you install the latest version.

Build

cargo web build

# without cargo-web, only the wasm32-unknown-unknown target is supported
cargo build --target wasm32-unknown-unknown

Running Tests

For the tests to work one have to ensure that wasm-bindgen-cli is installed. Instructions

Additionally a webdriver must be installed locally and configured to be on the PATH. Currently supports geckodriver, chromedriver, and safaridriver, although more driver support may be added! You can download these at:

./ci/run_tests.sh

Running the examples

There are many examples that show how the framework works: counter, crm, custom_components, dashboard, fragments, game_of_life, mount_point, npm_and_rest, timer, todomvc, two_apps.

To start an example enter its directory and start it with cargo-web:

cargo web start

To run an optimised build instead of a debug build use:

cargo web start --release

This will use the wasm32-unknown-unknown target by default, which is Rust's native WebAssembly target. The Emscripten-based wasm32-unknown-emscripten and asmjs-unknown-emscripten targets are also supported if you tell the cargo-web to build for them using the --target parameter.

Project templates

Contributors

Code Contributors

This project exists thanks to all the people who contribute. 68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f636f6e7472696275746f72732e7376673f77696474683d38393026627574746f6e3d66616c7365

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f696e646976696475616c732e7376673f77696474683d383930

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f6f7267616e697a6174696f6e2f302f6176617461722e737667 68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f6f7267616e697a6174696f6e2f312f6176617461722e737667 68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f6f7267616e697a6174696f6e2f322f6176617461722e737667 68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f6f7267616e697a6174696f6e2f332f6176617461722e737667 68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f6f7267616e697a6174696f6e2f342f6176617461722e737667 68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f6f7267616e697a6174696f6e2f352f6176617461722e737667 68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f6f7267616e697a6174696f6e2f362f6176617461722e737667 68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f6f7267616e697a6174696f6e2f372f6176617461722e737667 68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f6f7267616e697a6174696f6e2f382f6176617461722e737667 68747470733a2f2f6f70656e636f6c6c6563746976652e636f6d2f7965772f6f7267616e697a6174696f6e2f392f6176617461722e737667


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK