Skip to main content

compose_rust/ui/
mod.rs

1//! The widget vocabulary as composables: the same widgets, the same properties and the
2//! same Modifier slots the `rsx!` layer writes, with Compose's names and Compose's shape.
3//!
4//! ```ignore
5//! use compose_rust::runtime::*;
6//! use compose_rust::ui::*;
7//!
8//! #[Composable]
9//! fn Greeting(name: String) {
10//!     Column().modifier(Modifier.padding(16.0).fill_max_width()).content(|| {
11//!         Text(format!("Hello, {name}")).type_role(TypeRole::Title);
12//!         Button("Wave").on_click(|| show_message("Hello back"));
13//!     });
14//! }
15//! ```
16//!
17//! **A widget is written as a statement.** `Text("Hello")` creates a description and the
18//! statement's end hands it to the composition; the methods in between set what Compose
19//! would take as named arguments. A container's children are the closure given to
20//! `content`, which runs at once. Binding a widget to a variable delays it to the end of
21//! the variable's scope, so a widget is not bound.
22//!
23//! **Nothing here defines a widget.** Each composable writes exactly the attributes its
24//! `rsx!` counterpart writes, through the same translation into wire records, so a screen
25//! written either way is the same tree of the same nodes for the Renderer. A Modifier the
26//! `rsx!` counterpart does not accept is still written when it is set, because the wire
27//! carries every Modifier slot on every node.
28
29pub(crate) mod focus;
30mod lazy;
31mod widgets;
32
33pub use crate::boundary::LaunchBuilder;
34pub use crate::brush::{Brush, Stop, brush};
35pub use crate::clipboard::{Clipboard, use_clipboard};
36pub use crate::drawing::{DrawCommand, DrawList, DrawListBuilder};
37pub use crate::font_features::FontFeature;
38pub use crate::message::{Message, show_message};
39pub use crate::runtime::{application, launch};
40pub use crate::schema::SemanticsRole as Role;
41pub use crate::schema::{
42    Alignment, Arrangement, BackgroundRepeat, ButtonKind, ButtonVariant, Color, ColorRole,
43    ColorScheme, CompactNavigation, ContentScale, DesignSystem, HorizontalAlignment, IconRole, Key,
44    MaterialRole, MessageDuration, MessageHorizontal, MessagePlacement, MessageVertical,
45    MotionRole, Paint, PopoverAlign, PopoverPlacement, SemanticsRole, ShapeRole, SheetPresentation,
46    Snap, SpaceRole, TextAlign, TextOverflow, Theme, TypeRole, VerticalAlignment,
47    WindowHeightClass, WindowSizeClass,
48};
49pub use crate::spans::TextSpans;
50pub use crate::theme::{ThemeHandle, current_theme};
51
52/// The application's theme, to read and to change while it runs. A change is one
53/// `SetTheme` record in the batch the call that made it produces.
54pub fn theme() -> ThemeHandle {
55    ThemeHandle::default()
56}
57pub use crate::asset::AssetId;
58pub use crate::window::{NodeSize, WindowSafeArea, WindowSize};
59pub use crate::{
60    Cursor, FileDrop, KeyEvent, PointerEvent, PointerKind, PointerKinds, RangeRequest, UserSelect,
61    asset, pointer_button,
62};
63pub use focus::{FocusHandle, use_focus_handle};
64pub use lazy::{LazyColumn, LazyGrid, LazyList, LazyListScope, LazyRow};
65pub use widgets::*;
66
67use crate::runtime::composer::{EventCallback, OwnedAttr};
68use crate::runtime::{group_guard, with_composer, with_composer_if_idle};
69use crate::schema::WidgetKind;
70
71/// The most shadow layers one node can carry through this API.
72pub const MAX_SHADOWS: usize = 4;
73
74/// One layer of a drop shadow, as CSS `box-shadow` writes it: an offset, a blur, a spread
75/// and a colour with its alpha. It follows the corners of the node that casts it.
76#[derive(Clone, Copy, Debug, PartialEq)]
77pub struct Shadow {
78    pub x: f32,
79    pub y: f32,
80    pub blur: f32,
81    pub spread: f32,
82    pub paint: Paint,
83}
84
85impl Shadow {
86    pub const fn new(x: f32, y: f32, blur: f32, spread: f32, paint: Paint) -> Self {
87        Self {
88            x,
89            y,
90            blur,
91            spread,
92            paint,
93        }
94    }
95}
96
97/// The most background brush layers one node can carry through this API.
98pub const MAX_BACKGROUND_BRUSHES: usize = 4;
99
100/// One background layer, as CSS draws a `background-image` with its position, size and
101/// repeat: a brush laid into a rectangle of the node, in dp from its top left corner, and
102/// repeated from there. A gradient is measured against the rectangle, not the node. The
103/// layer is cut to the node's outline and painted over its background colour.
104#[derive(Clone, Copy, Debug, PartialEq)]
105pub struct BackgroundBrush {
106    pub x: f32,
107    pub y: f32,
108    pub width: f32,
109    pub height: f32,
110    pub paint: Paint,
111    pub repeat: BackgroundRepeat,
112    /// How far apart the copies are, in dp. The rectangle's own size is CSS `repeat`.
113    pub tile_width: f32,
114    pub tile_height: f32,
115}
116
117impl BackgroundBrush {
118    /// One copy of `paint` in the rectangle, not repeated.
119    pub const fn new(x: f32, y: f32, width: f32, height: f32, paint: Paint) -> Self {
120        Self {
121            x,
122            y,
123            width,
124            height,
125            paint,
126            repeat: BackgroundRepeat::NoRepeat,
127            tile_width: width,
128            tile_height: height,
129        }
130    }
131
132    /// Repeats the rectangle the given ways, a rectangle's size apart unless
133    /// [`BackgroundBrush::step`] says otherwise.
134    pub const fn repeat(mut self, repeat: BackgroundRepeat) -> Self {
135        self.repeat = repeat;
136        self
137    }
138
139    /// How far apart the copies are, in dp, for CSS `space` and `round`. A step of zero or
140    /// less is not a step, and a layer with one is not sent.
141    pub const fn step(mut self, width: f32, height: f32) -> Self {
142        self.tile_width = width;
143        self.tile_height = height;
144        self
145    }
146}
147
148/// How a node presents itself to assistive technology. Each tri-state field is unset until
149/// it is given a value, and an unset one sends nothing. The flags are off until set.
150#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
151pub struct SemanticsState {
152    pub checked: Option<bool>,
153    pub selected: Option<bool>,
154    pub expanded: Option<bool>,
155    pub disabled: Option<bool>,
156    pub focused: Option<bool>,
157    pub hidden: bool,
158    pub click_action: bool,
159    pub focus_action: bool,
160    pub has_popup: bool,
161}
162
163impl SemanticsState {
164    const NONE: Self = Self {
165        checked: None,
166        selected: None,
167        expanded: None,
168        disabled: None,
169        focused: None,
170        hidden: false,
171        click_action: false,
172        focus_action: false,
173        has_popup: false,
174    };
175
176    pub const fn checked(checked: bool) -> Self {
177        Self {
178            checked: Some(checked),
179            ..Self::NONE
180        }
181    }
182
183    pub const fn selected(selected: bool) -> Self {
184        Self {
185            selected: Some(selected),
186            ..Self::NONE
187        }
188    }
189
190    pub const fn expanded(expanded: bool) -> Self {
191        Self {
192            expanded: Some(expanded),
193            ..Self::NONE
194        }
195    }
196
197    pub const fn disabled(disabled: bool) -> Self {
198        Self {
199            disabled: Some(disabled),
200            ..Self::NONE
201        }
202    }
203
204    pub const fn focused(focused: bool) -> Self {
205        Self {
206            focused: Some(focused),
207            ..Self::NONE
208        }
209    }
210
211    pub const fn hidden(hidden: bool) -> Self {
212        Self {
213            hidden,
214            ..Self::NONE
215        }
216    }
217
218    pub const fn click_action(exposed: bool) -> Self {
219        Self {
220            click_action: exposed,
221            ..Self::NONE
222        }
223    }
224
225    pub const fn focus_action(exposed: bool) -> Self {
226        Self {
227            focus_action: exposed,
228            ..Self::NONE
229        }
230    }
231
232    pub const fn has_popup(has_popup: bool) -> Self {
233        Self {
234            has_popup,
235            ..Self::NONE
236        }
237    }
238
239    /// The state word the `Semantics` modifier carries.
240    pub(crate) fn bits(self) -> u32 {
241        use crate::schema::*;
242        let tri = |value: Option<bool>| value.map_or(0_u32, |on| if on { 2 } else { 1 });
243        (tri(self.checked) << SEMANTICS_CHECKED_SHIFT)
244            | (tri(self.selected) << SEMANTICS_SELECTED_SHIFT)
245            | (tri(self.expanded) << SEMANTICS_EXPANDED_SHIFT)
246            | (tri(self.disabled) << SEMANTICS_DISABLED_SHIFT)
247            | (tri(self.focused) << SEMANTICS_FOCUSED_SHIFT)
248            | if self.hidden { SEMANTICS_HIDDEN_BIT } else { 0 }
249            | if self.click_action {
250                SEMANTICS_CLICK_ACTION_BIT
251            } else {
252                0
253            }
254            | if self.focus_action {
255                SEMANTICS_FOCUS_ACTION_BIT
256            } else {
257                0
258            }
259            | if self.has_popup {
260                SEMANTICS_HAS_POPUP_BIT
261            } else {
262                0
263            }
264    }
265}
266
267use std::sync::Arc;
268
269/// A bounded cache of recent accessible names.
270pub(crate) struct LabelCache {
271    entries: Vec<Arc<str>>,
272    capacity: usize,
273}
274
275pub(crate) const DEFAULT_LABEL_CACHE_CAPACITY: usize = 128;
276
277impl LabelCache {
278    pub(crate) fn new() -> Self {
279        Self::with_capacity(DEFAULT_LABEL_CACHE_CAPACITY)
280    }
281
282    pub(crate) fn with_capacity(capacity: usize) -> Self {
283        Self {
284            entries: Vec::with_capacity(capacity),
285            capacity,
286        }
287    }
288
289    /// The kept copy of `label`. If present in the cache, it is moved to the most recently
290    /// used position and returned with no allocation. Otherwise a new `Arc<str>` is created,
291    /// the oldest entry is evicted if full, and the new entry is returned.
292    pub(crate) fn intern(&mut self, label: &str) -> Arc<str> {
293        if let Some(pos) = self
294            .entries
295            .iter()
296            .position(|entry| entry.as_ref() == label)
297        {
298            let entry = self.entries.remove(pos);
299            self.entries.push(Arc::clone(&entry));
300            return entry;
301        }
302        let entry: Arc<str> = Arc::from(label);
303        if self.entries.len() >= self.capacity && self.capacity > 0 {
304            self.entries.remove(0);
305        }
306        if self.capacity > 0 {
307            self.entries.push(Arc::clone(&entry));
308        }
309        entry
310    }
311
312    #[cfg(test)]
313    pub(crate) fn len(&self) -> usize {
314        self.entries.len()
315    }
316}
317
318fn keep_label(label: &str) -> Option<Arc<str>> {
319    use std::cell::RefCell;
320
321    if label.is_empty() {
322        return None;
323    }
324
325    thread_local! {
326        static LAST: RefCell<Option<Arc<str>>> = const { RefCell::new(None) };
327        static CACHE: RefCell<LabelCache> = RefCell::new(LabelCache::new());
328    }
329
330    if let Some(last) = LAST.with(|cell| {
331        let borrowed = cell.borrow();
332        if let Some(last) = borrowed.as_ref() {
333            if last.as_ref() == label {
334                return Some(Arc::clone(last));
335            }
336        }
337        None
338    }) {
339        return Some(last);
340    }
341
342    let kept = CACHE.with(|cache| cache.borrow_mut().intern(label));
343    LAST.with(|cell| {
344        *cell.borrow_mut() = Some(Arc::clone(&kept));
345    });
346    Some(kept)
347}
348
349/// One side of a node, for [`Modifier::border_side`].
350#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
351pub enum Side {
352    Top,
353    /// The side a line of text ends on: the right side.
354    End,
355    Bottom,
356    /// The side a line of text starts on: the left side.
357    Start,
358}
359
360/// What sits around a widget: its size, its surface, its outline, how far its content
361/// is inset, and what the Renderer reports about it. Compose's `Modifier`.
362///
363/// Written the way Compose writes it, from the empty value `Modifier`:
364///
365/// ```ignore
366/// Card().modifier(Modifier.fill_max_width().padding(16.0).background(Paint::Role(ColorRole::Surface)))
367/// ```
368///
369/// The order of the calls does not matter. Each kind of Modifier has a fixed slot in the
370/// node's chain, outside in: size, shape, fill, outline, lift, press, inset. That is what
371/// the `rsx!` attributes do too, so the same Modifier draws the same either way.
372#[derive(Clone, Debug, Default, PartialEq)]
373pub struct Modifier {
374    observe_size: Option<i64>,
375    observe_size_every_dp: bool,
376    motion: Option<MotionRole>,
377    material: Option<MaterialRole>,
378    weight: Option<f32>,
379    width: Option<f32>,
380    height: Option<f32>,
381    padding: Option<f32>,
382    padding_role: Option<SpaceRole>,
383    background: Option<Paint>,
384    shape_role: Option<ShapeRole>,
385    corner_radius: Option<f32>,
386    corner_radii: Option<[f32; 4]>,
387    corner_curve: Option<f32>,
388    min_touch_target: Option<f32>,
389    overlay: Option<Paint>,
390    border_width: Option<f32>,
391    border_color: Option<Paint>,
392    border_each: Option<[(f32, Paint); 4]>,
393    elevation: Option<f32>,
394    alpha: Option<f32>,
395    press_feedback: Option<(f32, f32)>,
396    semantics_role: Option<SemanticsRole>,
397    semantics_label: Option<Arc<str>>,
398    semantics_state: SemanticsState,
399    transform: Option<[f32; 8]>,
400    animated_alpha: Option<crate::Animated<f32>>,
401    animated_background: Option<crate::Animated<Paint>>,
402    animated_offset: Option<crate::Animated<(f32, f32)>>,
403    cursor: Option<crate::Cursor>,
404    user_select: Option<crate::UserSelect>,
405    clip: bool,
406    window_drag: Option<bool>,
407    offset: Option<(f32, f32)>,
408    shadows: [Option<Shadow>; MAX_SHADOWS],
409    background_brushes: [Option<BackgroundBrush>; MAX_BACKGROUND_BRUSHES],
410    fill_max_width: bool,
411    match_parent_size: bool,
412    fill_max_height: bool,
413    sticky: bool,
414    unbounded_width: bool,
415    size_in: Option<[f32; 4]>,
416    aspect_ratio: Option<(f32, bool)>,
417}
418
419/// The empty Modifier, to start a chain from: `Modifier.padding(8.0)`.
420#[allow(non_upper_case_globals)]
421pub const Modifier: Modifier = Modifier::new();
422
423impl Modifier {
424    /// The empty Modifier. The same as the value `Modifier`.
425    pub const fn new() -> Self {
426        Self {
427            observe_size: None,
428            observe_size_every_dp: false,
429            motion: None,
430            material: None,
431            weight: None,
432            width: None,
433            height: None,
434            padding: None,
435            padding_role: None,
436            background: None,
437            shape_role: None,
438            corner_radius: None,
439            corner_radii: None,
440            corner_curve: None,
441            min_touch_target: None,
442            overlay: None,
443            border_width: None,
444            border_color: None,
445            border_each: None,
446            elevation: None,
447            alpha: None,
448            press_feedback: None,
449            semantics_role: None,
450            semantics_label: None,
451            semantics_state: SemanticsState::NONE,
452            transform: None,
453            animated_alpha: None,
454            animated_background: None,
455            animated_offset: None,
456            cursor: None,
457            user_select: None,
458            clip: false,
459            window_drag: None,
460            offset: None,
461            shadows: [None; MAX_SHADOWS],
462            background_brushes: [None; MAX_BACKGROUND_BRUSHES],
463            fill_max_width: false,
464            match_parent_size: false,
465            fill_max_height: false,
466            sticky: false,
467            unbounded_width: false,
468            size_in: None,
469            aspect_ratio: None,
470        }
471    }
472
473    /// A share of the space left in a `Row` or `Column`.
474    pub const fn weight(mut self, weight: f32) -> Self {
475        self.weight = Some(weight);
476        self
477    }
478
479    pub const fn width(mut self, dp: f32) -> Self {
480        self.width = Some(dp);
481        self
482    }
483
484    pub const fn height(mut self, dp: f32) -> Self {
485        self.height = Some(dp);
486        self
487    }
488
489    /// Both at once.
490    pub const fn size(self, width: f32, height: f32) -> Self {
491        self.width(width).height(height)
492    }
493
494    /// A width that may be unset, for a screen whose measure depends on the window.
495    pub const fn width_if(mut self, dp: Option<f32>) -> Self {
496        self.width = dp;
497        self
498    }
499
500    /// Matches the bounds of a Box parent without affecting its size.
501    pub const fn match_parent_size(mut self) -> Self {
502        self.match_parent_size = true;
503        self
504    }
505
506    /// Pins a child to the start edge of a scrolling container (such as ScrollRow)
507    /// while the rest of the content scrolls.
508    pub const fn sticky(mut self) -> Self {
509        self.sticky = true;
510        self
511    }
512
513    pub const fn fill_max_width(mut self) -> Self {
514        self.fill_max_width = true;
515        self
516    }
517
518    pub const fn fill_max_height(mut self) -> Self {
519        self.fill_max_height = true;
520        self
521    }
522
523    pub const fn fill_max_size(self) -> Self {
524        self.fill_max_width().fill_max_height()
525    }
526
527    /// Measures the node with no maximum width, so [`Modifier::observe_size`] or
528    /// [`Modifier::observe_size_every_dp`] reports the width its content asks for instead
529    /// of the width its parent offered.
530    ///
531    /// Only the measurement changes. The node still takes the width its parent offered,
532    /// its content starts at the start edge, and whatever is wider than that is clipped.
533    /// A table column sized to its widest cell uses it: a cell wider than the column
534    /// reports its own width, and the column grows on the next frame.
535    pub const fn unbounded_width(mut self) -> Self {
536        self.unbounded_width = true;
537        self
538    }
539
540    /// [`Modifier::unbounded_width`] when `unbounded` is `true`, and nothing when it is
541    /// `false`: the node is measured inside its parent's width as usual. The last call of
542    /// the two decides.
543    pub const fn wrap_content_width(mut self, unbounded: bool) -> Self {
544        self.unbounded_width = unbounded;
545        self
546    }
547
548    /// Constrains the size of the content within minimum and maximum bounds in dp.
549    ///
550    /// Pass `f32::NAN` for any bound that should remain unconstrained.
551    pub const fn size_in(
552        mut self,
553        min_width: f32,
554        max_width: f32,
555        min_height: f32,
556        max_height: f32,
557    ) -> Self {
558        self.size_in = Some([min_width, max_width, min_height, max_height]);
559        self
560    }
561
562    /// Constrains width within minimum and maximum bounds in dp, preserving any height constraints.
563    pub const fn width_in(mut self, min: f32, max: f32) -> Self {
564        let (min_h, max_h) = match self.size_in {
565            Some([_, _, min_h, max_h]) => (min_h, max_h),
566            None => (f32::NAN, f32::NAN),
567        };
568        self.size_in = Some([min, max, min_h, max_h]);
569        self
570    }
571
572    /// Constrains height within minimum and maximum bounds in dp, preserving any width constraints.
573    pub const fn height_in(mut self, min: f32, max: f32) -> Self {
574        let (min_w, max_w) = match self.size_in {
575            Some([min_w, max_w, _, _]) => (min_w, max_w),
576            None => (f32::NAN, f32::NAN),
577        };
578        self.size_in = Some([min_w, max_w, min, max]);
579        self
580    }
581
582    /// Constrains maximum width in dp, preserving any height constraints.
583    pub const fn max_width(self, max: f32) -> Self {
584        self.width_in(f32::NAN, max)
585    }
586
587    /// Constrains maximum height in dp, preserving any width constraints.
588    pub const fn max_height(self, max: f32) -> Self {
589        self.height_in(f32::NAN, max)
590    }
591
592    /// Constrains minimum width in dp, preserving any height constraints.
593    pub const fn min_width(self, min: f32) -> Self {
594        self.width_in(min, f32::NAN)
595    }
596
597    /// Constrains minimum height in dp, preserving any width constraints.
598    pub const fn min_height(self, min: f32) -> Self {
599        self.height_in(min, f32::NAN)
600    }
601
602    /// Attempts to size the content to match a specified aspect ratio.
603    pub const fn aspect_ratio(mut self, ratio: f32) -> Self {
604        self.aspect_ratio = Some((ratio, false));
605        self
606    }
607
608    /// Attempts to size the content to match a specified aspect ratio, optionally matching height constraints first.
609    pub const fn aspect_ratio_match_height(
610        mut self,
611        ratio: f32,
612        match_height_constraints_first: bool,
613    ) -> Self {
614        self.aspect_ratio = Some((ratio, match_height_constraints_first));
615        self
616    }
617
618    /// Fills the width only when `fill` is true.
619    pub const fn fill_max_width_if(mut self, fill: bool) -> Self {
620        self.fill_max_width = fill;
621        self
622    }
623
624    /// The same inset on every side, in dp.
625    pub const fn padding(mut self, dp: f32) -> Self {
626        self.padding = Some(dp);
627        self
628    }
629
630    /// An inset from the design system's spacing ladder. Wins over `padding`.
631    pub const fn padding_role(mut self, role: SpaceRole) -> Self {
632        self.padding_role = Some(role);
633        self
634    }
635
636    /// The same, when the inset may be unset.
637    pub const fn padding_role_if(mut self, role: Option<SpaceRole>) -> Self {
638        self.padding_role = role;
639        self
640    }
641
642    pub const fn background(mut self, paint: Paint) -> Self {
643        self.background = Some(paint);
644        self
645    }
646
647    /// The same, when there may be no background.
648    pub const fn background_if(mut self, paint: Option<Paint>) -> Self {
649        self.background = paint;
650        self
651    }
652
653    /// A paint laid over the node: over its content and its background, in the box its
654    /// background fills and cut to the same corners (`corner_radius`, `corner_radii`,
655    /// `shape_role`, curved as `corner_curve` says). It takes no room, so a node sized by
656    /// its content keeps its size, and nothing has to restate the node's size or radius.
657    /// A press tint or a selection wash is one of these; give it a colour with alpha.
658    pub const fn overlay(mut self, paint: Paint) -> Self {
659        self.overlay = Some(paint);
660        self
661    }
662
663    /// The same, when there may be no overlay.
664    pub const fn overlay_if(mut self, paint: Option<Paint>) -> Self {
665        self.overlay = paint;
666        self
667    }
668
669    /// A shape from the design system's ladder. `ShapeRole::Full` is a pill at whatever
670    /// height the node has, so round ends need no radius worked out from the height.
671    pub const fn shape_role(mut self, role: ShapeRole) -> Self {
672        self.shape_role = Some(role);
673        self
674    }
675
676    /// A literal corner, in dp. Wins over `shape_role`.
677    pub const fn corner_radius(mut self, dp: f32) -> Self {
678        self.corner_radius = Some(dp);
679        self.corner_radii = None;
680        self
681    }
682
683    /// Individual corner radii `[top_start, top_end, bottom_end, bottom_start]`, in dp.
684    /// Wins over `shape_role` and `corner_radius`.
685    pub const fn corner_radii(mut self, radii: [f32; 4]) -> Self {
686        self.corner_radii = Some(radii);
687        self.corner_radius = None;
688        self
689    }
690
691    /// Clips the node and its children to its shape, or to its rectangle when it has none.
692    pub const fn clip(mut self, clip: bool) -> Self {
693        self.clip = clip;
694        self
695    }
696
697    /// Includes or excludes this node from window dragging.
698    pub const fn window_drag(mut self, enabled: bool) -> Self {
699        self.window_drag = Some(enabled);
700        self
701    }
702
703    /// The same border on every side. It takes the place of `border_each` and
704    /// `border_side`.
705    pub const fn border(mut self, width: f32, paint: Paint) -> Self {
706        self.border_width = Some(width);
707        self.border_color = Some(paint);
708        self.border_each = None;
709        self
710    }
711
712    /// A border whose sides each have their own width and paint, in CSS order: top,
713    /// right, bottom, left. A side of width 0 draws nothing. It takes the place of
714    /// `border`.
715    ///
716    /// The sides are the screen's, not the reading direction's: `right` is the right side
717    /// in a right-to-left window too.
718    pub const fn border_each(
719        mut self,
720        top: (f32, Paint),
721        right: (f32, Paint),
722        bottom: (f32, Paint),
723        left: (f32, Paint),
724    ) -> Self {
725        self.border_each = Some([top, right, bottom, left]);
726        self.border_width = None;
727        self.border_color = None;
728        self
729    }
730
731    /// A border on one side only, such as the guide line beside an indented row. The
732    /// other sides have width 0, unless an earlier `border_side` or `border_each` in the
733    /// same chain gave them one, so `border_side(Side::Top, ..).border_side(Side::Start,
734    /// ..)` draws two sides. It takes the place of `border`.
735    ///
736    /// `Side::Start` is the left side and `Side::End` the right one. The Host lays every
737    /// screen out left to right and the Renderer draws a border on the screen's sides, so
738    /// a right-to-left window does not move a start border to the right.
739    pub const fn border_side(mut self, side: Side, width: f32, paint: Paint) -> Self {
740        let mut sides = match self.border_each {
741            Some(sides) => sides,
742            None => [(0.0, paint); 4],
743        };
744        let index = match side {
745            Side::Top => 0,
746            Side::End => 1,
747            Side::Bottom => 2,
748            Side::Start => 3,
749        };
750        sides[index] = (width, paint);
751        self.border_each = Some(sides);
752        self.border_width = None;
753        self.border_color = None;
754        self
755    }
756
757    /// A resting height above the default, in dp. How it is drawn is the design system's.
758    pub const fn elevation(mut self, dp: f32) -> Self {
759        self.elevation = Some(dp);
760        self
761    }
762
763    /// Asks the Renderer to report this node's size under the token from
764    /// [`crate::runtime::remember_node_size`].
765    ///
766    /// A report goes out on the first measurement and then whenever the width or height
767    /// class changes. A resize inside one class says nothing; use
768    /// [`Modifier::observe_size_every_dp`] for that.
769    pub const fn observe_size(mut self, token: i64) -> Self {
770        self.observe_size = Some(token);
771        self.observe_size_every_dp = false;
772        self
773    }
774
775    /// Like [`Modifier::observe_size`], and also reports whenever the width or height,
776    /// rounded to the nearest whole dp, changes inside one class. Several changes in one
777    /// frame are one report carrying the last size.
778    pub const fn observe_size_every_dp(mut self, token: i64) -> Self {
779        self.observe_size = Some(token);
780        self.observe_size_every_dp = true;
781        self
782    }
783
784    /// How important this node's changes are. The curve is the design system's.
785    pub const fn motion(mut self, role: MotionRole) -> Self {
786        self.motion = Some(role);
787        self
788    }
789
790    /// What this node's surface is made of. The effect is the design system's.
791    pub const fn material(mut self, role: MaterialRole) -> Self {
792        self.material = Some(role);
793        self
794    }
795
796    /// Moves the node from where it was laid out, in dp, without moving anything else.
797    pub const fn offset(mut self, x: f32, y: f32) -> Self {
798        self.offset = Some((x, y));
799        self
800    }
801
802    /// Adds a shadow layer. Layers are drawn in the order they are added, the first at
803    /// the bottom. A node takes at most [`MAX_SHADOWS`]; a layer past that is ignored.
804    pub const fn shadow(mut self, shadow: Shadow) -> Self {
805        let mut index = 0;
806        while index < MAX_SHADOWS {
807            if self.shadows[index].is_none() {
808                self.shadows[index] = Some(shadow);
809                break;
810            }
811            index += 1;
812        }
813        self
814    }
815
816    /// Adds several shadow layers, in order.
817    pub fn shadows(mut self, shadows: impl IntoIterator<Item = Shadow>) -> Self {
818        for shadow in shadows {
819            self = self.shadow(shadow);
820        }
821        self
822    }
823
824    /// Adds a background brush layer. Layers are drawn in the order they are added, the
825    /// first at the bottom, all of them over the background colour. A node takes at most
826    /// [`MAX_BACKGROUND_BRUSHES`]; a layer past that is ignored.
827    pub const fn background_brush(mut self, layer: BackgroundBrush) -> Self {
828        let mut index = 0;
829        while index < MAX_BACKGROUND_BRUSHES {
830            if self.background_brushes[index].is_none() {
831                self.background_brushes[index] = Some(layer);
832                break;
833            }
834            index += 1;
835        }
836        self
837    }
838
839    /// Adds several background brush layers, in order. CSS writes its list top first, so
840    /// a list taken from CSS is added last to first.
841    pub fn background_brushes(mut self, layers: impl IntoIterator<Item = BackgroundBrush>) -> Self {
842        for layer in layers {
843            self = self.background_brush(layer);
844        }
845        self
846    }
847
848    /// An opacity for the node and everything in it, faded as one group.
849    pub const fn alpha(mut self, alpha: f32) -> Self {
850        self.alpha = Some(alpha);
851        self
852    }
853
854    /// How the node's rounded corners curve, from 0 (a circular arc, the default) to 1.
855    /// Above 0 the curve eases in from each side with continuously changing curvature, as
856    /// Figma's corner smoothing does; 0.6 is the look of iOS. The radius stays whatever
857    /// `corner_radius`, `corner_radii` or `shape_role` made it, and the background, border,
858    /// shadow and clip all follow the same curve. A value outside 0..=1 is taken as the
859    /// nearer end, and NaN as 0.
860    pub fn corner_curve(mut self, smoothing: f32) -> Self {
861        self.corner_curve = Some(crate::schema::corner_smoothing(smoothing));
862        self
863    }
864
865    /// The least size, in dp, of the area that takes this node's presses. A node drawn
866    /// smaller, such as a 26 by 32 dp icon button, takes presses over a box grown to this
867    /// size around it. Its size, its place and how it is drawn stay as they are, so nothing
868    /// laid out beside it moves. Compose's `minimumInteractiveComponentSize` does the same
869    /// for Material's controls; 44 dp is the usual target for a finger. Off unless set.
870    pub const fn min_touch_target(mut self, dp: f32) -> Self {
871        self.min_touch_target = Some(dp);
872        self
873    }
874
875    /// Sets the pressed scale and tint opacity.
876    pub const fn press_feedback(mut self, scale: f32, tint_alpha: f32) -> Self {
877        self.press_feedback = Some((scale, tint_alpha));
878        self
879    }
880
881    /// The name assistive technology reads for this node. On a widget with a visible label
882    /// it replaces that label; an empty name is the same as none.
883    pub fn label(mut self, label: &str) -> Self {
884        self.semantics_label = keep_label(label);
885        self
886    }
887
888    /// What this node is to assistive technology, for a node that is not a widget with
889    /// a role of its own: a `Box` that is pressed is a button.
890    pub const fn role(mut self, role: Role) -> Self {
891        self.semantics_role = Some(role);
892        self
893    }
894
895    /// Whether the node is checked, as a toggle announces it.
896    pub const fn checked(mut self, checked: bool) -> Self {
897        self.semantics_state.checked = Some(checked);
898        self
899    }
900
901    /// Whether the node is the selected one of its group.
902    pub const fn selected(mut self, selected: bool) -> Self {
903        self.semantics_state.selected = Some(selected);
904        self
905    }
906
907    /// Whether the node is expanded, as a disclosure or a tree item announces it.
908    pub const fn expanded(mut self, expanded: bool) -> Self {
909        self.semantics_state.expanded = Some(expanded);
910        self
911    }
912
913    /// Whether the node is disabled for assistive technology.
914    pub const fn disabled(mut self, disabled: bool) -> Self {
915        self.semantics_state.disabled = Some(disabled);
916        self
917    }
918
919    /// Whether the node holds the focus, as assistive technology reads it.
920    pub const fn focused(mut self, focused: bool) -> Self {
921        self.semantics_state.focused = Some(focused);
922        self
923    }
924
925    /// Leaves the node out of the accessibility tree when true.
926    pub const fn hidden(mut self, hidden: bool) -> Self {
927        self.semantics_state.hidden = hidden;
928        self
929    }
930
931    /// Exposes a click action on the node, which runs the node's click handler.
932    pub const fn click_action(mut self, exposed: bool) -> Self {
933        self.semantics_state.click_action = exposed;
934        self
935    }
936
937    /// Exposes a focus action on the node.
938    pub const fn focus_action(mut self, exposed: bool) -> Self {
939        self.semantics_state.focus_action = exposed;
940        self
941    }
942
943    /// Whether the node opens a popup, as a menu button announces it.
944    pub const fn has_popup(mut self, has_popup: bool) -> Self {
945        self.semantics_state.has_popup = has_popup;
946        self
947    }
948
949    /// The role, the name and the state in one call.
950    pub fn semantics(self, role: Role, label: &str, state: SemanticsState) -> Self {
951        let mut named = self.role(role).label(label);
952        named.semantics_state = state;
953        named
954    }
955
956    /// Compose's `graphicsLayer`: a rotation, a scale and a translation about an origin,
957    /// drawn without moving the layout, and an opacity for the whole group. A pointer is
958    /// tested against the shape that is drawn.
959    pub fn graphics_layer(mut self, layer: crate::GraphicsLayer) -> Self {
960        if let crate::schema::Modifier::Transform {
961            a,
962            b,
963            c,
964            d,
965            e,
966            f,
967            origin_x,
968            origin_y,
969        } = layer.transform()
970        {
971            self.transform = Some([a, b, c, d, e, f, origin_x, origin_y]);
972        }
973        self.alpha = Some(layer.alpha);
974        self
975    }
976
977    /// An opacity the Renderer animates to, from [`crate::animate_float_as_state`]. It
978    /// takes the place of `alpha`.
979    pub const fn animated_alpha(mut self, value: crate::Animated<f32>) -> Self {
980        self.animated_alpha = Some(value);
981        self
982    }
983
984    /// A background the Renderer animates to, from [`crate::animate_color_as_state`]. It
985    /// takes the place of `background`.
986    pub const fn animated_background(mut self, value: crate::Animated<Paint>) -> Self {
987        self.animated_background = Some(value);
988        self
989    }
990
991    /// A translation the Renderer animates to, from [`crate::animate_offset_as_state`].
992    /// It takes the place of the transform a `graphics_layer` would draw.
993    pub const fn animated_offset(mut self, value: crate::Animated<(f32, f32)>) -> Self {
994        self.animated_offset = Some(value);
995        self
996    }
997
998    /// The cursor the platform shows over the node. CSS `cursor`: the deepest node under
999    /// the pointer that names one other than `Cursor::Auto` wins, and while a node holds a
1000    /// pointer capture its cursor stays.
1001    pub const fn cursor(mut self, cursor: crate::Cursor) -> Self {
1002        self.cursor = Some(cursor);
1003        self
1004    }
1005
1006    /// Whether the text under the node can be selected. CSS `user-select`; `Auto` follows
1007    /// the parent.
1008    pub const fn user_select(mut self, user_select: crate::UserSelect) -> Self {
1009        self.user_select = Some(user_select);
1010        self
1011    }
1012}
1013
1014/// Which Modifier attributes a widget's `rsx!` counterpart always writes. The others are
1015/// written only when they are set.
1016#[derive(Clone, Copy, PartialEq, Eq)]
1017pub(crate) enum Mods {
1018    /// The containers that take every Modifier: Column, Row, Box, Card, Surface.
1019    Container,
1020    /// The thirteen every other widget takes.
1021    Standard,
1022    /// A chip's six.
1023    Chip,
1024    /// A Scaffold's background and material.
1025    Scaffold,
1026    /// None.
1027    None,
1028}
1029
1030pub(crate) type Attrs = Vec<(&'static str, OwnedAttr)>;
1031
1032fn float(value: Option<f32>) -> OwnedAttr {
1033    value.map_or(OwnedAttr::None, |value| OwnedAttr::Float(f64::from(value)))
1034}
1035
1036fn role(value: Option<impl Into<u16>>) -> OwnedAttr {
1037    value.map_or(OwnedAttr::None, |value| {
1038        OwnedAttr::Int(i64::from(value.into()))
1039    })
1040}
1041
1042fn paint(value: Option<Paint>) -> OwnedAttr {
1043    value.map_or(OwnedAttr::None, |paint| {
1044        OwnedAttr::Int(paint.to_bits() as i64)
1045    })
1046}
1047
1048/// A role that was not set is tag 0, which means "not sent".
1049pub(crate) fn role_or_zero(value: Option<impl Into<u16>>) -> OwnedAttr {
1050    OwnedAttr::Int(value.map_or(0, |value| i64::from(value.into())))
1051}
1052
1053/// A dp value that was not set is 0.
1054pub(crate) fn dp_or_zero(value: Option<f32>) -> OwnedAttr {
1055    OwnedAttr::Float(f64::from(value.unwrap_or(0.0)))
1056}
1057
1058/// A paint that was not set is 0.
1059pub(crate) fn paint_or_zero(value: Option<Paint>) -> OwnedAttr {
1060    OwnedAttr::Int(value.map_or(0, |paint| paint.to_bits() as i64))
1061}
1062
1063pub(crate) fn optional_text(value: Option<String>) -> OwnedAttr {
1064    value.map_or(OwnedAttr::None, OwnedAttr::Text)
1065}
1066
1067/// The role and state of a Modifier as the one integer the `semantics` attribute carries,
1068/// or none when neither was given.
1069fn semantics_bits(modifier: &Modifier) -> Option<i64> {
1070    let state = modifier.semantics_state;
1071    if modifier.semantics_role.is_none() && state == SemanticsState::NONE {
1072        return None;
1073    }
1074    let role = i64::from(u16::from(
1075        modifier.semantics_role.unwrap_or(SemanticsRole::None),
1076    ));
1077    Some(role | (i64::from(state.bits()) << 16))
1078}
1079
1080/// Writes the Modifier attributes, in the order the `rsx!` widgets write them.
1081pub(crate) fn push_modifiers(modifier: &Modifier, mods: Mods, out: &mut Attrs) {
1082    let container = mods == Mods::Container;
1083    let standard = container || mods == Mods::Standard;
1084    let chip = standard || mods == Mods::Chip;
1085    let scaffold = mods == Mods::Scaffold;
1086    let mut push = |always: bool, name: &'static str, value: OwnedAttr| {
1087        let set = !matches!(value, OwnedAttr::None | OwnedAttr::Bool(false));
1088        if always || set {
1089            out.push((name, value));
1090        }
1091    };
1092    // One slot, two names: whichever is not in use goes out unset, which clears nothing
1093    // because only the name that wrote a slot may clear it.
1094    let (plain, every_dp) = match modifier.observe_size {
1095        Some(token) if modifier.observe_size_every_dp => (OwnedAttr::None, OwnedAttr::Int(token)),
1096        Some(token) => (OwnedAttr::Int(token), OwnedAttr::None),
1097        None => (OwnedAttr::None, OwnedAttr::None),
1098    };
1099    push(container, "observe_size", plain);
1100    push(container, "observe_size_every_dp", every_dp);
1101    push(container, "motion", role(modifier.motion));
1102    push(container || scaffold, "material", role(modifier.material));
1103    push(chip, "weight", float(modifier.weight));
1104    push(chip, "width", float(modifier.width));
1105    push(chip, "height", float(modifier.height));
1106    push(chip, "padding", float(modifier.padding));
1107    push(chip, "padding_role", role(modifier.padding_role));
1108    // An animated background owns the background's slot while it is set.
1109    push(
1110        standard || scaffold,
1111        "background",
1112        paint(if modifier.animated_background.is_some() {
1113            None
1114        } else {
1115            modifier.background
1116        }),
1117    );
1118    push(standard, "shape_role", role(modifier.shape_role));
1119    push(standard, "corner_radius", float(modifier.corner_radius));
1120    push(
1121        false,
1122        "corner_radii",
1123        modifier.corner_radii.map_or(OwnedAttr::None, |values| {
1124            OwnedAttr::Bytes(
1125                values
1126                    .iter()
1127                    .flat_map(|value| value.to_le_bytes())
1128                    .collect(),
1129            )
1130        }),
1131    );
1132    push(false, "corner_curve", float(modifier.corner_curve));
1133    push(false, "min_touch_target", float(modifier.min_touch_target));
1134    push(false, "overlay", paint(modifier.overlay));
1135    push(false, "clip", OwnedAttr::Bool(modifier.clip));
1136    push(
1137        true,
1138        "window_drag",
1139        modifier
1140            .window_drag
1141            .map_or(OwnedAttr::None, OwnedAttr::Bool),
1142    );
1143    push(standard, "border_width", float(modifier.border_width));
1144    push(standard, "border_color", paint(modifier.border_color));
1145    // Four widths and then four paints, written only when set. It shares the border's
1146    // slot, after the plain border, so whichever of the two the chain holds is the one
1147    // the slot ends up with.
1148    push(
1149        false,
1150        "border_each",
1151        modifier.border_each.map_or(OwnedAttr::None, |sides| {
1152            let mut bytes = Vec::with_capacity(48);
1153            for (width, _) in sides {
1154                bytes.extend_from_slice(&width.to_le_bytes());
1155            }
1156            for (_, paint) in sides {
1157                bytes.extend_from_slice(&paint.to_bits().to_le_bytes());
1158            }
1159            OwnedAttr::Bytes(bytes)
1160        }),
1161    );
1162    push(standard, "elevation", float(modifier.elevation));
1163    push(
1164        false,
1165        "match_parent_size",
1166        OwnedAttr::Bool(modifier.match_parent_size),
1167    );
1168    push(false, "sticky", OwnedAttr::Bool(modifier.sticky));
1169    push(
1170        chip,
1171        "fill_max_width",
1172        OwnedAttr::Bool(modifier.fill_max_width),
1173    );
1174    push(
1175        standard,
1176        "fill_max_height",
1177        OwnedAttr::Bool(modifier.fill_max_height),
1178    );
1179    push(
1180        false,
1181        "unbounded_width",
1182        OwnedAttr::Bool(modifier.unbounded_width),
1183    );
1184    // The layer and the values the Renderer animates, written only when they are set. An
1185    // animated value owns its slot while it is set, as an animated background does above.
1186    push(
1187        false,
1188        "press_feedback",
1189        modifier
1190            .press_feedback
1191            .map_or(OwnedAttr::None, |(scale, alpha)| {
1192                OwnedAttr::Bytes([scale.to_le_bytes(), alpha.to_le_bytes()].concat())
1193            }),
1194    );
1195    // The role and state travel as one integer, the role in the low 16 bits; the name is a
1196    // property of the node because a string does not fit in a modifier's words.
1197    push(
1198        false,
1199        "semantics",
1200        semantics_bits(modifier).map_or(OwnedAttr::None, OwnedAttr::Int),
1201    );
1202    push(
1203        false,
1204        "accessible_name",
1205        modifier
1206            .semantics_label
1207            .as_ref()
1208            .map_or(OwnedAttr::None, |label| OwnedAttr::Label(Arc::clone(label))),
1209    );
1210    push(
1211        false,
1212        "alpha",
1213        float(if modifier.animated_alpha.is_some() {
1214            None
1215        } else {
1216            modifier.alpha
1217        }),
1218    );
1219    push(
1220        false,
1221        "transform",
1222        match (modifier.animated_offset, modifier.transform) {
1223            (None, Some(values)) => OwnedAttr::Bytes(
1224                values
1225                    .iter()
1226                    .flat_map(|value| value.to_le_bytes())
1227                    .collect(),
1228            ),
1229            _ => OwnedAttr::None,
1230        },
1231    );
1232    // Written only when set, and `Auto` is the same as not set.
1233    push(
1234        false,
1235        "cursor",
1236        match modifier.cursor {
1237            Some(crate::Cursor::Auto) | None => OwnedAttr::None,
1238            Some(cursor) => OwnedAttr::Int(i64::from(u16::from(cursor))),
1239        },
1240    );
1241    push(
1242        false,
1243        "user_select",
1244        match modifier.user_select {
1245            Some(crate::UserSelect::Auto) | None => OwnedAttr::None,
1246            Some(select) => OwnedAttr::Int(i64::from(u16::from(select))),
1247        },
1248    );
1249    // The layers and the displacement, written only when they are set.
1250    push(
1251        false,
1252        "offset",
1253        modifier.offset.map_or(OwnedAttr::None, |(x, y)| {
1254            let mut bytes = Vec::with_capacity(8);
1255            bytes.extend_from_slice(&x.to_le_bytes());
1256            bytes.extend_from_slice(&y.to_le_bytes());
1257            OwnedAttr::Bytes(bytes)
1258        }),
1259    );
1260    push(
1261        false,
1262        "shadows",
1263        if modifier.shadows[0].is_none() {
1264            OwnedAttr::None
1265        } else {
1266            let mut bytes = Vec::new();
1267            for shadow in modifier.shadows.iter().flatten() {
1268                for value in [shadow.x, shadow.y, shadow.blur, shadow.spread] {
1269                    bytes.extend_from_slice(&value.to_le_bytes());
1270                }
1271                bytes.extend_from_slice(&shadow.paint.to_bits().to_le_bytes());
1272            }
1273            OwnedAttr::Bytes(bytes)
1274        },
1275    );
1276    push(
1277        false,
1278        "background_brushes",
1279        if modifier.background_brushes[0].is_none() {
1280            OwnedAttr::None
1281        } else {
1282            let mut bytes = Vec::new();
1283            for layer in modifier.background_brushes.iter().flatten() {
1284                for value in [layer.x, layer.y, layer.width, layer.height] {
1285                    bytes.extend_from_slice(&value.to_le_bytes());
1286                }
1287                bytes.extend_from_slice(&layer.paint.to_bits().to_le_bytes());
1288                bytes.extend_from_slice(&u32::from(u16::from(layer.repeat)).to_le_bytes());
1289                bytes.extend_from_slice(&layer.tile_width.to_le_bytes());
1290                bytes.extend_from_slice(&layer.tile_height.to_le_bytes());
1291                // Padding to the layer's 40 bytes, so a layer starts on an eight byte
1292                // boundary as the writer reads it.
1293                bytes.extend_from_slice(&[0; 4]);
1294            }
1295            OwnedAttr::Bytes(bytes)
1296        },
1297    );
1298    push(
1299        false,
1300        "animated_alpha",
1301        modifier.animated_alpha.map_or(OwnedAttr::None, |value| {
1302            OwnedAttr::Bytes(crate::animation::animated_bytes(
1303                &[value.target.to_bits()],
1304                &value.spec,
1305            ))
1306        }),
1307    );
1308    push(
1309        false,
1310        "animated_background",
1311        modifier
1312            .animated_background
1313            .map_or(OwnedAttr::None, |value| {
1314                let bits = value.target.to_bits();
1315                OwnedAttr::Bytes(crate::animation::animated_bytes(
1316                    &[bits as u32, (bits >> 32) as u32],
1317                    &value.spec,
1318                ))
1319            }),
1320    );
1321    push(
1322        false,
1323        "animated_offset",
1324        modifier.animated_offset.map_or(OwnedAttr::None, |value| {
1325            OwnedAttr::Bytes(crate::animation::animated_bytes(
1326                &[value.target.0.to_bits(), value.target.1.to_bits()],
1327                &value.spec,
1328            ))
1329        }),
1330    );
1331    push(
1332        false,
1333        "size_in",
1334        modifier
1335            .size_in
1336            .map_or(OwnedAttr::None, |[min_w, max_w, min_h, max_h]| {
1337                let mut bytes = Vec::with_capacity(16);
1338                bytes.extend_from_slice(&min_w.to_le_bytes());
1339                bytes.extend_from_slice(&max_w.to_le_bytes());
1340                bytes.extend_from_slice(&min_h.to_le_bytes());
1341                bytes.extend_from_slice(&max_h.to_le_bytes());
1342                OwnedAttr::Bytes(bytes)
1343            }),
1344    );
1345    push(
1346        false,
1347        "aspect_ratio",
1348        modifier
1349            .aspect_ratio
1350            .map_or(OwnedAttr::None, |(ratio, match_height)| {
1351                let mut bytes = Vec::with_capacity(5);
1352                bytes.extend_from_slice(&ratio.to_le_bytes());
1353                bytes.push(u8::from(match_height));
1354                OwnedAttr::Bytes(bytes)
1355            }),
1356    );
1357}
1358
1359/// Composes one widget node: its group, its attributes and listeners, and its children.
1360///
1361/// `fill` writes the attributes and runs while the composer is held, so it only moves
1362/// values out of the builder. `content` runs afterwards, with the node as the parent of
1363/// whatever it composes.
1364pub(crate) fn emit(
1365    key: u64,
1366    widget: WidgetKind,
1367    fill: impl FnOnce(&mut Attrs),
1368    listeners: Vec<(&'static str, EventCallback)>,
1369    content: impl FnOnce(),
1370) {
1371    let _group = group_guard(key);
1372    emit_node(widget, fill, listeners, content);
1373}
1374
1375/// The same, inside a group the caller has already opened, for a widget that remembers
1376/// something of its own before its node.
1377pub(crate) fn emit_node(
1378    widget: WidgetKind,
1379    fill: impl FnOnce(&mut Attrs),
1380    listeners: Vec<(&'static str, EventCallback)>,
1381    content: impl FnOnce(),
1382) {
1383    let node = with_composer_if_idle(|composer| {
1384        if !composer.composing() {
1385            return None;
1386        }
1387        let mut attrs = composer.take_attrs();
1388        fill(&mut attrs);
1389        Some(composer.update_node(widget, attrs, listeners))
1390    })
1391    .flatten();
1392    let Some(node) = node else {
1393        return;
1394    };
1395    with_composer(|composer| composer.push_node_context(node));
1396    let _context = NodeContextGuard;
1397    content();
1398}
1399
1400/// Closes a widget's node context on every way out of its content, an unwind included.
1401struct NodeContextGuard;
1402
1403impl Drop for NodeContextGuard {
1404    fn drop(&mut self) {
1405        with_composer_if_idle(|composer| composer.pop_node_context());
1406    }
1407}
1408
1409/// A call site key for a widget, from its name.
1410pub(crate) const fn widget_key(name: &str) -> u64 {
1411    crate::runtime::composer::call_site(name, 0)
1412}
1413
1414#[cfg(test)]
1415mod fr19_9_tests {
1416    use super::*;
1417
1418    #[test]
1419    fn fr19_9_window_drag_builder_preserves_false() {
1420        for enabled in [false, true] {
1421            let mut attrs = Vec::new();
1422            push_modifiers(
1423                &Modifier::new().window_drag(enabled),
1424                Mods::Standard,
1425                &mut attrs,
1426            );
1427            assert!(attrs.iter().any(|(name, value)| *name == "window_drag"
1428                && matches!(value, OwnedAttr::Bool(value) if *value == enabled)));
1429        }
1430    }
1431}
1432
1433#[cfg(test)]
1434mod fr68_label_tests {
1435    use super::*;
1436
1437    #[test]
1438    fn fr68_repeated_labels_do_not_grow_the_cache() {
1439        let mut cache = LabelCache::new();
1440        let first = cache.intern("Refresh");
1441        for _ in 0..10_000 {
1442            let again = cache.intern("Refresh");
1443            assert!(Arc::ptr_eq(&first, &again));
1444        }
1445        assert_eq!(cache.len(), 1);
1446    }
1447
1448    #[test]
1449    fn fr68_cache_evicts_old_entries_without_dropping_new_labels() {
1450        let mut cache = LabelCache::with_capacity(32);
1451        for n in 0..100 {
1452            let label = cache.intern(&format!("label {n}"));
1453            assert_eq!(label.as_ref(), format!("label {n}"));
1454        }
1455        assert_eq!(cache.len(), 32);
1456        // An old entry evicted earlier can still be interned again as new.
1457        let re_interned = cache.intern("label 0");
1458        assert_eq!(re_interned.as_ref(), "label 0");
1459        assert_eq!(cache.len(), 32);
1460    }
1461}