Synchronous prevent default (#2792)

* add prevent default methods to the event

* sync prevent default almost working

* sync prevent default working

* Move event handling into the runtime

* update core tests

* restore desktop file dialog

* implement prevent default on web

* add a hint about the new prevent default method

* fix web prevent default

* Fix CTRL+click on links

* fix values memorize in place test

* Fix a few more tests

* Add a playwright test for sync prevent default

* Fix core doc tests

* create a deprecated VirtualDom::handle_event

* fix macos imports in desktop

* Fix onmounted event

* Fix liveview support

* switch to RefCell for metadata

* Remove println

* remove prevent default attribute

* remove web specific link behavior

* Fix liveview links

* more liveview fixes for link

* Fix merge conflicts

* Fix clippy

* use the new prevent default in the file upload example
This commit is contained in:
Evan Almloff authored and GitHub committed 2024-08-13 11:57:54 -07:00
1 parent 8b62b71e2d
commit cab573eefd
54 files changed
+940 -729

No files matched your search

+21 -41
View File
@@ -6,10 +6,11 @@
//! - tests to ensure dyn_into works for various event types.
//! - Partial delegation?
use std::{any::Any, rc::Rc};
use dioxus_core::Runtime;
use dioxus_core::{ElementId, Template};
use dioxus_html::PlatformEventData;
use dioxus_interpreter_js::unified_bindings::Interpreter;
use futures_channel::mpsc;
use rustc_hash::FxHashMap;
use wasm_bindgen::{closure::Closure, JsCast};
use web_sys::{Document, Element, Event};
@@ -24,7 +25,7 @@ pub struct WebsysDom {
pub(crate) interpreter: Interpreter,
#[cfg(feature = "mounted")]
pub(crate) event_channel: mpsc::UnboundedSender<UiEvent>,
pub(crate) runtime: Rc<Runtime>,
#[cfg(feature = "mounted")]
pub(crate) queued_mounted_events: Vec<ElementId>,
@@ -49,15 +50,8 @@ pub struct WebsysDom {
pub(crate) suspense_hydration_ids: crate::hydration::SuspenseHydrationIds,
}
pub struct UiEvent {
pub name: String,
pub bubbles: bool,
pub element: ElementId,
pub data: PlatformEventData,
}
impl WebsysDom {
pub fn new(cfg: Config, event_channel: mpsc::UnboundedSender<UiEvent>) -> Self {
pub fn new(cfg: Config, runtime: Rc<Runtime>) -> Self {
let (document, root) = match cfg.root {
crate::cfg::ConfigRoot::RootName(rootname) => {
// eventually, we just want to let the interpreter do all the work of decoding events into our event type
@@ -87,46 +81,32 @@ impl WebsysDom {
let interpreter = Interpreter::default();
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 = event.bubbles();
let runtime = runtime.clone();
move |web_sys_event: &web_sys::Event| {
let name = web_sys_event.type_();
let element = walk_event_for_id(web_sys_event);
let bubbles = web_sys_event.bubbles();
let Some((element, target)) = element else {
return;
};
let prevent_event;
if let Some(prevent_requests) = target
.get_attribute("dioxus-prevent-default")
.as_deref()
.map(|f| f.split_whitespace())
{
prevent_event = prevent_requests
.map(|f| f.strip_prefix("on").unwrap_or(f))
.any(|f| f == name);
} else {
prevent_event = false;
}
let data = virtual_event_from_websys_event(web_sys_event.clone(), target);
let event = dioxus_core::Event::new(Rc::new(data) as Rc<dyn Any>, bubbles);
runtime.handle_event(name.as_str(), event.clone(), element);
// Prevent the default action if the user set prevent default on the event
let prevent_default = !event.default_action_enabled();
// 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 !prevent_event {
event.prevent_default();
if !prevent_default {
web_sys_event.prevent_default();
}
} else if prevent_event {
event.prevent_default();
} else if prevent_default {
web_sys_event.prevent_default();
}
let data = virtual_event_from_websys_event(event.clone(), target);
let _ = event_channel.unbounded_send(UiEvent {
name,
bubbles,
element,
data,
});
}
}));
@@ -145,7 +125,7 @@ impl WebsysDom {
interpreter,
templates: FxHashMap::default(),
#[cfg(feature = "mounted")]
event_channel,
runtime,
#[cfg(feature = "mounted")]
queued_mounted_events: Default::default(),
#[cfg(feature = "hydrate")]
+13 -40
View File
@@ -20,8 +20,6 @@
//! To purview the examples, check of the root Dioxus crate - the examples in this crate are mostly meant to provide
//! validation of websys-specific features and not the general use of Dioxus.
use std::{panic, rc::Rc};
pub use crate::cfg::Config;
use crate::hydration::SuspenseMessage;
use dioxus_core::VirtualDom;
@@ -58,13 +56,11 @@ pub use hydration::*;
/// let app_fut = dioxus_web::run_with_props(App, RootProps { name: String::from("foo") });
/// wasm_bindgen_futures::spawn_local(app_fut);
/// ```
pub async fn run(virtual_dom: VirtualDom, web_config: Config) -> ! {
pub async fn run(mut virtual_dom: VirtualDom, web_config: Config) -> ! {
tracing::info!("Starting up");
let mut dom = virtual_dom;
#[cfg(feature = "document")]
dom.in_runtime(document::init_document);
virtual_dom.in_runtime(document::init_document);
#[cfg(feature = "panic_hook")]
if web_config.default_panic_hook {
@@ -74,11 +70,11 @@ pub async fn run(virtual_dom: VirtualDom, web_config: Config) -> ! {
#[cfg(all(feature = "hot_reload", debug_assertions))]
let mut hotreload_rx = hot_reload::init();
let (tx, mut rx) = futures_channel::mpsc::unbounded();
let runtime = virtual_dom.runtime();
let should_hydrate = web_config.hydrate;
let mut websys_dom = WebsysDom::new(web_config, tx);
let mut websys_dom = WebsysDom::new(web_config, runtime);
let mut hydration_receiver: Option<futures_channel::mpsc::UnboundedReceiver<SuspenseMessage>> =
None;
@@ -101,14 +97,14 @@ pub async fn run(virtual_dom: VirtualDom, web_config: Config) -> ! {
let server_data = HTMLDataCursor::from_serialized(&hydration_data);
// If the server serialized an error into the root suspense boundary, throw it into the root scope
if let Some(error) = server_data.error() {
dom.in_runtime(|| dioxus_core::ScopeId::APP.throw_error(error));
virtual_dom.in_runtime(|| dioxus_core::ScopeId::APP.throw_error(error));
}
with_server_data(server_data, || {
dom.rebuild(&mut websys_dom);
virtual_dom.rebuild(&mut websys_dom);
});
websys_dom.skip_mutations = false;
let rx = websys_dom.rehydrate(&dom).unwrap();
let rx = websys_dom.rehydrate(&virtual_dom).unwrap();
hydration_receiver = Some(rx);
}
#[cfg(not(feature = "hydrate"))]
@@ -116,7 +112,7 @@ pub async fn run(virtual_dom: VirtualDom, web_config: Config) -> ! {
panic!("Hydration is not enabled. Please enable the `hydrate` feature.");
}
} else {
dom.rebuild(&mut websys_dom);
virtual_dom.rebuild(&mut websys_dom);
websys_dom.flush_edits();
}
@@ -127,17 +123,15 @@ pub async fn run(virtual_dom: VirtualDom, web_config: Config) -> ! {
loop {
// if virtual dom has nothing, wait for it to have something before requesting idle time
// if there is work then this future resolves immediately.
let mut res;
#[cfg(all(feature = "hot_reload", debug_assertions))]
let template;
#[allow(unused)]
let mut hydration_work: Option<SuspenseMessage> = None;
{
let work = dom.wait_for_work().fuse();
let work = virtual_dom.wait_for_work().fuse();
pin_mut!(work);
let mut rx_next = rx.select_next_some();
let mut hydration_receiver_iter = futures_util::stream::iter(&mut hydration_receiver)
.fuse()
.flatten();
@@ -149,19 +143,12 @@ pub async fn run(virtual_dom: VirtualDom, web_config: Config) -> ! {
let mut hot_reload_next = hotreload_rx.select_next_some();
select! {
_ = work => {
res = None;
template = None;
},
new_template = hot_reload_next => {
res = None;
template = Some(new_template);
},
evt = rx_next => {
res = Some(evt);
template = None;
}
hydration_data = rx_hydration => {
res = None;
template = None;
#[cfg(feature = "hydrate")]
{
@@ -175,10 +162,8 @@ pub async fn run(virtual_dom: VirtualDom, web_config: Config) -> ! {
#[allow(unused)]
{
select! {
_ = work => res = None,
evt = rx_next => res = Some(evt),
_ = work => {},
hyd = rx_hydration => {
res = None;
#[cfg(feature = "hydrate")]
{
hydration_work = Some(hyd);
@@ -191,7 +176,7 @@ pub async fn run(virtual_dom: VirtualDom, web_config: Config) -> ! {
#[cfg(all(feature = "hot_reload", debug_assertions))]
if let Some(hr_msg) = template {
// Replace all templates
dioxus_hot_reload::apply_changes(&mut dom, &hr_msg);
dioxus_hot_reload::apply_changes(&mut virtual_dom, &hr_msg);
if !hr_msg.assets.is_empty() {
crate::hot_reload::invalidate_browser_asset_cache();
@@ -200,19 +185,7 @@ pub async fn run(virtual_dom: VirtualDom, web_config: Config) -> ! {
#[cfg(feature = "hydrate")]
if let Some(hydration_data) = hydration_work {
websys_dom.rehydrate_streaming(hydration_data, &mut dom);
}
// Dequeue all of the events from the channel in send order
// todo: we should re-order these if possible
while let Some(evt) = res {
dom.handle_event(
evt.name.as_str(),
Rc::new(evt.data),
evt.element,
evt.bubbles,
);
res = rx.try_next().transpose().unwrap().ok();
websys_dom.rehydrate_streaming(hydration_data, &mut virtual_dom);
}
// Todo: This is currently disabled because it has a negative impact on response times for events but it could be re-enabled for tasks
@@ -227,7 +200,7 @@ pub async fn run(virtual_dom: VirtualDom, web_config: Config) -> ! {
// let deadline = work_loop.wait_for_idle_time().await;
// run the virtualdom work phase until the frame deadline is reached
dom.render_immediate(&mut websys_dom);
virtual_dom.render_immediate(&mut websys_dom);
// wait for the animation frame to fire so we can apply our changes
// work_loop.wait_for_raf().await;
+8 -6
View File
@@ -63,12 +63,14 @@ impl WebsysDom {
for id in self.queued_mounted_events.drain(..) {
let node = self.interpreter.base().get_node(id.0 as u32);
if let Some(element) = node.dyn_ref::<web_sys::Element>() {
let _ = self.event_channel.unbounded_send(crate::dom::UiEvent {
name: "mounted".to_string(),
bubbles: false,
element: id,
data: dioxus_html::PlatformEventData::new(Box::new(element.clone())),
});
let event = dioxus_core::Event::new(
std::rc::Rc::new(dioxus_html::PlatformEventData::new(Box::new(
element.clone(),
))) as std::rc::Rc<dyn std::any::Any>,
false,
);
let name = "mounted";
self.runtime.handle_event(name, event, id)
}
}
}