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