Merge branch 'main' into fix-effect
This commit is contained in:
commit
3827378f68
49 files changed
+1100
-670
No files matched your search
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "dioxus-cli-config"
|
||||
version = "0.4.1"
|
||||
version = { workspace = true }
|
||||
authors = ["Jonathan Kelley"]
|
||||
edition = "2021"
|
||||
description = "Configuration for the Dioxus CLI"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "dioxus-cli"
|
||||
version = "0.4.3"
|
||||
version = { workspace = true }
|
||||
authors = ["Jonathan Kelley"]
|
||||
edition = "2021"
|
||||
description = "CLI tool for developing, testing, and publishing Dioxus apps"
|
||||
|
||||
@@ -20,9 +20,11 @@ slab = { workspace = true }
|
||||
futures-channel = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { version = "1", features = ["derive"], optional = true }
|
||||
tracing-subscriber = "0.3.18"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
tracing-fluent-assertions = "0.3.0"
|
||||
dioxus = { workspace = true }
|
||||
pretty_assertions = "1.3.0"
|
||||
rand = "0.8.5"
|
||||
|
||||
@@ -21,6 +21,7 @@ use futures_util::StreamExt;
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
use slab::Slab;
|
||||
use std::{any::Any, collections::BTreeSet, rc::Rc};
|
||||
use tracing::instrument;
|
||||
|
||||
/// A virtual node system that progresses user events and diffs UI trees.
|
||||
///
|
||||
@@ -305,6 +306,7 @@ impl VirtualDom {
|
||||
/// let mut dom = VirtualDom::new_from_root(VComponent::new(Example, SomeProps { name: "jane" }, "Example"));
|
||||
/// let mutations = dom.rebuild();
|
||||
/// ```
|
||||
#[instrument(skip(root), level = "trace", name = "VirtualDom::new")]
|
||||
pub(crate) fn new_with_component(root: impl AnyProps + 'static) -> Self {
|
||||
let (tx, rx) = futures_channel::mpsc::unbounded();
|
||||
|
||||
@@ -347,6 +349,7 @@ impl VirtualDom {
|
||||
}
|
||||
|
||||
/// Run a closure inside the dioxus runtime
|
||||
#[instrument(skip(self, f), level = "trace", name = "VirtualDom::in_runtime")]
|
||||
pub fn in_runtime<O>(&self, f: impl FnOnce() -> O) -> O {
|
||||
let _runtime = RuntimeGuard::new(self.runtime.clone());
|
||||
f()
|
||||
@@ -375,7 +378,7 @@ impl VirtualDom {
|
||||
return;
|
||||
};
|
||||
|
||||
tracing::trace!("Marking scope {:?} as dirty", id);
|
||||
tracing::event!(tracing::Level::TRACE, "Marking scope {:?} as dirty", id);
|
||||
let order = ScopeOrder::new(scope.height(), id);
|
||||
self.dirty_scopes.queue_scope(order);
|
||||
}
|
||||
@@ -388,6 +391,14 @@ impl VirtualDom {
|
||||
let Some(scope) = self.runtime.get_state(scope) else {
|
||||
return;
|
||||
};
|
||||
|
||||
tracing::event!(
|
||||
tracing::Level::TRACE,
|
||||
"Marking task {:?} (spawned in {:?}) as dirty",
|
||||
task,
|
||||
scope.id
|
||||
);
|
||||
|
||||
let order = ScopeOrder::new(scope.height(), scope.id);
|
||||
self.dirty_scopes.queue_task(task, order);
|
||||
}
|
||||
@@ -401,6 +412,7 @@ impl VirtualDom {
|
||||
/// It is up to the listeners themselves to mark nodes as dirty.
|
||||
///
|
||||
/// If you have multiple events, you can call this method multiple times before calling "render_with_deadline"
|
||||
#[instrument(skip(self), level = "trace", name = "VirtualDom::handle_event")]
|
||||
pub fn handle_event(
|
||||
&mut self,
|
||||
name: &str,
|
||||
@@ -434,12 +446,14 @@ impl VirtualDom {
|
||||
/// ```rust, ignore
|
||||
/// let dom = VirtualDom::new(app);
|
||||
/// ```
|
||||
#[instrument(skip(self), level = "trace", name = "VirtualDom::wait_for_work")]
|
||||
pub async fn wait_for_work(&mut self) {
|
||||
// And then poll the futures
|
||||
self.poll_tasks().await;
|
||||
}
|
||||
|
||||
/// Poll the scheduler for any work
|
||||
#[instrument(skip(self), level = "trace", name = "VirtualDom::poll_tasks")]
|
||||
async fn poll_tasks(&mut self) {
|
||||
loop {
|
||||
// Process all events - Scopes are marked dirty, etc
|
||||
@@ -478,6 +492,7 @@ impl VirtualDom {
|
||||
}
|
||||
|
||||
/// Process all events in the queue until there are no more left
|
||||
#[instrument(skip(self), level = "trace", name = "VirtualDom::process_events")]
|
||||
pub fn process_events(&mut self) {
|
||||
let _runtime = RuntimeGuard::new(self.runtime.clone());
|
||||
self.queue_events();
|
||||
@@ -513,7 +528,8 @@ impl VirtualDom {
|
||||
///
|
||||
/// The caller must ensure that the template references the same dynamic attributes and nodes as the original template.
|
||||
///
|
||||
/// This will only replace the the parent template, not any nested templates.
|
||||
/// This will only replace the parent template, not any nested templates.
|
||||
#[instrument(skip(self), level = "trace", name = "VirtualDom::replace_template")]
|
||||
pub fn replace_template(&mut self, template: Template) {
|
||||
self.register_template_first_byte_index(template);
|
||||
// iterating a slab is very inefficient, but this is a rare operation that will only happen during development so it's fine
|
||||
@@ -552,7 +568,7 @@ impl VirtualDom {
|
||||
/// The mutations item expects the RealDom's stack to be the root of the application.
|
||||
///
|
||||
/// Tasks will not be polled with this method, nor will any events be processed from the event queue. Instead, the
|
||||
/// root component will be ran once and then diffed. All updates will flow out as mutations.
|
||||
/// root component will be run once and then diffed. All updates will flow out as mutations.
|
||||
///
|
||||
/// All state stored in components will be completely wiped away.
|
||||
///
|
||||
@@ -567,6 +583,7 @@ impl VirtualDom {
|
||||
///
|
||||
/// apply_edits(edits);
|
||||
/// ```
|
||||
#[instrument(skip(self, to), level = "trace", name = "VirtualDom::rebuild")]
|
||||
pub fn rebuild(&mut self, to: &mut impl WriteMutations) {
|
||||
self.flush_templates(to);
|
||||
let _runtime = RuntimeGuard::new(self.runtime.clone());
|
||||
@@ -580,6 +597,7 @@ impl VirtualDom {
|
||||
|
||||
/// Render whatever the VirtualDom has ready as fast as possible without requiring an executor to progress
|
||||
/// suspended subtrees.
|
||||
#[instrument(skip(self, to), level = "trace", name = "VirtualDom::render_immediate")]
|
||||
pub fn render_immediate(&mut self, to: &mut impl WriteMutations) {
|
||||
self.flush_templates(to);
|
||||
|
||||
@@ -627,7 +645,8 @@ impl VirtualDom {
|
||||
/// The mutations will be thrown out, so it's best to use this method for things like SSR that have async content
|
||||
///
|
||||
/// We don't call "flush_sync" here since there's no sync work to be done. Futures will be progressed like usual,
|
||||
/// however any futures wating on flush_sync will remain pending
|
||||
/// however any futures waiting on flush_sync will remain pending
|
||||
#[instrument(skip(self), level = "trace", name = "VirtualDom::wait_for_suspense")]
|
||||
pub async fn wait_for_suspense(&mut self) {
|
||||
loop {
|
||||
if self.suspended_scopes.is_empty() {
|
||||
@@ -648,6 +667,7 @@ impl VirtualDom {
|
||||
}
|
||||
|
||||
/// Flush any queued template changes
|
||||
#[instrument(skip(self, to), level = "trace", name = "VirtualDom::flush_templates")]
|
||||
fn flush_templates(&mut self, to: &mut impl WriteMutations) {
|
||||
for template in self.queued_templates.drain(..) {
|
||||
to.register_template(template);
|
||||
@@ -675,6 +695,11 @@ impl VirtualDom {
|
||||
| | | <-- no, broke early
|
||||
| <-- no, broke early
|
||||
*/
|
||||
#[instrument(
|
||||
skip(self, uievent),
|
||||
level = "trace",
|
||||
name = "VirtualDom::handle_bubbling_event"
|
||||
)]
|
||||
fn handle_bubbling_event(
|
||||
&mut self,
|
||||
mut parent: Option<ElementRef>,
|
||||
@@ -713,6 +738,11 @@ impl VirtualDom {
|
||||
|
||||
// Now that we've accumulated all the parent attributes for the target element, call them in reverse order
|
||||
// We check the bubble state between each call to see if the event has been stopped from bubbling
|
||||
tracing::event!(
|
||||
tracing::Level::TRACE,
|
||||
"Calling {} listeners",
|
||||
listeners.len()
|
||||
);
|
||||
for listener in listeners.into_iter().rev() {
|
||||
if let AttributeValue::Listener(listener) = listener {
|
||||
self.runtime.rendering.set(false);
|
||||
@@ -731,6 +761,11 @@ impl VirtualDom {
|
||||
}
|
||||
|
||||
/// Call an event listener in the simplest way possible without bubbling upwards
|
||||
#[instrument(
|
||||
skip(self, uievent),
|
||||
level = "trace",
|
||||
name = "VirtualDom::handle_non_bubbling_event"
|
||||
)]
|
||||
fn handle_non_bubbling_event(&mut self, node: ElementRef, name: &str, uievent: Event<dyn Any>) {
|
||||
let el_ref = &self.mounts[node.mount.0].node;
|
||||
let node_template = el_ref.template.get();
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_core::{AttributeValue, DynamicNode, NoOpMutations, VComponent, VNode, *};
|
||||
use std::{cfg, collections::HashSet, default::Default};
|
||||
use std::{
|
||||
cfg, collections::HashSet, default::Default, sync::atomic::AtomicUsize, sync::atomic::Ordering,
|
||||
};
|
||||
|
||||
fn random_ns() -> Option<&'static str> {
|
||||
let namespace = rand::random::<u8>() % 2;
|
||||
@@ -220,20 +222,14 @@ fn create_random_dynamic_attr() -> Attribute {
|
||||
)
|
||||
}
|
||||
|
||||
static mut TEMPLATE_COUNT: usize = 0;
|
||||
static TEMPLATE_COUNT: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
fn create_template_location() -> &'static str {
|
||||
Box::leak(
|
||||
format!(
|
||||
"{}{}",
|
||||
concat!(file!(), ":", line!(), ":", column!(), ":"),
|
||||
{
|
||||
unsafe {
|
||||
let old = TEMPLATE_COUNT;
|
||||
TEMPLATE_COUNT += 1;
|
||||
old
|
||||
}
|
||||
}
|
||||
TEMPLATE_COUNT.fetch_add(1, Ordering::Relaxed)
|
||||
)
|
||||
.into_boxed_str(),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
use dioxus::html::SerializedHtmlEventConverter;
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_core::ElementId;
|
||||
use std::rc::Rc;
|
||||
use tracing_fluent_assertions::{AssertionRegistry, AssertionsLayer};
|
||||
use tracing_subscriber::{layer::SubscriberExt, Registry};
|
||||
|
||||
#[test]
|
||||
fn basic_tracing() {
|
||||
// setup tracing
|
||||
let assertion_registry = AssertionRegistry::default();
|
||||
let base_subscriber = Registry::default();
|
||||
// log to standard out for testing
|
||||
let std_out_log = tracing_subscriber::fmt::layer().pretty();
|
||||
let subscriber = base_subscriber
|
||||
.with(std_out_log)
|
||||
.with(AssertionsLayer::new(&assertion_registry));
|
||||
tracing::subscriber::set_global_default(subscriber).unwrap();
|
||||
|
||||
let new_virtual_dom = assertion_registry
|
||||
.build()
|
||||
.with_name("VirtualDom::new")
|
||||
.was_created()
|
||||
.was_entered_exactly(1)
|
||||
.was_closed()
|
||||
.finalize();
|
||||
|
||||
let edited_virtual_dom = assertion_registry
|
||||
.build()
|
||||
.with_name("VirtualDom::rebuild")
|
||||
.was_created()
|
||||
.was_entered_exactly(1)
|
||||
.was_closed()
|
||||
.finalize();
|
||||
|
||||
set_event_converter(Box::new(SerializedHtmlEventConverter));
|
||||
let mut dom = VirtualDom::new(app);
|
||||
|
||||
dom.rebuild(&mut dioxus_core::NoOpMutations);
|
||||
|
||||
new_virtual_dom.assert();
|
||||
edited_virtual_dom.assert();
|
||||
|
||||
for _ in 0..3 {
|
||||
dom.handle_event(
|
||||
"click",
|
||||
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
|
||||
ElementId(2),
|
||||
true,
|
||||
);
|
||||
dom.process_events();
|
||||
_ = dom.render_immediate_to_vec();
|
||||
}
|
||||
}
|
||||
|
||||
fn app() -> Element {
|
||||
let mut idx = use_signal(|| 0);
|
||||
let onhover = |_| println!("go!");
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
button {
|
||||
onclick: move |_| {
|
||||
idx += 1;
|
||||
println!("Clicked");
|
||||
},
|
||||
"+"
|
||||
}
|
||||
button { onclick: move |_| idx -= 1, "-" }
|
||||
ul {
|
||||
{(0..idx()).map(|i| rsx! {
|
||||
ChildExample { i: i, onhover: onhover }
|
||||
})}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ChildExample(i: i32, onhover: EventHandler<MouseEvent>) -> Element {
|
||||
rsx! { li { onmouseover: move |e| onhover.call(e), "{i}" } }
|
||||
}
|
||||
@@ -14,8 +14,9 @@ pub(crate) fn check_app_exits(app: fn() -> Element) {
|
||||
let should_panic = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
|
||||
let should_panic_clone = should_panic.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(std::time::Duration::from_secs(30));
|
||||
std::thread::sleep(std::time::Duration::from_secs(60));
|
||||
if should_panic_clone.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
eprintln!("App did not exit in time");
|
||||
std::process::exit(exitcode::SOFTWARE);
|
||||
}
|
||||
});
|
||||
@@ -31,7 +32,7 @@ pub(crate) fn check_app_exits(app: fn() -> Element) {
|
||||
fn mock_event(id: &'static str, value: &'static str) {
|
||||
use_hook(move || {
|
||||
spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(2000)).await;
|
||||
tokio::time::sleep(std::time::Duration::from_millis(5000)).await;
|
||||
|
||||
let js = format!(
|
||||
r#"
|
||||
|
||||
@@ -43,6 +43,7 @@ fn handle_edits_code() -> String {
|
||||
}"#;
|
||||
let polling_request = format!(
|
||||
r#"// Poll for requests
|
||||
window.interpreter = new JSChannel();
|
||||
window.interpreter.wait_for_request = (headless) => {{
|
||||
fetch(new Request("{EDITS_PATH}"))
|
||||
.then(response => {{
|
||||
@@ -50,11 +51,11 @@ fn handle_edits_code() -> String {
|
||||
.then(bytes => {{
|
||||
// In headless mode, the requestAnimationFrame callback is never called, so we need to run the bytes directly
|
||||
if (headless) {{
|
||||
run_from_bytes(bytes);
|
||||
window.interpreter.run_from_bytes(bytes);
|
||||
}}
|
||||
else {{
|
||||
requestAnimationFrame(() => {{
|
||||
run_from_bytes(bytes);
|
||||
window.interpreter.run_from_bytes(bytes);
|
||||
}});
|
||||
}}
|
||||
window.interpreter.wait_for_request(headless);
|
||||
@@ -74,7 +75,7 @@ fn handle_edits_code() -> String {
|
||||
interpreter.replace_range(import_start..import_end, "");
|
||||
}
|
||||
|
||||
format!("{interpreter}\nconst config = new InterpreterConfig(true);")
|
||||
format!("{interpreter}\nconst intercept_link_redirects = true;")
|
||||
}
|
||||
|
||||
static DEFAULT_INDEX: &str = include_str!("./index.html");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "dioxus-ext"
|
||||
version = "0.1.0"
|
||||
version = { workspace = true }
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
@@ -12,6 +12,5 @@ dioxus-autofmt = { workspace = true }
|
||||
rsx-rosetta = { workspace = true }
|
||||
html_parser = { workspace = true }
|
||||
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
@@ -2,14 +2,14 @@
|
||||
"name": "dioxus",
|
||||
"displayName": "Dioxus",
|
||||
"description": "Useful tools for working with Dioxus",
|
||||
"version": "0.0.2",
|
||||
"version": "0.4.0",
|
||||
"publisher": "DioxusLabs",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"icon": "static/icon.png",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/DioxusLabs/cli"
|
||||
"url": "https://github.com/DioxusLabs/dioxus"
|
||||
},
|
||||
"engines": {
|
||||
"vscode": "^1.68.1"
|
||||
|
||||
@@ -13,10 +13,10 @@ resolver = "2"
|
||||
[dependencies]
|
||||
# server functions
|
||||
server_fn = { version = "0.6.5", features = ["json", "url", "browser"], default-features = false }
|
||||
dioxus_server_macro = { workspace = true, version = "0.6.5", default-features = false }
|
||||
dioxus_server_macro = { workspace = true }
|
||||
|
||||
# axum
|
||||
axum = { workspace = true, features = ["ws", "macros"], default-features = false, optional = true }
|
||||
axum = { workspace = true, features = ["ws", "macros"], optional = true }
|
||||
tower-http = { workspace = true, optional = true, features = ["fs", "compression-gzip"] }
|
||||
|
||||
dioxus-lib = { workspace = true }
|
||||
@@ -44,7 +44,7 @@ anymap = { version = "0.12.1", optional = true }
|
||||
serde = "1.0.159"
|
||||
serde_json = { version = "1.0.95", optional = true }
|
||||
tokio-stream = { version = "0.1.12", features = ["sync"], optional = true }
|
||||
futures-util = { workspace = true, default-features = false }
|
||||
futures-util = { workspace = true }
|
||||
ciborium = "0.2.1"
|
||||
base64 = "0.21.0"
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "generational-box"
|
||||
authors = ["Evan Almloff"]
|
||||
version = "0.4.3"
|
||||
version = { workspace = true }
|
||||
edition = "2021"
|
||||
description = "A box backed by a generational runtime"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
@@ -14,6 +14,18 @@ pub fn try_use_context<T: 'static + Clone>() -> Option<T> {
|
||||
/// Consume some context in the tree, providing a sharable handle to the value
|
||||
///
|
||||
/// Does not regenerate the value if the value is changed at the parent.
|
||||
/// ```rust
|
||||
/// fn Parent() -> Element {
|
||||
/// use_context_provider(|| Theme::Dark);
|
||||
/// rsx! { Child {} }
|
||||
/// }
|
||||
/// #[component]
|
||||
/// fn Child() -> Element {
|
||||
/// //gets context provided by parent element with use_context_provider
|
||||
/// let user_theme = use_context::<Theme>();
|
||||
/// rsx! { "user using dark mode: {user_theme == Theme::Dark}" }
|
||||
/// }
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn use_context<T: 'static + Clone>() -> T {
|
||||
use_hook(|| consume_context::<T>())
|
||||
@@ -22,6 +34,24 @@ pub fn use_context<T: 'static + Clone>() -> T {
|
||||
/// Provide some context via the tree and return a reference to it
|
||||
///
|
||||
/// Once the context has been provided, it is immutable. Mutations should be done via interior mutability.
|
||||
/// Context can be read by any child components of the context provider, and is a solution to prop
|
||||
/// drilling, using a context provider with a Signal inside is a good way to provide global/shared
|
||||
/// state in your app:
|
||||
/// ```rust
|
||||
///fn app() -> Element {
|
||||
/// use_context_provider(|| Signal::new(0));
|
||||
/// rsx! { Child {} }
|
||||
///}
|
||||
/// // This component does read from the signal, so when the signal changes it will rerun
|
||||
///#[component]
|
||||
///fn Child() -> Element {
|
||||
/// let signal: Signal<i32> = use_context();
|
||||
/// rsx! {
|
||||
/// button { onclick: move |_| signal += 1, "increment context" }
|
||||
/// p {"{signal}"}
|
||||
/// }
|
||||
///}
|
||||
/// ```
|
||||
pub fn use_context_provider<T: 'static + Clone>(f: impl FnOnce() -> T) -> T {
|
||||
use_hook(|| {
|
||||
let val = f();
|
||||
|
||||
@@ -93,7 +93,8 @@ where
|
||||
}
|
||||
|
||||
/// Get a handle to a coroutine higher in the tree
|
||||
///
|
||||
/// Analagous to use_context_provider and use_context,
|
||||
/// but used for coroutines specifically
|
||||
/// See the docs for [`use_coroutine`] for more details.
|
||||
#[must_use]
|
||||
pub fn use_coroutine_handle<M: 'static>() -> Coroutine<M> {
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
use dioxus_core::prelude::*;
|
||||
use dioxus_signals::ReactiveContext;
|
||||
|
||||
/// Create a new effect. The effect will be run immediately and whenever any signal it reads changes.
|
||||
/// The signal will be owned by the current component and will be dropped when the component is dropped.
|
||||
///
|
||||
/// `use_effect` will subscribe to any changes in the signal values it captures
|
||||
/// effects will always run after first mount and then whenever the signal values change
|
||||
/// If the use_effect call was skipped due to an early return, the effect will no longer activate.
|
||||
/// ```rust
|
||||
/// fn app() -> Element {
|
||||
/// let mut count = use_signal(|| 0);
|
||||
/// //the effect runs again each time count changes
|
||||
/// use_effect(move || println!("Count changed to {count}"));
|
||||
///
|
||||
/// rsx! {
|
||||
/// h1 { "High-Five counter: {count}" }
|
||||
/// button { onclick: move |_| count += 1, "Up high!" }
|
||||
/// button { onclick: move |_| count -= 1, "Down low!" }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[track_caller]
|
||||
pub fn use_effect(mut callback: impl FnMut() + 'static) {
|
||||
// let mut run_effect = use_hook(|| CopyValue::new(true));
|
||||
|
||||
@@ -8,10 +8,34 @@ use dioxus_signals::*;
|
||||
use dioxus_signals::{Readable, Writable};
|
||||
use std::future::Future;
|
||||
|
||||
/// A hook that allows you to spawn a future
|
||||
///
|
||||
/// A hook that allows you to spawn a future.
|
||||
/// This future will **not** run on the server
|
||||
/// The future is spawned on the next call to `flush_sync` which means that it will not run on the server.
|
||||
/// To run a future on the server, you should use `spawn` directly.
|
||||
/// `use_future` **won't return a value**.
|
||||
/// If you want to return a value from a future, use `use_resource` instead.
|
||||
/// ```rust
|
||||
/// fn app() -> Element {
|
||||
/// let mut count = use_signal(|| 0);
|
||||
/// let mut running = use_signal(|| true);
|
||||
/// // `use_future` will spawn an infinitely running future that can be started and stopped
|
||||
/// use_future(move || async move {
|
||||
/// loop {
|
||||
/// if running() {
|
||||
/// count += 1;
|
||||
/// }
|
||||
/// tokio::time::sleep(Duration::from_millis(400)).await;
|
||||
/// }
|
||||
/// });
|
||||
/// rsx! {
|
||||
/// div {
|
||||
/// h1 { "Current count: {count}" }
|
||||
/// button { onclick: move |_| running.toggle(), "Start/Stop the count"}
|
||||
/// button { onclick: move |_| count.set(0), "Reset the count" }
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub fn use_future<F>(mut future: impl FnMut() -> F + 'static) -> UseFuture
|
||||
where
|
||||
F: Future + 'static,
|
||||
|
||||
@@ -10,8 +10,32 @@ use futures_util::{future, pin_mut, FutureExt};
|
||||
use std::future::Future;
|
||||
|
||||
/// A memo that resolve to a value asynchronously.
|
||||
/// Unlike `use_future`, `use_resource` runs on the **server**
|
||||
/// See [`Resource`] for more details.
|
||||
/// ```rust
|
||||
///fn app() -> Element {
|
||||
/// let country = use_signal(|| WeatherLocation {
|
||||
/// city: "Berlin".to_string(),
|
||||
/// country: "Germany".to_string(),
|
||||
/// coordinates: (52.5244, 13.4105)
|
||||
/// });
|
||||
///
|
||||
/// This runs on the server
|
||||
/// let current_weather = //run a future inside the use_resource hook
|
||||
/// use_resource(move || async move { get_weather(&country.read().clone()).await });
|
||||
///
|
||||
/// rsx! {
|
||||
/// //the value of the future can be polled to
|
||||
/// //conditionally render elements based off if the future
|
||||
/// //finished (Some(Ok(_)), errored Some(Err(_)),
|
||||
/// //or is still finishing (None)
|
||||
/// match current_weather.value() {
|
||||
/// Some(Ok(weather)) => WeatherElement { weather },
|
||||
/// Some(Err(e)) => p { "Loading weather failed, {e}" }
|
||||
/// None => p { "Loading..." }
|
||||
/// }
|
||||
/// }
|
||||
///}
|
||||
/// ```
|
||||
#[must_use = "Consider using `cx.spawn` to run a future without reading its value"]
|
||||
pub fn use_resource<T, F>(future: impl Fn() -> F + 'static) -> Resource<T>
|
||||
where
|
||||
|
||||
@@ -25,4 +25,4 @@ name = "tests"
|
||||
path = "tests/progress.rs"
|
||||
|
||||
[dev-dependencies]
|
||||
trybuild = { version = "1.0.82", features = ["diff"] }
|
||||
trybuild = { version = "1.0.82", features = ["diff"] }
|
||||
@@ -1613,10 +1613,10 @@ builder_constructors! {
|
||||
/// element.
|
||||
hatchpath "http://www.w3.org/2000/svg" {};
|
||||
|
||||
// /// Build a
|
||||
// /// [`<image>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image)
|
||||
// /// element.
|
||||
// image "http://www.w3.org/2000/svg" {};
|
||||
/// Build a
|
||||
/// [`<image>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image)
|
||||
/// element.
|
||||
image "http://www.w3.org/2000/svg" {};
|
||||
|
||||
/// Build a
|
||||
/// [`<line>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/line)
|
||||
|
||||
@@ -2285,8 +2285,8 @@ trait_methods! {
|
||||
/// <https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform-origin>
|
||||
transform_origin: "transform-origin";
|
||||
|
||||
/// <https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/_type>
|
||||
r#type: "_type";
|
||||
/// <https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/type>
|
||||
r#type: "type";
|
||||
|
||||
/// <https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/u1>
|
||||
u1: "u1";
|
||||
|
||||
@@ -17,7 +17,7 @@ web-sys = { version = "0.3.56", optional = true, features = [
|
||||
"Element",
|
||||
"Node",
|
||||
] }
|
||||
sledgehammer_bindgen = { version = "0.3.1", default-features = false, optional = true }
|
||||
sledgehammer_bindgen = { version = "0.4.0", default-features = false, optional = true }
|
||||
sledgehammer_utils = { version = "0.2", optional = true }
|
||||
serde = { version = "1.0", features = ["derive"], optional = true }
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export function setAttributeInner(node, field, value, ns) {
|
||||
this.setAttributeInner = function (node, field, value, ns) {
|
||||
const name = field;
|
||||
if (ns === "style") {
|
||||
// ????? why do we need to do this
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
export function setAttributeInner(node, field, value, ns) {
|
||||
const name = field;
|
||||
if (ns === "style") {
|
||||
// ????? why do we need to do this
|
||||
if (node.style === undefined) {
|
||||
node.style = {};
|
||||
}
|
||||
node.style[name] = value;
|
||||
} else if (!!ns) {
|
||||
node.setAttributeNS(ns, name, value);
|
||||
} else {
|
||||
switch (name) {
|
||||
case "value":
|
||||
if (value !== node.value) {
|
||||
node.value = value;
|
||||
}
|
||||
break;
|
||||
case "initial_value":
|
||||
node.defaultValue = value;
|
||||
break;
|
||||
case "checked":
|
||||
node.checked = truthy(value);
|
||||
break;
|
||||
case "initial_checked":
|
||||
node.defaultChecked = truthy(value);
|
||||
break;
|
||||
case "selected":
|
||||
node.selected = truthy(value);
|
||||
break;
|
||||
case "initial_selected":
|
||||
node.defaultSelected = truthy(value);
|
||||
break;
|
||||
case "dangerous_inner_html":
|
||||
node.innerHTML = value;
|
||||
break;
|
||||
default:
|
||||
// https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js#L352-L364
|
||||
if (!truthy(value) && bool_attrs.hasOwnProperty(name)) {
|
||||
node.removeAttribute(name);
|
||||
} else {
|
||||
node.setAttribute(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const bool_attrs = {
|
||||
allowfullscreen: true,
|
||||
allowpaymentrequest: true,
|
||||
async: true,
|
||||
autofocus: true,
|
||||
autoplay: true,
|
||||
checked: true,
|
||||
controls: true,
|
||||
default: true,
|
||||
defer: true,
|
||||
disabled: true,
|
||||
formnovalidate: true,
|
||||
hidden: true,
|
||||
ismap: true,
|
||||
itemscope: true,
|
||||
loop: true,
|
||||
multiple: true,
|
||||
muted: true,
|
||||
nomodule: true,
|
||||
novalidate: true,
|
||||
open: true,
|
||||
playsinline: true,
|
||||
readonly: true,
|
||||
required: true,
|
||||
reversed: true,
|
||||
selected: true,
|
||||
truespeed: true,
|
||||
webkitdirectory: true,
|
||||
};
|
||||
|
||||
function truthy(val) {
|
||||
return val === "true" || val === true;
|
||||
}
|
||||
@@ -1,12 +1,6 @@
|
||||
class InterpreterConfig {
|
||||
constructor(intercept_link_redirects) {
|
||||
this.intercept_link_redirects = intercept_link_redirects;
|
||||
}
|
||||
}
|
||||
|
||||
// this handler is only provided on the desktop and liveview implementations since this
|
||||
// method is not used by the web implementation
|
||||
async function handler(event, name, bubbles, config) {
|
||||
this.handler = async function (event, name, bubbles) {
|
||||
let target = event.target;
|
||||
if (target != null) {
|
||||
let preventDefaultRequests = null;
|
||||
@@ -17,7 +11,7 @@ async function handler(event, name, bubbles, config) {
|
||||
|
||||
if (event.type === "click") {
|
||||
// todo call prevent default if it's the right type of event
|
||||
if (config.intercept_link_redirects) {
|
||||
if (intercept_link_redirects) {
|
||||
let a_element = target.closest("a");
|
||||
if (a_element != null) {
|
||||
event.preventDefault();
|
||||
@@ -35,7 +29,7 @@ async function handler(event, name, bubbles, config) {
|
||||
const href = a_element.getAttribute("href");
|
||||
if (href !== "" && href !== null && href !== undefined) {
|
||||
window.ipc.postMessage(
|
||||
window.interpreter.serializeIpcMessage("browser_open", { href })
|
||||
this.serializeIpcMessage("browser_open", { href })
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -142,7 +136,7 @@ async function handler(event, name, bubbles, config) {
|
||||
return;
|
||||
}
|
||||
window.ipc.postMessage(
|
||||
window.interpreter.serializeIpcMessage("user_event", {
|
||||
this.serializeIpcMessage("user_event", {
|
||||
name: name,
|
||||
element: parseInt(realId),
|
||||
data: contents,
|
||||
@@ -223,43 +217,40 @@ class ListenerMap {
|
||||
delete this.local[id];
|
||||
}
|
||||
}
|
||||
function LoadChild(array) {
|
||||
this.LoadChild = function (array) {
|
||||
// iterate through each number and get that child
|
||||
node = stack[stack.length - 1];
|
||||
let node = this.stack[this.stack.length - 1];
|
||||
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
end = array[i];
|
||||
for (node = node.firstChild; end > 0; end--) {
|
||||
this.end = array[i];
|
||||
for (node = node.firstChild; this.end > 0; this.end--) {
|
||||
node = node.nextSibling;
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
const listeners = new ListenerMap();
|
||||
let nodes = [];
|
||||
let stack = [];
|
||||
let root;
|
||||
const templates = {};
|
||||
let node, els, end, k;
|
||||
this.listeners = new ListenerMap();
|
||||
this.nodes = [];
|
||||
this.stack = [];
|
||||
this.templates = {};
|
||||
this.end = null;
|
||||
|
||||
function AppendChildren(id, many) {
|
||||
root = nodes[id];
|
||||
els = stack.splice(stack.length - many);
|
||||
for (k = 0; k < many; k++) {
|
||||
this.AppendChildren = function (id, many) {
|
||||
let root = this.nodes[id];
|
||||
let els = this.stack.splice(this.stack.length - many);
|
||||
for (let k = 0; k < many; k++) {
|
||||
root.appendChild(els[k]);
|
||||
}
|
||||
}
|
||||
|
||||
window.interpreter = {}
|
||||
|
||||
window.interpreter.initialize = function (root) {
|
||||
nodes = [root];
|
||||
stack = [root];
|
||||
listeners.root = root;
|
||||
this.initialize = function (root) {
|
||||
this.nodes = [root];
|
||||
this.stack = [root];
|
||||
this.listeners.root = root;
|
||||
}
|
||||
|
||||
window.interpreter.getClientRect = function (id) {
|
||||
const node = nodes[id];
|
||||
this.getClientRect = function (id) {
|
||||
const node = this.nodes[id];
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
@@ -271,8 +262,8 @@ window.interpreter.getClientRect = function (id) {
|
||||
};
|
||||
}
|
||||
|
||||
window.interpreter.scrollTo = function (id, behavior) {
|
||||
const node = nodes[id];
|
||||
this.scrollTo = function (id, behavior) {
|
||||
const node = this.nodes[id];
|
||||
if (!node) {
|
||||
return false;
|
||||
}
|
||||
@@ -283,8 +274,8 @@ window.interpreter.scrollTo = function (id, behavior) {
|
||||
}
|
||||
|
||||
/// Set the focus on the element
|
||||
window.interpreter.setFocus = function (id, focus) {
|
||||
const node = nodes[id];
|
||||
this.setFocus = function (id, focus) {
|
||||
const node = this.nodes[id];
|
||||
if (!node) {
|
||||
return false;
|
||||
}
|
||||
@@ -579,7 +570,7 @@ async function serialize_event(event) {
|
||||
}
|
||||
}
|
||||
}
|
||||
window.interpreter.serializeIpcMessage = function (method, params = {}) {
|
||||
this.serializeIpcMessage = function (method, params = {}) {
|
||||
return JSON.stringify({ method, params });
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ pub use write_native_mutations::*;
|
||||
#[cfg(all(feature = "minimal_bindings", feature = "webonly"))]
|
||||
pub mod minimal_bindings {
|
||||
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
|
||||
#[wasm_bindgen(module = "/src/common.js")]
|
||||
#[wasm_bindgen(module = "/src/common_exported.js")]
|
||||
extern "C" {
|
||||
pub fn setAttributeInner(node: JsValue, name: &str, value: JsValue, ns: Option<&str>);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ mod js {
|
||||
this.global = {};
|
||||
// non bubbling events listen at the element the listener was created at
|
||||
this.local = {};
|
||||
this.root = null;
|
||||
this.root = root;
|
||||
this.handler = null;
|
||||
}
|
||||
|
||||
@@ -65,35 +65,33 @@ mod js {
|
||||
delete this.local[id];
|
||||
}
|
||||
}
|
||||
function LoadChild(ptr, len) {
|
||||
this.LoadChild = function(ptr, len) {
|
||||
// iterate through each number and get that child
|
||||
node = stack[stack.length - 1];
|
||||
ptr_end = ptr + len;
|
||||
let node = this.stack[this.stack.length - 1];
|
||||
let ptr_end = ptr + len;
|
||||
for (; ptr < ptr_end; ptr++) {
|
||||
end = m.getUint8(ptr);
|
||||
let end = this.m.getUint8(ptr);
|
||||
for (node = node.firstChild; end > 0; end--) {
|
||||
node = node.nextSibling;
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
const listeners = new ListenerMap();
|
||||
let nodes = [];
|
||||
let stack = [];
|
||||
let root;
|
||||
const templates = {};
|
||||
let node, els, end, ptr_end, k;
|
||||
export function save_template(nodes, tmpl_id) {
|
||||
templates[tmpl_id] = nodes;
|
||||
this.listeners = new ListenerMap();
|
||||
this.nodes = [];
|
||||
this.stack = [];
|
||||
this.templates = {};
|
||||
this.save_template = function(nodes, tmpl_id) {
|
||||
this.templates[tmpl_id] = nodes;
|
||||
}
|
||||
export function hydrate(ids) {
|
||||
this.hydrate = function (ids) {
|
||||
const hydrateNodes = document.querySelectorAll('[data-node-hydration]');
|
||||
for (let i = 0; i < hydrateNodes.length; i++) {
|
||||
const hydrateNode = hydrateNodes[i];
|
||||
const hydration = hydrateNode.getAttribute('data-node-hydration');
|
||||
const split = hydration.split(',');
|
||||
const id = ids[parseInt(split[0])];
|
||||
nodes[id] = hydrateNode;
|
||||
this.nodes[id] = hydrateNode;
|
||||
if (split.length > 1) {
|
||||
hydrateNode.listening = split.length - 1;
|
||||
hydrateNode.setAttribute('data-dioxus-id', id);
|
||||
@@ -102,7 +100,7 @@ mod js {
|
||||
const split2 = listener.split(':');
|
||||
const event_name = split2[0];
|
||||
const bubbles = split2[1] === '1';
|
||||
listeners.create(event_name, hydrateNode, bubbles);
|
||||
this.listeners.create(event_name, hydrateNode, bubbles);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,91 +113,77 @@ mod js {
|
||||
const id = currentNode.textContent;
|
||||
const split = id.split('node-id');
|
||||
if (split.length > 1) {
|
||||
nodes[ids[parseInt(split[1])]] = currentNode.nextSibling;
|
||||
this.nodes[ids[parseInt(split[1])]] = currentNode.nextSibling;
|
||||
}
|
||||
currentNode = treeWalker.nextNode();
|
||||
}
|
||||
}
|
||||
export function get_node(id) {
|
||||
return nodes[id];
|
||||
this.get_node = function(id) {
|
||||
return this.nodes[id];
|
||||
}
|
||||
export function initialize(root, handler) {
|
||||
listeners.handler = handler;
|
||||
nodes = [root];
|
||||
stack = [root];
|
||||
listeners.root = root;
|
||||
this.initialize = function(root, handler) {
|
||||
this.listeners.handler = handler;
|
||||
this.nodes = [root];
|
||||
this.stack = [root];
|
||||
this.listeners.root = root;
|
||||
}
|
||||
function AppendChildren(id, many){
|
||||
root = nodes[id];
|
||||
els = stack.splice(stack.length-many);
|
||||
for (k = 0; k < many; k++) {
|
||||
this.AppendChildren = function (id, many){
|
||||
let root = this.nodes[id];
|
||||
let els = this.stack.splice(this.stack.length-many);
|
||||
for (let k = 0; k < many; k++) {
|
||||
root.appendChild(els[k]);
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
extern "C" {
|
||||
#[wasm_bindgen]
|
||||
pub fn save_template(nodes: Vec<Node>, tmpl_id: u16);
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn hydrate(ids: Vec<u32>);
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn get_node(id: u32) -> Node;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn initialize(root: Node, handler: &Function);
|
||||
}
|
||||
|
||||
fn mount_to_root() {
|
||||
"{AppendChildren(root, stack.length-1);}"
|
||||
"{this.AppendChildren(this.listeners.root, this.stack.length-1);}"
|
||||
}
|
||||
fn push_root(root: u32) {
|
||||
"{stack.push(nodes[$root$]);}"
|
||||
"{this.stack.push(this.nodes[$root$]);}"
|
||||
}
|
||||
fn append_children(id: u32, many: u16) {
|
||||
"{AppendChildren($id$, $many$);}"
|
||||
"{this.AppendChildren($id$, $many$);}"
|
||||
}
|
||||
fn pop_root() {
|
||||
"{stack.pop();}"
|
||||
"{this.stack.pop();}"
|
||||
}
|
||||
fn replace_with(id: u32, n: u16) {
|
||||
"{root = nodes[$id$]; els = stack.splice(stack.length-$n$); if (root.listening) { listeners.removeAllNonBubbling(root); } root.replaceWith(...els);}"
|
||||
"{const root = this.nodes[$id$]; let els = this.stack.splice(this.stack.length-$n$); if (root.listening) { this.listeners.removeAllNonBubbling(root); } root.replaceWith(...els);}"
|
||||
}
|
||||
fn insert_after(id: u32, n: u16) {
|
||||
"{nodes[$id$].after(...stack.splice(stack.length-$n$));}"
|
||||
"{this.nodes[$id$].after(...this.stack.splice(this.stack.length-$n$));}"
|
||||
}
|
||||
fn insert_before(id: u32, n: u16) {
|
||||
"{nodes[$id$].before(...stack.splice(stack.length-$n$));}"
|
||||
"{this.nodes[$id$].before(...this.stack.splice(this.stack.length-$n$));}"
|
||||
}
|
||||
fn remove(id: u32) {
|
||||
"{node = nodes[$id$]; if (node !== undefined) { if (node.listening) { listeners.removeAllNonBubbling(node); } node.remove(); }}"
|
||||
"{let node = this.nodes[$id$]; if (node !== undefined) { if (node.listening) { this.listeners.removeAllNonBubbling(node); } node.remove(); }}"
|
||||
}
|
||||
fn create_raw_text(text: &str) {
|
||||
"{stack.push(document.createTextNode($text$));}"
|
||||
"{this.stack.push(document.createTextNode($text$));}"
|
||||
}
|
||||
fn create_text_node(text: &str, id: u32) {
|
||||
"{node = document.createTextNode($text$); nodes[$id$] = node; stack.push(node);}"
|
||||
"{let node = document.createTextNode($text$); this.nodes[$id$] = node; this.stack.push(node);}"
|
||||
}
|
||||
fn create_placeholder(id: u32) {
|
||||
"{node = document.createElement('pre'); node.hidden = true; stack.push(node); nodes[$id$] = node;}"
|
||||
"{let node = document.createElement('pre'); node.hidden = true; this.stack.push(node); this.nodes[$id$] = node;}"
|
||||
}
|
||||
fn new_event_listener(event_name: &str<u8, evt>, id: u32, bubbles: u8) {
|
||||
r#"node = nodes[id]; if(node.listening){node.listening += 1;}else{node.listening = 1;} node.setAttribute('data-dioxus-id', `\${id}`); listeners.create($event_name$, node, $bubbles$);"#
|
||||
r#"let node = this.nodes[id]; if(node.listening){node.listening += 1;}else{node.listening = 1;} node.setAttribute('data-dioxus-id', `\${id}`); this.listeners.create($event_name$, node, $bubbles$);"#
|
||||
}
|
||||
fn remove_event_listener(event_name: &str<u8, evt>, id: u32, bubbles: u8) {
|
||||
"{node = nodes[$id$]; node.listening -= 1; node.removeAttribute('data-dioxus-id'); listeners.remove(node, $event_name$, $bubbles$);}"
|
||||
"{let node = this.nodes[$id$]; node.listening -= 1; node.removeAttribute('data-dioxus-id'); this.listeners.remove(node, $event_name$, $bubbles$);}"
|
||||
}
|
||||
fn set_text(id: u32, text: &str) {
|
||||
"{nodes[$id$].textContent = $text$;}"
|
||||
"{this.nodes[$id$].textContent = $text$;}"
|
||||
}
|
||||
fn set_attribute(id: u32, field: &str<u8, attr>, value: &str, ns: &str<u8, ns_cache>) {
|
||||
"{node = nodes[$id$]; setAttributeInner(node, $field$, $value$, $ns$);}"
|
||||
"{let node = this.nodes[$id$]; this.setAttributeInner(node, $field$, $value$, $ns$);}"
|
||||
}
|
||||
fn remove_attribute(id: u32, field: &str<u8, attr>, ns: &str<u8, ns_cache>) {
|
||||
r#"{
|
||||
node = nodes[$id$];
|
||||
let node = this.nodes[$id$];
|
||||
if (!ns) {
|
||||
switch (field) {
|
||||
case "value":
|
||||
@@ -226,29 +210,54 @@ mod js {
|
||||
}"#
|
||||
}
|
||||
fn assign_id(ptr: u32, len: u8, id: u32) {
|
||||
"{nodes[$id$] = LoadChild($ptr$, $len$);}"
|
||||
"{this.nodes[$id$] = this.LoadChild($ptr$, $len$);}"
|
||||
}
|
||||
fn hydrate_text(ptr: u32, len: u8, value: &str, id: u32) {
|
||||
r#"{
|
||||
node = LoadChild($ptr$, $len$);
|
||||
if (node.nodeType == Node.TEXT_NODE) {
|
||||
let node = this.LoadChild($ptr$, $len$);
|
||||
if (node.nodeType == node.TEXT_NODE) {
|
||||
node.textContent = value;
|
||||
} else {
|
||||
let text = document.createTextNode(value);
|
||||
node.replaceWith(text);
|
||||
node = text;
|
||||
}
|
||||
nodes[$id$] = node;
|
||||
this.nodes[$id$] = node;
|
||||
}"#
|
||||
}
|
||||
fn replace_placeholder(ptr: u32, len: u8, n: u16) {
|
||||
"{els = stack.splice(stack.length - $n$); node = LoadChild($ptr$, $len$); node.replaceWith(...els);}"
|
||||
"{els = this.stack.splice(this.stack.length - $n$); let node = this.LoadChild($ptr$, $len$); node.replaceWith(...els);}"
|
||||
}
|
||||
fn load_template(tmpl_id: u16, index: u16, id: u32) {
|
||||
"{node = templates[$tmpl_id$][$index$].cloneNode(true); nodes[$id$] = node; stack.push(node);}"
|
||||
"{let node = this.templates[$tmpl_id$][$index$].cloneNode(true); this.nodes[$id$] = node; this.stack.push(node);}"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "webonly")]
|
||||
#[wasm_bindgen::prelude::wasm_bindgen(inline_js = r#"
|
||||
export function save_template(channel, nodes, tmpl_id) {
|
||||
channel.save_template(nodes, tmpl_id);
|
||||
}
|
||||
export function hydrate(channel, ids) {
|
||||
channel.hydrate(ids);
|
||||
}
|
||||
export function get_node(channel, id) {
|
||||
return channel.get_node(id);
|
||||
}
|
||||
export function initialize(channel, root, handler) {
|
||||
channel.initialize(root, handler);
|
||||
}
|
||||
"#)]
|
||||
extern "C" {
|
||||
pub fn save_template(channel: &JSChannel, nodes: Vec<Node>, tmpl_id: u16);
|
||||
|
||||
pub fn hydrate(channel: &JSChannel, ids: Vec<u32>);
|
||||
|
||||
pub fn get_node(channel: &JSChannel, id: u32) -> Node;
|
||||
|
||||
pub fn initialize(channel: &JSChannel, root: Node, handler: &Function);
|
||||
}
|
||||
|
||||
#[cfg(feature = "binary-protocol")]
|
||||
pub mod binary_protocol {
|
||||
use sledgehammer_bindgen::bindgen;
|
||||
@@ -259,61 +268,58 @@ pub mod binary_protocol {
|
||||
const JS_FILE: &str = "./src/interpreter.js";
|
||||
const JS_FILE: &str = "./src/common.js";
|
||||
|
||||
fn mount_to_root() {
|
||||
"{AppendChildren(root, stack.length-1);}"
|
||||
}
|
||||
fn push_root(root: u32) {
|
||||
"{stack.push(nodes[$root$]);}"
|
||||
"{this.stack.push(this.nodes[$root$]);}"
|
||||
}
|
||||
fn append_children(id: u32, many: u16) {
|
||||
"{AppendChildren($id$, $many$);}"
|
||||
"{this.AppendChildren($id$, $many$);}"
|
||||
}
|
||||
fn append_children_to_top(many: u16) {
|
||||
"{
|
||||
root = stack[stack.length-many-1];
|
||||
els = stack.splice(stack.length-many);
|
||||
for (k = 0; k < many; k++) {
|
||||
let root = this.stack[this.stack.length-many-1];
|
||||
let els = this.stack.splice(this.stack.length-many);
|
||||
for (let k = 0; k < many; k++) {
|
||||
root.appendChild(els[k]);
|
||||
}
|
||||
}"
|
||||
}
|
||||
fn pop_root() {
|
||||
"{stack.pop();}"
|
||||
"{this.stack.pop();}"
|
||||
}
|
||||
fn replace_with(id: u32, n: u16) {
|
||||
"{root = nodes[$id$]; els = stack.splice(stack.length-$n$); if (root.listening) { listeners.removeAllNonBubbling(root); } root.replaceWith(...els);}"
|
||||
"{let root = this.nodes[$id$]; let els = this.stack.splice(this.stack.length-$n$); if (root.listening) { this.listeners.removeAllNonBubbling(root); } root.replaceWith(...els);}"
|
||||
}
|
||||
fn insert_after(id: u32, n: u16) {
|
||||
"{nodes[$id$].after(...stack.splice(stack.length-$n$));}"
|
||||
"{this.nodes[$id$].after(...this.stack.splice(this.stack.length-$n$));}"
|
||||
}
|
||||
fn insert_before(id: u32, n: u16) {
|
||||
"{nodes[$id$].before(...stack.splice(stack.length-$n$));}"
|
||||
"{this.nodes[$id$].before(...this.stack.splice(this.stack.length-$n$));}"
|
||||
}
|
||||
fn remove(id: u32) {
|
||||
"{node = nodes[$id$]; if (node !== undefined) { if (node.listening) { listeners.removeAllNonBubbling(node); } node.remove(); }}"
|
||||
"{let node = this.nodes[$id$]; if (node !== undefined) { if (node.listening) { this.listeners.removeAllNonBubbling(node); } node.remove(); }}"
|
||||
}
|
||||
fn create_raw_text(text: &str) {
|
||||
"{stack.push(document.createTextNode($text$));}"
|
||||
"{this.stack.push(document.createTextNode($text$));}"
|
||||
}
|
||||
fn create_text_node(text: &str, id: u32) {
|
||||
"{node = document.createTextNode($text$); nodes[$id$] = node; stack.push(node);}"
|
||||
"{let node = document.createTextNode($text$); this.nodes[$id$] = node; this.stack.push(node);}"
|
||||
}
|
||||
fn create_element(element: &'static str<u8, el>) {
|
||||
"{stack.push(document.createElement($element$))}"
|
||||
"{this.stack.push(document.createElement($element$))}"
|
||||
}
|
||||
fn create_element_ns(element: &'static str<u8, el>, ns: &'static str<u8, namespace>) {
|
||||
"{stack.push(document.createElementNS($ns$, $element$))}"
|
||||
"{this.stack.push(document.createElementNS($ns$, $element$))}"
|
||||
}
|
||||
fn create_placeholder(id: u32) {
|
||||
"{node = document.createElement('pre'); node.hidden = true; stack.push(node); nodes[$id$] = node;}"
|
||||
"{let node = document.createElement('pre'); node.hidden = true; this.stack.push(node); this.nodes[$id$] = node;}"
|
||||
}
|
||||
fn add_placeholder() {
|
||||
"{node = document.createElement('pre'); node.hidden = true; stack.push(node);}"
|
||||
"{let node = document.createElement('pre'); node.hidden = true; this.stack.push(node);}"
|
||||
}
|
||||
fn new_event_listener(event: &str<u8, evt>, id: u32, bubbles: u8) {
|
||||
r#"
|
||||
bubbles = bubbles == 1;
|
||||
node = nodes[id];
|
||||
let node = this.nodes[id];
|
||||
if(node.listening){
|
||||
node.listening += 1;
|
||||
} else {
|
||||
@@ -325,7 +331,7 @@ pub mod binary_protocol {
|
||||
// if this is a mounted listener, we send the event immediately
|
||||
if (event_name === "mounted") {
|
||||
window.ipc.postMessage(
|
||||
window.interpreter.serializeIpcMessage("user_event", {
|
||||
this.serializeIpcMessage("user_event", {
|
||||
name: event_name,
|
||||
element: id,
|
||||
data: null,
|
||||
@@ -333,26 +339,26 @@ pub mod binary_protocol {
|
||||
})
|
||||
);
|
||||
} else {
|
||||
listeners.create(event_name, node, bubbles, (event) => {
|
||||
handler(event, event_name, bubbles, config);
|
||||
this.listeners.create(event_name, node, bubbles, (event) => {
|
||||
this.handler(event, event_name, bubbles);
|
||||
});
|
||||
}"#
|
||||
}
|
||||
fn remove_event_listener(event_name: &str<u8, evt>, id: u32, bubbles: u8) {
|
||||
"{node = nodes[$id$]; node.listening -= 1; node.removeAttribute('data-dioxus-id'); listeners.remove(node, $event_name$, $bubbles$);}"
|
||||
"{let node = this.nodes[$id$]; node.listening -= 1; node.removeAttribute('data-dioxus-id'); this.listeners.remove(node, $event_name$, $bubbles$);}"
|
||||
}
|
||||
fn set_text(id: u32, text: &str) {
|
||||
"{nodes[$id$].textContent = $text$;}"
|
||||
"{this.nodes[$id$].textContent = $text$;}"
|
||||
}
|
||||
fn set_attribute(id: u32, field: &str<u8, attr>, value: &str, ns: &str<u8, ns_cache>) {
|
||||
"{node = nodes[$id$]; setAttributeInner(node, $field$, $value$, $ns$);}"
|
||||
"{let node = this.nodes[$id$]; this.setAttributeInner(node, $field$, $value$, $ns$);}"
|
||||
}
|
||||
fn set_top_attribute(field: &str<u8, attr>, value: &str, ns: &str<u8, ns_cache>) {
|
||||
"{setAttributeInner(stack[stack.length-1], $field$, $value$, $ns$);}"
|
||||
"{this.setAttributeInner(this.stack[this.stack.length-1], $field$, $value$, $ns$);}"
|
||||
}
|
||||
fn remove_attribute(id: u32, field: &str<u8, attr>, ns: &str<u8, ns_cache>) {
|
||||
r#"{
|
||||
node = nodes[$id$];
|
||||
let node = this.nodes[$id$];
|
||||
if (!ns) {
|
||||
switch (field) {
|
||||
case "value":
|
||||
@@ -379,29 +385,29 @@ pub mod binary_protocol {
|
||||
}"#
|
||||
}
|
||||
fn assign_id(array: &[u8], id: u32) {
|
||||
"{nodes[$id$] = LoadChild($array$);}"
|
||||
"{this.nodes[$id$] = this.LoadChild($array$);}"
|
||||
}
|
||||
fn hydrate_text(array: &[u8], value: &str, id: u32) {
|
||||
r#"{
|
||||
node = LoadChild($array$);
|
||||
if (node.nodeType == Node.TEXT_NODE) {
|
||||
let node = this.LoadChild($array$);
|
||||
if (node.nodeType == node.TEXT_NODE) {
|
||||
node.textContent = value;
|
||||
} else {
|
||||
let text = document.createTextNode(value);
|
||||
node.replaceWith(text);
|
||||
node = text;
|
||||
}
|
||||
nodes[$id$] = node;
|
||||
this.nodes[$id$] = node;
|
||||
}"#
|
||||
}
|
||||
fn replace_placeholder(array: &[u8], n: u16) {
|
||||
"{els = stack.splice(stack.length - $n$); node = LoadChild($array$); node.replaceWith(...els);}"
|
||||
"{let els = this.stack.splice(this.stack.length - $n$); let node = this.LoadChild($array$); node.replaceWith(...els);}"
|
||||
}
|
||||
fn load_template(tmpl_id: u16, index: u16, id: u32) {
|
||||
"{node = templates[$tmpl_id$][$index$].cloneNode(true); nodes[$id$] = node; stack.push(node);}"
|
||||
"{let node = this.templates[$tmpl_id$][$index$].cloneNode(true); this.nodes[$id$] = node; this.stack.push(node);}"
|
||||
}
|
||||
fn add_templates(tmpl_id: u16, len: u16) {
|
||||
"{templates[$tmpl_id$] = stack.splice(stack.length-$len$);}"
|
||||
"{this.templates[$tmpl_id$] = this.stack.splice(this.stack.length-$len$);}"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
const config = new InterpreterConfig(false);
|
||||
const intercept_link_redirects = false;
|
||||
|
||||
function main() {
|
||||
let root = window.document.getElementById("main");
|
||||
@@ -9,6 +9,7 @@ function main() {
|
||||
|
||||
class IPC {
|
||||
constructor(root) {
|
||||
window.interpreter = new JSChannel();
|
||||
window.interpreter.initialize(root);
|
||||
const ws = new WebSocket(WS_ADDR);
|
||||
ws.binaryType = "arraybuffer";
|
||||
@@ -34,7 +35,7 @@ class IPC {
|
||||
// The first byte tells the shim if this is a binary of text frame
|
||||
if (binaryFrame) {
|
||||
// binary frame
|
||||
run_from_bytes(messageData);
|
||||
window.interpreter.run_from_bytes(messageData);
|
||||
}
|
||||
else {
|
||||
// text frame
|
||||
|
||||
@@ -559,6 +559,7 @@ impl RouteEnum {
|
||||
#(#type_defs)*
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum #match_error_name {
|
||||
#(#error_variants),*
|
||||
|
||||
@@ -309,6 +309,7 @@ pub(crate) fn create_error_type(
|
||||
|
||||
quote! {
|
||||
#[allow(non_camel_case_types)]
|
||||
#[allow(clippy::derive_partial_eq_without_eq)]
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum #error_name {
|
||||
ExtraSegments(String),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "dioxus-signals"
|
||||
authors = ["Jonathan Kelley"]
|
||||
version = "0.4.3"
|
||||
authors = ["Jonathan Kelley", "Evan Almloff"]
|
||||
version = { workspace = true }
|
||||
edition = "2021"
|
||||
description = "Signals for Dioxus"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
@@ -39,7 +39,9 @@ pub trait Readable {
|
||||
MappedSignal::new(try_read, peek)
|
||||
}
|
||||
|
||||
/// Get the current value of the state. If this is a signal, this will subscribe the current scope to the signal. If the value has been dropped, this will panic.
|
||||
/// Get the current value of the state. If this is a signal, this will subscribe the current scope to the signal.
|
||||
/// If the value has been dropped, this will panic. Calling this on a Signal is the same as
|
||||
/// using the signal() syntax to read and subscribe to its value
|
||||
#[track_caller]
|
||||
fn read(&self) -> ReadableRef<Self> {
|
||||
self.try_read().unwrap()
|
||||
|
||||
@@ -20,7 +20,7 @@ tracing = { workspace = true }
|
||||
http = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
chrono = { verison = "0.4.34", optional = true }
|
||||
chrono = { version = "0.4.34", optional = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
tokio = { version = "1.28", features = ["io-util"], optional = true }
|
||||
|
||||
@@ -110,6 +110,7 @@ impl WebsysDom {
|
||||
}));
|
||||
|
||||
dioxus_interpreter_js::initialize(
|
||||
interpreter.js_channel(),
|
||||
root.clone().unchecked_into(),
|
||||
handler.as_ref().unchecked_ref(),
|
||||
);
|
||||
|
||||
@@ -62,7 +62,7 @@ impl WebsysDom {
|
||||
// Now that we've flushed the edits and the dom nodes exist, we can send the mounted events.
|
||||
{
|
||||
for id in self.queued_mounted_events.drain(..) {
|
||||
let node = get_node(id.0 as u32);
|
||||
let node = get_node(self.interpreter.js_channel(), id.0 as u32);
|
||||
if let Some(element) = node.dyn_ref::<web_sys::Element>() {
|
||||
let _ = self.event_channel.unbounded_send(UiEvent {
|
||||
name: "mounted".to_string(),
|
||||
@@ -91,7 +91,7 @@ impl WriteMutations for WebsysDom {
|
||||
|
||||
self.templates
|
||||
.insert(template.name.to_owned(), self.max_template_id);
|
||||
save_template(roots, self.max_template_id);
|
||||
save_template(self.interpreter.js_channel(), roots, self.max_template_id);
|
||||
self.max_template_id += 1
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ impl WebsysDom {
|
||||
// Recursively rehydrate the dom from the VirtualDom
|
||||
self.rehydrate_scope(root_scope, dom, &mut ids, &mut to_mount)?;
|
||||
|
||||
dioxus_interpreter_js::hydrate(ids);
|
||||
dioxus_interpreter_js::hydrate(self.interpreter.js_channel(), ids);
|
||||
|
||||
#[cfg(feature = "mounted")]
|
||||
for id in to_mount {
|
||||
@@ -168,7 +168,11 @@ impl WriteMutations for OnlyWriteTemplates<'_> {
|
||||
self.0
|
||||
.templates
|
||||
.insert(template.name.to_owned(), self.0.max_template_id);
|
||||
save_template(roots, self.0.max_template_id);
|
||||
save_template(
|
||||
self.0.interpreter.js_channel(),
|
||||
roots,
|
||||
self.0.max_template_id,
|
||||
);
|
||||
self.0.max_template_id += 1
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user