Skip to main content

cranpose_core/composer/
scope_frame.rs

1//! The frames of a composer's scope stack: a scope, or a group that makes
2//! its scope only when its body first needs one.
3
4use super::{GroupScopeEntry, reparent_restored_scopes};
5use crate::{
6    AnchorId, Composer, LocalStackSnapshot, NodeId, RecomposeOptions, RecomposeScope,
7    RetentionMode, ScopeRead, StateId,
8    slot::{ActiveGroupId, GroupStartKind},
9};
10
11// A frame of the composer's scope stack: a group's scope, the scope a
12// restarted body or a callback runs in, or a group whose body makes its
13// scope when it first needs one.
14pub(crate) enum ScopeFrame {
15    Made(RecomposeScope),
16    Deferred(DeferredScope),
17}
18
19// What a group without a scope keeps to make one: most bodies read no
20// state, take no callback and ask for no scope, and their groups keep none.
21pub(crate) struct DeferredScope {
22    pub(crate) group: ActiveGroupId,
23    anchor: AnchorId,
24    parent_hint: Option<NodeId>,
25    locals: LocalStackSnapshot,
26    pub(crate) recompose: Option<fn(&Composer)>,
27    // The composables around the group when it took `recompose`: a scope
28    // its body makes later, inside its own source scope, restores these.
29    #[cfg(feature = "inspection")]
30    source: Option<std::rc::Rc<[crate::source_trace::SourceLocation]>>,
31    // Whether the body runs whatever its parameters: a changed static
32    // composition local, or reused content around it.
33    pub(crate) forced: bool,
34    pub(crate) composed_once: bool,
35    // The scope the body made.
36    pub(crate) made: Option<RecomposeScope>,
37}
38
39impl ScopeFrame {
40    pub(crate) fn scope(&self) -> Option<&RecomposeScope> {
41        match self {
42            Self::Made(scope) => Some(scope),
43            Self::Deferred(deferred) => deferred.made.as_ref(),
44        }
45    }
46
47    // Whether a state read in the frame recomposes it: a group of a
48    // composable, which recomposes through its function, or a scope with a
49    // hand-written body.
50    fn has_recompose_callback(&self) -> bool {
51        match self {
52            Self::Made(scope) => scope.has_recompose_callback(),
53            Self::Deferred(deferred) => match &deferred.made {
54                Some(scope) => scope.has_recompose_callback(),
55                None => deferred.recompose.is_some(),
56            },
57        }
58    }
59}
60
61// Whether a group opened with `options` and `kind` waits for its body to
62// make its scope.
63pub(super) fn may_defer(options: RecomposeOptions, kind: GroupStartKind) -> bool {
64    !options.force_reuse
65        && !options.force_recompose
66        && matches!(options.retention, RetentionMode::DisposeWhenInactive)
67        && !matches!(kind, GroupStartKind::Restored)
68}
69
70#[expect(clippy::multiple_inherent_impl, reason = "one file per concern")]
71impl Composer {
72    /// Returns the recompose scope being composed, or `None` outside any scope.
73    pub fn current_recompose_scope(&self) -> Option<RecomposeScope> {
74        let mut stack = self.core.scope_stack.borrow_mut();
75        let top = stack.len().checked_sub(1)?;
76        Some(self.frame_scope(&mut stack, top))
77    }
78
79    // The scope being composed when it has one: a group whose body made
80    // none yet gives `None`, and makes none.
81    pub(crate) fn peek_recompose_scope(&self) -> Option<RecomposeScope> {
82        self.core
83            .scope_stack
84            .borrow()
85            .last()
86            .and_then(ScopeFrame::scope)
87            .cloned()
88    }
89
90    pub(crate) fn note_state_read(
91        &self,
92        state_id: Option<StateId>,
93    ) -> Option<(RecomposeScope, ScopeRead)> {
94        let scope = {
95            let mut stack = self.core.scope_stack.borrow_mut();
96            let index = stack
97                .iter()
98                .rposition(ScopeFrame::has_recompose_callback)
99                .or_else(|| stack.len().checked_sub(1))?;
100            self.frame_scope(&mut stack, index)
101        };
102        let read = state_id.map_or(ScopeRead::NotReading, |id| scope.note_read(id));
103        (!matches!(read, ScopeRead::Watched)).then_some((scope, read))
104    }
105
106    // Whether a group opened now waits for its body to make its scope: not
107    // a group with no group around it, one in pausable content, or the
108    // first group of a subcomposition slot, whose scope the slot keeps.
109    pub(super) fn defers_scopes_here(&self) -> bool {
110        !self.core.scope_stack.borrow().is_empty()
111            && !self.core.shared_state.pausing.is_holding()
112            && self
113                .subcompose_stack()
114                .last()
115                .is_none_or(|frame| !frame.scopes.is_empty())
116    }
117
118    // Opens the scope frame of a group that makes its scope when its body
119    // first needs one.
120    pub(super) fn push_deferred_scope(
121        &self,
122        (group, anchor): (ActiveGroupId, AnchorId),
123        kind: GroupStartKind,
124        parent_hint: Option<NodeId>,
125    ) {
126        let forced = self.core.locals_changed.get() || self.core.reused_depth.get() > 0;
127        let frame = DeferredScope {
128            group,
129            anchor,
130            parent_hint,
131            locals: self.core.local_stack.borrow().clone(),
132            recompose: None,
133            #[cfg(feature = "inspection")]
134            source: None,
135            forced,
136            composed_once: !matches!(kind, GroupStartKind::Inserted),
137            made: None,
138        };
139        self.scope_stack().push(ScopeFrame::Deferred(frame));
140    }
141
142    // The scope of the frame at `index`, made now for a group that has
143    // none yet.
144    pub(super) fn frame_scope(&self, stack: &mut [ScopeFrame], index: usize) -> RecomposeScope {
145        let (below, frame) = stack.split_at_mut(index);
146        let deferred = match &mut frame[0] {
147            ScopeFrame::Made(scope) => return scope.clone(),
148            ScopeFrame::Deferred(deferred) => deferred,
149        };
150        if let Some(scope) = &deferred.made {
151            return scope.clone();
152        }
153        let owner = below.iter().rev().find_map(ScopeFrame::scope);
154        let scope = RecomposeScope::new(self.runtime_handle());
155        match owner {
156            Some(owner) => scope.set_parent_scope(Some(owner)),
157            None => scope
158                .set_lifetime_owner_scope(self.core.subcomposition_owner_scope.borrow().as_ref()),
159        }
160        // The scope learns its slot host when its group closes: a body may
161        // read a state while the host's table is open for a write.
162        scope.set_group_anchor(deferred.anchor);
163        scope.snapshot_locals(&deferred.locals);
164        scope.set_parent_hint(deferred.parent_hint);
165        if let Some(recompose) = deferred.recompose {
166            scope.set_recompose_fn(recompose);
167            #[cfg(feature = "inspection")]
168            if let Some(source) = deferred.source.take() {
169                scope.set_recompose_source(source);
170            }
171        }
172        if deferred.composed_once {
173            scope.mark_composed_once();
174        }
175        scope.begin_reads();
176        if let Some(frame) = self.subcompose_stack().last_mut() {
177            frame.scopes.push(scope.clone());
178        }
179        deferred.made = Some(scope.clone());
180        scope
181    }
182
183    // Enters `scope_ref`, the scope of a group opened with it; returns
184    // whether the group forces the groups below it to run their bodies, as
185    // reused content does.
186    pub(super) fn enter_group_scope(
187        &self,
188        scope_ref: &RecomposeScope,
189        entry: &GroupScopeEntry<'_>,
190    ) -> bool {
191        let GroupScopeEntry {
192            options,
193            start_kind,
194            host,
195            group,
196            parent_hint,
197        } = *entry;
198        // A group entered while its scope is inactive is reused content, as
199        // when a lazy list gives a recycled row to another item: like Compose,
200        // it composes again rather than skipping, which reactivates the
201        // scopes beneath it.
202        let reused = !scope_ref.is_active() && scope_ref.has_composed_once();
203        scope_ref.reactivate();
204        {
205            let mut stack = self.scope_stack();
206            // Content a group keeps when it leaves is found again by its
207            // parent's scope.
208            if matches!(options.retention, RetentionMode::RetainWhenInactive)
209                && let Some(top) = stack.len().checked_sub(1)
210            {
211                self.frame_scope(&mut stack, top);
212            }
213            match stack.iter().rev().find_map(ScopeFrame::scope) {
214                Some(parent_scope) => scope_ref.set_parent_scope(Some(parent_scope)),
215                None => scope_ref.set_lifetime_owner_scope(
216                    self.core.subcomposition_owner_scope.borrow().as_ref(),
217                ),
218            }
219            stack.push(ScopeFrame::Made(scope_ref.clone()));
220        }
221        scope_ref.set_retention_mode(options.retention);
222
223        // Content under a changed static composition local runs every body,
224        // as restored content does.
225        let restored = matches!(start_kind, GroupStartKind::Restored);
226        let recompose = options.force_recompose | self.core.locals_changed.get() | restored;
227        // Reused content runs every body below it, whose scopes it left
228        // inactive; restored content reactivates the scopes below it.
229        let forces_content = reused & !restored & !options.force_reuse;
230        if recompose | forces_content {
231            scope_ref.force_recompose();
232        } else if options.force_reuse {
233            scope_ref.force_reuse();
234        }
235        if forces_content {
236            let depth = &self.core.reused_depth;
237            depth.set(depth.get() + 1);
238        }
239
240        scope_ref.set_slots_host(host);
241
242        {
243            let mut stack = self.subcompose_stack();
244            if let Some(frame) = stack.last_mut() {
245                frame.scopes.push(scope_ref.clone());
246            }
247        }
248
249        scope_ref.snapshot_locals(&self.core.local_stack.borrow());
250        if restored {
251            reparent_restored_scopes(host, group, scope_ref.parent_hint(), parent_hint);
252        }
253        scope_ref.set_parent_hint(parent_hint);
254        forces_content
255    }
256
257    // The deferred frame of the group opened last, whose body has not run.
258    fn with_last_deferred<R>(&self, read: fn(&mut DeferredScope) -> R) -> Option<R> {
259        match self.scope_stack().last_mut() {
260            Some(ScopeFrame::Deferred(deferred)) => Some(read(deferred)),
261            _ => None,
262        }
263    }
264
265    // Whether the group opened last, which waits for its body to make its
266    // scope, runs its body whatever its parameters.
267    pub(super) fn deferred_scope_forced(&self) -> bool {
268        self.with_last_deferred(|deferred| deferred.forced)
269            .unwrap_or(false)
270    }
271
272    // Whether the group opened last, which waits for its body to make its
273    // scope, composed before.
274    pub(super) fn deferred_scope_composed_once(&self) -> bool {
275        self.with_last_deferred(|deferred| deferred.composed_once)
276            .unwrap_or(false)
277    }
278
279    // Gives the group opened last, which waits for its body to make its
280    // scope, the function that recomposes the scope it makes.
281    pub(super) fn set_deferred_recompose_fn(&self, body: fn(&Self)) {
282        if let Some(ScopeFrame::Deferred(deferred)) = self.scope_stack().last_mut() {
283            match &deferred.made {
284                Some(scope) => scope.set_recompose_fn(body),
285                None => {
286                    deferred.recompose = Some(body);
287                    #[cfg(feature = "inspection")]
288                    {
289                        deferred.source = Some(crate::source_trace::current_source_trace());
290                    }
291                }
292            }
293        }
294    }
295
296    // The scope the body of the group that closes now made, with the group.
297    pub(super) fn scope_made_by_body(&self) -> Option<(ActiveGroupId, RecomposeScope)> {
298        match self.scope_stack().last() {
299            Some(ScopeFrame::Deferred(deferred)) => deferred
300                .made
301                .as_ref()
302                .map(|scope| (deferred.group, scope.clone())),
303            _ => None,
304        }
305    }
306
307    // Leaves a group that forced the groups below it to run their bodies.
308    pub(super) fn leave_forced_content(&self) {
309        let depth = &self.core.reused_depth;
310        depth.set(depth.get().saturating_sub(1));
311    }
312
313    pub(crate) fn pop_closed_scope(&self) {
314        if self.scope_stack().pop().is_none() {
315            log::error!("scope stack underflow while closing a group");
316        }
317    }
318}