Skip to main content

cranpose_ui/
lib.rs

1//! High level UI primitives built on top of the Compose core runtime.
2
3#![deny(unsafe_code)]
4
5use cranpose_core::{location_key, ApplierGuard, MemoryApplier, NodeError, NodeId, RuntimeHandle};
6pub use cranpose_core::{Composition, Key};
7pub use cranpose_macros::composable;
8use std::ops::{Deref, DerefMut};
9use std::rc::Rc;
10
11mod cursor_animation;
12mod debug;
13mod draw;
14pub mod fling_animation;
15mod focus_dispatch;
16mod interaction;
17mod key_event;
18pub mod layout;
19mod modifier;
20mod modifier_nodes;
21mod pointer_dispatch;
22mod primitives;
23mod render_state;
24mod renderer;
25pub mod scroll;
26mod subcompose_layout;
27pub mod text;
28pub mod text_field_focus;
29mod text_field_handler;
30mod text_field_input;
31mod text_field_modifier_node;
32pub mod text_layout_result;
33mod text_modifier_node;
34pub mod widgets;
35mod word_boundaries;
36
37// Export for cursor blink animation - AppShell checks this to continuously redraw
38pub use text_field_focus::has_focused_field;
39// Export cursor blink timing for WaitUntil scheduling
40pub use cursor_animation::{
41    is_cursor_visible, next_cursor_blink_time, reset_cursor_blink, start_cursor_blink,
42    stop_cursor_blink, tick_cursor_blink,
43};
44
45pub use cranpose_ui_graphics::{BlurredEdgeTreatment, ColorFilter, Dp, ImageBitmap, ImageSampling};
46pub use cranpose_ui_layout::IntrinsicSize;
47pub use draw::{execute_draw_commands, DrawCacheBuilder, DrawCommand};
48pub use focus_dispatch::{
49    active_focus_target, clear_focus_invalidations, has_pending_focus_invalidations,
50    process_focus_invalidations, schedule_focus_invalidation, set_active_focus_target,
51};
52pub use interaction::{
53    rememberMutableInteractionSource, Interaction, MutableInteractionSource, PressInteraction,
54    PressInteractionCancel, PressInteractionPress, PressInteractionRelease,
55};
56// Re-export FocusManager from cranpose-foundation to avoid duplication
57pub use cranpose_foundation::nodes::input::focus::FocusManager;
58pub use cranpose_foundation::{
59    DelegatableNode, ModifierNode, ModifierNodeElement, NodeCapabilities, NodeState,
60};
61pub use layout::{
62    build_layout_tree_from_applier, build_semantics_tree_from_applier,
63    build_semantics_tree_from_layout_tree,
64    core::{
65        Alignment, Arrangement, HorizontalAlignment, LinearArrangement, Measurable, Placeable,
66        VerticalAlignment,
67    },
68    measure_layout, measure_layout_with_options, tree_needs_layout, tree_needs_semantics,
69    LayoutAllocationDebugStats, LayoutBox, LayoutEngine, LayoutMeasurements, LayoutNodeData,
70    LayoutNodeKind, LayoutTree, MeasureLayoutOptions, SemanticsAction, SemanticsCallback,
71    SemanticsNode, SemanticsRole, SemanticsTree,
72};
73pub use modifier::{
74    collect_modifier_slices, collect_semantics_from_modifier, collect_slices_from_modifier,
75    BlendMode, Brush, Color, CompositingStrategy, CornerRadii, DpOffset, EdgeInsets,
76    FocusDirection, FocusRequester, GlassMaterial, GraphicsLayer, LayerShape, Modifier,
77    ModifierNodeSlices, ModifierNodeSlicesDebugStats, Point, PointerEvent, PointerEventKind,
78    PointerInputScope, Rect, RenderEffect, ResolvedBackground, ResolvedModifiers,
79    RoundedCornerShape, RuntimeShader, Shadow, ShadowScope, Size, TransformOrigin,
80};
81pub use modifier_nodes::{
82    AlphaElement, AlphaNode, BackgroundElement, BackgroundNode, ClickableElement, ClickableNode,
83    CornerShapeElement, CornerShapeNode, FillDirection, FillElement, FillNode, OffsetElement,
84    OffsetNode, PaddingElement, PaddingNode, SizeElement, SizeNode,
85};
86pub use pointer_dispatch::{
87    clear_pointer_repasses, has_pending_pointer_repasses, process_pointer_repasses,
88    schedule_pointer_repass,
89};
90pub use primitives::{
91    remember_svg, BasicText, BasicTextField, BasicTextFieldOptions, BasicTextWithOptions,
92    BitmapPainter, Box, BoxScope, BoxSpec, BoxWithConstraints, BoxWithConstraintsScope,
93    BoxWithConstraintsScopeImpl, Button, ButtonSpec, Canvas, Column, ColumnSpec, ContentScale,
94    ForEach, Image, Layout, LayoutNode, Painter, Row, RowSpec, Spacer, SubcomposeLayout,
95    SvgPainter, SvgPainterError, Text, TextWithOptions, DEFAULT_ALPHA,
96};
97// Lazy list exports - single source from cranpose-foundation
98pub use cranpose_foundation::lazy::{LazyListItemInfo, LazyListLayoutInfo, LazyListState};
99pub use key_event::{KeyCode, KeyEvent, KeyEventType, Modifiers};
100#[cfg(any(test, feature = "test-helpers"))]
101#[doc(hidden)]
102pub use render_state::reset_render_state_for_tests;
103pub use render_state::{
104    current_density, debug_last_fling_velocity, debug_reset_last_fling_velocity,
105    has_current_app_context, has_pending_draw_repasses, has_pending_layout_repasses,
106    peek_focus_invalidation, peek_layout_invalidation, peek_pointer_invalidation,
107    peek_render_invalidation, request_focus_invalidation, request_layout_invalidation,
108    request_pointer_invalidation, request_render_invalidation, schedule_draw_repass,
109    schedule_layout_repass, set_density, take_draw_repass_nodes, take_focus_invalidation,
110    take_layout_invalidation, take_layout_repass_nodes, take_pointer_invalidation,
111    take_render_invalidation, AppContext, AppContextScope,
112};
113pub use renderer::{HeadlessRenderer, PaintLayer, RecordedRenderScene, RenderOp};
114pub use scroll::{ScrollElement, ScrollNode, ScrollState};
115// Test utilities for fling velocity verification (only with test-helpers feature)
116#[cfg(feature = "test-helpers")]
117pub use modifier::{last_fling_velocity, reset_last_fling_velocity};
118pub use subcompose_layout::{
119    Constraints, MeasureResult, Placement, SubcomposeLayoutNode, SubcomposeLayoutScope,
120    SubcomposeMeasureScope, SubcomposeMeasureScopeImpl,
121};
122pub use text::{
123    get_cursor_x_for_offset, get_offset_for_position, layout_text, measure_text,
124    measure_text_for_node, measure_text_with_options, measure_text_with_options_for_node,
125    prepare_text_layout, prepare_text_layout_for_node, set_text_measurer, LinkAnnotation,
126    ParagraphStyle, PlatformParagraphStyle, PlatformSpanStyle, PlatformTextStyle,
127    PreparedTextLayout, SpanStyle, StringAnnotation, TextDrawStyle, TextLayoutOptions,
128    TextLayoutResult, TextMeasurer, TextMetrics, TextOptions, TextOverflow, TextShaping, TextStyle,
129};
130pub use text_field_modifier_node::{TextFieldElement, TextFieldModifierNode};
131pub use text_modifier_node::{TextModifierElement, TextModifierNode};
132pub use widgets::clickable_text::ClickableText;
133pub use widgets::lazy_list::{LazyColumn, LazyColumnSpec, LazyRow, LazyRowSpec};
134pub use widgets::linked_text::LinkedText;
135
136// Debug utilities
137pub use debug::{
138    format_layout_tree, format_modifier_chain, format_render_scene, format_screen_summary,
139    install_modifier_chain_trace, log_layout_tree, log_modifier_chain, log_render_scene,
140    log_screen_summary, ModifierChainTraceGuard,
141};
142
143/// In-memory composition helper used by tests.
144pub struct TestComposition {
145    _scope: render_state::AppContextScope,
146    app_context: Rc<AppContext>,
147    composition: Composition<MemoryApplier>,
148}
149
150impl TestComposition {
151    pub fn root(&self) -> Option<NodeId> {
152        self.app_context.enter(|| self.composition.root())
153    }
154
155    pub fn runtime_handle(&self) -> RuntimeHandle {
156        self.app_context.enter(|| self.composition.runtime_handle())
157    }
158
159    pub fn should_render(&self) -> bool {
160        self.app_context.enter(|| self.composition.should_render())
161    }
162
163    pub fn take_root_render_request(&mut self) -> bool {
164        let app_context = Rc::clone(&self.app_context);
165        app_context.enter(|| self.composition.take_root_render_request())
166    }
167
168    pub fn flush_pending_node_updates(&mut self) -> Result<(), NodeError> {
169        let app_context = Rc::clone(&self.app_context);
170        app_context.enter(|| self.composition.flush_pending_node_updates())
171    }
172
173    pub fn process_invalid_scopes(&mut self) -> Result<bool, NodeError> {
174        let app_context = Rc::clone(&self.app_context);
175        app_context.enter(|| self.composition.process_invalid_scopes())
176    }
177
178    pub fn render(&mut self, root_key: Key, content: impl FnMut()) -> Result<(), NodeError> {
179        let app_context = Rc::clone(&self.app_context);
180        app_context.enter(|| self.composition.render(root_key, content))
181    }
182
183    pub fn applier_mut(&mut self) -> TestApplierGuard<'_> {
184        let scope = self.app_context.enter_scope();
185        let applier = self.composition.applier_mut();
186        TestApplierGuard {
187            _scope: scope,
188            applier,
189        }
190    }
191
192    pub fn with_app_context<R>(&self, block: impl FnOnce() -> R) -> R {
193        self.app_context.enter(block)
194    }
195}
196
197pub struct TestApplierGuard<'a> {
198    _scope: render_state::AppContextScope,
199    applier: ApplierGuard<'a, MemoryApplier>,
200}
201
202impl Deref for TestApplierGuard<'_> {
203    type Target = MemoryApplier;
204
205    fn deref(&self) -> &Self::Target {
206        &self.applier
207    }
208}
209
210impl DerefMut for TestApplierGuard<'_> {
211    fn deref_mut(&mut self) -> &mut Self::Target {
212        &mut self.applier
213    }
214}
215
216/// Build a composition with a simple in-memory applier and run the provided closure once.
217pub fn run_test_composition(build: impl FnMut()) -> TestComposition {
218    let app_context = AppContext::new();
219    app_context.enter(|| {
220        #[cfg(test)]
221        reset_render_state_for_tests();
222    });
223    let mut test_composition = TestComposition {
224        _scope: app_context.enter_scope(),
225        app_context,
226        composition: Composition::new(MemoryApplier::new()),
227    };
228    test_composition
229        .render(location_key(file!(), line!(), column!()), build)
230        .expect("initial render succeeds");
231    test_composition
232}
233
234pub use cranpose_core::MutableState as SnapshotState;
235
236#[cfg(test)]
237#[path = "tests/anchor_async_tests.rs"]
238mod anchor_async_tests;
239
240#[cfg(test)]
241#[path = "tests/async_runtime_full_layout_test.rs"]
242mod async_runtime_full_layout_test;
243
244#[cfg(test)]
245#[path = "tests/cursor_position_tests.rs"]
246mod cursor_position_tests;
247
248#[cfg(test)]
249#[path = "tests/tab_switching_tests.rs"]
250mod tab_switching_tests;
251
252#[cfg(test)]
253#[path = "tests/lazy_list_viewport_tests.rs"]
254mod lazy_list_viewport_tests;
255
256#[cfg(test)]
257#[path = "tests/lazy_list_recompose_tests.rs"]
258mod lazy_list_recompose_tests;