dioxus/packages/web/src/lib.rs

447 lines
11 KiB
Rust
Raw Normal View History

2021-02-12 21:11:33 +00:00
//! Dioxus WebSys
2021-02-17 15:53:55 +00:00
//! --------------
2021-02-24 07:22:05 +00:00
//! This crate implements a renderer of the Dioxus Virtual DOM for the web browser using Websys.
use dioxus::prelude::{Context, Properties, VNode};
use futures_util::{pin_mut, Stream, StreamExt};
2021-02-24 07:22:05 +00:00
use fxhash::FxHashMap;
2021-02-17 15:53:55 +00:00
use web_sys::{window, Document, Element, Event, Node};
2021-05-15 16:03:08 +00:00
// use futures::{channel::mpsc, SinkExt, StreamExt};
2021-02-12 21:11:33 +00:00
use dioxus::virtual_dom::VirtualDom;
2021-02-15 04:39:46 +00:00
pub use dioxus_core as dioxus;
use dioxus_core::{events::EventTrigger, prelude::FC};
2021-02-24 08:51:26 +00:00
2021-04-02 01:44:18 +00:00
pub use dioxus_core::prelude;
2021-06-23 05:44:48 +00:00
// pub mod interpreter;
2021-06-20 06:16:42 +00:00
pub mod new;
2021-02-24 07:22:05 +00:00
2021-02-12 21:11:33 +00:00
/// The `WebsysRenderer` provides a way of rendering a Dioxus Virtual DOM to the browser's DOM.
/// Under the hood, we leverage WebSys and interact directly with the DOM
///
pub struct WebsysRenderer {
internal_dom: VirtualDom,
}
impl WebsysRenderer {
2021-02-24 09:03:52 +00:00
/// This method is the primary entrypoint for Websys Dioxus apps. Will panic if an error occurs while rendering.
/// See DioxusErrors for more information on how these errors could occour.
///
/// ```ignore
/// fn main() {
/// wasm_bindgen_futures::spawn_local(WebsysRenderer::start(Example));
/// }
/// ```
///
2021-02-24 07:22:05 +00:00
/// Run the app to completion, panicing if any error occurs while rendering.
/// Pairs well with the wasm_bindgen async handler
2021-06-23 05:44:48 +00:00
pub async fn start(root: FC<()>) {
2021-04-01 04:01:42 +00:00
Self::new(root).run().await.expect("Virtual DOM failed :(");
2021-02-24 07:22:05 +00:00
}
2021-02-12 21:11:33 +00:00
/// Create a new instance of the Dioxus Virtual Dom with no properties for the root component.
///
2021-02-12 21:11:33 +00:00
/// This means that the root component must either consumes its own context, or statics are used to generate the page.
/// The root component can access things like routing in its context.
2021-06-23 05:44:48 +00:00
pub fn new(root: FC<()>) -> Self {
2021-02-12 21:11:33 +00:00
Self::new_with_props(root, ())
}
2021-04-01 04:01:42 +00:00
2021-02-12 21:11:33 +00:00
/// Create a new text-renderer instance from a functional component root.
/// Automatically progresses the creation of the VNode tree to completion.
///
/// A VDom is automatically created. If you want more granular control of the VDom, use `from_vdom`
2021-06-23 05:44:48 +00:00
pub fn new_with_props<T: Properties + 'static>(root: FC<T>, root_props: T) -> Self {
2021-02-12 21:11:33 +00:00
Self::from_vdom(VirtualDom::new_with_props(root, root_props))
}
2021-02-12 21:11:33 +00:00
/// Create a new text renderer from an existing Virtual DOM.
pub fn from_vdom(dom: VirtualDom) -> Self {
2021-02-25 23:44:00 +00:00
Self { internal_dom: dom }
}
2021-02-24 06:31:19 +00:00
pub async fn run(&mut self) -> dioxus_core::error::Result<()> {
2021-02-24 15:12:26 +00:00
let body_element = prepare_websys_dom();
2021-02-24 15:12:26 +00:00
let root_node = body_element.first_child().unwrap();
2021-06-23 05:44:48 +00:00
let mut websys_dom = crate::new::WebsysDom::new(body_element.clone());
websys_dom.stack.push(root_node);
2021-02-24 15:12:26 +00:00
self.internal_dom.rebuild(&mut websys_dom)?;
2021-06-23 05:44:48 +00:00
log::info!("Going into event loop");
loop {
let trigger = {
let real_queue = websys_dom.wait_for_event();
let task_queue = (&mut self.internal_dom.tasks).next();
pin_mut!(real_queue);
pin_mut!(task_queue);
match futures_util::future::select(real_queue, task_queue).await {
futures_util::future::Either::Left((trigger, _)) => trigger,
futures_util::future::Either::Right((trigger, _)) => trigger,
}
};
log::info!("event received");
2021-06-23 05:44:48 +00:00
let root_node = body_element.first_child().unwrap();
websys_dom.stack.push(root_node.clone());
self.internal_dom
.progress_with_event(&mut websys_dom, trigger.unwrap())?;
// let t2 = self.internal_dom.tasks.next();
// futures::select! {
// trigger = t1 => {
// log::info!("event received");
// let root_node = body_element.first_child().unwrap();
// websys_dom.stack.push(root_node.clone());
// self.internal_dom
// .progress_with_event(&mut websys_dom, trigger)?;
// },
// () = t2 => {}
// };
2021-06-23 05:44:48 +00:00
}
// while let Some(trigger) = websys_dom.wait_for_event().await {
// }
2021-06-23 05:44:48 +00:00
2021-02-24 08:51:26 +00:00
Ok(()) // should actually never return from this, should be an error, rustc just cant see it
2021-02-15 04:39:46 +00:00
}
}
2021-02-24 07:22:05 +00:00
fn prepare_websys_dom() -> Element {
2021-02-24 06:31:19 +00:00
// Initialize the container on the dom
// Hook up the body as the root component to render tinto
let window = web_sys::window().expect("should have access to the Window");
let document = window
.document()
.expect("should have access to the Document");
let body = document.body().unwrap();
// Build a dummy div
let container: &Element = body.as_ref();
2021-07-05 05:11:49 +00:00
// container.set_inner_html("");
2021-02-24 06:31:19 +00:00
container
.append_child(
document
.create_element("div")
.expect("should create element OK")
.as_ref(),
)
.expect("should append child OK");
2021-02-24 07:22:05 +00:00
container.clone()
2021-02-24 06:31:19 +00:00
}
// Progress the mount of the root component
// Iterate through the nodes, attaching the closure and sender to the listener
// {
// let mut remote_sender = sender.clone();
// let listener = move || {
// let event = EventTrigger::new();
// wasm_bindgen_futures::spawn_local(async move {
// remote_sender
// .send(event)
// .await
// .expect("Updating receiver failed");
// })
// };
// }
2021-07-05 05:11:49 +00:00
/// Wasm-bindgen has a performance option to intern commonly used phrases
/// This saves the decoding cost, making the interaction of Rust<->JS more performant.
/// We intern all the HTML tags and attributes, making most operations much faster.
///
/// Interning takes about 1ms at the start of the app, but saves a *ton* of time later on.
pub fn intern_cache() {
let cached_words = [
// All the HTML Tags
"a",
"abbr",
"address",
"area",
"article",
"aside",
"audio",
"b",
"base",
"bdi",
"bdo",
"big",
"blockquote",
"body",
"br",
"button",
"canvas",
"caption",
"cite",
"code",
"col",
"colgroup",
"command",
"data",
"datalist",
"dd",
"del",
"details",
"dfn",
"dialog",
"div",
"dl",
"dt",
"em",
"embed",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"head",
"header",
"hr",
"html",
"i",
"iframe",
"img",
"input",
"ins",
"kbd",
"keygen",
"label",
"legend",
"li",
"link",
"main",
"map",
"mark",
"menu",
"menuitem",
"meta",
"meter",
"nav",
"noscript",
"object",
"ol",
"optgroup",
"option",
"output",
"p",
"param",
"picture",
"pre",
"progress",
"q",
"rp",
"rt",
"ruby",
"s",
"samp",
"script",
"section",
"select",
"small",
"source",
"span",
"strong",
"style",
"sub",
"summary",
"sup",
"table",
"tbody",
"td",
"textarea",
"tfoot",
"th",
"thead",
"time",
"title",
"tr",
"track",
"u",
"ul",
"var",
"video",
"wbr",
// All the event handlers
"Attribute",
"accept",
"accept-charset",
"accesskey",
"action",
"alt",
"async",
"autocomplete",
"autofocus",
"autoplay",
"charset",
"checked",
"cite",
"class",
"cols",
"colspan",
"content",
"contenteditable",
"controls",
"coords",
"data",
"data-*",
"datetime",
"default",
"defer",
"dir",
"dirname",
"disabled",
"download",
"draggable",
"enctype",
"for",
"form",
"formaction",
"headers",
"height",
"hidden",
"high",
"href",
"hreflang",
"http-equiv",
"id",
"ismap",
"kind",
"label",
"lang",
"list",
"loop",
"low",
"max",
"maxlength",
"media",
"method",
"min",
"multiple",
"muted",
"name",
"novalidate",
"onabort",
"onafterprint",
"onbeforeprint",
"onbeforeunload",
"onblur",
"oncanplay",
"oncanplaythrough",
"onchange",
"onclick",
"oncontextmenu",
"oncopy",
"oncuechange",
"oncut",
"ondblclick",
"ondrag",
"ondragend",
"ondragenter",
"ondragleave",
"ondragover",
"ondragstart",
"ondrop",
"ondurationchange",
"onemptied",
"onended",
"onerror",
"onfocus",
"onhashchange",
"oninput",
"oninvalid",
"onkeydown",
"onkeypress",
"onkeyup",
"onload",
"onloadeddata",
"onloadedmetadata",
"onloadstart",
"onmousedown",
"onmousemove",
"onmouseout",
"onmouseover",
"onmouseup",
"onmousewheel",
"onoffline",
"ononline",
"<body>",
"onpageshow",
"onpaste",
"onpause",
"onplay",
"onplaying",
"<body>",
"onprogress",
"onratechange",
"onreset",
"onresize",
"onscroll",
"onsearch",
"onseeked",
"onseeking",
"onselect",
"onstalled",
"<body>",
"onsubmit",
"onsuspend",
"ontimeupdate",
"ontoggle",
"onunload",
"onvolumechange",
"onwaiting",
"onwheel",
"open",
"optimum",
"pattern",
"placeholder",
"poster",
"preload",
"readonly",
"rel",
"required",
"reversed",
"rows",
"rowspan",
"sandbox",
"scope",
"selected",
"shape",
"size",
"sizes",
"span",
"spellcheck",
"src",
"srcdoc",
"srclang",
"srcset",
"start",
"step",
"style",
"tabindex",
"target",
"title",
"translate",
"type",
"usemap",
"value",
"width",
"wrap",
];
for s in cached_words {
wasm_bindgen::intern(s);
}
}