Skip to main content

cranpose_core/
lib.rs

1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3#![deny(unsafe_code)]
4
5pub extern crate self as cranpose_core;
6
7mod applier;
8mod applier_host;
9pub use applier::Applier;
10mod blocking;
11mod bubble_passes;
12mod callbacks;
13mod child_positions;
14mod child_sync;
15pub(crate) use child_positions::{
16    build_child_positions, insert_child_into_diff_state, move_child_in_diff_state,
17};
18pub(crate) use child_sync::{
19    apply_remove_child, attach_child_at, cleanup_detached_child, detach_child_from_parent,
20    insert_child_with_reparenting, join_made_children, remove_child_and_cleanup_now,
21    sync_or_settle_children,
22};
23mod command;
24pub(crate) use command::{
25    Command, CommandCallback, DeferredChildCleanup, DeferredChildCleanupQueue, DirtyBubble,
26};
27mod command_queue;
28pub(crate) use command_queue::{
29    CHILD_LIST_INLINE, COMMAND_FLUSH_THRESHOLD, ChildList, CommandQueue,
30    SMALL_CHILD_SYNC_LINEAR_THRESHOLD,
31};
32#[cfg(test)]
33pub(crate) use command_queue::{CommandTag, SyncChildrenCommand};
34mod composer;
35/// The composer that is current on this thread, which composable code reaches without passing it as
36/// a parameter.
37pub mod composer_context;
38pub(crate) use composer_context::with_current_composer_opt;
39pub use composer_context::{
40    current_recompose_scope_invalidated_only_by, recompose_current_scope_again, withCurrentComposer,
41};
42mod composition;
43mod composition_locals;
44pub(crate) use composition_locals::{LocalKey, LocalStackSnapshot};
45mod computed_state;
46pub mod concurrency;
47mod debug_trace;
48mod disposable_effect;
49pub use diagnostics::{DIAGNOSTICS, Diagnostic, Diagnostics};
50#[cfg(test)]
51pub(crate) use disposable_effect::DisposableEffectState;
52pub use disposable_effect::{
53    __disposable_effect_impl, DisposableEffect, DisposableEffectResult, DisposableEffectScope,
54    SideEffect,
55};
56mod effect_key;
57mod emit;
58mod event_dispatch;
59pub use event_dispatch::{
60    EventHandlerScopeGuard, dispatch_ui_event, enter_event_handler_scope, in_applied_snapshot,
61    in_event_handler, run_in_mutable_snapshot,
62};
63pub mod debug_toggles;
64pub mod diagnostics;
65#[cfg(any(feature = "internal", test))]
66mod frame_clock;
67mod hooks;
68#[cfg(feature = "internal")]
69mod node_reads;
70pub(crate) use key_group::{explicit_group_key_seed, hash_key};
71mod key_group;
72pub use key_group::{key, with_key};
73mod launched_effect;
74mod layout_dirt_roots;
75mod location_key;
76mod memory_applier;
77mod worker_job;
78#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
79mod worker_pool;
80pub use memory_applier::{MemoryApplier, MemoryApplierDebugStats, SceneNodeAttachmentScratch};
81mod movable_content;
82mod node;
83#[cfg(any(test, debug_assertions))]
84pub(crate) use location_key::LocationKeyDebugInfo;
85pub(crate) use location_key::{HotOrigin, avalanche_location_key};
86#[cfg(test)]
87pub(crate) use location_key::{
88    hot_call_site_key, location_key_debug_collision_count_for_test,
89    location_key_debug_info_for_test, register_location_key_debug_info_for_test,
90};
91pub use movable_content::{
92    MovableContent, forget_movable, movable, movableContentOf, rememberMovableContentOf,
93};
94pub use node::{
95    Node, bubble_layout_dirty, bubble_layout_dirty_in_composer, bubble_measure_dirty,
96    bubble_measure_dirty_in_composer, bubble_semantics_dirty, bubble_semantics_dirty_in_composer,
97    pop_parent, push_parent, queue_semantics_invalidation, with_node_mut,
98};
99mod node_error;
100mod node_id_cell;
101pub use node_id_cell::NodeIdCell;
102mod packed_node_id;
103pub use packed_node_id::PackedNodeId;
104mod node_marks;
105mod phase;
106pub use phase::Phase;
107mod anchor_id;
108pub use anchor_id::AnchorId;
109mod packed_u64;
110pub use node_error::NodeError;
111pub use packed_u64::PackedU64;
112mod process_ids;
113pub use process_ids::ProcessIds;
114/// `Owned`, the handle to a value that a composition remembers.
115pub mod owned;
116mod pausable;
117#[doc(hidden)]
118pub use pausable::{PausableContent, with_pausable_content};
119pub mod platform;
120mod recompose;
121mod recompose_scope;
122pub(crate) use recompose_scope::{BodyRun, RecomposeScopeInner, ScopeRead};
123pub use recompose_scope::{RecomposeOptions, RecomposeScope, RecomposeScopeRegistryDebugStats};
124mod recycle_pool;
125mod recycled_node;
126use recycle_pool::RecyclePool;
127pub use recycled_node::{RecyclableShell, RecycleOrigin, RecycledNode, RecycledNodeInsertion};
128mod retention;
129/// The runtime in which a composition runs: state cells, UI tasks, frame callbacks and the queue of
130/// invalidated scopes.
131pub mod runtime;
132mod runtime_cell;
133#[cfg(test)]
134pub(crate) use runtime::{TestRuntime, TestScheduler};
135mod scene_records;
136pub use scene_records::{RecordId, RecordRef, SceneUpdate, StoreId};
137mod scope_order;
138#[expect(clippy::multiple_inherent_impl, reason = "one file per concern")]
139mod slot;
140mod slots_host;
141pub(crate) use slots_host::SlotPassOutcome;
142pub use slots_host::SlotsHost;
143/// A min-heap of snapshot ids that supports removal by handle.
144pub mod snapshot_double_index_heap;
145/// A compact set of snapshot ids.
146pub mod snapshot_id_set;
147/// Tracks the pinned snapshots, which bound the state records that may be reclaimed.
148pub mod snapshot_pinning;
149/// Records which state objects a scope reads and calls back when one of them changes.
150pub mod snapshot_state_observer;
151pub mod snapshot_v2;
152mod snapshot_weak_set;
153pub mod source_trace;
154mod stable_index;
155mod state;
156#[doc(hidden)]
157pub use source_trace::{__inline_source_scope, __source_scope};
158#[doc(hidden)]
159pub use thread_state::with_or_fresh;
160mod stage_times;
161pub mod subcompose;
162mod task_site;
163pub use task_site::TaskSite;
164mod thread_state;
165#[doc(hidden)]
166pub use stage_times::{StageTimes, stage_ms};
167
168#[cfg(feature = "internal")]
169#[doc(hidden)]
170pub mod internal {
171    pub use crate::{
172        frame_clock::{FrameCallbackRegistration, FrameClock},
173        node_reads::{NodeReads, ReaderGuard},
174    };
175}
176pub use applier_host::{ApplierGuard, ApplierHost, ConcreteApplierHost, NodeDisposal};
177pub use blocking::{
178    BlockingError, BlockingExecutor, BlockingExecutorConfig, BlockingTask, BlockingWork,
179    launchBlocking, withBlocking,
180};
181pub use callbacks::{
182    CallbackForwarder, CallbackHolder, ParamReturnState, ParamSlot, ParamState, ReturnSlot,
183    SharedParam, refresh_param, refresh_shared_param, store_param,
184};
185pub use composer::{
186    __branch_group_scope_advance, __branch_group_scope_deferred, BranchGroupGuard,
187    CapturedCompositionContext, ComposableGroup, Composer, ParameterChange, ScopedBranchGroupGuard,
188    ValueSlotHandle,
189};
190pub(crate) use composer::{ComposerCore, EmittedNode, ParentAttachMode, ParentFrame};
191#[cfg(any(test, feature = "leak-debug"))]
192pub use composition::CompositionPassDebugStats;
193pub use composition::{Composition, LayoutBudget, ROOT_RENDER_REPLAY_LIMIT};
194pub use composition_locals::{
195    CompositionLocal, CompositionLocalAccessorScope, CompositionLocalProvider, ProvidedValue,
196    ReadableCompositionLocal, StaticCompositionLocal, compositionLocalOf,
197    compositionLocalOfWithPolicy, compositionLocalWithComputedDefaultOf, staticCompositionLocalOf,
198    staticCompositionLocalOfWithPolicy, staticCompositionLocalWithComputedDefaultOf,
199};
200pub(crate) use composition_locals::{ComputedLocalEntry, LocalStateEntry};
201#[doc(hidden)]
202pub use computed_state::{ComputedState, computedStateOf};
203pub use concurrency::{
204    CollectEvents, CoroutineScope, Delay, EventChannel, EventSender, EventStream, EventStreamNext,
205    ProduceScope, collectAsState, delay, interval, produceState, rememberCoroutineScope,
206    rememberEventStream, spawn_ui_task,
207};
208#[doc(hidden)]
209pub use debug_trace::{
210    debug_label_current_scope, debug_live_recompose_scope_count,
211    debug_recompose_scope_registry_stats, debug_scope_invalidation_sources, debug_scope_label,
212};
213pub use hooks::{
214    derivedStateOf, mutableStateList, mutableStateListOf, mutableStateMap, mutableStateMapOf,
215    mutableStateOf, mutableStateOfNeverEqual, ownedMutableStateOf, ownedMutableStateOfNeverEqual,
216    remember, rememberKeyed, rememberMutableStateOf, rememberMutableStateOfNeverEqual,
217    rememberUpdatedState, try_mutableStateOf,
218};
219pub use launched_effect::{
220    __launched_effect_impl, CancelToken, LaunchedEffect, LaunchedEffectScope,
221};
222pub use location_key::{
223    HotOriginGuard, branch_location_key, cached_composable_definition_key, caller_location_key,
224    composable_definition_key, composable_identity_key, const_location_key, constant_value_key,
225    hot_branch_key, hot_definition_key, hot_origin, location_key, noted_location_key,
226};
227pub use node_marks::NodeMarks;
228pub use owned::Owned;
229pub use platform::{Clock, RuntimeScheduler, SchedulerRef, scheduler_ref};
230pub use retention::{RetentionBudget, RetentionEvictionPolicy, RetentionMode, RetentionPolicy};
231#[doc(hidden)]
232pub use runtime::{
233    DefaultScheduler, Runtime, RuntimeHandle, StateId, TaskHandle, UiDispatcher,
234    current_runtime_handle, schedule_frame, schedule_node_update,
235};
236pub use runtime_cell::RuntimeCell;
237#[cfg(any(test, feature = "leak-debug"))]
238pub use slot::SlotTableMutationDebugStats;
239pub use slot::{
240    SlotDebugAnchor, SlotDebugEntry, SlotDebugEntryKind, SlotDebugGroup, SlotDebugScope,
241    SlotDebugSnapshot, SlotRetentionDebugStats, SlotTable, SlotTableDebugStats,
242    SlotTableLocalDebugStats,
243};
244pub use snapshot_state_observer::SnapshotStateObserver;
245pub use worker_job::{__worker, WorkerCall, WorkerData, WorkerJob};
246
247/// Identifies a composition group: the hash of its call site, or of an explicit key together with
248/// its call site. Kept at a 32-bit word's alignment on ESP-IDF, as a [`PackedU64`] is.
249#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
250#[cfg_attr(target_os = "espidf", repr(C, packed(4)))]
251pub struct Key(pub u64);
252
253impl Key {
254    /// This key scoped to `site`, for a group that both identify: the bitwise xor of the two.
255    pub const fn scoped(self, site: Self) -> Self {
256        Self(self.0 ^ site.0)
257    }
258
259    // One FNV-1a step folding `other` into this key.
260    pub(crate) const fn mixed(self, other: Self) -> Self {
261        Self((self.0 ^ other.0).wrapping_mul(0x0000_0100_0000_01b3))
262    }
263}
264
265impl std::fmt::Display for Key {
266    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267        { self.0 }.fmt(f)
268    }
269}
270/// Identifies a node in an applier.
271#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
272pub struct NodeId(pub usize);
273
274impl NodeId {
275    // The id an applier hands out after this one.
276    pub(crate) const fn next(self) -> Self {
277        Self(self.0.saturating_add(1))
278    }
279}
280
281impl std::str::FromStr for NodeId {
282    type Err = std::num::ParseIntError;
283
284    fn from_str(text: &str) -> Result<Self, Self::Err> {
285        text.parse().map(Self)
286    }
287}
288
289impl std::fmt::Display for NodeId {
290    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291        self.0.fmt(f)
292    }
293}
294
295pub(crate) type ScopeId = usize;
296pub(crate) type FrameCallbackId = u64;
297pub use composer_context::{
298    __current_composer, note_nested_slots_host, try_with_composer,
299    with_composer as with_current_composer,
300};
301pub(crate) use state::MutableStateInner;
302pub use state::{
303    MutableState, OwnedMutableState, SnapshotStateList, SnapshotStateMap, State,
304    StateSubscriptionHold,
305};
306pub use subcompose::{
307    ContentTypeReusePolicy, DefaultSlotReusePolicy, SlotId, SlotReusePolicy, SubcomposeState,
308    TypedSlot,
309};
310
311#[cfg(test)]
312#[path = "tests/mod.rs"]
313mod tests;
314
315#[cfg(test)]
316#[path = "tests/recursive_decrease_increase_test.rs"]
317mod recursive_decrease_increase_test;
318
319pub mod collections;
320/// The hasher type and constructor that the framework uses by default.
321pub mod hash;
322
323/// Where a test writes real files. Behind `test-helpers` so only a test build
324/// of the workspace carries it.
325#[cfg(any(test, feature = "test-helpers"))]
326pub mod test_scratch;
327#[cfg(any(test, feature = "test-helpers"))]
328pub use test_scratch::test_scratch_dir;