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