web-sys

The web-sys crate provides bindings for Web APIs. This is procedurally generated from browser WebIDL which is why some of the names are so long and why some of the types are vague.

Features in web-sys

The web-sys crate with all of it’s features enabled can add lots of bloat to a Wasm application, in order to get around this issue most types are feature gated so that you only include the types you require for your application. Yew includes a number of features from web-sys and exposes some types in it’s public API, you will often need to add web-sys as a dependency yourself.

Inheritance in web-sys

In the Simulating inheritance section you can read how in general Rust provides an approach to simulate inheritance in JavaScript. This is very important in web-sys as understanding what methods are available on a type means understanding it’s inheritance.

This section is going to look at a specific element and list out it’s inheritance using Rust by calling Deref::deref until the value is JsValue:

  1. use std::ops::Deref;
  2. use web_sys::{
  3. Element,
  4. EventTarget,
  5. HtmlElement,
  6. HtmlTextAreaElement,
  7. Node,
  8. };
  9. fn inheritance_of_text_area(text_area: HtmlTextAreaElement) {
  10. // HtmlTextAreaElement is <textarea> in html.
  11. let html_element: &HtmlElement = text_area.deref();
  12. let element: &Element = html_element.deref();
  13. let node: &Node = element.deref();
  14. let event_target: &EventTarget = node.deref();
  15. // Notice we've moved from web-sys types now into built-in
  16. // JavaScript types which are in the js-sys crate.
  17. let object: &js_sys::Object = event_target.deref();
  18. // Notice we've moved from js-sys type to the root JsValue from
  19. // the wasm-bindgen crate.
  20. let js_value: &wasm_bindgen::JsValue = object.deref();
  21. // Using deref like this means we have to manually traverse
  22. // the inheritance tree, however, you can call JsValue methods
  23. // on the HtmlTextAreaElement type.
  24. // The `is_string` method comes from JsValue.
  25. assert!(!text_area.is_string());
  26. // empty function just to prove we can pass HtmlTextAreaElement as a
  27. // &EventTarget.
  28. fn this_function_only_takes_event_targets(targets: &EventTarget) {};
  29. // The compiler will walk down the deref chain in order to match the types here.
  30. this_function_only_takes_event_targets(&text_area);
  31. // The AsRef implementations allow you to treat the HtmlTextAreaElement
  32. // as an &EventTarget.
  33. let event_target: &EventTarget = text_area.as_ref();
  34. }

Inheritance in web-sys in The wasm-bindgen Guide.

The Node in NodeRef

Yew uses a NodeRef in order to provide a way for keeping a reference to a Node made by the html! macro. The Node part of NodeRef is referring to web_sys::Node. The NodeRef::get method will return a Option<Node> value, however, most of the time in Yew you want to cast this value to a specific element so you can use it’s specific methods. This casting can be done using JsCast on the Node value, if present, but Yew provides the NodeRef::cast method to perform this casting for convenience and so that you don’t necessarily have to include the wasm-bindgen dependency for the JsCast trait.

The two code blocks below do essentially the same thing, the first is using NodeRef::cast and the second is using JsCast::dyn_into on the web_sys::Node returned from NodeRef::get.

  • Using NodeRef::cast
  • Using NodeRef::get
  1. use web_sys::HtmlInputElement;
  2. use yew::NodeRef;
  3. fn with_node_ref_cast(node_ref: NodeRef) {
  4. if let Some(input) = node_ref.cast::<HtmlInputElement>() {
  5. // do something with HtmlInputElement
  6. }
  7. }
  1. use wasm_bindgen::JsCast;
  2. use web_sys::HtmlInputElement;
  3. use yew::NodeRef;
  4. fn with_jscast(node_ref: NodeRef) {
  5. if let Some(input) = node_ref
  6. .get()
  7. .and_then(|node| node.dyn_into::<HtmlInputElement>().ok()) {
  8. // do something with HtmlInputElement
  9. }
  10. }

JavaScript example to Rust

This section is to help show that any examples that use JavaScript to interact with the Web APIs can be adapted and written using Rust with web-sys.

JavaScript example

  1. document.getElementById('mousemoveme').onmousemove = (e) => {
  2. // e = Mouse event.
  3. var rect = e.target.getBoundingClientRect()
  4. var x = e.clientX - rect.left //x position within the element.
  5. var y = e.clientY - rect.top //y position within the element.
  6. console.log('Left? : ' + x + ' ; Top? : ' + y + '.')
  7. }

web-sys example

Using web-sys alone the above JavaScript example could be implemented like this:

Cargo.toml

  1. [dependencies]
  2. wasm-bindgen = "0.2"
  3. [dependencies.web-sys]
  4. version = "0.3"
  5. # We need to enable all the web-sys features we want to use!
  6. features = [
  7. "console",
  8. "Document",
  9. "HtmlElement",
  10. "MouseEvent",
  11. "DomRect",
  12. ]
  1. use wasm_bindgen::{prelude::Closure, JsCast};
  2. use web_sys::{console, Document, HtmlElement, MouseEvent};
  3. let mousemove = Closure::<dyn Fn(MouseEvent)>::wrap(Box::new(|e| {
  4. let rect = e
  5. .target()
  6. .expect("mouse event doesn't have a target")
  7. .dyn_into::<HtmlElement>()
  8. .expect("event target should be of type HtmlElement")
  9. .get_bounding_client_rect();
  10. let x = (e.client_x() as f64) - rect.left();
  11. let y = (e.client_y() as f64) - rect.top();
  12. console::log_1(&format!("Left? : {} ; Top? : {}", x, y).into());
  13. }));
  14. Document::new()
  15. .expect("global document not set")
  16. .get_element_by_id("mousemoveme")
  17. .expect("element with id `mousemoveme` not present")
  18. .unchecked_into::<HtmlElement>()
  19. .set_onmousemove(mousemove.as_ref().dyn_ref());
  20. // we now need to save the `mousemove` Closure so that when
  21. // this event fires the closure is still in memory.

This version is much more verbose, but you will probably notice part of that is because of failure types reminding us that some of these function calls have invariants that must be held otherwise will cause a panic in Rust. Another part of the verbosity is the calls to JsCast in order to cast into different types so that you can call it’s specific methods.

Yew example

In Yew you will mostly be creating Callbacks to use in the html! macro so the example is going to use this approach instead of completely copying the approach above:

Cargo.toml

  1. [dependencies.web-sys]
  2. version = "0.3"
  3. # We need to enable the `DomRect` feature in order to use the
  4. # `get_bounding_client_rect` method.
  5. features = [
  6. "console",
  7. "HtmlElement",
  8. "MouseEvent",
  9. "DomRect",
  10. ]
  1. use web_sys::{console, HtmlElement, MouseEvent};
  2. use yew::{
  3. html,
  4. Callback, TargetCast,
  5. };
  6. let onmousemove = Callback::from(|e: MouseEvent| {
  7. if let Some(target) = e.target_dyn_into::<HtmlElement>() {
  8. let rect = target.get_bounding_client_rect();
  9. let x = (e.client_x() as f64) - rect.left();
  10. let y = (e.client_y() as f64) - rect.top();
  11. console::log_1(&format!("Left? : {} ; Top? : {}", x, y).into());
  12. }
  13. });
  14. html! {
  15. <div id="mousemoveme" {onmousemove}></div>
  16. };

External libraries

web-sys is a raw binding to the Web API so it comes with some pain in Rust because it was not designed with Rust or even a strong type system in mind, this is where community crates come in to provide abstractions over web-sys to provide more idiomatic Rust APIs.

External libraries page