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