Skip to main content

waft_widgets/framework/
build_owner.rs

1//! `BuildScope`, `BuildOwner`, and the inactive-element list.
2
3use std::collections::{HashMap, HashSet};
4
5use waft_foundation::{App, Handle, Listener, ValueChanged};
6
7use super::element::{AnyElement, ElementLifecycle};
8use super::widget::GlobalKey;
9use crate::widgets::focus_manager::FocusManager;
10use waft_foundation::Ref;
11
12/// A class that determines the scope of a `BuildOwner::build_scope` operation.
13///
14/// The `BuildOwner::build_scope` method rebuilds all dirty `Element`s who share the same
15/// [`BuildScope`] with its `context` argument, and skips those with a different
16/// `Element::build_scope`.
17///
18/// `Element`s by default have the same [`BuildScope`] as their parents. Special `Element`s
19/// may override `Element::build_scope` to create an isolated build scope for its descendants.
20/// The `LayoutBuilder` widget, for example, establishes its own [`BuildScope`] such that no
21/// descendant `Element`s may rebuild prematurely until the incoming constraints are known.
22pub struct BuildScope {
23    build_scheduled: bool,
24    building: bool,
25    /// An optional `VoidCallback` that will be called when `Element`s in this [`BuildScope`]
26    /// are marked as dirty for the first time.
27    ///
28    /// This callback usually signifies that the `BuildOwner::build_scope` method must be
29    /// called at a later time in this frame to rebuild dirty elements in this
30    /// [`BuildScope`]. It will **not** be called if this scope is actively being built by
31    /// `BuildOwner::build_scope`, since the [`BuildScope`] will be clean when
32    /// `BuildOwner::build_scope` returns.
33    schedule_rebuild: Option<Listener>,
34    /// Whether `dirty_elements` need to be sorted again as a result of more elements
35    /// becoming dirty during the build.
36    ///
37    /// This is necessary to preserve the sort order defined by `Element::sort`.
38    ///
39    /// This field is set to `None` when `BuildOwner::build_scope` is not actively rebuilding
40    /// the widget tree.
41    dirty_elements_needs_resorting: Option<bool>,
42    dirty_elements: Vec<AnyElement>,
43}
44
45impl BuildScope {
46    /// Creates a [`BuildScope`] with an optional `schedule_rebuild` callback.
47    pub fn new(app: &mut App, schedule_rebuild: Option<Listener>) -> Ref<BuildScope> {
48        app.create(BuildScope {
49            build_scheduled: false,
50            building: false,
51            schedule_rebuild,
52            dirty_elements_needs_resorting: None,
53            dirty_elements: Vec::new(),
54        })
55    }
56
57    /// The elements marked dirty in this scope, in scheduling order.
58    pub fn dirty_elements(self: Handle<Self>, app: &App) -> &[AnyElement] {
59        &app.get(self).dirty_elements
60    }
61
62    pub(crate) fn schedule_build_for(self: Handle<Self>, app: &mut App, element: AnyElement) {
63        debug_assert!(element.build_scope(app) == self);
64        if !element.in_dirty_list(app) {
65            app.get_mut(self).dirty_elements.push(element);
66            element.data_mut(app).in_dirty_list = true;
67        }
68        let scope = app.get(self);
69        if !scope.build_scheduled && !scope.building {
70            app.get_mut(self).build_scheduled = true;
71            if let Some(schedule_rebuild) = app.get(self).schedule_rebuild.clone() {
72                schedule_rebuild.call(app);
73            }
74        }
75        if app.get(self).dirty_elements_needs_resorting.is_some() {
76            app.get_mut(self).dirty_elements_needs_resorting = Some(true);
77        }
78    }
79
80    fn try_rebuild(self: Handle<Self>, app: &mut App, element: AnyElement) {
81        debug_assert!(element.in_dirty_list(app));
82        debug_assert!(element.build_scope(app) == self);
83        element.rebuild(app, false);
84    }
85
86    fn debug_assert_element_in_scope(
87        app: &App,
88        element: AnyElement,
89        debug_build_root: AnyElement,
90    ) -> bool {
91        let is_in_scope =
92            element.debug_is_descendant_of(app, debug_build_root) || !element.debug_is_active(app);
93        assert!(
94            is_in_scope,
95            "Tried to build dirty widget in the wrong build scope. A widget which was marked \
96             as dirty and is still active was scheduled to be built, but the current build \
97             scope unexpectedly does not contain that widget."
98        );
99        true
100    }
101
102    /// Rebuilds every dirty element of this scope, in depth order, resorting when a rebuild
103    /// dirties more.
104    pub(crate) fn flush_dirty_elements(
105        self: Handle<Self>,
106        app: &mut App,
107        debug_build_root: AnyElement,
108    ) {
109        debug_assert!(
110            app.get(self).dirty_elements_needs_resorting.is_none(),
111            "_flushDirtyElements must be non-reentrant"
112        );
113        sort_dirty_elements(app, self);
114        app.get_mut(self).dirty_elements_needs_resorting = Some(false);
115        let mut index = 0;
116        while index < app.get(self).dirty_elements.len() {
117            let element = app.get(self).dirty_elements[index];
118            if element.build_scope(app) == self {
119                debug_assert!(BuildScope::debug_assert_element_in_scope(
120                    app,
121                    element,
122                    debug_build_root
123                ));
124                self.try_rebuild(app, element);
125            }
126            index = self.dirty_element_index_after(app, index);
127        }
128        if cfg!(debug_assertions) {
129            let missed: Vec<AnyElement> = app
130                .get(self)
131                .dirty_elements
132                .iter()
133                .copied()
134                .filter(|element| {
135                    element.debug_is_active(app)
136                        && element.dirty(app)
137                        && element.build_scope(app) == self
138                })
139                .collect();
140            assert!(
141                missed.is_empty(),
142                "buildScope missed some dirty elements. This probably indicates that the \
143                 dirty list should have been resorted but was not: {missed:?}"
144            );
145        }
146        let dirty_elements = std::mem::take(&mut app.get_mut(self).dirty_elements);
147        for element in dirty_elements {
148            if element.build_scope(app) == self {
149                element.data_mut(app).in_dirty_list = false;
150            }
151        }
152        let scope = app.get_mut(self);
153        scope.dirty_elements_needs_resorting = None;
154        scope.build_scheduled = false;
155    }
156
157    fn dirty_element_index_after(self: Handle<Self>, app: &mut App, index: usize) -> usize {
158        if app.get(self).dirty_elements_needs_resorting != Some(true) {
159            return index + 1;
160        }
161        let mut index = index + 1;
162        sort_dirty_elements(app, self);
163        app.get_mut(self).dirty_elements_needs_resorting = Some(false);
164        while index > 0 && app.get(self).dirty_elements[index - 1].dirty(app) {
165            index -= 1;
166        }
167        if cfg!(debug_assertions) {
168            for i in (0..index).rev() {
169                let element = app.get(self).dirty_elements[i];
170                debug_assert!(
171                    !element.dirty(app) || element.lifecycle(app) != ElementLifecycle::Active
172                );
173            }
174        }
175        index
176    }
177
178    pub(crate) fn set_building(self: Handle<Self>, app: &mut App, building: bool) {
179        app.get_mut(self).building = building;
180    }
181}
182
183/// Dart's `_dirtyElements.sort(Element._sort)`: by depth, dirty last within a depth.
184fn sort_dirty_elements(app: &mut App, scope: Handle<BuildScope>) {
185    let mut keyed: Vec<(u32, bool, AnyElement)> = app
186        .get(scope)
187        .dirty_elements
188        .iter()
189        .map(|element| (element.depth(app), element.dirty(app), *element))
190        .collect();
191    keyed.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
192    app.get_mut(scope).dirty_elements = keyed.into_iter().map(|(_, _, element)| element).collect();
193}
194
195/// The elements removed from the tree during this frame, waiting to be reactivated by a
196/// global key or unmounted by `BuildOwner::finalize_tree`.
197#[derive(Default)]
198struct InactiveElements {
199    locked: bool,
200    elements: HashSet<AnyElement>,
201}
202
203/// The callback `BuildOwner::build_scope` runs before building the dirty elements.
204pub type BuildScopeCallback = Box<dyn FnOnce(&mut App)>;
205
206/// Dart's `onBuildScheduled`, given the element marked dirty.
207pub type BuildScheduledCallback = ValueChanged<AnyElement>;
208
209/// Manager class for the widgets framework.
210///
211/// This class tracks which widgets need rebuilding, and handles other tasks that apply to
212/// widget trees as a whole, such as managing the inactive element list for the tree and
213/// triggering the "reassemble" command when necessary during hot reload when debugging.
214///
215/// The main build owner is typically owned by the `WidgetsBinding`, and is driven from the
216/// operating system along with the rest of the build/layout/paint pipeline.
217///
218/// Additional build owners can be built to manage off-screen widget trees.
219///
220/// To assign a build owner to a tree, use the `RootElementMixin::assign_owner` method on the
221/// root element of the widget tree.
222pub struct BuildOwner {
223    /// Called for each element marked dirty outside a build pass.
224    on_build_scheduled: Option<BuildScheduledCallback>,
225    focus_manager: Ref<FocusManager>,
226    inactive_elements: InactiveElements,
227    /// [`build_scope`](Self::build_scope) is running: it builds the elements marked dirty
228    /// meanwhile, so none is scheduled.
229    in_build_scope: bool,
230    global_key_registry: HashMap<GlobalKey, AnyElement>,
231    debug_state_lock_level: i32,
232    debug_building: bool,
233    debug_current_build_target: Option<AnyElement>,
234}
235
236impl BuildOwner {
237    /// Creates an object that manages widgets.
238    ///
239    /// This constructs a new [`FocusManager`] and registers its global input handlers via
240    /// [`FocusManager::register_global_handlers`], which will modify static state. Callers
241    /// wishing to avoid altering this state can explicitly pass a focus manager to
242    /// [`with_focus_manager`](Self::with_focus_manager), Dart's `focusManager` argument.
243    pub fn new(
244        app: &mut App,
245        on_build_scheduled: Option<BuildScheduledCallback>,
246    ) -> Ref<BuildOwner> {
247        let focus_manager = FocusManager::new(app);
248        focus_manager.register_global_handlers(app);
249        BuildOwner::with_focus_manager(app, on_build_scheduled, focus_manager)
250    }
251
252    /// Creates an object that manages widgets, with the [`FocusManager`] Dart's `focusManager`
253    /// argument supplies; its global input handlers are not registered.
254    pub fn with_focus_manager(
255        app: &mut App,
256        on_build_scheduled: Option<BuildScheduledCallback>,
257        focus_manager: Ref<FocusManager>,
258    ) -> Ref<BuildOwner> {
259        app.create(BuildOwner {
260            on_build_scheduled,
261            focus_manager,
262            inactive_elements: InactiveElements::default(),
263            in_build_scope: false,
264            global_key_registry: HashMap::new(),
265            debug_state_lock_level: 0,
266            debug_building: false,
267            debug_current_build_target: None,
268        })
269    }
270
271    /// The object in charge of the focus tree.
272    ///
273    /// Rarely used directly. Instead, consider using `FocusScope::of` to obtain the
274    /// `FocusScopeNode` for a given `BuildContext`.
275    pub fn focus_manager(self: Handle<Self>, app: &App) -> Handle<FocusManager> {
276        app.get(self).focus_manager.handle()
277    }
278
279    /// Replaces the object in charge of the focus tree (Dart's mutable `focusManager` field).
280    pub fn set_focus_manager(self: Handle<Self>, app: &mut App, focus_manager: Ref<FocusManager>) {
281        app.get_mut(self).focus_manager = focus_manager;
282    }
283
284    /// Replaces the `on_build_scheduled` callback.
285    pub fn set_on_build_scheduled(
286        self: Handle<Self>,
287        app: &mut App,
288        callback: Option<BuildScheduledCallback>,
289    ) {
290        app.get_mut(self).on_build_scheduled = callback;
291    }
292
293    /// Adds an element to the dirty elements list so that it will be rebuilt when
294    /// `WidgetsBinding::draw_frame` calls [`build_scope`](Self::build_scope).
295    pub fn schedule_build_for(self: Handle<Self>, app: &mut App, element: AnyElement) {
296        debug_assert!(element.owner(app) == Some(self));
297        debug_assert!(element.data(app).parent_build_scope.is_some());
298        debug_assert!(
299            element.dirty(app),
300            "scheduleBuildFor() called for a widget that is not marked as dirty."
301        );
302        let build_scope = element.build_scope(app);
303        debug_assert!(
304            app.get(self).debug_building || !element.in_dirty_list(app),
305            "BuildOwner.scheduleBuildFor() called on an Element that is already in the dirty \
306             list."
307        );
308        if !app.get(self).in_build_scope
309            && let Some(on_build_scheduled) = app.get(self).on_build_scheduled.clone()
310        {
311            on_build_scheduled(app, element);
312        }
313        build_scope.schedule_build_for(app, element);
314    }
315
316    pub(crate) fn debug_state_locked(self: Handle<Self>, app: &App) -> bool {
317        app.get(self).debug_state_lock_level > 0
318    }
319
320    /// Whether this widget tree is in the build phase.
321    ///
322    /// Only valid when asserts are enabled.
323    pub fn debug_building(self: Handle<Self>, app: &App) -> bool {
324        app.get(self).debug_building
325    }
326
327    pub(crate) fn debug_current_build_target(self: Handle<Self>, app: &App) -> Option<AnyElement> {
328        app.get(self).debug_current_build_target
329    }
330
331    pub(crate) fn set_debug_current_build_target(
332        self: Handle<Self>,
333        app: &mut App,
334        target: Option<AnyElement>,
335    ) {
336        app.get_mut(self).debug_current_build_target = target;
337    }
338
339    /// Establishes a scope in which calls to `State::set_state` are forbidden, and calls the
340    /// given `callback`.
341    ///
342    /// This mechanism is used to ensure that, for instance, `State::dispose` does not call
343    /// `State::set_state`.
344    pub fn lock_state(self: Handle<Self>, app: &mut App, callback: impl FnOnce(&mut App)) {
345        debug_assert!(app.get(self).debug_state_lock_level >= 0);
346        if cfg!(debug_assertions) {
347            app.get_mut(self).debug_state_lock_level += 1;
348        }
349        callback(app);
350        if cfg!(debug_assertions) {
351            app.get_mut(self).debug_state_lock_level -= 1;
352        }
353        debug_assert!(app.get(self).debug_state_lock_level >= 0);
354    }
355
356    /// Establishes a scope for updating the widget tree, and calls the given `callback`, if
357    /// any. Then, builds all the elements that were marked as dirty using
358    /// [`schedule_build_for`](Self::schedule_build_for), in depth order.
359    ///
360    /// This mechanism prevents build methods from transitively requiring other build methods
361    /// to run, potentially causing infinite loops.
362    ///
363    /// The dirty list is processed after `callback` returns, building all the elements that
364    /// were marked as dirty using [`schedule_build_for`](Self::schedule_build_for), in depth
365    /// order. If elements are marked as dirty while this method is running, they must be
366    /// deeper than the `context` node, and deeper than any previously-built node in this
367    /// pass.
368    ///
369    /// To flush the current dirty list without performing any other work, this function can
370    /// be called with no callback. This is what the framework does each frame, in
371    /// `WidgetsBinding::draw_frame`.
372    ///
373    /// Only one [`build_scope`](Self::build_scope) can be active at a time.
374    ///
375    /// A [`build_scope`](Self::build_scope) implies a [`lock_state`](Self::lock_state) scope
376    /// as well.
377    pub fn build_scope(
378        self: Handle<Self>,
379        app: &mut App,
380        context: AnyElement,
381        callback: Option<BuildScopeCallback>,
382    ) {
383        let build_scope = context.build_scope(app);
384        if callback.is_none() && app.get(build_scope).dirty_elements.is_empty() {
385            return;
386        }
387        debug_assert!(app.get(self).debug_state_lock_level >= 0);
388        debug_assert!(!app.get(self).debug_building);
389        if cfg!(debug_assertions) {
390            let owner = app.get_mut(self);
391            owner.debug_state_lock_level += 1;
392            owner.debug_building = true;
393        }
394        app.get_mut(self).in_build_scope = true;
395        build_scope.set_building(app, true);
396        if let Some(callback) = callback {
397            debug_assert!(self.debug_state_locked(app));
398            let debug_previous_build_target = self.debug_current_build_target(app);
399            if cfg!(debug_assertions) {
400                self.set_debug_current_build_target(app, Some(context));
401            }
402            callback(app);
403            if cfg!(debug_assertions) {
404                debug_assert!(self.debug_current_build_target(app) == Some(context));
405                self.set_debug_current_build_target(app, debug_previous_build_target);
406            }
407        }
408        build_scope.flush_dirty_elements(app, context);
409        build_scope.set_building(app, false);
410        app.get_mut(self).in_build_scope = false;
411        debug_assert!(app.get(self).debug_building);
412        if cfg!(debug_assertions) {
413            let owner = app.get_mut(self);
414            owner.debug_building = false;
415            owner.debug_state_lock_level -= 1;
416        }
417        debug_assert!(app.get(self).debug_state_lock_level >= 0);
418    }
419
420    /// The number of `GlobalKey` instances that are currently associated with `Element`s
421    /// that have been built by this build owner.
422    pub fn global_key_count(self: Handle<Self>, app: &App) -> usize {
423        app.get(self).global_key_registry.len()
424    }
425
426    pub(crate) fn register_global_key(
427        self: Handle<Self>,
428        app: &mut App,
429        key: &GlobalKey,
430        element: AnyElement,
431    ) {
432        if cfg!(debug_assertions)
433            && let Some(old_element) = app.get(self).global_key_registry.get(key).copied()
434        {
435            debug_assert!(
436                element.widget(app).widget_type() != old_element.widget(app).widget_type(),
437                "Multiple widgets used the same GlobalKey: {key:?}"
438            );
439        }
440        app.get_mut(self)
441            .global_key_registry
442            .insert(key.clone(), element);
443    }
444
445    pub(crate) fn unregister_global_key(
446        self: Handle<Self>,
447        app: &mut App,
448        key: &GlobalKey,
449        element: AnyElement,
450    ) {
451        if app.get(self).global_key_registry.get(key) == Some(&element) {
452            app.get_mut(self).global_key_registry.remove(key);
453        }
454    }
455
456    /// The element registered under a global key, if any.
457    pub fn global_key_element(
458        self: Handle<Self>,
459        app: &App,
460        key: &GlobalKey,
461    ) -> Option<AnyElement> {
462        app.get(self).global_key_registry.get(key).copied()
463    }
464
465    // ---- the inactive-element list (Dart's `_InactiveElements`) ----
466
467    pub(crate) fn inactive_add(self: Handle<Self>, app: &mut App, element: AnyElement) {
468        debug_assert!(!app.get(self).inactive_elements.locked);
469        debug_assert!(!app.get(self).inactive_elements.elements.contains(&element));
470        debug_assert!(element.parent(app).is_none());
471        match element.lifecycle(app) {
472            ElementLifecycle::Active => {
473                deactivate_recursively(app, element);
474                app.get_mut(self).inactive_elements.elements.insert(element);
475            }
476            ElementLifecycle::Inactive => {
477                app.get_mut(self).inactive_elements.elements.insert(element);
478            }
479            state @ (ElementLifecycle::Initial
480            | ElementLifecycle::Failed
481            | ElementLifecycle::Defunct) => {
482                panic!("{element:?} must not be deactivated when in {state:?} state.");
483            }
484        }
485    }
486
487    pub(crate) fn inactive_remove(self: Handle<Self>, app: &mut App, element: AnyElement) {
488        debug_assert!(!app.get(self).inactive_elements.locked);
489        debug_assert!(app.get(self).inactive_elements.elements.contains(&element));
490        debug_assert!(element.parent(app).is_none());
491        app.get_mut(self)
492            .inactive_elements
493            .elements
494            .remove(&element);
495        debug_assert!(element.lifecycle(app) == ElementLifecycle::Inactive);
496    }
497
498    /// Whether `element` is on the inactive list; for tests.
499    pub fn debug_inactive_contains(self: Handle<Self>, app: &App, element: AnyElement) -> bool {
500        app.get(self).inactive_elements.elements.contains(&element)
501    }
502
503    fn inactive_unmount_all(self: Handle<Self>, app: &mut App) {
504        app.get_mut(self).inactive_elements.locked = true;
505        let mut elements: Vec<AnyElement> = app
506            .get_mut(self)
507            .inactive_elements
508            .elements
509            .drain()
510            .collect();
511        let mut keyed: Vec<(u32, bool, AnyElement)> = elements
512            .drain(..)
513            .map(|element| (element.depth(app), element.dirty(app), element))
514            .collect();
515        keyed.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
516        for (_, _, element) in keyed.into_iter().rev() {
517            unmount_recursively(app, element);
518        }
519        debug_assert!(app.get(self).inactive_elements.elements.is_empty());
520        app.get_mut(self).inactive_elements.locked = false;
521    }
522
523    /// Complete the element build pass by unmounting any elements that are no longer active.
524    ///
525    /// This is called by `WidgetsBinding::draw_frame`.
526    ///
527    /// In debug mode, this also runs some sanity checks, for example checking for duplicate
528    /// global keys.
529    pub fn finalize_tree(self: Handle<Self>, app: &mut App) {
530        self.lock_state(app, |app| self.inactive_unmount_all(app));
531    }
532}
533
534/// Dart's `_unmount`: unmounts `element`'s subtree, children before their parent.
535///
536/// A loop over a stack rather than recursion, as the other whole-subtree walks here: a walk
537/// down a deep tree costs a call per level, and Safari's wasm stack is about a megabyte.
538fn unmount_recursively(app: &mut App, element: AnyElement) {
539    let mut stack = vec![Walk::Enter(element)];
540    while let Some(step) = stack.pop() {
541        match step {
542            Walk::Enter(element) => {
543                debug_assert!(element.lifecycle(app) == ElementLifecycle::Inactive);
544                stack.push(Walk::Leave(element));
545                for child in element.children(app).into_iter().rev() {
546                    debug_assert!(child.parent(app) == Some(element));
547                    stack.push(Walk::Enter(child));
548                }
549            }
550            Walk::Leave(element) => {
551                element.unmount(app);
552                debug_assert!(element.lifecycle(app) == ElementLifecycle::Defunct);
553                // Dart drops a defunct element. A handle to it kept past this frame (a callback's
554                // `BuildContext`) still reads it until the next checkpoint, then finds it
555                // unmounted.
556                app.release_tree_node(element.id());
557            }
558        }
559    }
560}
561
562/// Dart's `_deactivateRecursively`: deactivates `element`, then its children; in a debug build
563/// each element checks its deactivation once its children are done. A loop, as
564/// [`unmount_recursively`].
565fn deactivate_recursively(app: &mut App, element: AnyElement) {
566    let mut stack = vec![Walk::Enter(element)];
567    while let Some(step) = stack.pop() {
568        match step {
569            Walk::Enter(element) => {
570                debug_assert!(element.lifecycle(app) == ElementLifecycle::Active);
571                element.deactivate(app);
572                stack.push(Walk::Leave(element));
573                for child in element.children(app).into_iter().rev() {
574                    stack.push(Walk::Enter(child));
575                }
576            }
577            Walk::Leave(element) => {
578                if cfg!(debug_assertions) {
579                    element.debug_deactivated(app);
580                }
581            }
582        }
583    }
584}
585
586/// A step of a subtree walk: an element reached on the way down, or left once its children are
587/// done.
588enum Walk {
589    Enter(AnyElement),
590    Leave(AnyElement),
591}
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596    use crate::{ElementBase, IntoWidget, SingleChildRenderObjectElement, SizedBox};
597    use waft_foundation::AppCell;
598
599    /// A rebuild can leave clean and dirty siblings at the same depth before a resort.
600    #[test]
601    fn dirty_scope_resort_keeps_clean_siblings_before_pending_builds() {
602        let cell = AppCell::new();
603        let mut app = cell.borrow_mut();
604        let widget = SizedBox::shrink().into_widget();
605        let pending = widget.create_element(&mut app, widget.clone());
606        let cleaned = widget.create_element(&mut app, widget.clone());
607        let focus = FocusManager::new(&mut app);
608        let owner = BuildOwner::with_focus_manager(&mut app, None, focus);
609        for element in [pending, cleaned] {
610            element.assign_owner(&mut app, owner.handle());
611            let handle = element
612                .downcast::<SingleChildRenderObjectElement>(&app)
613                .unwrap();
614            ElementBase::mount(handle, &mut app, None, None);
615        }
616        pending.set_dirty(&mut app, true);
617        cleaned.set_dirty(&mut app, false);
618        let scope = BuildScope::new(&mut app, None);
619        app.get_mut(&scope).dirty_elements = vec![pending, cleaned];
620        app.get_mut(&scope).dirty_elements_needs_resorting = Some(true);
621        let next = scope.dirty_element_index_after(&mut app, 0);
622        assert_eq!(app.get(&scope).dirty_elements, [cleaned, pending]);
623        assert_eq!(
624            next, 1,
625            "the resume index must point after the last clean sibling"
626        );
627        assert!(app.get(&scope).dirty_elements[next].dirty(&app));
628    }
629}