Merge branch 'master' into prevent-default-form-web

This commit is contained in:
Evan Almloff committed 2023-07-20 13:42:14 -07:00
commit 67a2d31f9c
612 files changed
+45532 -7959

No files matched your search

+4 -3
View File
@@ -49,15 +49,16 @@ impl Config {
/// Set the name of the element that Dioxus will use as the root.
///
/// This is akint to calling React.render() on the element with the specified name.
/// This is akin to calling React.render() on the element with the specified name.
pub fn rootname(mut self, name: impl Into<String>) -> Self {
self.rootname = name.into();
self
}
/// Set the name of the element that Dioxus will use as the root.
/// Sets a string cache for wasm bindgen to [intern](https://docs.rs/wasm-bindgen/0.2.84/wasm_bindgen/fn.intern.html). This can help reduce the time it takes for wasm bindgen to pass
/// strings from rust to javascript. This can significantly improve pefromance when passing strings to javascript, but can have a negative impact on startup time.
///
/// This is akint to calling React.render() on the element with the specified name.
/// > Currently this cache is only used when creating static elements and attributes.
pub fn with_string_cache(mut self, cache: Vec<String>) -> Self {
self.cached_strings = cache;
self
+135 -71
View File
@@ -10,15 +10,16 @@
use dioxus_core::{
BorrowedAttributeValue, ElementId, Mutation, Template, TemplateAttribute, TemplateNode,
};
use dioxus_html::{event_bubbles, CompositionData, 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};
use wasm_bindgen::{closure::Closure, JsCast};
use web_sys::{Document, Element, Event, HtmlElement};
use std::{any::Any, rc::Rc, sync::Arc};
use wasm_bindgen::{closure::Closure, prelude::wasm_bindgen, JsCast, JsValue};
use web_sys::{Document, Element, Event};
use crate::Config;
use crate::{file_engine::WebFileEngine, Config};
pub struct WebsysDom {
document: Document,
@@ -27,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 {
@@ -34,7 +36,6 @@ pub struct UiEvent {
pub bubbles: bool,
pub element: ElementId,
pub data: Rc<dyn Any>,
pub event: Event,
}
impl WebsysDom {
@@ -48,24 +49,36 @@ 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 {
let prevent_default_attribute = target.get_attribute("dioxus-prevent-default");
let prevented_event = prevent_default_attribute
let prevent_event;
if let Some(prevent_requests) = target
.get_attribute("dioxus-prevent-default")
.as_deref()
.map(|f| f.trim_start_matches("on"));
.map(|f| f.split_whitespace())
{
prevent_event = prevent_requests
.map(|f| f.trim_start_matches("on"))
.any(|f| f == name);
} else {
prevent_event = false;
}
// Prevent forms from submitting and redirecting
if name == "submit" {
// On forms the default behavior is not to submit, if prevent default is set then we submit the form
if prevented_event != Some("submit") {
if !prevent_event {
event.prevent_default();
}
} else {
if prevent_event {
event.prevent_default();
}
} else if prevented_event == Some(&name) {
event.prevent_default();
}
let data = virtual_event_from_websys_event(event.clone(), target);
@@ -74,10 +87,10 @@ impl WebsysDom {
bubbles,
element,
data,
event: event.clone(),
});
}
}));
}
}));
dioxus_interpreter_js::initilize(
root.clone().unchecked_into(),
@@ -90,6 +103,7 @@ impl WebsysDom {
interpreter,
templates: FxHashMap::default(),
max_template_id: 0,
event_channel,
}
}
@@ -133,14 +147,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 {
@@ -161,6 +173,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),
@@ -211,17 +225,43 @@ impl WebsysDom {
},
SetText { value, id } => i.set_text(id.0 as u32, value),
NewEventListener { name, id, .. } => {
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,
});
}
}
}
}
@@ -264,9 +304,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(()),
@@ -330,64 +372,86 @@ fn read_input_to_data(target: Element) -> Rc<FormData> {
// try to fill in form values
if let Some(form) = target.dyn_ref::<web_sys::HtmlFormElement>() {
let elements = form.elements();
for x in 0..elements.length() {
let element = elements.item(x).unwrap();
if let Some(name) = element.get_attribute("name") {
let value: Option<String> = element
.dyn_ref()
.map(|input: &web_sys::HtmlInputElement| {
match input.type_().as_str() {
"checkbox" => {
match input.checked() {
true => Some("true".to_string()),
false => Some("false".to_string()),
}
},
"radio" => {
match input.checked() {
true => Some(input.value()),
false => None,
}
}
_ => Some(input.value())
}
})
.or_else(|| element.dyn_ref().map(|input: &web_sys::HtmlTextAreaElement| Some(input.value())))
.or_else(|| element.dyn_ref().map(|input: &web_sys::HtmlSelectElement| Some(input.value())))
.or_else(|| Some(element.dyn_ref::<web_sys::HtmlElement>().unwrap().text_content()))
.expect("only an InputElement or TextAreaElement or an element with contenteditable=true can have an oninput event listener");
if let Some(value) = value {
values.insert(name, value);
let form_data = get_form_data(form);
for value in form_data.entries().into_iter().flatten() {
if let Ok(array) = value.dyn_into::<Array>() {
if let Some(name) = array.get(0).as_string() {
if let Ok(item_values) = array.get(1).dyn_into::<Array>() {
let item_values =
item_values.iter().filter_map(|v| v.as_string()).collect();
values.insert(name, item_values);
}
}
}
}
}
let files = target
.dyn_ref()
.and_then(|input: &web_sys::HtmlInputElement| {
input.files().and_then(|files| {
WebFileEngine::new(files).map(|f| Arc::new(f) as Arc<dyn FileEngine>)
})
});
Rc::new(FormData {
value,
values,
files: None,
files,
})
}
// web-sys does not expose the keys api for form data, so we need to manually bind to it
#[wasm_bindgen(inline_js = r#"
export function get_form_data(form) {
let values = new Map();
const formData = new FormData(form);
for (let name of formData.keys()) {
values.set(name, formData.getAll(name));
}
return values;
}
"#)]
extern "C" {
fn get_form_data(form: &web_sys::HtmlFormElement) -> js_sys::Map;
}
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,
}
}
}
+103
View File
@@ -0,0 +1,103 @@
use dioxus_html::FileEngine;
use futures_channel::oneshot;
use js_sys::Uint8Array;
use wasm_bindgen::{prelude::Closure, JsCast};
use web_sys::{File, FileList, FileReader};
pub(crate) struct WebFileEngine {
file_reader: FileReader,
file_list: FileList,
}
impl WebFileEngine {
pub fn new(file_list: FileList) -> Option<Self> {
Some(Self {
file_list,
file_reader: FileReader::new().ok()?,
})
}
fn len(&self) -> usize {
self.file_list.length() as usize
}
fn get(&self, index: usize) -> Option<File> {
self.file_list.item(index as u32)
}
fn find(&self, name: &str) -> Option<File> {
(0..self.len())
.filter_map(|i| self.get(i))
.find(|f| f.name() == name)
}
}
#[async_trait::async_trait(?Send)]
impl FileEngine for WebFileEngine {
fn files(&self) -> Vec<String> {
(0..self.len())
.filter_map(|i| self.get(i).map(|f| f.name()))
.collect()
}
// read a file to bytes
async fn read_file(&self, file: &str) -> Option<Vec<u8>> {
let file = self.find(file)?;
let file_reader = self.file_reader.clone();
let (rx, tx) = oneshot::channel();
let on_load: Closure<dyn FnMut()> = Closure::new({
let mut rx = Some(rx);
move || {
let result = file_reader.result();
let _ = rx
.take()
.expect("multiple files read without refreshing the channel")
.send(result);
}
});
self.file_reader
.set_onload(Some(on_load.as_ref().unchecked_ref()));
on_load.forget();
self.file_reader.read_as_array_buffer(&file).ok()?;
if let Ok(Ok(js_val)) = tx.await {
let as_u8_arr = Uint8Array::new(&js_val);
let as_u8_vec = as_u8_arr.to_vec();
Some(as_u8_vec)
} else {
None
}
}
// read a file to string
async fn read_file_to_string(&self, file: &str) -> Option<String> {
let file = self.find(file)?;
let file_reader = self.file_reader.clone();
let (rx, tx) = oneshot::channel();
let on_load: Closure<dyn FnMut()> = Closure::new({
let mut rx = Some(rx);
move || {
let result = file_reader.result();
let _ = rx
.take()
.expect("multiple files read without refreshing the channel")
.send(result);
}
});
self.file_reader
.set_onload(Some(on_load.as_ref().unchecked_ref()));
on_load.forget();
self.file_reader.read_as_text(&file).ok()?;
if let Ok(Ok(js_val)) = tx.await {
js_val.as_string()
} else {
None
}
}
}
+3 -2
View File
@@ -61,6 +61,7 @@ use futures_util::{pin_mut, FutureExt, StreamExt};
mod cache;
mod cfg;
mod dom;
mod file_engine;
mod hot_reload;
#[cfg(feature = "hydrate")]
mod rehydrate;
@@ -225,7 +226,7 @@ pub async fn run_with_props<T: 'static>(root: fn(Scope<T>) -> Element, root_prop
websys_dom.mount();
loop {
log::debug!("waiting for work");
log::trace!("waiting for work");
// if virtualdom has nothing, wait for it to have something before requesting idle time
// if there is work then this future resolves immediately.
@@ -253,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 -3
View File
@@ -90,7 +90,7 @@ impl WebsysDom {
// make sure we set the root node ids even if the node is not dynamic
set_node(
hydrated,
vnode.root_ids.get(i).ok_or(VNodeNotInitialized)?,
*vnode.root_ids.borrow().get(i).ok_or(VNodeNotInitialized)?,
current_child.clone()?,
);
@@ -115,6 +115,12 @@ impl WebsysDom {
node: &TemplateNode,
last_node_was_static_text: &mut bool,
) -> Result<(), RehydrationError> {
log::trace!("rehydrate template node: {:?}", node);
if let Ok(current_child) = current_child {
if log::log_enabled!(log::Level::Trace) {
web_sys::console::log_1(&current_child.clone().into());
}
}
match node {
TemplateNode::Element {
children, attrs, ..
@@ -128,10 +134,11 @@ impl WebsysDom {
mounted_id = Some(id);
let name = attribute.name;
if let AttributeValue::Listener(_) = value {
let event_name = &name[2..];
self.interpreter.new_event_listener(
&name[2..],
event_name,
id.0 as u32,
event_bubbles(name) as u8,
event_bubbles(event_name) as u8,
);
}
}
@@ -197,6 +204,12 @@ impl WebsysDom {
dynamic: &DynamicNode,
last_node_was_static_text: &mut bool,
) -> Result<(), RehydrationError> {
log::trace!("rehydrate dynamic node: {:?}", dynamic);
if let Ok(current_child) = current_child {
if log::log_enabled!(log::Level::Trace) {
web_sys::console::log_1(&current_child.clone().into());
}
}
match dynamic {
dioxus_core::DynamicNode::Text(VText { id, .. }) => {
// skip comment separator before node
+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>
})
}