1use std::{
2 any::Any,
3 cell::{Cell, RefCell, RefMut},
4 hash::Hash,
5 marker::PhantomData,
6 rc::{Rc, Weak},
7};
8
9use smallvec::SmallVec;
10
11use crate::{
12 AnchorId, Applier, ApplierGuard, ApplierHost, COMMAND_FLUSH_THRESHOLD, Command, CommandQueue,
13 CompositionLocal, ComputedLocalEntry, DirtyBubble, Key, LocalKey, LocalStackSnapshot,
14 LocalStateEntry, MutableState, Node, NodeError, NodeId, Owned, ProvidedValue, RecomposeOptions,
15 RecomposeScope, RecomposeScopeInner, RecycledNode, RetentionMode, RuntimeHandle, ScopeId,
16 SlotId, SlotPassOutcome, SlotTable, SlotsHost, SnapshotStateList, SnapshotStateMap,
17 StaticCompositionLocal, SubcomposeState, composer_context,
18 retention::RetainKey,
19 runtime,
20 slot::{FinishGroupResult, GroupStart, GroupStartKind, PayloadKind, RootNodeIds, ValueSlotId},
21};
22
23mod composable_group;
24mod parent_frame;
25mod runtime_state;
26mod scope_frame;
27mod subcompose_slot;
28pub use composable_group::{ComposableGroup, ParameterChange};
29use parent_frame::{InitialParentFrame, push_root_frame};
30pub(crate) use parent_frame::{ParentAttachMode, ParentFrame};
31pub(crate) use runtime_state::ComposerRuntimeState;
32pub(crate) use scope_frame::ScopeFrame;
33use subcompose_slot::{measure_slot_state, subcompose_slot_at};
34
35pub struct ValueSlotHandle<'pass, T: 'static> {
38 slot: ValueSlotId,
39 record: Option<usize>,
40 _pass: PhantomData<&'pass Composer>,
41 _value: PhantomData<fn() -> T>,
42}
43
44impl<T: 'static> Copy for ValueSlotHandle<'_, T> {}
45
46impl<T: 'static> Clone for ValueSlotHandle<'_, T> {
47 fn clone(&self) -> Self {
48 *self
49 }
50}
51
52impl<T: 'static> ValueSlotHandle<'_, T> {
53 pub(crate) fn new(slot: ValueSlotId, record: Option<usize>) -> Self {
54 Self {
55 slot,
56 record,
57 _pass: PhantomData,
58 _value: PhantomData,
59 }
60 }
61}
62
63fn slots_storage_key(host: &Rc<SlotsHost>) -> usize {
64 host.storage_key()
65}
66
67fn bind_slots_host_to_runtime_state(
68 state: &Rc<ComposerRuntimeState>,
69 host: &Rc<SlotsHost>,
70) -> Rc<SlotsHost> {
71 if host.runtime_state_ptr() == Some(Rc::as_ptr(state)) {
74 debug_assert!(
75 state
76 .host_for_storage_key(host.storage_key())
77 .is_some_and(|registered| Rc::ptr_eq(®istered, host)),
78 "a slot host bound to a runtime state must be in its registry"
79 );
80 return Rc::clone(host);
81 }
82 if host.runtime_state().is_some() {
83 if host.rebind_orphaned_runtime_state(state) {
84 state.bind_slots_host(host);
85 return Rc::clone(host);
86 }
87 log::error!(
88 "slot host already belongs to a different composer runtime state; using a fresh slot host"
89 );
90 let replacement = Rc::new(SlotsHost::new(SlotTable::new()));
91 state.bind_slots_host(&replacement);
92 return replacement;
93 }
94 state.bind_slots_host(host);
95 Rc::clone(host)
96}
97
98struct GroupEntry {
99 key: crate::slot::GroupKey,
100 restored: Option<Box<crate::slot::DetachedSubtree>>,
102 placeholder_for: Option<crate::slot::GroupKey>,
103}
104
105struct GroupScopeEntry<'a> {
106 options: RecomposeOptions,
107 start_kind: GroupStartKind,
108 host: &'a SlotsHost,
109 group: crate::slot::ActiveGroupId,
110 parent_hint: Option<NodeId>,
111}
112
113struct SlotHostPassGuard {
114 core: Rc<ComposerCore>,
115 host: Rc<SlotsHost>,
116 fold_base: usize,
118 active: bool,
119}
120
121impl SlotHostPassGuard {
122 fn close(&mut self) {
123 if !self.active {
124 return;
125 }
126 if self.host.has_active_pass() {
127 self.host.abandon_active_pass();
128 }
129 match self.core.slot_hosts.borrow_mut().pop() {
130 Some(host) if Rc::ptr_eq(&host, &self.host) => {}
131 Some(_) => {
132 log::error!("slot host stack mismatch while closing slot host pass");
133 }
134 None => {
135 log::error!("slot host stack underflow while closing slot host pass");
136 }
137 }
138 self.core.branch_folds.end_pass(self.fold_base);
139 self.active = false;
140 }
141}
142
143impl Drop for SlotHostPassGuard {
144 fn drop(&mut self) {
145 self.close();
146 }
147}
148
149pub(crate) struct PendingMovable {
150 pub(crate) key: crate::slot::GroupKey,
151 pub(crate) placeholder: AnchorId,
152 pub(crate) parent_scope: Option<Weak<RecomposeScopeInner>>,
153}
154
155fn reparent_restored_scopes(
156 host: &SlotsHost,
157 group: crate::slot::ActiveGroupId,
158 old_hint: Option<NodeId>,
159 parent_hint: Option<NodeId>,
160) {
161 host.with_write_session(|slots| {
162 slots.for_each_subtree_scope(group, |scope| {
163 if scope.parent_hint() == old_hint {
164 scope.set_parent_hint(parent_hint);
165 }
166 scope.reactivate();
167 });
168 });
169}
170
171fn movable_retain_key(id: Key) -> RetainKey {
172 RetainKey::for_group(
173 None,
174 crate::slot::GroupKey::new(crate::slot::MOVABLE_STATIC_KEY, Some(id), 0),
175 )
176}
177
178const SPARE_COMMAND_QUEUES: usize = 8;
180
181const SPARE_COMMAND_CAPACITY: usize = 1024;
184
185fn spare_commands() -> CommandQueue {
186 crate::thread_state::try_runtimes(|state| state.spare_commands.borrow_mut().pop())
187 .flatten()
188 .unwrap_or_default()
189}
190
191#[derive(Default)]
194pub(crate) struct ComposerStacks {
195 slot_hosts: Vec<Rc<SlotsHost>>,
196 parent_stack: Vec<ParentFrame>,
197 scope_stack: Vec<ScopeFrame>,
198}
199
200const SPARE_STACK_CAPACITY: usize = 256;
203
204fn spare_composer_stacks() -> ComposerStacks {
205 crate::thread_state::try_runtimes(|state| state.spare_composer_stacks.take())
206 .flatten()
207 .unwrap_or_default()
208}
209
210impl ComposerStacks {
211 fn holds_storage(&self) -> bool {
212 self.slot_hosts.capacity() > 0
213 || self.parent_stack.capacity() > 0
214 || self.scope_stack.capacity() > 0
215 }
216}
217
218fn recycle_composer_stacks(mut stacks: ComposerStacks) {
220 let ComposerStacks {
221 slot_hosts,
222 parent_stack,
223 scope_stack,
224 } = &mut stacks;
225 if slot_hosts.capacity() > SPARE_STACK_CAPACITY
226 || parent_stack.capacity() > SPARE_STACK_CAPACITY
227 || scope_stack.capacity() > SPARE_STACK_CAPACITY
228 {
229 return;
230 }
231 slot_hosts.clear();
232 parent_stack.clear();
233 scope_stack.clear();
234 crate::thread_state::try_runtimes(|state| state.spare_composer_stacks.set(Some(stacks)));
235}
236
237pub(crate) fn recycle_commands(commands: CommandQueue) {
239 if commands.capacity() > SPARE_COMMAND_CAPACITY {
240 return;
241 }
242 crate::thread_state::try_runtimes(|state| {
243 let mut spare = state.spare_commands.borrow_mut();
244 if spare.len() < SPARE_COMMAND_QUEUES {
245 spare.push(commands);
246 }
247 });
248}
249
250#[derive(Default)]
251pub(crate) struct SubcomposeFrame {
252 pub(crate) nodes: Vec<NodeId>,
253 pub(crate) scopes: Vec<RecomposeScope>,
254}
255
256pub(crate) struct LocalFrame {
259 values: SmallVec<[(LocalKey, Rc<dyn Any>); 2]>,
260 parent: LocalStackSnapshot,
261}
262
263pub(crate) fn provided_entry(stack: &LocalStackSnapshot, key: &LocalKey) -> Option<Rc<dyn Any>> {
265 let mut frame = stack.as_deref();
266 while let Some(current) = frame {
267 if let Some((_, entry)) = current.values.iter().find(|(provided, _)| provided == key) {
268 return Some(Rc::clone(entry));
269 }
270 frame = current.parent.as_deref();
271 }
272 None
273}
274
275pub(crate) struct ComposerCore {
276 pub(crate) shared_state: Rc<ComposerRuntimeState>,
277 pub(crate) branch_folds: Rc<crate::slot::BranchFolds>,
280 pub(crate) slots: Rc<SlotsHost>,
281 slot_hosts: RefCell<Vec<Rc<SlotsHost>>>,
282 pub(crate) applier: Rc<dyn ApplierHost>,
283 pub(crate) runtime: RuntimeHandle,
284 pub(crate) parent_stack: RefCell<Vec<ParentFrame>>,
285 pub(crate) subcompose_stack: RefCell<Vec<SubcomposeFrame>>,
286 pub(crate) root: Cell<Option<NodeId>>,
287 pub(crate) commands: RefCell<CommandQueue>,
288 pub(crate) scope_stack: RefCell<Vec<ScopeFrame>>,
289 subcomposition_owner_scope: RefCell<Option<RecomposeScope>>,
290 pub(crate) local_stack: RefCell<LocalStackSnapshot>,
291 pub(crate) side_effects: RefCell<Vec<Box<dyn FnOnce()>>>,
292 pub(crate) pending_scope_options: Cell<Option<RecomposeOptions>>,
293 pub(crate) phase: Cell<crate::Phase>,
294 pub(crate) recompose_parent_hint: Cell<Option<NodeId>>,
295 pub(crate) recompose_child_cursor: Cell<crate::recompose::RecomposeChildCursor>,
296 pub(crate) restarted_scope: RefCell<Option<RecomposeScope>>,
300 pub(crate) root_render_requested: Cell<bool>,
301 locals_changed: Cell<bool>,
304 reused_depth: Cell<u32>,
307 pub(crate) _not_send: PhantomData<*const ()>,
308}
309
310#[derive(Clone, Default)]
314pub struct CapturedCompositionContext {
315 locals: LocalStackSnapshot,
316 owner_scope: Option<Weak<RecomposeScopeInner>>,
317 locals_changed: bool,
318}
319
320impl CapturedCompositionContext {
321 pub fn locals_changed(&self) -> bool {
326 self.locals_changed
327 }
328
329 pub fn owner_chain_deactivation_epoch(&self) -> u64 {
333 self.owner_scope
334 .as_ref()
335 .and_then(Weak::upgrade)
336 .map_or(0, |inner| {
337 RecomposeScope { inner }.owner_chain_deactivation_epoch()
338 })
339 }
340}
341
342fn take_subcompose_frame(core: &ComposerCore, operation: &str) -> SubcomposeFrame {
343 match core.subcompose_stack.borrow_mut().pop() {
344 Some(frame) => frame,
345 None => {
346 log::error!("subcompose stack underflow while finishing {operation}");
347 SubcomposeFrame::default()
348 }
349 }
350}
351
352struct SubcomposeStackGuard {
353 core: Rc<ComposerCore>,
354 leaked: bool,
355}
356
357impl Drop for SubcomposeStackGuard {
358 fn drop(&mut self) {
359 if !self.leaked {
360 self.core.subcompose_stack.borrow_mut().pop();
361 }
362 }
363}
364
365impl Drop for ComposerCore {
366 fn drop(&mut self) {
369 let commands = std::mem::take(self.commands.get_mut());
370 if commands.len() == 0 && commands.capacity() > 0 {
371 recycle_commands(commands);
372 }
373 let stacks = self.take_stacks();
374 if stacks.holds_storage() {
375 recycle_composer_stacks(stacks);
376 }
377 }
378}
379
380impl ComposerCore {
381 fn new(parts: ComposerParts) -> Self {
382 let ComposerParts {
383 shared_state,
384 slots,
385 applier,
386 runtime,
387 root,
388 initial_parent_frame,
389 } = parts;
390 let ComposerStacks {
391 slot_hosts,
392 mut parent_stack,
393 scope_stack,
394 } = spare_composer_stacks();
395 push_root_frame(&mut parent_stack, root, initial_parent_frame);
396 Self {
397 branch_folds: Rc::clone(&shared_state.branch_folds),
398 shared_state,
399 slots,
400 slot_hosts: RefCell::new(slot_hosts),
401 applier,
402 runtime,
403 parent_stack: RefCell::new(parent_stack),
404 subcompose_stack: RefCell::new(Vec::new()),
405 root: Cell::new(root),
406 commands: RefCell::new(spare_commands()),
407 scope_stack: RefCell::new(scope_stack),
408 subcomposition_owner_scope: RefCell::new(None),
409 local_stack: RefCell::new(None),
410 side_effects: RefCell::new(Vec::new()),
411 pending_scope_options: Cell::new(None),
412 phase: Cell::new(crate::Phase::Compose),
413 recompose_parent_hint: Cell::new(None),
414 recompose_child_cursor: Cell::new(crate::recompose::RecomposeChildCursor::Unknown),
415 restarted_scope: RefCell::new(None),
416 root_render_requested: Cell::new(false),
417 locals_changed: Cell::new(false),
418 reused_depth: Cell::new(0),
419 _not_send: PhantomData,
420 }
421 }
422
423 fn take_stacks(&mut self) -> ComposerStacks {
425 let mut stacks = ComposerStacks {
426 slot_hosts: std::mem::take(self.slot_hosts.get_mut()),
427 parent_stack: std::mem::take(self.parent_stack.get_mut()),
428 scope_stack: std::mem::take(self.scope_stack.get_mut()),
429 };
430 stacks.slot_hosts.clear();
431 stacks.parent_stack.clear();
432 stacks.scope_stack.clear();
433 stacks
434 }
435
436 fn restart(&mut self, parts: ComposerParts) {
440 let Self {
441 shared_state,
442 branch_folds,
443 slots,
444 slot_hosts,
445 applier,
446 runtime,
447 parent_stack,
448 subcompose_stack,
449 root,
450 commands,
451 scope_stack,
452 subcomposition_owner_scope,
453 local_stack,
454 side_effects,
455 pending_scope_options,
456 phase,
457 recompose_parent_hint,
458 recompose_child_cursor,
459 restarted_scope,
460 root_render_requested,
461 locals_changed,
462 reused_depth,
463 _not_send: _,
464 } = self;
465 if !Rc::ptr_eq(shared_state, &parts.shared_state) {
466 *branch_folds = Rc::clone(&parts.shared_state.branch_folds);
467 *shared_state = parts.shared_state;
468 }
469 *slots = parts.slots;
470 *applier = parts.applier;
471 *runtime = parts.runtime;
472 slot_hosts.get_mut().clear();
473 let parent_stack = parent_stack.get_mut();
474 parent_stack.clear();
475 push_root_frame(parent_stack, parts.root, parts.initial_parent_frame);
476 subcompose_stack.get_mut().clear();
477 root.set(parts.root);
478 let commands = commands.get_mut();
479 if commands.len() > 0 || commands.capacity() == 0 {
480 *commands = spare_commands();
481 }
482 scope_stack.get_mut().clear();
483 *subcomposition_owner_scope.get_mut() = None;
484 *local_stack.get_mut() = None;
485 side_effects.get_mut().clear();
486 pending_scope_options.set(None);
487 phase.set(crate::Phase::Compose);
488 recompose_parent_hint.set(None);
489 recompose_child_cursor.set(crate::recompose::RecomposeChildCursor::Unknown);
490 *restarted_scope.get_mut() = None;
491 root_render_requested.set(false);
492 locals_changed.set(false);
493 reused_depth.set(0);
494 }
495
496 fn park(&mut self) {
499 self.slot_hosts.get_mut().clear();
500 self.parent_stack.get_mut().clear();
501 self.scope_stack.get_mut().clear();
502 self.subcompose_stack.get_mut().clear();
503 *self.subcomposition_owner_scope.get_mut() = None;
504 *self.local_stack.get_mut() = None;
505 self.side_effects.get_mut().clear();
506 }
507}
508
509#[derive(Clone, Copy)]
513struct SubcomposeSite<'a> {
514 applier: &'a Rc<dyn ApplierHost>,
515 runtime: &'a RuntimeHandle,
516 phase: crate::Phase,
517 locals_changed: bool,
518}
519
520impl SubcomposeSite<'_> {
521 fn spin_up_core(
524 self,
525 shared_state: Rc<ComposerRuntimeState>,
526 slots: &Rc<SlotsHost>,
527 root: Option<NodeId>,
528 locals: LocalStackSnapshot,
529 ) -> Rc<ComposerCore> {
530 let core = Rc::new(ComposerCore::new(ComposerParts {
531 shared_state,
532 slots: Rc::clone(slots),
533 applier: Rc::clone(self.applier),
534 runtime: self.runtime.clone(),
535 root,
536 initial_parent_frame: InitialParentFrame::RealParent,
537 }));
538 core.phase.set(self.phase);
539 core.locals_changed.set(self.locals_changed);
540 *core.local_stack.borrow_mut() = locals;
541 core
542 }
543
544 fn flush(
549 self,
550 mut commands: CommandQueue,
551 compact_applier: bool,
552 side_effects: Vec<Box<dyn FnOnce()>>,
553 ) -> Result<(), NodeError> {
554 {
555 let mut applier = self.applier.borrow_dyn();
556 commands.apply(&mut *applier)?;
557 for update in self.runtime.take_updates() {
558 update.apply(&mut *applier)?;
559 }
560 }
561 recycle_commands(commands);
562 if compact_applier {
563 self.applier.compact();
564 self.applier.borrow_dyn().clear_recycled_nodes();
565 }
566 composer_context::without_composer(|| {
567 for effect in side_effects {
568 effect();
569 }
570 });
571 Ok(())
572 }
573}
574
575struct ComposerParts {
578 shared_state: Rc<ComposerRuntimeState>,
579 slots: Rc<SlotsHost>,
580 applier: Rc<dyn ApplierHost>,
581 runtime: RuntimeHandle,
582 root: Option<NodeId>,
583 initial_parent_frame: InitialParentFrame,
584}
585
586#[derive(Clone)]
590pub struct Composer {
591 pub(crate) core: Rc<ComposerCore>,
592}
593
594#[doc(hidden)]
597pub struct BranchGroupGuard<'a> {
598 folds: &'a crate::slot::BranchFolds,
599 token: crate::slot::FoldToken,
600}
601
602impl BranchGroupGuard<'_> {
603 #[doc(hidden)]
606 #[inline]
607 pub fn advance(&mut self, key: Key) {
608 self.folds.advance(&mut self.token, key);
609 }
610}
611
612impl Drop for BranchGroupGuard<'_> {
613 #[inline]
614 fn drop(&mut self) {
615 self.folds.close(self.token);
616 }
617}
618
619#[doc(hidden)]
626pub struct ScopedBranchGroupGuard {
627 open: std::mem::ManuallyDrop<Option<ScopedBranchGroup>>,
630}
631
632struct ScopedBranchGroup {
634 folds: Rc<crate::slot::BranchFolds>,
635 token: crate::slot::FoldToken,
636}
637
638#[doc(hidden)]
641#[inline]
642pub fn __branch_group_scope_deferred(key: Key) -> ScopedBranchGroupGuard {
643 let open = composer_context::with_current_core(|core| ScopedBranchGroup {
644 token: core.branch_folds.push(key),
645 folds: Rc::clone(&core.branch_folds),
646 });
647 ScopedBranchGroupGuard {
648 open: std::mem::ManuallyDrop::new(open),
649 }
650}
651
652#[doc(hidden)]
657#[inline]
658pub fn __branch_group_scope_advance(guard: &mut ScopedBranchGroupGuard, key: Key) {
659 if let Some(group) = guard.open.as_mut() {
660 group.folds.advance(&mut group.token, key);
661 }
662}
663
664impl Drop for ScopedBranchGroupGuard {
665 #[inline(always)]
666 fn drop(&mut self) {
667 if let Some(group) = self.open.take() {
668 close_scoped_branch_group(group);
669 }
670 }
671}
672
673#[inline(never)]
674fn close_scoped_branch_group(group: ScopedBranchGroup) {
675 group.folds.close(group.token);
676}
677
678pub(crate) enum EmittedNode {
679 Fresh(Box<dyn Node>),
680 Recycled(RecycledNode),
681}
682
683impl Composer {
684 pub(crate) fn new_with_shared_state(
685 shared_state: Rc<ComposerRuntimeState>,
686 slots: Rc<SlotsHost>,
687 applier: Rc<dyn ApplierHost>,
688 runtime: RuntimeHandle,
689 root: Option<NodeId>,
690 ) -> Self {
691 Self::new_with_shared_state_with_parent_frame(
692 shared_state,
693 slots,
694 applier,
695 runtime,
696 root,
697 InitialParentFrame::SyntheticRoot,
698 )
699 }
700
701 fn new_with_shared_state_with_parent_frame(
702 shared_state: Rc<ComposerRuntimeState>,
703 slots: Rc<SlotsHost>,
704 applier: Rc<dyn ApplierHost>,
705 runtime: RuntimeHandle,
706 root: Option<NodeId>,
707 initial_parent_frame: InitialParentFrame,
708 ) -> Self {
709 shared_state.bind_applier_host(&applier);
710 let slots = bind_slots_host_to_runtime_state(&shared_state, &slots);
711 let core = Rc::new(ComposerCore::new(ComposerParts {
712 shared_state,
713 slots,
714 applier,
715 runtime,
716 root,
717 initial_parent_frame,
718 }));
719 Self { core }
720 }
721
722 pub(crate) fn for_pass(
726 parked: Option<Self>,
727 shared_state: Rc<ComposerRuntimeState>,
728 slots: Rc<SlotsHost>,
729 applier: Rc<dyn ApplierHost>,
730 runtime: RuntimeHandle,
731 root: Option<NodeId>,
732 ) -> Self {
733 let Some(mut composer) = parked.filter(|parked| Rc::strong_count(&parked.core) == 1) else {
734 return Self::new_with_shared_state(shared_state, slots, applier, runtime, root);
735 };
736 let Some(core) = Rc::get_mut(&mut composer.core) else {
737 return Self::new_with_shared_state(shared_state, slots, applier, runtime, root);
738 };
739 shared_state.bind_applier_host(&applier);
740 let slots = bind_slots_host_to_runtime_state(&shared_state, &slots);
741 core.restart(ComposerParts {
742 shared_state,
743 slots,
744 applier,
745 runtime,
746 root,
747 initial_parent_frame: InitialParentFrame::SyntheticRoot,
748 });
749 composer
750 }
751
752 pub(crate) fn park(mut self) -> Option<Self> {
756 Rc::get_mut(&mut self.core)?.park();
757 Some(self)
758 }
759
760 pub fn new(
763 slots: Rc<SlotsHost>,
764 applier: Rc<dyn ApplierHost>,
765 runtime: RuntimeHandle,
766 root: Option<NodeId>,
767 ) -> Self {
768 Self::new_with_shared_state_with_parent_frame(
769 slots
770 .runtime_state()
771 .unwrap_or_else(|| Rc::new(ComposerRuntimeState::default())),
772 slots,
773 applier,
774 runtime,
775 root,
776 InitialParentFrame::RealParent,
777 )
778 }
779
780 pub(crate) fn from_core(core: Rc<ComposerCore>) -> Self {
781 Self { core }
782 }
783
784 pub(crate) fn clone_core(&self) -> Rc<ComposerCore> {
785 Rc::clone(&self.core)
786 }
787
788 pub(crate) fn request_root_render(&self) {
789 self.core.root_render_requested.set(true);
790 }
791
792 pub(crate) fn take_root_render_request(&self) -> bool {
793 self.core.root_render_requested.replace(false)
794 }
795
796 pub fn active_slots_host(&self) -> Rc<SlotsHost> {
799 self.core
800 .slot_hosts
801 .borrow()
802 .last()
803 .cloned()
804 .unwrap_or_else(|| Rc::clone(&self.core.slots))
805 }
806
807 fn with_active_slots_host<R>(&self, f: impl FnOnce(&SlotsHost) -> R) -> R {
808 let hosts = self.core.slot_hosts.borrow();
809 f(hosts.last().unwrap_or(&self.core.slots))
810 }
811
812 pub(crate) fn with_slots<R>(&self, f: impl FnOnce(&SlotTable) -> R) -> R {
813 self.with_active_slots_host(|host| f(&host.borrow()))
814 }
815
816 pub(crate) fn with_slots_mut<R>(&self, f: impl FnOnce(&mut SlotTable) -> R) -> R {
817 self.with_active_slots_host(|host| f(&mut host.borrow_mut()))
818 }
819
820 pub(crate) fn with_slot_session_mut<R>(
821 &self,
822 f: impl FnOnce(&mut crate::slot::SlotWriteSession<'_>) -> R,
823 ) -> R {
824 self.with_active_slots_host(|host| host.with_write_session(f))
825 }
826
827 pub(crate) fn try_with_slot_host_pass<R>(
828 &self,
829 slots: Rc<SlotsHost>,
830 mode: crate::slot::SlotPassMode,
831 f: impl FnOnce(&Self) -> R,
832 ) -> Result<(R, SlotPassOutcome), NodeError> {
833 let mut guard = self.begin_slot_host_pass(&slots, mode);
834 let result = f(self);
835 let outcome = self.finish_slot_host_pass(&guard.host)?;
836 guard.close();
837 Ok((result, outcome))
838 }
839
840 pub(crate) fn with_slot_host_pass<R>(
841 &self,
842 slots: Rc<SlotsHost>,
843 mode: crate::slot::SlotPassMode,
844 f: impl FnOnce(&Self) -> R,
845 ) -> (R, SlotPassOutcome) {
846 let mut guard = self.begin_slot_host_pass(&slots, mode);
847 let result = f(self);
848 let outcome = match self.finish_slot_host_pass(&guard.host) {
849 Ok(outcome) => outcome,
850 Err(err) => {
851 log::error!("slot host pass finalization failed: {err}");
852 SlotPassOutcome::default()
853 }
854 };
855 guard.close();
856 (result, outcome)
857 }
858
859 pub(crate) fn with_slot_override<R>(
860 &self,
861 slots: Rc<SlotsHost>,
862 f: impl FnOnce(&Self) -> R,
863 ) -> (R, SlotPassOutcome) {
864 self.with_slot_host_pass(slots, crate::slot::SlotPassMode::Compose, f)
865 }
866
867 fn begin_slot_host_pass(
868 &self,
869 slots: &Rc<SlotsHost>,
870 mode: crate::slot::SlotPassMode,
871 ) -> SlotHostPassGuard {
872 let slots = bind_slots_host_to_runtime_state(&self.core.shared_state, slots);
873 let fold_base = self.core.branch_folds.len();
874 slots.begin_pass(mode, &self.core.branch_folds);
875 {
876 let mut stack = self.core.slot_hosts.borrow_mut();
877 if let Some(parent) = stack.last()
878 && !Rc::ptr_eq(parent, &slots)
879 {
880 parent.note_nested_host(&slots);
881 }
882 stack.push(Rc::clone(&slots));
883 }
884 SlotHostPassGuard {
885 core: self.clone_core(),
886 host: slots,
887 fold_base,
888 active: true,
889 }
890 }
891
892 fn finish_slot_host_pass(&self, slots: &Rc<SlotsHost>) -> Result<SlotPassOutcome, NodeError> {
893 let finished = {
894 let mut applier = self.core.applier.borrow_dyn();
895 slots.finish_pass(&mut *applier)
896 }?;
897 self.handle_detached_children_in_host(slots, None, finished.detached_root_children)?;
898 self.wake_sites_whose_movable_arrived();
899 self.evict_retained_subtrees_for_host(slots)?;
900 slots.complete_pass_cleanup(&finished.outcome);
901 Ok(finished.outcome)
902 }
903
904 fn wake_sites_whose_movable_arrived(&self) {
905 for host in self.core.shared_state.hosts_awaiting_movables() {
906 self.wake_sites_in_host(&host);
907 }
908 }
909
910 fn wake_sites_in_host(&self, slots: &Rc<SlotsHost>) {
911 let pending = self.core.shared_state.take_pending_movables(slots);
912 if pending.is_empty() {
913 return;
914 }
915 let mut waiting = Vec::new();
916 for site in pending {
917 if !slots.borrow().group_is_active(site.placeholder) {
918 continue;
919 }
920 let retain_key = RetainKey::for_group(None, site.key);
921 if !self.core.shared_state.movable_retained_anywhere(retain_key) {
922 waiting.push(site);
923 continue;
924 }
925 match site.parent_scope.as_ref().and_then(RecomposeScope::upgrade) {
926 Some(scope) => {
927 scope.force_recompose();
928 scope.invalidate();
929 }
930 None => log::error!(
931 "movable content {:?} arrived for a site whose scope is gone",
932 site.key
933 ),
934 }
935 }
936 self.core.shared_state.keep_pending_movables(slots, waiting);
937 }
938
939 pub(crate) fn forget_movables(&self, ids: &[Key]) -> Result<(), NodeError> {
940 for id in ids {
941 let Some((host, subtree)) = self.core.shared_state.take_retained_movable(*id) else {
942 continue;
943 };
944 self.dispose_detached_subtree_in_host(&host, subtree)?;
945 host.flush_pending_drops();
946 }
947 Ok(())
948 }
949
950 pub(crate) fn parent_stack(&self) -> RefMut<'_, Vec<ParentFrame>> {
951 self.core.parent_stack.borrow_mut()
952 }
953
954 pub(crate) fn current_parent_hint(&self) -> Option<NodeId> {
955 let stack = self.core.parent_stack.borrow();
956 let stack_hint = stack
957 .last()
958 .and_then(|frame| (!frame.synthetic_root).then_some(frame.id));
959 stack_hint.or_else(|| self.core.recompose_parent_hint.get())
960 }
961
962 pub(crate) fn subcompose_stack(&self) -> RefMut<'_, Vec<SubcomposeFrame>> {
963 self.core.subcompose_stack.borrow_mut()
964 }
965
966 pub(crate) fn commands_mut(&self) -> RefMut<'_, CommandQueue> {
967 self.core.commands.borrow_mut()
968 }
969
970 pub(crate) fn enqueue_semantics_invalidation(&self, id: NodeId) {
971 self.commands_mut().push(Command::BubbleDirty {
972 node_id: id,
973 bubble: DirtyBubble::SEMANTICS,
974 });
975 }
976
977 pub(crate) fn scope_stack(&self) -> RefMut<'_, Vec<ScopeFrame>> {
978 self.core.scope_stack.borrow_mut()
979 }
980
981 pub(crate) fn local_stack(&self) -> RefMut<'_, LocalStackSnapshot> {
982 self.core.local_stack.borrow_mut()
983 }
984
985 pub(crate) fn current_local_stack(&self) -> LocalStackSnapshot {
986 self.core.local_stack.borrow().clone()
987 }
988
989 pub(crate) fn side_effects_mut(&self) -> RefMut<'_, Vec<Box<dyn FnOnce()>>> {
990 self.core.side_effects.borrow_mut()
991 }
992
993 pub(crate) fn borrow_applier(&self) -> ApplierGuard<'_, dyn Applier> {
994 self.core.applier.borrow_dyn()
995 }
996
997 pub fn record_rebound_slot_children(&self, children: &[NodeId]) {
1008 let mut applier = self.borrow_applier();
1009 for &child in children {
1010 applier.record_structural_change(child);
1011 }
1012 }
1013
1014 pub fn create_virtual_node(&self, node: Box<dyn Node>) -> NodeId {
1017 debug_assert!(node.is_virtual(), "a virtual node reports `is_virtual`");
1018 let mut applier = self.borrow_applier();
1019 let node_id = applier.create(node);
1020 if let Ok(node) = applier.get_mut(node_id) {
1021 node.set_node_id(node_id);
1022 }
1023 node_id
1024 }
1025
1026 pub fn dispose_subcomposed_nodes(
1038 &self,
1039 disposal: crate::subcompose::SubcomposeDisposal,
1040 ) -> Result<(), NodeError> {
1041 if disposal.nodes.is_empty() && disposal.slot_hosts.is_empty() {
1042 return Ok(());
1043 }
1044 self.apply_pending_commands()?;
1045 Self::dispose_measure_subcomposed_nodes(&self.core.applier, disposal)
1046 }
1047
1048 pub fn dispose_measure_subcomposed_nodes(
1052 applier: &Rc<dyn ApplierHost>,
1053 disposal: crate::subcompose::SubcomposeDisposal,
1054 ) -> Result<(), NodeError> {
1055 if disposal.nodes.is_empty() && disposal.slot_hosts.is_empty() {
1056 return Ok(());
1057 }
1058 let disposal = crate::NodeDisposal::from_subcomposed(disposal, &*applier.borrow_dyn());
1059 applier.dispose_nodes(disposal)
1060 }
1061
1062 pub fn node_has_no_parent(&self, node_id: NodeId) -> bool {
1065 let mut applier = self.borrow_applier();
1066 match applier.get_mut(node_id) {
1067 Ok(node) => node.parent().is_none(),
1068 Err(_) => true,
1069 }
1070 }
1071
1072 pub fn node_parent(&self, node_id: NodeId) -> Result<Option<NodeId>, NodeError> {
1076 self.borrow_applier()
1077 .get_mut(node_id)
1078 .map(|node| node.parent())
1079 }
1080
1081 pub fn get_node_children(&self, node_id: NodeId) -> SmallVec<[NodeId; 8]> {
1086 let mut applier = self.borrow_applier();
1087 match applier.get_mut(node_id) {
1088 Ok(node) => {
1089 let mut children = SmallVec::<[NodeId; 8]>::new();
1090 node.collect_children_into(&mut children);
1091 children
1092 }
1093 Err(_) => SmallVec::<[NodeId; 8]>::new(),
1094 }
1095 }
1096
1097 pub fn visit_node_children(&self, node_id: NodeId, mut visit: impl FnMut(NodeId, bool)) {
1103 let applier = self.borrow_applier();
1104 let Ok(node) = applier.get_ref(node_id) else {
1105 return;
1106 };
1107 node.for_each_child(&mut |child| {
1108 let needs_relayout = applier.get_ref(child).is_ok_and(Node::layout_dirty);
1109 visit(child, needs_relayout);
1110 });
1111 }
1112
1113 pub fn nodes_need_relayout(&self, node_ids: impl IntoIterator<Item = NodeId>) -> bool {
1122 let applier = self.borrow_applier();
1123 node_ids
1124 .into_iter()
1125 .any(|node_id| applier.get_ref(node_id).is_ok_and(Node::layout_dirty))
1126 }
1127
1128 pub fn clear_node_children(&self, node_id: NodeId) {
1134 let mut applier = self.borrow_applier();
1135 if let Ok(node) = applier.get_mut(node_id) {
1136 node.update_children(&[]);
1137 }
1138 }
1139
1140 pub fn install<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
1143 let _composer_guard = composer_context::enter(self);
1144 runtime::push_active_runtime(&self.core.runtime);
1145 struct Guard;
1146 impl Drop for Guard {
1147 fn drop(&mut self) {
1148 runtime::pop_active_runtime();
1149 }
1150 }
1151 let guard = Guard;
1152 let result = f(self);
1153 drop(guard);
1154 result
1155 }
1156
1157 pub(crate) fn flush_pending_commands_if_large(&self) -> Result<(), NodeError> {
1158 let queued = self.core.commands.borrow().len();
1159 if queued < COMMAND_FLUSH_THRESHOLD {
1160 return Ok(());
1161 }
1162 self.apply_pending_commands()
1163 }
1164
1165 fn resolve_group_entry(
1166 &self,
1167 host: &Rc<SlotsHost>,
1168 seed: crate::slot::GroupKeySeed,
1169 parent_scope_id: Option<ScopeId>,
1170 ) -> GroupEntry {
1171 let key = host.with_write_session(|slots| slots.reserve_group_key(seed));
1172 let retain_key = RetainKey::for_group(parent_scope_id, key);
1173 let restored = self
1174 .core
1175 .shared_state
1176 .take_retained(host, retain_key, |subtree| {
1177 host.with_write_session(|slots| slots.retained_restore_ready(key, subtree))
1178 })
1179 .or_else(|| self.take_movable_from_another_table(host, retain_key, key))
1180 .map(Box::new);
1181 if restored.is_some() || !key.is_movable() {
1182 return GroupEntry {
1183 key,
1184 restored,
1185 placeholder_for: None,
1186 };
1187 }
1188 let attached_elsewhere = self.movable_attached_elsewhere(host, key);
1189 if !attached_elsewhere {
1190 return GroupEntry {
1191 key,
1192 restored: None,
1193 placeholder_for: None,
1194 };
1195 }
1196 let id = key.explicit_key.unwrap_or_default();
1197 let placeholder = host.with_write_session(|slots| {
1198 slots.reserve_group_key(crate::slot::GroupKeySeed::movable_placeholder(id))
1199 });
1200 GroupEntry {
1201 key: placeholder,
1202 restored: None,
1203 placeholder_for: Some(key),
1204 }
1205 }
1206
1207 fn take_movable_from_another_table(
1212 &self,
1213 host: &Rc<SlotsHost>,
1214 retain_key: RetainKey,
1215 key: crate::slot::GroupKey,
1216 ) -> Option<crate::slot::DetachedSubtree> {
1217 if !key.is_movable() {
1218 return None;
1219 }
1220 let (source, mut subtree) = self
1221 .core
1222 .shared_state
1223 .take_retained_movable_elsewhere(host, retain_key)?;
1224 source
1225 .borrow_mut()
1226 .invalidate_detached_subtree_anchors(&subtree);
1227 if host.with_write_session(|slots| slots.retained_restore_ready(key, &mut subtree)) {
1228 return Some(subtree);
1229 }
1230 log::error!(
1231 "movable content {key:?} could not be taken over by the slot table that asked for it"
1232 );
1233 if let Err(error) = self.dispose_detached_subtree_in_host(host, subtree) {
1234 log::error!("disposing movable content that could not move failed: {error}");
1235 }
1236 None
1237 }
1238
1239 fn movable_attached_elsewhere(&self, host: &Rc<SlotsHost>, key: crate::slot::GroupKey) -> bool {
1242 if host.with_write_session(|slots| slots.movable_attached_elsewhere(key)) {
1243 return true;
1244 }
1245 let Some(id) = key.movable_id() else {
1246 return false;
1247 };
1248 self.core
1249 .shared_state
1250 .host_holding_movable(id)
1251 .is_some_and(|holder| !Rc::ptr_eq(&holder, host))
1252 }
1253
1254 fn start_group(
1255 &self,
1256 host: &Rc<SlotsHost>,
1257 seed: crate::slot::GroupKeySeed,
1258 parent_node: Option<NodeId>,
1259 ) -> (
1260 GroupStart<crate::slot::ActiveGroupId>,
1261 Option<crate::slot::GroupKey>,
1262 ) {
1263 if !self.core.shared_state.retains_any() {
1264 let started = host.with_write_session(|slots| {
1265 let key = slots.reserve_group_key(seed);
1266 (!key.is_movable()).then(|| slots.begin_group(key, None, parent_node))
1267 });
1268 if let Some(started) = started {
1269 return (started, None);
1270 }
1271 }
1272 let parent_scope_id = {
1274 let mut stack = self.scope_stack();
1275 let top = stack.len().checked_sub(1);
1276 top.map(|top| self.frame_scope(&mut stack, top).id())
1277 };
1278 let GroupEntry {
1279 key,
1280 restored,
1281 placeholder_for,
1282 } = self.resolve_group_entry(host, seed, parent_scope_id);
1283 let started =
1284 host.with_write_session(|slots| slots.begin_group(key, restored, parent_node));
1285 (started, placeholder_for)
1286 }
1287
1288 #[doc(hidden)]
1289 pub fn __branch_group_deferred(&self, key: Key) -> BranchGroupGuard<'_> {
1290 let folds = &*self.core.branch_folds;
1291 BranchGroupGuard {
1292 token: folds.push(key),
1293 folds,
1294 }
1295 }
1296
1297 fn dispose_detached_nodes(&self, nodes: impl IntoIterator<Item = NodeId>) {
1298 for node_id in nodes {
1299 self.commands_mut().push(Command::callback(move |applier| {
1300 crate::slot::dispose_detached_node_now(applier, node_id)
1301 }));
1302 }
1303 }
1304
1305 fn detached_root_parent_commands(
1306 &self,
1307 subtree: &crate::slot::DetachedSubtree,
1308 context: &'static str,
1309 ) -> Result<Vec<(NodeId, Option<NodeId>)>, NodeError> {
1310 let mut root_nodes = Vec::new();
1311 subtree.collect_root_nodes_checked_into(&mut root_nodes, context);
1312 let mut roots = Vec::with_capacity(root_nodes.len());
1313 for root in root_nodes {
1314 let parent_id = {
1315 let mut applier = self.borrow_applier();
1316 applier.get_mut(root)?.parent()
1317 };
1318 roots.push((root, parent_id));
1319 }
1320 Ok(roots)
1321 }
1322
1323 fn retain_detached_subtree_in_host(
1324 &self,
1325 slots_host: &Rc<SlotsHost>,
1326 parent_scope: Option<ScopeId>,
1327 subtree: crate::slot::DetachedSubtree,
1328 ) -> Result<(), NodeError> {
1329 let Some(root_key) = subtree.root_key_checked() else {
1330 log::error!("retention rejected detached subtree without a root group");
1331 self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1332 return Ok(());
1333 };
1334 let root_detaches = self.detached_root_parent_commands(&subtree, "retention")?;
1335 subtree.scopes().for_each(RecomposeScope::deactivate);
1336 for (root, parent_id) in root_detaches {
1337 if let Some(parent_id) = parent_id {
1338 self.commands_mut().push(Command::DetachChild {
1339 parent_id,
1340 child_id: root,
1341 });
1342 }
1343 }
1344 let evicted = self.core.shared_state.insert_retained(
1345 slots_host,
1346 RetainKey::for_group(parent_scope, root_key),
1347 subtree,
1348 root_key.is_movable(),
1349 );
1350 for subtree in evicted {
1351 self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1352 }
1353 Ok(())
1354 }
1355
1356 fn evict_retained_subtrees_for_host(
1357 &self,
1358 slots_host: &Rc<SlotsHost>,
1359 ) -> Result<(), NodeError> {
1360 let evicted = self.core.shared_state.advance_retention_pass(slots_host);
1361 for subtree in evicted {
1362 self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1363 }
1364 Ok(())
1365 }
1366
1367 fn dispose_detached_subtree_in_host(
1368 &self,
1369 slots_host: &Rc<SlotsHost>,
1370 subtree: crate::slot::DetachedSubtree,
1371 ) -> Result<(), NodeError> {
1372 let root_nodes = self
1373 .detached_root_parent_commands(&subtree, "disposal")?
1374 .into_iter()
1375 .map(|(root, _)| root);
1376 subtree.scopes().for_each(RecomposeScope::deactivate);
1377 self.dispose_detached_nodes(root_nodes);
1378 slots_host.with_table_and_lifecycle_mut(|table, lifecycle| {
1379 table.invalidate_detached_subtree_anchors(&subtree);
1380 lifecycle.queue_subtree_disposal(subtree);
1381 });
1382 Ok(())
1383 }
1384
1385 fn handle_detached_children_in_host(
1386 &self,
1387 slots_host: &Rc<SlotsHost>,
1388 parent_scope: Option<ScopeId>,
1389 detached: Vec<crate::slot::DetachedSubtree>,
1390 ) -> Result<(), NodeError> {
1391 for mut subtree in detached {
1392 for movable in subtree.split_off_nested_movables() {
1393 self.retain_detached_subtree_in_host(slots_host, None, movable)?;
1394 }
1395 if subtree
1396 .root_key_checked()
1397 .is_some_and(crate::slot::GroupKey::is_movable)
1398 {
1399 self.retain_detached_subtree_in_host(slots_host, None, subtree)?;
1400 continue;
1401 }
1402 let retention_mode = subtree
1403 .root_scope()
1404 .map_or_default(RecomposeScope::retention_mode);
1405 match retention_mode {
1406 RetentionMode::DisposeWhenInactive => {
1407 self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1408 }
1409 RetentionMode::RetainWhenInactive => {
1410 self.retain_detached_subtree_in_host(slots_host, parent_scope, subtree)?;
1411 }
1412 }
1413 }
1414 Ok(())
1415 }
1416
1417 fn handle_finished_group_result(
1418 &self,
1419 host: &Rc<SlotsHost>,
1420 parent_scope: Option<ScopeId>,
1421 result: FinishGroupResult,
1422 ) {
1423 let FinishGroupResult {
1424 detached_children,
1425 direct_nodes,
1426 root_nodes,
1427 was_skipped,
1428 } = result;
1429 if was_skipped {
1430 self.attach_root_nodes(root_nodes);
1431 }
1432 self.dispose_detached_nodes(direct_nodes);
1433 if detached_children.is_empty() {
1434 return;
1435 }
1436 if let Err(err) =
1437 self.handle_detached_children_in_host(host, parent_scope, detached_children)
1438 {
1439 log::error!("detached subtree handling failed while closing a group: {err}");
1440 }
1441 }
1442
1443 pub(crate) fn close_current_group_body_for_scope(&self, scope: &RecomposeScope) {
1444 self.close_group_body(&self.active_slots_host(), scope);
1445 }
1446
1447 fn close_group_body(&self, host: &Rc<SlotsHost>, scope: &RecomposeScope) {
1448 #[expect(
1449 clippy::redundant_closure_for_method_calls,
1450 reason = "the method path is not general over the session lifetime"
1451 )]
1452 let result = host.with_write_session(|slots| slots.finish_group_body_changes());
1453 self.close_finished_group(host, Some(scope), result);
1454 }
1455
1456 fn close_finished_group(
1459 &self,
1460 host: &Rc<SlotsHost>,
1461 scope: Option<&RecomposeScope>,
1462 result: Option<FinishGroupResult>,
1463 ) {
1464 if let Some(result) = result {
1465 self.handle_finished_group_result(host, scope.map(RecomposeScope::id), result);
1466 }
1467 self.pop_closed_scope();
1468 }
1469
1470 #[track_caller]
1473 pub fn remember<T: 'static>(&self, init: impl FnOnce() -> T) -> Owned<T> {
1474 self.remember_at(crate::caller_location_key(), init)
1475 }
1476
1477 #[doc(hidden)]
1478 pub fn remember_at<T: 'static>(&self, source: Key, init: impl FnOnce() -> T) -> Owned<T> {
1479 self.with_slot_session_mut(|slots| {
1480 slots.remember_with_kind(PayloadKind::Remember, source, init)
1481 })
1482 }
1483
1484 #[track_caller]
1485 pub(crate) fn remember_internal<T: 'static>(
1486 &self,
1487 source_salt: Key,
1488 init: impl FnOnce() -> T,
1489 ) -> Owned<T> {
1490 let source = crate::caller_location_key().scoped(source_salt);
1491 self.with_slot_session_mut(|slots| {
1492 slots.remember_with_kind(PayloadKind::Internal, source, init)
1493 })
1494 }
1495
1496 #[track_caller]
1497 pub(crate) fn remember_effect<T: Default + 'static>(&self, site: Key) -> Owned<T> {
1500 self.with_slot_session_mut(|slots| slots.remember_effect::<T>(site))
1501 }
1502
1503 #[track_caller]
1506 pub fn use_value_slot<T: 'static>(&self, init: impl FnOnce() -> T) -> ValueSlotHandle<'_, T> {
1507 let source = crate::caller_location_key();
1508 let (slot, record) = self.with_slot_session_mut(|slots| {
1509 slots.located_value_slot(PayloadKind::Internal, source, init)
1510 });
1511 ValueSlotHandle::new(slot, record)
1512 }
1513
1514 #[doc(hidden)]
1515 pub fn __use_param_slot<T: 'static>(
1516 &self,
1517 source: Key,
1518 init: impl FnOnce() -> T,
1519 ) -> ValueSlotHandle<'_, T> {
1520 let (slot, record) = self.with_slot_session_mut(|slots| {
1521 slots.located_value_slot(PayloadKind::Param, source, init)
1522 });
1523 ValueSlotHandle::new(slot, record)
1524 }
1525
1526 #[doc(hidden)]
1529 pub fn __update_param_slot<T: 'static, R>(
1530 &self,
1531 source: Key,
1532 init: impl FnOnce() -> T,
1533 update: impl FnOnce(&mut T) -> R,
1534 ) -> (ValueSlotHandle<'_, T>, R) {
1535 self.update_value_slot(PayloadKind::Param, source, init, update)
1536 }
1537
1538 #[doc(hidden)]
1541 pub fn __update_return_slot<T: 'static, R>(
1542 &self,
1543 source: Key,
1544 init: impl FnOnce() -> T,
1545 read: impl FnOnce(&mut T) -> R,
1546 ) -> (ValueSlotHandle<'_, T>, R) {
1547 self.update_value_slot(PayloadKind::Return, source, init, read)
1548 }
1549
1550 fn update_value_slot<T: 'static, R>(
1551 &self,
1552 kind: PayloadKind,
1553 source: Key,
1554 init: impl FnOnce() -> T,
1555 update: impl FnOnce(&mut T) -> R,
1556 ) -> (ValueSlotHandle<'_, T>, R) {
1557 self.with_slot_session_mut(|slots| {
1558 let (slot, record, value) = slots.value_slot_and_value(kind, source, init);
1559 (ValueSlotHandle::new(slot, record), update(value))
1560 })
1561 }
1562
1563 #[doc(hidden)]
1564 #[track_caller]
1565 pub fn __use_return_slot<T: 'static>(
1566 &self,
1567 init: impl FnOnce() -> T,
1568 ) -> ValueSlotHandle<'_, T> {
1569 let source = crate::caller_location_key();
1570 let (slot, record) = self.with_slot_session_mut(|slots| {
1571 slots.located_value_slot(PayloadKind::Return, source, init)
1572 });
1573 ValueSlotHandle::new(slot, record)
1574 }
1575
1576 #[doc(hidden)]
1577 pub fn __invalidate_return_consumer_scope(&self) {
1578 let Some(scope) = self.current_recompose_scope() else {
1579 self.request_root_render();
1580 return;
1581 };
1582
1583 if let Some(target) = scope.callback_promotion_target() {
1584 target.invalidate();
1585 } else {
1586 self.request_root_render();
1587 }
1588 }
1589
1590 pub fn with_slot_value<'pass, T: 'static, R>(
1592 &'pass self,
1593 handle: ValueSlotHandle<'pass, T>,
1594 f: impl FnOnce(&T) -> R,
1595 ) -> R {
1596 self.with_slots(|slots| f(slots.value_at(handle.slot, handle.record)))
1597 }
1598
1599 pub fn with_slot_value_mut<'pass, T: 'static, R>(
1601 &'pass self,
1602 handle: ValueSlotHandle<'pass, T>,
1603 f: impl FnOnce(&mut T) -> R,
1604 ) -> R {
1605 self.with_slots_mut(|slots| f(slots.value_at_mut(handle.slot, handle.record)))
1606 }
1607
1608 pub fn mutable_state_of<T: Clone + 'static>(&self, initial: T) -> MutableState<T> {
1611 MutableState::with_runtime(initial, self.runtime_handle())
1612 }
1613
1614 pub fn mutable_state_list_of<T, I>(&self, values: I) -> SnapshotStateList<T>
1617 where
1618 T: Clone + 'static,
1619 I: IntoIterator<Item = T>,
1620 {
1621 SnapshotStateList::with_runtime(values, self.runtime_handle())
1622 }
1623
1624 pub fn mutable_state_map_of<K, V, I>(&self, pairs: I) -> SnapshotStateMap<K, V>
1627 where
1628 K: Clone + Eq + Hash + 'static,
1629 V: Clone + 'static,
1630 I: IntoIterator<Item = (K, V)>,
1631 {
1632 SnapshotStateMap::with_runtime(pairs, self.runtime_handle())
1633 }
1634
1635 pub fn read_composition_local<T: Clone + 'static>(&self, local: &CompositionLocal<T>) -> T {
1638 self.read_provided(
1639 &local.key,
1640 |entry: &LocalStateEntry<T>| entry.value(),
1641 |entry: &ComputedLocalEntry<T>| entry.value(),
1642 )
1643 .unwrap_or_else(|| local.default_value())
1644 }
1645
1646 pub fn read_static_composition_local<T: Clone + 'static>(
1649 &self,
1650 local: &StaticCompositionLocal<T>,
1651 ) -> T {
1652 let provided = local.provided_under(&self.core.local_stack.borrow());
1653 provided.unwrap_or_else(|deferred| deferred.value(local))
1654 }
1655
1656 fn read_provided<V: 'static, C: 'static, T>(
1660 &self,
1661 key: &LocalKey,
1662 value: impl FnOnce(&V) -> T,
1663 computed: impl FnOnce(&C) -> T,
1664 ) -> Option<T> {
1665 let entry = provided_entry(&self.core.local_stack.borrow(), key)?;
1666 match entry.downcast::<V>() {
1667 Ok(entry) => Some(value(&entry)),
1668 Err(entry) => entry
1669 .downcast::<C>()
1670 .inspect_err(|_| key.report_type_mismatch())
1671 .ok()
1672 .map(|entry| computed(&entry)),
1673 }
1674 }
1675
1676 pub(crate) fn restarted_scope(&self) -> Option<RecomposeScope> {
1679 self.core.restarted_scope.borrow().clone()
1680 }
1681
1682 pub fn phase(&self) -> crate::Phase {
1684 self.core.phase.get()
1685 }
1686
1687 pub(crate) fn set_phase(&self, phase: crate::Phase) {
1688 self.core.phase.set(phase);
1689 }
1690
1691 pub fn enter_phase(&self, phase: crate::Phase) {
1693 self.set_phase(phase);
1694 }
1695
1696 pub(crate) fn subcompose<R>(
1697 &self,
1698 state: &mut SubcomposeState,
1699 slot_id: SlotId,
1700 content: impl FnOnce(&Self) -> R,
1701 ) -> (R, Vec<NodeId>) {
1702 match self.phase() {
1703 crate::Phase::Measure | crate::Phase::Layout => {}
1704 current => panic!(
1705 "subcompose() may only be called during measure or layout; current phase: {current:?}"
1706 ),
1707 }
1708
1709 self.subcompose_stack().push(SubcomposeFrame::default());
1710 let mut guard = SubcomposeStackGuard {
1711 core: self.clone_core(),
1712 leaked: false,
1713 };
1714
1715 let slot_host = state.get_or_create_slots(slot_id);
1716 let (result, _) = self.with_slot_override(slot_host, |composer| {
1717 composer.with_group(Key(slot_id.raw()), |composer| content(composer))
1718 });
1719
1720 let frame = {
1721 let frame = take_subcompose_frame(&guard.core, "subcompose");
1722 guard.leaked = true;
1723 frame
1724 };
1725 let nodes = frame.nodes;
1726 let scopes = frame.scopes;
1727 state.register_active(slot_id, &nodes, &scopes);
1728 (result, nodes)
1729 }
1730
1731 pub fn subcompose_measurement<R>(
1734 &self,
1735 state: &mut SubcomposeState,
1736 slot_id: SlotId,
1737 content: impl FnOnce(&Self) -> R,
1738 ) -> (R, Vec<NodeId>) {
1739 let (result, nodes) = self.subcompose(state, slot_id, content);
1740 let roots = nodes
1741 .into_iter()
1742 .filter(|&id| self.node_has_no_parent(id))
1743 .collect();
1744
1745 (result, roots)
1746 }
1747
1748 fn subcompose_site(&self) -> SubcomposeSite<'_> {
1750 SubcomposeSite {
1751 applier: &self.core.applier,
1752 runtime: &self.core.runtime,
1753 phase: self.phase(),
1754 locals_changed: self.core.locals_changed.get(),
1755 }
1756 }
1757
1758 pub fn subcompose_in<R>(
1762 &self,
1763 slots: &Rc<SlotsHost>,
1764 root: Option<NodeId>,
1765 f: impl FnOnce(&Self) -> R,
1766 ) -> Result<R, NodeError> {
1767 let _teardown = runtime::enter_state_teardown_scope();
1768 let site = self.subcompose_site();
1769 let shared_state = slots
1770 .runtime_state()
1771 .unwrap_or_else(|| Rc::clone(&self.core.shared_state));
1772 let core = site.spin_up_core(shared_state, slots, root, self.current_local_stack());
1773 let composer = Self::from_core(core);
1774 let (result, commands, side_effects, compact_applier) = composer.install(|composer| {
1775 let (output, outcome) = composer.try_with_slot_host_pass(
1776 Rc::clone(slots),
1777 crate::slot::SlotPassMode::Compose,
1778 |composer| f(composer),
1779 )?;
1780 let commands = composer.take_commands();
1781 let side_effects = composer.take_side_effects();
1782 Ok((output, commands, side_effects, outcome.compacted))
1783 })?;
1784 site.flush(commands, compact_applier, side_effects)?;
1785 Ok(result)
1786 }
1787
1788 pub fn capture_composition_context(&self) -> CapturedCompositionContext {
1799 CapturedCompositionContext {
1800 locals: self.current_local_stack(),
1801 owner_scope: self
1802 .current_recompose_scope()
1803 .map(|scope| scope.downgrade()),
1804 locals_changed: self.core.locals_changed.get(),
1805 }
1806 }
1807
1808 pub fn with_captured_locals<R>(
1813 &self,
1814 context: &CapturedCompositionContext,
1815 f: impl FnOnce(&Self) -> R,
1816 ) -> R {
1817 let parent = self.current_local_stack();
1818 self.local_stack().clone_from(&context.locals);
1819 let result = self.with_locals_changed(context.locals_changed, f);
1820 *self.local_stack() = parent;
1821 result
1822 }
1823
1824 pub fn with_locals_changed<R>(&self, changed: bool, f: impl FnOnce(&Self) -> R) -> R {
1828 let outer = self.core.locals_changed.get();
1829 self.core.locals_changed.set(outer || changed);
1830 let result = f(self);
1831 self.core.locals_changed.set(outer);
1832 result
1833 }
1834
1835 pub fn subcompose_slot<R>(
1840 &self,
1841 slots: &Rc<SlotsHost>,
1842 root: Option<NodeId>,
1843 f: impl FnOnce(&Self) -> R,
1844 ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1845 let context = self.capture_composition_context();
1846 self.subcompose_slot_with_context(slots, root, &context, f)
1847 }
1848
1849 pub fn subcompose_slot_with_context<R>(
1853 &self,
1854 slots: &Rc<SlotsHost>,
1855 root: Option<NodeId>,
1856 context: &CapturedCompositionContext,
1857 f: impl FnOnce(&Self) -> R,
1858 ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1859 subcompose_slot_at(
1860 self.subcompose_site(),
1861 || Rc::clone(&self.core.shared_state),
1862 slots,
1863 root,
1864 context,
1865 f,
1866 )
1867 }
1868
1869 pub fn subcompose_measure_slot<R>(
1874 applier: &Rc<dyn ApplierHost>,
1875 runtime: &RuntimeHandle,
1876 slots: &Rc<SlotsHost>,
1877 root: NodeId,
1878 context: &CapturedCompositionContext,
1879 f: impl FnOnce(&Self) -> R,
1880 ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1881 let site = SubcomposeSite {
1882 applier,
1883 runtime,
1884 phase: crate::Phase::Measure,
1885 locals_changed: false,
1886 };
1887 let new_state = || measure_slot_state(applier, context);
1888 subcompose_slot_at(site, new_state, slots, Some(root), context, f)
1889 }
1890
1891 fn attach_root_nodes(&self, root_nodes: RootNodeIds) {
1892 for id in root_nodes {
1893 self.attach_to_parent(id);
1894 }
1895 }
1896
1897 pub fn skip_current_group(&self) {
1900 #[expect(
1901 clippy::redundant_closure_for_method_calls,
1902 reason = "the method path is not general over the session lifetime"
1903 )]
1904 self.with_slot_session_mut(|slots| slots.skip_group());
1905 }
1906
1907 pub fn runtime_handle(&self) -> RuntimeHandle {
1909 self.core.runtime.clone()
1910 }
1911
1912 pub fn set_recompose_callback<F>(&self, callback: F)
1915 where
1916 F: FnMut(&Self) + 'static,
1917 {
1918 if let Some(scope) = self.current_recompose_scope() {
1919 scope.set_recompose_callback(callback);
1920 }
1921 }
1922
1923 pub fn set_recompose_fn(&self, callback: fn(&Self)) {
1925 if let Some(scope) = self.current_recompose_scope() {
1926 scope.set_recompose_fn(callback);
1927 }
1928 }
1929
1930 pub fn with_composition_locals<R>(
1933 &self,
1934 provided: impl IntoIterator<Item = ProvidedValue>,
1935 site: Key,
1936 f: impl FnOnce(&Self) -> R,
1937 ) -> R {
1938 let provided: SmallVec<[ProvidedValue; 2]> = provided.into_iter().collect();
1939 if provided.is_empty() {
1940 return f(self);
1941 }
1942 let mut values = SmallVec::<[(LocalKey, Rc<dyn Any>); 2]>::new();
1943 let mut static_changed = false;
1944 for value in provided.into_iter().rev() {
1945 if values.iter().any(|(key, _)| key == value.key()) {
1946 continue;
1947 }
1948 let (key, entry, changed) = value.into_entry(self, site);
1949 static_changed |= changed;
1950 values.push((key, entry));
1951 }
1952 let parent = self.current_local_stack();
1953 *self.local_stack() = Some(Rc::new(LocalFrame {
1954 values,
1955 parent: parent.clone(),
1956 }));
1957 let result = self.with_locals_changed(static_changed, f);
1958 *self.local_stack() = parent;
1959 result
1960 }
1961}