dioxus-core 0.8.0-alpha.3

Build fullstack web, desktop, and mobile apps with a single codebase.
Documentation
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
use std::{any::Any, rc::Rc};

use crate::{
    DynamicNode,
    diff::context::DiffContext,
    diff::placement::{InsertionSite, insertion_site_at, splice_streamed_nodes},
    innerlude::*,
    mount::{RenderMode, SuspenseBranch},
    render_driver::{RenderDriver, remove_rendered_output},
    scope_context::SuspenseLocation,
};

/// Properties for the [`SuspenseBoundary`] component.
#[allow(non_camel_case_types)]
pub struct SuspenseBoundaryProps {
    fallback: Callback<SuspenseContext, Element>,
    /// The children of the suspense boundary
    children: LastRenderedNode,
}

impl Clone for SuspenseBoundaryProps {
    fn clone(&self) -> Self {
        Self {
            fallback: self.fallback,
            children: self.children.clone(),
        }
    }
}

#[must_use]
#[allow(dead_code, non_camel_case_types, non_snake_case)]
#[doc(hidden)]
/// Builder for [`SuspenseBoundaryProps`].
pub struct SuspenseBoundaryPropsBuilder<TypedBuilderFields> {
    owner: Owner,
    fields: TypedBuilderFields,
    _phantom: (),
}

#[must_use]
#[allow(dead_code, non_camel_case_types, non_snake_case)]
#[doc(hidden)]
/// Component builder for [`SuspenseBoundary`].
pub struct SuspenseBoundaryComponentBuilder<RenderFn, Marker, TypedBuilderFields> {
    render_fn: RenderFn,
    builder: SuspenseBoundaryPropsBuilder<TypedBuilderFields>,
    _marker: std::marker::PhantomData<fn() -> Marker>,
}

impl Properties for SuspenseBoundaryProps
where
    Self: Clone,
{
    type ComponentBuilder<RenderFn, Marker> =
        SuspenseBoundaryComponentBuilder<RenderFn, Marker, ((), ())>;

    fn component_builder<RenderFn, Marker>(
        render_fn: RenderFn,
    ) -> Self::ComponentBuilder<RenderFn, Marker> {
        SuspenseBoundaryComponentBuilder {
            render_fn,
            builder: SuspenseBoundaryPropsBuilder {
                owner: Owner::default(),
                fields: ((), ()),
                _phantom: ::core::default::Default::default(),
            },
            _marker: std::marker::PhantomData,
        }
    }

    fn memoize(&mut self, new: &Self) -> bool {
        self.fallback.__point_to(&new.fallback);
        self.children = new.children.clone();
        false
    }
}

#[allow(dead_code, non_camel_case_types, missing_docs)]
#[doc(hidden)]
impl<RenderFn, ComponentMarker, __children>
    SuspenseBoundaryComponentBuilder<RenderFn, ComponentMarker, ((), __children)>
{
    #[allow(clippy::type_complexity)]
    #[doc(hidden)]
    pub fn fallback<__Marker>(
        self,
        fallback: impl SuperInto<Callback<SuspenseContext, Element>, __Marker>,
    ) -> SuspenseBoundaryComponentBuilder<
        RenderFn,
        ComponentMarker,
        ((Callback<SuspenseContext, Element>,), __children),
    > {
        SuspenseBoundaryComponentBuilder {
            render_fn: self.render_fn,
            builder: self.builder.fallback(fallback),
            _marker: self._marker,
        }
    }
}

#[allow(dead_code, non_camel_case_types, missing_docs)]
#[doc(hidden)]
impl<RenderFn, ComponentMarker, __fallback>
    SuspenseBoundaryComponentBuilder<RenderFn, ComponentMarker, (__fallback, ())>
{
    #[allow(clippy::type_complexity)]
    #[doc(hidden)]
    pub fn children(
        self,
        children: Element,
    ) -> SuspenseBoundaryComponentBuilder<RenderFn, ComponentMarker, (__fallback, (Element,))> {
        SuspenseBoundaryComponentBuilder {
            render_fn: self.render_fn,
            builder: self.builder.children(children),
            _marker: self._marker,
        }
    }
}
#[allow(dead_code, non_camel_case_types, non_snake_case)]
#[doc(hidden)]
/// Helper trait used by the generated suspense boundary props builder.
pub trait SuspenseBoundaryPropsBuilder_Optional<T> {
    /// Convert the optional builder field into a value.
    fn into_value<F: FnOnce() -> T>(self, default: F) -> T;
}
impl<T> SuspenseBoundaryPropsBuilder_Optional<T> for () {
    fn into_value<F: FnOnce() -> T>(self, default: F) -> T {
        default()
    }
}
impl<T> SuspenseBoundaryPropsBuilder_Optional<T> for (T,) {
    fn into_value<F: FnOnce() -> T>(self, _: F) -> T {
        self.0
    }
}
#[allow(dead_code, non_camel_case_types, missing_docs)]
#[doc(hidden)]
impl<__children> SuspenseBoundaryPropsBuilder<((), __children)> {
    #[allow(clippy::type_complexity)]
    #[doc(hidden)]
    pub fn fallback<__Marker>(
        self,
        fallback: impl SuperInto<Callback<SuspenseContext, Element>, __Marker>,
    ) -> SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)> {
        let fallback = (with_owner(self.owner.clone(), move || {
            SuperInto::super_into(fallback)
        }),);
        let (_, children) = self.fields;
        SuspenseBoundaryPropsBuilder {
            owner: self.owner,
            fields: (fallback, children),
            _phantom: self._phantom,
        }
    }
}
#[allow(dead_code, non_camel_case_types, non_snake_case)]
#[doc(hidden)]
/// Error marker for setting the `fallback` field more than once.
pub enum SuspenseBoundaryPropsBuilder_Error_Repeated_field_fallback {}
#[allow(dead_code, non_camel_case_types, missing_docs)]
#[doc(hidden)]
impl<__children> SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)> {
    #[deprecated(note = "Repeated field fallback")]
    #[allow(clippy::type_complexity)]
    #[doc(hidden)]
    pub fn fallback(
        self,
        _: SuspenseBoundaryPropsBuilder_Error_Repeated_field_fallback,
    ) -> SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)> {
        self
    }
}
#[allow(dead_code, non_camel_case_types, missing_docs)]
#[doc(hidden)]
impl<__fallback> SuspenseBoundaryPropsBuilder<(__fallback, ())> {
    #[allow(clippy::type_complexity)]
    #[doc(hidden)]
    pub fn children(
        self,
        children: Element,
    ) -> SuspenseBoundaryPropsBuilder<(__fallback, (Element,))> {
        let children = (children,);
        let (fallback, _) = self.fields;
        SuspenseBoundaryPropsBuilder {
            owner: self.owner,
            fields: (fallback, children),
            _phantom: self._phantom,
        }
    }
}
#[allow(dead_code, non_camel_case_types, non_snake_case)]
#[doc(hidden)]
/// Error marker for setting the `children` field more than once.
pub enum SuspenseBoundaryPropsBuilder_Error_Repeated_field_children {}
#[allow(dead_code, non_camel_case_types, missing_docs)]
#[doc(hidden)]
impl<__fallback> SuspenseBoundaryPropsBuilder<(__fallback, (Element,))> {
    #[deprecated(note = "Repeated field children")]
    #[allow(clippy::type_complexity)]
    #[doc(hidden)]
    pub fn children(
        self,
        _: SuspenseBoundaryPropsBuilder_Error_Repeated_field_children,
    ) -> SuspenseBoundaryPropsBuilder<(__fallback, (Element,))> {
        self
    }
}
#[allow(dead_code, non_camel_case_types, non_snake_case)]
#[doc(hidden)]
/// Error marker for missing the required `fallback` field.
pub enum SuspenseBoundaryPropsBuilder_Error_Missing_required_field_fallback {}
#[allow(dead_code, non_camel_case_types, missing_docs, clippy::panic)]
#[doc(hidden)]
impl<__children> SuspenseBoundaryPropsBuilder<((), __children)> {
    #[deprecated(note = "Missing required field fallback")]
    #[doc(hidden)]
    pub fn build(
        self,
        _: SuspenseBoundaryPropsBuilder_Error_Missing_required_field_fallback,
    ) -> SuspenseBoundaryProps {
        panic!()
    }
}
#[allow(dead_code, non_camel_case_types, missing_docs)]
#[doc(hidden)]
/// [`SuspenseBoundaryProps`] bundled with the owner that created its callbacks.
pub struct SuspenseBoundaryPropsWithOwner {
    inner: SuspenseBoundaryProps,
    owner: Owner,
}
#[automatically_derived]
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl ::core::clone::Clone for SuspenseBoundaryPropsWithOwner {
    #[inline]
    fn clone(&self) -> SuspenseBoundaryPropsWithOwner {
        SuspenseBoundaryPropsWithOwner {
            inner: ::core::clone::Clone::clone(&self.inner),
            owner: ::core::clone::Clone::clone(&self.owner),
        }
    }
}
impl PartialEq for SuspenseBoundaryPropsWithOwner {
    fn eq(&self, other: &Self) -> bool {
        self.inner.eq(&other.inner)
    }
}
impl SuspenseBoundaryPropsWithOwner {
    /// Create a component from the props.
    pub fn into_vcomponent<M: 'static>(
        self,
        render_fn: impl ComponentFunction<SuspenseBoundaryProps, M>,
    ) -> VComponent {
        let component_name = std::any::type_name_of_val(&render_fn);
        let render_fn_ptr = render_fn.fn_ptr();
        let props = Box::new(VProps::new(
            move |wrapper: Self| render_fn.rebuild(wrapper.inner),
            <Self as Properties>::memoize,
            self,
            component_name,
        ));
        VComponent::new_with_driver(
            component_name,
            render_fn_ptr,
            Rc::new(SuspenseDriver {
                context: SuspenseContext::new(),
            }),
            props,
        )
    }
}

impl<RenderFn, Marker> ComponentBuilderRender<RenderFn, Marker> for SuspenseBoundaryPropsWithOwner
where
    RenderFn: ComponentFunction<SuspenseBoundaryProps, Marker>,
    Marker: 'static,
{
    fn into_vcomponent(self, render_fn: RenderFn) -> VComponent {
        SuspenseBoundaryPropsWithOwner::into_vcomponent(self, render_fn)
    }
}

impl Properties for SuspenseBoundaryPropsWithOwner {
    type ComponentBuilder<RenderFn, Marker> = ();

    fn component_builder<RenderFn, Marker>(
        _: RenderFn,
    ) -> Self::ComponentBuilder<RenderFn, Marker> {
        unreachable!()
    }

    fn memoize(&mut self, new: &Self) -> bool {
        self.inner.memoize(&new.inner)
    }
}
#[allow(dead_code, non_camel_case_types, missing_docs)]
#[doc(hidden)]
impl<__children: SuspenseBoundaryPropsBuilder_Optional<Element>>
    SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)>
{
    #[doc(hidden)]
    pub fn build(self) -> SuspenseBoundaryPropsWithOwner {
        let (fallback, children) = self.fields;
        let fallback = fallback.0;
        let children = SuspenseBoundaryPropsBuilder_Optional::into_value(children, VNode::empty);
        SuspenseBoundaryPropsWithOwner {
            inner: SuspenseBoundaryProps {
                fallback,
                children: LastRenderedNode::new(children),
            },
            owner: self.owner,
        }
    }
}

#[allow(dead_code, non_camel_case_types, missing_docs)]
#[doc(hidden)]
impl<RenderFn, ComponentMarker, __children: SuspenseBoundaryPropsBuilder_Optional<Element>>
    SuspenseBoundaryComponentBuilder<
        RenderFn,
        ComponentMarker,
        ((Callback<SuspenseContext, Element>,), __children),
    >
{
    #[doc(hidden)]
    pub fn build(
        self,
    ) -> ComponentBuilderOutput<RenderFn, SuspenseBoundaryPropsWithOwner, ComponentMarker> {
        ComponentBuilderOutput::new(self.render_fn, self.builder.build())
    }
}

#[automatically_derived]
#[allow(non_camel_case_types)]
impl ::core::cmp::PartialEq for SuspenseBoundaryProps {
    #[inline]
    fn eq(&self, other: &SuspenseBoundaryProps) -> bool {
        self.fallback == other.fallback && self.children == other.children
    }
}

/// Suspense Boundaries let you render a fallback UI while a child component is suspended.
///
/// # Example
///
/// ```rust
/// # use dioxus::prelude::*;
/// # fn Article() -> Element { rsx! { "Article" } }
/// fn App() -> Element {
///     rsx! {
///         SuspenseBoundary {
///             fallback: |_| rsx! { "Loading..." },
///             Article {}
///         }
///     }
/// }
/// ```
#[allow(non_snake_case)]
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn SuspenseBoundary(_: SuspenseBoundaryProps) -> Element {
    unreachable!("SuspenseBoundary should not be called directly")
}

/// The rendering lifecycle of a suspense boundary scope.
struct SuspenseDriver {
    context: SuspenseContext,
}

impl RenderDriver for SuspenseDriver {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn suspense_location(&self, _: SuspenseLocation) -> SuspenseLocation {
        SuspenseLocation::SuspenseBoundary(self.context.clone())
    }

    fn create(
        &self,
        dom: &mut VirtualDom,
        scope_id: ScopeId,
        parent: Option<MountId>,
        to: Option<&mut (dyn WriteMutations + '_)>,
    ) -> usize {
        if let Some(rendered) = dom.scopes[scope_id.index()]
            .last_rendered_node
            .as_ref()
            .map(|rendered| rendered.node().clone())
        {
            dom.mark_clean(scope_id);
            return dom.create_scope(to, scope_id, rendered, parent);
        }

        self.context.mount(scope_id);

        let nodes = suspense_create(scope_id, parent, dom, to);
        dom.mark_clean(scope_id);
        nodes
    }

    fn diff(
        &self,
        dom: &mut VirtualDom,
        scope_id: ScopeId,
        _: Option<DiffContext<'_>>,
        to: Option<&mut (dyn WriteMutations + '_)>,
    ) {
        let render_to = to.filter(|_| dom.scope_should_write_now(scope_id));
        suspense_diff(scope_id, dom, render_to)
    }

    fn remove(
        &self,
        dom: &mut VirtualDom,
        scope_id: ScopeId,
        to: Option<&mut (dyn WriteMutations + '_)>,
        destroy_component_state: bool,
    ) {
        // If this is a suspense boundary, remove the suspended nodes as well.
        //
        // When we are only moving a component out of the real DOM for an
        // ancestor suspense boundary, the nested boundary's suspended nodes
        // are still its background state. Keep them so the nested boundary
        // can resume or continue diffing while hidden.
        if destroy_component_state {
            SuspenseContext::remove_suspended_nodes(dom, scope_id, destroy_component_state);
        }

        // The scope's rendered output (children or fallback) is removed the
        // same way a plain component's output is.
        remove_rendered_output(dom, scope_id, to, destroy_component_state);
    }
}

fn suspense_props(dom: &VirtualDom, scope_id: ScopeId) -> &SuspenseBoundaryPropsWithOwner {
    dom.scopes[scope_id.index()]
        .props
        .props()
        .downcast_ref::<SuspenseBoundaryPropsWithOwner>()
        .expect("suspense boundary scope carries SuspenseBoundaryPropsWithOwner")
}

fn suspense_children(dom: &VirtualDom, scope_id: ScopeId) -> LastRenderedNode {
    suspense_props(dom, scope_id).inner.children.clone()
}

fn suspense_fallback(dom: &VirtualDom, scope_id: ScopeId) -> Callback<SuspenseContext, Element> {
    suspense_props(dom, scope_id).inner.fallback
}

fn store_suspense_children(dom: &mut VirtualDom, scope_id: ScopeId, children: &LastRenderedNode) {
    let props = dom.scopes[scope_id.index()]
        .props
        .props_mut()
        .downcast_mut::<SuspenseBoundaryPropsWithOwner>()
        .expect("suspense boundary scope carries SuspenseBoundaryPropsWithOwner");
    props.inner.children.clone_from(children);
}
#[allow(non_snake_case)]
#[doc(hidden)]
mod SuspenseBoundary_completions {
    #[doc(hidden)]
    #[allow(non_camel_case_types)]
    /// This enum is generated to help autocomplete the braces after the component. It does nothing
    pub enum Component {
        /// Autocomplete variant for `SuspenseBoundary`.
        SuspenseBoundary {},
    }
}
#[allow(unused)]
#[doc(hidden)]
pub use SuspenseBoundary_completions::Component::SuspenseBoundary;
use generational_box::Owner;

/// Mount a suspense boundary scope: render the children in the background
/// first, then mount either the children or the fallback depending on whether
/// anything suspended.
fn suspense_create(
    scope_id: ScopeId,
    parent: Option<MountId>,
    dom: &mut VirtualDom,
    to: Option<&mut (dyn WriteMutations + '_)>,
) -> usize {
    dom.runtime.clone().with_scope_on_stack(scope_id, || {
        let suspense_context = dom.runtime.get_state(scope_id).suspense_boundary().unwrap();

        let children = suspense_children(dom, scope_id);

        // First always render the children in the background. Rendering the children may cause this boundary to suspend
        let background = suspense_context.under_suspense_boundary(&dom.runtime(), || {
            children.as_vnode().create_mounted(dom, parent, None)
        });

        store_suspense_children(dom, scope_id, &children);

        // If there are suspended futures, render the fallback

        if !suspense_context.suspended_futures().is_empty() {
            let placeholder_context = suspense_context.clone();
            let (node, nodes_created) =
                suspense_context.in_suspense_placeholder(&dom.runtime(), || {
                    let fallback = suspense_fallback(dom, scope_id);
                    let branch = SuspenseBranch::new(children.as_vnode().clone(), background.mount);
                    store_suspended_branch(dom, scope_id, &branch);
                    placeholder_context.set_suspended_branch(branch);
                    let suspense_placeholder =
                        LastRenderedNode::new(fallback.call(placeholder_context));
                    let nodes_created = suspense_placeholder
                        .as_vnode()
                        .create_mounted(dom, parent, to);
                    (suspense_placeholder, nodes_created)
                });

            dom.scopes[scope_id.index()].last_rendered_node =
                Some(MountedOutput::new(node, nodes_created.mount));
            nodes_created.nodes
        } else {
            // Otherwise promote the background-rendered children into the real dom,
            // reusing the background mount and its scopes instead of recreating.
            let nodes_created = suspense_context.under_suspense_boundary(&dom.runtime(), || {
                children
                    .as_vnode()
                    .recreate_with_mount(dom, background.mount, parent, parent, to)
            });
            dom.scopes[scope_id.index()].last_rendered_node =
                Some(MountedOutput::new(children, nodes_created.mount));
            suspense_context.take_suspended_branch();
            mark_suspense_resolved(&suspense_context, dom, scope_id);

            nodes_created.nodes
        }
    })
}

impl SuspenseBoundaryProps {
    /// Manually rerun the children of this suspense boundary without diffing against the old nodes.
    ///
    /// This should only be called by dioxus-web after the suspense boundary has been streamed in from the server.
    #[doc(hidden)]
    pub fn resolve_suspense<M: WriteMutations>(
        scope_id: ScopeId,
        dom: &mut VirtualDom,
        to: &mut M,
        push_replacements: impl FnOnce(&mut M) -> usize,
    ) {
        dom.runtime.clone().with_scope_on_stack(scope_id, || {
            let _runtime = RuntimeGuard::new(dom.runtime());
            let Some(scope_state) = dom.scopes.get_mut(scope_id.index()) else {
                return;
            };

            // Reset the suspense context
            let suspense_context = scope_state.state().suspense_boundary().unwrap().clone();
            suspense_context.inner.suspended_tasks.borrow_mut().clear();

            // Get the render parent of the suspense boundary so the resolved
            // children inherit both the right logical parent (for creation) and
            // the right render parent. Without the render parent, an event
            // bubbling out of the resolved subtree panics in
            // `Runtime::child_slot_path` ("child mount should have a render
            // parent"), the same way the non-streaming `(None, false)` resolve
            // path copies it onto the diffed mount below.
            let currently_rendered = scope_state.last_rendered_node.clone().unwrap();
            let mount = currently_rendered.root_mount();
            let render_parent = dom.mounted_render_parent(mount);
            let parent = render_parent.as_ref().map(|parent| parent.parent());

            // Unmount any children to reset any scopes under this suspense boundary
            let children = suspense_children(dom, scope_id);
            // Take the suspended nodes out of the suspense boundary so the children know that the boundary is not suspended while diffing
            if let Some(branch) = suspense_context.take_suspended_branch() {
                let mount = branch.root_mount();
                branch.into_root().remove_node(mount, &mut *dom, None);
            }

            // Streaming replacements are pushed after the target node so the splice can stay
            // stack-only. Insert streamed nodes before the fallback when it has a DOM node, then
            // remove the fallback normally. An empty (or all-suspense) fallback renders to nothing,
            // so streamed nodes are inserted at the boundary's position instead.
            let placement = match currently_rendered.mounted_vnode().find_first_element(dom) {
                Some(id) => InsertionSite::before(id),
                None => insertion_site_at(currently_rendered.mounted_vnode(), dom, None),
            };
            splice_streamed_nodes(to, placement, push_replacements);
            currently_rendered.as_vnode().remove_node(
                currently_rendered.root_mount(),
                &mut *dom,
                Some(to),
            );

            // First always render the children in the background. Rendering the children may cause this boundary to suspend
            let created = suspense_context.under_suspense_boundary(&dom.runtime(), || {
                let mut no_op = crate::NoOpMutations;
                children
                    .as_vnode()
                    .create_mounted(dom, parent, Some(&mut no_op))
            });

            // Preserve the boundary's render parent on the resolved subtree so
            // events can bubble out of it (see the comment where `render_parent`
            // is captured above).
            if let Some(render_parent) = render_parent {
                dom.set_mounted_render_parent(created.mount, render_parent);
            }

            set_rendered_children(dom, scope_id, children, created.mount);

            // Run any closures that were waiting for the suspense to resolve
            suspense_context.run_resolved_closures(&dom.runtime);
        })
    }
}

/// Diff a suspense boundary scope against its current children/fallback
/// props.
///
/// `to` is the pre-gated writer: [`SuspenseDriver::diff`] applies the scope
/// write gate before calling in.
fn suspense_diff(
    scope_id: ScopeId,
    dom: &mut VirtualDom,
    mut to: Option<&mut (dyn WriteMutations + '_)>,
) {
    dom.runtime.clone().with_scope_on_stack(scope_id, || {
        let scope = &dom.scopes[scope_id.index()];
        let last_rendered_node = scope.last_rendered_node.clone().unwrap();
        let children = suspense_children(dom, scope_id);
        let fallback = suspense_fallback(dom, scope_id);

        let suspense_context = scope.state().suspense_boundary().unwrap().clone();
        let suspended_branch = suspense_context.suspended_branch();
        let suspended = !suspense_context.suspended_futures().is_empty();
        match (suspended_branch, suspended) {
            // We already have suspended nodes that still need to be suspended
            // Just diff the normal and suspended nodes
            (Some(suspended_branch), true) => {
                let suspended_nodes = suspended_branch.root();
                let suspended_mount = suspended_branch.root_mount();
                let new_suspended_nodes: VNode = children.as_vnode().clone();

                // Diff the suspended nodes in the background *first*: re-running the
                // child may cancel its suspend (e.g. a signal flipped a `mode` flag)
                // and we want to observe that before committing to a fallback render.
                let new_suspended_mount =
                    suspense_context.under_suspense_boundary(&dom.runtime(), || {
                        MountedVNode::new(&suspended_nodes, suspended_mount).diff_node(
                            &new_suspended_nodes,
                            dom,
                            None,
                        )
                    });
                flush_retained_branch_scopes(dom, scope_id);

                if !suspense_context.suspended_futures().is_empty() {
                    // Still suspended: diff the placeholder against a fresh fallback.
                    let (new_placeholder, placeholder_mount) = suspense_context
                        .in_suspense_placeholder(&dom.runtime(), || {
                            let new_placeholder =
                                LastRenderedNode::new(fallback.call(suspense_context.clone()));
                            let placeholder_mount = last_rendered_node.mounted_vnode().diff_node(
                                new_placeholder.as_vnode(),
                                dom,
                                to,
                            );
                            (new_placeholder, placeholder_mount)
                        });
                    dom.scopes[scope_id.index()].last_rendered_node =
                        Some(MountedOutput::new(new_placeholder, placeholder_mount));
                    let branch = SuspenseBranch::new(new_suspended_nodes, new_suspended_mount);
                    store_suspended_branch(dom, scope_id, &branch);
                    suspense_context.set_suspended_branch(branch);
                } else {
                    // The background diff resolved the suspension. Promote the
                    // background-rendered nodes by replacing the fallback placeholder.
                    suspense_context.take_suspended_branch();
                    set_suspense_mounts_render_mode(
                        dom,
                        &new_suspended_nodes,
                        new_suspended_mount,
                        RenderMode::Foreground,
                        false,
                    );
                    suspense_context.under_suspense_boundary(&dom.runtime(), || {
                        new_suspended_nodes.remove_node_inner(
                            new_suspended_mount,
                            dom,
                            None,
                            false,
                        );
                        let mounted_children = dom
                            .current_mounted_view(new_suspended_mount)
                            .expect("suspense child");
                        replace_placeholder_with(
                            &last_rendered_node,
                            MountedVNode::new(&mounted_children, new_suspended_mount),
                            dom,
                            to.as_deref_mut(),
                        );
                    });
                    set_rendered_children(
                        dom,
                        scope_id,
                        LastRenderedNode::Real(new_suspended_nodes),
                        new_suspended_mount,
                    );
                    mark_suspense_resolved(&suspense_context, dom, scope_id);
                }
            }
            // We have no suspended nodes, and we are not suspended. Just diff the children like normal
            (None, false) => {
                let old_render_parent = dom.mounted_render_parent(last_rendered_node.root_mount());
                let new_mount = suspense_context.under_suspense_boundary(&dom.runtime(), || {
                    last_rendered_node
                        .mounted_vnode()
                        .diff_node(children.as_vnode(), dom, to)
                });
                if let Some(old_render_parent) = old_render_parent {
                    dom.set_mounted_render_parent(new_mount, old_render_parent);
                }

                set_rendered_children(dom, scope_id, children, new_mount);
            }
            // We have no suspended nodes, but we just became suspended. Move the children to the background
            (None, true) => {
                let old_children = last_rendered_node;
                let new_children: VNode = children.as_vnode().clone();

                let new_placeholder =
                    LastRenderedNode::new(fallback.call(suspense_context.clone()));

                // Move the children to the background
                let old_children_mount = old_children.root_mount();
                let parent = dom
                    .mounted_render_parent(old_children_mount)
                    .map(|parent| parent.parent());

                let placeholder_mount =
                    suspense_context.in_suspense_placeholder(&dom.runtime(), || {
                        let created = old_children.as_vnode().move_node_to_background(
                            old_children_mount,
                            new_placeholder.as_vnode(),
                            parent,
                            dom,
                            to.as_deref_mut(),
                        );
                        created.mount
                    });

                // Then diff the new children in the background
                set_suspense_mounts_render_mode(
                    dom,
                    old_children.as_vnode(),
                    old_children_mount,
                    RenderMode::Background,
                    false,
                );
                let new_children_mount =
                    suspense_context.under_suspense_boundary(&dom.runtime(), || {
                        old_children
                            .mounted_vnode()
                            .diff_node(&new_children, dom, None)
                    });
                flush_retained_branch_scopes(dom, scope_id);

                if suspense_context.suspended_futures().is_empty() {
                    let placeholder_output = MountedOutput::new(new_placeholder, placeholder_mount);
                    set_suspense_mounts_render_mode(
                        dom,
                        &new_children,
                        new_children_mount,
                        RenderMode::Foreground,
                        false,
                    );
                    suspense_context.under_suspense_boundary(&dom.runtime(), || {
                        new_children.remove_node_inner(new_children_mount, dom, None, false);
                        let mounted_children = dom
                            .current_mounted_view(new_children_mount)
                            .expect("suspense child");
                        replace_placeholder_with(
                            &placeholder_output,
                            MountedVNode::new(&mounted_children, new_children_mount),
                            dom,
                            to.as_deref_mut(),
                        );
                    });
                    set_rendered_children(
                        dom,
                        scope_id,
                        LastRenderedNode::Real(new_children),
                        new_children_mount,
                    );
                    mark_suspense_resolved(&suspense_context, dom, scope_id);
                } else {
                    let branch = SuspenseBranch::new(new_children, new_children_mount);
                    store_suspended_branch(dom, scope_id, &branch);
                    // Set the last rendered node to the new suspense placeholder
                    dom.scopes[scope_id.index()].last_rendered_node =
                        Some(MountedOutput::new(new_placeholder, placeholder_mount));
                    suspense_context.set_suspended_branch(branch);

                    un_resolve_suspense(dom, scope_id);
                }
            }
            // We have suspended nodes, but we just got out of suspense. Move the suspended nodes to the foreground
            (Some(_), false) => {
                // Take the suspended nodes out of the suspense boundary so the children know that the boundary is not suspended while diffing
                let old_suspended_branch = suspense_context.take_suspended_branch().unwrap();
                let old_suspended_mount = old_suspended_branch.root_mount();
                let old_suspended_nodes = old_suspended_branch.root();

                // First diff the two children nodes in the background
                let mut new_children_mount = old_suspended_mount;
                suspense_context.under_suspense_boundary(&dom.runtime(), || {
                    new_children_mount = MountedVNode::new(
                        &old_suspended_nodes,
                        old_suspended_mount,
                    )
                    .diff_node(children.as_vnode(), dom, None);
                    set_suspense_mounts_render_mode(
                        dom,
                        children.as_vnode(),
                        new_children_mount,
                        RenderMode::Foreground,
                        true,
                    );
                    let mounted_children = dom
                        .current_mounted_view(new_children_mount)
                        .expect("suspense child");
                    replace_placeholder_with(
                        &last_rendered_node,
                        MountedVNode::new(&mounted_children, new_children_mount),
                        dom,
                        to,
                    );
                });

                set_rendered_children(dom, scope_id, children, new_children_mount);

                mark_suspense_resolved(&suspense_context, dom, scope_id);
            }
        }
    })
}

fn flush_retained_branch_scopes(dom: &mut VirtualDom, scope_id: ScopeId) {
    while let Some(order) = dom.pop_dirty_descendant_scope(scope_id) {
        let dirty_scope = order.id;
        let run_scope = dom
            .runtime
            .try_get_state(dirty_scope)
            .filter(|scope| scope.should_run_during_suspense())
            .is_some();
        if run_scope {
            dom.runtime.clone().while_rendering(|| {
                dom.run_and_diff_scope(None, dirty_scope);
            });
        }
    }
}

fn set_rendered_children(
    dom: &mut VirtualDom,
    scope_id: ScopeId,
    children: LastRenderedNode,
    root_mount: MountId,
) {
    store_suspense_children(dom, scope_id, &children);
    dom.scopes[scope_id.index()].last_rendered_node =
        Some(MountedOutput::new(children, root_mount));
    dom.runtime
        .get_state(scope_id)
        .set_root_mount(Some(root_mount));
}

fn store_suspended_branch(dom: &mut VirtualDom, scope_id: ScopeId, branch: &SuspenseBranch) {
    set_suspense_mounts_render_mode(
        dom,
        &branch.root(),
        branch.root_mount(),
        RenderMode::Background,
        false,
    );
    store_suspense_children(dom, scope_id, &LastRenderedNode::Real(branch.root()));
}

fn replace_placeholder_with(
    placeholder: &MountedOutput,
    children: MountedVNode<'_>,
    dom: &mut VirtualDom,
    to: Option<&mut (dyn WriteMutations + '_)>,
) {
    // Invariant: `placeholder` is the currently visible fallback and `children` is the already
    // materialized retained branch.
    let placeholder_mount = placeholder.root_mount();
    let parent = dom
        .mounted_render_parent(placeholder_mount)
        .map(|parent| parent.parent());
    let mut to = to.filter(|_| dom.mount_should_render(placeholder_mount));
    dom.copy_render_parent_slot(placeholder_mount, children.mount());
    // Promote the already-materialized retained branch by reusing its mount (and
    // scope subtree) instead of rebuilding it, so component state and scope ids
    // survive the fallback -> children swap.
    if let Some(to) = to.as_deref_mut() {
        let site = insertion_site_at(placeholder.mounted_vnode(), dom, None);
        site.create_and_place_with_result(to, dom.runtime.clone(), |to| {
            let created = children.vnode().recreate_with_mount(
                dom,
                children.mount(),
                parent,
                parent,
                Some(to),
            );
            (created.nodes, created)
        });
    } else {
        children
            .vnode()
            .recreate_with_mount(dom, children.mount(), parent, parent, None);
    }
    placeholder
        .as_vnode()
        .remove_node(placeholder_mount, dom, to);
}

/// Move to a resolved suspense state
fn mark_suspense_resolved(
    suspense_context: &SuspenseContext,
    dom: &mut VirtualDom,
    scope_id: ScopeId,
) {
    dom.resolved_scopes.push(scope_id);
    // Run any closures that were waiting for the suspense to resolve
    suspense_context.run_resolved_closures(&dom.runtime);
}

fn set_suspense_mounts_render_mode(
    dom: &mut VirtualDom,
    vnode: &VNode,
    mount: MountId,
    mode: RenderMode,
    rerun_dirty_scopes: bool,
) {
    // Invariant: the retained suspense branch mode is subtree-wide.
    dom.set_mount_mode(mount, mode);

    for anchor in vnode.dynamic_anchors() {
        for slot in anchor.nodes() {
            let idx = slot.index();
            match &*slot {
                DynamicNode::Component(_) => {
                    let scope_id = dom.unchecked_mounted_dynamic_component_scope(mount, idx);
                    if rerun_dirty_scopes && dom.mark_clean(scope_id) {
                        dom.run_and_diff_scope(None, scope_id);
                    }

                    let rendered = dom.scopes[scope_id.index()]
                        .last_rendered_node
                        .clone()
                        .expect("scope output");
                    set_suspense_mounts_render_mode(
                        dom,
                        rendered.as_vnode(),
                        rendered.root_mount(),
                        mode,
                        rerun_dirty_scopes,
                    );
                }
                DynamicNode::Fragment(nodes) => {
                    let mounts = dom.mounted_fragment_children_exact(mount, idx, nodes.len());
                    for (node, mount) in nodes.iter().zip(mounts) {
                        set_suspense_mounts_render_mode(dom, node, mount, mode, rerun_dirty_scopes);
                    }
                }
                DynamicNode::Text(_) => {}
            }
        }
    }
}

/// Move from a resolved suspense state to an suspended state
fn un_resolve_suspense(dom: &mut VirtualDom, scope_id: ScopeId) {
    dom.resolved_scopes.retain(|&id| id != scope_id);
}

impl SuspenseContext {
    /// Run a closure under a suspense boundary
    pub(crate) fn under_suspense_boundary<O>(&self, runtime: &Runtime, f: impl FnOnce() -> O) -> O {
        runtime.with_suspense_location(SuspenseLocation::UnderSuspense(self.clone()), f)
    }

    /// Run a closure under a suspense placeholder
    pub(crate) fn in_suspense_placeholder<O>(&self, runtime: &Runtime, f: impl FnOnce() -> O) -> O {
        runtime.with_suspense_location(SuspenseLocation::InSuspensePlaceholder(self.clone()), f)
    }

    /// Try to get a suspense boundary from a scope id
    pub fn downcast_suspense_boundary_from_scope(
        runtime: &Runtime,
        scope_id: ScopeId,
    ) -> Option<Self> {
        runtime.try_get_state(scope_id)?.suspense_boundary()
    }

    pub(crate) fn remove_suspended_nodes(
        dom: &mut VirtualDom,
        scope_id: ScopeId,
        destroy_component_state: bool,
    ) {
        if let Some(scope) = Self::downcast_suspense_boundary_from_scope(&dom.runtime, scope_id)
            && let Some(branch) = scope.take_suspended_branch()
        {
            let mount = branch.root_mount();
            branch
                .into_root()
                .remove_node_inner(mount, dom, None, destroy_component_state)
        }
    }
}