Skip to main content

repose_ui/
lib.rs

1#![allow(non_snake_case)]
2//! # Views, Modifiers, and Layout
3//!
4//! Repose UI is built around three core ideas:
5//!
6//! - `View`: an immutable description of a UI node (cheap to rebuild every frame).
7//! - `Modifier`: layout, styling, and interaction hints attached to a `View`.
8//! - Incremental layout + paint via a persistent engine:
9//!   composition produces a new `View` tree each frame; `LayoutEngine`
10//!   reconciles it into a persistent `ViewTree` (`repose-tree`) and runs
11//!   incremental Taffy layout + paint (with scopes, dirty sets, and paint caches).
12//!
13//! ## Views
14//!
15//! A `View` is a lightweight value that describes *what* to show, not *how* it is
16//! rendered. It is cheap to create; you rebuild the description each frame
17//! (Compose-style). Identity and layout state live in the persistent tree, not
18//! in the `View` values themselves.
19//!
20//! ```rust,ignore
21//! use repose_core::*;
22//! use repose_ui::*;
23//!
24//! fn Counter(count: i32, on_inc: impl Fn() + 'static) -> View {
25//!     Column(Modifier::new().padding(16.0)).child((
26//!         Text(format!("Count = {count}")),
27//!         Button("Increment".into_children(), on_inc),
28//!     ))
29//! }
30//! ```
31//!
32//! Internally, a `View` has:
33//!
34//! - `id: ViewId` - assigned during composition / layout.
35//! - `kind: ViewKind` - which widget it is (Text, Button, etc.).
36//! - `modifier: Modifier` - layout/styling/interaction metadata.
37//! - `children: Vec<View>` - owned child views.
38//!
39//! Views are *pure data*: they do not hold state or platform handles.
40//! State lives in signals / `remember_*`; platform integration is in
41//! `repose-platform` / `repose-app`.
42//!
43//! ## Modifiers
44//!
45//! `Modifier` describes *how* a view participates in layout and hit-testing:
46//!
47//! - Size: `size`, `width`, `height`, `min_*`, `max_*`, `fill_max_*`
48//! - Box model: `padding`, `padding_values`, margins
49//! - Visuals: `background`, `border`, `clip_rounded`, `alpha`, `transform`, layers
50//! - Flex / grid: `flex_*`, `align_*`, `justify_*`, `grid`, `grid_span`
51//! - Positioning: `absolute()`, `offset(..)`
52//! - Scroll: `vertical_scroll` / `horizontal_scroll` / `scrollable`, `nested_scroll_connection`
53//! - Interaction: `clickable()`, pointer callbacks, `semantics`
54//! - Custom paint: `painter` (used by `repose-canvas`)
55//! - Incremental helpers: `key`, `repaint_boundary`, `scope!` (core)
56//!
57//! Modifiers are mapped to Taffy `Style` inside `LayoutEngine`. Values are in
58//! density-independent pixels (dp) and converted to physical px via `Density`.
59//!
60//! ## Layout + paint
61//!
62//! Public entry:
63//!
64//! ```rust,ignore
65//! pub fn layout_and_paint(
66//!     root: &View,
67//!     size_px: (u32, u32),
68//!     textfield_states: &HashMap<u64, Rc<RefCell<TextFieldState>>>,
69//!     interactions: &Interactions,
70//!     focused: Option<u64>,
71//! ) -> (Scene, Vec<HitRegion>, Vec<SemNode>);
72//! ```
73//!
74//! This is a thin thread-local wrapper around `LayoutEngine::layout_frame`, which:
75//!
76//! 1. Reconciles `root` into the persistent `ViewTree` (stable `NodeId`s, content +
77//!    subtree hashes, dirty set, generation GC).
78//! 2. Syncs dual Taffy trees (root + per-`scope!` `ScopeLayoutTree`s).
79//! 3. Computes layout (measure callbacks, constraint equality skip for scopes).
80//! 4. Walks the tree to emit `SceneNode`s, `HitRegion`s, and `SemNode`s, with
81//!    paint-cache hits on `repaint_boundary` / scopes, culling, nested scroll, etc.
82//!
83//! Prefer `scope!`, stable keys, and `repaint_boundary` on expensive subtrees so
84//! the incremental engine can skip work.
85
86pub mod adaptive;
87pub mod anim;
88pub mod anim_ext;
89pub mod color_picker;
90pub mod gestures;
91pub mod layout;
92pub use layout::IntrinsicSizeMode;
93pub mod lazy;
94pub mod selection;
95pub mod subcompose;
96pub use lazy::{
97    LazyColumn, LazyHorizontalGrid, LazyRow, LazyVerticalGrid, LazyVerticalStaggeredGrid,
98    SimpleList,
99};
100pub mod lazy_states;
101pub use lazy_states::{
102    ItemHeight, LazyColumnConfig, LazyColumnState, LazyGridConfig, LazyGridState, LazyRowConfig,
103    LazyRowState, LazyVerticalStaggeredGridConfig, LazyVerticalStaggeredGridState,
104};
105pub use subcompose::{
106    BoxWithConstraints, SubcomposeLayout, box_with_constraints_with_key, subcompose_hash_key,
107    subcompose_layout_with_slots, subcompose_with_key, subcompose_with_key_slots,
108};
109pub mod overlay;
110pub mod pager;
111pub mod scroll;
112pub mod windowing;
113
114use std::cell::RefCell;
115use std::collections::{HashMap, HashSet};
116use std::rc::Rc;
117use std::sync::atomic::{AtomicU64, Ordering};
118
119use repose_core::*;
120
121pub mod textfield;
122use repose_core::locals;
123pub use selection::{SelectableText, SelectableTextExt};
124pub use textfield::{
125    BasicSecureTextField, BasicTextField, KeyboardOptions, TextFieldConfig, TextFieldState,
126};
127
128thread_local! {
129    static LAYOUT_ENGINE: RefCell<layout::LayoutEngine> =
130        RefCell::new(layout::LayoutEngine::new());
131}
132
133#[derive(Default)]
134pub struct Interactions {
135    pub hover: Option<u64>,
136    pub pressed: HashSet<u64>,
137}
138
139pub fn Box(modifier: Modifier) -> View {
140    View::new(0, ViewKind::Box).modifier(modifier)
141}
142
143pub fn Row(modifier: Modifier) -> View {
144    View::new(0, ViewKind::Row).modifier(modifier)
145}
146
147pub fn Column(modifier: Modifier) -> View {
148    View::new(0, ViewKind::Column).modifier(modifier)
149}
150
151/// A horizontally-oriented flow layout that wraps children to new rows when
152/// they exceed the available width. Equivalent to `Row` with `flex_wrap(Wrap)`.
153pub fn FlowRow(modifier: Modifier) -> View {
154    Row(modifier.flex_wrap(FlexWrap::Wrap))
155}
156
157/// Flipped container (identical to `Column`).
158/// Deprecated: use `Column` directly.
159#[deprecated = "Use Column instead (identical behavior)"]
160pub fn Stack(modifier: Modifier) -> View {
161    Column(modifier)
162}
163
164/// A vertically-oriented flow layout that wraps children to new columns when
165/// they exceed the available height. Equivalent to `Column` with `flex_wrap(Wrap)`.
166pub fn FlowColumn(modifier: Modifier) -> View {
167    Column(modifier.flex_wrap(FlexWrap::Wrap))
168}
169
170/// Centers children both axes inside this Box.
171/// (Compose `Box(contentAlignment = Alignment.Center)`.)
172pub fn Center(modifier: Modifier) -> View {
173    Box(modifier.content_alignment(Alignment::Center))
174}
175
176pub fn ZStack(modifier: Modifier) -> View {
177    View::new(0, ViewKind::ZStack).modifier(modifier)
178}
179
180pub fn OverlayHost(modifier: Modifier) -> View {
181    View::new(0, ViewKind::OverlayHost).modifier(modifier)
182}
183
184#[deprecated = "Use Modifier::vertical_scroll instead"]
185pub fn Scroll(modifier: Modifier) -> View {
186    View::new(0, ViewKind::Box).modifier(modifier.vertical_scroll(ScrollAxisBinding {
187        show_scrollbar: true,
188        ..Default::default()
189    }))
190}
191
192pub fn Text(text: impl Into<String>) -> View {
193    View::new(
194        0,
195        ViewKind::Text {
196            text: text.into(),
197            color: locals::content_color(),
198            font_size: locals::text_size().unwrap_or(16.0), // dp (converted to px in layout/paint)
199            soft_wrap: true,
200            max_lines: None,
201            overflow: TextOverflow::Visible,
202            font_family: Some("sans-serif"),
203            annotations: None,
204            text_align: TextAlign::Start,
205            font_weight: FontWeight::NORMAL,
206            font_style: FontStyle::Normal,
207            text_decoration: TextDecoration::default(),
208            letter_spacing: 0.0,
209            line_height: 0.0,
210            url: None,
211            font_variation_settings: None,
212        },
213    )
214}
215
216/// Create a text view with rich text spans (AnnotatedString).
217///
218/// Each span can override color and font_size for a range of text.
219pub fn AnnotatedText(annotated: AnnotatedString) -> View {
220    let annotations: Option<std::sync::Arc<[TextSpan]>> = if annotated.spans.is_empty() {
221        None
222    } else {
223        Some(annotated.spans.clone())
224    };
225    View::new(
226        0,
227        ViewKind::Text {
228            text: annotated.text,
229            color: locals::content_color(),
230            font_size: locals::text_size().unwrap_or(16.0),
231            soft_wrap: true,
232            max_lines: None,
233            overflow: TextOverflow::Visible,
234            font_family: Some("sans-serif"),
235            annotations,
236            text_align: TextAlign::Start,
237            font_weight: FontWeight::NORMAL,
238            font_style: FontStyle::Normal,
239            text_decoration: TextDecoration::default(),
240            letter_spacing: 0.0,
241            line_height: 0.0,
242            url: None,
243            font_variation_settings: None,
244        },
245    )
246}
247
248pub fn Spacer() -> View {
249    Box(Modifier::new().flex_grow(1.0))
250}
251
252pub fn Space(modifier: Modifier) -> View {
253    Box(modifier)
254}
255
256pub fn Grid(
257    columns: usize,
258    modifier: Modifier,
259    children: Vec<View>,
260    row_gap: f32,
261    column_gap: f32,
262) -> View {
263    Column(modifier.grid(columns, row_gap, column_gap)).with_children(children)
264}
265
266pub fn Expander(modifier: Modifier, expanded: bool, on_toggle: impl Fn() + 'static) -> View {
267    View::new(
268        0,
269        ViewKind::Expander {
270            expanded,
271            on_toggle: Some(Rc::new(on_toggle)),
272        },
273    )
274    .modifier(modifier)
275}
276
277/// A single row in a tree view.
278///
279/// Renders with indentation based on `depth`, an expand/collapse arrow if
280/// `has_children` is true, and a highlight background if `is_selected`.
281/// The first child is the row's label/content.
282pub fn TreeRow(
283    modifier: Modifier,
284    depth: usize,
285    has_children: bool,
286    is_expanded: bool,
287    is_selected: bool,
288    on_toggle: impl Fn() + 'static,
289    on_select: impl Fn() + 'static,
290) -> View {
291    View::new(
292        0,
293        ViewKind::TreeRow {
294            depth,
295            has_children,
296            is_expanded,
297            is_selected,
298            on_toggle: Some(Rc::new(on_toggle)),
299            on_select: Some(Rc::new(on_select)),
300        },
301    )
302    .modifier(modifier)
303}
304
305static DRAGVALUE_COUNTER: AtomicU64 = AtomicU64::new(0);
306
307/// A drag-to-change numeric value field (like egui's `DragValue`).
308///
309/// Click and drag left/right to change the value. Displays the current value
310/// as centered text in a bordered box.
311pub fn DragValue(
312    value: f32,
313    range: (f32, f32),
314    speed: f32,
315    on_change: impl Fn(f32) + 'static,
316) -> View {
317    let id = DRAGVALUE_COUNTER.fetch_add(1, Ordering::Relaxed);
318    let drag_start_x = remember_mutable_with_key(format!("dv_dsx_{}", id), || 0.0f32);
319    let drag_start_val = remember_mutable_with_key(format!("dv_dsv_{}", id), || 0.0f32);
320    let is_dragging = remember_mutable_with_key(format!("dv_drg_{}", id), || false);
321
322    let oc = Rc::new(on_change);
323    let min = range.0;
324    let max = range.1;
325    let cur = value;
326
327    let th = locals::theme();
328
329    Box(Modifier::new()
330        .min_width(48.0)
331        .height(28.0)
332        .background(th.surface_container)
333        .border(1.0, th.outline, 4.0)
334        .clip_rounded(4.0)
335        .padding_values(PaddingValues {
336            left: 4.0,
337            right: 4.0,
338            top: 0.0,
339            bottom: 0.0,
340        })
341        .on_pointer_down({
342            let dsx = drag_start_x.clone();
343            let dsv = drag_start_val.clone();
344            let drg = is_dragging.clone();
345            move |pe: PointerEvent| {
346                drg.set(true);
347                dsx.set(pe.position_in_window().x);
348                dsv.set(cur);
349            }
350        })
351        .on_pointer_move({
352            let dsx = drag_start_x.clone();
353            let dsv = drag_start_val.clone();
354            let drg = is_dragging.clone();
355            let oc = oc.clone();
356            move |pe: PointerEvent| {
357                if !drg.with(|v| *v) {
358                    return;
359                }
360                let start_x = dsx.with(|v| *v);
361                let start_val = dsv.with(|v| *v);
362                let new_val =
363                    (start_val + (pe.position_in_window().x - start_x) * speed).clamp(min, max);
364                (oc)(new_val);
365            }
366        })
367        .on_pointer_up({
368            let drg = is_dragging.clone();
369            move |_pe: PointerEvent| {
370                drg.set(false);
371            }
372        })
373        .cursor(CursorIcon::EwResize))
374    .child(
375        Text(format_value(value))
376            .size(13.0)
377            .color(th.on_surface)
378            .single_line()
379            .overflow_ellipsize(),
380    )
381}
382
383fn format_value(v: f32) -> String {
384    if (v - v.round()).abs() < 1e-6 {
385        format!("{}", v.round() as i64)
386    } else if (v * 10.0 - (v * 10.0).round()).abs() < 1e-6 {
387        format!("{:.1}", v)
388    } else {
389        format!("{:.2}", v)
390    }
391}
392
393pub fn Image(modifier: Modifier, handle: ImageHandle) -> View {
394    View::new(
395        0,
396        ViewKind::Image {
397            handle,
398            tint: Color::WHITE,
399            fit: ImageFit::Contain,
400        },
401    )
402    .modifier(modifier)
403}
404
405pub trait ImageExt {
406    fn image_tint(self, c: Color) -> View;
407    fn image_fit(self, fit: ImageFit) -> View;
408}
409impl ImageExt for View {
410    fn image_tint(mut self, c: Color) -> View {
411        if let ViewKind::Image { tint, .. } = &mut self.kind {
412            *tint = c;
413        }
414        self
415    }
416    fn image_fit(mut self, fit: ImageFit) -> View {
417        if let ViewKind::Image { fit: f, .. } = &mut self.kind {
418            *f = fit;
419        }
420        self
421    }
422}
423
424/// Extension trait for child building
425pub trait ViewExt: Sized {
426    fn child(self, children: impl IntoChildren) -> Self;
427}
428
429impl ViewExt for View {
430    fn child(mut self, children: impl IntoChildren) -> Self {
431        self.children.extend(children.into_children());
432        self
433    }
434}
435
436pub trait IntoChildren {
437    fn into_children(self) -> Vec<View>;
438}
439
440impl IntoChildren for View {
441    fn into_children(self) -> Vec<View> {
442        vec![self]
443    }
444}
445
446impl IntoChildren for Vec<View> {
447    fn into_children(self) -> Vec<View> {
448        self
449    }
450}
451
452impl<const N: usize> IntoChildren for [View; N] {
453    fn into_children(self) -> Vec<View> {
454        self.into()
455    }
456}
457
458// Tuple implementations
459macro_rules! impl_into_children_tuple {
460    ($($idx:tt $t:ident),+) => {
461        impl<$($t: IntoChildren),+> IntoChildren for ($($t,)+) {
462            fn into_children(self) -> Vec<View> {
463                let mut v = Vec::new();
464                $(v.extend(self.$idx.into_children());)+
465                v
466            }
467        }
468    };
469}
470
471impl_into_children_tuple!(0 A);
472impl_into_children_tuple!(0 A, 1 B);
473impl_into_children_tuple!(0 A, 1 B, 2 C);
474impl_into_children_tuple!(0 A, 1 B, 2 C, 3 D);
475impl_into_children_tuple!(0 A, 1 B, 2 C, 3 D, 4 E);
476impl_into_children_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F);
477impl_into_children_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G);
478impl_into_children_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H);
479
480/// Reconcile `root` into the thread-local `LayoutEngine` and run incremental
481/// layout + paint for this frame.
482pub fn layout_and_paint(
483    root: &View,
484    size_px_u32: (u32, u32),
485    textfield_states: &HashMap<u64, Rc<RefCell<TextFieldState>>>,
486    interactions: &Interactions,
487    focused: Option<u64>,
488) -> (Scene, Vec<HitRegion>, Vec<SemNode>) {
489    LAYOUT_ENGINE.with(|engine| {
490        engine
491            .borrow_mut()
492            .layout_frame(root, size_px_u32, textfield_states, interactions, focused)
493    })
494}
495
496/// Return the [`LayoutStats`] from the most recent `layout_and_paint` call on
497/// this thread. Used by the inspector / HUD to report real layout+paint timing
498/// and cache counters instead of a hardcoded estimate.
499pub fn last_layout_stats() -> layout::LayoutStats {
500    LAYOUT_ENGINE.with(|engine| engine.borrow().stats.clone())
501}
502
503pub use layout::LayoutStats;
504
505/// Method styling
506pub trait TextStyle {
507    fn color(self, c: Color) -> View;
508    fn size(self, px: f32) -> View;
509    fn max_lines(self, n: usize) -> View;
510    fn single_line(self) -> View;
511    fn overflow_ellipsize(self) -> View;
512    fn overflow_clip(self) -> View;
513    fn overflow_visible(self) -> View;
514    fn font_family(self, family: &'static str) -> View;
515    fn text_align(self, align: TextAlign) -> View;
516    fn font_weight(self, weight: FontWeight) -> View;
517    fn font_style(self, style: FontStyle) -> View;
518    fn text_decoration(self, decoration: TextDecoration) -> View;
519    fn letter_spacing(self, spacing: f32) -> View;
520    fn line_height(self, height: f32) -> View;
521    fn url(self, url: impl Into<std::sync::Arc<str>>) -> View;
522    fn font_variation_settings(self, settings: &str) -> View;
523}
524impl TextStyle for View {
525    fn color(mut self, c: Color) -> View {
526        if let ViewKind::Text {
527            color: text_color, ..
528        } = &mut self.kind
529        {
530            *text_color = c;
531        }
532        self
533    }
534    fn size(mut self, dp_font: f32) -> View {
535        if let ViewKind::Text {
536            font_size: text_size_dp,
537            ..
538        } = &mut self.kind
539        {
540            *text_size_dp = dp_font;
541        }
542        self
543    }
544    fn max_lines(mut self, n: usize) -> View {
545        if let ViewKind::Text {
546            max_lines,
547            soft_wrap,
548            ..
549        } = &mut self.kind
550        {
551            *max_lines = Some(n);
552            *soft_wrap = true;
553        }
554        self
555    }
556    fn single_line(mut self) -> View {
557        if let ViewKind::Text {
558            soft_wrap,
559            max_lines,
560            ..
561        } = &mut self.kind
562        {
563            *soft_wrap = false;
564            *max_lines = Some(1);
565        }
566        self
567    }
568    fn overflow_ellipsize(mut self) -> View {
569        if let ViewKind::Text { overflow, .. } = &mut self.kind {
570            *overflow = TextOverflow::Ellipsis;
571        }
572        self
573    }
574    fn overflow_clip(mut self) -> View {
575        if let ViewKind::Text { overflow, .. } = &mut self.kind {
576            *overflow = TextOverflow::Clip;
577        }
578        self
579    }
580    fn overflow_visible(mut self) -> View {
581        if let ViewKind::Text { overflow, .. } = &mut self.kind {
582            *overflow = TextOverflow::Visible;
583        }
584        self
585    }
586    fn font_family(mut self, family: &'static str) -> View {
587        if let ViewKind::Text {
588            font_family: ff, ..
589        } = &mut self.kind
590        {
591            *ff = Some(family);
592        }
593        self
594    }
595    fn text_align(mut self, align: TextAlign) -> View {
596        if let ViewKind::Text { text_align, .. } = &mut self.kind {
597            *text_align = align;
598        }
599        self
600    }
601    fn font_weight(mut self, weight: FontWeight) -> View {
602        if let ViewKind::Text { font_weight, .. } = &mut self.kind {
603            *font_weight = weight;
604        }
605        self
606    }
607    fn font_style(mut self, style: FontStyle) -> View {
608        if let ViewKind::Text { font_style, .. } = &mut self.kind {
609            *font_style = style;
610        }
611        self
612    }
613    fn text_decoration(mut self, decoration: TextDecoration) -> View {
614        if let ViewKind::Text {
615            text_decoration, ..
616        } = &mut self.kind
617        {
618            *text_decoration = decoration;
619        }
620        self
621    }
622    fn letter_spacing(mut self, spacing: f32) -> View {
623        if let ViewKind::Text { letter_spacing, .. } = &mut self.kind {
624            *letter_spacing = spacing;
625        }
626        self
627    }
628    fn line_height(mut self, height: f32) -> View {
629        if let ViewKind::Text { line_height, .. } = &mut self.kind {
630            *line_height = height;
631        }
632        self
633    }
634    fn url(mut self, url: impl Into<std::sync::Arc<str>>) -> View {
635        if let ViewKind::Text {
636            url: u,
637            text_decoration,
638            ..
639        } = &mut self.kind
640        {
641            *u = Some(url.into());
642            if !text_decoration.underline && !text_decoration.strikethrough {
643                *text_decoration = TextDecoration::UNDERLINE;
644            }
645        }
646        self
647    }
648    fn font_variation_settings(mut self, settings: &str) -> View {
649        if let ViewKind::Text {
650            font_variation_settings,
651            ..
652        } = &mut self.kind
653        {
654            *font_variation_settings = Some(settings.into());
655        }
656        self
657    }
658}