Merge branch 'master' into add-file-data-drag-event

This commit is contained in:
Evan Almloff committed 2023-07-11 17:53:09 -05:00
commit 7577019946
374 files changed
+28686 -1919

No files matched your search

+16 -16
View File
@@ -1,34 +1,34 @@
[package]
name = "dioxus-web"
version = "0.3.1"
version = "0.3.2"
authors = ["Jonathan Kelley"]
edition = "2018"
description = "Dioxus VirtualDOM renderer for the web browser using websys"
description = "Web renderer for Dioxus using websys"
license = "MIT/Apache-2.0"
repository = "https://github.com/DioxusLabs/dioxus/"
homepage = "https://dioxuslabs.com"
documentation = "https://dioxuslabs.com"
homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/web.html"
keywords = ["dom", "ui", "gui", "react", "wasm"]
[dependencies]
dioxus-core = { path = "../core", version = "^0.3.0", features = ["serialize"] }
dioxus-html = { path = "../html", version = "^0.3.0", features = ["wasm-bind"] }
dioxus-interpreter-js = { path = "../interpreter", version = "^0.3.0", features = [
"sledgehammer"
dioxus-core = { workspace = true, features = ["serialize"] }
dioxus-html = { workspace = true, features = ["wasm-bind"] }
dioxus-interpreter-js = { workspace = true, features = [
"sledgehammer",
"minimal_bindings",
] }
js-sys = "0.3.56"
wasm-bindgen = { version = "0.2.79", features = ["enable-interning"] }
wasm-bindgen = { workspace = true, features = ["enable-interning"] }
wasm-bindgen-futures = "0.4.29"
log = "0.4.14"
rustc-hash = "1.1.0"
log = { workspace = true }
rustc-hash = { workspace = true }
console_error_panic_hook = { version = "0.1.7", optional = true }
once_cell = "1.9.0"
anyhow = "1.0.53"
gloo-timers = { version = "0.2.3", features = ["futures"] }
futures-util = "0.3.19"
futures-util = { workspace = true, features = ["std", "async-await", "async-await-macro"] }
smallstr = "0.2.0"
futures-channel = "0.3.21"
futures-channel = { workspace = true }
serde_json = { version = "1.0" }
serde = { version = "1.0" }
serde-wasm-bindgen = "0.4.5"
@@ -89,8 +89,8 @@ panic_hook = ["console_error_panic_hook"]
hydrate = []
[dev-dependencies]
dioxus = { path = "../dioxus", version = "0.3.0" }
dioxus = { workspace = true }
wasm-bindgen-test = "0.3.29"
dioxus-ssr = { path = "../ssr", version = "0.3.0"}
dioxus-ssr = { workspace = true}
wasm-logger = "0.2.0"
dioxus-web = { path = ".", features = ["hydrate"] }
dioxus-web = { workspace = true, features = ["hydrate"] }
+87 -39
View File
@@ -10,14 +10,14 @@
use dioxus_core::{
BorrowedAttributeValue, ElementId, Mutation, Template, TemplateAttribute, TemplateNode,
};
use dioxus_html::{event_bubbles, CompositionData, FileEngine, FormData};
use dioxus_interpreter_js::{save_template, Channel};
use dioxus_html::{event_bubbles, CompositionData, FileEngine, FormData, MountedData};
use dioxus_interpreter_js::{get_node, minimal_bindings, save_template, Channel};
use futures_channel::mpsc;
use js_sys::Array;
use rustc_hash::FxHashMap;
use std::{any::Any, rc::Rc, sync::Arc};
use wasm_bindgen::{closure::Closure, prelude::wasm_bindgen, JsCast};
use web_sys::{console, Document, Element, Event, HtmlElement};
use wasm_bindgen::{closure::Closure, prelude::wasm_bindgen, JsCast, JsValue};
use web_sys::{Document, Element, Event};
use crate::{file_engine::WebFileEngine, Config};
@@ -28,6 +28,7 @@ pub struct WebsysDom {
templates: FxHashMap<String, u32>,
max_template_id: u32,
pub(crate) interpreter: Channel,
event_channel: mpsc::UnboundedSender<UiEvent>,
}
pub struct UiEvent {
@@ -35,7 +36,6 @@ pub struct UiEvent {
pub bubbles: bool,
pub element: ElementId,
pub data: Rc<dyn Any>,
pub event: Event,
}
impl WebsysDom {
@@ -49,19 +49,24 @@ impl WebsysDom {
};
let interpreter = Channel::default();
let handler: Closure<dyn FnMut(&Event)> =
Closure::wrap(Box::new(move |event: &web_sys::Event| {
let handler: Closure<dyn FnMut(&Event)> = Closure::wrap(Box::new({
let event_channel = event_channel.clone();
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
if let Some(prevent_requests) = target
.get_attribute("dioxus-prevent-default")
.as_deref()
.map(|f| f.trim_start_matches("on"))
== Some(&name)
.map(|f| f.split_whitespace())
{
event.prevent_default();
if prevent_requests
.map(|f| f.trim_start_matches("on"))
.any(|f| f == name)
{
event.prevent_default();
}
}
let data = virtual_event_from_websys_event(event.clone(), target);
@@ -70,10 +75,10 @@ impl WebsysDom {
bubbles,
element,
data,
event: event.clone(),
});
}
}));
}
}));
dioxus_interpreter_js::initilize(
root.clone().unchecked_into(),
@@ -86,6 +91,7 @@ impl WebsysDom {
interpreter,
templates: FxHashMap::default(),
max_template_id: 0,
event_channel,
}
}
@@ -129,14 +135,12 @@ impl WebsysDom {
namespace,
} = attr
{
match namespace {
Some(ns) if *ns == "style" => {
el.dyn_ref::<HtmlElement>()
.map(|f| f.style().set_property(name, value));
}
Some(ns) => el.set_attribute_ns(Some(ns), name, value).unwrap(),
None => el.set_attribute(name, value).unwrap(),
}
minimal_bindings::setAttributeInner(
el.clone().into(),
name,
JsValue::from_str(value),
*namespace,
);
}
}
for child in *children {
@@ -157,6 +161,8 @@ impl WebsysDom {
pub fn apply_edits(&mut self, mut edits: Vec<Mutation>) {
use Mutation::*;
let i = &mut self.interpreter;
// we need to apply the mount events last, so we collect them here
let mut to_mount = Vec::new();
for edit in &edits {
match edit {
AppendChildren { id, m } => i.append_children(id.0 as u32, *m as u32),
@@ -207,18 +213,43 @@ impl WebsysDom {
},
SetText { value, id } => i.set_text(id.0 as u32, value),
NewEventListener { name, id, .. } => {
console::log_1(&format!("new event listener: {}", name).into());
i.new_event_listener(name, id.0 as u32, event_bubbles(name) as u8);
}
RemoveEventListener { name, id } => {
i.remove_event_listener(name, id.0 as u32, event_bubbles(name) as u8)
match *name {
// mounted events are fired immediately after the element is mounted.
"mounted" => {
to_mount.push(*id);
}
_ => {
i.new_event_listener(name, id.0 as u32, event_bubbles(name) as u8);
}
}
}
RemoveEventListener { name, id } => match *name {
"mounted" => {}
_ => {
i.remove_event_listener(name, id.0 as u32, event_bubbles(name) as u8);
}
},
Remove { id } => i.remove(id.0 as u32),
PushRoot { id } => i.push_root(id.0 as u32),
}
}
edits.clear();
i.flush();
for id in to_mount {
let node = get_node(id.0 as u32);
if let Some(element) = node.dyn_ref::<Element>() {
log::info!("mounted event fired: {}", id.0);
let data: MountedData = element.into();
let data = Rc::new(data);
let _ = self.event_channel.unbounded_send(UiEvent {
name: "mounted".to_string(),
bubbles: false,
element: id,
data,
});
}
}
}
}
@@ -226,7 +257,6 @@ impl WebsysDom {
// We need tests that simulate clicks/etc and make sure every event type works.
pub fn virtual_event_from_websys_event(event: web_sys::Event, target: Element) -> Rc<dyn Any> {
use dioxus_html::events::*;
console::log_1(&event.clone().into());
match event.type_().as_str() {
"copy" | "cut" | "paste" => Rc::new(ClipboardData {}),
@@ -271,9 +301,11 @@ pub fn virtual_event_from_websys_event(event: web_sys::Event, target: Element) -
}
"transitionend" => Rc::new(TransitionData::from(event)),
"abort" | "canplay" | "canplaythrough" | "durationchange" | "emptied" | "encrypted"
| "ended" | "error" | "loadeddata" | "loadedmetadata" | "loadstart" | "pause" | "play"
| "ended" | "loadeddata" | "loadedmetadata" | "loadstart" | "pause" | "play"
| "playing" | "progress" | "ratechange" | "seeked" | "seeking" | "stalled" | "suspend"
| "timeupdate" | "volumechange" | "waiting" => Rc::new(MediaData {}),
"error" => Rc::new(ImageData { load_error: true }),
"load" => Rc::new(ImageData { load_error: false }),
"toggle" => Rc::new(ToggleData {}),
_ => Rc::new(()),
@@ -385,22 +417,38 @@ extern "C" {
}
fn walk_event_for_id(event: &web_sys::Event) -> Option<(ElementId, web_sys::Element)> {
let mut target = event
let target = event
.target()
.expect("missing target")
.dyn_into::<web_sys::Element>()
.expect("not a valid element");
.dyn_into::<web_sys::Node>()
.expect("not a valid node");
let mut current_target_element = target.dyn_ref::<web_sys::Element>().cloned();
loop {
match target.get_attribute("data-dioxus-id").map(|f| f.parse()) {
Some(Ok(id)) => return Some((ElementId(id), target)),
Some(Err(_)) => return None,
match (
current_target_element
.as_ref()
.and_then(|el| el.get_attribute("data-dioxus-id").map(|f| f.parse())),
current_target_element,
) {
// This node is an element, and has a dioxus id, so we can stop walking
(Some(Ok(id)), Some(target)) => return Some((ElementId(id), target)),
// walk the tree upwards until we actually find an event target
None => match target.parent_element() {
Some(parent) => target = parent,
None => return None,
},
// Walk the tree upwards until we actually find an event target
(None, target_element) => {
let parent = match target_element.as_ref() {
Some(el) => el.parent_element(),
// if this is the first node and not an element, we need to get the parent from the target node
None => target.parent_element(),
};
match parent {
Some(parent) => current_target_element = Some(parent),
_ => return None,
}
}
// This node is an element with an invalid dioxus id, give up
_ => return None,
}
}
}
+1 -1
View File
@@ -254,7 +254,7 @@ pub async fn run_with_props<T: 'static>(root: fn(Scope<T>) -> Element, root_prop
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
// Todo: This is currently disabled because it has a negative impact on response times for events but it could be re-enabled for tasks
// Jank free rendering
//
// 1. wait for the browser to give us "idle" time
+16 -18
View File
@@ -2,6 +2,7 @@
use std::{
future::{IntoFuture, Ready},
rc::Rc,
str::FromStr,
};
@@ -22,29 +23,26 @@ use serde_json::Value;
///
/// 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) -> EvalResult {
pub fn use_eval(cx: &ScopeState) -> &Rc<dyn Fn(String) -> EvalResult> {
cx.use_hook(|| {
|script: S| {
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"))
}
Rc::new(|script: String| EvalResult {
value: if let Ok(value) =
js_sys::Function::new_no_args(&script).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 execute script"))
},
}
}
Err(serde_json::Error::custom("Failed to stringify result"))
}
} else {
Err(serde_json::Error::custom("Failed to execute script"))
},
}) as Rc<dyn Fn(String) -> EvalResult>
})
}