cranpose-core 0.29.0

Composition runtime and reactive state for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use std::{cell::Cell, hash::Hash, rc::Rc};

use super::{GroupScopeEntry, PendingMovable, SlotHostPassGuard, scope_frame};
use crate::{
    BodyRun, Composer, Key, NodeId, RecomposeOptions, RecomposeScope, RetentionMode, ScopeId,
    SlotsHost, explicit_group_key_seed, retention::RetainKey, slot::GroupStart,
};

/// A group a composable call opened; [`ComposableGroup::close`] ends it
/// after the call's body.
#[doc(hidden)]
pub struct ComposableGroup<'a> {
    composer: &'a Composer,
    host: Rc<SlotsHost>,
    // The group's scope when it opened with one; `None` for a group whose
    // body makes its scope when it first needs one.
    scope: Option<RecomposeScope>,
    pass: Option<SlotHostPassGuard>,
    runs_body: bool,
    // Whether the group composes reused content, under which every group
    // runs its body.
    forces_content: bool,
    completed: bool,
    body: Cell<Body>,
}

/// Whether a composable call's parameters changed since its body last ran,
/// or its scope asks to recompose.
#[doc(hidden)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ParameterChange {
    /// Nothing the body reads as a parameter changed.
    Unchanged,
    /// A parameter changed or the scope asks to recompose.
    Changed,
}

impl From<bool> for ParameterChange {
    fn from(changed: bool) -> Self {
        if changed {
            Self::Changed
        } else {
            Self::Unchanged
        }
    }
}

// What a composable call does with its group's body.
#[derive(Clone, Copy)]
enum Body {
    Runs,
    // What the body composed last stays.
    Skipped,
    // The first body waits for a later frame, in pausable content.
    Paused,
}

impl ComposableGroup<'_> {
    /// Whether the group's body runs whatever its parameters: its scope asks
    /// to recompose, or the content around it runs every body.
    pub fn should_recompose(&self) -> bool {
        match &self.scope {
            Some(scope) => scope.should_recompose(),
            None => self.composer.deferred_scope_forced(),
        }
    }

    /// Registers `body` as the function that recomposes the group's scope,
    /// as [`Composer::set_recompose_fn`] does for the current scope: a plain
    /// function needs no box and no call shim.
    #[inline]
    pub fn set_recompose_fn(&self, body: fn(&Composer)) {
        match &self.scope {
            Some(scope) => scope.set_recompose_fn(body),
            None => self.composer.set_deferred_recompose_fn(body),
        }
    }

    // Whether the group composed before.
    fn has_composed_once(&self) -> bool {
        match &self.scope {
            Some(scope) => scope.has_composed_once(),
            None => self.composer.deferred_scope_composed_once(),
        }
    }

    /// Skips the group's body: what it composed last stays. The call
    /// composes nothing more in the group before closing it.
    pub fn skip(&self) {
        self.body.set(Body::Skipped);
    }

    /// Registers `recompose` as the function that recomposes the group's scope,
    /// as [`Self::set_recompose_fn`] does, and answers whether the call runs
    /// its body: `change` says whether a parameter changed or the scope asks
    /// to recompose. A body that does not run keeps what it composed
    /// last, or, for a group that opened in pausable content past the
    /// frame's budget, waits for a later frame. When the body does not run,
    /// the call composes nothing more in the group before closing it.
    /// Compose's `Composer.shouldExecute`.
    pub fn should_execute(&self, change: ParameterChange, recompose: fn(&Composer)) -> bool {
        self.set_recompose_fn(recompose);
        match self.body.get() {
            Body::Paused => false,
            _ if change == ParameterChange::Unchanged && self.has_composed_once() => {
                self.body.set(Body::Skipped);
                false
            }
            _ => true,
        }
    }

    // Closes a group whose first body waits for a later frame: its scope has
    // not composed once and stays invalid until the body runs.
    #[cold]
    #[inline(never)]
    fn close_paused(&self, scope: &RecomposeScope) {
        scope.end_reads(BodyRun::Skipped);
        self.composer
            .close_group_in_active_pass(&self.host, Some(scope), None);
        self.composer.hold_paused(scope);
    }

    /// Ends the group after its body composed.
    #[inline]
    pub fn close(mut self) {
        self.completed = true;
    }
}

impl Drop for ComposableGroup<'_> {
    fn drop(&mut self) {
        let body = self.body.get();
        match (body, &self.scope) {
            (Body::Paused, Some(scope)) => self.close_paused(scope),
            _ => {
                // The scope the group opened with, or one its body made.
                let made_by_body = self
                    .scope
                    .is_none()
                    .then(|| self.composer.scope_made_by_body())
                    .flatten();
                let scope = self
                    .scope
                    .as_ref()
                    .or_else(|| made_by_body.as_ref().map(|(_, scope)| scope));
                if let Some(scope) = scope {
                    if self.completed {
                        scope.mark_composed_once();
                    }
                    let ran = matches!(body, Body::Runs) & self.completed & self.runs_body;
                    scope.end_reads(BodyRun::from(ran));
                }
                if matches!(body, Body::Skipped) {
                    self.composer
                        .close_skipped_group_in_active_pass(&self.host, scope);
                } else {
                    let store = made_by_body.as_ref().map(|(group, scope)| {
                        scope.set_slots_host(&self.host);
                        (*group, scope)
                    });
                    self.composer
                        .close_group_in_active_pass(&self.host, scope, store);
                }
            }
        }
        if self.forces_content {
            self.composer.leave_forced_content();
        }
        if let Some(pass) = self.pass.take()
            && self.completed
            && let Err(err) = self.composer.finish_slot_host_pass(&pass.host)
        {
            log::error!("slot host pass finalization failed: {err}");
        }
    }
}

enum RetentionParent {
    Root,
    Scope(ScopeId),
    Deferred,
}

#[expect(clippy::multiple_inherent_impl, reason = "one file per concern")]
impl Composer {
    fn scope_for_started_group(
        &self,
        host: &SlotsHost,
        group: crate::slot::ActiveGroupId,
        scope: Option<RecomposeScope>,
    ) -> RecomposeScope {
        if let Some(scope) = scope {
            return scope;
        }
        let scope = RecomposeScope::new(self.runtime_handle());
        host.with_write_session(|slots| slots.set_group_scope(group, scope.clone()));
        if self.core.shared_state.pausing.is_holding() {
            self.hold_scope(&scope);
        }
        scope
    }

    fn retention_parent(&self) -> RetentionParent {
        match self.core.scope_stack.borrow().last() {
            None => RetentionParent::Root,
            Some(frame) => match frame.scope() {
                Some(scope) => RetentionParent::Scope(scope.id()),
                None => RetentionParent::Deferred,
            },
        }
    }

    fn begin_fresh_group(
        host: &Rc<SlotsHost>,
        seed: crate::slot::GroupKeySeed,
        parent_node: Option<NodeId>,
    ) -> GroupStart<crate::slot::ActiveGroupId> {
        host.with_write_session(|slots| {
            let key = slots.reserve_group_key(seed);
            slots.begin_group(key, None, parent_node)
        })
    }

    fn start_group(
        &self,
        host: &Rc<SlotsHost>,
        seed: crate::slot::GroupKeySeed,
        parent_node: Option<NodeId>,
    ) -> GroupStart<crate::slot::ActiveGroupId> {
        if !self.core.shared_state.retains_any() {
            return Self::begin_fresh_group(host, seed, parent_node);
        }
        let parent_scope_id = match self.retention_parent() {
            RetentionParent::Root => None,
            RetentionParent::Scope(id) => Some(id),
            // A deferred parent has never held a scope id, so no retained
            // group can be keyed under it.
            RetentionParent::Deferred => return Self::begin_fresh_group(host, seed, parent_node),
        };
        let key = host.with_write_session(|slots| slots.reserve_group_key(seed));
        let retain_key = RetainKey::for_group(parent_scope_id, key);
        let restored = self
            .core
            .shared_state
            .take_retained(host, retain_key, key)
            .map(Box::new);
        host.with_write_session(|slots| slots.begin_group(key, restored, parent_node))
    }

    fn start_movable_group(
        &self,
        host: &Rc<SlotsHost>,
        id: Key,
        parent_node: Option<NodeId>,
        lookup: super::MovableLookup,
    ) -> (
        GroupStart<crate::slot::ActiveGroupId>,
        Option<crate::slot::GroupKey>,
    ) {
        let seed = crate::slot::GroupKeySeed::movable(id);
        if lookup == super::MovableLookup::FreshUnshown {
            return (Self::begin_fresh_group(host, seed, parent_node), None);
        }
        let key = host.with_write_session(|slots| slots.reserve_group_key(seed));
        let super::GroupEntry {
            key,
            restored,
            placeholder_for,
        } = self.resolve_movable_group_entry(host, key, lookup);
        let started =
            host.with_write_session(|slots| slots.begin_group(key, restored, parent_node));
        (started, placeholder_for)
    }

    // Opens a group; returns its scope, `None` for one whose body makes it
    // when it first needs one, and whether it forces the groups below it to
    // run theirs.
    #[inline(never)]
    fn open_group_in_active_pass(
        &self,
        host: &Rc<SlotsHost>,
        key: crate::slot::GroupKeySeed,
    ) -> (Option<RecomposeScope>, bool) {
        let options = self.core.pending_scope_options.take().unwrap_or_default();
        let parent_node = self.current_parent_hint();
        let GroupStart {
            group,
            anchor,
            scope,
            kind,
        } = self.start_group(host, key, parent_node);
        if scope.is_none()
            && !key.exact
            && scope_frame::may_defer(options, kind)
            && self.defers_scopes_here()
        {
            self.push_deferred_scope((group, anchor), kind, parent_node);
            return (None, false);
        }
        let scope_ref = self.scope_for_started_group(host, group, scope);
        let forces_content = self.enter_group_scope(
            &scope_ref,
            &GroupScopeEntry {
                options,
                start_kind: kind,
                host,
                group,
                parent_hint: parent_node,
            },
        );
        (Some(scope_ref), forces_content)
    }

    #[inline(never)]
    fn open_movable_group_in_active_pass(
        &self,
        host: &Rc<SlotsHost>,
        id: Key,
        lookup: super::MovableLookup,
    ) -> (Option<RecomposeScope>, bool, bool) {
        let options = self.core.pending_scope_options.take().unwrap_or_default();
        let parent_node = self.current_parent_hint();
        let (
            GroupStart {
                group,
                anchor,
                scope,
                kind,
            },
            placeholder_for,
        ) = self.start_movable_group(host, id, parent_node, lookup);
        let scope_ref = self.scope_for_started_group(host, group, scope);
        if let Some(movable_key) = placeholder_for {
            let parent_scope = {
                let mut stack = self.scope_stack();
                let top = stack.len().checked_sub(1);
                top.map(|top| self.frame_scope(&mut stack, top).downgrade())
            };
            self.core.shared_state.record_pending_movable(
                host,
                PendingMovable {
                    key: movable_key,
                    placeholder: anchor,
                    parent_scope,
                    woken: false,
                },
            );
        }
        let forces_content = self.enter_group_scope(
            &scope_ref,
            &GroupScopeEntry {
                options,
                start_kind: kind,
                host,
                group,
                parent_hint: parent_node,
            },
        );
        (Some(scope_ref), placeholder_for.is_none(), forces_content)
    }

    // Closes a group whose body ran: `store` is the scope its body made,
    // which goes into the group's record.
    #[inline(never)]
    fn close_group_in_active_pass(
        &self,
        host: &Rc<SlotsHost>,
        scope: Option<&RecomposeScope>,
        store: Option<(crate::slot::ActiveGroupId, &RecomposeScope)>,
    ) {
        let result = host.with_write_session(|slots| {
            let result = slots.finish_group_body_changes();
            if let Some((group, made)) = store {
                slots.set_group_scope(group, made.clone());
            }
            slots.end_group();
            result
        });
        self.close_finished_group(host, scope, result);
        self.settle_closed_group(scope);
    }

    // Closes a group whose body was skipped, in one slot session: its root
    // nodes stay attached where they were.
    #[inline(never)]
    fn close_skipped_group_in_active_pass(
        &self,
        host: &Rc<SlotsHost>,
        scope: Option<&RecomposeScope>,
    ) {
        // Attaching a node reaches the parent stack and the applier, never
        // the slot table the session holds.
        host.with_write_session(|slots| slots.skip_and_end_group(|id| self.attach_to_parent(id)));
        self.pop_closed_scope();
        self.settle_closed_group(scope);
    }

    fn settle_closed_group(&self, scope: Option<&RecomposeScope>) {
        if let Some(scope) = scope {
            scope.mark_recomposed();
        }
        if let Err(err) = self.flush_pending_commands_if_large() {
            log::error!("mid-composition command flush failed: {err}");
        }
    }

    #[inline]
    fn acquire_pass_host(&self) -> (Rc<SlotsHost>, Option<SlotHostPassGuard>) {
        let host = self.active_slots_host();
        if host.has_active_pass() {
            (host, None)
        } else {
            let pass = self.begin_slot_host_pass(&host, crate::slot::SlotPassMode::Compose);
            (self.active_slots_host(), Some(pass))
        }
    }

    #[inline]
    fn finish_open_group(
        &self,
        host: Rc<SlotsHost>,
        pass: Option<SlotHostPassGuard>,
        scope: Option<RecomposeScope>,
        runs_body: bool,
        forces_content: bool,
    ) -> ComposableGroup<'_> {
        if let Some(scope) = &scope {
            scope.begin_reads();
        }
        ComposableGroup {
            composer: self,
            host,
            scope,
            pass,
            runs_body,
            forces_content,
            completed: false,
            body: Cell::new(Body::Runs),
        }
    }

    #[inline(never)]
    fn open_group(&self, key: crate::slot::GroupKeySeed) -> ComposableGroup<'_> {
        let (host, pass) = self.acquire_pass_host();
        let (scope, forces_content) = self.open_group_in_active_pass(&host, key);
        self.finish_open_group(host, pass, scope, true, forces_content)
    }

    fn open_movable_group(&self, id: Key, lookup: super::MovableLookup) -> ComposableGroup<'_> {
        super::movable::enable_movable_hooks();
        let (host, pass) = self.acquire_pass_host();
        let (scope, runs_body, forces_content) =
            self.open_movable_group_in_active_pass(&host, id, lookup);
        self.finish_open_group(host, pass, scope, runs_body, forces_content)
    }

    #[doc(hidden)]
    pub fn __open_composable_group(&self, key: Key) -> ComposableGroup<'_> {
        // A composable that returns a value invalidates its caller's scope
        // when a recomposition of its own returns another one.
        self.current_recompose_scope();
        self.open_group(crate::slot::GroupKeySeed::unkeyed(key))
    }

    // Opens the group of a composable that returns nothing: in pausable
    // content past the frame's budget, its first body waits.
    #[doc(hidden)]
    pub fn __open_pausable_group(&self, key: Key) -> ComposableGroup<'_> {
        let group = self.open_group(crate::slot::GroupKeySeed::unkeyed(key));
        if self.core.shared_state.pausing.is_holding()
            && let Some(scope) = &group.scope
            && self.pauses_first_body(scope)
        {
            group.body.set(Body::Paused);
        }
        group
    }

    pub(crate) fn with_group_seed<R>(
        &self,
        key: crate::slot::GroupKeySeed,
        f: impl FnOnce(&Self) -> R,
    ) -> R {
        let group = self.open_group(key);
        debug_assert!(group.runs_body, "only movable content waits for a body");
        let result = f(self);
        group.close();
        result
    }

    pub(crate) fn with_movable_group(
        &self,
        id: Key,
        lookup: super::MovableLookup,
        f: impl FnOnce(&Self),
    ) {
        let group = self.open_movable_group(id, lookup);
        if group.runs_body {
            f(self);
        }
        group.close();
    }

    /// Runs `f` in a group identified by `key`. Slots and nodes that `f` creates belong to the
    /// group.
    pub fn with_group<R>(&self, key: Key, f: impl FnOnce(&Self) -> R) -> R {
        self.with_group_seed(crate::slot::GroupKeySeed::unkeyed(key), f)
    }

    /// Runs `f` in a group identified by `key` that is retained when it leaves the composition,
    /// with the recompose `options` applied to its scope. A retained group returns with its state
    /// and nodes when `key` is composed again.
    pub fn cranpose_with_reuse<R>(
        &self,
        key: Key,
        mut options: RecomposeOptions,
        f: impl FnOnce(&Self) -> R,
    ) -> R {
        options.retention = RetentionMode::RetainWhenInactive;
        self.core.pending_scope_options.set(Some(options));
        self.with_group(key, f)
    }

    /// Runs `f` in a group identified by the hash of `key`, so state and nodes follow the key when
    /// siblings move. Compose's `key`.
    #[track_caller]
    pub fn with_key<K: Hash, R>(&self, key: &K, f: impl FnOnce(&Self) -> R) -> R {
        let seed = explicit_group_key_seed(key, std::panic::Location::caller());
        self.with_group_seed(seed, f)
    }
}