Skip to main content

cranpose_core/
composer.rs

1use std::{
2    any::Any,
3    cell::{Cell, RefCell, RefMut},
4    hash::Hash,
5    marker::PhantomData,
6    rc::{Rc, Weak},
7};
8
9use smallvec::SmallVec;
10
11use crate::{
12    AnchorId, Applier, ApplierGuard, ApplierHost, COMMAND_FLUSH_THRESHOLD, Command, CommandQueue,
13    CompositionLocal, ComputedLocalEntry, DirtyBubble, Key, LocalKey, LocalStackSnapshot,
14    LocalStateEntry, MutableState, Node, NodeError, NodeId, Owned, ProvidedValue, RecomposeOptions,
15    RecomposeScope, RecomposeScopeInner, RecycledNode, RetentionMode, RuntimeHandle, ScopeId,
16    SlotId, SlotPassOutcome, SlotTable, SlotsHost, SnapshotStateList, SnapshotStateMap,
17    StaticCompositionLocal, SubcomposeState, composer_context,
18    retention::RetainKey,
19    runtime,
20    slot::{FinishGroupResult, GroupStart, GroupStartKind, PayloadKind, RootNodeIds, ValueSlotId},
21};
22
23mod composable_group;
24mod parent_frame;
25mod runtime_state;
26mod scope_frame;
27mod subcompose_slot;
28pub use composable_group::{ComposableGroup, ParameterChange};
29use parent_frame::{InitialParentFrame, push_root_frame};
30pub(crate) use parent_frame::{ParentAttachMode, ParentFrame};
31pub(crate) use runtime_state::ComposerRuntimeState;
32pub(crate) use scope_frame::ScopeFrame;
33use subcompose_slot::{measure_slot_state, subcompose_slot_at};
34
35/// A typed reference to a value stored in a slot, made by `Composer::use_value_slot`. It is valid
36/// for the composition pass that made it, and `Composer::with_slot_value` reads through it.
37pub struct ValueSlotHandle<'pass, T: 'static> {
38    slot: ValueSlotId,
39    record: Option<usize>,
40    _pass: PhantomData<&'pass Composer>,
41    _value: PhantomData<fn() -> T>,
42}
43
44impl<T: 'static> Copy for ValueSlotHandle<'_, T> {}
45
46impl<T: 'static> Clone for ValueSlotHandle<'_, T> {
47    fn clone(&self) -> Self {
48        *self
49    }
50}
51
52impl<T: 'static> ValueSlotHandle<'_, T> {
53    pub(crate) fn new(slot: ValueSlotId, record: Option<usize>) -> Self {
54        Self {
55            slot,
56            record,
57            _pass: PhantomData,
58            _value: PhantomData,
59        }
60    }
61}
62
63fn slots_storage_key(host: &Rc<SlotsHost>) -> usize {
64    host.storage_key()
65}
66
67fn bind_slots_host_to_runtime_state(
68    state: &Rc<ComposerRuntimeState>,
69    host: &Rc<SlotsHost>,
70) -> Rc<SlotsHost> {
71    // A host bound to `state` is in its registry: whatever drops the entry
72    // also unbinds the host, so binding it again would change nothing.
73    if host.runtime_state_ptr() == Some(Rc::as_ptr(state)) {
74        debug_assert!(
75            state
76                .host_for_storage_key(host.storage_key())
77                .is_some_and(|registered| Rc::ptr_eq(&registered, host)),
78            "a slot host bound to a runtime state must be in its registry"
79        );
80        return Rc::clone(host);
81    }
82    if host.runtime_state().is_some() {
83        if host.rebind_orphaned_runtime_state(state) {
84            state.bind_slots_host(host);
85            return Rc::clone(host);
86        }
87        log::error!(
88            "slot host already belongs to a different composer runtime state; using a fresh slot host"
89        );
90        let replacement = Rc::new(SlotsHost::new(SlotTable::new()));
91        state.bind_slots_host(&replacement);
92        return replacement;
93    }
94    state.bind_slots_host(host);
95    Rc::clone(host)
96}
97
98struct GroupEntry {
99    key: crate::slot::GroupKey,
100    /// Boxed: a restore is rare, and the entry moves on every call.
101    restored: Option<Box<crate::slot::DetachedSubtree>>,
102    placeholder_for: Option<crate::slot::GroupKey>,
103}
104
105struct GroupScopeEntry<'a> {
106    options: RecomposeOptions,
107    start_kind: GroupStartKind,
108    host: &'a SlotsHost,
109    group: crate::slot::ActiveGroupId,
110    parent_hint: Option<NodeId>,
111}
112
113struct SlotHostPassGuard {
114    core: Rc<ComposerCore>,
115    host: Rc<SlotsHost>,
116    /// The branch fold depth the pass began at.
117    fold_base: usize,
118    active: bool,
119}
120
121impl SlotHostPassGuard {
122    fn close(&mut self) {
123        if !self.active {
124            return;
125        }
126        if self.host.has_active_pass() {
127            self.host.abandon_active_pass();
128        }
129        match self.core.slot_hosts.borrow_mut().pop() {
130            Some(host) if Rc::ptr_eq(&host, &self.host) => {}
131            Some(_) => {
132                log::error!("slot host stack mismatch while closing slot host pass");
133            }
134            None => {
135                log::error!("slot host stack underflow while closing slot host pass");
136            }
137        }
138        self.core.branch_folds.end_pass(self.fold_base);
139        self.active = false;
140    }
141}
142
143impl Drop for SlotHostPassGuard {
144    fn drop(&mut self) {
145        self.close();
146    }
147}
148
149pub(crate) struct PendingMovable {
150    pub(crate) key: crate::slot::GroupKey,
151    pub(crate) placeholder: AnchorId,
152    pub(crate) parent_scope: Option<Weak<RecomposeScopeInner>>,
153}
154
155fn reparent_restored_scopes(
156    host: &SlotsHost,
157    group: crate::slot::ActiveGroupId,
158    old_hint: Option<NodeId>,
159    parent_hint: Option<NodeId>,
160) {
161    host.with_write_session(|slots| {
162        slots.for_each_subtree_scope(group, |scope| {
163            if scope.parent_hint() == old_hint {
164                scope.set_parent_hint(parent_hint);
165            }
166            scope.reactivate();
167        });
168    });
169}
170
171fn movable_retain_key(id: Key) -> RetainKey {
172    RetainKey::for_group(
173        None,
174        crate::slot::GroupKey::new(crate::slot::MOVABLE_STATIC_KEY, Some(id), 0),
175    )
176}
177
178/// How many applied command queues a thread keeps for its passes.
179const SPARE_COMMAND_QUEUES: usize = 8;
180
181/// The most commands a kept queue has room for. A larger one grew in a
182/// spike such as the first composition, and keeping it would hold its memory.
183const SPARE_COMMAND_CAPACITY: usize = 1024;
184
185fn spare_commands() -> CommandQueue {
186    crate::thread_state::try_runtimes(|state| state.spare_commands.borrow_mut().pop())
187        .flatten()
188        .unwrap_or_default()
189}
190
191/// The stacks a composer grows while it composes, kept empty between passes
192/// so the next composer on this thread starts with their storage.
193#[derive(Default)]
194pub(crate) struct ComposerStacks {
195    slot_hosts: Vec<Rc<SlotsHost>>,
196    parent_stack: Vec<ParentFrame>,
197    scope_stack: Vec<ScopeFrame>,
198}
199
200/// The most entries a kept stack has room for; a larger one grew in a spike
201/// such as a deep first composition.
202const SPARE_STACK_CAPACITY: usize = 256;
203
204fn spare_composer_stacks() -> ComposerStacks {
205    crate::thread_state::try_runtimes(|state| state.spare_composer_stacks.take())
206        .flatten()
207        .unwrap_or_default()
208}
209
210impl ComposerStacks {
211    fn holds_storage(&self) -> bool {
212        self.slot_hosts.capacity() > 0
213            || self.parent_stack.capacity() > 0
214            || self.scope_stack.capacity() > 0
215    }
216}
217
218/// Keeps a dropped composer's emptied stacks for the next composer.
219fn recycle_composer_stacks(mut stacks: ComposerStacks) {
220    let ComposerStacks {
221        slot_hosts,
222        parent_stack,
223        scope_stack,
224    } = &mut stacks;
225    if slot_hosts.capacity() > SPARE_STACK_CAPACITY
226        || parent_stack.capacity() > SPARE_STACK_CAPACITY
227        || scope_stack.capacity() > SPARE_STACK_CAPACITY
228    {
229        return;
230    }
231    slot_hosts.clear();
232    parent_stack.clear();
233    scope_stack.clear();
234    crate::thread_state::try_runtimes(|state| state.spare_composer_stacks.set(Some(stacks)));
235}
236
237/// Keeps an applied, empty command queue for the next pass on this thread.
238pub(crate) fn recycle_commands(commands: CommandQueue) {
239    if commands.capacity() > SPARE_COMMAND_CAPACITY {
240        return;
241    }
242    crate::thread_state::try_runtimes(|state| {
243        let mut spare = state.spare_commands.borrow_mut();
244        if spare.len() < SPARE_COMMAND_QUEUES {
245            spare.push(commands);
246        }
247    });
248}
249
250#[derive(Default)]
251pub(crate) struct SubcomposeFrame {
252    pub(crate) nodes: Vec<NodeId>,
253    pub(crate) scopes: Vec<RecomposeScope>,
254}
255
256/// The values one provider supplies, over the frames of the providers around
257/// it.
258pub(crate) struct LocalFrame {
259    values: SmallVec<[(LocalKey, Rc<dyn Any>); 2]>,
260    parent: LocalStackSnapshot,
261}
262
263/// The entry the innermost provider in `stack` supplies for `key`.
264pub(crate) fn provided_entry(stack: &LocalStackSnapshot, key: &LocalKey) -> Option<Rc<dyn Any>> {
265    let mut frame = stack.as_deref();
266    while let Some(current) = frame {
267        if let Some((_, entry)) = current.values.iter().find(|(provided, _)| provided == key) {
268            return Some(Rc::clone(entry));
269        }
270        frame = current.parent.as_deref();
271    }
272    None
273}
274
275pub(crate) struct ComposerCore {
276    pub(crate) shared_state: Rc<ComposerRuntimeState>,
277    /// The branch fold stack of the runtime state, which its nested
278    /// composers share.
279    pub(crate) branch_folds: Rc<crate::slot::BranchFolds>,
280    pub(crate) slots: Rc<SlotsHost>,
281    slot_hosts: RefCell<Vec<Rc<SlotsHost>>>,
282    pub(crate) applier: Rc<dyn ApplierHost>,
283    pub(crate) runtime: RuntimeHandle,
284    pub(crate) parent_stack: RefCell<Vec<ParentFrame>>,
285    pub(crate) subcompose_stack: RefCell<Vec<SubcomposeFrame>>,
286    pub(crate) root: Cell<Option<NodeId>>,
287    pub(crate) commands: RefCell<CommandQueue>,
288    pub(crate) scope_stack: RefCell<Vec<ScopeFrame>>,
289    subcomposition_owner_scope: RefCell<Option<RecomposeScope>>,
290    pub(crate) local_stack: RefCell<LocalStackSnapshot>,
291    pub(crate) side_effects: RefCell<Vec<Box<dyn FnOnce()>>>,
292    pub(crate) pending_scope_options: Cell<Option<RecomposeOptions>>,
293    pub(crate) phase: Cell<crate::Phase>,
294    pub(crate) recompose_parent_hint: Cell<Option<NodeId>>,
295    pub(crate) recompose_child_cursor: Cell<crate::recompose::RecomposeChildCursor>,
296    // The scope whose body runs again from its own invalidation: the bodies
297    // that run below it run because it called them, with the arguments it
298    // worked out.
299    pub(crate) restarted_scope: RefCell<Option<RecomposeScope>>,
300    pub(crate) root_render_requested: Cell<bool>,
301    /// Whether a static composition local provided around what composes
302    /// now changed: every group opened meanwhile runs its body.
303    locals_changed: Cell<bool>,
304    // How many open groups compose reused or restored content, under which
305    // every group runs its body.
306    reused_depth: Cell<u32>,
307    pub(crate) _not_send: PhantomData<*const ()>,
308}
309
310/// The composition context inherited by work that is composed in another slot
311/// host. Besides composition locals, this carries the source owner scope so a
312/// secondary tree cannot outlive the composition that supplied its callbacks.
313#[derive(Clone, Default)]
314pub struct CapturedCompositionContext {
315    locals: LocalStackSnapshot,
316    owner_scope: Option<Weak<RecomposeScopeInner>>,
317    locals_changed: bool,
318}
319
320impl CapturedCompositionContext {
321    /// Whether a static composition local provided around the capture site
322    /// changed in the composition that captured this context: what composes
323    /// under it, subcompositions included, must compose again without
324    /// skipping.
325    pub fn locals_changed(&self) -> bool {
326        self.locals_changed
327    }
328
329    /// Total deactivations along the capturing scope's owner chain right now;
330    /// see [`crate::RecomposeScope::owner_chain_deactivation_epoch`]. Zero
331    /// when the context has no owner scope or it is gone.
332    pub fn owner_chain_deactivation_epoch(&self) -> u64 {
333        self.owner_scope
334            .as_ref()
335            .and_then(Weak::upgrade)
336            .map_or(0, |inner| {
337                RecomposeScope { inner }.owner_chain_deactivation_epoch()
338            })
339    }
340}
341
342fn take_subcompose_frame(core: &ComposerCore, operation: &str) -> SubcomposeFrame {
343    match core.subcompose_stack.borrow_mut().pop() {
344        Some(frame) => frame,
345        None => {
346            log::error!("subcompose stack underflow while finishing {operation}");
347            SubcomposeFrame::default()
348        }
349    }
350}
351
352struct SubcomposeStackGuard {
353    core: Rc<ComposerCore>,
354    leaked: bool,
355}
356
357impl Drop for SubcomposeStackGuard {
358    fn drop(&mut self) {
359        if !self.leaked {
360            self.core.subcompose_stack.borrow_mut().pop();
361        }
362    }
363}
364
365impl Drop for ComposerCore {
366    /// A pass that queued nothing never takes its queue: hand its storage
367    /// back for the next pass.
368    fn drop(&mut self) {
369        let commands = std::mem::take(self.commands.get_mut());
370        if commands.len() == 0 && commands.capacity() > 0 {
371            recycle_commands(commands);
372        }
373        let stacks = self.take_stacks();
374        if stacks.holds_storage() {
375            recycle_composer_stacks(stacks);
376        }
377    }
378}
379
380impl ComposerCore {
381    fn new(parts: ComposerParts) -> Self {
382        let ComposerParts {
383            shared_state,
384            slots,
385            applier,
386            runtime,
387            root,
388            initial_parent_frame,
389        } = parts;
390        let ComposerStacks {
391            slot_hosts,
392            mut parent_stack,
393            scope_stack,
394        } = spare_composer_stacks();
395        push_root_frame(&mut parent_stack, root, initial_parent_frame);
396        Self {
397            branch_folds: Rc::clone(&shared_state.branch_folds),
398            shared_state,
399            slots,
400            slot_hosts: RefCell::new(slot_hosts),
401            applier,
402            runtime,
403            parent_stack: RefCell::new(parent_stack),
404            subcompose_stack: RefCell::new(Vec::new()),
405            root: Cell::new(root),
406            commands: RefCell::new(spare_commands()),
407            scope_stack: RefCell::new(scope_stack),
408            subcomposition_owner_scope: RefCell::new(None),
409            local_stack: RefCell::new(None),
410            side_effects: RefCell::new(Vec::new()),
411            pending_scope_options: Cell::new(None),
412            phase: Cell::new(crate::Phase::Compose),
413            recompose_parent_hint: Cell::new(None),
414            recompose_child_cursor: Cell::new(crate::recompose::RecomposeChildCursor::Unknown),
415            restarted_scope: RefCell::new(None),
416            root_render_requested: Cell::new(false),
417            locals_changed: Cell::new(false),
418            reused_depth: Cell::new(0),
419            _not_send: PhantomData,
420        }
421    }
422
423    /// The stacks, emptied, with their storage.
424    fn take_stacks(&mut self) -> ComposerStacks {
425        let mut stacks = ComposerStacks {
426            slot_hosts: std::mem::take(self.slot_hosts.get_mut()),
427            parent_stack: std::mem::take(self.parent_stack.get_mut()),
428            scope_stack: std::mem::take(self.scope_stack.get_mut()),
429        };
430        stacks.slot_hosts.clear();
431        stacks.parent_stack.clear();
432        stacks.scope_stack.clear();
433        stacks
434    }
435
436    /// Becomes the core of a new pass, in place, as [`Self::new`] builds
437    /// one: the allocation and the stacks' storage stay. Every field is
438    /// named, so a new field cannot be left out.
439    fn restart(&mut self, parts: ComposerParts) {
440        let Self {
441            shared_state,
442            branch_folds,
443            slots,
444            slot_hosts,
445            applier,
446            runtime,
447            parent_stack,
448            subcompose_stack,
449            root,
450            commands,
451            scope_stack,
452            subcomposition_owner_scope,
453            local_stack,
454            side_effects,
455            pending_scope_options,
456            phase,
457            recompose_parent_hint,
458            recompose_child_cursor,
459            restarted_scope,
460            root_render_requested,
461            locals_changed,
462            reused_depth,
463            _not_send: _,
464        } = self;
465        if !Rc::ptr_eq(shared_state, &parts.shared_state) {
466            *branch_folds = Rc::clone(&parts.shared_state.branch_folds);
467            *shared_state = parts.shared_state;
468        }
469        *slots = parts.slots;
470        *applier = parts.applier;
471        *runtime = parts.runtime;
472        slot_hosts.get_mut().clear();
473        let parent_stack = parent_stack.get_mut();
474        parent_stack.clear();
475        push_root_frame(parent_stack, parts.root, parts.initial_parent_frame);
476        subcompose_stack.get_mut().clear();
477        root.set(parts.root);
478        let commands = commands.get_mut();
479        if commands.len() > 0 || commands.capacity() == 0 {
480            *commands = spare_commands();
481        }
482        scope_stack.get_mut().clear();
483        *subcomposition_owner_scope.get_mut() = None;
484        *local_stack.get_mut() = None;
485        side_effects.get_mut().clear();
486        pending_scope_options.set(None);
487        phase.set(crate::Phase::Compose);
488        recompose_parent_hint.set(None);
489        recompose_child_cursor.set(crate::recompose::RecomposeChildCursor::Unknown);
490        *restarted_scope.get_mut() = None;
491        root_render_requested.set(false);
492        locals_changed.set(false);
493        reused_depth.set(0);
494    }
495
496    /// Lets go of what the finished pass composed under: its stacks, locals,
497    /// owner scope and side effects.
498    fn park(&mut self) {
499        self.slot_hosts.get_mut().clear();
500        self.parent_stack.get_mut().clear();
501        self.scope_stack.get_mut().clear();
502        self.subcompose_stack.get_mut().clear();
503        *self.subcomposition_owner_scope.get_mut() = None;
504        *self.local_stack.get_mut() = None;
505        self.side_effects.get_mut().clear();
506    }
507}
508
509/// What a subcomposition takes from where it runs: the applier its nodes go
510/// to, the runtime, the phase, and whether a static composition local changed
511/// above it.
512#[derive(Clone, Copy)]
513struct SubcomposeSite<'a> {
514    applier: &'a Rc<dyn ApplierHost>,
515    runtime: &'a RuntimeHandle,
516    phase: crate::Phase,
517    locals_changed: bool,
518}
519
520impl SubcomposeSite<'_> {
521    /// A core that composes into `slots` with `shared_state`, its top-level
522    /// nodes under `root`, seeing `locals`.
523    fn spin_up_core(
524        self,
525        shared_state: Rc<ComposerRuntimeState>,
526        slots: &Rc<SlotsHost>,
527        root: Option<NodeId>,
528        locals: LocalStackSnapshot,
529    ) -> Rc<ComposerCore> {
530        let core = Rc::new(ComposerCore::new(ComposerParts {
531            shared_state,
532            slots: Rc::clone(slots),
533            applier: Rc::clone(self.applier),
534            runtime: self.runtime.clone(),
535            root,
536            initial_parent_frame: InitialParentFrame::RealParent,
537        }));
538        core.phase.set(self.phase);
539        core.locals_changed.set(self.locals_changed);
540        *core.local_stack.borrow_mut() = locals;
541        core
542    }
543
544    /// Applies a subcomposition's commands. The pass holds a state teardown
545    /// scope from its start until this returns, as a root pass does: the
546    /// states a removed group remembered stay readable until the nodes it
547    /// emitted are detached, whose modifier nodes may read them.
548    fn flush(
549        self,
550        mut commands: CommandQueue,
551        compact_applier: bool,
552        side_effects: Vec<Box<dyn FnOnce()>>,
553    ) -> Result<(), NodeError> {
554        {
555            let mut applier = self.applier.borrow_dyn();
556            commands.apply(&mut *applier)?;
557            for update in self.runtime.take_updates() {
558                update.apply(&mut *applier)?;
559            }
560        }
561        recycle_commands(commands);
562        if compact_applier {
563            self.applier.compact();
564            self.applier.borrow_dyn().clear_recycled_nodes();
565        }
566        composer_context::without_composer(|| {
567            for effect in side_effects {
568                effect();
569            }
570        });
571        Ok(())
572    }
573}
574
575/// What a composer core is built for: the tree it composes and the
576/// parent its top-level nodes attach under.
577struct ComposerParts {
578    shared_state: Rc<ComposerRuntimeState>,
579    slots: Rc<SlotsHost>,
580    applier: Rc<dyn ApplierHost>,
581    runtime: RuntimeHandle,
582    root: Option<NodeId>,
583    initial_parent_frame: InitialParentFrame,
584}
585
586/// The state of one composition pass. It writes the slot table and queues node changes for the
587/// applier. Clones share the same pass. Composable functions reach the current composer through
588/// `with_current_composer`.
589#[derive(Clone)]
590pub struct Composer {
591    pub(crate) core: Rc<ComposerCore>,
592}
593
594/// Keeps a branch's key in the fold of the groups composed inside it, for
595/// code `#[composable]` expands to.
596#[doc(hidden)]
597pub struct BranchGroupGuard<'a> {
598    folds: &'a crate::slot::BranchFolds,
599    token: crate::slot::FoldToken,
600}
601
602impl BranchGroupGuard<'_> {
603    /// Closes this branch and opens one for `key` in its place, for the
604    /// statement after the one this guard folded.
605    #[doc(hidden)]
606    #[inline]
607    pub fn advance(&mut self, key: Key) {
608        self.folds.advance(&mut self.token, key);
609    }
610}
611
612impl Drop for BranchGroupGuard<'_> {
613    #[inline]
614    fn drop(&mut self) {
615        self.folds.close(self.token);
616    }
617}
618
619/// A [`BranchGroupGuard`] for code that reaches the composer through the
620/// thread's current one, as a content closure does.
621///
622/// A content closure also runs outside composition, as a draw or layout
623/// closure does, where its guards open nothing: such a guard drops with one
624/// inline test, and only an open one calls out to close its group.
625#[doc(hidden)]
626pub struct ScopedBranchGroupGuard {
627    /// The folds and the token of the open group; none outside composition.
628    /// [`Drop::drop`] takes and closes it, so the field has no drop of its own.
629    open: std::mem::ManuallyDrop<Option<ScopedBranchGroup>>,
630}
631
632/// The group a [`ScopedBranchGroupGuard`] holds open.
633struct ScopedBranchGroup {
634    folds: Rc<crate::slot::BranchFolds>,
635    token: crate::slot::FoldToken,
636}
637
638/// Opens a group keyed `key` in the current composer's folds; outside
639/// composition, a guard that opened nothing.
640#[doc(hidden)]
641#[inline]
642pub fn __branch_group_scope_deferred(key: Key) -> ScopedBranchGroupGuard {
643    let open = composer_context::with_current_core(|core| ScopedBranchGroup {
644        token: core.branch_folds.push(key),
645        folds: Rc::clone(&core.branch_folds),
646    });
647    ScopedBranchGroupGuard {
648        open: std::mem::ManuallyDrop::new(open),
649    }
650}
651
652/// Moves a content closure's statement guard to the next statement, keyed
653/// `key`: the guard the next statement would open, without looking up the
654/// composer again, as [`BranchGroupGuard::advance`] does. A guard opened
655/// outside composition stays empty.
656#[doc(hidden)]
657#[inline]
658pub fn __branch_group_scope_advance(guard: &mut ScopedBranchGroupGuard, key: Key) {
659    if let Some(group) = guard.open.as_mut() {
660        group.folds.advance(&mut group.token, key);
661    }
662}
663
664impl Drop for ScopedBranchGroupGuard {
665    #[inline(always)]
666    fn drop(&mut self) {
667        if let Some(group) = self.open.take() {
668            close_scoped_branch_group(group);
669        }
670    }
671}
672
673#[inline(never)]
674fn close_scoped_branch_group(group: ScopedBranchGroup) {
675    group.folds.close(group.token);
676}
677
678pub(crate) enum EmittedNode {
679    Fresh(Box<dyn Node>),
680    Recycled(RecycledNode),
681}
682
683impl Composer {
684    pub(crate) fn new_with_shared_state(
685        shared_state: Rc<ComposerRuntimeState>,
686        slots: Rc<SlotsHost>,
687        applier: Rc<dyn ApplierHost>,
688        runtime: RuntimeHandle,
689        root: Option<NodeId>,
690    ) -> Self {
691        Self::new_with_shared_state_with_parent_frame(
692            shared_state,
693            slots,
694            applier,
695            runtime,
696            root,
697            InitialParentFrame::SyntheticRoot,
698        )
699    }
700
701    fn new_with_shared_state_with_parent_frame(
702        shared_state: Rc<ComposerRuntimeState>,
703        slots: Rc<SlotsHost>,
704        applier: Rc<dyn ApplierHost>,
705        runtime: RuntimeHandle,
706        root: Option<NodeId>,
707        initial_parent_frame: InitialParentFrame,
708    ) -> Self {
709        shared_state.bind_applier_host(&applier);
710        let slots = bind_slots_host_to_runtime_state(&shared_state, &slots);
711        let core = Rc::new(ComposerCore::new(ComposerParts {
712            shared_state,
713            slots,
714            applier,
715            runtime,
716            root,
717            initial_parent_frame,
718        }));
719        Self { core }
720    }
721
722    /// A composer for a pass, as [`Self::new_with_shared_state`] makes,
723    /// built in place of `parked`'s core when nothing else holds it: the
724    /// pass then allocates no core and reuses the stacks' storage.
725    pub(crate) fn for_pass(
726        parked: Option<Self>,
727        shared_state: Rc<ComposerRuntimeState>,
728        slots: Rc<SlotsHost>,
729        applier: Rc<dyn ApplierHost>,
730        runtime: RuntimeHandle,
731        root: Option<NodeId>,
732    ) -> Self {
733        let Some(mut composer) = parked.filter(|parked| Rc::strong_count(&parked.core) == 1) else {
734            return Self::new_with_shared_state(shared_state, slots, applier, runtime, root);
735        };
736        let Some(core) = Rc::get_mut(&mut composer.core) else {
737            return Self::new_with_shared_state(shared_state, slots, applier, runtime, root);
738        };
739        shared_state.bind_applier_host(&applier);
740        let slots = bind_slots_host_to_runtime_state(&shared_state, &slots);
741        core.restart(ComposerParts {
742            shared_state,
743            slots,
744            applier,
745            runtime,
746            root,
747            initial_parent_frame: InitialParentFrame::SyntheticRoot,
748        });
749        composer
750    }
751
752    /// The composer of a finished pass, kept for [`Self::for_pass`] when
753    /// nothing else holds its core. It lets go of what the pass composed
754    /// under.
755    pub(crate) fn park(mut self) -> Option<Self> {
756        Rc::get_mut(&mut self.core)?.park();
757        Some(self)
758    }
759
760    /// Creates a composer that writes into `slots` and queues node changes for `applier`. Top-level
761    /// nodes attach under `root`, or have no parent when `root` is `None`.
762    pub fn new(
763        slots: Rc<SlotsHost>,
764        applier: Rc<dyn ApplierHost>,
765        runtime: RuntimeHandle,
766        root: Option<NodeId>,
767    ) -> Self {
768        Self::new_with_shared_state_with_parent_frame(
769            slots
770                .runtime_state()
771                .unwrap_or_else(|| Rc::new(ComposerRuntimeState::default())),
772            slots,
773            applier,
774            runtime,
775            root,
776            InitialParentFrame::RealParent,
777        )
778    }
779
780    pub(crate) fn from_core(core: Rc<ComposerCore>) -> Self {
781        Self { core }
782    }
783
784    pub(crate) fn clone_core(&self) -> Rc<ComposerCore> {
785        Rc::clone(&self.core)
786    }
787
788    pub(crate) fn request_root_render(&self) {
789        self.core.root_render_requested.set(true);
790    }
791
792    pub(crate) fn take_root_render_request(&self) -> bool {
793        self.core.root_render_requested.replace(false)
794    }
795
796    /// Returns the slot table host that receives this composer's writes: the innermost host set up
797    /// for a subcomposition, otherwise the composition's own.
798    pub fn active_slots_host(&self) -> Rc<SlotsHost> {
799        self.core
800            .slot_hosts
801            .borrow()
802            .last()
803            .cloned()
804            .unwrap_or_else(|| Rc::clone(&self.core.slots))
805    }
806
807    fn with_active_slots_host<R>(&self, f: impl FnOnce(&SlotsHost) -> R) -> R {
808        let hosts = self.core.slot_hosts.borrow();
809        f(hosts.last().unwrap_or(&self.core.slots))
810    }
811
812    pub(crate) fn with_slots<R>(&self, f: impl FnOnce(&SlotTable) -> R) -> R {
813        self.with_active_slots_host(|host| f(&host.borrow()))
814    }
815
816    pub(crate) fn with_slots_mut<R>(&self, f: impl FnOnce(&mut SlotTable) -> R) -> R {
817        self.with_active_slots_host(|host| f(&mut host.borrow_mut()))
818    }
819
820    pub(crate) fn with_slot_session_mut<R>(
821        &self,
822        f: impl FnOnce(&mut crate::slot::SlotWriteSession<'_>) -> R,
823    ) -> R {
824        self.with_active_slots_host(|host| host.with_write_session(f))
825    }
826
827    pub(crate) fn try_with_slot_host_pass<R>(
828        &self,
829        slots: Rc<SlotsHost>,
830        mode: crate::slot::SlotPassMode,
831        f: impl FnOnce(&Self) -> R,
832    ) -> Result<(R, SlotPassOutcome), NodeError> {
833        let mut guard = self.begin_slot_host_pass(&slots, mode);
834        let result = f(self);
835        let outcome = self.finish_slot_host_pass(&guard.host)?;
836        guard.close();
837        Ok((result, outcome))
838    }
839
840    pub(crate) fn with_slot_host_pass<R>(
841        &self,
842        slots: Rc<SlotsHost>,
843        mode: crate::slot::SlotPassMode,
844        f: impl FnOnce(&Self) -> R,
845    ) -> (R, SlotPassOutcome) {
846        let mut guard = self.begin_slot_host_pass(&slots, mode);
847        let result = f(self);
848        let outcome = match self.finish_slot_host_pass(&guard.host) {
849            Ok(outcome) => outcome,
850            Err(err) => {
851                log::error!("slot host pass finalization failed: {err}");
852                SlotPassOutcome::default()
853            }
854        };
855        guard.close();
856        (result, outcome)
857    }
858
859    pub(crate) fn with_slot_override<R>(
860        &self,
861        slots: Rc<SlotsHost>,
862        f: impl FnOnce(&Self) -> R,
863    ) -> (R, SlotPassOutcome) {
864        self.with_slot_host_pass(slots, crate::slot::SlotPassMode::Compose, f)
865    }
866
867    fn begin_slot_host_pass(
868        &self,
869        slots: &Rc<SlotsHost>,
870        mode: crate::slot::SlotPassMode,
871    ) -> SlotHostPassGuard {
872        let slots = bind_slots_host_to_runtime_state(&self.core.shared_state, slots);
873        let fold_base = self.core.branch_folds.len();
874        slots.begin_pass(mode, &self.core.branch_folds);
875        {
876            let mut stack = self.core.slot_hosts.borrow_mut();
877            if let Some(parent) = stack.last()
878                && !Rc::ptr_eq(parent, &slots)
879            {
880                parent.note_nested_host(&slots);
881            }
882            stack.push(Rc::clone(&slots));
883        }
884        SlotHostPassGuard {
885            core: self.clone_core(),
886            host: slots,
887            fold_base,
888            active: true,
889        }
890    }
891
892    fn finish_slot_host_pass(&self, slots: &Rc<SlotsHost>) -> Result<SlotPassOutcome, NodeError> {
893        let finished = {
894            let mut applier = self.core.applier.borrow_dyn();
895            slots.finish_pass(&mut *applier)
896        }?;
897        self.handle_detached_children_in_host(slots, None, finished.detached_root_children)?;
898        self.wake_sites_whose_movable_arrived();
899        self.evict_retained_subtrees_for_host(slots)?;
900        slots.complete_pass_cleanup(&finished.outcome);
901        Ok(finished.outcome)
902    }
903
904    fn wake_sites_whose_movable_arrived(&self) {
905        for host in self.core.shared_state.hosts_awaiting_movables() {
906            self.wake_sites_in_host(&host);
907        }
908    }
909
910    fn wake_sites_in_host(&self, slots: &Rc<SlotsHost>) {
911        let pending = self.core.shared_state.take_pending_movables(slots);
912        if pending.is_empty() {
913            return;
914        }
915        let mut waiting = Vec::new();
916        for site in pending {
917            if !slots.borrow().group_is_active(site.placeholder) {
918                continue;
919            }
920            let retain_key = RetainKey::for_group(None, site.key);
921            if !self.core.shared_state.movable_retained_anywhere(retain_key) {
922                waiting.push(site);
923                continue;
924            }
925            match site.parent_scope.as_ref().and_then(RecomposeScope::upgrade) {
926                Some(scope) => {
927                    scope.force_recompose();
928                    scope.invalidate();
929                }
930                None => log::error!(
931                    "movable content {:?} arrived for a site whose scope is gone",
932                    site.key
933                ),
934            }
935        }
936        self.core.shared_state.keep_pending_movables(slots, waiting);
937    }
938
939    pub(crate) fn forget_movables(&self, ids: &[Key]) -> Result<(), NodeError> {
940        for id in ids {
941            let Some((host, subtree)) = self.core.shared_state.take_retained_movable(*id) else {
942                continue;
943            };
944            self.dispose_detached_subtree_in_host(&host, subtree)?;
945            host.flush_pending_drops();
946        }
947        Ok(())
948    }
949
950    pub(crate) fn parent_stack(&self) -> RefMut<'_, Vec<ParentFrame>> {
951        self.core.parent_stack.borrow_mut()
952    }
953
954    pub(crate) fn current_parent_hint(&self) -> Option<NodeId> {
955        let stack = self.core.parent_stack.borrow();
956        let stack_hint = stack
957            .last()
958            .and_then(|frame| (!frame.synthetic_root).then_some(frame.id));
959        stack_hint.or_else(|| self.core.recompose_parent_hint.get())
960    }
961
962    pub(crate) fn subcompose_stack(&self) -> RefMut<'_, Vec<SubcomposeFrame>> {
963        self.core.subcompose_stack.borrow_mut()
964    }
965
966    pub(crate) fn commands_mut(&self) -> RefMut<'_, CommandQueue> {
967        self.core.commands.borrow_mut()
968    }
969
970    pub(crate) fn enqueue_semantics_invalidation(&self, id: NodeId) {
971        self.commands_mut().push(Command::BubbleDirty {
972            node_id: id,
973            bubble: DirtyBubble::SEMANTICS,
974        });
975    }
976
977    pub(crate) fn scope_stack(&self) -> RefMut<'_, Vec<ScopeFrame>> {
978        self.core.scope_stack.borrow_mut()
979    }
980
981    pub(crate) fn local_stack(&self) -> RefMut<'_, LocalStackSnapshot> {
982        self.core.local_stack.borrow_mut()
983    }
984
985    pub(crate) fn current_local_stack(&self) -> LocalStackSnapshot {
986        self.core.local_stack.borrow().clone()
987    }
988
989    pub(crate) fn side_effects_mut(&self) -> RefMut<'_, Vec<Box<dyn FnOnce()>>> {
990        self.core.side_effects.borrow_mut()
991    }
992
993    pub(crate) fn borrow_applier(&self) -> ApplierGuard<'_, dyn Applier> {
994        self.core.applier.borrow_dyn()
995    }
996
997    /// Records nodes whose retained subtrees a reused subcompose slot just
998    /// rebound to new content.
999    ///
1000    /// The rebinding recomposes inline during measure, so every repass it
1001    /// schedules is consumed by the layout pass already running — nothing
1002    /// else survives to tell the scoped scene update these subtrees changed,
1003    /// and a translate-only update would keep their stale layers (measured:
1004    /// a 60pt lazy scroll presented the old row's text at the new row's
1005    /// position). The structural-change set is the one channel drained
1006    /// after layout, so the rebound children ride it.
1007    pub fn record_rebound_slot_children(&self, children: &[NodeId]) {
1008        let mut applier = self.borrow_applier();
1009        for &child in children {
1010            applier.record_structural_change(child);
1011        }
1012    }
1013
1014    /// Stores a virtual node ([`Node::is_virtual`]) in the Applier and returns its id, assigned
1015    /// to the node so its layout registry and invalidation metadata belong to the stored node.
1016    pub fn create_virtual_node(&self, node: Box<dyn Node>) -> NodeId {
1017        debug_assert!(node.is_virtual(), "a virtual node reports `is_virtual`");
1018        let mut applier = self.borrow_applier();
1019        let node_id = applier.create(node);
1020        if let Ok(node) = applier.get_mut(node_id) {
1021            node.set_node_id(node_id);
1022        }
1023        node_id
1024    }
1025
1026    /// Detaches and disposes subcomposition roots evicted from their reuse pool.
1027    /// Applies pending composition commands before releasing the roots and their descendants.
1028    ///
1029    /// ```no_run
1030    /// # use cranpose_core::{Composer, NodeError, SubcomposeState};
1031    /// # fn finish(composer: &Composer, state: &mut SubcomposeState) -> Result<(), NodeError> {
1032    /// let evicted = state.finish_pass();
1033    /// composer.dispose_subcomposed_nodes(evicted)?;
1034    /// # Ok(())
1035    /// # }
1036    /// ```
1037    pub fn dispose_subcomposed_nodes(
1038        &self,
1039        disposal: crate::subcompose::SubcomposeDisposal,
1040    ) -> Result<(), NodeError> {
1041        if disposal.nodes.is_empty() && disposal.slot_hosts.is_empty() {
1042            return Ok(());
1043        }
1044        self.apply_pending_commands()?;
1045        Self::dispose_measure_subcomposed_nodes(&self.core.applier, disposal)
1046    }
1047
1048    /// Disposes what a measure-time subcomposition dropped from `applier`, as
1049    /// [`Self::dispose_subcomposed_nodes`] does under a composer, for a pass
1050    /// [`Self::subcompose_measure_slot`] ran.
1051    pub fn dispose_measure_subcomposed_nodes(
1052        applier: &Rc<dyn ApplierHost>,
1053        disposal: crate::subcompose::SubcomposeDisposal,
1054    ) -> Result<(), NodeError> {
1055        if disposal.nodes.is_empty() && disposal.slot_hosts.is_empty() {
1056            return Ok(());
1057        }
1058        let disposal = crate::NodeDisposal::from_subcomposed(disposal, &*applier.borrow_dyn());
1059        applier.dispose_nodes(disposal)
1060    }
1061
1062    /// Checks if a node has no parent (is a root node).
1063    /// Used by SubcomposeMeasureScope to filter subcompose results.
1064    pub fn node_has_no_parent(&self, node_id: NodeId) -> bool {
1065        let mut applier = self.borrow_applier();
1066        match applier.get_mut(node_id) {
1067            Ok(node) => node.parent().is_none(),
1068            Err(_) => true,
1069        }
1070    }
1071
1072    /// Returns a node's parent, or `None` for a root node.
1073    ///
1074    /// Returns an error when the node is no longer present in the applier.
1075    pub fn node_parent(&self, node_id: NodeId) -> Result<Option<NodeId>, NodeError> {
1076        self.borrow_applier()
1077            .get_mut(node_id)
1078            .map(|node| node.parent())
1079    }
1080
1081    /// Gets the children of a node from the Applier.
1082    ///
1083    /// This is used by SubcomposeLayoutNode to get children of virtual nodes
1084    /// directly from the Applier, where insert_child commands have been applied.
1085    pub fn get_node_children(&self, node_id: NodeId) -> SmallVec<[NodeId; 8]> {
1086        let mut applier = self.borrow_applier();
1087        match applier.get_mut(node_id) {
1088            Ok(node) => {
1089                let mut children = SmallVec::<[NodeId; 8]>::new();
1090                node.collect_children_into(&mut children);
1091                children
1092            }
1093            Err(_) => SmallVec::<[NodeId; 8]>::new(),
1094        }
1095    }
1096
1097    /// Runs `visit` on each child of `node_id`, in order, with whether the
1098    /// child needs measurement or placement before its cached layout can be
1099    /// reused: the walk [`Self::get_node_children`] and
1100    /// [`Self::nodes_need_relayout`] make together, under one borrow of the
1101    /// applier.
1102    pub fn visit_node_children(&self, node_id: NodeId, mut visit: impl FnMut(NodeId, bool)) {
1103        let applier = self.borrow_applier();
1104        let Ok(node) = applier.get_ref(node_id) else {
1105            return;
1106        };
1107        node.for_each_child(&mut |child| {
1108            let needs_relayout = applier.get_ref(child).is_ok_and(Node::layout_dirty);
1109            visit(child, needs_relayout);
1110        });
1111    }
1112
1113    /// Whether any node needs measurement or placement before its cached layout can be reused.
1114    ///
1115    /// ```no_run
1116    /// # use cranpose_core::{Composer, NodeId};
1117    /// # fn cache_is_current(composer: &Composer, children: &[NodeId]) -> bool {
1118    /// !composer.nodes_need_relayout(children.iter().copied())
1119    /// # }
1120    /// ```
1121    pub fn nodes_need_relayout(&self, node_ids: impl IntoIterator<Item = NodeId>) -> bool {
1122        let applier = self.borrow_applier();
1123        node_ids
1124            .into_iter()
1125            .any(|node_id| applier.get_ref(node_id).is_ok_and(Node::layout_dirty))
1126    }
1127
1128    /// Clears all children of a node in the Applier.
1129    ///
1130    /// This is used by SubcomposeLayoutNode when reusing a virtual node for
1131    /// different content. Without clearing, old children remain attached,
1132    /// causing duplicate/interleaved items in lazy lists after scrolling.
1133    pub fn clear_node_children(&self, node_id: NodeId) {
1134        let mut applier = self.borrow_applier();
1135        if let Ok(node) = applier.get_mut(node_id) {
1136            node.update_children(&[]);
1137        }
1138    }
1139
1140    /// Runs `f` with this composer as the current one and its runtime as the active runtime. Both
1141    /// are restored when `f` returns.
1142    pub fn install<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
1143        let _composer_guard = composer_context::enter(self);
1144        runtime::push_active_runtime(&self.core.runtime);
1145        struct Guard;
1146        impl Drop for Guard {
1147            fn drop(&mut self) {
1148                runtime::pop_active_runtime();
1149            }
1150        }
1151        let guard = Guard;
1152        let result = f(self);
1153        drop(guard);
1154        result
1155    }
1156
1157    pub(crate) fn flush_pending_commands_if_large(&self) -> Result<(), NodeError> {
1158        let queued = self.core.commands.borrow().len();
1159        if queued < COMMAND_FLUSH_THRESHOLD {
1160            return Ok(());
1161        }
1162        self.apply_pending_commands()
1163    }
1164
1165    fn resolve_group_entry(
1166        &self,
1167        host: &Rc<SlotsHost>,
1168        seed: crate::slot::GroupKeySeed,
1169        parent_scope_id: Option<ScopeId>,
1170    ) -> GroupEntry {
1171        let key = host.with_write_session(|slots| slots.reserve_group_key(seed));
1172        let retain_key = RetainKey::for_group(parent_scope_id, key);
1173        let restored = self
1174            .core
1175            .shared_state
1176            .take_retained(host, retain_key, |subtree| {
1177                host.with_write_session(|slots| slots.retained_restore_ready(key, subtree))
1178            })
1179            .or_else(|| self.take_movable_from_another_table(host, retain_key, key))
1180            .map(Box::new);
1181        if restored.is_some() || !key.is_movable() {
1182            return GroupEntry {
1183                key,
1184                restored,
1185                placeholder_for: None,
1186            };
1187        }
1188        let attached_elsewhere = self.movable_attached_elsewhere(host, key);
1189        if !attached_elsewhere {
1190            return GroupEntry {
1191                key,
1192                restored: None,
1193                placeholder_for: None,
1194            };
1195        }
1196        let id = key.explicit_key.unwrap_or_default();
1197        let placeholder = host.with_write_session(|slots| {
1198            slots.reserve_group_key(crate::slot::GroupKeySeed::movable_placeholder(id))
1199        });
1200        GroupEntry {
1201            key: placeholder,
1202            restored: None,
1203            placeholder_for: Some(key),
1204        }
1205    }
1206
1207    /// Movable content that was let go by a parent composed in another slot
1208    /// table — a `SubcomposeLayout`'s, or the one a subcomposition owns — is
1209    /// retained there, not here. Bring it over: the table that held it lets
1210    /// go of its anchors, and this one issues its own.
1211    fn take_movable_from_another_table(
1212        &self,
1213        host: &Rc<SlotsHost>,
1214        retain_key: RetainKey,
1215        key: crate::slot::GroupKey,
1216    ) -> Option<crate::slot::DetachedSubtree> {
1217        if !key.is_movable() {
1218            return None;
1219        }
1220        let (source, mut subtree) = self
1221            .core
1222            .shared_state
1223            .take_retained_movable_elsewhere(host, retain_key)?;
1224        source
1225            .borrow_mut()
1226            .invalidate_detached_subtree_anchors(&subtree);
1227        if host.with_write_session(|slots| slots.retained_restore_ready(key, &mut subtree)) {
1228            return Some(subtree);
1229        }
1230        log::error!(
1231            "movable content {key:?} could not be taken over by the slot table that asked for it"
1232        );
1233        if let Err(error) = self.dispose_detached_subtree_in_host(host, subtree) {
1234            log::error!("disposing movable content that could not move failed: {error}");
1235        }
1236        None
1237    }
1238
1239    /// Whether the movable's content is attached to some parent that is not
1240    /// the one composing, in this slot table or in another.
1241    fn movable_attached_elsewhere(&self, host: &Rc<SlotsHost>, key: crate::slot::GroupKey) -> bool {
1242        if host.with_write_session(|slots| slots.movable_attached_elsewhere(key)) {
1243            return true;
1244        }
1245        let Some(id) = key.movable_id() else {
1246            return false;
1247        };
1248        self.core
1249            .shared_state
1250            .host_holding_movable(id)
1251            .is_some_and(|holder| !Rc::ptr_eq(&holder, host))
1252    }
1253
1254    fn start_group(
1255        &self,
1256        host: &Rc<SlotsHost>,
1257        seed: crate::slot::GroupKeySeed,
1258        parent_node: Option<NodeId>,
1259    ) -> (
1260        GroupStart<crate::slot::ActiveGroupId>,
1261        Option<crate::slot::GroupKey>,
1262    ) {
1263        if !self.core.shared_state.retains_any() {
1264            let started = host.with_write_session(|slots| {
1265                let key = slots.reserve_group_key(seed);
1266                (!key.is_movable()).then(|| slots.begin_group(key, None, parent_node))
1267            });
1268            if let Some(started) = started {
1269                return (started, None);
1270            }
1271        }
1272        // Retained content is found again by its parent's scope.
1273        let parent_scope_id = {
1274            let mut stack = self.scope_stack();
1275            let top = stack.len().checked_sub(1);
1276            top.map(|top| self.frame_scope(&mut stack, top).id())
1277        };
1278        let GroupEntry {
1279            key,
1280            restored,
1281            placeholder_for,
1282        } = self.resolve_group_entry(host, seed, parent_scope_id);
1283        let started =
1284            host.with_write_session(|slots| slots.begin_group(key, restored, parent_node));
1285        (started, placeholder_for)
1286    }
1287
1288    #[doc(hidden)]
1289    pub fn __branch_group_deferred(&self, key: Key) -> BranchGroupGuard<'_> {
1290        let folds = &*self.core.branch_folds;
1291        BranchGroupGuard {
1292            token: folds.push(key),
1293            folds,
1294        }
1295    }
1296
1297    fn dispose_detached_nodes(&self, nodes: impl IntoIterator<Item = NodeId>) {
1298        for node_id in nodes {
1299            self.commands_mut().push(Command::callback(move |applier| {
1300                crate::slot::dispose_detached_node_now(applier, node_id)
1301            }));
1302        }
1303    }
1304
1305    fn detached_root_parent_commands(
1306        &self,
1307        subtree: &crate::slot::DetachedSubtree,
1308        context: &'static str,
1309    ) -> Result<Vec<(NodeId, Option<NodeId>)>, NodeError> {
1310        let mut root_nodes = Vec::new();
1311        subtree.collect_root_nodes_checked_into(&mut root_nodes, context);
1312        let mut roots = Vec::with_capacity(root_nodes.len());
1313        for root in root_nodes {
1314            let parent_id = {
1315                let mut applier = self.borrow_applier();
1316                applier.get_mut(root)?.parent()
1317            };
1318            roots.push((root, parent_id));
1319        }
1320        Ok(roots)
1321    }
1322
1323    fn retain_detached_subtree_in_host(
1324        &self,
1325        slots_host: &Rc<SlotsHost>,
1326        parent_scope: Option<ScopeId>,
1327        subtree: crate::slot::DetachedSubtree,
1328    ) -> Result<(), NodeError> {
1329        let Some(root_key) = subtree.root_key_checked() else {
1330            log::error!("retention rejected detached subtree without a root group");
1331            self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1332            return Ok(());
1333        };
1334        let root_detaches = self.detached_root_parent_commands(&subtree, "retention")?;
1335        subtree.scopes().for_each(RecomposeScope::deactivate);
1336        for (root, parent_id) in root_detaches {
1337            if let Some(parent_id) = parent_id {
1338                self.commands_mut().push(Command::DetachChild {
1339                    parent_id,
1340                    child_id: root,
1341                });
1342            }
1343        }
1344        let evicted = self.core.shared_state.insert_retained(
1345            slots_host,
1346            RetainKey::for_group(parent_scope, root_key),
1347            subtree,
1348            root_key.is_movable(),
1349        );
1350        for subtree in evicted {
1351            self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1352        }
1353        Ok(())
1354    }
1355
1356    fn evict_retained_subtrees_for_host(
1357        &self,
1358        slots_host: &Rc<SlotsHost>,
1359    ) -> Result<(), NodeError> {
1360        let evicted = self.core.shared_state.advance_retention_pass(slots_host);
1361        for subtree in evicted {
1362            self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1363        }
1364        Ok(())
1365    }
1366
1367    fn dispose_detached_subtree_in_host(
1368        &self,
1369        slots_host: &Rc<SlotsHost>,
1370        subtree: crate::slot::DetachedSubtree,
1371    ) -> Result<(), NodeError> {
1372        let root_nodes = self
1373            .detached_root_parent_commands(&subtree, "disposal")?
1374            .into_iter()
1375            .map(|(root, _)| root);
1376        subtree.scopes().for_each(RecomposeScope::deactivate);
1377        self.dispose_detached_nodes(root_nodes);
1378        slots_host.with_table_and_lifecycle_mut(|table, lifecycle| {
1379            table.invalidate_detached_subtree_anchors(&subtree);
1380            lifecycle.queue_subtree_disposal(subtree);
1381        });
1382        Ok(())
1383    }
1384
1385    fn handle_detached_children_in_host(
1386        &self,
1387        slots_host: &Rc<SlotsHost>,
1388        parent_scope: Option<ScopeId>,
1389        detached: Vec<crate::slot::DetachedSubtree>,
1390    ) -> Result<(), NodeError> {
1391        for mut subtree in detached {
1392            for movable in subtree.split_off_nested_movables() {
1393                self.retain_detached_subtree_in_host(slots_host, None, movable)?;
1394            }
1395            if subtree
1396                .root_key_checked()
1397                .is_some_and(crate::slot::GroupKey::is_movable)
1398            {
1399                self.retain_detached_subtree_in_host(slots_host, None, subtree)?;
1400                continue;
1401            }
1402            let retention_mode = subtree
1403                .root_scope()
1404                .map_or_default(RecomposeScope::retention_mode);
1405            match retention_mode {
1406                RetentionMode::DisposeWhenInactive => {
1407                    self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1408                }
1409                RetentionMode::RetainWhenInactive => {
1410                    self.retain_detached_subtree_in_host(slots_host, parent_scope, subtree)?;
1411                }
1412            }
1413        }
1414        Ok(())
1415    }
1416
1417    fn handle_finished_group_result(
1418        &self,
1419        host: &Rc<SlotsHost>,
1420        parent_scope: Option<ScopeId>,
1421        result: FinishGroupResult,
1422    ) {
1423        let FinishGroupResult {
1424            detached_children,
1425            direct_nodes,
1426            root_nodes,
1427            was_skipped,
1428        } = result;
1429        if was_skipped {
1430            self.attach_root_nodes(root_nodes);
1431        }
1432        self.dispose_detached_nodes(direct_nodes);
1433        if detached_children.is_empty() {
1434            return;
1435        }
1436        if let Err(err) =
1437            self.handle_detached_children_in_host(host, parent_scope, detached_children)
1438        {
1439            log::error!("detached subtree handling failed while closing a group: {err}");
1440        }
1441    }
1442
1443    pub(crate) fn close_current_group_body_for_scope(&self, scope: &RecomposeScope) {
1444        self.close_group_body(&self.active_slots_host(), scope);
1445    }
1446
1447    fn close_group_body(&self, host: &Rc<SlotsHost>, scope: &RecomposeScope) {
1448        #[expect(
1449            clippy::redundant_closure_for_method_calls,
1450            reason = "the method path is not general over the session lifetime"
1451        )]
1452        let result = host.with_write_session(|slots| slots.finish_group_body_changes());
1453        self.close_finished_group(host, Some(scope), result);
1454    }
1455
1456    /// Handles what a group's body left, when it left anything, and pops
1457    /// the group's scope.
1458    fn close_finished_group(
1459        &self,
1460        host: &Rc<SlotsHost>,
1461        scope: Option<&RecomposeScope>,
1462        result: Option<FinishGroupResult>,
1463    ) {
1464        if let Some(result) = result {
1465            self.handle_finished_group_result(host, scope.map(RecomposeScope::id), result);
1466        }
1467        self.pop_closed_scope();
1468    }
1469
1470    /// Returns the value `init` made on the first composition at this call site. Later compositions
1471    /// return the same value until the call site leaves the composition.
1472    #[track_caller]
1473    pub fn remember<T: 'static>(&self, init: impl FnOnce() -> T) -> Owned<T> {
1474        self.remember_at(crate::caller_location_key(), init)
1475    }
1476
1477    #[doc(hidden)]
1478    pub fn remember_at<T: 'static>(&self, source: Key, init: impl FnOnce() -> T) -> Owned<T> {
1479        self.with_slot_session_mut(|slots| {
1480            slots.remember_with_kind(PayloadKind::Remember, source, init)
1481        })
1482    }
1483
1484    #[track_caller]
1485    pub(crate) fn remember_internal<T: 'static>(
1486        &self,
1487        source_salt: Key,
1488        init: impl FnOnce() -> T,
1489    ) -> Owned<T> {
1490        let source = crate::caller_location_key().scoped(source_salt);
1491        self.with_slot_session_mut(|slots| {
1492            slots.remember_with_kind(PayloadKind::Internal, source, init)
1493        })
1494    }
1495
1496    #[track_caller]
1497    /// The state of the effect written at `site`, in a slot of the current
1498    /// group: it leaves with the slot, and its drop ends the effect.
1499    pub(crate) fn remember_effect<T: Default + 'static>(&self, site: Key) -> Owned<T> {
1500        self.with_slot_session_mut(|slots| slots.remember_effect::<T>(site))
1501    }
1502
1503    /// Reserves the next slot at the call site for a `T` that `init` makes on the first
1504    /// composition. Returns a handle for reading the value through `with_slot_value`.
1505    #[track_caller]
1506    pub fn use_value_slot<T: 'static>(&self, init: impl FnOnce() -> T) -> ValueSlotHandle<'_, T> {
1507        let source = crate::caller_location_key();
1508        let (slot, record) = self.with_slot_session_mut(|slots| {
1509            slots.located_value_slot(PayloadKind::Internal, source, init)
1510        });
1511        ValueSlotHandle::new(slot, record)
1512    }
1513
1514    #[doc(hidden)]
1515    pub fn __use_param_slot<T: 'static>(
1516        &self,
1517        source: Key,
1518        init: impl FnOnce() -> T,
1519    ) -> ValueSlotHandle<'_, T> {
1520        let (slot, record) = self.with_slot_session_mut(|slots| {
1521            slots.located_value_slot(PayloadKind::Param, source, init)
1522        });
1523        ValueSlotHandle::new(slot, record)
1524    }
1525
1526    /// Finds the call's next parameter slot and runs `update` on its value,
1527    /// with one slot lookup for both.
1528    #[doc(hidden)]
1529    pub fn __update_param_slot<T: 'static, R>(
1530        &self,
1531        source: Key,
1532        init: impl FnOnce() -> T,
1533        update: impl FnOnce(&mut T) -> R,
1534    ) -> (ValueSlotHandle<'_, T>, R) {
1535        self.update_value_slot(PayloadKind::Param, source, init, update)
1536    }
1537
1538    /// Finds the call's return slot and runs `read` on its value, with one
1539    /// slot lookup for both.
1540    #[doc(hidden)]
1541    pub fn __update_return_slot<T: 'static, R>(
1542        &self,
1543        source: Key,
1544        init: impl FnOnce() -> T,
1545        read: impl FnOnce(&mut T) -> R,
1546    ) -> (ValueSlotHandle<'_, T>, R) {
1547        self.update_value_slot(PayloadKind::Return, source, init, read)
1548    }
1549
1550    fn update_value_slot<T: 'static, R>(
1551        &self,
1552        kind: PayloadKind,
1553        source: Key,
1554        init: impl FnOnce() -> T,
1555        update: impl FnOnce(&mut T) -> R,
1556    ) -> (ValueSlotHandle<'_, T>, R) {
1557        self.with_slot_session_mut(|slots| {
1558            let (slot, record, value) = slots.value_slot_and_value(kind, source, init);
1559            (ValueSlotHandle::new(slot, record), update(value))
1560        })
1561    }
1562
1563    #[doc(hidden)]
1564    #[track_caller]
1565    pub fn __use_return_slot<T: 'static>(
1566        &self,
1567        init: impl FnOnce() -> T,
1568    ) -> ValueSlotHandle<'_, T> {
1569        let source = crate::caller_location_key();
1570        let (slot, record) = self.with_slot_session_mut(|slots| {
1571            slots.located_value_slot(PayloadKind::Return, source, init)
1572        });
1573        ValueSlotHandle::new(slot, record)
1574    }
1575
1576    #[doc(hidden)]
1577    pub fn __invalidate_return_consumer_scope(&self) {
1578        let Some(scope) = self.current_recompose_scope() else {
1579            self.request_root_render();
1580            return;
1581        };
1582
1583        if let Some(target) = scope.callback_promotion_target() {
1584            target.invalidate();
1585        } else {
1586            self.request_root_render();
1587        }
1588    }
1589
1590    /// Runs `f` with a shared reference to the value in the slot that `handle` names.
1591    pub fn with_slot_value<'pass, T: 'static, R>(
1592        &'pass self,
1593        handle: ValueSlotHandle<'pass, T>,
1594        f: impl FnOnce(&T) -> R,
1595    ) -> R {
1596        self.with_slots(|slots| f(slots.value_at(handle.slot, handle.record)))
1597    }
1598
1599    /// Runs `f` with a mutable reference to the value in the slot that `handle` names.
1600    pub fn with_slot_value_mut<'pass, T: 'static, R>(
1601        &'pass self,
1602        handle: ValueSlotHandle<'pass, T>,
1603        f: impl FnOnce(&mut T) -> R,
1604    ) -> R {
1605        self.with_slots_mut(|slots| f(slots.value_at_mut(handle.slot, handle.record)))
1606    }
1607
1608    /// Creates a [`MutableState`] holding `initial`, tied to this composer's runtime. It is not
1609    /// remembered, so each call makes a new state.
1610    pub fn mutable_state_of<T: Clone + 'static>(&self, initial: T) -> MutableState<T> {
1611        MutableState::with_runtime(initial, self.runtime_handle())
1612    }
1613
1614    /// Creates a snapshot-aware list holding `values`, tied to this composer's runtime. It is not
1615    /// remembered, so each call makes a new list.
1616    pub fn mutable_state_list_of<T, I>(&self, values: I) -> SnapshotStateList<T>
1617    where
1618        T: Clone + 'static,
1619        I: IntoIterator<Item = T>,
1620    {
1621        SnapshotStateList::with_runtime(values, self.runtime_handle())
1622    }
1623
1624    /// Creates a snapshot-aware map holding `pairs`, tied to this composer's runtime. It is not
1625    /// remembered, so each call makes a new map.
1626    pub fn mutable_state_map_of<K, V, I>(&self, pairs: I) -> SnapshotStateMap<K, V>
1627    where
1628        K: Clone + Eq + Hash + 'static,
1629        V: Clone + 'static,
1630        I: IntoIterator<Item = (K, V)>,
1631    {
1632        SnapshotStateMap::with_runtime(pairs, self.runtime_handle())
1633    }
1634
1635    /// Returns the value of `local` from the innermost enclosing provider, or the local's default
1636    /// value when no provider is in scope.
1637    pub fn read_composition_local<T: Clone + 'static>(&self, local: &CompositionLocal<T>) -> T {
1638        self.read_provided(
1639            &local.key,
1640            |entry: &LocalStateEntry<T>| entry.value(),
1641            |entry: &ComputedLocalEntry<T>| entry.value(),
1642        )
1643        .unwrap_or_else(|| local.default_value())
1644    }
1645
1646    /// Returns the value of `local` from the innermost enclosing provider, or the local's default
1647    /// value when no provider is in scope.
1648    pub fn read_static_composition_local<T: Clone + 'static>(
1649        &self,
1650        local: &StaticCompositionLocal<T>,
1651    ) -> T {
1652        let provided = local.provided_under(&self.core.local_stack.borrow());
1653        provided.unwrap_or_else(|deferred| deferred.value(local))
1654    }
1655
1656    /// The value of the innermost provided entry for `key`, a plain value
1657    /// `V` or a computed one `C`; `None` without a provider. A computed value
1658    /// runs after the local stack is released, as it reads other locals.
1659    fn read_provided<V: 'static, C: 'static, T>(
1660        &self,
1661        key: &LocalKey,
1662        value: impl FnOnce(&V) -> T,
1663        computed: impl FnOnce(&C) -> T,
1664    ) -> Option<T> {
1665        let entry = provided_entry(&self.core.local_stack.borrow(), key)?;
1666        match entry.downcast::<V>() {
1667            Ok(entry) => Some(value(&entry)),
1668            Err(entry) => entry
1669                .downcast::<C>()
1670                .inspect_err(|_| key.report_type_mismatch())
1671                .ok()
1672                .map(|entry| computed(&entry)),
1673        }
1674    }
1675
1676    // The scope whose body runs again from its own invalidation and calls
1677    // the bodies that run now; `None` outside a recomposition.
1678    pub(crate) fn restarted_scope(&self) -> Option<RecomposeScope> {
1679        self.core.restarted_scope.borrow().clone()
1680    }
1681
1682    /// Returns the phase of the frame in which this composer is used.
1683    pub fn phase(&self) -> crate::Phase {
1684        self.core.phase.get()
1685    }
1686
1687    pub(crate) fn set_phase(&self, phase: crate::Phase) {
1688        self.core.phase.set(phase);
1689    }
1690
1691    /// Switches the composer to `phase`.
1692    pub fn enter_phase(&self, phase: crate::Phase) {
1693        self.set_phase(phase);
1694    }
1695
1696    pub(crate) fn subcompose<R>(
1697        &self,
1698        state: &mut SubcomposeState,
1699        slot_id: SlotId,
1700        content: impl FnOnce(&Self) -> R,
1701    ) -> (R, Vec<NodeId>) {
1702        match self.phase() {
1703            crate::Phase::Measure | crate::Phase::Layout => {}
1704            current => panic!(
1705                "subcompose() may only be called during measure or layout; current phase: {current:?}"
1706            ),
1707        }
1708
1709        self.subcompose_stack().push(SubcomposeFrame::default());
1710        let mut guard = SubcomposeStackGuard {
1711            core: self.clone_core(),
1712            leaked: false,
1713        };
1714
1715        let slot_host = state.get_or_create_slots(slot_id);
1716        let (result, _) = self.with_slot_override(slot_host, |composer| {
1717            composer.with_group(Key(slot_id.raw()), |composer| content(composer))
1718        });
1719
1720        let frame = {
1721            let frame = take_subcompose_frame(&guard.core, "subcompose");
1722            guard.leaked = true;
1723            frame
1724        };
1725        let nodes = frame.nodes;
1726        let scopes = frame.scopes;
1727        state.register_active(slot_id, &nodes, &scopes);
1728        (result, nodes)
1729    }
1730
1731    /// Composes `content` in the slot `slot_id` of `state` and returns its result with the ids of
1732    /// the nodes it produced that have no parent. Panics outside the measure and layout phases.
1733    pub fn subcompose_measurement<R>(
1734        &self,
1735        state: &mut SubcomposeState,
1736        slot_id: SlotId,
1737        content: impl FnOnce(&Self) -> R,
1738    ) -> (R, Vec<NodeId>) {
1739        let (result, nodes) = self.subcompose(state, slot_id, content);
1740        let roots = nodes
1741            .into_iter()
1742            .filter(|&id| self.node_has_no_parent(id))
1743            .collect();
1744
1745        (result, roots)
1746    }
1747
1748    /// What a subcomposition this composer runs takes from it.
1749    fn subcompose_site(&self) -> SubcomposeSite<'_> {
1750        SubcomposeSite {
1751            applier: &self.core.applier,
1752            runtime: &self.core.runtime,
1753            phase: self.phase(),
1754            locals_changed: self.core.locals_changed.get(),
1755        }
1756    }
1757
1758    /// Composes `f` as an independent pass over the separate slot table `slots` and applies its
1759    /// node changes before returning. Top-level nodes from `f` attach under `root`, if any. The
1760    /// pass sees the composition locals in scope at the call.
1761    pub fn subcompose_in<R>(
1762        &self,
1763        slots: &Rc<SlotsHost>,
1764        root: Option<NodeId>,
1765        f: impl FnOnce(&Self) -> R,
1766    ) -> Result<R, NodeError> {
1767        let _teardown = runtime::enter_state_teardown_scope();
1768        let site = self.subcompose_site();
1769        let shared_state = slots
1770            .runtime_state()
1771            .unwrap_or_else(|| Rc::clone(&self.core.shared_state));
1772        let core = site.spin_up_core(shared_state, slots, root, self.current_local_stack());
1773        let composer = Self::from_core(core);
1774        let (result, commands, side_effects, compact_applier) = composer.install(|composer| {
1775            let (output, outcome) = composer.try_with_slot_host_pass(
1776                Rc::clone(slots),
1777                crate::slot::SlotPassMode::Compose,
1778                |composer| f(composer),
1779            )?;
1780            let commands = composer.take_commands();
1781            let side_effects = composer.take_side_effects();
1782            Ok((output, commands, side_effects, outcome.compacted))
1783        })?;
1784        site.flush(commands, compact_applier, side_effects)?;
1785        Ok(result)
1786    }
1787
1788    /// Captures the composition context at the current point so work composed
1789    /// in another slot host inherits both locals and source ownership.
1790    ///
1791    /// A `SubcomposeLayout` captures this while it is being composed and replays
1792    /// it while subcomposing off the measure pass, so content that is
1793    /// subcomposed during layout observes the same composition locals as the
1794    /// `SubcomposeLayout` call site — matching Jetpack Compose, where a
1795    /// subcomposition inherits the composition locals of the layout that
1796    /// created it rather than whatever happens to be in scope during measure
1797    /// (which, after composition unwinds, no longer carries ancestor providers).
1798    pub fn capture_composition_context(&self) -> CapturedCompositionContext {
1799        CapturedCompositionContext {
1800            locals: self.current_local_stack(),
1801            owner_scope: self
1802                .current_recompose_scope()
1803                .map(|scope| scope.downgrade()),
1804            locals_changed: self.core.locals_changed.get(),
1805        }
1806    }
1807
1808    /// Runs `f` with the composition locals of `context` in scope, as at the
1809    /// site that captured it: content that composes elsewhere, as a popup's
1810    /// content at the window's root, reads the locals of the site that placed
1811    /// it. Compose's `CompositionLocalProvider(currentCompositionLocalContext)`.
1812    pub fn with_captured_locals<R>(
1813        &self,
1814        context: &CapturedCompositionContext,
1815        f: impl FnOnce(&Self) -> R,
1816    ) -> R {
1817        let parent = self.current_local_stack();
1818        self.local_stack().clone_from(&context.locals);
1819        let result = self.with_locals_changed(context.locals_changed, f);
1820        *self.local_stack() = parent;
1821        result
1822    }
1823
1824    /// Runs `f` as content under a static composition local that changed
1825    /// when `changed`: every group it opens runs its body, as under the
1826    /// provider of a changed static local.
1827    pub fn with_locals_changed<R>(&self, changed: bool, f: impl FnOnce(&Self) -> R) -> R {
1828        let outer = self.core.locals_changed.get();
1829        self.core.locals_changed.set(outer || changed);
1830        let result = f(self);
1831        self.core.locals_changed.set(outer);
1832        result
1833    }
1834
1835    /// Subcomposes content using an isolated SlotsHost without resetting it.
1836    /// Unlike `subcompose_in`, this preserves existing slot state across calls,
1837    /// allowing efficient reuse during measurement passes. This is critical for
1838    /// lazy lists where items need stable slot positions.
1839    pub fn subcompose_slot<R>(
1840        &self,
1841        slots: &Rc<SlotsHost>,
1842        root: Option<NodeId>,
1843        f: impl FnOnce(&Self) -> R,
1844    ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1845        let context = self.capture_composition_context();
1846        self.subcompose_slot_with_context(slots, root, &context, f)
1847    }
1848
1849    /// Like [`Composer::subcompose_slot`], but uses a context captured at the
1850    /// source composition site. This is required for measure-time composition,
1851    /// where the source scope is no longer on the active stack.
1852    pub fn subcompose_slot_with_context<R>(
1853        &self,
1854        slots: &Rc<SlotsHost>,
1855        root: Option<NodeId>,
1856        context: &CapturedCompositionContext,
1857        f: impl FnOnce(&Self) -> R,
1858    ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1859        subcompose_slot_at(
1860            self.subcompose_site(),
1861            || Rc::clone(&self.core.shared_state),
1862            slots,
1863            root,
1864            context,
1865            f,
1866        )
1867    }
1868
1869    /// Subcomposes `f` into `slots` for a measure pass that runs under no
1870    /// composer, as [`Self::subcompose_slot_with_context`] does under one:
1871    /// the nodes go to `applier` under `root`, in the measure phase. A host
1872    /// without a runtime state takes a new one bound to `applier`.
1873    pub fn subcompose_measure_slot<R>(
1874        applier: &Rc<dyn ApplierHost>,
1875        runtime: &RuntimeHandle,
1876        slots: &Rc<SlotsHost>,
1877        root: NodeId,
1878        context: &CapturedCompositionContext,
1879        f: impl FnOnce(&Self) -> R,
1880    ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1881        let site = SubcomposeSite {
1882            applier,
1883            runtime,
1884            phase: crate::Phase::Measure,
1885            locals_changed: false,
1886        };
1887        let new_state = || measure_slot_state(applier, context);
1888        subcompose_slot_at(site, new_state, slots, Some(root), context, f)
1889    }
1890
1891    fn attach_root_nodes(&self, root_nodes: RootNodeIds) {
1892        for id in root_nodes {
1893            self.attach_to_parent(id);
1894        }
1895    }
1896
1897    /// Skips the currently open group without running it again. Its nodes and remembered values
1898    /// stay as the last composition left them.
1899    pub fn skip_current_group(&self) {
1900        #[expect(
1901            clippy::redundant_closure_for_method_calls,
1902            reason = "the method path is not general over the session lifetime"
1903        )]
1904        self.with_slot_session_mut(|slots| slots.skip_group());
1905    }
1906
1907    /// Returns a handle to the runtime of this composer.
1908    pub fn runtime_handle(&self) -> RuntimeHandle {
1909        self.core.runtime.clone()
1910    }
1911
1912    /// Registers `callback` as the code that recomposes the current scope when state it read
1913    /// changes. Does nothing outside a recompose scope.
1914    pub fn set_recompose_callback<F>(&self, callback: F)
1915    where
1916        F: FnMut(&Self) + 'static,
1917    {
1918        if let Some(scope) = self.current_recompose_scope() {
1919            scope.set_recompose_callback(callback);
1920        }
1921    }
1922
1923    /// Like `set_recompose_callback` for a plain function pointer.
1924    pub fn set_recompose_fn(&self, callback: fn(&Self)) {
1925        if let Some(scope) = self.current_recompose_scope() {
1926            scope.set_recompose_fn(callback);
1927        }
1928    }
1929
1930    /// Runs `f` with `provided` in scope over the locals around it; of values
1931    /// for one local, the last wins.
1932    pub fn with_composition_locals<R>(
1933        &self,
1934        provided: impl IntoIterator<Item = ProvidedValue>,
1935        site: Key,
1936        f: impl FnOnce(&Self) -> R,
1937    ) -> R {
1938        let provided: SmallVec<[ProvidedValue; 2]> = provided.into_iter().collect();
1939        if provided.is_empty() {
1940            return f(self);
1941        }
1942        let mut values = SmallVec::<[(LocalKey, Rc<dyn Any>); 2]>::new();
1943        let mut static_changed = false;
1944        for value in provided.into_iter().rev() {
1945            if values.iter().any(|(key, _)| key == value.key()) {
1946                continue;
1947            }
1948            let (key, entry, changed) = value.into_entry(self, site);
1949            static_changed |= changed;
1950            values.push((key, entry));
1951        }
1952        let parent = self.current_local_stack();
1953        *self.local_stack() = Some(Rc::new(LocalFrame {
1954            values,
1955            parent: parent.clone(),
1956        }));
1957        let result = self.with_locals_changed(static_changed, f);
1958        *self.local_stack() = parent;
1959        result
1960    }
1961}