Skip to content
ImagineWorld

Advanced JavaScript Integration with Yew

node_idnode-book_programming-web-assembly-with-rust_chapter-05-advanced-javascript-integration-with-yew
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleAdvanced JavaScript Integration with Yew
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — Advanced JavaScript Integration with Yew

Section titled “Chapter 5 — Advanced JavaScript Integration with Yew”

CHAPTER 5

Advanced JavaScript Integration with Yew

Your journey started out with some fundamental background on what WebAssembly is and how it works. You progressed from there to build a checkers engine with nothing but your mind, a text editor, and the wast syntax.

Next, you broadened your horizons and learned how to explicitly and tightly control JavaScript interaction across the boundaries between WebAssembly and the browser’s scripting host.

In this chapter, you will continue your journey away from the low-level WebAssembly syntax and learn how the combination of Rust, Rust macros, build tooling, and WebAssembly give you the power to create a complete, interactive, network-connected application written entirely in Rust and executed in the browser, maximizing code safety and performance.

Getting Started with Yew

As much as I dislike the traditional “Hello, World” program as a means to illustrate real-world lessons, I do think they have value in giving you an initial exposure to something brand new.

The Yew crate is unlike anything you’ve seen thus far in the book, and so we’re going to start off with a simple example of how to build a Yew application before getting into the real work of building the live multi-user chat.

The samples in this chapter are written with Yew version 0.4.0. If you’re reading this book and the crates.io¹ version of Yew is up to 0.5.0 or later, you’ll need to decide which version you want to use. Thanks to Cargo’s excellent version pinning, the book sample written against 0.4.0 will always work as it appears in the dead tree version of this book. However, Yew 0.5.0

[1] crates.io/crates/yew looks like it might contain some syntax improvements as well as multi-threaded worker support. If you end up deciding to use Yew for a real application, you might want to invest some time in learning the new syntax (which is likely to include breaking changes from 0.4.0).

What Is Yew?

Inspired by the Elm language and the React JavaScript framework, Yew is a modern web application framework designed to compile to WebAssembly (wasm32-unknown-unknown), asmjs, or emscripten. We’ll only be using the pure Rust WebAssembly target in this book.

Yew is a framework based on components, contexts, and message passing, creating a powerful environment for building responsive front-end applications that still operate nicely within the confines of Rust’s requirements and safety constraints. It supports a virtual DOM, reusable fragments and components, and has many of the features we look for in modern JavaScript web UI frameworks.

Yew has two main Rust traits, which are very similar to interfaces in other languages. These traits are Component and Renderable. The component is responsible for providing the business logic and managing state for a discrete portion of the user interface. Anything that implements the Renderable trait is, as the name implies, responsible for producing the HTML necessary to render that entity in place within a virtual DOM. If you’ve had any exposure to React, then you’ll recognize the power and performance benefits you get from a virtual DOM.

Yew’s power comes from the use of a custom plugin build tool (which you’ll install shortly), some library code, and a large number of macros in the Yew crate and others upon which it depends. It generates an enormous amount of wiring code that allows you to think in terms of pure Rust, components, and renderables, and not worry too much about how that Rust is going to work inside a browser as a WebAssembly module.

The Yew Component trait has create(), update(), change(), and destroy() functions. When you build a component you implement these functions to manage state and logic. The Yew Renderable trait simply contains the view() function, which returns HTML that should be rendered to the client.

Why Yew?

The purpose of this chapter is to show you how to build a web application using (nearly) nothing but Rust code compiled to WebAssembly. When we traditionally go to build web applications, we have to write things in JavaScript

Getting.Started.with.Yew * 91

and HTML, and CSS and we typically need to know a ton of frameworks on top of that (e.g., Vue, React, Angular), we need to know front-end build tools and back-end build tools, and we need to figure out where to split our code —what goes in the back end and what goes in the front end?

Frameworks like Yew let us build everything in Rust, give us the benefit of strong typing and safe code that we get from Rust, allow us to use a single, unified toolchain for our web application, and dramatically simplify the development process. Not every React application should be immediately re- written as a “Rust-pure WebAssembly Yew” app, but hopefully by the end of the chapter, you’ll have an idea of where these kinds of frameworks can come in handy. Yew is not the only web framework available for Rust and WebAssembly, but it’s a mature and accessible one, so it makes for a decent book example.

As an added bonus, working with the Yew framework will expose you to some more foundational aspects of Rust, including traits, generics, referencing modules, mutable reference passing, and more.

Building Your First Yew Application

Building an application with Yew means composing a hierarchy of UI elements composed of components and renderables. The sample you’ll build is a simple counter. You’ll render a number and, whenever a user clicks a nearby button, the number will increase.

That might seem overly simplistic, but remember this is being done from inside Rust, built into a WebAssembly module, and then executed as Java- Script. It’s worth it to take the effort to build this small sample to see how components and renderables work in Yew before moving onto a bigger problem domain. State will be maintained entirely within your Rust code, and you won’t have to worry about which part of it is a back-end component and which is front-end.

The first thing you’ll need to do is install Yew’s required build plugin, cargo- web. To do that, issue the following command at a terminal prompt:

$ cargo install cargo-web

Depending on how much Rust development you’ve been doing on your machine, this can take quite a while for all of the components to be download- ed and compiled.

Don’t confuse the cargo command with the rustup command; rustup is responsible for managing your installed toolchains and targets while cargo is responsible for building and creating your projects. For the rest of this chapter, you’ll be building and running your applications with the cargo web command instead of the usual cargo.

To get started, create a new project (deleting the edition = “2018” line) with cargo new (I called mine yewcounter). Unlike previous Rust projects, you don’t have to declare that the application is a dynamic library, as cargo web will take care of those details. Create a Cargo.toml that looks like this one:

yewcounter/Cargo.toml

[package]
name = "yewcounter"
version = "0.1.0"
authors = ["Kevin Hoffman <[email protected]>"]
[dependencies]
stdweb = "0.4.2"
yew = "0.4.0"

The next thing we’ll do is create a src/main.rs, which is typically reserved for standalone application binaries and not library modules.² cargo web takes care of the project metadata and compilation configuration for us, but I like being able to think of this as an application and not just an isolated module so the use of main.rs feels right.

In this new file, you’ll see a Context structure. It implements a trait called AsMut. Anything that implements this trait indicates that it can expose a mutable reference to the type given in the generic type parameter. In this case, the context can provide a mutable reference to a service called ConsoleService, a service that provides access to JavaScript’s console variable:

yewcounter/src/main.rs

extern crate yew;
extern crate yewcounter; // refers to lib.rs
use yew::prelude::*;
use yew::services::console::ConsoleService;
use yewcounter::Model;
pub struct Context {
console: ConsoleService,
}
impl AsMut<ConsoleService> for Context {
fn as_mut(&mut self) -> &mut ConsoleService {
&mut self.console
}
}

[2] doc.rust-lang.org/book/ch07-00-packages-crates-and-modules.html

fn main() {
yew::initialize();
let context = Context {
console: ConsoleService::new(),
};
let app: App<_, Model> = App::new(context);
app.mount_to_body();
yew::run_loop();
}

From a polymorphism perspective, the goal of what’s happening with this struct and trait is the ability to pass a concrete struct type known only to the main module and have the components and renderables be able to use the services contained within that context. In other words, the UI code relies on the ability to obtain a mutable reference to a console service, but they aren’t tightly coupled to how that service is made available. In other languages, you’d accomplish something like this with dependency injection or structural typing.

In addition to components and renderables, Yew also has the concept of services. Services, within the realm of Yew applications, are designed to expose “headless” (no UI) functionality to UI components. In this sample, the service we’re using exposes the ability to log to JavaScript’s console as a service. In the next sample in the chapter, you’ll create a service that exposes a multi-user chat engine.

The code in the main() function is pretty standard for all Yew applications—initialize the Yew runtime, create the context that’s appropriate for your application, then create an application for your model that takes your context as a parameter, and finally kick off the execution loop. Next, you’ll define your model, which is the data read and manipulated by your component.

We’ll put the model, component, and renderable in lib.rs in the same src directory as main.rs. For a more complex application, we might choose a more robust module hierarchy (you’ll see some of those later in the book). In the case of a simple counter, you can express the model as just a single field on a struct:

pub struct Model {
value: i64,
}

In keeping with the React³-like architecture, we need to figure out which messages (Redux developers might call them actions) we want to pass through

[3] reactjs.org/ the component to produce changes within the model, which in turn changes how the component renders. The Yew crate’s stock counter sample comes with the following messages, defined by a Rust enum:

pub enum Msg {
Increment,
Decrement,
Bulk(Vec<Msg>),
}

You might have noticed that one of the variants (Bulk) can actually contain a vector (array) of itself. As you’ll see, this lets us bundle up multiple messages together and send them through the component as a single batch. Before getting into the full code listing for the implementation, there’s some new Rust syntax to cover that you’ll see:

impl<C> Component<C> for Model
where
C: AsMut<ConsoleService> {
...
}

This syntax combines Rust’s generics system with its trait system. This is really one of the first areas beyond borrows, moves, and references where Rust’s syntax may start to confuse people who have backgrounds in other languages. This syntax indicates that, for any instance of the Model struct, this scope contains a bound Component trait implementation when the type parameter to that component (C) implements the AsMut trait.

Putting much of the syntax details aside, this code boils down to this statement —Model can be treated as a Component so long as we can extract a mutable ref- erence to a ConsoleService from the component. If you look back at the src/main.rs code, you’ll see that we don’t actually instantiate our Model directly. Instead, we pass it as a type parameter to Yew’s App struct.

There’s a similar, slightly more complex syntax that’s used to define the Ren- derable responsible for emitting the HTML for the component:

impl<C> Renderable<C, Model> for Model
where
C: AsMut<ConsoleService> + 'static {
...
}

Essentially this code says that the Model struct can render anything that is of type Model with a context type parameter that allows us to extract a mutable reference to a ConsoleService.

I personally find this type of Rust syntax “bumpy,” and it doesn’t read naturally for me. The only way I learned it was simply to get used to it. Others, possibly those with more exposure to traditional C++, find this syntax more natural and low-friction. The other potentially confusing bit of syntax is the ‘static bit—a lifetime specifier.

The Rust compiler prevents us from accessing values that may no longer exist. To do this, it needs to know how long (relatively) those values should exist. Most of the time, Rust can infer a memory lifetime and save us the bother of explicitly defining one, and it does an even better job of eliding these details in the 2018 edition syntax. But why do we need a lifetime specifier here? I’m glad you asked!

In this one line of fairly dense syntax, you can assume that the code inside the implementation block will, at some point, obtain a mutable reference to something of type ConsoleService. The Rust compiler must now police this lifetime to ensure that it lasts long enough for us to invoke the log() method on a console instance without the console instance being null due to going out of scope or being deallocated. Here, the static lifetime specifier is used. Without boring you with 20 pages of detail, this doesn’t necessarily mean the value lasts forever. It just means that it has an unlimited potential lifetime as far as the Rust compiler is concerned. Since we know this is JavaScript’s console variable, we can assume that its lifetime will never end so long as the WebAssembly module is loaded.

If you were to remove the static lifetime specifier and then try to compile the code in the upcoming listing, you’d get one of Rust’s famously expressive and helpful error messages:

error: Could not compile yewcounter.

To learn more, run the command again with —verbose. error[E0310]: the parameter type C may not live long enough —> src/lib.rs:54:9 49 | impl Renderable<C, Model> for Model | - help: consider adding an explicit lifetime bound C: 'static… … 54 | / html! { 55 | |

56 | | <nav class=“menu”,> 57 | | <button onclick=|_| Msg::Increment,>{ “Increment” } … 63 | |
64 | | } note: …so that the type C will meet its required lifetime bounds —> src/lib.rs:54:9

54 | / html! { 55 | |

56 | | <nav class=“menu”,> 57 | | <button onclick=|| Msg::Increment,>{ “Increment” } … 63 | |
64 | | } | |______^

The error message even suggests that we should consider adding a static lifetime bound so that the C type will meet its requirements. I really do love the Rust compiler error messages—an enormous amount of community effort has gone into making them readable and provide useful hints.

Here is the completed src/lib.rs code that implements a component and a renderable for the simple counter model:

yewcounter/src/lib.rs

extern crate stdweb;
#[macro_use]
extern crate yew;
use stdweb::web::Date;
use yew::prelude::*;
use yew::services::console::ConsoleService;
pub struct Model {
value: i64,
}
pub enum Msg {
Increment,
Decrement,
Bulk(Vec<Msg>),
}
impl<C> Component<C> for Model
where
C: AsMut<ConsoleService>,
{
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, _: &mut Env<C, Self>) -> Self {
Model { value: 0 }
}
}
fn update(&mut self, msg: Self::Message,
env: &mut Env<C, Self>) -> ShouldRender {
match msg {
Msg::Increment => {
self.value = self.value + 1;
env.as_mut().log("plus one");
}
Msg::Decrement => {
self.value = self.value - 1;
env.as_mut().log("minus one");
}
Msg::Bulk(list) => for msg in list {
self.update(msg, env);
env.as_mut().log("Bulk action");
},
}
true
}
impl<C> Renderable<C, Model> for Model
where
C: AsMut<ConsoleService> + 'static,
{
fn view(&self) -> Html<C, Self> {
html! {
<div>
<nav class="menu",>
<button onclick=|_| Msg::Increment,>{ "Increment" }</button>
<button onclick=|_| Msg::Decrement,>{ "Decrement" }</button>
<button onclick=|_| Msg::Bulk(vec![Msg::Increment,
Msg::Increment]),>{ "Increment Twice" }</button>
</nav>
<p>{ self.value }</p>
<p>{ Date::new().to_string() }</p>
</div>
}
}
}

The html! procedural macro (you can spot procedural macros by their exclamatory nature!) takes the elements contained within it and produces real HTML, which the Yew virtual DOM will render as soon as it deems appropriate. The html! macro is defined by the stdweb crate, along with the js! macro that will emit in-situ JavaScript wherever encountered in your Rust code.

[4] crates.io/crates/stdweb

Pay close attention to what’s inside the html! macro, though. It might look like regular HTML, but it’s really just tokens waiting to be parsed by Rust. As such, you’ll notice that the macro requires a comma after every attribute-value segment, even if it precedes the closing markup character. It takes a little getting used to, and readers with experience using React’s JSX have seen this kind of mild frustration before. If you’re using a text editor with real Rust support, though, it should be able to detect syntax errors in your macro and try to warn you (though the error message may often seem obscure).

With these two files written, it’s time to compile and run this application. If you’re wondering where the index.js JavaScript file is or the index.html file is—we don’t need them. At least, not for this sample because Yew builds some reasonable defaults for us via cargo web:

Terminal window
$ cargo web build --target=wasm32-unknown-unknown
Compiling yewcounter v0.1.0
(file:///home/kevin/Code/Rust/wasmbook/khrust/Book/code/yewcounter)
Finished release [optimized] target(s) in 0.19s
Compiling yewcounter v0.1.0
(file:///home/kevin/Code/Rust/wasmbook/khrust/Book/code/yewcounter)
Finished release [optimized] target(s) in 3.57s
Processing "yewcounter.wasm"...
Finished processing of "yewcounter.wasm"!
$ cargo web start --target=wasm32-unknown-unknown
Finished release [optimized] target(s) in 0.04s
Processing "yewcounter.wasm"...
Finished processing of "yewcounter.wasm"!

If you need to serve any extra files, put them in the ‘static’ directory in the root of your crate. They’ll be served alongside your application. You can also put a ‘static’ directory in your ‘src’ directory.

Your application is being served at ‘/yewcounter.js’. It will be automatically rebuilt if you make any changes in your code.

You can access the web server at http://[::1]:8000.

Let’s open the indicated website and see what we get:

localhost

Increment Decrement Increment Twice

10

Sat Aug 25 2018 14:21:53 GMT-0400 (EDT) Playing with this application feels just like it would if you had written it entirely in JavaScript—clicking the buttons provides immediate feedback. You can also see the invocations of the console service by checking the JavaScript console. And you can see that the invocations are happening inside yewcounter, a file generated completely on your behalf by the Yew build tool: Finished loading Rust wasm module ‘yewcounter’ plus one minus one plus one duck action Now that you’ve seen the basics behind building a service, a component, and a renderable in Yew, let’s build on that knowledge by creating a multi-user chat application sitting on top of a third-party JavaScript chat engine.

Building on some basic exposure to the Yew programming model, it’s time to create something a bit more complex and powerful than an app that increments a counter. You’ve got the basic building blocks already: components, renderables, and services—the trick lies in figuring out where and how to stack those blocks.

For this next sample, we’re going to stack the building blocks to make a real- time chat application. This app will have an area that displays chat messages, an area that shows the currently online users, and an area that lets you enter your alias and connect.

Luckily we won’t have to do all the multi-user, real-time chat work ourselves. There are companies and products that can help here, including Pubnub, Ably, XMPP platforms, Rapid.io, Emitter.io, and the list goes on ad infinitum.

Due to its ease of use and the fact that one does not have to supply a credit card number to begin experimenting, I’ve decided to use Pubnub’s ChatEngine product to provide the underlying infrastructure for this WebAssembly app. If you have concerns about signing up for this service, feel free to read along without doing so or simply supply minimal information and delete your account when you’re done with the samples.

If you don’t already have your free Pubnub account, head on over to their home page1 and create one. You’ll need to provide some basic information.

After signing up and getting to your main dashboard, you’ll see tiles for each of your applications. You’ll be creating an application for this sample, but don’t create a new one with the “Create New app” button. Instead, if you see a banner advertising the ChatEngine product at the top, click that link. If you don’t see it, then you can manually go to the ChatEngine tutorial page.^[6]

Once at the tutorial/quick-start, you should see a button called Setup, like the one in the screenshot from Pubnub’s website:

When you click the setup button, Pubnub will create an application for you, but it will also create a function in your application that hosts your chat engine server. This function being up and running is the essential key to being able to use the ChatEngine functionality. If you navigate to the functions button and then click on your ChatEngine function, you should see a screen like the one shown in the figure on page 101.

If the function isn’t running, start it now. If the navigation doesn’t match what I’ve described in the book, then Pubnub may have changed their design and you might need to search around in their new interface to find out how to get set up. Before heading to the next section, you’ll need to know the

  1. www.pubnub.com/tutorials/chatengine/

ChatEngine Function Running 1 TOTAL

publish and subscribe keys for your app and be sure that your ChatEngine function is running.

The goal of this chapter isn’t to write a Pubnub app, it’s to illustrate how you can wrap third-party JavaScript libraries inside your own Rust WebAssembly modules and utilize auto-generated bridge code to communicate between your Rust/Yew code and another JavaScript library that you don’t own.

Yew services are blocks of functionality that can be exposed to renderables and components. They’re designed specifically to act as gateways (or facades or Anti-Corruption Layers depending on which terminology is your favorite) between your code and other dependencies.

In this case, the dependency is a JavaScript library from Pubnub. Because we’re using Yew and building on top of other code generation tools that make interacting with JavaScript easy, it should be fairly straightforward to wrap some of the functions in the ChatEngine module as a Yew service. Of course, “fairly straightforward” is usually how all innocent endeavors appear until they explode in a fiery ball. There are a couple of quirks to watch out for here.

The largest quirk here is one that caused me endless hours of frustration involving a conflict between my own code, asynchronous JavaScript, and my own JS inexperience. I had two options: either force synchronous operations and wait for manual initialization to finish, or declare a global variable (myChat) to hold the handle to the chat conversation once the futures completed.

I chose the latter, which required me to add a couple of JavaScript variables to the top of the index.html shown here. Those with better JavaScript chops than I might want to refactor these global variables out as an exercise to get more familiar with Yew+JavaScript interaction subtleties. Try capturing the third-party library variables inside a Yew service, if you can:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Yew • Online Chat</title>
<link rel="stylesheet" href="styles.css">
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/
dist/chat-engine.min.js"
type="text/javascript">
</script>
<link
rel="stylesheet"
type="text/css"
href="https://maxcdn.bootstrapcdn.com/font-awesome/
4.4.0/css/font-awesome.min.css">
</link>
</head>
<body>
<script id="bootstrap">
var myChat;
var me;
</script>
<script src="js/app.js"></script>
</body>
</html>

To get started with this project, you can copy the counter project from earlier. I put mine in a directory called yew_wasmchat. The first changes you’ll need to make will be to Cargo.toml to add a few new dependencies:

yew_wasmchat/Cargo.toml
[package]
name = "wasmchat"
version = "0.1.0"
authors = ["Kevin Hoffman <[email protected]>"]
[dependencies]
web_logger = "0.1"
log = "0.4"
strum = "0.9"
strum_macros = "0.9"
serde = "1"
serde_json = "1"
serde_derive = "1"
stdweb = "0.4.8"
yew = "0.4.0"

Web Logger is a handy little crate. Once initialized, web_logger will allow all of your Rust-native log macros (info!, debug!, etc.) to generate very nice log messages in the JavaScript console. You wrote a small wrapper around console.log earlier in the book—this is just a fancier version of that same concept bundled as a crate. The serde dependencies all deal with serialization and de-serialization.

There will be three files in this project: src/lib.rs, src/main.rs, and src/services.rs. The initialization takes place in main.rs, lib.rs contains the UI, and services.rs contains our Pubnub wrapper.

Let’s take a look at the service implementation and then step through some of the parts that might look a little crazy:

yew_wasmchat/src/services.rs

use super::Message;
use stdweb::Value;
use yew::prelude::*;
pub struct PubnubService {
lib: Option<Value>,
chat: Option<Value>,
}
impl PubnubService {
pub fn new(publish_key: &str, subscribe_key: &str) -> Self {
info!("Creating new instance of pubnub chatengine service");
let chat_engine = js! {
let ce = ChatEngineCore.create({
publishKey: @{publish_key},
subscribeKey: @{subscribe_key}
});
console.log("Chat engine core created");
return ce;
};
PubnubService {
lib: Some(chat_engine),
chat: None,
}
}
pub fn send_message(&mut self, msg: &str) -> () {
js! {
let m = @{msg};
myChat.emit("message", {
text: m
});
}
}
}
pub fn connect(
&mut self,
topic: &str,
nickname: &str,
onmessage: Callback<Message>,
onoffline: Callback<String>,
ononline: Callback<String>,
) -> () {
let lib = self.lib.as_ref().expect("No pubnub library!");
let chat_callback = move |text: String, source: String| {
let msg = Message {
text: text,
from: source,
};
onmessage.emit(msg);
};
let useroffline_callback = move |username: String| {
onoffline.emit(username);
};
let useronline_callback = move |username: String| {
ononline.emit(username);
};
let chat = js! {
var pn = @{lib};
var chat_callback = @{chat_callback};
var online_cb = @{useronline_callback};
var offline_cb = @{useroffline_callback};
pn.on("$ .ready", function(data) {
console.log("PubNub Chat Engine Ready");
// set global variable
me = data.me;
// create a new ChatEngine Chat (global var)
myChat = new pn.Chat(@{topic});
myChat.on("$ .connected", () => {
console.log("The chat is connected!");
myChat.on("message", (message) => {
chat_callback(message.data.text,
message.sender.state.nickName);
console.log("message: " + message.data.text +
" from " + message.sender.state.nickName);
});
myChat.on("$ .online.*", (data) => {
console.log("User is Online: ", data.user);
online_cb(data.user.state.nickName);
});
});
};
myChat.on("$ offline.*", (data) => {
console.log("User is Offline: ", data.user);
offline_cb(data.user.state.nickName);
});
});
pn.connect(String(new Date().getTime()), {
nickName: @{nickname}
});
console.log("pubnub connecting");
return myChat;
};
self.chat = Some(chat);
}

① Inject JavaScript to instantiate Pubnub’s ChatEnginecore.

② Return a new PubnubService with a captured reference to the chat engine JavaScript object.

③ Define a set of callback functions that will be invoked by various Chat Engine handlers.

④ Inject the JavaScript necessary to attach the Rust/wasm callbacks to chat engine JavaScript handlers.

Let’s take a closer look at this bit of code from the PubnubService::new() function:

let chat_engine = js! {
let ce = ChatEngineCore.create({
publishKey: @{publish_key},
subscribeKey: @{subscribe_key}
});
console.log("Chat engine core created");
return ce;
};

There’s a lot happening that you don’t see, so let’s walk through everything that’s happening in detail:

  • Everything inside the js! block is wrapped in a private scope and converted into a JavaScript function that shows up in the generated JavaScript file.

  • The publish_key and subscribe_key parameters are made available as function parameters in this JavaScript snippet.

  • An extern block is created for this anonymous JavaScript function to allow it to be invoked from WebAssembly.

  • The “pass as a string” pattern is used to allow these values to be passed to the JavaScript function by way of shared linear memory.

  • At runtime, this anonymous function is invoked. The return value is stored as an object reference in linear memory.

  • That object reference is handed to Rust as a return value and stored in chat_engine.

This is what is involved with just a few lines of js! macro, and that is even with a few of the gory details being glossed over here to try to keep things easy to follow. Hopefully, after having spent a few chapters doing things the hard way, you are better able to follow the amount of work macros like this save you.

Now you’ve seen what it looks like when you want to execute some JavaScript that captures data via closure around Rust lexically scoped values and then stores the return value of that JavaScript block as a native Rust variable. I think it’s worth it to take a moment, pause, and thank the code generation gremlins for their assistance here, recognizing how much power is now at your fingertips.

Creating the Yew Chat UI

The user interface for the chat application is fairly simple. There’s an area for messages that come from the chat engine (via the PubnubService), an area that shows the list of connected users, an area that lets us provide an alias and connect, and lastly, a textbox that lets us type text that will be transmitted to all other users when we hit Enter.

To reproduce this layout, you can find both the index.html and styles.css files in the static directory in the code sample download for the book.

As you now know, a Yew UI is composed of components, renderables, and messages that are used to trigger updates. This app will have the following messages:

  • SendChat - indicates a text message should be sent out through the chat engine
  • AddMessage - indicates that we should add a text message to a component’s internal state
  • Connect - performs a chat engine connection via the service
  • UserName - occurs as the user types in the “name” textbox
  • UserOnline - indication of a change in presence status from the chat engine service
  • UserOffline - indication of a change in presence status from the chat engine service
  • UpdatePendingText - occurs as the user types in the text input box for the outbound chat message

We’re going to create a component to manage state and we’re going to create a renderable to manage the HTML output and virtual DOM manipulation. In the following component code, the create() function is called to initialize state, while the update() function is called every time a message bubbles up through the queue. Most of the time, messages make their way to the update() function by virtue of event handlers in renderables.

Note that the Msg type is used for Yew component internal messaging and the Message type represents the data for a chat message. We use emsend back() to dispatch a Msg:

yew_wasmchat/src/lib.rs
#![recursion_limit = "512"]
extern crate strum;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate yew;
#[macro_use]
extern crate log;
#[macro_use]
extern crate stdweb;
use services::PubnubService;
use std::collections::HashSet;
use yew::prelude::*;
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
pub text: String,
pub from: String,
}
pub struct Model {
alias: String,
pending_text: String,
messages: Vec<Message>,
users: HashSet<String>,
}
#[derive(Debug)]
pub enum Msg {
SendChat,
AddMessage(Message),
Connect,
EnterName(String),
UserOffline(String),
UserOnline(String),
UpdatePendingText(String),
NoOp,
}
impl<C> Component<C> for Model
where
C: AsMut<PubnubService> + 'static,
{
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, _: &mut Env<C, Self>) -> Self {
Model {
messages: Vec::new(),
alias: "".into(),
users: HashSet::new(),
pending_text: "".into(),
}
}
fn update(&mut self, msg: Self::Message, env: &mut Env<C, Self>) -> ShouldRender {
match msg {
Msg::AddMessage(msg) => {
self.messages.push(msg);
}
Msg::UserOnline(nick) => {
info!("Adding user {:?}" , nick);
self.users.insert(nick);
}
Msg::UserOffline(nick) => {
info!("Removing user {:?}" , nick);
self.users.remove(&nick);
}
Msg::SendChat => {
info!("Called send chat!");
env.as_mut().send_message(&self.pending_text);
self.pending_text = "".into();
}
Msg::Connect => {
let on_message = env.send_back(|msg| Msg::AddMessage(msg));
let onoffline = env.send_back(|user| Msg::UserOffline(user));
let ononline = env.send_back(|user| Msg::UserOnline(user));
}
}
}
}

env.as_mut().connect(

"chatengine-demo-chat",
&self.alias,
on_message,
onoffline,
ononline,
);
}

Msg::EnterName(n) => {

self.alias = n;
}

Msg::UpdatePendingText(s) => {

self.pending_text = s;
}

Msg::NoOp => {} } true }

Now that we have a component complete with message dispatching and state management, let’s create the renderable view for this component:

yew_wasmchat/src/lib.rs impl Renderable<C, Model> for Model where

C: AsMut<PubnubService> + 'static,
{
fn view(&self) -> Html<C, Self> {
html! {
<div class="wrapper",>
<div class="chat-text",>
<h1>{"Messages" }</h1><br/>
<ul class="message-list",>
{ for self.messages.iter().enumerate().map(view_message) }
</ul>
</div>
<div class="users",>
<h1>{"Users" }</h1><br/>
<ul class="user-list",>
{ for self.users.iter().enumerate().map(view_user) }
</ul>
</div>
<div class="connect",>
<input placeholder="Your Name",
value=&self.alias,
oninput=|e| Msg::EnterName(e.value),>
</input>
<button onclick=|_| Msg::Connect,>{"Connect" }</button>
</div>
</div>
}
}
}
<div class="text-entry",>
<input placeholder="Message Text",
class="pending-text",
value=&self.pending_text,
oninput=|e| Msg::UpdatePendingText(e.value),
onkeypress=|e| {
if e.key() == "Enter" { Msg::SendChat } else { Msg::NoOp }
},
>
</input>
</div>
</div>
}

Keep an eye on the code inside the html! macro. As you experiment with this and try to add more controls, you will undoubtedly produce a syntax error and the error message might not be immediately obvious because it’s a parse failure rather than a language syntax error.

Inside the view() function, there are some utility functions that let us abstract out and potentially reuse views: view_message() and view_user(). They each take a tuple as a parameter and return HTML snippets:

yew_wasmchat/src/lib.rs fn view_message((_idx, message): (usize, &Message)) -> Html<C, Model> where C: AsMut + ‘static,

{

html! {

<li>
<label>
<span class="sender",>{"["}{&message.from}{"]"}</span>
<span class="chatmsg",>{&message.text}</span>
</label>
</li>
}
}
fn view_user<C>((_idx, user): (usize, &String)) -> Html<C, Model>

where C: AsMut + ‘static,

{

html! {

<li>
<label>{ user }</label>
</li>
}
}
pub mod services;

Finally, now that you’ve got a chat engine service sitting on top of a valid, active Pubnub account, you can create a src/main.rs to initialize the application and components:

yew_wasmchat/src/main.rs
extern crate wasmchat;
extern crate web_logger;
extern crate yew;
use wasmchat::{services::PubnubService, Model};
use yew::prelude::*;
pub struct Context {
pubnub: PubnubService,
}
impl AsMut<PubnubService> for Context {
fn as_mut(&mut self) -> &mut PubnubService {
&mut self.pubnub
}
}
fn main() {
web_logger::init();
yew::initialize();
let context = Context {
pubnub: PubnubService::new("(your publish key)",
"(your subscribe key)",
);
};
let app: App<_, Model> = App::new(context);
app.mount_to_body();
yew::run_loop();
}

Make sure that you replace the publish and subscribe keys with the ones you got from your own application. Run the following commands from the project root (the same directory as Cargo.toml):

Terminal window
$ cargo web build --target=wasm32-unknown-unknown
Processing "wasmchat.wasm"...
Finished processing of "wasmchat.wasm"!
$ cargo web start --target=wasm32-unknown-unknown
Processing "wasmchat.wasm"...
Finished processing of "wasmchat.wasm"!

If you need to serve any extra files, put them in the ‘static’ directory in the root of your crate. They’ll be served alongside your application. You can also put a ‘static’ directory in your ‘src’ directory.

Your application is being served at ‘/wasmchat.js’. It will automatically rebuild if you make any changes in your code.

You can access the web server at http://[::1]:8000.

You should be able to open this application in two separate tabs, provide two aliases, and hit the Connect button. You can then have an intense and thought-provoking discussion with yourself as shown in this screenshot:

Wrapping Up

It’s been a long journey since the early days when you were building checkers games with raw wast. You’ve seen the underpinnings of WebAssembly and its architecture, you’ve learned how to write low-level code, how to interact with JavaScript via manual extern blocks, and in this chapter you took advantage of libraries and code generation to build a nearly 100% Rust WebAssembly application that even uses a third-party chat engine.

Your Jedi training in JavaScript integration is complete. You must now move on and learn new, more powerful techniques. In the coming chapters, you will experiment with hosting WebAssembly modules in Rust applications rather than the browser. You’ll extrapolate from what you’ve learned about JavaScript integration to build WebAssembly modules that run on Raspberry Pis or that can even battle each other in online multiplayer combat.

Part III

Working with Non-Web Hosts

Let’s take our WebAssembly skills to the next level and explore some exciting use cases for hosting WebAssembly modules in Rust applications.

  1. www.pubnub.com but it’s a five-minute process that goes even faster if you want to authenticate using a Google ID (again, for the security-conscious, you can skip using your Google ID and create new credentials instead) ↩