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, ApplierHost, COMMAND_FLUSH_THRESHOLD, ChildList, Command, CommandQueue,
13    CompositionLocal, DirtyBubble, Key, LocalKey, LocalStackSnapshot, LocalStateEntry,
14    MutableState, Node, NodeError, NodeId, Owned, ProvidedValue, RecomposeOptions, RecomposeScope,
15    RecomposeScopeInner, RecycledNode, RetentionMode, RetentionPolicy, RuntimeHandle, ScopeId,
16    SlotId, SlotPassOutcome, SlotTable, SlotsHost, SnapshotStateList, SnapshotStateMap,
17    SnapshotStateObserver, StaticCompositionLocal, StaticLocalEntry, SubcomposeState,
18    collections::map::{HashMap, HashSet},
19    composer_context, empty_local_stack, explicit_group_key_seed,
20    retention::{RetainKey, RetentionManager},
21    runtime,
22    slot::{FinishGroupResult, GroupStart, GroupStartKind, PayloadKind, ValueSlotId},
23};
24
25pub struct ValueSlotHandle<'pass, T: 'static> {
26    slot: ValueSlotId,
27    _pass: PhantomData<&'pass Composer>,
28    _value: PhantomData<fn() -> T>,
29}
30
31impl<T: 'static> Copy for ValueSlotHandle<'_, T> {}
32
33impl<T: 'static> Clone for ValueSlotHandle<'_, T> {
34    fn clone(&self) -> Self {
35        *self
36    }
37}
38
39impl<T: 'static> ValueSlotHandle<'_, T> {
40    pub(crate) fn new(slot: ValueSlotId) -> Self {
41        Self {
42            slot,
43            _pass: PhantomData,
44            _value: PhantomData,
45        }
46    }
47
48    pub(crate) fn slot(self) -> ValueSlotId {
49        self.slot
50    }
51}
52
53fn slots_storage_key(host: &Rc<SlotsHost>) -> usize {
54    host.storage_key()
55}
56
57fn bind_slots_host_to_runtime_state(
58    state: &Rc<ComposerRuntimeState>,
59    host: &Rc<SlotsHost>,
60) -> Rc<SlotsHost> {
61    if let Some(bound_state) = host.runtime_state() {
62        if Rc::ptr_eq(&bound_state, state) {
63            state.bind_slots_host(host);
64            return Rc::clone(host);
65        }
66        drop(bound_state);
67        if host.rebind_orphaned_runtime_state(state) {
68            state.bind_slots_host(host);
69            return Rc::clone(host);
70        }
71        log::error!(
72            "slot host already belongs to a different composer runtime state; using a fresh slot host"
73        );
74        let replacement = Rc::new(SlotsHost::new(SlotTable::new()));
75        state.bind_slots_host(&replacement);
76        return replacement;
77    }
78    state.bind_slots_host(host);
79    Rc::clone(host)
80}
81
82struct SlotHostPassGuard {
83    core: Rc<ComposerCore>,
84    host: Rc<SlotsHost>,
85    active: bool,
86}
87
88impl SlotHostPassGuard {
89    fn close(&mut self) {
90        if !self.active {
91            return;
92        }
93        if self.host.has_active_pass() {
94            self.host.abandon_active_pass();
95        }
96        match self.core.slot_hosts.borrow_mut().pop() {
97            Some(host) if Rc::ptr_eq(&host, &self.host) => {}
98            Some(_) => {
99                log::error!("slot host stack mismatch while closing slot host pass");
100            }
101            None => {
102                log::error!("slot host stack underflow while closing slot host pass");
103            }
104        }
105        self.active = false;
106    }
107}
108
109impl Drop for SlotHostPassGuard {
110    fn drop(&mut self) {
111        self.close();
112    }
113}
114
115pub(crate) struct ComposerRuntimeState {
116    scope_registry: RefCell<HashMap<ScopeId, RecomposeScope>>,
117    retention_by_host: RefCell<HashMap<usize, RetentionManager>>,
118    retention_policy: Cell<RetentionPolicy>,
119    live_hosts: RefCell<HashMap<usize, std::rc::Weak<SlotsHost>>>,
120    applier_host: RefCell<Option<std::rc::Weak<dyn ApplierHost>>>,
121}
122
123impl Default for ComposerRuntimeState {
124    fn default() -> Self {
125        Self {
126            scope_registry: RefCell::new(HashMap::default()),
127            retention_by_host: RefCell::new(HashMap::default()),
128            retention_policy: Cell::new(RetentionPolicy::default()),
129            live_hosts: RefCell::new(HashMap::default()),
130            applier_host: RefCell::new(None),
131        }
132    }
133}
134
135impl ComposerRuntimeState {
136    pub(crate) fn clear_host_storage_key(&self, host_key: usize) {
137        self.retention_by_host.borrow_mut().remove(&host_key);
138        self.live_hosts.borrow_mut().remove(&host_key);
139        let removed_scopes = {
140            let mut removed = Vec::new();
141            self.scope_registry.borrow_mut().retain(|_, scope| {
142                if scope.slots_storage_key() == Some(host_key) {
143                    removed.push(scope.clone());
144                    false
145                } else {
146                    true
147                }
148            });
149            removed
150        };
151        for scope in removed_scopes {
152            scope.deactivate();
153        }
154    }
155
156    pub(crate) fn force_recompose_host_scopes(&self, host_key: usize) {
157        for scope in self.scope_registry.borrow().values() {
158            if scope.slots_storage_key() == Some(host_key) {
159                scope.force_recompose();
160            }
161        }
162    }
163
164    pub(crate) fn bind_applier_host(&self, applier: &Rc<dyn ApplierHost>) {
165        *self.applier_host.borrow_mut() = Some(Rc::downgrade(applier));
166    }
167
168    pub(crate) fn has_live_applier_host(&self) -> bool {
169        self.applier_host
170            .borrow()
171            .as_ref()
172            .and_then(std::rc::Weak::upgrade)
173            .is_some()
174    }
175
176    pub(crate) fn bind_slots_host(self: &Rc<Self>, host: &Rc<SlotsHost>) {
177        host.bind_runtime_state(self);
178        self.live_hosts
179            .borrow_mut()
180            .insert(host.storage_key(), Rc::downgrade(host));
181    }
182
183    pub(crate) fn scope_for_id(&self, scope_id: ScopeId) -> Option<RecomposeScope> {
184        self.scope_registry.borrow().get(&scope_id).cloned()
185    }
186
187    pub(crate) fn register_scope(&self, scope: &RecomposeScope) {
188        self.scope_registry
189            .borrow_mut()
190            .insert(scope.id(), scope.clone());
191    }
192
193    pub(crate) fn remove_scope(&self, scope_id: ScopeId) -> Option<RecomposeScope> {
194        self.scope_registry.borrow_mut().remove(&scope_id)
195    }
196
197    pub(crate) fn set_retention_policy(&self, policy: RetentionPolicy) {
198        self.retention_policy.set(policy);
199    }
200
201    pub(crate) fn retention_policy(&self) -> RetentionPolicy {
202        self.retention_policy.get()
203    }
204
205    pub(crate) fn scope_registry_len(&self) -> usize {
206        self.scope_registry.borrow().len()
207    }
208
209    pub(crate) fn take_retained(
210        &self,
211        host: &Rc<SlotsHost>,
212        key: RetainKey,
213        preflight: impl FnOnce(&crate::slot::DetachedSubtree) -> bool,
214    ) -> Option<crate::slot::DetachedSubtree> {
215        let host_key = slots_storage_key(host);
216        let mut retention = self.retention_by_host.borrow_mut();
217        let subtree = retention
218            .get_mut(&host_key)?
219            .take_after_restore_preflight(key, preflight);
220        if retention
221            .get(&host_key)
222            .is_some_and(|manager| manager.is_empty() && manager.evictions_total() == 0)
223        {
224            retention.remove(&host_key);
225        }
226        subtree
227    }
228
229    pub(crate) fn insert_retained(
230        &self,
231        host: &Rc<SlotsHost>,
232        key: RetainKey,
233        subtree: crate::slot::DetachedSubtree,
234    ) -> Vec<crate::slot::DetachedSubtree> {
235        let policy = self.retention_policy();
236        let mut retention_by_host = self.retention_by_host.borrow_mut();
237        let manager = retention_by_host
238            .entry(slots_storage_key(host))
239            .or_insert_with(|| RetentionManager::new(policy));
240        manager.set_policy(policy);
241        manager.insert(key, subtree)
242    }
243
244    pub(crate) fn advance_retention_pass(
245        &self,
246        host: &Rc<SlotsHost>,
247    ) -> Vec<crate::slot::DetachedSubtree> {
248        let host_key = slots_storage_key(host);
249        let policy = self.retention_policy();
250        let mut retention_by_host = self.retention_by_host.borrow_mut();
251        let Some(manager) = retention_by_host.get_mut(&host_key) else {
252            return Vec::new();
253        };
254        manager.set_policy(policy);
255        manager.advance_pass()
256    }
257
258    pub(crate) fn fill_slot_debug_snapshot(
259        &self,
260        host: &SlotsHost,
261        snapshot: &mut crate::SlotDebugSnapshot,
262    ) {
263        let retention = self.retention_debug_stats(host.storage_key());
264        snapshot.runtime_scope_registry_count = Some(self.scope_registry_len());
265        snapshot.retained_subtree_count = retention.subtree_count;
266        snapshot.retained_group_count = retention.group_count;
267        snapshot.retained_payload_count = retention.payload_count;
268        snapshot.retained_node_count = retention.node_count;
269        snapshot.retained_scope_count = retention.scope_count;
270    }
271
272    pub(crate) fn slot_retention_debug_stats(
273        &self,
274        host: &SlotsHost,
275    ) -> crate::slot::SlotRetentionDebugStats {
276        let retention = self.retention_debug_stats(host.storage_key());
277        crate::slot::SlotRetentionDebugStats {
278            retained_subtree_count: retention.subtree_count,
279            retained_group_count: retention.group_count,
280            retained_payload_count: retention.payload_count,
281            retained_node_count: retention.node_count,
282            retained_scope_count: retention.scope_count,
283            retained_anchor_count: retention.anchor_count,
284            retained_heap_bytes: retention.heap_bytes,
285            retained_evictions_total: retention.evictions_total,
286        }
287    }
288
289    pub(crate) fn compact_table_identity_storage_for_host(
290        &self,
291        host: &SlotsHost,
292        table: &mut SlotTable,
293        compact_anchors: bool,
294        compact_payloads: bool,
295    ) {
296        if !compact_anchors && !compact_payloads {
297            return;
298        }
299
300        let host_key = host.storage_key();
301        let mut retention = self.retention_by_host.borrow_mut();
302        if let Some(retained) = retention.get_mut(&host_key) {
303            if compact_anchors {
304                table.compact_anchor_registry_storage(Some(&mut *retained));
305            }
306            if compact_payloads {
307                table.compact_payload_anchor_registry_storage(Some(&mut *retained));
308            }
309        } else {
310            if compact_anchors {
311                table.compact_anchor_registry_storage(None);
312            }
313            if compact_payloads {
314                table.compact_payload_anchor_registry_storage(None);
315            }
316        }
317    }
318
319    pub(crate) fn clear_host(&self, host: &SlotsHost) {
320        let host_key = host.storage_key();
321        debug_assert!(
322            self.host_retention_is_empty(host),
323            "host retention must be drained before clearing host ownership"
324        );
325        self.clear_host_storage_key(host_key);
326    }
327
328    fn deactivate_and_queue_subtrees(
329        &self,
330        retention: RetentionManager,
331        table: &mut SlotTable,
332        lifecycle: &mut crate::slot::SlotLifecycleCoordinator,
333    ) {
334        for subtree in retention.into_subtrees() {
335            for scope_id in subtree.scope_ids() {
336                if let Some(scope) = self.remove_scope(scope_id) {
337                    scope.deactivate();
338                }
339            }
340            table.invalidate_detached_subtree_anchors(&subtree);
341            lifecycle.queue_subtree_disposal(subtree);
342        }
343    }
344
345    pub(crate) fn dispose_retained_subtrees_for_host(
346        &self,
347        host_key: usize,
348        table: &mut SlotTable,
349        lifecycle: &mut crate::slot::SlotLifecycleCoordinator,
350    ) -> Result<(), NodeError> {
351        let applier_host = self
352            .applier_host
353            .borrow()
354            .as_ref()
355            .and_then(std::rc::Weak::upgrade);
356        if let Some(applier_host) = applier_host.as_ref() {
357            let retention_by_host = self.retention_by_host.borrow();
358            let Some(retention) = retention_by_host.get(&host_key) else {
359                return Ok(());
360            };
361            let mut applier = applier_host.borrow_dyn();
362            for subtree in retention.subtrees() {
363                crate::slot::dispose_detached_subtree_now(&mut *applier, subtree)?;
364            }
365        }
366        let Some(retention) = self.retention_by_host.borrow_mut().remove(&host_key) else {
367            return Ok(());
368        };
369        self.deactivate_and_queue_subtrees(retention, table, lifecycle);
370        Ok(())
371    }
372
373    pub(crate) fn abandon_retained_subtrees_for_host(
374        &self,
375        host_key: usize,
376        table: &mut SlotTable,
377        lifecycle: &mut crate::slot::SlotLifecycleCoordinator,
378    ) {
379        let Some(retention) = self.retention_by_host.borrow_mut().remove(&host_key) else {
380            self.clear_host_storage_key(host_key);
381            return;
382        };
383        self.deactivate_and_queue_subtrees(retention, table, lifecycle);
384        self.clear_host_storage_key(host_key);
385    }
386
387    pub(crate) fn host_retention_is_empty(&self, host: &SlotsHost) -> bool {
388        self.retention_by_host
389            .borrow()
390            .get(&host.storage_key())
391            .is_none_or(RetentionManager::is_empty)
392    }
393
394    #[cfg(any(test, debug_assertions))]
395    pub(crate) fn debug_verify_host(&self, host: &SlotsHost, table: &SlotTable) {
396        if let Some(retention) = self.retention_by_host.borrow().get(&host.storage_key()) {
397            retention.debug_verify(table);
398        }
399    }
400
401    #[cfg(test)]
402    pub(crate) fn validate_host_retention(
403        &self,
404        host: &SlotsHost,
405        table: &SlotTable,
406    ) -> Result<(), crate::slot::SlotInvariantError> {
407        if let Some(retention) = self.retention_by_host.borrow().get(&host.storage_key()) {
408            retention.validate(table)?;
409        }
410        Ok(())
411    }
412
413    pub(crate) fn host_for_storage_key(&self, storage_key: usize) -> Option<Rc<SlotsHost>> {
414        self.live_hosts
415            .borrow()
416            .get(&storage_key)
417            .and_then(std::rc::Weak::upgrade)
418    }
419
420    fn retention_debug_stats(&self, host_key: usize) -> crate::retention::RetentionDebugStats {
421        self.retention_by_host
422            .borrow()
423            .get(&host_key)
424            .map(RetentionManager::debug_stats)
425            .unwrap_or_default()
426    }
427}
428
429pub(crate) struct ParentFrame {
430    pub(crate) id: NodeId,
431    pub(crate) previous: ChildList,
432    pub(crate) new_children: ChildList,
433    pub(crate) new_children_membership: Option<HashSet<NodeId>>,
434    pub(crate) attach_mode: ParentAttachMode,
435    pub(crate) synthetic_root: bool,
436}
437
438#[derive(Clone, Copy)]
439pub(crate) enum InitialParentFrame {
440    SyntheticRoot,
441    RealParent,
442}
443
444const LARGE_DEFERRED_CHILD_TRACKING_THRESHOLD: usize = 16;
445
446#[derive(Clone, Copy, Debug, PartialEq, Eq)]
447pub(crate) enum ParentAttachMode {
448    ImmediateAppend,
449    DeferredSync,
450}
451
452#[derive(Default)]
453pub(crate) struct SubcomposeFrame {
454    pub(crate) nodes: Vec<NodeId>,
455    pub(crate) scopes: Vec<RecomposeScope>,
456}
457
458#[derive(Default, Clone)]
459pub(crate) struct LocalContext {
460    pub(crate) values: HashMap<LocalKey, Rc<dyn Any>>,
461}
462
463pub(crate) struct ComposerCore {
464    pub(crate) shared_state: Rc<ComposerRuntimeState>,
465    pub(crate) slots: Rc<SlotsHost>,
466    slot_hosts: RefCell<Vec<Rc<SlotsHost>>>,
467    pub(crate) applier: Rc<dyn ApplierHost>,
468    pub(crate) runtime: RuntimeHandle,
469    pub(crate) observer: SnapshotStateObserver,
470    pub(crate) parent_stack: RefCell<Vec<ParentFrame>>,
471    pub(crate) subcompose_stack: RefCell<Vec<SubcomposeFrame>>,
472    pub(crate) root: Cell<Option<NodeId>>,
473    pub(crate) commands: RefCell<CommandQueue>,
474    pub(crate) scope_stack: RefCell<Vec<RecomposeScope>>,
475    subcomposition_owner_scope: RefCell<Option<RecomposeScope>>,
476    pub(crate) local_stack: RefCell<LocalStackSnapshot>,
477    pub(crate) side_effects: RefCell<Vec<Box<dyn FnOnce()>>>,
478    pub(crate) pending_scope_options: RefCell<Option<RecomposeOptions>>,
479    pub(crate) phase: Cell<crate::Phase>,
480    pub(crate) last_node_reused: Cell<Option<bool>>,
481    pub(crate) recompose_parent_hint: Cell<Option<NodeId>>,
482    pub(crate) root_render_requested: Cell<bool>,
483    pub(crate) _not_send: PhantomData<*const ()>,
484}
485
486/// The composition context inherited by work that is composed in another slot
487/// host. Besides composition locals, this carries the source owner scope so a
488/// secondary tree cannot outlive the composition that supplied its callbacks.
489#[derive(Clone)]
490pub struct CapturedCompositionContext {
491    locals: LocalStackSnapshot,
492    owner_scope: Option<Weak<RecomposeScopeInner>>,
493}
494
495impl CapturedCompositionContext {
496    /// Total deactivations along the capturing scope's owner chain right now;
497    /// see [`crate::RecomposeScope::owner_chain_deactivation_epoch`]. Zero
498    /// when the context has no owner scope or it is gone.
499    pub fn owner_chain_deactivation_epoch(&self) -> u64 {
500        self.owner_scope
501            .as_ref()
502            .and_then(Weak::upgrade)
503            .map(|inner| crate::RecomposeScope { inner }.owner_chain_deactivation_epoch())
504            .unwrap_or(0)
505    }
506}
507
508fn take_subcompose_frame(core: &ComposerCore, operation: &str) -> SubcomposeFrame {
509    match core.subcompose_stack.borrow_mut().pop() {
510        Some(frame) => frame,
511        None => {
512            log::error!("subcompose stack underflow while finishing {operation}");
513            SubcomposeFrame::default()
514        }
515    }
516}
517
518struct SubcomposeStackGuard {
519    core: Rc<ComposerCore>,
520    leaked: bool,
521}
522
523impl Drop for SubcomposeStackGuard {
524    fn drop(&mut self) {
525        if !self.leaked {
526            self.core.subcompose_stack.borrow_mut().pop();
527        }
528    }
529}
530
531impl ComposerCore {
532    pub(crate) fn new(
533        shared_state: Rc<ComposerRuntimeState>,
534        slots: Rc<SlotsHost>,
535        applier: Rc<dyn ApplierHost>,
536        runtime: RuntimeHandle,
537        observer: SnapshotStateObserver,
538        root: Option<NodeId>,
539        initial_parent_frame: InitialParentFrame,
540    ) -> Self {
541        let parent_stack = if let Some(root_id) = root {
542            vec![ParentFrame {
543                id: root_id,
544                previous: ChildList::new(),
545                new_children: ChildList::new(),
546                new_children_membership: None,
547                attach_mode: ParentAttachMode::DeferredSync,
548                synthetic_root: matches!(initial_parent_frame, InitialParentFrame::SyntheticRoot),
549            }]
550        } else {
551            Vec::new()
552        };
553
554        Self {
555            shared_state,
556            slots,
557            slot_hosts: RefCell::new(Vec::new()),
558            applier,
559            runtime,
560            observer,
561            parent_stack: RefCell::new(parent_stack),
562            subcompose_stack: RefCell::new(Vec::new()),
563            root: Cell::new(root),
564            commands: RefCell::new(CommandQueue::default()),
565            scope_stack: RefCell::new(Vec::new()),
566            subcomposition_owner_scope: RefCell::new(None),
567            local_stack: RefCell::new(empty_local_stack()),
568            side_effects: RefCell::new(Vec::new()),
569            pending_scope_options: RefCell::new(None),
570            phase: Cell::new(crate::Phase::Compose),
571            last_node_reused: Cell::new(None),
572            recompose_parent_hint: Cell::new(None),
573            root_render_requested: Cell::new(false),
574            _not_send: PhantomData,
575        }
576    }
577}
578
579#[derive(Clone)]
580pub struct Composer {
581    pub(crate) core: Rc<ComposerCore>,
582}
583
584pub struct BranchGroupGuard {
585    composer: Composer,
586    fold_token: Option<usize>,
587}
588
589impl Drop for BranchGroupGuard {
590    fn drop(&mut self) {
591        let Some(token) = self.fold_token else {
592            return;
593        };
594        if !self
595            .composer
596            .active_slots_host()
597            .try_close_branch_fold(token)
598        {
599            log::error!("a branch fold guard closed while its slot host was busy");
600        }
601    }
602}
603
604pub(crate) enum EmittedNode {
605    Fresh(Box<dyn Node>),
606    Recycled(RecycledNode),
607}
608
609impl Composer {
610    pub(crate) fn new_with_shared_state(
611        shared_state: Rc<ComposerRuntimeState>,
612        slots: Rc<SlotsHost>,
613        applier: Rc<dyn ApplierHost>,
614        runtime: RuntimeHandle,
615        observer: SnapshotStateObserver,
616        root: Option<NodeId>,
617    ) -> Self {
618        Self::new_with_shared_state_with_parent_frame(
619            shared_state,
620            slots,
621            applier,
622            runtime,
623            observer,
624            root,
625            InitialParentFrame::SyntheticRoot,
626        )
627    }
628
629    fn new_with_shared_state_with_parent_frame(
630        shared_state: Rc<ComposerRuntimeState>,
631        slots: Rc<SlotsHost>,
632        applier: Rc<dyn ApplierHost>,
633        runtime: RuntimeHandle,
634        observer: SnapshotStateObserver,
635        root: Option<NodeId>,
636        initial_parent_frame: InitialParentFrame,
637    ) -> Self {
638        shared_state.bind_applier_host(&applier);
639        let slots = bind_slots_host_to_runtime_state(&shared_state, &slots);
640        let core = Rc::new(ComposerCore::new(
641            shared_state,
642            slots,
643            applier,
644            runtime,
645            observer,
646            root,
647            initial_parent_frame,
648        ));
649        Self { core }
650    }
651
652    pub fn new(
653        slots: Rc<SlotsHost>,
654        applier: Rc<dyn ApplierHost>,
655        runtime: RuntimeHandle,
656        observer: SnapshotStateObserver,
657        root: Option<NodeId>,
658    ) -> Self {
659        Self::new_with_shared_state_with_parent_frame(
660            slots
661                .runtime_state()
662                .unwrap_or_else(|| Rc::new(ComposerRuntimeState::default())),
663            slots,
664            applier,
665            runtime,
666            observer,
667            root,
668            InitialParentFrame::RealParent,
669        )
670    }
671
672    pub(crate) fn from_core(core: Rc<ComposerCore>) -> Self {
673        Self { core }
674    }
675
676    pub(crate) fn clone_core(&self) -> Rc<ComposerCore> {
677        Rc::clone(&self.core)
678    }
679
680    fn observer(&self) -> SnapshotStateObserver {
681        self.core.observer.clone()
682    }
683
684    pub(crate) fn request_root_render(&self) {
685        self.core.root_render_requested.set(true);
686    }
687
688    pub(crate) fn take_root_render_request(&self) -> bool {
689        self.core.root_render_requested.replace(false)
690    }
691
692    pub(crate) fn observe_scope<R>(&self, scope: &RecomposeScope, block: impl FnOnce() -> R) -> R {
693        let observer = self.observer();
694        let scope_clone = scope.clone();
695        observer.observe_reads(scope_clone, move |scope_ref| scope_ref.invalidate(), block)
696    }
697
698    pub fn active_slots_host(&self) -> Rc<SlotsHost> {
699        self.core
700            .slot_hosts
701            .borrow()
702            .last()
703            .cloned()
704            .unwrap_or_else(|| Rc::clone(&self.core.slots))
705    }
706
707    pub(crate) fn with_slots<R>(&self, f: impl FnOnce(&SlotTable) -> R) -> R {
708        let host = self.active_slots_host();
709        let slots = host.borrow();
710        f(&slots)
711    }
712
713    pub(crate) fn with_slots_mut<R>(&self, f: impl FnOnce(&mut SlotTable) -> R) -> R {
714        let host = self.active_slots_host();
715        let mut slots = host.borrow_mut();
716        f(&mut slots)
717    }
718
719    pub(crate) fn with_slot_session_mut<R>(
720        &self,
721        f: impl FnOnce(&mut crate::slot::SlotWriteSession<'_>) -> R,
722    ) -> R {
723        self.active_slots_host().with_write_session(f)
724    }
725
726    pub(crate) fn try_with_slot_host_pass<R>(
727        &self,
728        slots: Rc<SlotsHost>,
729        mode: crate::slot::SlotPassMode,
730        f: impl FnOnce(&Composer) -> R,
731    ) -> Result<(R, SlotPassOutcome), NodeError> {
732        let mut guard = self.begin_slot_host_pass(&slots, mode);
733        let result = f(self);
734        let outcome = self.finish_slot_host_pass(&guard.host)?;
735        guard.close();
736        Ok((result, outcome))
737    }
738
739    pub(crate) fn with_slot_host_pass<R>(
740        &self,
741        slots: Rc<SlotsHost>,
742        mode: crate::slot::SlotPassMode,
743        f: impl FnOnce(&Composer) -> R,
744    ) -> (R, SlotPassOutcome) {
745        let mut guard = self.begin_slot_host_pass(&slots, mode);
746        let result = f(self);
747        let outcome = match self.finish_slot_host_pass(&guard.host) {
748            Ok(outcome) => outcome,
749            Err(err) => {
750                log::error!("slot host pass finalization failed: {err}");
751                SlotPassOutcome::default()
752            }
753        };
754        guard.close();
755        (result, outcome)
756    }
757
758    pub(crate) fn with_slot_override<R>(
759        &self,
760        slots: Rc<SlotsHost>,
761        f: impl FnOnce(&Composer) -> R,
762    ) -> (R, SlotPassOutcome) {
763        self.with_slot_host_pass(slots, crate::slot::SlotPassMode::Compose, f)
764    }
765
766    fn begin_slot_host_pass(
767        &self,
768        slots: &Rc<SlotsHost>,
769        mode: crate::slot::SlotPassMode,
770    ) -> SlotHostPassGuard {
771        let slots = bind_slots_host_to_runtime_state(&self.core.shared_state, slots);
772        slots.begin_pass(mode);
773        {
774            let mut stack = self.core.slot_hosts.borrow_mut();
775            if let Some(parent) = stack.last()
776                && !Rc::ptr_eq(parent, &slots)
777            {
778                parent.note_nested_host(&slots);
779            }
780            stack.push(Rc::clone(&slots));
781        }
782        SlotHostPassGuard {
783            core: self.clone_core(),
784            host: slots,
785            active: true,
786        }
787    }
788
789    fn finish_slot_host_pass(&self, slots: &Rc<SlotsHost>) -> Result<SlotPassOutcome, NodeError> {
790        let finished = {
791            let mut applier = self.core.applier.borrow_dyn();
792            slots.finish_pass(&mut *applier)
793        }?;
794        self.handle_detached_children_in_host(slots, None, finished.detached_root_children)?;
795        self.evict_retained_subtrees_for_host(slots)?;
796        slots.complete_pass_cleanup(&finished.outcome);
797        Ok(finished.outcome)
798    }
799
800    pub(crate) fn parent_stack(&self) -> RefMut<'_, Vec<ParentFrame>> {
801        self.core.parent_stack.borrow_mut()
802    }
803
804    fn current_parent_hint(&self) -> Option<NodeId> {
805        let stack = self.core.parent_stack.borrow();
806        let stack_hint = stack
807            .last()
808            .and_then(|frame| (!frame.synthetic_root).then_some(frame.id));
809        stack_hint.or_else(|| self.core.recompose_parent_hint.get())
810    }
811
812    pub(crate) fn subcompose_stack(&self) -> RefMut<'_, Vec<SubcomposeFrame>> {
813        self.core.subcompose_stack.borrow_mut()
814    }
815
816    pub(crate) fn commands_mut(&self) -> RefMut<'_, CommandQueue> {
817        self.core.commands.borrow_mut()
818    }
819
820    pub(crate) fn enqueue_semantics_invalidation(&self, id: NodeId) {
821        self.commands_mut().push(Command::BubbleDirty {
822            node_id: id,
823            bubble: DirtyBubble::SEMANTICS,
824        });
825    }
826
827    pub(crate) fn scope_stack(&self) -> RefMut<'_, Vec<RecomposeScope>> {
828        self.core.scope_stack.borrow_mut()
829    }
830
831    fn scope_for_id(&self, scope_id: ScopeId) -> Option<RecomposeScope> {
832        self.core.shared_state.scope_for_id(scope_id)
833    }
834
835    fn register_scope(&self, scope: &RecomposeScope) {
836        self.core.shared_state.register_scope(scope);
837    }
838
839    fn remove_scope(&self, scope_id: ScopeId) -> Option<RecomposeScope> {
840        self.core.shared_state.remove_scope(scope_id)
841    }
842
843    pub(crate) fn local_stack(&self) -> RefMut<'_, LocalStackSnapshot> {
844        self.core.local_stack.borrow_mut()
845    }
846
847    pub(crate) fn current_local_stack(&self) -> LocalStackSnapshot {
848        self.core.local_stack.borrow().clone()
849    }
850
851    pub(crate) fn side_effects_mut(&self) -> RefMut<'_, Vec<Box<dyn FnOnce()>>> {
852        self.core.side_effects.borrow_mut()
853    }
854
855    fn pending_scope_options(&self) -> RefMut<'_, Option<RecomposeOptions>> {
856        self.core.pending_scope_options.borrow_mut()
857    }
858
859    pub(crate) fn borrow_applier(&self) -> RefMut<'_, dyn Applier> {
860        self.core.applier.borrow_dyn()
861    }
862
863    /// Records nodes whose retained subtrees a reused subcompose slot just
864    /// rebound to new content.
865    ///
866    /// The rebinding recomposes inline during measure, so every repass it
867    /// schedules is consumed by the layout pass already running — nothing
868    /// else survives to tell the scoped scene update these subtrees changed,
869    /// and a translate-only update would keep their stale layers (measured:
870    /// a 60pt lazy scroll presented the old row's text at the new row's
871    /// position). The structural-change set is the one channel drained
872    /// after layout, so the rebound children ride it.
873    pub fn record_rebound_slot_children(&self, children: &[NodeId]) {
874        let mut applier = self.borrow_applier();
875        for &child in children {
876            applier.record_structural_change(child);
877        }
878    }
879
880    /// Registers a virtual node in the Applier.
881    ///
882    /// This is used by SubcomposeLayoutNode to register virtual container nodes
883    /// so that subsequent insert_child commands can find them and attach children.
884    /// Without this, virtual nodes would only exist in SubcomposeLayoutNodeInner.virtual_nodes
885    /// and applier.get_mut(virtual_node_id) would fail, breaking child attachment.
886    pub fn register_virtual_node(
887        &self,
888        node_id: NodeId,
889        node: Box<dyn Node>,
890    ) -> Result<(), NodeError> {
891        let mut applier = self.borrow_applier();
892        applier.insert_with_id(node_id, node)
893    }
894
895    /// Checks if a node has no parent (is a root node).
896    /// Used by SubcomposeMeasureScope to filter subcompose results.
897    pub fn node_has_no_parent(&self, node_id: NodeId) -> bool {
898        let mut applier = self.borrow_applier();
899        match applier.get_mut(node_id) {
900            Ok(node) => node.parent().is_none(),
901            Err(_) => true,
902        }
903    }
904
905    /// Gets the children of a node from the Applier.
906    ///
907    /// This is used by SubcomposeLayoutNode to get children of virtual nodes
908    /// directly from the Applier, where insert_child commands have been applied.
909    pub fn get_node_children(&self, node_id: NodeId) -> SmallVec<[NodeId; 8]> {
910        let mut applier = self.borrow_applier();
911        match applier.get_mut(node_id) {
912            Ok(node) => {
913                let mut children = SmallVec::<[NodeId; 8]>::new();
914                node.collect_children_into(&mut children);
915                children
916            }
917            Err(_) => SmallVec::<[NodeId; 8]>::new(),
918        }
919    }
920
921    pub fn nodes_need_measure(&self, node_ids: &[NodeId]) -> bool {
922        let mut applier = self.borrow_applier();
923        node_ids.iter().any(|node_id| {
924            applier
925                .get_mut(*node_id)
926                .is_ok_and(|node| node.needs_measure())
927        })
928    }
929
930    /// Whether any of `node_ids` carries a pending *layout* (placement) repass.
931    ///
932    /// Layout-only dirtiness is not a subset of measure dirtiness: a scroll
933    /// offset change keeps every measured size intact and therefore bubbles
934    /// `needs_layout` alone. Callers that gate cache reuse on
935    /// [`Self::nodes_need_measure`] must also consult this, or a node whose
936    /// *position* changed will replay its stale cached placement forever.
937    pub fn nodes_need_layout(&self, node_ids: &[NodeId]) -> bool {
938        let mut applier = self.borrow_applier();
939        node_ids.iter().any(|node_id| {
940            applier
941                .get_mut(*node_id)
942                .is_ok_and(|node| node.needs_layout())
943        })
944    }
945
946    /// Records a child node in the current parent frame's expected children list.
947    ///
948    /// Used by SubcomposeLayout's `perform_subcompose` to register virtual nodes
949    /// with the outer composer's parent frame. This ensures that the `pop_parent`
950    /// call at the end of `subcompose_slot` generates a correct `SyncChildren`
951    /// command that preserves (rather than removes) the virtual nodes.
952    ///
953    /// Without this, `pop_parent` would generate `SyncChildren { expected: [] }`,
954    /// which removes all virtual nodes and their subtrees from the applier.
955    pub fn record_subcompose_child(&self, child_id: NodeId) {
956        let mut parent_stack = self.parent_stack();
957        if let Some(frame) = parent_stack.last_mut()
958            && matches!(frame.attach_mode, ParentAttachMode::DeferredSync)
959        {
960            if let Some(membership) = frame.new_children_membership.as_mut() {
961                if membership.insert(child_id) {
962                    frame.new_children.push(child_id);
963                }
964            } else if frame.new_children.len() >= LARGE_DEFERRED_CHILD_TRACKING_THRESHOLD {
965                let mut membership = HashSet::default();
966                membership.reserve(frame.new_children.len() + 1);
967                membership.extend(frame.new_children.iter().copied());
968                if membership.insert(child_id) {
969                    frame.new_children.push(child_id);
970                }
971                frame.new_children_membership = Some(membership);
972            } else if !frame.new_children.contains(&child_id) {
973                frame.new_children.push(child_id);
974            }
975        }
976    }
977
978    /// Clears all children of a node in the Applier.
979    ///
980    /// This is used by SubcomposeLayoutNode when reusing a virtual node for
981    /// different content. Without clearing, old children remain attached,
982    /// causing duplicate/interleaved items in lazy lists after scrolling.
983    pub fn clear_node_children(&self, node_id: NodeId) {
984        let mut applier = self.borrow_applier();
985        if let Ok(node) = applier.get_mut(node_id) {
986            node.update_children(&[]);
987        }
988    }
989
990    pub fn install<R>(&self, f: impl FnOnce(&Composer) -> R) -> R {
991        let _composer_guard = composer_context::enter(self);
992        runtime::push_active_runtime(&self.core.runtime);
993        struct Guard;
994        impl Drop for Guard {
995            fn drop(&mut self) {
996                runtime::pop_active_runtime();
997            }
998        }
999        let guard = Guard;
1000        let result = f(self);
1001        drop(guard);
1002        result
1003    }
1004
1005    pub(crate) fn flush_pending_commands_if_large(&self) -> Result<(), NodeError> {
1006        let queued = self.core.commands.borrow().len();
1007        if queued < COMMAND_FLUSH_THRESHOLD {
1008            return Ok(());
1009        }
1010        self.apply_pending_commands()
1011    }
1012
1013    fn with_group_in_active_pass<R>(
1014        &self,
1015        key: crate::slot::GroupKeySeed,
1016        f: impl FnOnce(&Composer) -> R,
1017    ) -> R {
1018        let mut f = Some(f);
1019        let mut result = None;
1020        self.with_group_in_active_pass_dyn(key, &mut |composer| {
1021            let f = f.take().expect("group body must run at most once");
1022            result = Some(f(composer));
1023        });
1024        result.expect("group body must run exactly once")
1025    }
1026
1027    #[inline(never)]
1028    fn with_group_in_active_pass_dyn(
1029        &self,
1030        key: crate::slot::GroupKeySeed,
1031        f: &mut dyn FnMut(&Composer),
1032    ) {
1033        struct GroupGuard {
1034            composer: Composer,
1035            scope: RecomposeScope,
1036        }
1037
1038        impl Drop for GroupGuard {
1039            fn drop(&mut self) {
1040                self.composer
1041                    .close_current_group_body_for_scope(&self.scope);
1042                self.scope.mark_recomposed();
1043                self.composer
1044                    .with_slot_session_mut(|slots| slots.end_group());
1045                if let Err(err) = self.composer.flush_pending_commands_if_large() {
1046                    log::error!("mid-composition command flush failed: {err}");
1047                }
1048            }
1049        }
1050
1051        let parent_scope = self.current_recompose_scope();
1052        let options = self.pending_scope_options().take().unwrap_or_default();
1053        let parent_scope_id = parent_scope.as_ref().map(RecomposeScope::id);
1054        let reserved_key = self.with_slot_session_mut(|slots| slots.reserve_group_key(key));
1055        let host = self.active_slots_host();
1056        let restored = self.core.shared_state.take_retained(
1057            &host,
1058            RetainKey {
1059                parent_scope: parent_scope_id,
1060                key: reserved_key,
1061            },
1062            |subtree| {
1063                self.with_slot_session_mut(|slots| {
1064                    slots.retained_restore_ready(reserved_key, subtree)
1065                })
1066            },
1067        );
1068        let (group, start_scope_id, start_kind) = self.with_slot_session_mut(|slots| {
1069            let GroupStart {
1070                group,
1071                scope_id,
1072                kind,
1073                ..
1074            } = slots.begin_group(reserved_key, restored);
1075            (group, scope_id, kind)
1076        });
1077        let scope_ref =
1078            if let Some(scope) = start_scope_id.and_then(|scope_id| self.scope_for_id(scope_id)) {
1079                scope
1080            } else {
1081                let scope = RecomposeScope::new(self.runtime_handle());
1082                self.register_scope(&scope);
1083                self.with_slot_session_mut(|slots| slots.set_group_scope(group, scope.id()));
1084                scope
1085            };
1086
1087        let lifetime_owner_scope = if parent_scope.is_none() {
1088            self.core.subcomposition_owner_scope.borrow().clone()
1089        } else {
1090            None
1091        };
1092        scope_ref.reactivate();
1093        scope_ref.set_parent_scope(parent_scope);
1094        scope_ref.set_lifetime_owner_scope(lifetime_owner_scope);
1095        scope_ref.set_retention_mode(options.retention);
1096
1097        if options.force_recompose {
1098            scope_ref.force_recompose();
1099        } else if options.force_reuse {
1100            scope_ref.force_reuse();
1101        }
1102        if matches!(start_kind, GroupStartKind::Restored) {
1103            scope_ref.force_recompose();
1104        }
1105
1106        scope_ref.set_slots_host(&host);
1107
1108        {
1109            let mut stack = self.scope_stack();
1110            stack.push(scope_ref.clone());
1111        }
1112
1113        {
1114            let mut stack = self.subcompose_stack();
1115            if let Some(frame) = stack.last_mut() {
1116                frame.scopes.push(scope_ref.clone());
1117            }
1118        }
1119
1120        scope_ref.snapshot_locals(self.current_local_stack());
1121        {
1122            let parent_hint = self.current_parent_hint();
1123            scope_ref.set_parent_hint(parent_hint);
1124        }
1125
1126        let guard = GroupGuard {
1127            composer: self.clone(),
1128            scope: scope_ref.clone(),
1129        };
1130        self.observe_scope(&scope_ref, || f(self));
1131        scope_ref.mark_composed_once();
1132        drop(guard);
1133    }
1134
1135    pub(crate) fn with_group_seed<R>(
1136        &self,
1137        key: crate::slot::GroupKeySeed,
1138        f: impl FnOnce(&Composer) -> R,
1139    ) -> R {
1140        let host = self.active_slots_host();
1141        if host.has_active_pass() {
1142            return self.with_group_in_active_pass(key, f);
1143        }
1144        let (result, _) =
1145            self.with_slot_host_pass(host, crate::slot::SlotPassMode::Compose, |composer| {
1146                composer.with_group_in_active_pass(key, f)
1147            });
1148        result
1149    }
1150
1151    pub fn with_group<R>(&self, key: Key, f: impl FnOnce(&Composer) -> R) -> R {
1152        self.with_group_seed(crate::slot::GroupKeySeed::unkeyed(key), f)
1153    }
1154
1155    pub fn cranpose_with_reuse<R>(
1156        &self,
1157        key: Key,
1158        mut options: RecomposeOptions,
1159        f: impl FnOnce(&Composer) -> R,
1160    ) -> R {
1161        options.retention = RetentionMode::RetainWhenInactive;
1162        self.pending_scope_options().replace(options);
1163        self.with_group(key, f)
1164    }
1165
1166    #[track_caller]
1167    pub fn with_key<K: Hash, R>(&self, key: &K, f: impl FnOnce(&Composer) -> R) -> R {
1168        let seed = explicit_group_key_seed(key, std::panic::Location::caller());
1169        self.with_group_seed(seed, f)
1170    }
1171
1172    #[doc(hidden)]
1173    pub fn __branch_group_deferred(&self, key: Key) -> BranchGroupGuard {
1174        BranchGroupGuard {
1175            composer: self.clone(),
1176            fold_token: self.active_slots_host().try_push_branch_fold(key),
1177        }
1178    }
1179
1180    fn dispose_detached_nodes(&self, nodes: impl IntoIterator<Item = NodeId>) {
1181        for node_id in nodes {
1182            self.commands_mut().push(Command::callback(move |applier| {
1183                crate::slot::dispose_detached_node_now(applier, node_id)
1184            }));
1185        }
1186    }
1187
1188    fn deactivate_scope_ids(&self, scope_ids: impl IntoIterator<Item = ScopeId>) {
1189        for scope_id in scope_ids {
1190            if let Some(scope) = self.scope_for_id(scope_id) {
1191                scope.deactivate();
1192            }
1193        }
1194    }
1195
1196    fn dispose_scope_ids(&self, scope_ids: impl IntoIterator<Item = ScopeId>) {
1197        for scope_id in scope_ids {
1198            if let Some(scope) = self.remove_scope(scope_id) {
1199                scope.deactivate();
1200            }
1201        }
1202    }
1203
1204    fn detached_root_parent_commands(
1205        &self,
1206        subtree: &crate::slot::DetachedSubtree,
1207        context: &'static str,
1208    ) -> Result<Vec<(NodeId, Option<NodeId>)>, NodeError> {
1209        let mut root_nodes = Vec::new();
1210        subtree.collect_root_nodes_checked_into(&mut root_nodes, context);
1211        let mut roots = Vec::with_capacity(root_nodes.len());
1212        for root in root_nodes {
1213            let parent_id = {
1214                let mut applier = self.borrow_applier();
1215                applier.get_mut(root)?.parent()
1216            };
1217            roots.push((root, parent_id));
1218        }
1219        Ok(roots)
1220    }
1221
1222    fn retain_detached_subtree_in_host(
1223        &self,
1224        slots_host: &Rc<SlotsHost>,
1225        parent_scope: Option<ScopeId>,
1226        subtree: crate::slot::DetachedSubtree,
1227    ) -> Result<(), NodeError> {
1228        let Some(root_key) = subtree.root_key_checked() else {
1229            log::error!("retention rejected detached subtree without a root group");
1230            self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1231            return Ok(());
1232        };
1233        let root_detaches = self.detached_root_parent_commands(&subtree, "retention")?;
1234        self.deactivate_scope_ids(subtree.scope_ids_iter());
1235        for (root, parent_id) in root_detaches {
1236            if let Some(parent_id) = parent_id {
1237                self.commands_mut().push(Command::DetachChild {
1238                    parent_id,
1239                    child_id: root,
1240                });
1241            }
1242        }
1243        let evicted = self.core.shared_state.insert_retained(
1244            slots_host,
1245            RetainKey {
1246                parent_scope,
1247                key: root_key,
1248            },
1249            subtree,
1250        );
1251        for subtree in evicted {
1252            self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1253        }
1254        Ok(())
1255    }
1256
1257    fn evict_retained_subtrees_for_host(
1258        &self,
1259        slots_host: &Rc<SlotsHost>,
1260    ) -> Result<(), NodeError> {
1261        let evicted = self.core.shared_state.advance_retention_pass(slots_host);
1262        for subtree in evicted {
1263            self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1264        }
1265        Ok(())
1266    }
1267
1268    fn dispose_detached_subtree_in_host(
1269        &self,
1270        slots_host: &Rc<SlotsHost>,
1271        subtree: crate::slot::DetachedSubtree,
1272    ) -> Result<(), NodeError> {
1273        let root_nodes = self
1274            .detached_root_parent_commands(&subtree, "disposal")?
1275            .into_iter()
1276            .map(|(root, _)| root);
1277        self.dispose_scope_ids(subtree.scope_ids_iter());
1278        self.dispose_detached_nodes(root_nodes);
1279        slots_host.with_table_and_lifecycle_mut(|table, lifecycle| {
1280            table.invalidate_detached_subtree_anchors(&subtree);
1281            lifecycle.queue_subtree_disposal(subtree);
1282        });
1283        Ok(())
1284    }
1285
1286    fn handle_detached_children_in_host(
1287        &self,
1288        slots_host: &Rc<SlotsHost>,
1289        parent_scope: Option<ScopeId>,
1290        detached: Vec<crate::slot::DetachedSubtree>,
1291    ) -> Result<(), NodeError> {
1292        for subtree in detached {
1293            let retention_mode = subtree
1294                .root_scope_id()
1295                .and_then(|scope_id| self.scope_for_id(scope_id))
1296                .map(|scope| scope.retention_mode())
1297                .unwrap_or_default();
1298            match retention_mode {
1299                RetentionMode::DisposeWhenInactive => {
1300                    self.dispose_detached_subtree_in_host(slots_host, subtree)?
1301                }
1302                RetentionMode::RetainWhenInactive => {
1303                    self.retain_detached_subtree_in_host(slots_host, parent_scope, subtree)?
1304                }
1305            }
1306        }
1307        Ok(())
1308    }
1309
1310    fn handle_detached_children(
1311        &self,
1312        parent_scope: Option<ScopeId>,
1313        detached: Vec<crate::slot::DetachedSubtree>,
1314    ) {
1315        let host = self.active_slots_host();
1316        if let Err(err) = self.handle_detached_children_in_host(&host, parent_scope, detached) {
1317            log::error!("detached subtree handling failed while closing a group: {err}");
1318        }
1319    }
1320
1321    fn handle_finished_group_result(
1322        &self,
1323        parent_scope: Option<ScopeId>,
1324        result: FinishGroupResult,
1325    ) {
1326        let FinishGroupResult {
1327            detached_children,
1328            direct_nodes,
1329            root_nodes,
1330            was_skipped,
1331        } = result;
1332        if was_skipped {
1333            self.attach_root_nodes(root_nodes);
1334        }
1335        self.dispose_detached_nodes(direct_nodes);
1336        self.handle_detached_children(parent_scope, detached_children);
1337    }
1338
1339    pub(crate) fn close_current_group_body_for_scope(&self, scope: &RecomposeScope) {
1340        let result = self.with_slot_session_mut(|slots| slots.finish_group_body());
1341        self.handle_finished_group_result(Some(scope.id()), result);
1342        if let Some(popped) = self.scope_stack().pop() {
1343            debug_assert_eq!(
1344                popped.id(),
1345                scope.id(),
1346                "closed scope must match the active scope stack"
1347            );
1348        } else {
1349            log::error!("scope stack underflow while closing scope {}", scope.id());
1350        }
1351    }
1352
1353    #[track_caller]
1354    pub fn remember<T: 'static>(&self, init: impl FnOnce() -> T) -> Owned<T> {
1355        self.remember_at(crate::caller_location_key(), init)
1356    }
1357
1358    #[doc(hidden)]
1359    pub fn remember_at<T: 'static>(
1360        &self,
1361        source: crate::Key,
1362        init: impl FnOnce() -> T,
1363    ) -> Owned<T> {
1364        self.with_slot_session_mut(|slots| {
1365            slots.remember_with_kind(PayloadKind::Remember, source, init)
1366        })
1367    }
1368
1369    #[track_caller]
1370    pub(crate) fn remember_internal<T: 'static>(
1371        &self,
1372        source_salt: crate::Key,
1373        init: impl FnOnce() -> T,
1374    ) -> Owned<T> {
1375        let source = crate::caller_location_key() ^ source_salt;
1376        self.with_slot_session_mut(|slots| {
1377            slots.remember_with_kind(PayloadKind::Internal, source, init)
1378        })
1379    }
1380
1381    #[track_caller]
1382    pub(crate) fn remember_effect<T: Default + 'static>(&self) -> Owned<T> {
1383        let source = crate::caller_location_key();
1384        self.with_slot_session_mut(|slots| slots.remember_effect::<T>(source))
1385    }
1386
1387    #[track_caller]
1388    pub fn use_value_slot<'pass, T: 'static>(
1389        &'pass self,
1390        init: impl FnOnce() -> T,
1391    ) -> ValueSlotHandle<'pass, T> {
1392        let source = crate::caller_location_key();
1393        let slot = self.with_slot_session_mut(|slots| {
1394            slots.value_slot_with_kind(PayloadKind::Internal, source, init)
1395        });
1396        ValueSlotHandle::new(slot)
1397    }
1398
1399    #[doc(hidden)]
1400    #[track_caller]
1401    pub fn __use_param_slot<'pass, T: 'static>(
1402        &'pass self,
1403        init: impl FnOnce() -> T,
1404    ) -> ValueSlotHandle<'pass, T> {
1405        let source = crate::caller_location_key();
1406        let slot = self.with_slot_session_mut(|slots| {
1407            slots.value_slot_with_kind(PayloadKind::Param, source, init)
1408        });
1409        ValueSlotHandle::new(slot)
1410    }
1411
1412    #[doc(hidden)]
1413    #[track_caller]
1414    pub fn __use_return_slot<'pass, T: 'static>(
1415        &'pass self,
1416        init: impl FnOnce() -> T,
1417    ) -> ValueSlotHandle<'pass, T> {
1418        let source = crate::caller_location_key();
1419        let slot = self.with_slot_session_mut(|slots| {
1420            slots.value_slot_with_kind(PayloadKind::Return, source, init)
1421        });
1422        ValueSlotHandle::new(slot)
1423    }
1424
1425    #[doc(hidden)]
1426    pub fn __invalidate_return_consumer_scope(&self) {
1427        let Some(scope) = self.current_recompose_scope() else {
1428            self.request_root_render();
1429            return;
1430        };
1431
1432        if let Some(target) = scope.callback_promotion_target() {
1433            target.invalidate();
1434        } else {
1435            self.request_root_render();
1436        }
1437    }
1438
1439    pub fn with_slot_value<'pass, T: 'static, R>(
1440        &'pass self,
1441        handle: ValueSlotHandle<'pass, T>,
1442        f: impl FnOnce(&T) -> R,
1443    ) -> R {
1444        self.with_slots(|slots| f(slots.read_value(handle.slot())))
1445    }
1446
1447    pub fn with_slot_value_mut<'pass, T: 'static, R>(
1448        &'pass self,
1449        handle: ValueSlotHandle<'pass, T>,
1450        f: impl FnOnce(&mut T) -> R,
1451    ) -> R {
1452        self.with_slots_mut(|slots| f(slots.read_value_mut(handle.slot())))
1453    }
1454
1455    pub fn mutable_state_of<T: Clone + 'static>(&self, initial: T) -> MutableState<T> {
1456        MutableState::with_runtime(initial, self.runtime_handle())
1457    }
1458
1459    pub fn mutable_state_list_of<T, I>(&self, values: I) -> SnapshotStateList<T>
1460    where
1461        T: Clone + 'static,
1462        I: IntoIterator<Item = T>,
1463    {
1464        SnapshotStateList::with_runtime(values, self.runtime_handle())
1465    }
1466
1467    pub fn mutable_state_map_of<K, V, I>(&self, pairs: I) -> SnapshotStateMap<K, V>
1468    where
1469        K: Clone + Eq + Hash + 'static,
1470        V: Clone + 'static,
1471        I: IntoIterator<Item = (K, V)>,
1472    {
1473        SnapshotStateMap::with_runtime(pairs, self.runtime_handle())
1474    }
1475
1476    pub fn read_composition_local<T: Clone + 'static>(&self, local: &CompositionLocal<T>) -> T {
1477        let stack = self.core.local_stack.borrow();
1478        for context in stack.iter().rev() {
1479            if let Some(entry) = context.values.get(&local.key) {
1480                match entry.clone().downcast::<LocalStateEntry<T>>() {
1481                    Ok(typed) => return typed.value(),
1482                    Err(_) => {
1483                        log::error!(
1484                            "composition local entry type mismatch for key {:?}",
1485                            local.key
1486                        );
1487                        return local.default_value();
1488                    }
1489                }
1490            }
1491        }
1492        local.default_value()
1493    }
1494
1495    pub fn read_static_composition_local<T: Clone + 'static>(
1496        &self,
1497        local: &StaticCompositionLocal<T>,
1498    ) -> T {
1499        let stack = self.core.local_stack.borrow();
1500        for context in stack.iter().rev() {
1501            if let Some(entry) = context.values.get(&local.key) {
1502                match entry.clone().downcast::<StaticLocalEntry<T>>() {
1503                    Ok(typed) => return typed.value(),
1504                    Err(_) => {
1505                        log::error!(
1506                            "static composition local entry type mismatch for key {:?}",
1507                            local.key
1508                        );
1509                        return local.default_value();
1510                    }
1511                }
1512            }
1513        }
1514        local.default_value()
1515    }
1516
1517    pub fn current_recompose_scope(&self) -> Option<RecomposeScope> {
1518        self.core.scope_stack.borrow().last().cloned()
1519    }
1520
1521    pub(crate) fn current_state_invalidation_scope(&self) -> Option<RecomposeScope> {
1522        let stack = self.core.scope_stack.borrow();
1523        stack
1524            .iter()
1525            .rev()
1526            .find(|scope| scope.has_recompose_callback())
1527            .cloned()
1528            .or_else(|| stack.last().cloned())
1529    }
1530
1531    pub fn phase(&self) -> crate::Phase {
1532        self.core.phase.get()
1533    }
1534
1535    pub(crate) fn set_phase(&self, phase: crate::Phase) {
1536        self.core.phase.set(phase);
1537    }
1538
1539    pub fn enter_phase(&self, phase: crate::Phase) {
1540        self.set_phase(phase);
1541    }
1542
1543    pub(crate) fn subcompose<R>(
1544        &self,
1545        state: &mut SubcomposeState,
1546        slot_id: SlotId,
1547        content: impl FnOnce(&Composer) -> R,
1548    ) -> (R, Vec<NodeId>) {
1549        match self.phase() {
1550            crate::Phase::Measure | crate::Phase::Layout => {}
1551            current => panic!(
1552                "subcompose() may only be called during measure or layout; current phase: {:?}",
1553                current
1554            ),
1555        }
1556
1557        self.subcompose_stack().push(SubcomposeFrame::default());
1558        let mut guard = SubcomposeStackGuard {
1559            core: self.clone_core(),
1560            leaked: false,
1561        };
1562
1563        let slot_host = state.get_or_create_slots(slot_id);
1564        let (result, _) = self.with_slot_override(slot_host.clone(), |composer| {
1565            composer.with_group(slot_id.raw(), |composer| content(composer))
1566        });
1567
1568        let frame = {
1569            let frame = take_subcompose_frame(&guard.core, "subcompose");
1570            guard.leaked = true;
1571            frame
1572        };
1573        let nodes = frame.nodes;
1574        let scopes = frame.scopes;
1575        state.register_active(slot_id, &nodes, &scopes);
1576        (result, nodes)
1577    }
1578
1579    pub fn subcompose_measurement<R>(
1580        &self,
1581        state: &mut SubcomposeState,
1582        slot_id: SlotId,
1583        content: impl FnOnce(&Composer) -> R,
1584    ) -> (R, Vec<NodeId>) {
1585        let (result, nodes) = self.subcompose(state, slot_id, content);
1586        let roots = nodes
1587            .into_iter()
1588            .filter(|&id| self.node_has_no_parent(id))
1589            .collect();
1590
1591        (result, roots)
1592    }
1593
1594    fn spin_up_subcompose_core(
1595        &self,
1596        slots: &Rc<SlotsHost>,
1597        root: Option<NodeId>,
1598        runtime_handle: &RuntimeHandle,
1599        locals: LocalStackSnapshot,
1600    ) -> Rc<ComposerCore> {
1601        let phase = self.phase();
1602        let shared_state = slots
1603            .runtime_state()
1604            .unwrap_or_else(|| Rc::clone(&self.core.shared_state));
1605        let core = Rc::new(ComposerCore::new(
1606            shared_state,
1607            Rc::clone(slots),
1608            Rc::clone(&self.core.applier),
1609            runtime_handle.clone(),
1610            self.observer(),
1611            root,
1612            InitialParentFrame::RealParent,
1613        ));
1614        core.phase.set(phase);
1615        *core.local_stack.borrow_mut() = locals;
1616        core
1617    }
1618
1619    fn flush_subcompose_pass(
1620        &self,
1621        commands: CommandQueue,
1622        runtime_handle: &RuntimeHandle,
1623        compact_applier: bool,
1624        side_effects: Vec<Box<dyn FnOnce()>>,
1625    ) -> Result<(), NodeError> {
1626        {
1627            let mut applier = self.borrow_applier();
1628            commands.apply(&mut *applier)?;
1629            for update in runtime_handle.take_updates() {
1630                update.apply(&mut *applier)?;
1631            }
1632        }
1633        if compact_applier {
1634            self.core.applier.compact();
1635            self.core.applier.borrow_dyn().clear_recycled_nodes();
1636        }
1637        runtime_handle.drain_ui();
1638        for effect in side_effects {
1639            effect();
1640        }
1641        runtime_handle.drain_ui();
1642        Ok(())
1643    }
1644
1645    pub fn subcompose_in<R>(
1646        &self,
1647        slots: &Rc<SlotsHost>,
1648        root: Option<NodeId>,
1649        f: impl FnOnce(&Composer) -> R,
1650    ) -> Result<R, NodeError> {
1651        let runtime_handle = self.runtime_handle();
1652        let locals = self.current_local_stack();
1653        let core = self.spin_up_subcompose_core(slots, root, &runtime_handle, locals);
1654        let composer = Composer::from_core(core);
1655        let (result, commands, side_effects, compact_applier) = composer.install(|composer| {
1656            let (output, outcome) = composer.try_with_slot_host_pass(
1657                Rc::clone(slots),
1658                crate::slot::SlotPassMode::Compose,
1659                |composer| f(composer),
1660            )?;
1661            let commands = composer.take_commands();
1662            let side_effects = composer.take_side_effects();
1663            Ok((output, commands, side_effects, outcome.compacted))
1664        })?;
1665        self.flush_subcompose_pass(commands, &runtime_handle, compact_applier, side_effects)?;
1666        Ok(result)
1667    }
1668
1669    /// Captures the composition context at the current point so work composed
1670    /// in another slot host inherits both locals and source ownership.
1671    ///
1672    /// A `SubcomposeLayout` captures this while it is being composed and replays
1673    /// it while subcomposing off the measure pass, so content that is
1674    /// subcomposed during layout observes the same composition locals as the
1675    /// `SubcomposeLayout` call site — matching Jetpack Compose, where a
1676    /// subcomposition inherits the composition locals of the layout that
1677    /// created it rather than whatever happens to be in scope during measure
1678    /// (which, after composition unwinds, no longer carries ancestor providers).
1679    pub fn capture_composition_context(&self) -> CapturedCompositionContext {
1680        CapturedCompositionContext {
1681            locals: self.current_local_stack(),
1682            owner_scope: self
1683                .current_recompose_scope()
1684                .map(|scope| scope.downgrade()),
1685        }
1686    }
1687
1688    /// Subcomposes content using an isolated SlotsHost without resetting it.
1689    /// Unlike `subcompose_in`, this preserves existing slot state across calls,
1690    /// allowing efficient reuse during measurement passes. This is critical for
1691    /// lazy lists where items need stable slot positions.
1692    pub fn subcompose_slot<R>(
1693        &self,
1694        slots: &Rc<SlotsHost>,
1695        root: Option<NodeId>,
1696        f: impl FnOnce(&Composer) -> R,
1697    ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1698        let context = self.capture_composition_context();
1699        self.subcompose_slot_with_context(slots, root, &context, f)
1700    }
1701
1702    /// Like [`Composer::subcompose_slot`], but uses a context captured at the
1703    /// source composition site. This is required for measure-time composition,
1704    /// where the source scope is no longer on the active stack.
1705    pub fn subcompose_slot_with_context<R>(
1706        &self,
1707        slots: &Rc<SlotsHost>,
1708        root: Option<NodeId>,
1709        context: &CapturedCompositionContext,
1710        f: impl FnOnce(&Composer) -> R,
1711    ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1712        let runtime_handle = self.runtime_handle();
1713        let locals = context.locals.clone();
1714        let core = self.spin_up_subcompose_core(slots, root, &runtime_handle, locals);
1715        *core.subcomposition_owner_scope.borrow_mut() = context
1716            .owner_scope
1717            .as_ref()
1718            .and_then(Weak::upgrade)
1719            .map(|inner| RecomposeScope { inner });
1720        let composer = Composer::from_core(core);
1721        composer.subcompose_stack().push(SubcomposeFrame::default());
1722        let mut guard = SubcomposeStackGuard {
1723            core: composer.clone_core(),
1724            leaked: false,
1725        };
1726        let root_group_key = crate::location_key(file!(), line!(), column!());
1727        let (result, commands, side_effects, compact_applier) = composer.install(|composer| {
1728            let (output, outcome) = composer.try_with_slot_host_pass(
1729                Rc::clone(slots),
1730                crate::slot::SlotPassMode::Compose,
1731                |composer| {
1732                    let output = composer.with_group(root_group_key, |composer| f(composer));
1733                    if root.is_some() {
1734                        composer.pop_parent();
1735                    }
1736                    output
1737                },
1738            )?;
1739            let commands = composer.take_commands();
1740            let side_effects = composer.take_side_effects();
1741            Ok((output, commands, side_effects, outcome.compacted))
1742        })?;
1743        let frame = {
1744            let frame = take_subcompose_frame(&guard.core, "subcompose_slot");
1745            guard.leaked = true;
1746            frame
1747        };
1748
1749        self.flush_subcompose_pass(commands, &runtime_handle, compact_applier, side_effects)?;
1750        Ok((result, frame.scopes))
1751    }
1752
1753    fn attach_root_nodes(&self, root_nodes: Vec<NodeId>) {
1754        for id in root_nodes {
1755            self.attach_to_parent_with_mode(id, true);
1756        }
1757    }
1758
1759    pub fn skip_current_group(&self) {
1760        self.with_slot_session_mut(|slots| slots.skip_group());
1761    }
1762
1763    pub fn runtime_handle(&self) -> RuntimeHandle {
1764        self.core.runtime.clone()
1765    }
1766
1767    pub fn set_recompose_callback<F>(&self, callback: F)
1768    where
1769        F: FnMut(&Composer) + 'static,
1770    {
1771        self.set_recompose_callback_boxed(Box::new(callback));
1772    }
1773
1774    #[inline(never)]
1775    fn set_recompose_callback_boxed(&self, mut callback: Box<dyn FnMut(&Composer)>) {
1776        if let Some(scope) = self.current_recompose_scope() {
1777            let observer = self.observer();
1778            let scope_weak = scope.downgrade();
1779            scope.set_recompose(Box::new(move |composer: &Composer| {
1780                if let Some(inner) = scope_weak.upgrade() {
1781                    let scope_instance = RecomposeScope { inner };
1782                    observer.observe_reads(
1783                        scope_instance.clone(),
1784                        move |scope_ref| scope_ref.invalidate(),
1785                        || {
1786                            callback(composer);
1787                        },
1788                    );
1789                }
1790            }));
1791        }
1792    }
1793
1794    pub fn set_recompose_fn(&self, callback: fn(&Composer)) {
1795        if let Some(scope) = self.current_recompose_scope() {
1796            scope.set_recompose_fn(callback);
1797        }
1798    }
1799
1800    pub fn with_composition_locals<R>(
1801        &self,
1802        provided: Vec<ProvidedValue>,
1803        site: crate::Key,
1804        f: impl FnOnce(&Composer) -> R,
1805    ) -> R {
1806        if provided.is_empty() {
1807            return f(self);
1808        }
1809        let mut context = LocalContext::default();
1810        for value in provided.into_iter().rev() {
1811            if context.values.contains_key(value.key()) {
1812                continue;
1813            }
1814            let (key, entry) = value.into_entry(self, site);
1815            context.values.insert(key, entry);
1816        }
1817        {
1818            let mut stack = self.local_stack();
1819            Rc::make_mut(&mut *stack).push(context);
1820        }
1821        let result = f(self);
1822        {
1823            let mut stack = self.local_stack();
1824            Rc::make_mut(&mut *stack).pop();
1825        }
1826        result
1827    }
1828}