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.dp())).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(crate) mod hit_testing;
91pub use hit_testing::{
92    HitRegionSnapshot, dispatch_keyboard_action, hit_region_contains, hit_region_local_rect,
93    hit_region_pointer_coordinates, hit_region_to_local, hit_region_transformed_origin,
94    hit_region_world_rect, hit_test_enabled_frame, hit_test_frame, hit_test_frame_path,
95    hit_test_frame_regions,
96};
97pub mod layout;
98pub use layout::IntrinsicSizeMode;
99pub mod lazy;
100pub mod selection;
101pub mod subcompose;
102pub use lazy::{
103    LazyColumn, LazyHorizontalGrid, LazyRow, LazyVerticalGrid, LazyVerticalStaggeredGrid,
104    SimpleList,
105};
106pub mod lazy_states;
107pub use lazy_states::{
108    ItemHeight, LazyColumnConfig, LazyColumnState, LazyGridConfig, LazyGridState, LazyRowConfig,
109    LazyRowState, LazyVerticalStaggeredGridConfig, LazyVerticalStaggeredGridState,
110};
111pub use seekable::{SeekableTransitionScope, SeekableTransitionState};
112pub use subcompose::{
113    BoxWithConstraints, SubcomposeLayout, box_with_constraints_with_key, subcompose_hash_key,
114    subcompose_layout_with_slots, subcompose_with_key, subcompose_with_key_slots,
115};
116pub mod overlay;
117pub mod pager;
118pub mod scroll;
119pub mod scrollbar_fade;
120pub mod scrollbar_repeat;
121pub mod seekable;
122pub mod window_v2;
123pub mod windowing;
124
125use std::cell::RefCell;
126use std::collections::{HashMap, HashSet};
127use std::rc::Rc;
128use std::sync::atomic::{AtomicU64, Ordering};
129
130use repose_core::*;
131
132pub(crate) mod text_selection;
133pub mod textfield;
134use repose_core::locals;
135pub use selection::{SelectableText, SelectableTextExt};
136pub use textfield::{
137    BasicSecureTextField, BasicTextField, KeyboardOptions, TextFieldConfig, TextFieldState,
138};
139
140thread_local! {
141    static LAYOUT_ENGINE: RefCell<layout::LayoutEngine> =
142        RefCell::new(layout::LayoutEngine::new());
143}
144
145#[derive(Default)]
146pub struct Interactions {
147    pub hover: Option<u64>,
148    pub hover_ancestors: std::collections::HashSet<u64>,
149    pub pressed: HashSet<u64>,
150}
151
152pub fn Box(modifier: Modifier) -> View {
153    View::new(0, ViewKind::Box).modifier(modifier)
154}
155
156pub fn Row(modifier: Modifier) -> View {
157    View::new(0, ViewKind::Row).modifier(modifier)
158}
159
160/// Scope receiver for building `Row` children with row-only capabilities,
161/// mirroring Compose's `RowScope`.
162///
163/// Obtain one only inside [`row_scope`], whose closure signature keeps the
164/// reference from escaping, then attach the returned children to a `Row`:
165/// ```ignore
166/// Row(Modifier::new()).children(row_scope(|s| vec![
167///     s.align_by_baseline(Text("Ag").size(32.0)),
168///     Text("Ag").size(16.0),
169/// ]))
170/// ```
171/// Children built outside a scope (plain `View`s) mix freely with scoped
172/// ones; only `align_by_*` children participate in baseline alignment.
173pub struct RowScope {
174    _private: (),
175}
176
177impl RowScope {
178    /// Align this child by its first text baseline within the `Row`
179    /// (Compose `RowScope.alignByBaseline`). Siblings without a baseline
180    /// request keep their normal cross-axis alignment.
181    pub fn align_by_baseline(&self, view: View) -> View {
182        self.align_by(view, BaselineAlign::FirstBaseline)
183    }
184
185    /// Align this child by its last text baseline within the `Row`
186    /// (Compose `RowScope.alignBy(LastBaseline)`).
187    pub fn align_by_last_baseline(&self, view: View) -> View {
188        self.align_by(view, BaselineAlign::LastBaseline)
189    }
190
191    /// Align this child by the given baseline (Compose `RowScope.alignBy`).
192    pub fn align_by(&self, mut view: View, line: BaselineAlign) -> View {
193        view.modifier.baseline_align = Some(line);
194        view
195    }
196}
197
198/// Run `content` with a [`RowScope`] receiver and collect the children.
199/// The scope reference cannot escape the closure; use the result as (part
200/// of) a `Row`'s children.
201pub fn row_scope<R>(content: impl FnOnce(&RowScope) -> R) -> R {
202    content(&RowScope { _private: () })
203}
204
205pub fn Column(modifier: Modifier) -> View {
206    View::new(0, ViewKind::Column).modifier(modifier)
207}
208
209/// Configuration for [`FlowRow`]. M3-style config: construct with
210/// `..Default::default()` so future options don't break callers.
211#[derive(Clone, Copy, Debug, PartialEq)]
212pub struct FlowRowConfig {
213    /// Pack lines to balance their lengths instead of filling each line
214    /// greedily (taffy 0.14 `FlexWrap::Balance`). Best for chip/tag clouds.
215    pub balanced: bool,
216    /// Minimum number of lines; balanced items spread into at least this
217    /// many lines. `1` (default) leaves the count to layout.
218    pub min_lines: u16,
219}
220
221impl Default for FlowRowConfig {
222    fn default() -> Self {
223        Self {
224            balanced: false,
225            min_lines: 1,
226        }
227    }
228}
229
230/// Configuration for [`FlowColumn`]. See [`FlowRowConfig`].
231#[derive(Clone, Copy, Debug, PartialEq)]
232pub struct FlowColumnConfig {
233    /// Pack lines to balance their lengths (taffy 0.14 `FlexWrap::Balance`).
234    pub balanced: bool,
235    /// Minimum number of lines. `1` (default) leaves the count to layout.
236    pub min_lines: u16,
237}
238
239impl Default for FlowColumnConfig {
240    fn default() -> Self {
241        Self {
242            balanced: false,
243            min_lines: 1,
244        }
245    }
246}
247
248/// A horizontally-oriented flow layout that wraps children to new rows when
249/// they exceed the available width. Equivalent to `Row` with `flex_wrap(Wrap)`.
250/// Tune via [`FlowRowConfig`] (e.g. balanced packing).
251pub fn FlowRow(modifier: Modifier, config: FlowRowConfig) -> View {
252    let mut modifier = modifier.flex_wrap(if config.balanced {
253        FlexWrap::Balance
254    } else {
255        FlexWrap::Wrap
256    });
257    modifier.flex_line_count = Some(config.min_lines.max(1));
258    Row(modifier)
259}
260
261/// Flipped container (identical to `Column`).
262/// Deprecated: use `Column` directly.
263#[deprecated = "Use Column instead (identical behavior)"]
264pub fn Stack(modifier: Modifier) -> View {
265    Column(modifier)
266}
267
268/// A vertically-oriented flow layout that wraps children to new columns when
269/// they exceed the available height. Equivalent to `Column` with `flex_wrap(Wrap)`.
270/// Tune via [`FlowColumnConfig`] (e.g. balanced packing).
271pub fn FlowColumn(modifier: Modifier, config: FlowColumnConfig) -> View {
272    let mut modifier = modifier.flex_wrap(if config.balanced {
273        FlexWrap::Balance
274    } else {
275        FlexWrap::Wrap
276    });
277    modifier.flex_line_count = Some(config.min_lines.max(1));
278    Column(modifier)
279}
280
281/// Centers children both axes inside this Box.
282/// (Compose `Box(contentAlignment = Alignment.Center)`.)
283/// Uses *safe* centering so overflowing content stays reachable inside
284/// scroll containers instead of spilling past both edges.
285pub fn Center(modifier: Modifier) -> View {
286    Box(modifier.content_alignment_safe(Alignment::Center))
287}
288
289pub fn ZStack(modifier: Modifier) -> View {
290    View::new(0, ViewKind::ZStack).modifier(modifier)
291}
292
293pub fn OverlayHost(modifier: Modifier) -> View {
294    View::new(0, ViewKind::OverlayHost).modifier(modifier)
295}
296
297#[deprecated = "Use Modifier::vertical_scroll instead"]
298pub fn Scroll(modifier: Modifier) -> View {
299    View::new(0, ViewKind::Box).modifier(modifier.vertical_scroll(ScrollAxisBinding {
300        show_scrollbar: true,
301        ..Default::default()
302    }))
303}
304
305pub fn Text(text: impl Into<String>) -> View {
306    View::new(
307        0,
308        ViewKind::Text {
309            text: text.into(),
310            color: locals::content_color(),
311            // Sp (converted to px in layout/paint, including TextScale).
312            font_size: locals::text_size().unwrap_or(Sp(16.0)),
313            soft_wrap: true,
314            max_lines: None,
315            overflow: TextOverflow::Clip,
316            font_family: Some("sans-serif"),
317            annotations: None,
318            text_align: TextAlign::Start,
319            font_weight: FontWeight::NORMAL,
320            font_style: FontStyle::Normal,
321            text_decoration: TextDecoration::default(),
322            letter_spacing: Sp::ZERO,
323            line_height: Sp::ZERO,
324            url: None,
325            font_variation_settings: None,
326            draw_style: DrawStyle::Fill,
327        },
328    )
329}
330
331/// Create a text view with rich text spans (AnnotatedString).
332///
333/// Each span can override color and font_size for a range of text.
334pub fn AnnotatedText(annotated: AnnotatedString) -> View {
335    let annotations: Option<std::sync::Arc<[TextSpan]>> = if annotated.spans.is_empty() {
336        None
337    } else {
338        Some(annotated.spans.clone())
339    };
340    View::new(
341        0,
342        ViewKind::Text {
343            text: annotated.text,
344            color: locals::content_color(),
345            font_size: locals::text_size().unwrap_or(Sp(16.0)),
346            soft_wrap: true,
347            max_lines: None,
348            overflow: TextOverflow::Clip,
349            font_family: Some("sans-serif"),
350            annotations,
351            text_align: TextAlign::Start,
352            font_weight: FontWeight::NORMAL,
353            font_style: FontStyle::Normal,
354            text_decoration: TextDecoration::default(),
355            letter_spacing: Sp::ZERO,
356            line_height: Sp::ZERO,
357            url: None,
358            font_variation_settings: None,
359            draw_style: DrawStyle::Fill,
360        },
361    )
362}
363
364pub fn Spacer() -> View {
365    Box(Modifier::new().flex_grow(1.0))
366}
367
368pub fn Space(modifier: Modifier) -> View {
369    Box(modifier)
370}
371
372pub fn Grid(
373    columns: usize,
374    modifier: Modifier,
375    children: Vec<View>,
376    row_gap: Dp,
377    column_gap: Dp,
378) -> View {
379    Column(modifier.grid(columns, row_gap, column_gap)).with_children(children)
380}
381
382static DRAGVALUE_COUNTER: AtomicU64 = AtomicU64::new(0);
383
384/// A drag-to-change numeric value field (like egui's `DragValue`).
385///
386/// Click and drag left/right to change the value. Displays the current value
387/// as centered text in a bordered box.
388pub fn DragValue(
389    value: f32,
390    range: (f32, f32),
391    speed: f32,
392    on_change: impl Fn(f32) + 'static,
393) -> View {
394    let id = DRAGVALUE_COUNTER.fetch_add(1, Ordering::Relaxed);
395    let drag_start_x = remember_mutable_with_key(format!("dv_dsx_{}", id), || 0.0f32);
396    let drag_start_val = remember_mutable_with_key(format!("dv_dsv_{}", id), || 0.0f32);
397    let is_dragging = remember_mutable_with_key(format!("dv_drg_{}", id), || false);
398
399    let oc = Rc::new(on_change);
400    let min = range.0;
401    let max = range.1;
402    let cur = value;
403
404    let th = locals::theme();
405
406    Box(Modifier::new()
407        .min_width(Dp(48.0))
408        .height(Dp(28.0))
409        .background(th.surface_container)
410        .border(Dp(1.0), th.outline, Dp(4.0))
411        .clip_rounded(Dp(4.0))
412        .padding_values(PaddingValues {
413            left: Dp(4.0),
414            right: Dp(4.0),
415            top: Dp::ZERO,
416            bottom: Dp::ZERO,
417        })
418        .on_pointer_down({
419            let dsx = drag_start_x.clone();
420            let dsv = drag_start_val.clone();
421            let drg = is_dragging.clone();
422            move |pe: PointerEvent| {
423                drg.set(true);
424                dsx.set(pe.position_in_window().x);
425                dsv.set(cur);
426            }
427        })
428        .on_pointer_move({
429            let dsx = drag_start_x.clone();
430            let dsv = drag_start_val.clone();
431            let drg = is_dragging.clone();
432            let oc = oc.clone();
433            move |pe: PointerEvent| {
434                if !drg.with(|v| *v) {
435                    return;
436                }
437                let start_x = dsx.with(|v| *v);
438                let start_val = dsv.with(|v| *v);
439                let new_val =
440                    (start_val + (pe.position_in_window().x - start_x) * speed).clamp(min, max);
441                (oc)(new_val);
442            }
443        })
444        .on_pointer_up({
445            let drg = is_dragging.clone();
446            move |_pe: PointerEvent| {
447                drg.set(false);
448            }
449        })
450        .on_pointer_cancel({
451            let drg = is_dragging.clone();
452            move |_pe: PointerEvent| {
453                drg.set(false);
454            }
455        })
456        .cursor(CursorIcon::EwResize))
457    .child(
458        Text(format_value(value))
459            .size(Sp(13.0))
460            .color(th.on_surface)
461            .single_line()
462            .overflow_ellipsize(),
463    )
464}
465
466fn format_value(v: f32) -> String {
467    if (v - v.round()).abs() < 1e-6 {
468        format!("{}", v.round() as i64)
469    } else if (v * 10.0 - (v * 10.0).round()).abs() < 1e-6 {
470        format!("{:.1}", v)
471    } else {
472        format!("{:.2}", v)
473    }
474}
475
476pub fn Image(modifier: Modifier, handle: ImageHandle) -> View {
477    View::new(
478        0,
479        ViewKind::Image {
480            handle,
481            tint: Color::WHITE,
482            fit: ImageFit::Contain,
483            filter: ImageFilter::Linear,
484            source_rect: None,
485            alignment: ImageAlignment::Center,
486        },
487    )
488    .modifier(modifier)
489}
490
491/// Embedded GPU callback (like `egui::PaintCallback`).
492pub fn Embedded(modifier: Modifier, payload: PaintCallbackPayload) -> View {
493    let mut m = modifier.paint_callback(payload);
494    let has_size = m.size.is_some()
495        || m.width.is_some()
496        || m.height.is_some()
497        || m.fill_max.is_some()
498        || m.fill_max_w.is_some()
499        || m.fill_max_h.is_some();
500    if !has_size {
501        m = m.size(Dp(100.0), Dp(100.0));
502    }
503    Box(m)
504}
505
506pub trait ImageExt {
507    fn image_tint(self, c: Color) -> View;
508    fn image_fit(self, fit: ImageFit) -> View;
509    fn image_filter(self, filter: ImageFilter) -> View;
510    fn image_source_rect(self, source_rect: ImageSourceRect) -> View;
511    fn image_alignment(self, alignment: ImageAlignment) -> View;
512}
513impl ImageExt for View {
514    fn image_tint(mut self, c: Color) -> View {
515        if let ViewKind::Image { tint, .. } = &mut self.kind {
516            *tint = c;
517        }
518        self
519    }
520    fn image_fit(mut self, fit: ImageFit) -> View {
521        if let ViewKind::Image { fit: f, .. } = &mut self.kind {
522            *f = fit;
523        }
524        self
525    }
526    fn image_filter(mut self, filter: ImageFilter) -> View {
527        if let ViewKind::Image { filter: f, .. } = &mut self.kind {
528            *f = filter;
529        }
530        self
531    }
532    fn image_source_rect(mut self, source: ImageSourceRect) -> View {
533        if let ViewKind::Image { source_rect, .. } = &mut self.kind {
534            *source_rect = Some(source);
535        }
536        self
537    }
538    fn image_alignment(mut self, alignment: ImageAlignment) -> View {
539        if let ViewKind::Image {
540            alignment: current, ..
541        } = &mut self.kind
542        {
543            *current = alignment;
544        }
545        self
546    }
547}
548
549/// Extension trait for child building
550pub trait ViewExt: Sized {
551    fn child(self, children: impl IntoChildren) -> Self;
552}
553
554impl ViewExt for View {
555    fn child(mut self, children: impl IntoChildren) -> Self {
556        self.children.extend(children.into_children());
557        self
558    }
559}
560
561pub trait IntoChildren {
562    fn into_children(self) -> Vec<View>;
563}
564
565impl IntoChildren for View {
566    fn into_children(self) -> Vec<View> {
567        vec![self]
568    }
569}
570
571impl IntoChildren for Vec<View> {
572    fn into_children(self) -> Vec<View> {
573        self
574    }
575}
576
577impl<const N: usize> IntoChildren for [View; N] {
578    fn into_children(self) -> Vec<View> {
579        self.into()
580    }
581}
582
583// Tuple implementations
584macro_rules! impl_into_children_tuple {
585    ($($idx:tt $t:ident),+) => {
586        impl<$($t: IntoChildren),+> IntoChildren for ($($t,)+) {
587            fn into_children(self) -> Vec<View> {
588                let mut v = Vec::new();
589                $(v.extend(self.$idx.into_children());)+
590                v
591            }
592        }
593    };
594}
595
596impl_into_children_tuple!(0 A);
597impl_into_children_tuple!(0 A, 1 B);
598impl_into_children_tuple!(0 A, 1 B, 2 C);
599impl_into_children_tuple!(0 A, 1 B, 2 C, 3 D);
600impl_into_children_tuple!(0 A, 1 B, 2 C, 3 D, 4 E);
601impl_into_children_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F);
602impl_into_children_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G);
603impl_into_children_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H);
604
605/// Reconcile `root` into the thread-local `LayoutEngine` and run incremental
606/// layout + paint for this frame.
607pub fn layout_and_paint(
608    root: &View,
609    size_px_u32: (u32, u32),
610    textfield_states: &HashMap<u64, Rc<RefCell<TextFieldState>>>,
611    interactions: &Interactions,
612    focused: Option<u64>,
613) -> (Scene, Vec<HitRegion>, Vec<SemNode>) {
614    let result = LAYOUT_ENGINE.with(|engine| {
615        engine
616            .borrow_mut()
617            .layout_frame(root, size_px_u32, textfield_states, interactions, focused)
618    });
619    textfield::prune_textfield_registries();
620    result
621}
622
623/// Return the [`LayoutStats`] from the most recent `layout_and_paint` call on
624/// this thread. Used by the inspector / HUD to report real layout+paint timing
625/// and cache counters instead of a hardcoded estimate.
626pub fn last_layout_stats() -> layout::LayoutStats {
627    LAYOUT_ENGINE.with(|engine| engine.borrow().stats.clone())
628}
629
630/// Drop the retained layout/paint tree on this thread.
631///
632/// Tests and hot reload use this to start a composition from an empty engine;
633/// the next `layout_and_paint` rebuilds it from the passed root.
634pub fn reset_layout_engine() {
635    LAYOUT_ENGINE.with(|engine| *engine.borrow_mut() = layout::LayoutEngine::new());
636}
637
638pub use layout::LayoutStats;
639
640/// Method styling (text sizes are [`Sp`]).
641pub trait TextStyle {
642    fn color(self, c: Color) -> View;
643    fn size(self, size: Sp) -> View;
644    fn max_lines(self, n: usize) -> View;
645    fn single_line(self) -> View;
646    fn overflow_ellipsize(self) -> View;
647    fn overflow_clip(self) -> View;
648    fn overflow_visible(self) -> View;
649    fn font_family(self, family: &'static str) -> View;
650    fn text_align(self, align: TextAlign) -> View;
651    fn font_weight(self, weight: FontWeight) -> View;
652    fn font_style(self, style: FontStyle) -> View;
653    fn text_decoration(self, decoration: TextDecoration) -> View;
654    fn letter_spacing(self, spacing: Sp) -> View;
655    fn line_height(self, height: Sp) -> View;
656    fn url(self, url: impl Into<std::sync::Arc<str>>) -> View;
657    fn font_variation_settings(self, settings: &str) -> View;
658    fn draw_style(self, style: DrawStyle) -> View;
659    /// Faux-bold: fill plus a same-color outline (`width` in em-units,
660    /// 0.04 is a good start). For fonts without a bold face.
661    fn fill_and_stroke(self, width: f32) -> View;
662    /// Godot `font_outline_size` / `font_outline_color`: the fill with a
663    /// contrasting outline drawn underneath, in one layout pass. `width` is
664    /// em-units and the stroke is centred on the glyph outline, so pass
665    /// `2 * outline_px / font_px` to grow `outline_px` outward.
666    fn outlined(self, width: f32, color: Color) -> View;
667}
668impl TextStyle for View {
669    fn color(mut self, c: Color) -> View {
670        if let ViewKind::Text {
671            color: text_color, ..
672        } = &mut self.kind
673        {
674            *text_color = c;
675        }
676        self
677    }
678    fn size(mut self, size: Sp) -> View {
679        if let ViewKind::Text {
680            font_size: text_size_sp,
681            ..
682        } = &mut self.kind
683        {
684            *text_size_sp = size;
685        }
686        self
687    }
688    fn max_lines(mut self, n: usize) -> View {
689        if let ViewKind::Text {
690            max_lines,
691            soft_wrap,
692            ..
693        } = &mut self.kind
694        {
695            *max_lines = Some(n);
696            *soft_wrap = true;
697        }
698        self
699    }
700    fn single_line(mut self) -> View {
701        if let ViewKind::Text {
702            soft_wrap,
703            max_lines,
704            ..
705        } = &mut self.kind
706        {
707            *soft_wrap = false;
708            *max_lines = Some(1);
709        }
710        self
711    }
712    fn overflow_ellipsize(mut self) -> View {
713        if let ViewKind::Text { overflow, .. } = &mut self.kind {
714            *overflow = TextOverflow::Ellipsis;
715        }
716        self
717    }
718    fn overflow_clip(mut self) -> View {
719        if let ViewKind::Text { overflow, .. } = &mut self.kind {
720            *overflow = TextOverflow::Clip;
721        }
722        self
723    }
724    fn overflow_visible(mut self) -> View {
725        if let ViewKind::Text { overflow, .. } = &mut self.kind {
726            *overflow = TextOverflow::Visible;
727        }
728        self
729    }
730    fn font_family(mut self, family: &'static str) -> View {
731        if let ViewKind::Text {
732            font_family: ff, ..
733        } = &mut self.kind
734        {
735            *ff = Some(family);
736        }
737        self
738    }
739    fn text_align(mut self, align: TextAlign) -> View {
740        if let ViewKind::Text { text_align, .. } = &mut self.kind {
741            *text_align = align;
742        }
743        self
744    }
745    fn font_weight(mut self, weight: FontWeight) -> View {
746        if let ViewKind::Text { font_weight, .. } = &mut self.kind {
747            *font_weight = weight;
748        }
749        self
750    }
751    fn font_style(mut self, style: FontStyle) -> View {
752        if let ViewKind::Text { font_style, .. } = &mut self.kind {
753            *font_style = style;
754        }
755        self
756    }
757    fn text_decoration(mut self, decoration: TextDecoration) -> View {
758        if let ViewKind::Text {
759            text_decoration, ..
760        } = &mut self.kind
761        {
762            *text_decoration = decoration;
763        }
764        self
765    }
766    fn letter_spacing(mut self, spacing: Sp) -> View {
767        if let ViewKind::Text { letter_spacing, .. } = &mut self.kind {
768            *letter_spacing = spacing;
769        }
770        self
771    }
772    fn line_height(mut self, height: Sp) -> View {
773        if let ViewKind::Text { line_height, .. } = &mut self.kind {
774            *line_height = height;
775        }
776        self
777    }
778    fn url(mut self, url: impl Into<std::sync::Arc<str>>) -> View {
779        if let ViewKind::Text {
780            url: u,
781            text_decoration,
782            ..
783        } = &mut self.kind
784        {
785            *u = Some(url.into());
786            if !text_decoration.underline && !text_decoration.strikethrough {
787                *text_decoration = TextDecoration::UNDERLINE;
788            }
789        }
790        self
791    }
792    fn font_variation_settings(mut self, settings: &str) -> View {
793        if let ViewKind::Text {
794            font_variation_settings,
795            ..
796        } = &mut self.kind
797        {
798            *font_variation_settings = Some(settings.into());
799        }
800        self
801    }
802    fn draw_style(mut self, style: DrawStyle) -> View {
803        if let ViewKind::Text { draw_style, .. } = &mut self.kind {
804            *draw_style = style;
805        }
806        self
807    }
808    fn fill_and_stroke(mut self, width: f32) -> View {
809        if let ViewKind::Text { draw_style, .. } = &mut self.kind {
810            *draw_style = DrawStyle::fill_and_stroke(width);
811        }
812        self
813    }
814    fn outlined(mut self, width: f32, color: Color) -> View {
815        if let ViewKind::Text { draw_style, .. } = &mut self.kind {
816            *draw_style = DrawStyle::fill_and_stroke_with_outline(width, color);
817        }
818        self
819    }
820}