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