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