1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
use crate::mount::Mount;
use crate::scheduler::ScopeOrder;
use crate::scope_context::SuspenseLocation;
use crate::{AttributeValue, ElementId, Event, RenderTargetId, VNode, innerlude::MountId};
use crate::{CapturedError, arena::RenderTargetState};
use crate::{SuspenseContext, innerlude::Effect};
use crate::{
Task,
innerlude::{LocalTask, SchedulerMsg},
scope_context::Scope,
scopes::ScopeId,
};
use generational_box::{AnyStorage, Owner, SyncStorage, UnsyncStorage};
use slab::Slab;
use slotmap::DefaultKey;
use std::any::Any;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::{
cell::{Cell, Ref, RefCell},
rc::Rc,
};
use tracing::instrument;
use dioxus_core_template::TemplatePath;
thread_local! {
static RUNTIMES: RefCell<Vec<Rc<Runtime>>> = const { RefCell::new(vec![]) };
}
/// A global runtime that is shared across all scopes that provides the async runtime and context API
pub struct Runtime {
// We use this to track the current scope
// This stack should only be modified through [`Runtime::with_scope_on_stack`] to ensure that the stack is correctly restored
scope_stack: RefCell<Vec<ScopeId>>,
// We use this to track the current suspense location. Generally this lines up with the scope stack, but it may be different for children of a suspense boundary
// This stack should only be modified through [`Runtime::with_suspense_location`] to ensure that the stack is correctly restored
suspense_stack: RefCell<Vec<SuspenseLocation>>,
// A hand-rolled slab of scope states
pub(crate) scope_states: RefCell<Vec<Option<Scope>>>,
// We use this to track the current task
pub(crate) current_task: Cell<Option<Task>>,
/// Tasks created with cx.spawn
pub(crate) tasks: RefCell<slotmap::SlotMap<DefaultKey, Rc<LocalTask>>>,
// Currently suspended tasks
pub(crate) suspended_tasks: Cell<usize>,
pub(crate) rendering: Cell<bool>,
pub(crate) sender: futures_channel::mpsc::UnboundedSender<SchedulerMsg>,
// The effects that need to be run after the next render
pub(crate) pending_effects: RefCell<BTreeSet<Effect>>,
// Tasks that are waiting to be polled
pub(crate) dirty_tasks: RefCell<BTreeMap<ScopeOrder, VecDeque<Task>>>,
// The renderer targets and their element id arenas.
pub(crate) render_targets: RefCell<Slab<RenderTargetState>>,
// Once nodes are mounted, their persistent mount identity is stored here.
// Each mount is associated with a whole rsx block. [`Runtime::elements`]
// link to a specific node in that block.
pub(crate) mounts: RefCell<Slab<Mount>>,
}
struct ScopeStackGuard<'a> {
runtime: &'a Runtime,
}
impl Drop for ScopeStackGuard<'_> {
fn drop(&mut self) {
self.runtime.pop_scope();
}
}
struct SuspenseLocationGuard<'a> {
runtime: &'a Runtime,
}
impl Drop for SuspenseLocationGuard<'_> {
fn drop(&mut self) {
self.runtime.suspense_stack.borrow_mut().pop();
}
}
impl Runtime {
pub(crate) fn new(sender: futures_channel::mpsc::UnboundedSender<SchedulerMsg>) -> Rc<Self> {
let mut render_targets = Slab::default();
let root = render_targets.insert(RenderTargetState::new());
debug_assert_eq!(root, RenderTargetId::ROOT.index());
Rc::new(Self {
sender,
rendering: Cell::new(false),
scope_states: Default::default(),
scope_stack: Default::default(),
suspense_stack: Default::default(),
current_task: Default::default(),
tasks: Default::default(),
suspended_tasks: Default::default(),
pending_effects: Default::default(),
dirty_tasks: Default::default(),
render_targets: RefCell::new(render_targets),
mounts: Default::default(),
})
}
/// Get the current runtime
pub fn current() -> Rc<Self> {
RUNTIMES
.with(|stack| stack.borrow().last().cloned())
.unwrap_or_else(|| {
panic!(
"Must be called from inside a Dioxus runtime.
Help: Some APIs in dioxus require a global runtime to be present.
If you are calling one of these APIs from outside of a dioxus runtime
(typically in a web-sys closure or dynamic library), you will need to
grab the runtime from a scope that has it and then move it into your
new scope with a runtime guard.
For example, if you are trying to use dioxus apis from a web-sys
closure, you can grab the runtime from the scope it is created in:
```rust
use dioxus::prelude::*;
static COUNT: GlobalSignal<i32> = Signal::global(|| 0);
#[component]
fn MyComponent() -> Element {{
use_effect(|| {{
// Grab the runtime from the MyComponent scope
let runtime = Runtime::current().expect(\"Components run in the Dioxus runtime\");
// Move the runtime into the web-sys closure scope
let web_sys_closure = Closure::new(|| {{
// Then create a guard to provide the runtime to the closure
let _guard = RuntimeGuard::new(runtime);
// and run whatever code needs the runtime
tracing::info!(\"The count is: {{COUNT}}\");
}});
}})
}}
```"
)
})
}
/// Try to get the current runtime, returning None if it doesn't exist (outside the context of a dioxus app)
pub fn try_current() -> Option<Rc<Self>> {
RUNTIMES.with(|stack| stack.borrow().last().cloned())
}
/// Wrap a closure so that it always runs in the runtime that is currently active
pub fn wrap_closure<'a, I, O>(f: impl Fn(I) -> O + 'a) -> impl Fn(I) -> O + 'a {
let current_runtime = Self::current();
move |input| match current_runtime.try_current_scope_id() {
Some(scope) => current_runtime.in_scope(scope, || f(input)),
None => {
let _runtime_guard = RuntimeGuard::new(current_runtime.clone());
f(input)
}
}
}
/// Run a closure with the rendering flag set to true
pub(crate) fn while_rendering<T>(&self, f: impl FnOnce() -> T) -> T {
self.rendering.set(true);
let result = f();
self.rendering.set(false);
result
}
/// Run a closure with the rendering flag set to false
pub(crate) fn while_not_rendering<T>(&self, f: impl FnOnce() -> T) -> T {
let previous = self.rendering.get();
self.rendering.set(false);
let result = f();
self.rendering.set(previous);
result
}
/// Get the render target currently receiving renderer mutations: the
/// target of the scope currently being rendered, or the root target when
/// no scope is active. Every scope carries a flat target assignment;
/// portal scopes carry the portal's target and their subtree inherits it.
pub(crate) fn current_render_target_id(&self) -> RenderTargetId {
self.try_current_scope_id()
.and_then(|scope| self.try_get_state(scope).map(|state| state.target_id()))
.unwrap_or(RenderTargetId::ROOT)
}
/// Create a new renderer target with an isolated [`ElementId`] arena.
///
/// Hosts serve render targets through [`MultiWriter`](crate::MultiWriter)
/// implementations passed into [`VirtualDom::rebuild`](crate::VirtualDom::rebuild)
/// and [`VirtualDom::render_immediate`](crate::VirtualDom::render_immediate). If
/// the host does not serve a writer for the target, those mutations are skipped.
pub fn create_render_target(&self) -> RenderTargetId {
let mut targets = self.render_targets.borrow_mut();
RenderTargetId::new(targets.insert(RenderTargetState::new()))
}
/// Remove a render target previously created with [`create_render_target`](Self::create_render_target).
///
/// This drops the target's [`ElementId`] arena and template
/// cache, freeing the slot so its [`RenderTargetId`] may be handed back out by
/// a later [`create_render_target`](Self::create_render_target). The root target
/// ([`RenderTargetId::ROOT`]) is permanent and is never removed.
///
/// Removing a target that still has live mounts - for example because the
/// [`Portal`](crate::Portal) feeding it has not been torn down yet - would
/// leave those mounts dangling, so this leaves the target in place instead.
/// That happens when a host window is destroyed by the OS or during shutdown
/// before its owning component reclaims the target; the target is then freed
/// when the runtime is dropped. Callers that own the target's teardown should
/// remove the feeding node first so the slot can be recycled.
///
/// Returns `true` if a target was removed, or `false` if `id` was the root,
/// referred to a target that was already gone, or still had live mounts.
pub fn remove_render_target(&self, id: RenderTargetId) -> bool {
if id == RenderTargetId::ROOT {
return false;
}
let mut targets = self.render_targets.borrow_mut();
let Some(target) = targets.get(id.index()) else {
return false;
};
if target.elements.iter().any(|(_, slot)| slot.is_some()) {
return false;
}
targets.try_remove(id.index()).is_some()
}
/// Create a scope context. This slab is synchronized with the scope slab.
pub(crate) fn create_scope(&self, context: Scope) {
let id = context.id.index();
let mut scopes = self.scope_states.borrow_mut();
if id == scopes.len() {
scopes.push(Some(context));
return;
}
if scopes.len() <= id {
scopes.resize_with(id + 1, Default::default);
}
scopes[id] = Some(context);
}
pub(crate) fn set_scope_target_id(&self, scope: ScopeId, target_id: RenderTargetId) {
self.get_state(scope).set_target_id(target_id);
}
pub(crate) fn remove_scope(self: &Rc<Self>, id: ScopeId) {
{
let borrow = self.scope_states.borrow();
if let Some(scope) = &borrow[id.index()] {
let has_scoped_state = !scope.spawned_tasks.borrow().is_empty()
|| !scope.hooks.borrow().is_empty()
|| has_user_shared_contexts(scope);
if has_scoped_state {
// Manually drop tasks, hooks, and contexts inside of the runtime
self.in_scope(id, || {
// Drop all spawned tasks - order doesn't matter since tasks don't rely on eachother
// In theory nested tasks might not like this
for id in scope.spawned_tasks.take() {
self.remove_task(id);
}
// Drop all queued effects
self.pending_effects
.borrow_mut()
.remove(&ScopeOrder::new(scope.height, scope.id));
// Drop all hooks in reverse order in case a hook depends on another hook.
for hook in scope.hooks.take().drain(..).rev() {
drop(hook);
}
// Drop all contexts
scope.shared_contexts.take();
});
} else {
// Empty scopes do not need the runtime/scope stack just to clear bookkeeping.
self.pending_effects
.borrow_mut()
.remove(&ScopeOrder::new(scope.height, scope.id));
}
}
}
// Bind the removed scope so the `borrow_mut()` temporary is released at the end of
// this statement, *before* the scope is dropped. Otherwise the scope's `Drop` runs
// while `scope_states` is still mutably borrowed and re-entrant calls into
// `get_state` panic with "already mutably borrowed".
let removed = self.scope_states.borrow_mut()[id.index()].take();
drop(removed);
}
/// Get the owner for the current scope.
#[track_caller]
pub fn current_owner<S: AnyStorage>(&self) -> Owner<S> {
self.get_state(self.current_scope_id()).owner()
}
/// Get the owner for the current scope.
#[track_caller]
pub fn scope_owner<S: AnyStorage>(&self, scope: ScopeId) -> Owner<S> {
self.get_state(scope).owner()
}
/// Get the current scope id
pub fn current_scope_id(&self) -> ScopeId {
self.scope_stack.borrow().last().copied().unwrap()
}
/// Try to get the current scope id, returning None if it we aren't actively inside a scope
pub fn try_current_scope_id(&self) -> Option<ScopeId> {
self.scope_stack.borrow().last().copied()
}
/// Call this function with the current scope set to the given scope
#[track_caller]
pub fn in_scope<O>(self: &Rc<Self>, id: ScopeId, f: impl FnOnce() -> O) -> O {
let _runtime_guard = RuntimeGuard::new(self.clone());
self.with_scope_on_stack(id, f)
}
/// Get the current suspense location
pub(crate) fn current_suspense_location(&self) -> Option<SuspenseLocation> {
self.suspense_stack.borrow().last().cloned()
}
/// Run a callback a [`SuspenseLocation`] at the top of the stack
pub(crate) fn with_suspense_location<O>(
&self,
suspense_location: SuspenseLocation,
f: impl FnOnce() -> O,
) -> O {
self.suspense_stack.borrow_mut().push(suspense_location);
let _guard = SuspenseLocationGuard { runtime: self };
f()
}
/// Run a callback with the current scope at the top of the stack
pub(crate) fn with_scope_on_stack<O>(&self, scope: ScopeId, f: impl FnOnce() -> O) -> O {
self.push_scope(scope);
let _guard = ScopeStackGuard { runtime: self };
f()
}
/// Push a scope onto the stack
fn push_scope(&self, scope: ScopeId) {
let suspense_location = self
.scope_states
.borrow()
.get(scope.index())
.and_then(|s| s.as_ref())
.map(|s| s.suspense_location())
.unwrap_or_default();
self.suspense_stack.borrow_mut().push(suspense_location);
self.scope_stack.borrow_mut().push(scope);
}
/// Pop a scope off the stack
fn pop_scope(&self) {
self.suspense_stack.borrow_mut().pop();
self.scope_stack.borrow_mut().pop();
}
/// Get the state for any scope given its ID
///
/// This is useful for inserting or removing contexts from a scope, or rendering out its root node
pub(crate) fn get_state(&self, id: ScopeId) -> Ref<'_, Scope> {
Ref::filter_map(self.scope_states.borrow(), |scopes| {
scopes.get(id.index()).and_then(|f| f.as_ref())
})
.ok()
.unwrap()
}
/// Get the state for any scope given its ID
///
/// This is useful for inserting or removing contexts from a scope, or rendering out its root node
pub(crate) fn try_get_state(&self, id: ScopeId) -> Option<Ref<'_, Scope>> {
Ref::filter_map(self.scope_states.borrow(), |contexts| {
contexts.get(id.index()).and_then(|f| f.as_ref())
})
.ok()
}
/// Pushes a new scope onto the stack
pub(crate) fn push(runtime: Rc<Runtime>) {
RUNTIMES.with(|stack| stack.borrow_mut().push(runtime));
}
/// Pops a scope off the stack
pub(crate) fn pop() {
RUNTIMES.with(|stack| stack.borrow_mut().pop().unwrap());
}
/// Runs a function with the current runtime
pub(crate) fn with<R>(callback: impl FnOnce(&Runtime) -> R) -> R {
callback(&Self::current())
}
/// Runs a function with the current scope
pub(crate) fn with_current_scope<R>(callback: impl FnOnce(&Scope) -> R) -> R {
Self::with(|rt| Self::with_scope(rt.current_scope_id(), callback))
}
/// Runs a function with the current scope
pub(crate) fn with_scope<R>(scope: ScopeId, callback: impl FnOnce(&Scope) -> R) -> R {
let rt = Runtime::current();
Self::in_scope(&rt, scope, || callback(&rt.get_state(scope)))
}
/// Check if we should render a scope
pub(crate) fn scope_should_render(&self, scope_id: ScopeId) -> bool {
let scopes = self.scope_states.borrow();
let scope = &scopes[scope_id.index()].as_ref().unwrap();
let location = scope.suspense_location();
if self.suspended_tasks.get() == 0 {
return !matches!(
location,
SuspenseLocation::UnderSuspense(boundary) if boundary.is_suspended()
);
}
location.should_write()
}
/// Call a listener inside the VirtualDom with data from outside the VirtualDom. **The ElementId passed in must be the id of an element with a listener, not a static node or a text node.**
///
/// This method will identify the appropriate element. The data must match up with the listener declared. Note that
/// this method does not give any indication as to the success of the listener call. If the listener is not found,
/// nothing will happen.
///
/// 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, event), level = "trace", name = "Runtime::handle_event")]
pub fn handle_event(self: &Rc<Self>, name: &str, event: Event<dyn Any>, element: ElementId) {
self.handle_event_for_target(RenderTargetId::ROOT, name, event, element);
}
/// Call a listener inside the VirtualDom with data from a specific render target.
///
/// `ElementId`s are renderer-local, so multi-target renderers should use this
/// method instead of [`Self::handle_event`].
#[instrument(
skip(self, event),
level = "trace",
name = "Runtime::handle_event_for_target"
)]
pub fn handle_event_for_target(
self: &Rc<Self>,
target_id: RenderTargetId,
name: &str,
event: Event<dyn Any>,
element: ElementId,
) {
let _runtime = RuntimeGuard::new(self.clone());
let targets = self.render_targets.borrow();
let Some(target) = targets.get(target_id.index()) else {
return;
};
let parent_ref = target.elements.get(element.index()).copied().flatten();
drop(targets);
if let Some(parent_ref) = parent_ref
&& let Some(path) = self.event_target_path(parent_ref, element)
{
if event.propagates() {
self.handle_bubbling_event(parent_ref, path, name, event);
} else {
self.handle_non_bubbling_event(parent_ref, path, name, event);
}
}
}
fn event_target_path(&self, mount_id: MountId, element: ElementId) -> Option<TemplatePath> {
let mounts = self.mounts.borrow();
let mount = mounts.get(mount_id.0)?;
let node = mount.node();
for anchor in node.dynamic_anchors() {
let path = anchor.static_path();
let Some(id) = mount.mounted_anchor_node(anchor.anchor_index()) else {
continue;
};
if id.element_id() == element {
return Some(path);
}
}
None
}
fn child_slot_path(&self, parent_mount: MountId, child_mount: MountId) -> Option<TemplatePath> {
let mounts = self.mounts.borrow();
let child = mounts.get(child_mount.0)?;
debug_assert_eq!(child.logical_parent(), Some(parent_mount));
let render_parent = child
.render_parent()
.expect("child mount should have a render parent");
let parent = mounts.get(parent_mount.0)?;
let anchor = parent.node().dynamic_anchor(render_parent.anchor_index());
let target = if anchor.is_parent_append_target() {
anchor.static_path()
} else {
anchor.static_path().split_insertion().0
};
Some(target)
}
fn event_attributes<'a>(
node: &'a VNode,
name: &'a str,
) -> impl Iterator<Item = (TemplatePath, &'a AttributeValue)> + 'a {
node.dynamic_anchors().flat_map(move |anchor| {
let path = anchor.static_path();
anchor
.attrs()
.flat_map(|slot| slot.attrs())
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
.filter_map(move |attr| {
(attr.name.get(2..) == Some(name)).then_some((path, &attr.value))
})
})
}
/*
------------------------
The algorithm works by walking through the list of dynamic attributes, checking their paths, and breaking when
we find the target path.
With the target path, we try and move up to the parent until there is no parent.
Due to how bubbling works, we call the listeners before walking to the parent.
If we wanted to do capturing, then we would accumulate all the listeners and call them in reverse order.
----------------------
For a visual demonstration, here we present a tree on the left and whether or not a listener is collected on the
right.
| <-- yes (is ascendant)
| | | <-- no (is not direct ascendant)
| | <-- yes (is ascendant)
| | | | | <--- target element, break early, don't check other listeners
| | | <-- no, broke early
| <-- no, broke early
*/
#[instrument(
skip(self, path, uievent),
level = "trace",
name = "VirtualDom::handle_bubbling_event"
)]
fn handle_bubbling_event(
&self,
mount_id: MountId,
path: TemplatePath,
name: &str,
uievent: Event<dyn Any>,
) {
// If the event bubbles, we traverse through the tree until we find the target element.
// Loop through each dynamic attribute (in a depth first order) in this template before moving up to the template's parent.
let mut mount_id = mount_id;
let mut target_path = path;
loop {
let mut listeners = vec![];
let logical_parent;
// We do this in its own block to prevent mount borrows from staying open while we call user code
{
let mounts = self.mounts.borrow();
let Some(mount) = mounts.get(mount_id.0) else {
// If the node is suspended and not mounted, we can just ignore the event
return;
};
let el_ref = mount.node();
logical_parent = mount.logical_parent();
// Accumulate listeners into the listener list bottom to top
for (attr_path, value) in Self::event_attributes(el_ref, name) {
if !target_path.starts_with(attr_path) {
continue;
}
if let AttributeValue::Listener(listener) = value {
listeners.push(listener.clone());
}
// Break if this is the exact target element.
// This means we won't call two listeners with the same name on the same element. This should be
// documented, or be rejected from the rsx! macro outright
if target_path == attr_path {
break;
}
}
}
// Now that we've accumulated all the parent attributes for the target element, call them in
// reverse order. Listeners are accumulated in document order (ancestors first), so reversing
// calls the deepest (target) listener first and bubbles up toward the ancestors.
// 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() {
listener.call(uievent.clone());
let metadata = uievent.metadata.borrow();
if !metadata.propagates {
return;
}
}
let Some(parent_mount) = logical_parent else {
break;
};
let Some(slot_path) = self.child_slot_path(parent_mount, mount_id) else {
break;
};
mount_id = parent_mount;
target_path = slot_path;
}
}
/// Call an event listener in the simplest way possible without bubbling upwards
#[instrument(
skip(self, target_path, uievent),
level = "trace",
name = "VirtualDom::handle_non_bubbling_event"
)]
fn handle_non_bubbling_event(
&self,
mount_id: MountId,
target_path: TemplatePath,
name: &str,
uievent: Event<dyn Any>,
) {
let listeners = {
let mounts = self.mounts.borrow();
let Some(mount) = mounts.get(mount_id.0) else {
// If the node is suspended and not mounted, we can just ignore the event
return;
};
let mut listeners = Vec::new();
for (attr_path, value) in Self::event_attributes(mount.node(), name) {
if target_path != attr_path {
continue;
}
if let AttributeValue::Listener(listener) = value {
listeners.push(listener.clone());
break;
}
}
listeners
};
for listener in listeners {
listener.call(uievent.clone());
}
}
/// Consume context from the current scope
pub fn consume_context<T: 'static + Clone>(&self, id: ScopeId) -> Option<T> {
self.get_state(id).consume_context::<T>()
}
/// Consume context from the current scope
pub fn consume_context_from_scope<T: 'static + Clone>(&self, scope_id: ScopeId) -> Option<T> {
self.get_state(scope_id).consume_context::<T>()
}
/// Check if the current scope has a context
pub fn has_context<T: 'static + Clone>(&self, id: ScopeId) -> Option<T> {
self.get_state(id).has_context::<T>()
}
/// Provide context to the current scope
pub fn provide_context<T: 'static + Clone>(&self, id: ScopeId, value: T) -> T {
self.get_state(id).provide_context(value)
}
/// Get the parent of the current scope if it exists
pub fn parent_scope(&self, scope: ScopeId) -> Option<ScopeId> {
self.get_state(scope).parent_id()
}
/// Check if the current scope is a descendant of the given scope
pub fn is_descendant_of(&self, us: ScopeId, other: ScopeId) -> bool {
let mut current = us;
while let Some(parent) = self.parent_scope(current) {
if parent == other {
return true;
}
current = parent;
}
false
}
/// Mark the current scope as dirty, causing it to re-render
pub fn needs_update(&self, scope: ScopeId) {
self.get_state(scope).needs_update_any(scope);
}
/// Get the height of the current scope
pub fn height(&self, id: ScopeId) -> u32 {
self.get_state(id).height
}
/// Throw a [`CapturedError`] into a scope. The error will bubble up to the nearest [`ErrorBoundary`](crate::ErrorBoundary) or the root of the app.
///
/// # Examples
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// fn Component() -> Element {
/// let request = spawn(async move {
/// match reqwest::get("https://api.example.com").await {
/// Ok(_) => unimplemented!(),
/// // You can explicitly throw an error into a scope with throw_error
/// Err(err) => dioxus::core::Runtime::current().throw_error(ScopeId::APP, err),
/// }
/// });
///
/// unimplemented!()
/// }
/// ```
pub fn throw_error(&self, id: ScopeId, error: impl Into<CapturedError> + 'static) {
let error = error.into();
if let Some(cx) = self.consume_context::<crate::ErrorContext>(id) {
cx.insert_error(error)
} else {
tracing::error!(
"Tried to throw an error into an error boundary, but failed to locate a boundary: {:?}",
error
)
}
}
/// Get the suspense context the current scope is in
pub fn suspense_context(&self) -> Option<SuspenseContext> {
self.get_state(self.current_scope_id())
.suspense_location()
.suspense_context()
.cloned()
}
/// Force every component to be dirty and require a re-render. Used by hot-reloading.
///
/// This might need to change to a different flag in the event hooks order changes within components.
/// What we really need is a way to mark components as needing a complete rebuild if they were hit by changes.
pub fn force_all_dirty(&self) {
self.scope_states.borrow_mut().iter().for_each(|state| {
if let Some(scope) = state.as_ref() {
scope.needs_update_any(scope.id);
}
});
}
/// Check if the virtual dom is currently rendering
pub fn vdom_is_rendering(&self) -> bool {
self.rendering.get()
}
}
fn has_user_shared_contexts(scope: &Scope) -> bool {
scope.shared_contexts.borrow().iter().any(|context| {
let context = context.as_ref();
!context.is::<Owner<SyncStorage>>() && !context.is::<Owner<UnsyncStorage>>()
})
}
/// A guard for a new runtime. This must be used to override the current runtime when importing components from a dynamic library that has it's own runtime.
///
/// ```rust
/// use dioxus::prelude::*;
/// use dioxus_core::{Runtime, RuntimeGuard};
///
/// fn main() {
/// let virtual_dom = VirtualDom::new(app);
/// }
///
/// fn app() -> Element {
/// rsx! { Component { runtime: Runtime::current() } }
/// }
///
/// // In a dynamic library
/// #[derive(Props, Clone)]
/// struct ComponentProps {
/// runtime: std::rc::Rc<Runtime>,
/// }
///
/// impl PartialEq for ComponentProps {
/// fn eq(&self, _other: &Self) -> bool {
/// true
/// }
/// }
///
/// fn Component(cx: ComponentProps) -> Element {
/// use_hook(|| {
/// let _guard = RuntimeGuard::new(cx.runtime.clone());
/// });
///
/// rsx! { div {} }
/// }
/// ```
pub struct RuntimeGuard(());
impl RuntimeGuard {
/// Create a new runtime guard that sets the current Dioxus runtime. The runtime will be reset when the guard is dropped
pub fn new(runtime: Rc<Runtime>) -> Self {
Runtime::push(runtime);
Self(())
}
}
impl Drop for RuntimeGuard {
fn drop(&mut self) {
Runtime::pop();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn runtime() -> Rc<Runtime> {
let (sender, _receiver) = futures_channel::mpsc::unbounded();
Runtime::new(sender)
}
fn catch_expected_panic(f: impl FnOnce()) {
let panic_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
std::panic::set_hook(panic_hook);
assert!(result.is_err());
}
#[test]
fn with_scope_on_stack_restores_after_panic() {
let runtime = runtime();
catch_expected_panic(|| {
runtime.with_scope_on_stack(ScopeId::new(7), || panic!("forced panic"));
});
assert_eq!(runtime.try_current_scope_id(), None);
assert!(runtime.current_suspense_location().is_none());
}
#[test]
fn with_suspense_location_restores_after_panic() {
let runtime = runtime();
catch_expected_panic(|| {
runtime.with_suspense_location(SuspenseLocation::default(), || panic!("forced panic"));
});
assert!(runtime.current_suspense_location().is_none());
}
}