Merge branch 'upstream-master' into fix-hot-reloading

This commit is contained in:
= committed 2022-12-16 10:07:11 -06:00
commit 14dd568987
92 files changed
+3469 -2468

No files matched your search

+166 -46
View File
@@ -7,24 +7,34 @@
//! - tests to ensure dyn_into works for various event types.
//! - Partial delegation?>
use dioxus_core::{Mutation, Template};
use dioxus_core::{ElementId, Mutation, Template, TemplateAttribute, TemplateNode};
use dioxus_html::{event_bubbles, CompositionData, FormData};
use dioxus_interpreter_js::Interpreter;
use dioxus_interpreter_js::{save_template, Channel};
use futures_channel::mpsc;
use rustc_hash::FxHashMap;
use std::{any::Any, rc::Rc};
use wasm_bindgen::{closure::Closure, JsCast};
use web_sys::{Document, Element, Event};
use web_sys::{Document, Element, Event, HtmlElement};
use crate::Config;
pub struct WebsysDom {
interpreter: Interpreter,
handler: Closure<dyn FnMut(&Event)>,
_root: Element,
document: Document,
templates: FxHashMap<String, u32>,
max_template_id: u32,
interpreter: Channel,
}
pub struct UiEvent {
pub name: String,
pub bubbles: bool,
pub element: ElementId,
pub data: Rc<dyn Any>,
pub event: Event,
}
impl WebsysDom {
pub fn new(cfg: Config, event_channel: mpsc::UnboundedSender<Event>) -> Self {
pub fn new(cfg: Config, event_channel: mpsc::UnboundedSender<UiEvent>) -> Self {
// eventually, we just want to let the interpreter do all the work of decoding events into our event type
// a match here in order to avoid some error during runtime browser test
let document = load_document();
@@ -32,67 +42,158 @@ impl WebsysDom {
Some(root) => root,
None => document.create_element("body").ok().unwrap(),
};
let interpreter = Channel::default();
let handler: Closure<dyn FnMut(&Event)> =
Closure::wrap(Box::new(move |event: &web_sys::Event| {
let name = event.type_();
let element = walk_event_for_id(event);
let bubbles = dioxus_html::event_bubbles(name.as_str());
if let Some((element, target)) = element {
if target
.get_attribute("dioxus-prevent-default")
.as_deref()
.map(|f| f.trim_start_matches("on"))
== Some(&name)
{
event.prevent_default();
}
let data = virtual_event_from_websys_event(event.clone(), target);
let _ = event_channel.unbounded_send(UiEvent {
name,
bubbles,
element,
data,
event: event.clone(),
});
}
}));
dioxus_interpreter_js::initilize(root.unchecked_into(), handler.as_ref().unchecked_ref());
handler.forget();
Self {
interpreter: Interpreter::new(root.clone()),
_root: root,
handler: Closure::wrap(Box::new(move |event: &web_sys::Event| {
let _ = event_channel.unbounded_send(event.clone());
})),
document,
interpreter,
templates: FxHashMap::default(),
max_template_id: 0,
}
}
pub fn mount(&mut self) {
self.interpreter.MountToRoot();
self.interpreter.mount_to_root();
}
pub fn load_templates(&mut self, templates: &[Template]) {
log::debug!("Loading templates {:?}", templates);
for template in templates {
self.interpreter
.SaveTemplate(serde_wasm_bindgen::to_value(&template).unwrap());
let mut roots = vec![];
for root in template.roots {
roots.push(self.create_template_node(root))
}
self.templates
.insert(template.name.to_owned(), self.max_template_id);
save_template(roots, self.max_template_id);
self.max_template_id += 1
}
}
fn create_template_node(&self, v: &TemplateNode) -> web_sys::Node {
use TemplateNode::*;
match v {
Element {
tag,
namespace,
attrs,
children,
..
} => {
let el = match namespace {
Some(ns) => self.document.create_element_ns(Some(ns), tag).unwrap(),
None => self.document.create_element(tag).unwrap(),
};
for attr in *attrs {
if let TemplateAttribute::Static {
name,
value,
namespace,
} = attr
{
match namespace {
Some(ns) if *ns == "style" => el
.dyn_ref::<HtmlElement>()
.unwrap()
.style()
.set_property(name, value)
.unwrap(),
Some(ns) => el.set_attribute_ns(Some(ns), name, value).unwrap(),
None => el.set_attribute(name, value).unwrap(),
}
}
}
for child in *children {
let _ = el.append_child(&self.create_template_node(child));
}
el.dyn_into().unwrap()
}
Text { text } => self.document.create_text_node(text).dyn_into().unwrap(),
DynamicText { .. } => self.document.create_text_node("p").dyn_into().unwrap(),
Dynamic { .. } => {
let el = self.document.create_element("pre").unwrap();
let _ = el.toggle_attribute("hidden");
el.dyn_into().unwrap()
}
}
}
pub fn apply_edits(&mut self, mut edits: Vec<Mutation>) {
use Mutation::*;
let i = &self.interpreter;
for edit in edits.drain(..) {
let i = &mut self.interpreter;
for edit in &edits {
match edit {
AppendChildren { id, m } => i.AppendChildren(m as u32, id.0 as u32),
AssignId { path, id } => i.AssignId(path, id.0 as u32),
CreatePlaceholder { id } => i.CreatePlaceholder(id.0 as u32),
CreateTextNode { value, id } => i.CreateTextNode(value.into(), id.0 as u32),
HydrateText { path, value, id } => i.HydrateText(path, value, id.0 as u32),
LoadTemplate { name, index, id } => i.LoadTemplate(name, index as u32, id.0 as u32),
ReplaceWith { id, m } => i.ReplaceWith(id.0 as u32, m as u32),
ReplacePlaceholder { path, m } => i.ReplacePlaceholder(path, m as u32),
InsertAfter { id, m } => i.InsertAfter(id.0 as u32, m as u32),
InsertBefore { id, m } => i.InsertBefore(id.0 as u32, m as u32),
AppendChildren { id, m } => i.append_children(id.0 as u32, *m as u32),
AssignId { path, id } => {
i.assign_id(path.as_ptr() as u32, path.len() as u8, id.0 as u32)
}
CreatePlaceholder { id } => i.create_placeholder(id.0 as u32),
CreateTextNode { value, id } => i.create_text_node(value, id.0 as u32),
HydrateText { path, value, id } => {
i.hydrate_text(path.as_ptr() as u32, path.len() as u8, value, id.0 as u32)
}
LoadTemplate { name, index, id } => {
if let Some(tmpl_id) = self.templates.get(*name) {
i.load_template(*tmpl_id, *index as u32, id.0 as u32)
}
}
ReplaceWith { id, m } => i.replace_with(id.0 as u32, *m as u32),
ReplacePlaceholder { path, m } => {
i.replace_placeholder(path.as_ptr() as u32, path.len() as u8, *m as u32)
}
InsertAfter { id, m } => i.insert_after(id.0 as u32, *m as u32),
InsertBefore { id, m } => i.insert_before(id.0 as u32, *m as u32),
SetAttribute {
name,
value,
id,
ns,
} => i.SetAttribute(id.0 as u32, name, value.into(), ns),
} => i.set_attribute(id.0 as u32, name, value, ns.unwrap_or_default()),
SetBoolAttribute { name, value, id } => {
i.SetBoolAttribute(id.0 as u32, name, value)
i.set_attribute(id.0 as u32, name, if *value { "true" } else { "false" }, "")
}
SetText { value, id } => i.SetText(id.0 as u32, value.into()),
SetText { value, id } => i.set_text(id.0 as u32, value),
NewEventListener { name, id, .. } => {
self.interpreter.NewEventListener(
name,
id.0 as u32,
event_bubbles(&name[2..]),
self.handler.as_ref().unchecked_ref(),
);
i.new_event_listener(name, id.0 as u32, event_bubbles(&name[2..]) as u8);
}
RemoveEventListener { name, id } => i.RemoveEventListener(name, id.0 as u32),
Remove { id } => i.Remove(id.0 as u32),
PushRoot { id } => i.PushRoot(id.0 as u32),
RemoveEventListener { name, id } => {
i.remove_event_listener(name, id.0 as u32, event_bubbles(&name[2..]) as u8)
}
Remove { id } => i.remove(id.0 as u32),
PushRoot { id } => i.push_root(id.0 as u32),
}
}
edits.clear();
i.flush();
}
}
@@ -230,9 +331,28 @@ fn read_input_to_data(target: Element) -> Rc<FormData> {
}
}
Rc::new(FormData {
value,
values,
files: None,
})
Rc::new(FormData { value, values })
}
fn walk_event_for_id(event: &web_sys::Event) -> Option<(ElementId, web_sys::Element)> {
use wasm_bindgen::JsCast;
let mut target = event
.target()
.expect("missing target")
.dyn_into::<web_sys::Element>()
.expect("not a valid element");
loop {
match target.get_attribute("data-dioxus-id").map(|f| f.parse()) {
Some(Ok(id)) => return Some((ElementId(id), target)),
Some(Err(_)) => return None,
// walk the tree upwards until we actually find an event target
None => match target.parent_element() {
Some(parent) => target = parent,
None => return None,
},
}
}
}
+7 -35
View File
@@ -55,7 +55,7 @@
pub use crate::cfg::Config;
use crate::dom::virtual_event_from_websys_event;
pub use crate::util::use_eval;
pub use crate::util::{use_eval, EvalResult};
use dioxus_core::{Element, ElementId, Scope, VirtualDom};
use futures_util::{pin_mut, FutureExt, StreamExt};
@@ -195,7 +195,7 @@ pub async fn run_with_props<T: 'static>(root: fn(Scope<T>) -> Element, root_prop
// the mutations come back with nothing - we need to actually mount them
websys_dom.mount();
let mut work_loop = ric_raf::RafLoop::new();
let _work_loop = ric_raf::RafLoop::new();
loop {
log::debug!("waiting for work");
@@ -222,16 +222,11 @@ pub async fn run_with_props<T: 'static>(root: fn(Scope<T>) -> Element, root_prop
// Dequeue all of the events from the channel in send order
// todo: we should re-order these if possible
while let Some(evt) = res {
let name = evt.type_();
let element = walk_event_for_id(&evt);
let bubbles = dioxus_html::event_bubbles(name.as_str());
if let Some((element, target)) = element {
let data = virtual_event_from_websys_event(evt, target);
dom.handle_event(name.as_str(), data, element, bubbles);
}
dom.handle_event(evt.name.as_str(), evt.data, evt.element, evt.bubbles);
res = rx.try_next().transpose().unwrap().ok();
}
// Todo: This is currently disabled because it has a negative impact on responce times for events but it could be re-enabled for tasks
// Jank free rendering
//
// 1. wait for the browser to give us "idle" time
@@ -240,42 +235,19 @@ pub async fn run_with_props<T: 'static>(root: fn(Scope<T>) -> Element, root_prop
// 4. Wait for the animation frame to patch the dom
// wait for the mainthread to schedule us in
let deadline = work_loop.wait_for_idle_time().await;
// let deadline = work_loop.wait_for_idle_time().await;
// run the virtualdom work phase until the frame deadline is reached
let edits = dom.render_with_deadline(deadline).await;
let edits = dom.render_immediate();
// wait for the animation frame to fire so we can apply our changes
work_loop.wait_for_raf().await;
// work_loop.wait_for_raf().await;
websys_dom.load_templates(&edits.templates);
websys_dom.apply_edits(edits.edits);
}
}
fn walk_event_for_id(event: &web_sys::Event) -> Option<(ElementId, web_sys::Element)> {
use wasm_bindgen::JsCast;
let mut target = event
.target()
.expect("missing target")
.dyn_into::<web_sys::Element>()
.expect("not a valid element");
loop {
match target.get_attribute("data-dioxus-id").map(|f| f.parse()) {
Some(Ok(id)) => return Some((ElementId(id), target)),
Some(Err(_)) => return None,
// walk the tree upwards until we actually find an event target
None => match target.parent_element() {
Some(parent) => target = parent,
None => return None,
},
}
}
}
// if should_hydrate {
// // todo: we need to split rebuild and initialize into two phases
// // it's a waste to produce edits just to get the vdom loaded
+50 -4
View File
@@ -1,6 +1,13 @@
//! Utilities specific to websys
use std::{
future::{IntoFuture, Ready},
str::FromStr,
};
use dioxus_core::*;
use serde::de::Error;
use serde_json::Value;
/// Get a closure that executes any JavaScript in the webpage.
///
@@ -15,12 +22,51 @@ use dioxus_core::*;
///
/// The closure will panic if the provided script is not valid JavaScript code
/// or if it returns an uncaught error.
pub fn use_eval<S: std::string::ToString>(cx: &ScopeState) -> &dyn Fn(S) {
pub fn use_eval<S: std::string::ToString>(cx: &ScopeState) -> &dyn Fn(S) -> EvalResult {
cx.use_hook(|| {
|script: S| {
js_sys::Function::new_no_args(&script.to_string())
.call0(&wasm_bindgen::JsValue::NULL)
.expect("failed to eval script");
let body = script.to_string();
EvalResult {
value: if let Ok(value) =
js_sys::Function::new_no_args(&body).call0(&wasm_bindgen::JsValue::NULL)
{
if let Ok(stringified) = js_sys::JSON::stringify(&value) {
if !stringified.is_undefined() && stringified.is_valid_utf16() {
let string: String = stringified.into();
Value::from_str(&string)
} else {
Err(serde_json::Error::custom("Failed to stringify result"))
}
} else {
Err(serde_json::Error::custom("Failed to stringify result"))
}
} else {
Err(serde_json::Error::custom("Failed to execute script"))
},
}
}
})
}
/// A wrapper around the result of a JavaScript evaluation.
/// This implements IntoFuture to be compatible with the desktop renderer's EvalResult.
pub struct EvalResult {
value: Result<Value, serde_json::Error>,
}
impl EvalResult {
/// Get the result of the Javascript execution.
pub fn get(self) -> Result<Value, serde_json::Error> {
self.value
}
}
impl IntoFuture for EvalResult {
type Output = Result<Value, serde_json::Error>;
type IntoFuture = Ready<Result<Value, serde_json::Error>>;
fn into_future(self) -> Self::IntoFuture {
std::future::ready(self.value)
}
}