Skip to main content

compose_rust/ui/
widgets.rs

1//! One composable per widget in the schema.
2//!
3//! Each is a function with the widget's Compose name that takes what the widget cannot do
4//! without, and returns a description whose methods set the rest. The description is
5//! composed when the statement it is written in ends, or at once by `content` for a
6//! widget that has children.
7//!
8//! Every attribute list below is the `rsx!` widget's, in its order, with its defaults. A
9//! difference would be a widget that draws differently depending on which API wrote it.
10
11#![allow(non_snake_case)]
12
13use super::{
14    Attrs, Modifier, Mods, dp_or_zero, emit, optional_text, paint_or_zero, push_modifiers,
15    role_or_zero, widget_key,
16};
17use crate::asset::AssetId;
18use crate::drawing::DrawList;
19use crate::font_features::FontFeature;
20use crate::fonts::FontRefs;
21use crate::runtime::composer::{EventCallback, OwnedAttr};
22use crate::schema::{
23    Alignment, Arrangement, ButtonKind, ButtonVariant, ColorRole, CompactNavigation, ContentScale,
24    HorizontalAlignment, IconRole, OverflowWrap, Paint, PopoverAlign, PopoverPlacement,
25    SheetPresentation, SlotRole, Snap, SpaceRole, TextAlign, TextOverflow, TypeRole,
26    VerticalAlignment, WidgetKind, WordBreak,
27};
28use crate::spans::TextSpans;
29use crate::{FileDrop, KeyEvent, MotionFinished, PointerEvent, PointerKinds};
30use std::cell::RefCell;
31use std::rc::Rc;
32
33/// The empty handler every listener has until one is given. The `rsx!` widgets write
34/// their listeners whether or not a handler was supplied, so these do too.
35fn unit(handler: Option<Box<dyn FnMut()>>) -> EventCallback {
36    match handler {
37        Some(handler) => EventCallback::Unit(Rc::new(RefCell::new(handler))),
38        None => EventCallback::Unit(Rc::new(RefCell::new(|| {}))),
39    }
40}
41
42fn text_handler(handler: Option<Box<dyn FnMut(String)>>) -> EventCallback {
43    match handler {
44        Some(handler) => EventCallback::Text(Rc::new(RefCell::new(handler))),
45        None => EventCallback::Text(Rc::new(RefCell::new(|_: String| {}))),
46    }
47}
48
49fn value_handler(handler: Option<Box<dyn FnMut(f64)>>) -> EventCallback {
50    match handler {
51        Some(handler) => EventCallback::Value(Rc::new(RefCell::new(handler))),
52        None => EventCallback::Value(Rc::new(RefCell::new(|_: f64| {}))),
53    }
54}
55
56/// A node's subscription to pointer input: the kinds it wants and the handler that gets
57/// them. A node without one has no pointer input at all.
58struct PointerSubscription {
59    kinds: PointerKinds,
60    handler: Box<dyn FnMut(PointerEvent)>,
61}
62
63/// Writes a subscription as the two things the wire needs: the handler, and the mask. A
64/// subscription of no kinds writes neither, so it is not a subscription.
65fn pointer_input(
66    subscription: Option<PointerSubscription>,
67    attrs: &mut Attrs,
68    listeners: &mut Vec<(&'static str, EventCallback)>,
69) {
70    let Some(subscription) = subscription else {
71        return;
72    };
73    if subscription.kinds == PointerKinds::NONE {
74        return;
75    }
76    attrs.push((
77        "pointer_kinds",
78        OwnedAttr::Int(i64::from(subscription.kinds.bits())),
79    ));
80    listeners.push((
81        "onpointer",
82        EventCallback::Pointer(Rc::new(RefCell::new(subscription.handler))),
83    ));
84}
85
86/// What a node says about windows that is not a window's own: the key it is torn
87/// off under, and the handler for a dragged window passing over it.
88struct TearOff {
89    key: Option<String>,
90    drag_over: Option<Box<dyn FnMut(crate::windows::WindowDragOver)>>,
91}
92
93/// Writes a node's tear-off key and drag-over handler as what the wire needs. A node with
94/// neither writes nothing.
95fn tear_off_input(
96    tear_off: Option<TearOff>,
97    attrs: &mut Attrs,
98    listeners: &mut Vec<(&'static str, EventCallback)>,
99) {
100    let Some(tear_off) = tear_off else {
101        return;
102    };
103    if let Some(key) = tear_off.key {
104        attrs.push(("tear_off_key", OwnedAttr::Text(key)));
105    }
106    if let Some(mut handler) = tear_off.drag_over {
107        listeners.push((
108            "onwindowdragover",
109            EventCallback::Window(Rc::new(RefCell::new(
110                move |event: crate::windows::WindowEvent| {
111                    if let crate::windows::WindowEvent::DragOver { kind, window, x, y } = event {
112                        handler(crate::windows::WindowDragOver { kind, window, x, y });
113                    }
114                },
115            ))),
116        ));
117    }
118}
119
120/// Adds `tear_off_key` and `on_window_drag_over` to a builder that has a `tear_off` field.
121macro_rules! tear_off {
122    ($name:ident) => {
123        impl $name {
124            /// Lets the user pull this node out into a window of its own, named by `key`:
125            /// the `RestoreKey` of the window that results.
126            pub fn tear_off_key(mut self, key: impl Into<String>) -> Self {
127                self.tear_off
128                    .get_or_insert_with(|| TearOff {
129                        key: None,
130                        drag_over: None,
131                    })
132                    .key = Some(key.into());
133                self
134            }
135
136            /// Hears a dragged window pass over this node: where a tab row shows the place
137            /// a dropped tab would go.
138            pub fn on_window_drag_over(
139                mut self,
140                handler: impl FnMut(crate::windows::WindowDragOver) + 'static,
141            ) -> Self {
142                self.tear_off
143                    .get_or_insert_with(|| TearOff {
144                        key: None,
145                        drag_over: None,
146                    })
147                    .drag_over = Some(std::boxed::Box::new(handler));
148                self
149            }
150        }
151    };
152}
153
154/// Adds `on_pointer` to a builder that has a `pointer` field.
155macro_rules! pointer_subscription {
156    ($name:ident) => {
157        impl $name {
158            /// Subscribes the node to the kinds of pointer input in `kinds`. The handler runs
159            /// on the same call as the input; calling `consume` on the event keeps it from
160            /// the nearest subscribed ancestor and from the Renderer's own handling.
161            ///
162            /// A node that never calls this has no pointer input at all, and costs nothing.
163            pub fn on_pointer(
164                mut self,
165                kinds: PointerKinds,
166                handler: impl FnMut(PointerEvent) + 'static,
167            ) -> Self {
168                self.pointer = Some(PointerSubscription {
169                    kinds,
170                    handler: std::boxed::Box::new(handler),
171                });
172                self
173            }
174        }
175    };
176}
177
178/// Writes a container's click handler as the listener the wire needs. A container that was
179/// given none has no `OnClick` at all, so it is not a control: it takes no focus, no key and
180/// no pointer press, and says nothing to assistive technology.
181fn click_input(
182    on_click: Option<Box<dyn FnMut()>>,
183    listeners: &mut Vec<(&'static str, EventCallback)>,
184) {
185    if let Some(handler) = on_click {
186        listeners.push(("onclick", unit(Some(handler))));
187    }
188}
189
190/// Adds `on_click` to a builder that has an `on_click` field.
191macro_rules! click_handler {
192    ($name:ident) => {
193        impl $name {
194            /// Makes the container a button. The Renderer gives it keyboard focus, runs
195            /// the handler on a click and on Enter or Space, announces it to assistive
196            /// technology as a button, and shows hover, pressed and focus state.
197            ///
198            /// A container that never calls this is not a control and costs nothing.
199            pub fn on_click(mut self, handler: impl FnMut() + 'static) -> Self {
200                self.on_click = Some(std::boxed::Box::new(handler));
201                self
202            }
203        }
204    };
205}
206
207/// Optional focus and key handlers on a node. A node that registers none of these
208/// emits no focus or key listener property on the wire.
209#[derive(Default)]
210struct FocusAndKeyHandlers {
211    on_focus_gained: Option<Box<dyn FnMut()>>,
212    on_focus_lost: Option<Box<dyn FnMut()>>,
213    on_key_down: Option<Box<dyn FnMut(KeyEvent)>>,
214    on_key_up: Option<Box<dyn FnMut(KeyEvent)>>,
215    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
216    focus_handle: Option<super::FocusHandle>,
217}
218
219/// Writes a motion handler as the listener the wire needs. A node that was given none has
220/// no `OnMotionFinished` at all, and the Renderer attaches nothing to its size motion.
221pub(super) fn motion_input(
222    handler: Option<Box<dyn FnMut(MotionFinished)>>,
223    listeners: &mut Vec<(&'static str, EventCallback)>,
224) {
225    if let Some(handler) = handler {
226        listeners.push((
227            "onmotionfinished",
228            EventCallback::Motion(Rc::new(RefCell::new(handler))),
229        ));
230    }
231}
232
233/// A widget's own listeners with its motion handler after them, if it was given one.
234fn with_motion(
235    mut listeners: Vec<(&'static str, EventCallback)>,
236    handler: Option<Box<dyn FnMut(MotionFinished)>>,
237) -> Vec<(&'static str, EventCallback)> {
238    motion_input(handler, &mut listeners);
239    listeners
240}
241
242/// Adds `on_motion_finished` to a builder that has an `on_motion_finished` field. The
243/// containers that take focus and key handlers get theirs from `focus_and_key_handlers`.
244macro_rules! motion_handler {
245    ($name:ident $(<$lifetime:lifetime>)?) => {
246        impl$(<$lifetime>)? $name$(<$lifetime>)? {
247            /// Runs once when this node's size motion comes to rest, with the size it settled
248            /// at in dp. The node needs `Modifier::motion` for its size to move; without it
249            /// nothing is reported. A run interrupted by a newer size is not reported, only
250            /// the one that settles, and under reduced motion it arrives in the frame the
251            /// size changes in.
252            pub fn on_motion_finished(
253                mut self,
254                handler: impl FnMut(MotionFinished) + 'static,
255            ) -> Self {
256                self.on_motion_finished = Some(std::boxed::Box::new(handler));
257                self
258            }
259        }
260    };
261}
262
263/// Turns the handlers into listeners and binds the focus handle, if there is one, to the
264/// node the widget is about to emit, so it is called right before that `emit`.
265fn focus_and_key_input(
266    mut handlers: FocusAndKeyHandlers,
267    listeners: &mut Vec<(&'static str, EventCallback)>,
268) {
269    super::focus::bind_focus_handle(handlers.focus_handle.take());
270    if let Some(handler) = handlers.on_focus_gained.take() {
271        listeners.push(("onfocusgained", unit(Some(handler))));
272    }
273    if let Some(handler) = handlers.on_focus_lost.take() {
274        listeners.push(("onfocuslost", unit(Some(handler))));
275    }
276    if let Some(handler) = handlers.on_key_down.take() {
277        listeners.push((
278            "onkeydown",
279            EventCallback::Key(Rc::new(RefCell::new(handler))),
280        ));
281    }
282    if let Some(handler) = handlers.on_key_up.take() {
283        listeners.push((
284            "onkeyup",
285            EventCallback::Key(Rc::new(RefCell::new(handler))),
286        ));
287    }
288    motion_input(handlers.on_motion_finished.take(), listeners);
289}
290
291macro_rules! focus_and_key_handlers {
292    ($name:ident) => {
293        impl $name {
294            /// Runs when this node or a descendant inside it gains keyboard focus.
295            pub fn on_focus_gained(mut self, handler: impl FnMut() + 'static) -> Self {
296                self.focus_and_keys.on_focus_gained = Some(std::boxed::Box::new(handler));
297                self
298            }
299
300            /// Runs when this node and its descendants lose keyboard focus.
301            pub fn on_focus_lost(mut self, handler: impl FnMut() + 'static) -> Self {
302                self.focus_and_keys.on_focus_lost = Some(std::boxed::Box::new(handler));
303                self
304            }
305
306            /// Sees each key pressed while this node or a descendant inside it holds focus;
307            /// calling `consume` on the event keeps the Renderer from acting on it.
308            pub fn on_key_down(mut self, handler: impl FnMut(KeyEvent) + 'static) -> Self {
309                self.focus_and_keys.on_key_down = Some(std::boxed::Box::new(handler));
310                self
311            }
312
313            /// Sees each key released while this node or a descendant inside it holds focus.
314            pub fn on_key_up(mut self, handler: impl FnMut(KeyEvent) + 'static) -> Self {
315                self.focus_and_keys.on_key_up = Some(std::boxed::Box::new(handler));
316                self
317            }
318
319            /// Binds `handle` to this node, so `handle.request()` puts keyboard focus here.
320            pub fn focus_handle(mut self, handle: &super::FocusHandle) -> Self {
321                self.focus_and_keys.focus_handle = Some(handle.clone());
322                self
323            }
324
325            /// Runs once when this node's size motion comes to rest, with the size it settled
326            /// at in dp. The node needs `Modifier::motion` for its size to move; without it
327            /// nothing is reported. A run interrupted by a newer size is not reported, only
328            /// the one that settles, and under reduced motion it arrives in the frame the
329            /// size changes in.
330            pub fn on_motion_finished(
331                mut self,
332                handler: impl FnMut(MotionFinished) + 'static,
333            ) -> Self {
334                self.focus_and_keys.on_motion_finished = Some(std::boxed::Box::new(handler));
335                self
336            }
337        }
338    };
339}
340
341/// Composes the description when the statement it was written in ends.
342macro_rules! composed_on_drop {
343    ($name:ident $(<$lifetime:lifetime>)?) => {
344        impl$(<$lifetime>)? Drop for $name$(<$lifetime>)? {
345            fn drop(&mut self) {
346                // A panic is already unwinding the composition, and composing on the way
347                // out would only risk a second one.
348                if !self.done && !std::thread::panicking() {
349                    self.done = true;
350                    self.compose(|| {});
351                }
352            }
353        }
354
355        impl$(<$lifetime>)? $name$(<$lifetime>)? {
356            /// What sits around it. Compose's `modifier` parameter.
357            pub fn modifier(mut self, modifier: Modifier) -> Self {
358                self.modifier = modifier;
359                self
360            }
361        }
362    };
363}
364
365/// A container's `content`: composes it now, with these children.
366macro_rules! container {
367    ($name:ident $(<$lifetime:lifetime>)?) => {
368        composed_on_drop!($name $(<$lifetime>)?);
369
370        impl$(<$lifetime>)? $name$(<$lifetime>)? {
371            /// Composes this widget with `content` as its children.
372            pub fn content(mut self, content: impl FnOnce()) {
373                self.done = true;
374                self.compose(content);
375            }
376        }
377    };
378}
379
380// ----- layout ---------------------------------------------------------------------------
381
382/// The properties a linear layout takes.
383#[derive(Default)]
384struct Linear {
385    arrangement: Option<Arrangement>,
386    spacing: Option<f32>,
387    space_role: Option<SpaceRole>,
388    alignment: Option<Alignment>,
389    intrinsic_size: Option<bool>,
390    radio_group: bool,
391}
392
393impl Linear {
394    fn push(&self, attrs: &mut Attrs) {
395        attrs.push(("arrangement", role_or_zero(self.arrangement)));
396        attrs.push(("spacing", dp_or_zero(self.spacing)));
397        attrs.push(("space_role", role_or_zero(self.space_role)));
398        attrs.push(("alignment", role_or_zero(self.alignment)));
399        if let Some(intrinsic) = self.intrinsic_size {
400            attrs.push(("collapsible", OwnedAttr::Bool(intrinsic)));
401        }
402        // Written only for a group, so a plain layout sends what it always did.
403        if self.radio_group {
404            attrs.push(("radio_group", OwnedAttr::Bool(true)));
405        }
406    }
407}
408
409macro_rules! linear {
410    ($name:ident, $widget:ident, $key:literal) => {
411        #[doc = concat!("A `", stringify!($widget), "` and its builder.")]
412        pub struct $name {
413            modifier: Modifier,
414            linear: Linear,
415            pointer: Option<PointerSubscription>,
416            on_click: Option<Box<dyn FnMut()>>,
417            focus_and_keys: FocusAndKeyHandlers,
418            tear_off: Option<TearOff>,
419            done: bool,
420        }
421
422        #[doc = concat!("Lays its children out one after another. Compose's `", stringify!($widget), "`.")]
423        pub fn $widget() -> $name {
424            $name {
425                modifier: Modifier::new(),
426                linear: Linear::default(),
427                pointer: None,
428                on_click: None,
429                focus_and_keys: FocusAndKeyHandlers::default(),
430                tear_off: None,
431                done: false,
432            }
433        }
434
435        impl $name {
436            /// How the children share the main axis.
437            pub fn arrangement(mut self, arrangement: Arrangement) -> Self {
438                self.linear.arrangement = Some(arrangement);
439                self
440            }
441
442            /// A literal gap between children, in dp.
443            pub fn spacing(mut self, dp: f32) -> Self {
444                self.linear.spacing = Some(dp);
445                self
446            }
447
448            /// A gap from the design system's spacing ladder.
449            pub fn space_role(mut self, role: SpaceRole) -> Self {
450                self.linear.space_role = Some(role);
451                self
452            }
453
454            /// Where the children sit on the cross axis.
455            pub fn alignment(mut self, alignment: Alignment) -> Self {
456                self.linear.alignment = Some(alignment);
457                self
458            }
459
460            /// Sizes the cross axis to the tallest child in a `Row` or the widest child in
461            /// a `Column`, so children with `fill_max_height` or `fill_max_width` match the
462            /// largest sibling without an explicit container size.
463            pub fn intrinsic_size(mut self, enabled: bool) -> Self {
464                self.linear.intrinsic_size = Some(enabled);
465                self
466            }
467
468            /// Makes this layout a group of the `RadioButton`s inside it.
469            ///
470            /// The group is one stop for Tab: the selected button, or the first when none
471            /// is. The arrow keys move focus to the next or the previous button, wrapping
472            /// at the ends, and each move sends that button's `on_change(true)` once, the
473            /// same report a click sends. Which button is selected is still the
474            /// application's to decide. Assistive technology hears the layout as a radio
475            /// group.
476            pub fn radio_group(mut self, enabled: bool) -> Self {
477                self.linear.radio_group = enabled;
478                self
479            }
480
481            fn compose(&mut self, content: impl FnOnce()) {
482                let modifier = std::mem::take(&mut self.modifier);
483                let linear = std::mem::take(&mut self.linear);
484                let pointer = self.pointer.take();
485                let tear_off = self.tear_off.take();
486                let mut listeners = Vec::new();
487                let mut subscription = Attrs::new();
488                pointer_input(pointer, &mut subscription, &mut listeners);
489                click_input(self.on_click.take(), &mut listeners);
490                focus_and_key_input(std::mem::take(&mut self.focus_and_keys), &mut listeners);
491                tear_off_input(tear_off, &mut subscription, &mut listeners);
492                emit(
493                    widget_key($key),
494                    WidgetKind::$widget,
495                    |attrs| {
496                        push_modifiers(&modifier, Mods::Container, attrs);
497                        linear.push(attrs);
498                        attrs.append(&mut subscription);
499                    },
500                    listeners,
501                    content,
502                );
503            }
504        }
505
506        container!($name);
507        pointer_subscription!($name);
508        click_handler!($name);
509        focus_and_key_handlers!($name);
510        tear_off!($name);
511    };
512}
513
514linear!(ColumnScope, Column, "compose_rust::ui::Column");
515linear!(RowScope, Row, "compose_rust::ui::Row");
516
517impl RowScope {
518    /// Sizes the row to its tallest child so children with `fill_max_height` match their
519    /// siblings' height.
520    pub fn equal_height(self, enabled: bool) -> Self {
521        self.intrinsic_size(enabled)
522    }
523}
524
525impl ColumnScope {
526    /// Sizes the column to its widest child so children with `fill_max_width` match their
527    /// siblings' width.
528    pub fn equal_width(self, enabled: bool) -> Self {
529        self.intrinsic_size(enabled)
530    }
531}
532
533/// A `FlowRow` and its builder.
534pub struct FlowRowScope {
535    modifier: Modifier,
536    horizontal_spacing: Option<f32>,
537    vertical_spacing: Option<f32>,
538    horizontal_alignment: Option<HorizontalAlignment>,
539    vertical_alignment: Option<VerticalAlignment>,
540    max_items_in_each_row: Option<u32>,
541    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
542    done: bool,
543}
544
545/// Lays its children out on a line and starts a new line when the next child does not fit
546/// in what is left of it. Each child is measured at its own width, so a line breaks where
547/// the text really ends rather than where an estimate put it. A child wider than the whole
548/// line has the line to itself and is measured at the line's width. Compose's `FlowRow`.
549pub fn FlowRow() -> FlowRowScope {
550    FlowRowScope {
551        modifier: Modifier::new(),
552        horizontal_spacing: None,
553        vertical_spacing: None,
554        horizontal_alignment: None,
555        vertical_alignment: None,
556        max_items_in_each_row: None,
557        on_motion_finished: None,
558        done: false,
559    }
560}
561
562impl FlowRowScope {
563    /// The gap between two children on the same line, in dp.
564    pub fn horizontal_spacing(mut self, dp: f32) -> Self {
565        self.horizontal_spacing = Some(dp);
566        self
567    }
568
569    /// The gap between two lines, in dp.
570    pub fn vertical_spacing(mut self, dp: f32) -> Self {
571        self.vertical_spacing = Some(dp);
572        self
573    }
574
575    /// Where the children of a line sit along it when they do not fill it. `Start` when
576    /// not set.
577    pub fn horizontal_alignment(mut self, alignment: HorizontalAlignment) -> Self {
578        self.horizontal_alignment = Some(alignment);
579        self
580    }
581
582    /// Where a child sits inside the height of its line. `Top` when not set.
583    pub fn vertical_alignment(mut self, alignment: VerticalAlignment) -> Self {
584        self.vertical_alignment = Some(alignment);
585        self
586    }
587
588    /// The most children one line holds, even when more would fit. No limit when not set.
589    pub fn max_items_in_each_row(mut self, count: u32) -> Self {
590        self.max_items_in_each_row = Some(count);
591        self
592    }
593
594    fn compose(&mut self, content: impl FnOnce()) {
595        let modifier = std::mem::take(&mut self.modifier);
596        let (horizontal_spacing, vertical_spacing) =
597            (self.horizontal_spacing, self.vertical_spacing);
598        let (horizontal_alignment, vertical_alignment) =
599            (self.horizontal_alignment, self.vertical_alignment);
600        let max_items = self.max_items_in_each_row;
601        let motion = self.on_motion_finished.take();
602        emit(
603            widget_key("compose_rust::ui::FlowRow"),
604            WidgetKind::FlowRow,
605            |attrs| {
606                push_modifiers(&modifier, Mods::Container, attrs);
607                // Only what was set is written: an absent property is the Renderer's
608                // default, and a zero gap or tag would say nothing an absent one does not.
609                if let Some(dp) = horizontal_spacing {
610                    attrs.push(("horizontal_spacing", dp_or_zero(Some(dp))));
611                }
612                if let Some(dp) = vertical_spacing {
613                    attrs.push(("vertical_spacing", dp_or_zero(Some(dp))));
614                }
615                if let Some(alignment) = horizontal_alignment {
616                    attrs.push(("horizontal_alignment", role_or_zero(Some(alignment))));
617                }
618                if let Some(alignment) = vertical_alignment {
619                    attrs.push(("vertical_alignment", role_or_zero(Some(alignment))));
620                }
621                if let Some(count) = max_items {
622                    attrs.push(("max_items_in_each_row", OwnedAttr::Int(i64::from(count))));
623                }
624            },
625            with_motion(Vec::new(), motion),
626            content,
627        );
628    }
629}
630
631container!(FlowRowScope);
632motion_handler!(FlowRowScope);
633
634/// A `Box` and its builder. Named apart from `std::boxed::Box`, which a glob import of
635/// this module would otherwise hide.
636pub struct ComposeBox {
637    modifier: Modifier,
638    alignment: Option<Alignment>,
639    pointer: Option<PointerSubscription>,
640    on_click: Option<Box<dyn FnMut()>>,
641    focus_and_keys: FocusAndKeyHandlers,
642    tear_off: Option<TearOff>,
643    done: bool,
644}
645
646/// Stacks its children on top of each other. Compose's `Box`.
647pub fn Box() -> ComposeBox {
648    ComposeBox {
649        modifier: Modifier::new(),
650        alignment: None,
651        pointer: None,
652        on_click: None,
653        focus_and_keys: FocusAndKeyHandlers::default(),
654        tear_off: None,
655        done: false,
656    }
657}
658
659impl ComposeBox {
660    /// Where the children sit inside it.
661    pub fn alignment(mut self, alignment: Alignment) -> Self {
662        self.alignment = Some(alignment);
663        self
664    }
665
666    fn compose(&mut self, content: impl FnOnce()) {
667        let (modifier, alignment) = (std::mem::take(&mut self.modifier), self.alignment);
668        let pointer = self.pointer.take();
669        let tear_off = self.tear_off.take();
670        let mut listeners = Vec::new();
671        let mut subscription = Attrs::new();
672        pointer_input(pointer, &mut subscription, &mut listeners);
673        click_input(self.on_click.take(), &mut listeners);
674        focus_and_key_input(std::mem::take(&mut self.focus_and_keys), &mut listeners);
675        tear_off_input(tear_off, &mut subscription, &mut listeners);
676        emit(
677            widget_key("compose_rust::ui::Box"),
678            WidgetKind::Box,
679            |attrs| {
680                push_modifiers(&modifier, Mods::Container, attrs);
681                attrs.push(("alignment", role_or_zero(alignment)));
682                attrs.append(&mut subscription);
683            },
684            listeners,
685            content,
686        );
687    }
688}
689
690container!(ComposeBox);
691pointer_subscription!(ComposeBox);
692click_handler!(ComposeBox);
693focus_and_key_handlers!(ComposeBox);
694tear_off!(ComposeBox);
695
696/// A plain container with the standard Modifiers and nothing of its own.
697macro_rules! plain_container {
698    ($name:ident, $widget:ident, $mods:expr, $key:literal, $doc:literal) => {
699        #[doc = concat!("A `", stringify!($widget), "` and its builder.")]
700        pub struct $name {
701            modifier: Modifier,
702            pointer: Option<PointerSubscription>,
703            on_click: Option<Box<dyn FnMut()>>,
704            focus_and_keys: FocusAndKeyHandlers,
705            done: bool,
706        }
707
708        #[doc = $doc]
709        pub fn $widget() -> $name {
710            $name {
711                modifier: Modifier::new(),
712                pointer: None,
713                on_click: None,
714                focus_and_keys: FocusAndKeyHandlers::default(),
715                done: false,
716            }
717        }
718
719        impl $name {
720            fn compose(&mut self, content: impl FnOnce()) {
721                let modifier = std::mem::take(&mut self.modifier);
722                let pointer = self.pointer.take();
723                let mut listeners = Vec::new();
724                let mut subscription = Attrs::new();
725                pointer_input(pointer, &mut subscription, &mut listeners);
726                click_input(self.on_click.take(), &mut listeners);
727                focus_and_key_input(std::mem::take(&mut self.focus_and_keys), &mut listeners);
728                emit(
729                    widget_key($key),
730                    WidgetKind::$widget,
731                    |attrs| {
732                        push_modifiers(&modifier, $mods, attrs);
733                        attrs.append(&mut subscription);
734                    },
735                    listeners,
736                    content,
737                );
738            }
739        }
740
741        container!($name);
742        pointer_subscription!($name);
743        click_handler!($name);
744        focus_and_key_handlers!($name);
745    };
746}
747
748/// The scroll position of a [`ScrollColumn`] or [`ScrollRow`], and a handle to move it.
749///
750/// The Renderer owns the scroll physics and the scrollbar; this handle reads the current
751/// offset and maximum offset in dp as observable states and sends target scroll requests.
752#[derive(Clone, Debug, PartialEq, Eq)]
753pub struct ScrollState {
754    offset: crate::runtime::MutableState<f32>,
755    max_offset: crate::runtime::MutableState<f32>,
756    command: crate::runtime::MutableState<(i64, f32, bool)>,
757}
758
759impl Default for ScrollState {
760    fn default() -> Self {
761        Self::new()
762    }
763}
764
765impl ScrollState {
766    /// Creates a new scroll state starting at 0 dp.
767    pub fn new() -> Self {
768        Self {
769            offset: crate::runtime::mutable_state_of(0.0),
770            max_offset: crate::runtime::mutable_state_of(0.0),
771            command: crate::runtime::mutable_state_of((0, 0.0, false)),
772        }
773    }
774
775    /// The current scroll offset in dp. A composable that reads this runs again when the
776    /// user or a programmatic scroll moves the container.
777    pub fn offset(&self) -> f32 {
778        self.offset.get()
779    }
780
781    /// The furthest offset in dp the container can scroll to (`0.0` when the content fits
782    /// inside the viewport). A composable that reads this runs again when the content or
783    /// viewport size changes the scrollable distance.
784    pub fn max_offset(&self) -> f32 {
785        self.max_offset.get()
786    }
787
788    /// Jumps to `dp` (clamped by the Renderer to `0.0..=max_offset`).
789    pub fn scroll_to(&self, dp: f32) {
790        let (revision, _, _) = self.command.get_untracked();
791        self.command
792            .set((revision.wrapping_add(1).max(1), dp.max(0.0), false));
793    }
794
795    /// Smoothly scrolls to `dp` (clamped by the Renderer to `0.0..=max_offset`).
796    pub fn animate_scroll_to(&self, dp: f32) {
797        let (revision, _, _) = self.command.get_untracked();
798        self.command
799            .set((revision.wrapping_add(1).max(1), dp.max(0.0), true));
800    }
801}
802
803/// Remembers a [`ScrollState`] across recompositions. Compose's `rememberScrollState`.
804pub fn remember_scroll_state() -> ScrollState {
805    crate::runtime::remember(ScrollState::new)
806}
807
808fn scroll_state_input(
809    state: Option<ScrollState>,
810    attrs: &mut Attrs,
811    listeners: &mut Vec<(&'static str, EventCallback)>,
812) {
813    let Some(state) = state else {
814        return;
815    };
816    let (revision, target, animate) = state.command.get();
817    if revision > 0 {
818        attrs.push(("value", OwnedAttr::Float(f64::from(target))));
819        attrs.push(("determinate", OwnedAttr::Bool(animate)));
820        attrs.push(("count", OwnedAttr::Int(revision)));
821    }
822    let offset = state.offset;
823    let max_offset = state.max_offset;
824    listeners.push((
825        "onrangerequest",
826        EventCallback::Range(Rc::new(RefCell::new(move |range: crate::RangeRequest| {
827            let next_offset = f32::from_bits(range.start() as u32);
828            let next_max = f32::from_bits(range.count() as u32);
829            if next_offset.is_finite() {
830                offset.set(next_offset);
831            }
832            if next_max.is_finite() {
833                max_offset.set(next_max);
834            }
835        }))),
836    ));
837}
838
839macro_rules! scroll_container {
840    ($name:ident, $widget:ident, $key:literal, $doc:literal) => {
841        #[doc = concat!("A `", stringify!($widget), "` and its builder.")]
842        pub struct $name {
843            modifier: Modifier,
844            scroll_state: Option<ScrollState>,
845            snap: Snap,
846            pointer: Option<PointerSubscription>,
847            on_click: Option<Box<dyn FnMut()>>,
848            focus_and_keys: FocusAndKeyHandlers,
849            done: bool,
850        }
851
852        #[doc = $doc]
853        pub fn $widget() -> $name {
854            $name {
855                modifier: Modifier::new(),
856                scroll_state: None,
857                snap: Snap::None,
858                pointer: None,
859                on_click: None,
860                focus_and_keys: FocusAndKeyHandlers::default(),
861                done: false,
862            }
863        }
864
865        impl $name {
866            /// Binds a [`ScrollState`] so the application can read `offset()` and
867            /// `max_offset()` or call `scroll_to` and `animate_scroll_to`.
868            pub fn scroll_state(mut self, state: &ScrollState) -> Self {
869                self.scroll_state = Some(state.clone());
870                self
871            }
872
873            /// Where the content comes to rest once a drag or a fling ends.
874            ///
875            /// `Snap::None`, the default, stops wherever the user left it.
876            /// `Snap::ItemStart` stops with the start edge of the nearest direct child on
877            /// the start of the visible area, like CSS `scroll-snap-align: start`. The
878            /// Renderer runs the snap, so it follows the platform's fling physics.
879            pub fn snap(mut self, snap: Snap) -> Self {
880                self.snap = snap;
881                self
882            }
883
884            fn compose(&mut self, content: impl FnOnce()) {
885                let modifier = std::mem::take(&mut self.modifier);
886                let snap = self.snap;
887                let scroll_state = self.scroll_state.take();
888                let pointer = self.pointer.take();
889                let mut listeners = Vec::new();
890                let mut subscription = Attrs::new();
891                scroll_state_input(scroll_state, &mut subscription, &mut listeners);
892                pointer_input(pointer, &mut subscription, &mut listeners);
893                click_input(self.on_click.take(), &mut listeners);
894                focus_and_key_input(std::mem::take(&mut self.focus_and_keys), &mut listeners);
895                emit(
896                    widget_key($key),
897                    WidgetKind::$widget,
898                    |attrs| {
899                        push_modifiers(&modifier, Mods::Standard, attrs);
900                        // Free scrolling is the default, and the default is not sent: a
901                        // container that says nothing travels as it did before snapping.
902                        if snap != Snap::None {
903                            attrs.push(("snap", OwnedAttr::Int(i64::from(u16::from(snap)))));
904                        }
905                        attrs.append(&mut subscription);
906                    },
907                    listeners,
908                    content,
909                );
910            }
911        }
912
913        container!($name);
914        pointer_subscription!($name);
915        click_handler!($name);
916        focus_and_key_handlers!($name);
917    };
918}
919
920scroll_container!(
921    ScrollColumnScope,
922    ScrollColumn,
923    "compose_rust::ui::ScrollColumn",
924    "All of its content, with a vertical scroll the Renderer owns."
925);
926scroll_container!(
927    ScrollRowScope,
928    ScrollRow,
929    "compose_rust::ui::ScrollRow",
930    "All of its content, with a horizontal scroll the Renderer owns."
931);
932plain_container!(
933    CardScope,
934    Card,
935    Mods::Container,
936    "compose_rust::ui::Card",
937    "A grouped container. What it looks like is the design system's."
938);
939plain_container!(
940    SurfaceScope,
941    Surface,
942    Mods::Container,
943    "compose_rust::ui::Surface",
944    "A plain background and elevation, without a card's meaning."
945);
946plain_container!(
947    SelectionContainerScope,
948    SelectionContainer,
949    Mods::Standard,
950    "compose_rust::ui::SelectionContainer",
951    "Every `Text` inside can be selected and copied as one selection."
952);
953plain_container!(
954    SpacerScope,
955    Spacer,
956    Mods::Standard,
957    "compose_rust::ui::Spacer",
958    "Empty space, sized by its Modifier."
959);
960
961// ----- text -----------------------------------------------------------------------------
962
963/// A font list as the property blob, or nothing when it is empty.
964fn font_bytes(font: &FontRefs) -> OwnedAttr {
965    if font.is_empty() {
966        OwnedAttr::None
967    } else {
968        OwnedAttr::Bytes(font.as_bytes().to_vec())
969    }
970}
971
972/// A `Text` and its builder.
973pub struct TextScope {
974    modifier: Modifier,
975    text: String,
976    spans: TextSpans,
977    type_role: Option<TypeRole>,
978    font_size: Option<f32>,
979    font_weight: Option<u16>,
980    line_height: Option<f32>,
981    letter_spacing: Option<f32>,
982    color: Option<Paint>,
983    text_align: Option<TextAlign>,
984    max_lines: Option<u32>,
985    overflow: Option<TextOverflow>,
986    font: FontRefs,
987    font_features: OwnedAttr,
988    word_break: Option<WordBreak>,
989    overflow_wrap: Option<OverflowWrap>,
990    pointer: Option<PointerSubscription>,
991    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
992    done: bool,
993}
994
995/// Text. Compose's `Text`.
996///
997/// `type_role` alone takes the design system's size, weight, line height and letter
998/// spacing; each other style method overrides one axis of it.
999pub fn Text(text: impl Into<String>) -> TextScope {
1000    TextScope {
1001        modifier: Modifier::new(),
1002        text: text.into(),
1003        spans: TextSpans::default(),
1004        type_role: None,
1005        font_size: None,
1006        font_weight: None,
1007        line_height: None,
1008        letter_spacing: None,
1009        color: None,
1010        text_align: None,
1011        max_lines: None,
1012        overflow: None,
1013        font: FontRefs::default(),
1014        font_features: OwnedAttr::None,
1015        word_break: None,
1016        overflow_wrap: None,
1017        pointer: None,
1018        on_motion_finished: None,
1019        done: false,
1020    }
1021}
1022
1023impl TextScope {
1024    /// Runs of different treatment inside the text: a bold phrase, a link, some code.
1025    pub fn spans(mut self, spans: TextSpans) -> Self {
1026        self.spans = spans;
1027        self
1028    }
1029
1030    pub fn type_role(mut self, role: TypeRole) -> Self {
1031        self.type_role = Some(role);
1032        self
1033    }
1034
1035    pub fn font_size(mut self, sp: f32) -> Self {
1036        self.font_size = Some(sp);
1037        self
1038    }
1039
1040    pub fn font_weight(mut self, weight: u16) -> Self {
1041        self.font_weight = Some(weight);
1042        self
1043    }
1044
1045    /// Explicit line height in sp, or NaN (normal) to use the font's own metrics.
1046    /// An unset line height (0 or never calling this) falls back to the type role's
1047    /// line height.
1048    pub fn line_height(mut self, sp: f32) -> Self {
1049        self.line_height = Some(sp);
1050        self
1051    }
1052
1053    /// Extra space between letters, in sp. 0 draws no extra spacing; NaN, like never
1054    /// calling this, takes the type role's spacing.
1055    pub fn letter_spacing(mut self, sp: f32) -> Self {
1056        self.letter_spacing = Some(sp);
1057        self
1058    }
1059
1060    pub fn color(mut self, paint: Paint) -> Self {
1061        self.color = Some(paint);
1062        self
1063    }
1064
1065    pub fn text_align(mut self, align: TextAlign) -> Self {
1066        self.text_align = Some(align);
1067        self
1068    }
1069
1070    pub fn max_lines(mut self, lines: u32) -> Self {
1071        self.max_lines = Some(lines);
1072        self
1073    }
1074
1075    pub fn overflow(mut self, overflow: TextOverflow) -> Self {
1076        self.overflow = Some(overflow);
1077        self
1078    }
1079
1080    /// The fonts to try, in order. Only text with `TypeRole::None` takes its own fonts;
1081    /// text with a role is set in the theme's font for that role.
1082    pub fn font(mut self, font: FontRefs) -> Self {
1083        self.font = font;
1084        self
1085    }
1086
1087    /// OpenType features of the font the text is set in, such as
1088    /// `FontFeature::TABULAR_NUMS` for digits of one width. Compose's
1089    /// `TextStyle.fontFeatureSettings`, CSS's `font-feature-settings`.
1090    ///
1091    /// Taken with or without a type role: a feature picks one of the forms the font already
1092    /// has and does not change the font. A tag given twice takes the later value, an empty
1093    /// list is no features, and at most `MAX_FONT_FEATURES` (16) are taken. A font without
1094    /// the feature draws as it would have.
1095    pub fn font_feature_settings(mut self, features: &[FontFeature]) -> Self {
1096        self.font_features = crate::font_features::font_feature_attr(features);
1097        self
1098    }
1099
1100    /// Where a line may break inside a word. CSS `word-break`.
1101    pub fn word_break(mut self, word_break: WordBreak) -> Self {
1102        self.word_break = Some(word_break);
1103        self
1104    }
1105
1106    /// Whether a token too long for its line, such as a path or a URL, may break inside
1107    /// itself. CSS `overflow-wrap`. With `Anywhere` such a token breaks between its letters
1108    /// even under `WordBreak::KeepAll`; tokens that fit keep the breaking rule they had.
1109    pub fn overflow_wrap(mut self, overflow_wrap: OverflowWrap) -> Self {
1110        self.overflow_wrap = Some(overflow_wrap);
1111        self
1112    }
1113
1114    fn compose(&mut self, content: impl FnOnce()) {
1115        let modifier = std::mem::take(&mut self.modifier);
1116        let text = std::mem::take(&mut self.text);
1117        let spans = std::mem::take(&mut self.spans);
1118        let font = std::mem::take(&mut self.font);
1119        let font_features = std::mem::replace(&mut self.font_features, OwnedAttr::None);
1120        let (word_break, overflow_wrap) = (self.word_break, self.overflow_wrap);
1121        let (type_role, font_size, font_weight, line_height, letter_spacing) = (
1122            self.type_role,
1123            self.font_size,
1124            self.font_weight,
1125            self.line_height,
1126            self.letter_spacing,
1127        );
1128        let (color, text_align, max_lines, overflow) =
1129            (self.color, self.text_align, self.max_lines, self.overflow);
1130        let pointer = self.pointer.take();
1131        let mut listeners = Vec::new();
1132        let mut subscription = Attrs::new();
1133        pointer_input(pointer, &mut subscription, &mut listeners);
1134        motion_input(self.on_motion_finished.take(), &mut listeners);
1135        emit(
1136            widget_key("compose_rust::ui::Text"),
1137            WidgetKind::Text,
1138            |attrs| {
1139                push_modifiers(&modifier, Mods::Standard, attrs);
1140                // Left out entirely when there are none, as the rsx widget leaves it out.
1141                let span_fonts = spans.font_table().to_vec();
1142                let span_features = spans.shared_feature_table();
1143                attrs.push((
1144                    "spans",
1145                    if spans.is_empty() {
1146                        OwnedAttr::None
1147                    } else {
1148                        OwnedAttr::Spans(spans)
1149                    },
1150                ));
1151                // The fonts each styled run names travel beside the runs. Left out of the
1152                // list where no run names any: a first composition writes every attribute
1153                // in the list, an empty one as a record that sets nothing. A table that
1154                // goes away is cleared because it left the list.
1155                if !span_fonts.is_empty() {
1156                    attrs.push(("span_fonts", OwnedAttr::Bytes(span_fonts)));
1157                }
1158                // The OpenType features each styled run names travel beside the runs. Left
1159                // out of the list where no run names any, so such a text sends what it
1160                // always did: a first composition writes every attribute in the list, an
1161                // empty one as a record that sets nothing. A table that goes away is
1162                // cleared because it left the list.
1163                if let Some(table) = span_features {
1164                    attrs.push(("span_font_features", OwnedAttr::Shared(table)));
1165                }
1166                // The font list, the break rules and the features are each left out when
1167                // unset, for the same reason: their tags are outside the range the writer
1168                // drops at a neutral value, so listing them empty would send a record of
1169                // nothing for every plain text. One that was set and goes away is cleared
1170                // because it left the list.
1171                if !font.is_empty() {
1172                    attrs.push(("font", font_bytes(&font)));
1173                }
1174                if font_features != OwnedAttr::None {
1175                    attrs.push(("font_feature_settings", font_features));
1176                }
1177                if word_break.is_some() {
1178                    attrs.push(("word_break", super::role(word_break)));
1179                }
1180                if overflow_wrap.is_some() {
1181                    attrs.push(("overflow_wrap", super::role(overflow_wrap)));
1182                }
1183                attrs.push(("text", OwnedAttr::Text(text)));
1184                // `TypeRole::None` is tag 0, so it travels as an explicit 0 and a role that
1185                // was never set travels as nothing. Sent the other way, the text that names
1186                // its own fonts could not say it has no role, and the Renderer set it in
1187                // the default role's font with its fonts ignored.
1188                attrs.push(("type_role", super::role(type_role)));
1189                attrs.push(("font_size", dp_or_zero(font_size)));
1190                attrs.push((
1191                    "font_weight",
1192                    OwnedAttr::Int(i64::from(font_weight.unwrap_or(0))),
1193                ));
1194                attrs.push(("line_height", dp_or_zero(line_height)));
1195                // Unset is NaN, so an explicit 0 stays a 0 and draws no extra spacing.
1196                attrs.push((
1197                    "letter_spacing",
1198                    OwnedAttr::Float(letter_spacing.map_or(f64::NAN, f64::from)),
1199                ));
1200                attrs.push(("color", paint_or_zero(color)));
1201                attrs.push(("text_align", role_or_zero(text_align)));
1202                attrs.push((
1203                    "max_lines",
1204                    OwnedAttr::Int(i64::from(max_lines.unwrap_or(0))),
1205                ));
1206                attrs.push(("overflow", role_or_zero(overflow)));
1207                attrs.append(&mut subscription);
1208            },
1209            listeners,
1210            content,
1211        );
1212    }
1213}
1214
1215composed_on_drop!(TextScope);
1216motion_handler!(TextScope);
1217pointer_subscription!(TextScope);
1218
1219/// A `TextField` and its builder.
1220pub struct TextFieldScope {
1221    modifier: Modifier,
1222    text: String,
1223    placeholder: String,
1224    enabled: bool,
1225    multiline: bool,
1226    type_role: Option<TypeRole>,
1227    font_size: Option<f32>,
1228    font_weight: Option<u16>,
1229    line_height: Option<f32>,
1230    letter_spacing: Option<f32>,
1231    color: Option<Paint>,
1232    placeholder_color: Option<Paint>,
1233    caret_color: Option<Paint>,
1234    font: FontRefs,
1235    font_features: OwnedAttr,
1236    word_break: Option<WordBreak>,
1237    overflow_wrap: Option<OverflowWrap>,
1238    on_value_change: Option<Box<dyn FnMut(String)>>,
1239    on_submit: Option<Box<dyn FnMut(String)>>,
1240    on_focus_gained: Option<Box<dyn FnMut()>>,
1241    on_focus_lost: Option<Box<dyn FnMut()>>,
1242    on_key_down: Option<Box<dyn FnMut(KeyEvent)>>,
1243    on_key_up: Option<Box<dyn FnMut(KeyEvent)>>,
1244    on_composition_change: Option<Box<dyn FnMut(bool)>>,
1245    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
1246    focus_handle: Option<super::FocusHandle>,
1247    bare: bool,
1248    done: bool,
1249}
1250
1251/// An uncontrolled text field. Compose's `TextField`, with the value kept where the
1252/// platform's text input keeps it: the Renderer reports each change and the Host never
1253/// writes the value back while the user types.
1254pub fn TextField() -> TextFieldScope {
1255    TextFieldScope {
1256        modifier: Modifier::new(),
1257        text: String::new(),
1258        placeholder: String::new(),
1259        enabled: true,
1260        multiline: false,
1261        type_role: None,
1262        font_size: None,
1263        font_weight: None,
1264        line_height: None,
1265        letter_spacing: None,
1266        color: None,
1267        placeholder_color: None,
1268        caret_color: None,
1269        font: FontRefs::default(),
1270        font_features: OwnedAttr::None,
1271        word_break: None,
1272        overflow_wrap: None,
1273        on_value_change: None,
1274        on_submit: None,
1275        on_focus_gained: None,
1276        on_focus_lost: None,
1277        on_key_down: None,
1278        on_key_up: None,
1279        on_composition_change: None,
1280        on_motion_finished: None,
1281        focus_handle: None,
1282        bare: false,
1283        done: false,
1284    }
1285}
1286
1287impl TextFieldScope {
1288    /// The text the field starts with. Only the start: the field stays uncontrolled, so
1289    /// what the user types is never written back, and a later value here changes nothing
1290    /// on the field that is already there. To show other text, such as another document,
1291    /// give the field a new identity with `key`, and the new field starts with this text.
1292    pub fn text(mut self, text: impl Into<String>) -> Self {
1293        self.text = text.into();
1294        self
1295    }
1296
1297    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
1298        self.placeholder = placeholder.into();
1299        self
1300    }
1301
1302    pub fn enabled(mut self, enabled: bool) -> Self {
1303        self.enabled = enabled;
1304        self
1305    }
1306
1307    pub fn multiline(mut self, multiline: bool) -> Self {
1308        self.multiline = multiline;
1309        self
1310    }
1311
1312    /// The rung of the type ladder the field's own text is set in.
1313    pub fn type_role(mut self, role: TypeRole) -> Self {
1314        self.type_role = Some(role);
1315        self
1316    }
1317
1318    /// Explicit font size in sp. Overrides the type role's size.
1319    pub fn font_size(mut self, sp: f32) -> Self {
1320        self.font_size = Some(sp);
1321        self
1322    }
1323
1324    /// Explicit font weight (e.g. 400, 500, 600, 700). Overrides the type role's weight.
1325    pub fn font_weight(mut self, weight: u16) -> Self {
1326        self.font_weight = Some(weight);
1327        self
1328    }
1329
1330    /// Explicit line height in sp, or NaN (normal) to use the font's own metrics.
1331    /// An unset line height (0 or never calling this) falls back to the type role's
1332    /// line height.
1333    pub fn line_height(mut self, sp: f32) -> Self {
1334        self.line_height = Some(sp);
1335        self
1336    }
1337
1338    /// Explicit letter spacing in sp.
1339    pub fn letter_spacing(mut self, sp: f32) -> Self {
1340        self.letter_spacing = Some(sp);
1341        self
1342    }
1343
1344    /// Explicit text colour.
1345    pub fn color(mut self, paint: Paint) -> Self {
1346        self.color = Some(paint);
1347        self
1348    }
1349
1350    /// Explicit placeholder text colour. Sent only when set; absent keeps the design
1351    /// system's default.
1352    pub fn placeholder_color(mut self, paint: Paint) -> Self {
1353        self.placeholder_color = Some(paint);
1354        self
1355    }
1356
1357    /// Explicit caret colour. Sent only when set; absent keeps the design
1358    /// system's default.
1359    pub fn caret_color(mut self, paint: Paint) -> Self {
1360        self.caret_color = Some(paint);
1361        self
1362    }
1363
1364    /// The fonts to try for the field's text, in order. Taken only with `TypeRole::None`.
1365    pub fn font(mut self, font: FontRefs) -> Self {
1366        self.font = font;
1367        self
1368    }
1369
1370    /// OpenType features for the typed text and the placeholder, as
1371    /// `Text::font_feature_settings` takes them. Taken with or without a type role.
1372    pub fn font_feature_settings(mut self, features: &[FontFeature]) -> Self {
1373        self.font_features = crate::font_features::font_feature_attr(features);
1374        self
1375    }
1376
1377    /// Where a line of the typed text and of the placeholder may break inside a word, as
1378    /// `Text::word_break` does. CSS `word-break`.
1379    pub fn word_break(mut self, word_break: WordBreak) -> Self {
1380        self.word_break = Some(word_break);
1381        self
1382    }
1383
1384    /// Whether a token too long for its line may break inside itself, in the typed text
1385    /// and the placeholder, as `Text::overflow_wrap` does. CSS `overflow-wrap`.
1386    pub fn overflow_wrap(mut self, overflow_wrap: OverflowWrap) -> Self {
1387        self.overflow_wrap = Some(overflow_wrap);
1388        self
1389    }
1390
1391    pub fn on_value_change(mut self, handler: impl FnMut(String) + 'static) -> Self {
1392        self.on_value_change = Some(std::boxed::Box::new(handler));
1393        self
1394    }
1395
1396    pub fn on_submit(mut self, handler: impl FnMut(String) + 'static) -> Self {
1397        self.on_submit = Some(std::boxed::Box::new(handler));
1398        self
1399    }
1400
1401    pub fn on_focus_gained(mut self, handler: impl FnMut() + 'static) -> Self {
1402        self.on_focus_gained = Some(std::boxed::Box::new(handler));
1403        self
1404    }
1405
1406    pub fn on_focus_lost(mut self, handler: impl FnMut() + 'static) -> Self {
1407        self.on_focus_lost = Some(std::boxed::Box::new(handler));
1408        self
1409    }
1410
1411    /// Sees each key the field is pressed with; calling `consume` on the event keeps the
1412    /// field from acting on it.
1413    pub fn on_key_down(mut self, handler: impl FnMut(KeyEvent) + 'static) -> Self {
1414        self.on_key_down = Some(std::boxed::Box::new(handler));
1415        self
1416    }
1417
1418    /// Sees each key released while the field holds focus.
1419    pub fn on_key_up(mut self, handler: impl FnMut(KeyEvent) + 'static) -> Self {
1420        self.on_key_up = Some(std::boxed::Box::new(handler));
1421        self
1422    }
1423
1424    /// Reports when an input method begins or ends an active composition in the field.
1425    pub fn on_composition_change(mut self, handler: impl FnMut(bool) + 'static) -> Self {
1426        self.on_composition_change = Some(std::boxed::Box::new(handler));
1427        self
1428    }
1429
1430    /// Binds `handle` to this field, so `handle.request()` puts keyboard focus here.
1431    pub fn focus_handle(mut self, handle: &super::FocusHandle) -> Self {
1432        self.focus_handle = Some(handle.clone());
1433        self
1434    }
1435
1436    /// Runs once when the field's size motion comes to rest, with the size it settled at
1437    /// in dp. The field needs `Modifier::motion` for its size to move; without it nothing
1438    /// is reported. A run interrupted by a newer size is not reported, only the one that
1439    /// settles.
1440    pub fn on_motion_finished(mut self, handler: impl FnMut(MotionFinished) + 'static) -> Self {
1441        self.on_motion_finished = Some(std::boxed::Box::new(handler));
1442        self
1443    }
1444
1445    /// Draws the field without the design system's frame: no fill, line, underline,
1446    /// corner clip, inner padding, minimum height or focus line. Text, placeholder, caret,
1447    /// selection and input methods stay as they are. For a field that sits inside a box
1448    /// which already draws its own frame, so the frame is not drawn twice. A `background`
1449    /// or `border` given on the node is still drawn.
1450    pub fn bare(mut self) -> Self {
1451        self.bare = true;
1452        self
1453    }
1454
1455    fn compose(&mut self, content: impl FnOnce()) {
1456        let modifier = std::mem::take(&mut self.modifier);
1457        let text = std::mem::take(&mut self.text);
1458        let placeholder = std::mem::take(&mut self.placeholder);
1459        let (enabled, multiline, type_role) = (self.enabled, self.multiline, self.type_role);
1460        let bare = self.bare;
1461        let (font_size, font_weight, line_height) =
1462            (self.font_size, self.font_weight, self.line_height);
1463        let (letter_spacing, color) = (self.letter_spacing, self.color);
1464        let (placeholder_color, caret_color) = (self.placeholder_color, self.caret_color);
1465        let font = std::mem::take(&mut self.font);
1466        let font_features = std::mem::replace(&mut self.font_features, OwnedAttr::None);
1467        let (word_break, overflow_wrap) = (self.word_break, self.overflow_wrap);
1468        let key_down: EventCallback = match self.on_key_down.take() {
1469            Some(handler) => EventCallback::Key(Rc::new(RefCell::new(handler))),
1470            None => EventCallback::Key(Rc::new(RefCell::new(|_: KeyEvent| {}))),
1471        };
1472        let mut listeners = vec![
1473            ("onvaluechange", text_handler(self.on_value_change.take())),
1474            ("onsubmit", text_handler(self.on_submit.take())),
1475            ("onfocuslost", unit(self.on_focus_lost.take())),
1476            ("onkeydown", key_down),
1477        ];
1478        if let Some(handler) = self.on_focus_gained.take() {
1479            listeners.push(("onfocusgained", unit(Some(handler))));
1480        }
1481        if let Some(handler) = self.on_key_up.take() {
1482            listeners.push((
1483                "onkeyup",
1484                EventCallback::Key(Rc::new(RefCell::new(handler))),
1485            ));
1486        }
1487        if let Some(mut handler) = self.on_composition_change.take() {
1488            listeners.push((
1489                "oncompositionchange",
1490                EventCallback::Value(Rc::new(RefCell::new(move |value: f64| {
1491                    handler(value != 0.0);
1492                }))),
1493            ));
1494        }
1495        motion_input(self.on_motion_finished.take(), &mut listeners);
1496        super::focus::bind_focus_handle(self.focus_handle.take());
1497        emit(
1498            widget_key("compose_rust::ui::TextField"),
1499            WidgetKind::TextField,
1500            |attrs| {
1501                push_modifiers(&modifier, Mods::Standard, attrs);
1502                // Written only when there is a starting text, so a field without one sends
1503                // the same records it always did.
1504                if !text.is_empty() {
1505                    attrs.push(("text", OwnedAttr::Text(text)));
1506                }
1507                attrs.push(("placeholder", OwnedAttr::Text(placeholder)));
1508                attrs.push(("enabled", OwnedAttr::Bool(enabled)));
1509                attrs.push(("multiline", OwnedAttr::Bool(multiline)));
1510                // An explicit `TypeRole::None` is a 0 on the wire, an unset role nothing,
1511                // as for `Text`.
1512                attrs.push(("type_role", super::role(type_role)));
1513                if let Some(font_size) = font_size {
1514                    attrs.push(("font_size", OwnedAttr::Float(font_size as f64)));
1515                }
1516                if let Some(font_weight) = font_weight {
1517                    attrs.push(("font_weight", OwnedAttr::Int(font_weight as i64)));
1518                }
1519                if let Some(line_height) = line_height {
1520                    attrs.push(("line_height", OwnedAttr::Float(line_height as f64)));
1521                }
1522                if let Some(letter_spacing) = letter_spacing {
1523                    attrs.push(("letter_spacing", OwnedAttr::Float(letter_spacing as f64)));
1524                }
1525                if let Some(color) = color {
1526                    attrs.push(("color", super::paint(Some(color))));
1527                }
1528                if let Some(placeholder_color) = placeholder_color {
1529                    attrs.push(("placeholder_color", super::paint(Some(placeholder_color))));
1530                }
1531                if let Some(caret_color) = caret_color {
1532                    attrs.push(("caret_color", super::paint(Some(caret_color))));
1533                }
1534                // The font list, the features and the break rules are each left out when
1535                // unset, as `Text` leaves them out, and cleared once when they go away.
1536                if !font.is_empty() {
1537                    attrs.push(("font", font_bytes(&font)));
1538                }
1539                if font_features != OwnedAttr::None {
1540                    attrs.push(("font_feature_settings", font_features));
1541                }
1542                if word_break.is_some() {
1543                    attrs.push(("word_break", super::role(word_break)));
1544                }
1545                if overflow_wrap.is_some() {
1546                    attrs.push(("overflow_wrap", super::role(overflow_wrap)));
1547                }
1548                // Written only for a bare field, so a framed one sends what it always did.
1549                if bare {
1550                    attrs.push(("bare", OwnedAttr::Bool(true)));
1551                }
1552            },
1553            listeners,
1554            content,
1555        );
1556    }
1557}
1558
1559composed_on_drop!(TextFieldScope);
1560
1561// ----- buttons and controls ---------------------------------------------------------------
1562
1563/// The label's line limit and overflow, written only when they were set, so a widget that
1564/// never asks for them sends what it always sent.
1565fn lines_and_overflow(max_lines: Option<u32>, overflow: Option<TextOverflow>, attrs: &mut Attrs) {
1566    if let Some(lines) = max_lines {
1567        attrs.push(("max_lines", OwnedAttr::Int(i64::from(lines))));
1568    }
1569    if overflow.is_some() {
1570        attrs.push(("overflow", role_or_zero(overflow)));
1571    }
1572}
1573
1574/// The colours and size a Switch, Slider, Checkbox or RadioButton was asked to draw with. Each is sent
1575/// only when it was set, so a control that sets none sends the properties it always has
1576/// and the design system draws it.
1577#[derive(Clone, Copy, Default)]
1578struct ControlLook {
1579    track: Option<Paint>,
1580    thumb: Option<Paint>,
1581    active_track: Option<Paint>,
1582    container: Option<Paint>,
1583    check: Option<Paint>,
1584    size: Option<(f32, f32)>,
1585}
1586
1587impl ControlLook {
1588    fn push(&self, attrs: &mut Attrs) {
1589        let paints = [
1590            ("track_color", self.track),
1591            ("thumb_color", self.thumb),
1592            ("active_track_color", self.active_track),
1593            ("container_color", self.container),
1594            ("check_color", self.check),
1595        ];
1596        for (name, paint) in paints {
1597            if let Some(paint) = paint {
1598                attrs.push((name, super::paint(Some(paint))));
1599            }
1600        }
1601        if let Some((width, height)) = self.size {
1602            let mut bytes = Vec::with_capacity(8);
1603            bytes.extend_from_slice(&width.to_bits().to_le_bytes());
1604            bytes.extend_from_slice(&height.to_bits().to_le_bytes());
1605            attrs.push(("control_size", OwnedAttr::Bytes(bytes)));
1606        }
1607    }
1608}
1609
1610/// Adds a colour setter that fills one slot of `look`.
1611macro_rules! control_colour {
1612    ($name:ident, $slot:ident, $setter:ident, $doc:literal) => {
1613        impl $name {
1614            #[doc = $doc]
1615            pub fn $setter(mut self, paint: Paint) -> Self {
1616                self.look.$slot = Some(paint);
1617                self
1618            }
1619        }
1620    };
1621}
1622
1623/// Writes a widget's own accessible name. It replaces one the Modifier gave, so the name
1624/// said on the widget is the one that reaches assistive technology.
1625fn push_accessible_name(name: Option<String>, attrs: &mut Attrs) {
1626    if let Some(name) = name.filter(|name| !name.is_empty()) {
1627        attrs.retain(|(key, _)| *key != "accessible_name");
1628        attrs.push(("accessible_name", OwnedAttr::Text(name)));
1629    }
1630}
1631
1632/// Adds `accessible_name` to a builder that has an `accessible_name` field.
1633macro_rules! accessible_name {
1634    ($name:ident) => {
1635        impl $name {
1636            /// The name assistive technology reads. With no visible label it is the
1637            /// control's name; with one it replaces the label, and on an icon-only button
1638            /// it is read instead of the icon's meaning.
1639            pub fn accessible_name(mut self, name: impl Into<String>) -> Self {
1640                self.accessible_name = Some(name.into());
1641                self
1642            }
1643        }
1644    };
1645}
1646
1647/// A `Button` and its builder.
1648pub struct ButtonScope {
1649    modifier: Modifier,
1650    text: String,
1651    icon: Option<IconRole>,
1652    enabled: bool,
1653    variant: Option<ButtonVariant>,
1654    kind: Option<ButtonKind>,
1655    color: Option<Paint>,
1656    max_lines: Option<u32>,
1657    overflow: Option<TextOverflow>,
1658    accessible_name: Option<String>,
1659    text_align: Option<TextAlign>,
1660    font_size: Option<f32>,
1661    font_weight: Option<u16>,
1662    type_role: Option<TypeRole>,
1663    content_padding: Option<(f32, f32)>,
1664    on_click: Option<Box<dyn FnMut()>>,
1665    focus_handle: Option<super::FocusHandle>,
1666    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
1667    done: bool,
1668}
1669
1670/// A button with a label. Compose's `Button`; the variant is the design system's seam,
1671/// so `ButtonVariant::Text` is Compose's `TextButton` and `Outlined` its `OutlinedButton`.
1672///
1673/// An empty label with an icon is an icon button, named for assistive technology by its
1674/// icon's meaning.
1675pub fn Button(text: impl Into<String>) -> ButtonScope {
1676    ButtonScope {
1677        modifier: Modifier::new(),
1678        text: text.into(),
1679        icon: None,
1680        enabled: true,
1681        variant: None,
1682        kind: None,
1683        color: None,
1684        max_lines: None,
1685        overflow: None,
1686        accessible_name: None,
1687        text_align: None,
1688        font_size: None,
1689        font_weight: None,
1690        type_role: None,
1691        content_padding: None,
1692        on_click: None,
1693        focus_handle: None,
1694        on_motion_finished: None,
1695        done: false,
1696    }
1697}
1698
1699accessible_name!(ButtonScope);
1700
1701impl ButtonScope {
1702    /// Where the label sits in the button. A button that never calls this sends nothing
1703    /// and keeps its label centred.
1704    pub fn text_align(mut self, align: TextAlign) -> Self {
1705        self.text_align = Some(align);
1706        self
1707    }
1708
1709    /// The label's size in sp. A button that never calls this sends nothing and takes the
1710    /// design system's size for its variant.
1711    pub fn font_size(mut self, sp: f32) -> Self {
1712        self.font_size = Some(sp);
1713        self
1714    }
1715
1716    /// The label's weight (e.g. 400, 500, 600, 700). Overrides the type role's weight. A
1717    /// button that never calls this sends nothing.
1718    pub fn font_weight(mut self, weight: u16) -> Self {
1719        self.font_weight = Some(weight);
1720        self
1721    }
1722
1723    /// The rung of the type ladder the label is set in: its size, weight and line height.
1724    /// `font_size` and `font_weight` win over the role's values. A button that never calls
1725    /// this sends nothing and keeps the design system's label style for its variant.
1726    pub fn type_role(mut self, role: TypeRole) -> Self {
1727        self.type_role = Some(role);
1728        self
1729    }
1730
1731    /// The room between the button's edge and its label, in dp: `horizontal` at each side
1732    /// and `vertical` above and below. It replaces the design system's padding for this
1733    /// button only, and still gives way when the button is too small for the label and
1734    /// the padding together. `Modifier::padding` is the room around the button and is not
1735    /// changed by this. A button that never calls this sends nothing and keeps the design
1736    /// system's padding.
1737    pub fn content_padding(mut self, horizontal: f32, vertical: f32) -> Self {
1738        self.content_padding = Some((horizontal, vertical));
1739        self
1740    }
1741
1742    /// The meaning of the glyph on it, never a picture.
1743    pub fn icon(mut self, icon: IconRole) -> Self {
1744        self.icon = Some(icon);
1745        self
1746    }
1747
1748    pub fn enabled(mut self, enabled: bool) -> Self {
1749        self.enabled = enabled;
1750        self
1751    }
1752
1753    pub fn variant(mut self, variant: ButtonVariant) -> Self {
1754        self.variant = Some(variant);
1755        self
1756    }
1757
1758    /// What the button is, apart from how loud it is: `ButtonKind::ActionKey` is one key of
1759    /// a dense grid, drawn in the design system's own calculator-key shape.
1760    pub fn kind(mut self, kind: ButtonKind) -> Self {
1761        self.kind = Some(kind);
1762        self
1763    }
1764
1765    /// How many lines the label may take. A label is one line unless this says more, so a
1766    /// Korean label is never broken between syllables by a squeezed parent.
1767    pub fn max_lines(mut self, lines: u32) -> Self {
1768        self.max_lines = Some(lines);
1769        self
1770    }
1771
1772    /// What happens to a label longer than its lines.
1773    pub fn overflow(mut self, overflow: TextOverflow) -> Self {
1774        self.overflow = Some(overflow);
1775        self
1776    }
1777
1778    /// The label's colour, for the rare button whose meaning is not its variant's.
1779    pub fn color(mut self, paint: Paint) -> Self {
1780        self.color = Some(paint);
1781        self
1782    }
1783
1784    /// The same, when there may be no colour of its own.
1785    pub fn color_if(mut self, paint: Option<Paint>) -> Self {
1786        self.color = paint;
1787        self
1788    }
1789
1790    pub fn on_click(mut self, handler: impl FnMut() + 'static) -> Self {
1791        self.on_click = Some(std::boxed::Box::new(handler));
1792        self
1793    }
1794
1795    /// Binds `handle` to this button, so `handle.request()` puts keyboard focus here.
1796    pub fn focus_handle(mut self, handle: &super::FocusHandle) -> Self {
1797        self.focus_handle = Some(handle.clone());
1798        self
1799    }
1800
1801    fn compose(&mut self, content: impl FnOnce()) {
1802        let modifier = std::mem::take(&mut self.modifier);
1803        let text = std::mem::take(&mut self.text);
1804        let (icon, enabled, variant, kind, color) =
1805            (self.icon, self.enabled, self.variant, self.kind, self.color);
1806        let (max_lines, overflow) = (self.max_lines, self.overflow);
1807        let accessible_name = self.accessible_name.take();
1808        let (text_align, font_size) = (self.text_align, self.font_size);
1809        let (font_weight, type_role) = (self.font_weight, self.type_role);
1810        let content_padding = self.content_padding;
1811        let mut listeners = vec![("onclick", unit(self.on_click.take()))];
1812        super::focus::bind_focus_handle(self.focus_handle.take());
1813        motion_input(self.on_motion_finished.take(), &mut listeners);
1814        emit(
1815            widget_key("compose_rust::ui::Button"),
1816            WidgetKind::Button,
1817            |attrs| {
1818                push_modifiers(&modifier, Mods::Standard, attrs);
1819                attrs.push(("text", OwnedAttr::Text(text)));
1820                attrs.push(("icon", super::role(icon)));
1821                attrs.push(("enabled", OwnedAttr::Bool(enabled)));
1822                attrs.push(("variant", role_or_zero(variant)));
1823                attrs.push(("button_kind", role_or_zero(kind)));
1824                attrs.push(("color", super::paint(color)));
1825                lines_and_overflow(max_lines, overflow, attrs);
1826                push_accessible_name(accessible_name, attrs);
1827                if text_align.is_some() {
1828                    attrs.push(("text_align", role_or_zero(text_align)));
1829                }
1830                if font_size.is_some() {
1831                    attrs.push(("font_size", dp_or_zero(font_size)));
1832                }
1833                if let Some(font_weight) = font_weight {
1834                    attrs.push(("font_weight", OwnedAttr::Int(i64::from(font_weight))));
1835                }
1836                if type_role.is_some() {
1837                    attrs.push(("type_role", super::role(type_role)));
1838                }
1839                // Written only when it was set, so a button that never asks sends what it
1840                // always sent.
1841                if let Some((horizontal, vertical)) = content_padding {
1842                    let mut bytes = Vec::with_capacity(8);
1843                    bytes.extend_from_slice(&horizontal.to_le_bytes());
1844                    bytes.extend_from_slice(&vertical.to_le_bytes());
1845                    attrs.push(("content_padding", OwnedAttr::Bytes(bytes)));
1846                }
1847            },
1848            listeners,
1849            content,
1850        );
1851    }
1852}
1853
1854container!(ButtonScope);
1855motion_handler!(ButtonScope);
1856
1857/// A two-state control, for Checkbox, RadioButton and Switch alike: the Host owns the
1858/// value, the control draws exactly what it is told and reports what the user asked for.
1859macro_rules! toggle {
1860    ($name:ident, $widget:ident, $setter:ident, $key:literal, $doc:literal) => {
1861        #[doc = concat!("A `", stringify!($widget), "` and its builder.")]
1862        pub struct $name {
1863            modifier: Modifier,
1864            checked: bool,
1865            enabled: bool,
1866            accessible_name: Option<String>,
1867            look: ControlLook,
1868            on_change: Option<Box<dyn FnMut(bool)>>,
1869            on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
1870            done: bool,
1871        }
1872
1873        #[doc = $doc]
1874        pub fn $widget($setter: bool) -> $name {
1875            $name {
1876                modifier: Modifier::new(),
1877                checked: $setter,
1878                enabled: true,
1879                accessible_name: None,
1880                look: ControlLook::default(),
1881                on_change: None,
1882                on_motion_finished: None,
1883                done: false,
1884            }
1885        }
1886
1887        accessible_name!($name);
1888
1889        impl $name {
1890            pub fn enabled(mut self, enabled: bool) -> Self {
1891                self.enabled = enabled;
1892                self
1893            }
1894
1895            /// Called with the state the user asked for. The control changes only when the
1896            /// value passed in does.
1897            pub fn on_change(mut self, handler: impl FnMut(bool) + 'static) -> Self {
1898                self.on_change = Some(std::boxed::Box::new(handler));
1899                self
1900            }
1901
1902            fn compose(&mut self, content: impl FnOnce()) {
1903                let modifier = std::mem::take(&mut self.modifier);
1904                let (checked, enabled) = (self.checked, self.enabled);
1905                let accessible_name = self.accessible_name.take();
1906                let look = self.look;
1907                let handler: EventCallback = match self.on_change.take() {
1908                    Some(mut handler) => EventCallback::Value(Rc::new(RefCell::new(
1909                        // Off is 0.0 and on is anything else, so a Renderer that reports a
1910                        // half-finished transition still reads as on.
1911                        move |value: f64| handler(value != 0.0),
1912                    ))),
1913                    None => value_handler(None),
1914                };
1915                let motion = self.on_motion_finished.take();
1916                emit(
1917                    widget_key($key),
1918                    WidgetKind::$widget,
1919                    |attrs| {
1920                        push_modifiers(&modifier, Mods::Standard, attrs);
1921                        attrs.push(("checked", OwnedAttr::Bool(checked)));
1922                        attrs.push(("enabled", OwnedAttr::Bool(enabled)));
1923                        push_accessible_name(accessible_name, attrs);
1924                        look.push(attrs);
1925                    },
1926                    with_motion(vec![("onchange", handler)], motion),
1927                    content,
1928                );
1929            }
1930        }
1931
1932        composed_on_drop!($name);
1933        motion_handler!($name);
1934    };
1935}
1936
1937control_colour!(
1938    SwitchScope,
1939    track,
1940    track_color,
1941    "The track, whichever state it is in. The Host owns the state, so it passes the colour \
1942     that goes with it."
1943);
1944control_colour!(
1945    SwitchScope,
1946    thumb,
1947    thumb_color,
1948    "The thumb that travels along the track."
1949);
1950
1951impl SwitchScope {
1952    /// The track's width and height in dp. The thumb scales with the height.
1953    pub fn size(mut self, width: f32, height: f32) -> Self {
1954        self.look.size = Some((width, height));
1955        self
1956    }
1957}
1958
1959control_colour!(
1960    CheckboxScope,
1961    container,
1962    container_color,
1963    "The box when it is checked."
1964);
1965control_colour!(CheckboxScope, check, check_color, "The check mark.");
1966
1967impl CheckboxScope {
1968    /// The length of the box's side in dp.
1969    pub fn size(mut self, side: f32) -> Self {
1970        self.look.size = Some((side, side));
1971        self
1972    }
1973}
1974
1975control_colour!(
1976    RadioButtonScope,
1977    container,
1978    ring_color,
1979    "The ring around the button, selected or not. Where the design system fills a selected \
1980     button, the fill takes this colour as well."
1981);
1982control_colour!(
1983    RadioButtonScope,
1984    check,
1985    dot_color,
1986    "The dot inside a selected button."
1987);
1988
1989impl RadioButtonScope {
1990    /// The diameter of the ring in dp. The dot scales with it.
1991    pub fn size(mut self, side: f32) -> Self {
1992        self.look.size = Some((side, side));
1993        self
1994    }
1995}
1996
1997toggle!(
1998    CheckboxScope,
1999    Checkbox,
2000    checked,
2001    "compose_rust::ui::Checkbox",
2002    "A box that is ticked or not. Compose's `Checkbox(checked, onCheckedChange)`."
2003);
2004toggle!(
2005    RadioButtonScope,
2006    RadioButton,
2007    selected,
2008    "compose_rust::ui::RadioButton",
2009    "One choice out of several. Compose's `RadioButton(selected, onClick)`."
2010);
2011toggle!(
2012    SwitchScope,
2013    Switch,
2014    checked,
2015    "compose_rust::ui::Switch",
2016    "An on and off control. Compose's `Switch(checked, onCheckedChange)`."
2017);
2018
2019/// A `Slider` and its builder.
2020pub struct SliderScope {
2021    modifier: Modifier,
2022    color: Option<Paint>,
2023    value: f32,
2024    min: f32,
2025    max: f32,
2026    steps: u32,
2027    enabled: bool,
2028    accessible_name: Option<String>,
2029    look: ControlLook,
2030    thumb_size: Option<f32>,
2031    on_change: Option<Box<dyn FnMut(f32)>>,
2032    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2033    done: bool,
2034}
2035
2036/// A value picked from a range. Compose's `Slider`. The drag is the Renderer's; `value`
2037/// seeds it and moves it when the change came from elsewhere.
2038pub fn Slider(value: f32) -> SliderScope {
2039    SliderScope {
2040        modifier: Modifier::new(),
2041        color: None,
2042        value,
2043        min: 0.0,
2044        max: 1.0,
2045        steps: 0,
2046        enabled: true,
2047        accessible_name: None,
2048        look: ControlLook::default(),
2049        thumb_size: None,
2050        on_change: None,
2051        on_motion_finished: None,
2052        done: false,
2053    }
2054}
2055
2056accessible_name!(SliderScope);
2057control_colour!(
2058    SliderScope,
2059    track,
2060    track_color,
2061    "The part of the track that is not filled."
2062);
2063control_colour!(SliderScope, thumb, thumb_color, "The thumb.");
2064control_colour!(
2065    SliderScope,
2066    active_track,
2067    active_track_color,
2068    "The part of the track up to the thumb."
2069);
2070
2071impl SliderScope {
2072    /// The two ends. Compose's `valueRange`.
2073    pub fn range(mut self, min: f32, max: f32) -> Self {
2074        self.min = min;
2075        self.max = max;
2076        self
2077    }
2078
2079    /// Stops between the ends; zero is continuous.
2080    pub fn steps(mut self, steps: u32) -> Self {
2081        self.steps = steps;
2082        self
2083    }
2084
2085    pub fn enabled(mut self, enabled: bool) -> Self {
2086        self.enabled = enabled;
2087        self
2088    }
2089
2090    /// The filled part of the track and the thumb.
2091    pub fn color(mut self, paint: Paint) -> Self {
2092        self.color = Some(paint);
2093        self
2094    }
2095
2096    /// The thumb's diameter in dp. Without it the design system picks the size. The track
2097    /// and the area that takes a press do not change with it, so a small thumb is still
2098    /// easy to grab.
2099    pub fn thumb_size(mut self, dp: f32) -> Self {
2100        self.thumb_size = Some(dp);
2101        self
2102    }
2103
2104    pub fn on_change(mut self, handler: impl FnMut(f32) + 'static) -> Self {
2105        self.on_change = Some(std::boxed::Box::new(handler));
2106        self
2107    }
2108
2109    fn compose(&mut self, content: impl FnOnce()) {
2110        let modifier = std::mem::take(&mut self.modifier);
2111        let thumb_size = self.thumb_size;
2112        let (color, value, min, max, steps, enabled) = (
2113            self.color,
2114            self.value,
2115            self.min,
2116            self.max,
2117            self.steps,
2118            self.enabled,
2119        );
2120        let accessible_name = self.accessible_name.take();
2121        let look = self.look;
2122        let handler = match self.on_change.take() {
2123            Some(mut handler) => EventCallback::Value(Rc::new(RefCell::new(move |value: f64| {
2124                handler(value as f32)
2125            }))),
2126            None => value_handler(None),
2127        };
2128        let motion = self.on_motion_finished.take();
2129        emit(
2130            widget_key("compose_rust::ui::Slider"),
2131            WidgetKind::Slider,
2132            |attrs| {
2133                push_modifiers(&modifier, Mods::Standard, attrs);
2134                attrs.push(("color", super::paint(color)));
2135                attrs.push(("value", OwnedAttr::Float(f64::from(value))));
2136                attrs.push(("min", OwnedAttr::Float(f64::from(min))));
2137                attrs.push(("max", OwnedAttr::Float(f64::from(max))));
2138                attrs.push(("steps", OwnedAttr::Int(i64::from(steps))));
2139                attrs.push(("enabled", OwnedAttr::Bool(enabled)));
2140                push_accessible_name(accessible_name, attrs);
2141                look.push(attrs);
2142                if let Some(dp) = thumb_size {
2143                    attrs.push(("thumb_size", OwnedAttr::Float(f64::from(dp))));
2144                }
2145            },
2146            with_motion(vec![("onchange", handler)], motion),
2147            content,
2148        );
2149    }
2150}
2151
2152composed_on_drop!(SliderScope);
2153motion_handler!(SliderScope);
2154
2155/// A `ProgressIndicator` and its builder.
2156pub struct ProgressIndicatorScope {
2157    modifier: Modifier,
2158    value: f32,
2159    determinate: bool,
2160    circular: bool,
2161    color: Option<Paint>,
2162    track_color: Option<Paint>,
2163    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2164    done: bool,
2165}
2166
2167/// How far along something is, as a fraction. Compose's `LinearProgressIndicator(progress)`.
2168pub fn ProgressIndicator(value: f32) -> ProgressIndicatorScope {
2169    ProgressIndicatorScope {
2170        modifier: Modifier::new(),
2171        value,
2172        determinate: true,
2173        circular: false,
2174        color: None,
2175        track_color: None,
2176        on_motion_finished: None,
2177        done: false,
2178    }
2179}
2180
2181/// Work in progress of no known length.
2182pub fn IndeterminateProgressIndicator() -> ProgressIndicatorScope {
2183    ProgressIndicator(0.0).determinate(false)
2184}
2185
2186impl ProgressIndicatorScope {
2187    pub fn determinate(mut self, determinate: bool) -> Self {
2188        self.determinate = determinate;
2189        self
2190    }
2191
2192    /// The circular form rather than the linear one.
2193    pub fn circular(mut self, circular: bool) -> Self {
2194        self.circular = circular;
2195        self
2196    }
2197
2198    /// The indicator's colour.
2199    pub fn color(mut self, paint: Paint) -> Self {
2200        self.color = Some(paint);
2201        self
2202    }
2203
2204    /// The same, when there may be no colour of its own.
2205    pub fn color_if(mut self, paint: Option<Paint>) -> Self {
2206        self.color = paint;
2207        self
2208    }
2209
2210    /// The indicator's colour.
2211    pub fn indicator_color(self, paint: Paint) -> Self {
2212        self.color(paint)
2213    }
2214
2215    /// The track's colour.
2216    pub fn track_color(mut self, paint: Paint) -> Self {
2217        self.track_color = Some(paint);
2218        self
2219    }
2220
2221    /// The same, when there may be no track colour of its own.
2222    pub fn track_color_if(mut self, paint: Option<Paint>) -> Self {
2223        self.track_color = paint;
2224        self
2225    }
2226
2227    fn compose(&mut self, content: impl FnOnce()) {
2228        let modifier = std::mem::take(&mut self.modifier);
2229        let (value, determinate, circular) = (self.value, self.determinate, self.circular);
2230        let (color, track_color) = (self.color, self.track_color);
2231        let motion = self.on_motion_finished.take();
2232        emit(
2233            widget_key("compose_rust::ui::ProgressIndicator"),
2234            WidgetKind::ProgressIndicator,
2235            |attrs| {
2236                push_modifiers(&modifier, Mods::Standard, attrs);
2237                attrs.push(("value", OwnedAttr::Float(f64::from(value))));
2238                attrs.push(("determinate", OwnedAttr::Bool(determinate)));
2239                attrs.push(("circular", OwnedAttr::Bool(circular)));
2240                if let Some(color) = color {
2241                    attrs.push(("color", super::paint(Some(color))));
2242                }
2243                if let Some(track) = track_color {
2244                    attrs.push(("track_color", super::paint(Some(track))));
2245                }
2246            },
2247            with_motion(Vec::new(), motion),
2248            content,
2249        );
2250    }
2251}
2252
2253composed_on_drop!(ProgressIndicatorScope);
2254motion_handler!(ProgressIndicatorScope);
2255
2256/// A `Divider` and its builder.
2257pub struct DividerScope {
2258    modifier: Modifier,
2259    vertical: bool,
2260    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2261    done: bool,
2262}
2263
2264/// A line between two things. Compose's `HorizontalDivider`; `vertical` makes it the other.
2265pub fn Divider() -> DividerScope {
2266    DividerScope {
2267        modifier: Modifier::new(),
2268        vertical: false,
2269        on_motion_finished: None,
2270        done: false,
2271    }
2272}
2273
2274/// A hairline between two rows of a grouped list, in the design system's quiet edge or
2275/// the given colour. The same node as `Divider().modifier(Modifier.background(color))`.
2276pub fn Separator(color: Option<Paint>) -> DividerScope {
2277    Divider().modifier(Modifier::new().background_if(color))
2278}
2279
2280impl DividerScope {
2281    pub fn vertical(mut self, vertical: bool) -> Self {
2282        self.vertical = vertical;
2283        self
2284    }
2285
2286    fn compose(&mut self, content: impl FnOnce()) {
2287        let modifier = std::mem::take(&mut self.modifier);
2288        let vertical = self.vertical;
2289        let motion = self.on_motion_finished.take();
2290        emit(
2291            widget_key("compose_rust::ui::Divider"),
2292            WidgetKind::Divider,
2293            |attrs| {
2294                push_modifiers(&modifier, Mods::Standard, attrs);
2295                attrs.push(("vertical", OwnedAttr::Bool(vertical)));
2296            },
2297            with_motion(Vec::new(), motion),
2298            content,
2299        );
2300    }
2301}
2302
2303composed_on_drop!(DividerScope);
2304motion_handler!(DividerScope);
2305
2306// ----- pictures -------------------------------------------------------------------------
2307
2308/// An `Image` or an `Icon` and its builder.
2309pub struct AssetScope {
2310    modifier: Modifier,
2311    widget: WidgetKind,
2312    asset_id: u32,
2313    // Whether the asset is a picture drawn as an icon: in the icon slot, at an icon's size,
2314    // and in the icon's colour rather than its own.
2315    tinted: bool,
2316    color: Option<Paint>,
2317    content_scale: Option<ContentScale>,
2318    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2319    done: bool,
2320}
2321
2322/// A registered asset drawn as a picture. Compose's `Image`.
2323pub fn Image(asset_id: u32) -> AssetScope {
2324    AssetScope {
2325        modifier: Modifier::new(),
2326        widget: WidgetKind::Image,
2327        asset_id,
2328        tinted: false,
2329        color: None,
2330        content_scale: None,
2331        on_motion_finished: None,
2332        done: false,
2333    }
2334}
2335
2336/// A registered icon, tinted. Compose's `Icon`.
2337pub fn Icon(asset_id: u32) -> AssetScope {
2338    AssetScope {
2339        modifier: Modifier::new(),
2340        widget: WidgetKind::Icon,
2341        asset_id,
2342        tinted: false,
2343        color: None,
2344        content_scale: None,
2345        on_motion_finished: None,
2346        done: false,
2347    }
2348}
2349
2350/// The other ways to make an `Icon`, beside [`Icon()`] with an id registered by role.
2351pub enum Icon {}
2352
2353impl Icon {
2354    /// An icon drawn from an SVG the application ships, registered with
2355    /// [`asset`](crate::asset::asset) as [`AssetKind::Svg`](crate::schema::AssetKind::Svg).
2356    ///
2357    /// The picture is drawn in the icon slot at the size an [`IconRole`] icon has in the
2358    /// design system, and in the icon's colour: every fill and every stroke takes the
2359    /// [`color`](AssetScope::color) given, or the colour an icon has when none is, and keeps
2360    /// its own alpha. A colour given as a role follows the light and the dark scheme.
2361    ///
2362    /// ```ignore
2363    /// static BELL: &[u8] = include_bytes!("../icons/bell.svg");
2364    ///
2365    /// Icon::asset(asset(AssetKind::Svg, BELL)).color(Paint::Role(ColorRole::Primary));
2366    /// ```
2367    pub fn asset(asset_id: AssetId) -> AssetScope {
2368        AssetScope {
2369            modifier: Modifier::new(),
2370            widget: WidgetKind::Icon,
2371            asset_id,
2372            tinted: true,
2373            color: None,
2374            content_scale: None,
2375            on_motion_finished: None,
2376            done: false,
2377        }
2378    }
2379}
2380
2381impl AssetScope {
2382    /// The tint. An icon only; an image ignores it, as the rsx widget has no such property.
2383    pub fn color(mut self, paint: Paint) -> Self {
2384        self.color = Some(paint);
2385        self
2386    }
2387
2388    /// How the picture is laid into its box. An image only; an icon takes its design
2389    /// system's optical size instead.
2390    ///
2391    /// Not calling it draws `ContentScale::Fit`, the whole picture in its own proportions.
2392    /// `ContentScale::FillBounds` stretches it to the box, as CSS `object-fit: fill` does.
2393    pub fn content_scale(mut self, scale: ContentScale) -> Self {
2394        self.content_scale = Some(scale);
2395        self
2396    }
2397
2398    fn compose(&mut self, content: impl FnOnce()) {
2399        let modifier = std::mem::take(&mut self.modifier);
2400        let (widget, asset_id, tinted, color) =
2401            (self.widget, self.asset_id, self.tinted, self.color);
2402        let content_scale = self.content_scale;
2403        let key = if widget == WidgetKind::Icon {
2404            widget_key("compose_rust::ui::Icon")
2405        } else {
2406            widget_key("compose_rust::ui::Image")
2407        };
2408        let motion = self.on_motion_finished.take();
2409        emit(
2410            key,
2411            widget,
2412            |attrs| {
2413                push_modifiers(&modifier, Mods::Standard, attrs);
2414                let property = if tinted { "icon_asset" } else { "asset" };
2415                attrs.push((property, OwnedAttr::Int(i64::from(asset_id))));
2416                if widget == WidgetKind::Icon {
2417                    attrs.push(("color", paint_or_zero(color)));
2418                }
2419                // A picture that never chose is not sent a choice, so it reaches the
2420                // Renderer exactly as it did before there was one.
2421                if let (WidgetKind::Image, Some(scale)) = (widget, content_scale) {
2422                    attrs.push(("content_scale", OwnedAttr::Int(i64::from(u16::from(scale)))));
2423                }
2424            },
2425            with_motion(Vec::new(), motion),
2426            content,
2427        );
2428    }
2429}
2430
2431composed_on_drop!(AssetScope);
2432motion_handler!(AssetScope);
2433
2434/// A `Canvas` and its builder.
2435pub struct CanvasScope {
2436    modifier: Modifier,
2437    commands: DrawList,
2438    view_box: Option<(f32, f32)>,
2439    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2440    done: bool,
2441}
2442
2443/// Pixels the widget vocabulary cannot produce. Compose's `Canvas`, with the drawing as a
2444/// value rather than a callback: drawing code cannot cross into the Renderer, and an equal
2445/// list costs no record.
2446pub fn Canvas(commands: DrawList) -> CanvasScope {
2447    let view_box = commands.view_box();
2448    CanvasScope {
2449        modifier: Modifier::new(),
2450        commands,
2451        view_box,
2452        on_motion_finished: None,
2453        done: false,
2454    }
2455}
2456
2457impl CanvasScope {
2458    /// Scales the command list's coordinates from `(width, height)` to the `Canvas`'s
2459    /// measured width and height. Stroke widths stay in dp.
2460    pub fn view_box(mut self, width: f32, height: f32) -> Self {
2461        self.view_box = Some((width, height));
2462        self
2463    }
2464
2465    /// Scales the command list's coordinates as `0.0..=1.0` fractions of the `Canvas`'s
2466    /// measured width and height. Stroke widths stay in dp.
2467    pub fn fractional(self) -> Self {
2468        self.view_box(1.0, 1.0)
2469    }
2470
2471    fn compose(&mut self, content: impl FnOnce()) {
2472        let modifier = std::mem::take(&mut self.modifier);
2473        let commands = std::mem::take(&mut self.commands);
2474        let view_box = self.view_box;
2475        let motion = self.on_motion_finished.take();
2476        emit(
2477            widget_key("compose_rust::ui::Canvas"),
2478            WidgetKind::Canvas,
2479            |attrs| {
2480                push_modifiers(&modifier, Mods::Standard, attrs);
2481                attrs.push(("commands", OwnedAttr::Draw(commands)));
2482                if let Some((width, height)) = view_box {
2483                    attrs.push(("min", OwnedAttr::Float(f64::from(width))));
2484                    attrs.push(("max", OwnedAttr::Float(f64::from(height))));
2485                }
2486            },
2487            with_motion(Vec::new(), motion),
2488            content,
2489        );
2490    }
2491}
2492
2493composed_on_drop!(CanvasScope);
2494motion_handler!(CanvasScope);
2495
2496// ----- pickers ----------------------------------------------------------------------------
2497
2498/// A `DatePicker` and its builder.
2499pub struct DatePickerScope {
2500    modifier: Modifier,
2501    value: i64,
2502    min: Option<i64>,
2503    max: Option<i64>,
2504    enabled: bool,
2505    on_change: Option<Box<dyn FnMut(i64)>>,
2506    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2507    done: bool,
2508}
2509
2510/// A date, as whole days since 1970-01-01. How it is picked is the design system's.
2511pub fn DatePicker(value: i64) -> DatePickerScope {
2512    DatePickerScope {
2513        modifier: Modifier::new(),
2514        value,
2515        min: None,
2516        max: None,
2517        enabled: true,
2518        on_change: None,
2519        on_motion_finished: None,
2520        done: false,
2521    }
2522}
2523
2524impl DatePickerScope {
2525    pub fn min(mut self, days: i64) -> Self {
2526        self.min = Some(days);
2527        self
2528    }
2529
2530    pub fn max(mut self, days: i64) -> Self {
2531        self.max = Some(days);
2532        self
2533    }
2534
2535    pub fn enabled(mut self, enabled: bool) -> Self {
2536        self.enabled = enabled;
2537        self
2538    }
2539
2540    pub fn on_change(mut self, handler: impl FnMut(i64) + 'static) -> Self {
2541        self.on_change = Some(std::boxed::Box::new(handler));
2542        self
2543    }
2544
2545    fn compose(&mut self, content: impl FnOnce()) {
2546        let modifier = std::mem::take(&mut self.modifier);
2547        let (value, min, max, enabled) = (self.value, self.min, self.max, self.enabled);
2548        let handler = match self.on_change.take() {
2549            Some(mut handler) => EventCallback::Value(Rc::new(RefCell::new(move |value: f64| {
2550                handler(value as i64)
2551            }))),
2552            None => value_handler(None),
2553        };
2554        let motion = self.on_motion_finished.take();
2555        emit(
2556            widget_key("compose_rust::ui::DatePicker"),
2557            WidgetKind::DatePicker,
2558            |attrs| {
2559                push_modifiers(&modifier, Mods::Standard, attrs);
2560                attrs.push(("value", OwnedAttr::Int(value)));
2561                attrs.push(("min", OwnedAttr::Int(min.unwrap_or(i64::MIN))));
2562                attrs.push(("max", OwnedAttr::Int(max.unwrap_or(i64::MAX))));
2563                attrs.push(("enabled", OwnedAttr::Bool(enabled)));
2564            },
2565            with_motion(vec![("onchange", handler)], motion),
2566            content,
2567        );
2568    }
2569}
2570
2571composed_on_drop!(DatePickerScope);
2572motion_handler!(DatePickerScope);
2573
2574const MINUTES_IN_A_DAY: u32 = 24 * 60;
2575
2576/// A `TimePicker` and its builder.
2577pub struct TimePickerScope {
2578    modifier: Modifier,
2579    value: u32,
2580    min: Option<u32>,
2581    max: Option<u32>,
2582    enabled: bool,
2583    on_change: Option<Box<dyn FnMut(u32)>>,
2584    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2585    done: bool,
2586}
2587
2588/// A time of day, as minutes since midnight.
2589pub fn TimePicker(value: u32) -> TimePickerScope {
2590    TimePickerScope {
2591        modifier: Modifier::new(),
2592        value,
2593        min: None,
2594        max: None,
2595        enabled: true,
2596        on_change: None,
2597        on_motion_finished: None,
2598        done: false,
2599    }
2600}
2601
2602impl TimePickerScope {
2603    pub fn min(mut self, minutes: u32) -> Self {
2604        self.min = Some(minutes);
2605        self
2606    }
2607
2608    pub fn max(mut self, minutes: u32) -> Self {
2609        self.max = Some(minutes);
2610        self
2611    }
2612
2613    pub fn enabled(mut self, enabled: bool) -> Self {
2614        self.enabled = enabled;
2615        self
2616    }
2617
2618    pub fn on_change(mut self, handler: impl FnMut(u32) + 'static) -> Self {
2619        self.on_change = Some(std::boxed::Box::new(handler));
2620        self
2621    }
2622
2623    fn compose(&mut self, content: impl FnOnce()) {
2624        let modifier = std::mem::take(&mut self.modifier);
2625        let (value, min, max, enabled) = (self.value, self.min, self.max, self.enabled);
2626        let handler = match self.on_change.take() {
2627            Some(mut handler) => EventCallback::Value(Rc::new(RefCell::new(move |value: f64| {
2628                handler((value as i64).clamp(0, i64::from(MINUTES_IN_A_DAY - 1)) as u32)
2629            }))),
2630            None => value_handler(None),
2631        };
2632        let motion = self.on_motion_finished.take();
2633        emit(
2634            widget_key("compose_rust::ui::TimePicker"),
2635            WidgetKind::TimePicker,
2636            |attrs| {
2637                push_modifiers(&modifier, Mods::Standard, attrs);
2638                attrs.push(("value", OwnedAttr::Int(i64::from(value))));
2639                attrs.push(("min", OwnedAttr::Int(i64::from(min.unwrap_or(0)))));
2640                attrs.push((
2641                    "max",
2642                    OwnedAttr::Int(i64::from(max.unwrap_or(MINUTES_IN_A_DAY - 1))),
2643                ));
2644                attrs.push(("enabled", OwnedAttr::Bool(enabled)));
2645            },
2646            with_motion(vec![("onchange", handler)], motion),
2647            content,
2648        );
2649    }
2650}
2651
2652composed_on_drop!(TimePickerScope);
2653motion_handler!(TimePickerScope);
2654
2655/// A `Dropdown` and its builder.
2656pub struct DropdownScope {
2657    modifier: Modifier,
2658    selected_index: usize,
2659    enabled: bool,
2660    closed: bool,
2661    bare: bool,
2662    on_change: Option<Box<dyn FnMut(usize)>>,
2663    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2664    done: bool,
2665}
2666
2667/// One choice out of a list; each child is one option.
2668pub fn Dropdown(selected_index: usize) -> DropdownScope {
2669    DropdownScope {
2670        modifier: Modifier::new(),
2671        selected_index,
2672        enabled: true,
2673        closed: false,
2674        bare: false,
2675        on_change: None,
2676        on_motion_finished: None,
2677        done: false,
2678    }
2679}
2680
2681/// A compact closed-field selector that always rests as a single line and opens its
2682/// options in a popup below the field on every design system.
2683pub fn Select(selected_index: usize) -> DropdownScope {
2684    Dropdown(selected_index).closed(true)
2685}
2686
2687impl DropdownScope {
2688    pub fn enabled(mut self, enabled: bool) -> Self {
2689        self.enabled = enabled;
2690        self
2691    }
2692
2693    /// Keeps the control as a closed single-line field that opens a popup menu on click,
2694    /// even on design systems whose default picker presentation is a wheel.
2695    pub fn closed(mut self, closed: bool) -> Self {
2696        self.closed = closed;
2697        self
2698    }
2699
2700    pub fn on_change(mut self, handler: impl FnMut(usize) + 'static) -> Self {
2701        self.on_change = Some(std::boxed::Box::new(handler));
2702        self
2703    }
2704
2705    /// Draws the closed field without the design system's frame: no fill, line, corner
2706    /// clip, inner padding, minimum height or focus line. For a select that sits inside a
2707    /// box which already draws its own frame. A `background` or `border` given on the node
2708    /// is still drawn.
2709    pub fn bare(mut self) -> Self {
2710        self.bare = true;
2711        self
2712    }
2713
2714    fn compose(&mut self, content: impl FnOnce()) {
2715        let modifier = std::mem::take(&mut self.modifier);
2716        let (selected_index, enabled, closed) = (self.selected_index, self.enabled, self.closed);
2717        let bare = self.bare;
2718        let handler = match self.on_change.take() {
2719            Some(mut handler) => EventCallback::Value(Rc::new(RefCell::new(move |value: f64| {
2720                handler((value as i64).max(0) as usize)
2721            }))),
2722            None => value_handler(None),
2723        };
2724        let motion = self.on_motion_finished.take();
2725        emit(
2726            widget_key("compose_rust::ui::Dropdown"),
2727            WidgetKind::Dropdown,
2728            |attrs| {
2729                push_modifiers(&modifier, Mods::Standard, attrs);
2730                attrs.push(("selected_index", OwnedAttr::Int(selected_index as i64)));
2731                attrs.push(("enabled", OwnedAttr::Bool(enabled)));
2732                if closed {
2733                    attrs.push(("collapsible", OwnedAttr::Bool(true)));
2734                }
2735                if bare {
2736                    attrs.push(("bare", OwnedAttr::Bool(true)));
2737                }
2738            },
2739            with_motion(vec![("onchange", handler)], motion),
2740            content,
2741        );
2742    }
2743}
2744
2745container!(DropdownScope);
2746motion_handler!(DropdownScope);
2747
2748/// A `MenuItem` and its builder.
2749pub struct MenuItemScope {
2750    modifier: Modifier,
2751    text: String,
2752    icon: Option<IconRole>,
2753    selected: bool,
2754    enabled: bool,
2755    color: Option<Paint>,
2756    on_click: Option<Box<dyn FnMut()>>,
2757    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2758    done: bool,
2759}
2760
2761/// A single row in a `Menu` or action list: left-aligned label, optional leading icon,
2762/// and optional selected state.
2763pub fn MenuItem(text: impl Into<String>) -> MenuItemScope {
2764    MenuItemScope {
2765        modifier: Modifier::new(),
2766        text: text.into(),
2767        icon: None,
2768        selected: false,
2769        enabled: true,
2770        color: None,
2771        on_click: None,
2772        on_motion_finished: None,
2773        done: false,
2774    }
2775}
2776
2777impl MenuItemScope {
2778    /// Leading semantic icon for this menu row.
2779    pub fn icon(mut self, icon: IconRole) -> Self {
2780        self.icon = Some(icon);
2781        self
2782    }
2783
2784    /// Marks this row as the currently selected option.
2785    pub fn selected(mut self, selected: bool) -> Self {
2786        self.selected = selected;
2787        self
2788    }
2789
2790    pub fn enabled(mut self, enabled: bool) -> Self {
2791        self.enabled = enabled;
2792        self
2793    }
2794
2795    /// Overrides the row's label and icon colour (for example, a destructive action).
2796    pub fn color(mut self, paint: Paint) -> Self {
2797        self.color = Some(paint);
2798        self
2799    }
2800
2801    /// Conditional colour override.
2802    pub fn color_if(mut self, paint: Option<Paint>) -> Self {
2803        self.color = paint;
2804        self
2805    }
2806
2807    pub fn on_click(mut self, handler: impl FnMut() + 'static) -> Self {
2808        self.on_click = Some(std::boxed::Box::new(handler));
2809        self
2810    }
2811
2812    fn compose(&mut self, content: impl FnOnce()) {
2813        let modifier = std::mem::take(&mut self.modifier);
2814        let text = std::mem::take(&mut self.text);
2815        let (icon, selected, enabled, color) = (self.icon, self.selected, self.enabled, self.color);
2816        let mut listeners = vec![("onclick", unit(self.on_click.take()))];
2817        motion_input(self.on_motion_finished.take(), &mut listeners);
2818        emit(
2819            widget_key("compose_rust::ui::MenuItem"),
2820            WidgetKind::Button,
2821            |attrs| {
2822                push_modifiers(&modifier, Mods::Standard, attrs);
2823                attrs.push(("text", OwnedAttr::Text(text)));
2824                attrs.push(("icon", super::role(icon)));
2825                attrs.push(("enabled", OwnedAttr::Bool(enabled)));
2826                attrs.push(("variant", role_or_zero(Some(ButtonVariant::Text))));
2827                attrs.push(("text_align", role_or_zero(Some(TextAlign::Start))));
2828                attrs.push(("checked", OwnedAttr::Bool(selected)));
2829                attrs.push(("color", super::paint(color)));
2830            },
2831            listeners,
2832            content,
2833        );
2834    }
2835}
2836
2837composed_on_drop!(MenuItemScope);
2838motion_handler!(MenuItemScope);
2839
2840// ----- surfaces that come and go ----------------------------------------------------------
2841
2842/// A `Dialog` or a `Sheet` and its builder: `open` seeds the Renderer's own open state,
2843/// and `on_dismiss` says once that the user asked to close it.
2844pub struct ModalScope {
2845    modifier: Modifier,
2846    widget: WidgetKind,
2847    open: bool,
2848    scrim: Option<Paint>,
2849    max_height_fraction: Option<f32>,
2850    presentation: SheetPresentation,
2851    max_width: Option<u32>,
2852    on_dismiss: Option<Box<dyn FnMut()>>,
2853    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2854    done: bool,
2855}
2856
2857/// A modal. Compose's `Dialog`, kept in the tree and opened by `open`, so its enter and
2858/// exit belong to the Renderer.
2859pub fn Dialog(open: bool) -> ModalScope {
2860    ModalScope {
2861        modifier: Modifier::new(),
2862        widget: WidgetKind::Dialog,
2863        open,
2864        scrim: None,
2865        max_height_fraction: None,
2866        presentation: SheetPresentation::Edge,
2867        max_width: None,
2868        on_dismiss: None,
2869        on_motion_finished: None,
2870        done: false,
2871    }
2872}
2873
2874/// A surface that slides in from the edge the Renderer chooses. Compose's
2875/// `ModalBottomSheet`, without a promise about which edge.
2876pub fn Sheet(open: bool) -> ModalScope {
2877    ModalScope {
2878        modifier: Modifier::new(),
2879        widget: WidgetKind::Sheet,
2880        open,
2881        scrim: None,
2882        max_height_fraction: None,
2883        presentation: SheetPresentation::Edge,
2884        max_width: None,
2885        on_dismiss: None,
2886        on_motion_finished: None,
2887        done: false,
2888    }
2889}
2890
2891impl ModalScope {
2892    pub fn on_dismiss(mut self, handler: impl FnMut() + 'static) -> Self {
2893        self.on_dismiss = Some(std::boxed::Box::new(handler));
2894        self
2895    }
2896
2897    /// Sets the modal scrim colour, overriding the design system default.
2898    pub fn scrim(mut self, paint: impl Into<Paint>) -> Self {
2899        self.scrim = Some(paint.into());
2900        self
2901    }
2902
2903    /// The tallest the sheet grows, as a fraction of the window's height, above 0 and at
2904    /// most 1.
2905    ///
2906    /// Below it the sheet is as tall as its content; content taller than that stops the
2907    /// sheet at the fraction and scrolls inside it. A fraction above 1 is taken as 1, and
2908    /// one that is not above 0 is not sent, which leaves the height to the design system
2909    /// as it is without this call. A `Dialog` sizes itself to its content and does not
2910    /// take it.
2911    pub fn max_height_fraction(mut self, fraction: f32) -> Self {
2912        self.max_height_fraction = (fraction > 0.0).then(|| fraction.min(1.0));
2913        self
2914    }
2915
2916    /// What form the sheet takes: an edge drawer (`Edge`, the default) or a centered modal
2917    /// (`Centered`). A `Dialog` is always centered and does not take this.
2918    pub fn presentation(mut self, presentation: SheetPresentation) -> Self {
2919        self.presentation = presentation;
2920        self
2921    }
2922
2923    /// The maximum width of a centered sheet in dp.
2924    ///
2925    /// Zero or absent leaves the width to the design system (560 dp). Content wider than
2926    /// this or a window narrower than this shrinks the sheet to fit. An edge sheet sizes
2927    /// its width by its edge and does not take this.
2928    pub fn max_width(mut self, max_width_dp: u32) -> Self {
2929        self.max_width = (max_width_dp > 0).then_some(max_width_dp);
2930        self
2931    }
2932
2933    fn compose(&mut self, content: impl FnOnce()) {
2934        let modifier = std::mem::take(&mut self.modifier);
2935        let (widget, open) = (self.widget, self.open);
2936        let max_height_fraction = self
2937            .max_height_fraction
2938            .filter(|_| widget == WidgetKind::Sheet);
2939        let presentation = self.presentation;
2940        let max_width = self.max_width.filter(|_| widget == WidgetKind::Sheet);
2941        let key = if widget == WidgetKind::Dialog {
2942            widget_key("compose_rust::ui::Dialog")
2943        } else {
2944            widget_key("compose_rust::ui::Sheet")
2945        };
2946        let scrim = self.scrim;
2947        let motion = self.on_motion_finished.take();
2948        emit(
2949            key,
2950            widget,
2951            |attrs| {
2952                push_modifiers(&modifier, Mods::Standard, attrs);
2953                attrs.push(("open", OwnedAttr::Bool(open)));
2954                if let Some(scrim) = scrim {
2955                    attrs.push(("scrim", super::paint(Some(scrim))));
2956                }
2957                if let Some(fraction) = max_height_fraction {
2958                    attrs.push(("max_height_fraction", OwnedAttr::Float(f64::from(fraction))));
2959                }
2960                if widget == WidgetKind::Sheet && presentation != SheetPresentation::Edge {
2961                    attrs.push((
2962                        "presentation",
2963                        OwnedAttr::Int(i64::from(u16::from(presentation))),
2964                    ));
2965                }
2966                if let Some(max_width) = max_width {
2967                    attrs.push(("max_width", OwnedAttr::Int(i64::from(max_width))));
2968                }
2969            },
2970            with_motion(vec![("ondismiss", unit(self.on_dismiss.take()))], motion),
2971            content,
2972        );
2973    }
2974}
2975
2976container!(ModalScope);
2977motion_handler!(ModalScope);
2978
2979/// A `Menu` and its builder.
2980pub struct MenuScope<'a> {
2981    modifier: Modifier,
2982    expanded: bool,
2983    scrim: Option<Paint>,
2984    on_dismiss: Option<Box<dyn FnMut()>>,
2985    anchor: Option<Box<dyn FnOnce() + 'a>>,
2986    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
2987    done: bool,
2988}
2989
2990/// A popup hanging off its anchor. Compose's `DropdownMenu`, with the anchor said rather
2991/// than positioned: the Renderer places the popup.
2992pub fn Menu<'a>(expanded: bool) -> MenuScope<'a> {
2993    MenuScope {
2994        modifier: Modifier::new(),
2995        expanded,
2996        scrim: None,
2997        on_dismiss: None,
2998        anchor: None,
2999        on_motion_finished: None,
3000        done: false,
3001    }
3002}
3003
3004impl<'a> MenuScope<'a> {
3005    pub fn on_dismiss(mut self, handler: impl FnMut() + 'static) -> Self {
3006        self.on_dismiss = Some(std::boxed::Box::new(handler));
3007        self
3008    }
3009
3010    /// Sets the popup scrim colour, overriding the design system default.
3011    pub fn scrim(mut self, paint: impl Into<Paint>) -> Self {
3012        self.scrim = Some(paint.into());
3013        self
3014    }
3015
3016    /// The widget the menu hangs off. It is the first child on the wire.
3017    pub fn anchor(mut self, anchor: impl FnOnce() + 'a) -> Self {
3018        self.anchor = Some(std::boxed::Box::new(anchor));
3019        self
3020    }
3021
3022    fn compose(&mut self, content: impl FnOnce()) {
3023        let modifier = std::mem::take(&mut self.modifier);
3024        let expanded = self.expanded;
3025        let anchor = self.anchor.take();
3026        let scrim = self.scrim;
3027        let motion = self.on_motion_finished.take();
3028        emit(
3029            widget_key("compose_rust::ui::Menu"),
3030            WidgetKind::Menu,
3031            |attrs| {
3032                push_modifiers(&modifier, Mods::Standard, attrs);
3033                attrs.push(("open", OwnedAttr::Bool(expanded)));
3034                if let Some(scrim) = scrim {
3035                    attrs.push(("scrim", super::paint(Some(scrim))));
3036                }
3037            },
3038            with_motion(vec![("ondismiss", unit(self.on_dismiss.take()))], motion),
3039            || {
3040                if let Some(anchor) = anchor {
3041                    let _anchor =
3042                        crate::runtime::group_guard(widget_key("compose_rust::ui::Menu::anchor"));
3043                    anchor();
3044                }
3045                let _entries =
3046                    crate::runtime::group_guard(widget_key("compose_rust::ui::Menu::entries"));
3047                content();
3048            },
3049        );
3050    }
3051}
3052
3053container!(MenuScope<'a>);
3054motion_handler!(MenuScope<'a>);
3055
3056/// A `Popover` and its builder.
3057pub struct PopoverScope<'a> {
3058    modifier: Modifier,
3059    open: bool,
3060    placement: Option<PopoverPlacement>,
3061    align: Option<PopoverAlign>,
3062    offset: Option<f32>,
3063    scrim: bool,
3064    scrim_color: Option<Paint>,
3065    on_dismiss: Option<Box<dyn FnMut()>>,
3066    anchor: Option<Box<dyn FnOnce() + 'a>>,
3067    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3068    done: bool,
3069}
3070
3071/// A floating box of any content attached to its anchor.
3072///
3073/// The anchor is always drawn. The content is drawn only while `open` is true, and `open`
3074/// is the application's: pressing outside the box or pressing Escape calls `on_dismiss`
3075/// once and changes nothing, so the handler is where the application closes it or keeps
3076/// it open to ask about unsaved work.
3077///
3078/// The Renderer places the box. It opens on the side `placement` names, lined up with the
3079/// edge `align` names, and it moves to the opposite side or slides along the edge when it
3080/// would otherwise leave the window.
3081///
3082/// `modifier` belongs to the floating box, not to the anchor: a shape, a border, a shadow
3083/// or a material given there replaces the design system's for this box.
3084pub fn Popover<'a>(open: bool) -> PopoverScope<'a> {
3085    PopoverScope {
3086        modifier: Modifier::new(),
3087        open,
3088        placement: None,
3089        align: None,
3090        offset: None,
3091        scrim: false,
3092        scrim_color: None,
3093        on_dismiss: None,
3094        anchor: None,
3095        on_motion_finished: None,
3096        done: false,
3097    }
3098}
3099
3100impl<'a> PopoverScope<'a> {
3101    /// Called once when the user presses outside the box or presses Escape.
3102    pub fn on_dismiss(mut self, handler: impl FnMut() + 'static) -> Self {
3103        self.on_dismiss = Some(std::boxed::Box::new(handler));
3104        self
3105    }
3106
3107    /// The side of the anchor the box opens on. `Bottom` when it is not said.
3108    pub fn placement(mut self, placement: PopoverPlacement) -> Self {
3109        self.placement = Some(placement);
3110        self
3111    }
3112
3113    /// The edge of the anchor the box lines up with. `Start` when it is not said.
3114    pub fn align(mut self, align: PopoverAlign) -> Self {
3115        self.align = Some(align);
3116        self
3117    }
3118
3119    /// The gap between the anchor and the box, in dp. The design system's gap when it is
3120    /// not said.
3121    pub fn offset(mut self, dp: f32) -> Self {
3122        self.offset = Some(dp);
3123        self
3124    }
3125
3126    /// Whether the window behind the box is dimmed while it is open. It is not, unless
3127    /// asked.
3128    pub fn scrim(mut self, scrim: bool) -> Self {
3129        self.scrim = scrim;
3130        self
3131    }
3132
3133    /// Dims the window behind the box with this colour instead of the design system's.
3134    pub fn scrim_color(mut self, paint: impl Into<Paint>) -> Self {
3135        self.scrim_color = Some(paint.into());
3136        self
3137    }
3138
3139    /// The widget the box is attached to. It is the first child on the wire.
3140    pub fn anchor(mut self, anchor: impl FnOnce() + 'a) -> Self {
3141        self.anchor = Some(std::boxed::Box::new(anchor));
3142        self
3143    }
3144
3145    fn compose(&mut self, content: impl FnOnce()) {
3146        let modifier = std::mem::take(&mut self.modifier);
3147        let open = self.open;
3148        let (placement, align, offset) = (self.placement, self.align, self.offset);
3149        let (scrim, scrim_color) = (self.scrim, self.scrim_color);
3150        let anchor = self.anchor.take();
3151        let motion = self.on_motion_finished.take();
3152        emit(
3153            widget_key("compose_rust::ui::Popover"),
3154            WidgetKind::Popover,
3155            |attrs| {
3156                push_modifiers(&modifier, Mods::Standard, attrs);
3157                attrs.push(("open", OwnedAttr::Bool(open)));
3158                if let Some(placement) = placement {
3159                    attrs.push(("placement", role_or_zero(Some(placement))));
3160                }
3161                if let Some(align) = align {
3162                    attrs.push(("align", role_or_zero(Some(align))));
3163                }
3164                if let Some(offset) = offset {
3165                    attrs.push(("offset_dp", OwnedAttr::Float(f64::from(offset))));
3166                }
3167                if let Some(color) = scrim_color {
3168                    attrs.push(("scrim", super::paint(Some(color))));
3169                } else if scrim {
3170                    attrs.push(("scrim", OwnedAttr::Bool(true)));
3171                }
3172            },
3173            with_motion(vec![("ondismiss", unit(self.on_dismiss.take()))], motion),
3174            || {
3175                if let Some(anchor) = anchor {
3176                    let _anchor = crate::runtime::group_guard(widget_key(
3177                        "compose_rust::ui::Popover::anchor",
3178                    ));
3179                    anchor();
3180                }
3181                let _content =
3182                    crate::runtime::group_guard(widget_key("compose_rust::ui::Popover::content"));
3183                content();
3184            },
3185        );
3186    }
3187}
3188
3189container!(PopoverScope<'a>);
3190motion_handler!(PopoverScope<'a>);
3191
3192// ----- platform views -------------------------------------------------------------------
3193
3194/// A `NativeView` and its builder.
3195pub struct NativeViewScope {
3196    modifier: Modifier,
3197    handle: crate::schema::NativeHandle,
3198    visible: bool,
3199    on_focus_change: Option<Box<dyn FnMut(bool)>>,
3200    done: bool,
3201}
3202
3203/// A place in the window for a platform view the application made: a web view, a video
3204/// surface or a map, as an `NSView`, an `HWND` or an X11 window.
3205///
3206/// Make the view against the handle the window reported
3207/// (`compose_rust::native_view::native_parent`), then hand it over here. The Renderer
3208/// puts it over this node's rectangle and keeps it there as the layout moves and scrolls,
3209/// cuts it to what the node's ancestors and any menu, popover or dialog drawn above it
3210/// leave showing, and hands keyboard focus to it and back. It never destroys the view:
3211/// once the node is gone, or `NativeHandle::NONE` has replaced the handle, and the batch
3212/// saying so has been applied, the view is the application's to destroy.
3213///
3214/// The node has no size of its own. Give it one with its modifier (a size, a fill, a
3215/// weight); what the modifier draws shows only where the view does not cover it.
3216pub fn NativeView(handle: crate::schema::NativeHandle) -> NativeViewScope {
3217    NativeViewScope {
3218        modifier: Modifier::new(),
3219        handle,
3220        visible: true,
3221        on_focus_change: None,
3222        done: false,
3223    }
3224}
3225
3226impl NativeViewScope {
3227    /// Whether the view shows. A hidden view stays in the window with everything it holds,
3228    /// so showing it again shows the same page; only removing the node takes it out.
3229    pub fn visible(mut self, visible: bool) -> Self {
3230        self.visible = visible;
3231        self
3232    }
3233
3234    /// Hears the view take keyboard focus (`true`) and lose it (`false`): a click in it, a
3235    /// focus request, the window going to the background and coming back.
3236    pub fn on_focus_change(mut self, handler: impl FnMut(bool) + 'static) -> Self {
3237        self.on_focus_change = Some(std::boxed::Box::new(handler));
3238        self
3239    }
3240
3241    fn compose(&mut self, _content: impl FnOnce()) {
3242        let modifier = std::mem::take(&mut self.modifier);
3243        let visible = self.visible;
3244        let handle = self.handle;
3245        let mut listeners = Vec::new();
3246        if let Some(mut handler) = self.on_focus_change.take() {
3247            listeners.push((
3248                "onnativeviewfocus",
3249                EventCallback::Value(Rc::new(RefCell::new(move |value: f64| {
3250                    handler(value != 0.0)
3251                }))),
3252            ));
3253        }
3254        let _group = crate::runtime::group_guard(widget_key("compose_rust::ui::NativeView"));
3255        // The node and the handle last written for it. The handle is a command rather than
3256        // a property, so it goes out only when it changed or the node is new.
3257        let sent: Rc<std::cell::Cell<(u32, u64)>> =
3258            crate::runtime::remember(|| Rc::new(std::cell::Cell::new((0, 0))));
3259        super::emit_node(
3260            WidgetKind::NativeView,
3261            |attrs| {
3262                push_modifiers(&modifier, Mods::Standard, attrs);
3263                if !visible {
3264                    attrs.push(("native_visible", OwnedAttr::Bool(false)));
3265                }
3266            },
3267            listeners,
3268            // A NativeView takes no children: the content is the place to write the
3269            // command, because it runs with the node's id at hand.
3270            || {
3271                crate::runtime::with_composer(|composer| {
3272                    let Some(node) = composer.node_stack.last().map(|context| context.parent)
3273                    else {
3274                        return;
3275                    };
3276                    let (sent_node, sent_handle) = sent.get();
3277                    // A new node with no view needs nothing written: it has none yet.
3278                    let unchanged = if sent_node == node {
3279                        sent_handle == handle.0
3280                    } else {
3281                        handle.is_none()
3282                    };
3283                    if !unchanged {
3284                        composer.writer.batch_mut().attach_native_view(node, handle);
3285                    }
3286                    sent.set((node, handle.0));
3287                });
3288            },
3289        );
3290    }
3291}
3292
3293composed_on_drop!(NativeViewScope);
3294
3295/// A `Tabs` and its builder.
3296pub struct TabsScope {
3297    modifier: Modifier,
3298    color: Option<Paint>,
3299    selected_index: usize,
3300    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3301    done: bool,
3302}
3303
3304/// A row of tabs; each child is one tab, and a tap is that child's own click. Compose's
3305/// `TabRow`.
3306pub fn Tabs(selected_index: usize) -> TabsScope {
3307    TabsScope {
3308        modifier: Modifier::new(),
3309        color: None,
3310        selected_index,
3311        on_motion_finished: None,
3312        done: false,
3313    }
3314}
3315
3316impl TabsScope {
3317    /// The mark that shows which tab is selected.
3318    pub fn color(mut self, paint: Paint) -> Self {
3319        self.color = Some(paint);
3320        self
3321    }
3322
3323    fn compose(&mut self, content: impl FnOnce()) {
3324        let modifier = std::mem::take(&mut self.modifier);
3325        let (color, selected_index) = (self.color, self.selected_index);
3326        let motion = self.on_motion_finished.take();
3327        emit(
3328            widget_key("compose_rust::ui::Tabs"),
3329            WidgetKind::Tabs,
3330            |attrs| {
3331                push_modifiers(&modifier, Mods::Standard, attrs);
3332                attrs.push(("color", super::paint(color)));
3333                attrs.push(("selected_index", OwnedAttr::Int(selected_index as i64)));
3334            },
3335            with_motion(Vec::new(), motion),
3336            content,
3337        );
3338    }
3339}
3340
3341container!(TabsScope);
3342motion_handler!(TabsScope);
3343
3344/// A `TopAppBar` and its builder.
3345pub struct TopAppBarScope {
3346    modifier: Modifier,
3347    title: String,
3348    separator: Option<bool>,
3349    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3350    done: bool,
3351}
3352
3353/// The bar across the top of a screen; its children are its content. Compose's
3354/// `TopAppBar`, with the title a property so the Renderer can find it.
3355pub fn TopAppBar() -> TopAppBarScope {
3356    TopAppBarScope {
3357        modifier: Modifier::new(),
3358        title: String::new(),
3359        separator: None,
3360        on_motion_finished: None,
3361        done: false,
3362    }
3363}
3364
3365impl TopAppBarScope {
3366    pub fn title(mut self, title: impl Into<String>) -> Self {
3367        self.title = title.into();
3368        self
3369    }
3370
3371    /// Whether to draw the design system's hairline separator under the bar.
3372    ///
3373    /// When unset, the active design system decides (e.g. Cupertino, Fluent and GNOME draw one;
3374    /// Material 3 and Deepin do not; setting a custom border on the bar also suppresses it).
3375    pub fn hairline(mut self, show: bool) -> Self {
3376        self.separator = Some(show);
3377        self
3378    }
3379
3380    /// Alias for [`Self::hairline`].
3381    pub fn separator(mut self, show: bool) -> Self {
3382        self.separator = Some(show);
3383        self
3384    }
3385
3386    fn compose(&mut self, content: impl FnOnce()) {
3387        let modifier = std::mem::take(&mut self.modifier);
3388        let title = std::mem::take(&mut self.title);
3389        let separator = self.separator;
3390        let motion = self.on_motion_finished.take();
3391        emit(
3392            widget_key("compose_rust::ui::TopAppBar"),
3393            WidgetKind::TopAppBar,
3394            |attrs| {
3395                push_modifiers(&modifier, Mods::Standard, attrs);
3396                attrs.push(("text", OwnedAttr::Text(title)));
3397                if let Some(separator) = separator {
3398                    attrs.push(("separator", OwnedAttr::Bool(separator)));
3399                }
3400            },
3401            with_motion(Vec::new(), motion),
3402            content,
3403        );
3404    }
3405}
3406
3407container!(TopAppBarScope);
3408motion_handler!(TopAppBarScope);
3409
3410/// A `Tooltip` and its builder.
3411pub struct TooltipScope {
3412    modifier: Modifier,
3413    text: String,
3414    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3415    done: bool,
3416}
3417
3418/// An explanation attached to its child, which assistive technology reads too. Compose's
3419/// `TooltipBox`.
3420pub fn Tooltip(text: impl Into<String>) -> TooltipScope {
3421    TooltipScope {
3422        modifier: Modifier::new(),
3423        text: text.into(),
3424        on_motion_finished: None,
3425        done: false,
3426    }
3427}
3428
3429impl TooltipScope {
3430    fn compose(&mut self, content: impl FnOnce()) {
3431        let modifier = std::mem::take(&mut self.modifier);
3432        let text = std::mem::take(&mut self.text);
3433        let motion = self.on_motion_finished.take();
3434        emit(
3435            widget_key("compose_rust::ui::Tooltip"),
3436            WidgetKind::Tooltip,
3437            |attrs| {
3438                push_modifiers(&modifier, Mods::Standard, attrs);
3439                attrs.push(("text", OwnedAttr::Text(text)));
3440            },
3441            with_motion(Vec::new(), motion),
3442            content,
3443        );
3444    }
3445}
3446
3447container!(TooltipScope);
3448motion_handler!(TooltipScope);
3449
3450// ----- frames and navigation --------------------------------------------------------------
3451
3452/// Composes one slot of a frame: a ScaffoldSlot node holding `content`, in a group of its
3453/// own so that a slot coming and going leaves the others where they were.
3454fn slot(role: SlotRole, key: u64, content: impl FnOnce()) {
3455    emit(
3456        key,
3457        WidgetKind::ScaffoldSlot,
3458        |attrs| attrs.push(("slot", OwnedAttr::Int(i64::from(u16::from(role))))),
3459        Vec::new(),
3460        content,
3461    );
3462}
3463
3464type Slot<'a> = Option<Box<dyn FnOnce() + 'a>>;
3465
3466/// A `Scaffold` and its builder.
3467pub struct ScaffoldScope<'a> {
3468    modifier: Modifier,
3469    top_bar: Slot<'a>,
3470    bottom_bar: Slot<'a>,
3471    floating_action: Slot<'a>,
3472    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3473    done: bool,
3474}
3475
3476/// The screen's frame: which slots it has filled, and the page. Compose's `Scaffold`.
3477/// What each slot becomes on this platform at this width is the Renderer's decision.
3478///
3479/// The Modifier carries the two things a frame takes: `background` and `material`.
3480pub fn Scaffold<'a>() -> ScaffoldScope<'a> {
3481    ScaffoldScope {
3482        modifier: Modifier::new(),
3483        top_bar: None,
3484        bottom_bar: None,
3485        floating_action: None,
3486        on_motion_finished: None,
3487        done: false,
3488    }
3489}
3490
3491impl<'a> ScaffoldScope<'a> {
3492    pub fn top_bar(mut self, bar: impl FnOnce() + 'a) -> Self {
3493        self.top_bar = Some(std::boxed::Box::new(bar));
3494        self
3495    }
3496
3497    pub fn bottom_bar(mut self, bar: impl FnOnce() + 'a) -> Self {
3498        self.bottom_bar = Some(std::boxed::Box::new(bar));
3499        self
3500    }
3501
3502    pub fn floating_action(mut self, action: impl FnOnce() + 'a) -> Self {
3503        self.floating_action = Some(std::boxed::Box::new(action));
3504        self
3505    }
3506
3507    fn compose(&mut self, content: impl FnOnce()) {
3508        let modifier = std::mem::take(&mut self.modifier);
3509        let (top_bar, bottom_bar, floating_action) = (
3510            self.top_bar.take(),
3511            self.bottom_bar.take(),
3512            self.floating_action.take(),
3513        );
3514        let motion = self.on_motion_finished.take();
3515        emit(
3516            widget_key("compose_rust::ui::Scaffold"),
3517            WidgetKind::Scaffold,
3518            |attrs| push_modifiers(&modifier, Mods::Scaffold, attrs),
3519            with_motion(Vec::new(), motion),
3520            || {
3521                if let Some(bar) = top_bar {
3522                    slot(
3523                        SlotRole::TopBar,
3524                        widget_key("compose_rust::ui::Scaffold::top_bar"),
3525                        bar,
3526                    );
3527                }
3528                if let Some(bar) = bottom_bar {
3529                    slot(
3530                        SlotRole::BottomBar,
3531                        widget_key("compose_rust::ui::Scaffold::bottom_bar"),
3532                        bar,
3533                    );
3534                }
3535                if let Some(action) = floating_action {
3536                    slot(
3537                        SlotRole::FloatingAction,
3538                        widget_key("compose_rust::ui::Scaffold::floating_action"),
3539                        action,
3540                    );
3541                }
3542                slot(
3543                    SlotRole::Content,
3544                    widget_key("compose_rust::ui::Scaffold::content"),
3545                    content,
3546                );
3547            },
3548        );
3549    }
3550}
3551
3552container!(ScaffoldScope<'a>);
3553motion_handler!(ScaffoldScope<'a>);
3554
3555/// A `Navigation` and its builder.
3556pub struct NavigationScope<'a> {
3557    modifier: Modifier,
3558    selected_index: usize,
3559    compact: CompactNavigation,
3560    head: Slot<'a>,
3561    foot: Slot<'a>,
3562    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3563    done: bool,
3564}
3565
3566/// A set of destinations and the screen they lead to. The children that are
3567/// `NavigationItem`s are the destinations; whether they are a bar, a rail or a drawer is
3568/// the Renderer's choice. Compose's `NavigationSuiteScaffold`.
3569pub fn Navigation<'a>(selected_index: usize) -> NavigationScope<'a> {
3570    NavigationScope {
3571        modifier: Modifier::new(),
3572        selected_index,
3573        compact: CompactNavigation::Default,
3574        head: None,
3575        foot: None,
3576        on_motion_finished: None,
3577        done: false,
3578    }
3579}
3580
3581impl<'a> NavigationScope<'a> {
3582    /// What the destinations become in a compact window.
3583    ///
3584    /// Without it the design system answers, which is a bottom bar on most of them. An
3585    /// application whose own reference draws a compact window differently says so here:
3586    /// `Sidebar` puts the sidebar away behind a toggle on every design system, and `None`
3587    /// leaves the destinations off a compact window so the screen can reach them its own
3588    /// way. Medium and Expanded windows keep the design system's rail and drawer whatever
3589    /// this says, and the screen still never asks how wide the window is.
3590    pub fn compact(mut self, compact: CompactNavigation) -> Self {
3591        self.compact = compact;
3592        self
3593    }
3594
3595    /// What sits above the destinations in a strip.
3596    pub fn head(mut self, head: impl FnOnce() + 'a) -> Self {
3597        self.head = Some(std::boxed::Box::new(head));
3598        self
3599    }
3600
3601    /// What sits below them.
3602    pub fn foot(mut self, foot: impl FnOnce() + 'a) -> Self {
3603        self.foot = Some(std::boxed::Box::new(foot));
3604        self
3605    }
3606
3607    fn compose(&mut self, content: impl FnOnce()) {
3608        let modifier = std::mem::take(&mut self.modifier);
3609        let selected_index = self.selected_index;
3610        let compact = self.compact;
3611        let (head, foot) = (self.head.take(), self.foot.take());
3612        let motion = self.on_motion_finished.take();
3613        emit(
3614            widget_key("compose_rust::ui::Navigation"),
3615            WidgetKind::Navigation,
3616            |attrs| {
3617                push_modifiers(&modifier, Mods::Standard, attrs);
3618                attrs.push(("selected_index", OwnedAttr::Int(selected_index as i64)));
3619                // No choice is the default, and the default is not sent: a navigation that
3620                // says nothing travels exactly as it did before there was a choice.
3621                if compact != CompactNavigation::Default {
3622                    attrs.push((
3623                        "compact_navigation",
3624                        OwnedAttr::Int(i64::from(u16::from(compact))),
3625                    ));
3626                }
3627            },
3628            with_motion(Vec::new(), motion),
3629            || {
3630                if let Some(head) = head {
3631                    slot(
3632                        SlotRole::TopBar,
3633                        widget_key("compose_rust::ui::Navigation::head"),
3634                        head,
3635                    );
3636                }
3637                if let Some(foot) = foot {
3638                    slot(
3639                        SlotRole::BottomBar,
3640                        widget_key("compose_rust::ui::Navigation::foot"),
3641                        foot,
3642                    );
3643                }
3644                let _destinations = crate::runtime::group_guard(widget_key(
3645                    "compose_rust::ui::Navigation::content",
3646                ));
3647                content();
3648            },
3649        );
3650    }
3651}
3652
3653container!(NavigationScope<'a>);
3654motion_handler!(NavigationScope<'a>);
3655
3656/// A `NavigationItem` and its builder.
3657pub struct NavigationItemScope {
3658    modifier: Modifier,
3659    text: String,
3660    icon: Option<IconRole>,
3661    color: Option<Paint>,
3662    enabled: bool,
3663    section: Option<String>,
3664    on_click: Option<Box<dyn FnMut()>>,
3665    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3666    done: bool,
3667}
3668
3669/// One destination inside a `Navigation`. Compose's `NavigationSuiteItem`.
3670pub fn NavigationItem(text: impl Into<String>) -> NavigationItemScope {
3671    NavigationItemScope {
3672        modifier: Modifier::new(),
3673        text: text.into(),
3674        icon: None,
3675        color: None,
3676        enabled: true,
3677        section: None,
3678        on_click: None,
3679        on_motion_finished: None,
3680        done: false,
3681    }
3682}
3683
3684impl NavigationItemScope {
3685    pub fn icon(mut self, icon: IconRole) -> Self {
3686        self.icon = Some(icon);
3687        self
3688    }
3689
3690    pub fn color(mut self, paint: Paint) -> Self {
3691        self.color = Some(paint);
3692        self
3693    }
3694
3695    pub fn enabled(mut self, enabled: bool) -> Self {
3696        self.enabled = enabled;
3697        self
3698    }
3699
3700    /// The named group of the strip this destination belongs to.
3701    pub fn section(mut self, section: impl Into<String>) -> Self {
3702        self.section = Some(section.into());
3703        self
3704    }
3705
3706    pub fn on_click(mut self, handler: impl FnMut() + 'static) -> Self {
3707        self.on_click = Some(std::boxed::Box::new(handler));
3708        self
3709    }
3710
3711    fn compose(&mut self, content: impl FnOnce()) {
3712        let modifier = std::mem::take(&mut self.modifier);
3713        let text = std::mem::take(&mut self.text);
3714        let section = self.section.take();
3715        let (icon, color, enabled) = (self.icon, self.color, self.enabled);
3716        let motion = self.on_motion_finished.take();
3717        emit(
3718            widget_key("compose_rust::ui::NavigationItem"),
3719            WidgetKind::NavigationItem,
3720            |attrs| {
3721                push_modifiers(&modifier, Mods::Standard, attrs);
3722                attrs.push(("text", OwnedAttr::Text(text)));
3723                attrs.push(("icon", super::role(icon)));
3724                attrs.push(("color", super::paint(color)));
3725                attrs.push(("enabled", OwnedAttr::Bool(enabled)));
3726                attrs.push(("section", optional_text(section)));
3727            },
3728            with_motion(vec![("onclick", unit(self.on_click.take()))], motion),
3729            content,
3730        );
3731    }
3732}
3733
3734composed_on_drop!(NavigationItemScope);
3735motion_handler!(NavigationItemScope);
3736
3737// ----- small things ---------------------------------------------------------------------
3738
3739/// A `FileDropTarget` and its builder.
3740pub struct FileDropTargetScope {
3741    modifier: Modifier,
3742    alignment: Option<Alignment>,
3743    on_files_entered: Option<Box<dyn FnMut()>>,
3744    on_files_dropped: Option<Box<dyn FnMut(FileDrop)>>,
3745    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3746    done: bool,
3747}
3748
3749/// A place files may be dropped. Desktop only in effect.
3750pub fn FileDropTarget() -> FileDropTargetScope {
3751    FileDropTargetScope {
3752        modifier: Modifier::new(),
3753        alignment: None,
3754        on_files_entered: None,
3755        on_files_dropped: None,
3756        on_motion_finished: None,
3757        done: false,
3758    }
3759}
3760
3761impl FileDropTargetScope {
3762    pub fn alignment(mut self, alignment: Alignment) -> Self {
3763        self.alignment = Some(alignment);
3764        self
3765    }
3766
3767    pub fn on_files_entered(mut self, handler: impl FnMut() + 'static) -> Self {
3768        self.on_files_entered = Some(std::boxed::Box::new(handler));
3769        self
3770    }
3771
3772    pub fn on_files_dropped(mut self, handler: impl FnMut(FileDrop) + 'static) -> Self {
3773        self.on_files_dropped = Some(std::boxed::Box::new(handler));
3774        self
3775    }
3776
3777    fn compose(&mut self, content: impl FnOnce()) {
3778        let modifier = std::mem::take(&mut self.modifier);
3779        let alignment = self.alignment;
3780        let dropped: EventCallback = match self.on_files_dropped.take() {
3781            Some(handler) => EventCallback::Files(Rc::new(RefCell::new(handler))),
3782            None => EventCallback::Files(Rc::new(RefCell::new(|_: FileDrop| {}))),
3783        };
3784        let motion = self.on_motion_finished.take();
3785        emit(
3786            widget_key("compose_rust::ui::FileDropTarget"),
3787            WidgetKind::FileDropTarget,
3788            |attrs| {
3789                push_modifiers(&modifier, Mods::Standard, attrs);
3790                attrs.push(("alignment", super::role(alignment)));
3791            },
3792            with_motion(
3793                vec![
3794                    ("onfilesentered", unit(self.on_files_entered.take())),
3795                    ("onfilesdropped", dropped),
3796                ],
3797                motion,
3798            ),
3799            content,
3800        );
3801    }
3802}
3803
3804container!(FileDropTargetScope);
3805motion_handler!(FileDropTargetScope);
3806
3807/// A `Chip` and its builder.
3808pub struct ChipScope {
3809    modifier: Modifier,
3810    text: String,
3811    icon: Option<IconRole>,
3812    selected: bool,
3813    enabled: bool,
3814    max_lines: Option<u32>,
3815    overflow: Option<TextOverflow>,
3816    on_click: Option<Box<dyn FnMut()>>,
3817    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3818    done: bool,
3819}
3820
3821/// A small token that is chosen or filters. Compose's `FilterChip`.
3822pub fn Chip(text: impl Into<String>) -> ChipScope {
3823    ChipScope {
3824        modifier: Modifier::new(),
3825        text: text.into(),
3826        icon: None,
3827        selected: false,
3828        enabled: true,
3829        max_lines: None,
3830        overflow: None,
3831        on_click: None,
3832        on_motion_finished: None,
3833        done: false,
3834    }
3835}
3836
3837impl ChipScope {
3838    pub fn icon(mut self, icon: IconRole) -> Self {
3839        self.icon = Some(icon);
3840        self
3841    }
3842
3843    pub fn selected(mut self, selected: bool) -> Self {
3844        self.selected = selected;
3845        self
3846    }
3847
3848    pub fn enabled(mut self, enabled: bool) -> Self {
3849        self.enabled = enabled;
3850        self
3851    }
3852
3853    /// How many lines the label may take. A label is one line unless this says more, so a
3854    /// chip label is one line unless this says more.
3855    pub fn max_lines(mut self, lines: u32) -> Self {
3856        self.max_lines = Some(lines);
3857        self
3858    }
3859
3860    /// What happens to a label longer than its lines.
3861    pub fn overflow(mut self, overflow: TextOverflow) -> Self {
3862        self.overflow = Some(overflow);
3863        self
3864    }
3865
3866    pub fn on_click(mut self, handler: impl FnMut() + 'static) -> Self {
3867        self.on_click = Some(std::boxed::Box::new(handler));
3868        self
3869    }
3870
3871    fn compose(&mut self, content: impl FnOnce()) {
3872        let modifier = std::mem::take(&mut self.modifier);
3873        let text = std::mem::take(&mut self.text);
3874        let (max_lines, overflow) = (self.max_lines, self.overflow);
3875        let (icon, selected, enabled) = (self.icon, self.selected, self.enabled);
3876        let motion = self.on_motion_finished.take();
3877        emit(
3878            widget_key("compose_rust::ui::Chip"),
3879            WidgetKind::Chip,
3880            |attrs| {
3881                push_modifiers(&modifier, Mods::Chip, attrs);
3882                attrs.push(("text", OwnedAttr::Text(text)));
3883                attrs.push(("icon", super::role(icon)));
3884                attrs.push(("checked", OwnedAttr::Bool(selected)));
3885                attrs.push(("enabled", OwnedAttr::Bool(enabled)));
3886                lines_and_overflow(max_lines, overflow, attrs);
3887            },
3888            with_motion(vec![("onclick", unit(self.on_click.take()))], motion),
3889            content,
3890        );
3891    }
3892}
3893
3894composed_on_drop!(ChipScope);
3895motion_handler!(ChipScope);
3896
3897/// A `FloatingAction` and its builder.
3898pub struct FloatingActionScope {
3899    modifier: Modifier,
3900    text: String,
3901    icon: Option<IconRole>,
3902    on_click: Option<Box<dyn FnMut()>>,
3903    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3904    done: bool,
3905}
3906
3907/// The one action a screen is about. Compose's `ExtendedFloatingActionButton`; where it
3908/// goes is the design system's answer.
3909pub fn FloatingAction(text: impl Into<String>) -> FloatingActionScope {
3910    FloatingActionScope {
3911        modifier: Modifier::new(),
3912        text: text.into(),
3913        icon: None,
3914        on_click: None,
3915        on_motion_finished: None,
3916        done: false,
3917    }
3918}
3919
3920impl FloatingActionScope {
3921    pub fn icon(mut self, icon: IconRole) -> Self {
3922        self.icon = Some(icon);
3923        self
3924    }
3925
3926    pub fn on_click(mut self, handler: impl FnMut() + 'static) -> Self {
3927        self.on_click = Some(std::boxed::Box::new(handler));
3928        self
3929    }
3930
3931    fn compose(&mut self, content: impl FnOnce()) {
3932        let modifier = std::mem::take(&mut self.modifier);
3933        let text = std::mem::take(&mut self.text);
3934        let icon = self.icon;
3935        let motion = self.on_motion_finished.take();
3936        emit(
3937            widget_key("compose_rust::ui::FloatingAction"),
3938            WidgetKind::FloatingAction,
3939            |attrs| {
3940                push_modifiers(&modifier, Mods::None, attrs);
3941                attrs.push(("text", OwnedAttr::Text(text)));
3942                attrs.push(("icon", super::role(icon)));
3943            },
3944            with_motion(vec![("onclick", unit(self.on_click.take()))], motion),
3945            content,
3946        );
3947    }
3948}
3949
3950composed_on_drop!(FloatingActionScope);
3951motion_handler!(FloatingActionScope);
3952
3953/// A `Badge` and its builder.
3954pub struct BadgeScope {
3955    modifier: Modifier,
3956    value: Option<u32>,
3957    text: Option<String>,
3958    color: Option<ColorRole>,
3959    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
3960    done: bool,
3961}
3962
3963/// A count, a word or a dot, on its child or on its own. Compose's `BadgedBox` and `Badge`.
3964pub fn Badge() -> BadgeScope {
3965    BadgeScope {
3966        modifier: Modifier::new(),
3967        value: None,
3968        text: None,
3969        color: None,
3970        on_motion_finished: None,
3971        done: false,
3972    }
3973}
3974
3975impl BadgeScope {
3976    /// How many.
3977    pub fn value(mut self, value: u32) -> Self {
3978        self.value = Some(value);
3979        self
3980    }
3981
3982    /// One short word, shown where a count would be.
3983    pub fn text(mut self, text: impl Into<String>) -> Self {
3984        self.text = Some(text.into());
3985        self
3986    }
3987
3988    /// The role the mark is filled with; the error role where it is not given.
3989    pub fn color(mut self, role: ColorRole) -> Self {
3990        self.color = Some(role);
3991        self
3992    }
3993
3994    fn compose(&mut self, content: impl FnOnce()) {
3995        let modifier = std::mem::take(&mut self.modifier);
3996        let text = self.text.take();
3997        let (value, color) = (self.value, self.color);
3998        let motion = self.on_motion_finished.take();
3999        emit(
4000            widget_key("compose_rust::ui::Badge"),
4001            WidgetKind::Badge,
4002            |attrs| {
4003                push_modifiers(&modifier, Mods::Standard, attrs);
4004                attrs.push((
4005                    "count",
4006                    value.map_or(OwnedAttr::None, |value| OwnedAttr::Int(i64::from(value))),
4007                ));
4008                attrs.push(("text", optional_text(text)));
4009                attrs.push(("color", super::paint(color.map(Paint::Role))));
4010            },
4011            with_motion(Vec::new(), motion),
4012            content,
4013        );
4014    }
4015}
4016
4017container!(BadgeScope);
4018motion_handler!(BadgeScope);
4019
4020/// A `SplitPane` and its builder.
4021pub struct SplitPaneScope {
4022    modifier: Modifier,
4023    value: Option<f32>,
4024    min: Option<f32>,
4025    max: Option<f32>,
4026    collapsible: bool,
4027    collapse_below: Option<f32>,
4028    selected_index: usize,
4029    label: Option<String>,
4030    on_change: Option<Box<dyn FnMut(f32)>>,
4031    on_dismiss: Option<Box<dyn FnMut()>>,
4032    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
4033    done: bool,
4034}
4035
4036/// A side pane and a body with a divider the user drags. Exactly two children, side pane
4037/// first. The drag is reported once, when it ends.
4038pub fn SplitPane() -> SplitPaneScope {
4039    SplitPaneScope {
4040        modifier: Modifier::new(),
4041        value: None,
4042        min: None,
4043        max: None,
4044        collapsible: false,
4045        collapse_below: None,
4046        selected_index: 0,
4047        label: None,
4048        on_change: None,
4049        on_dismiss: None,
4050        on_motion_finished: None,
4051        done: false,
4052    }
4053}
4054
4055impl SplitPaneScope {
4056    /// The side pane's width in dp, or 0 to open it folded.
4057    pub fn value(mut self, dp: f32) -> Self {
4058        self.value = Some(dp);
4059        self
4060    }
4061
4062    pub fn min(mut self, dp: f32) -> Self {
4063        self.min = Some(dp);
4064        self
4065    }
4066
4067    pub fn max(mut self, dp: f32) -> Self {
4068        self.max = Some(dp);
4069        self
4070    }
4071
4072    pub fn collapsible(mut self, collapsible: bool) -> Self {
4073        self.collapsible = collapsible;
4074        self
4075    }
4076
4077    /// The split pane's own width in dp below which it shows one pane at a time, the one
4078    /// `selected_index` names. At or above it the panes are never stacked, and the design
4079    /// system still decides between two columns and a side pane laid over the body.
4080    ///
4081    /// Without it the line is the size class's: stacked below 600 dp. 0 is the same as not
4082    /// calling this. The width is measured on the Renderer, so crossing the line sends the
4083    /// Host nothing. A negative or non-finite width is reported as a protocol error and
4084    /// the split pane is drawn as if it had none.
4085    pub fn collapse_below(mut self, dp: f32) -> Self {
4086        self.collapse_below = Some(dp);
4087        self
4088    }
4089
4090    /// Which pane shows when only one fits: 0 the side pane, 1 the body.
4091    pub fn selected_index(mut self, index: usize) -> Self {
4092        self.selected_index = index;
4093        self
4094    }
4095
4096    /// What a screen reader calls the divider.
4097    pub fn label(mut self, label: impl Into<String>) -> Self {
4098        self.label = Some(label.into());
4099        self
4100    }
4101
4102    pub fn on_change(mut self, handler: impl FnMut(f32) + 'static) -> Self {
4103        self.on_change = Some(std::boxed::Box::new(handler));
4104        self
4105    }
4106
4107    pub fn on_dismiss(mut self, handler: impl FnMut() + 'static) -> Self {
4108        self.on_dismiss = Some(std::boxed::Box::new(handler));
4109        self
4110    }
4111
4112    fn compose(&mut self, content: impl FnOnce()) {
4113        let modifier = std::mem::take(&mut self.modifier);
4114        let label = self.label.take();
4115        let (value, min, max, collapsible, collapse_below, selected_index) = (
4116            self.value,
4117            self.min,
4118            self.max,
4119            self.collapsible,
4120            self.collapse_below,
4121            self.selected_index,
4122        );
4123        let change = match self.on_change.take() {
4124            Some(mut handler) => EventCallback::Value(Rc::new(RefCell::new(move |value: f64| {
4125                handler(value as f32)
4126            }))),
4127            None => value_handler(None),
4128        };
4129        let as_float = |value: Option<f32>| {
4130            value.map_or(OwnedAttr::None, |value| OwnedAttr::Float(f64::from(value)))
4131        };
4132        let motion = self.on_motion_finished.take();
4133        emit(
4134            widget_key("compose_rust::ui::SplitPane"),
4135            WidgetKind::SplitPane,
4136            |attrs| {
4137                push_modifiers(&modifier, Mods::Standard, attrs);
4138                attrs.push(("value", as_float(value)));
4139                attrs.push(("min", as_float(min)));
4140                attrs.push(("max", as_float(max)));
4141                attrs.push(("collapsible", OwnedAttr::Bool(collapsible)));
4142                attrs.push(("collapse_below", as_float(collapse_below)));
4143                attrs.push(("selected_index", OwnedAttr::Int(selected_index as i64)));
4144                attrs.push(("text", optional_text(label)));
4145            },
4146            with_motion(
4147                vec![
4148                    ("onchange", change),
4149                    ("ondismiss", unit(self.on_dismiss.take())),
4150                ],
4151                motion,
4152            ),
4153            content,
4154        );
4155    }
4156}
4157
4158container!(SplitPaneScope);
4159motion_handler!(SplitPaneScope);
4160
4161/// The worked extension widget: Material 3's determinate linear progress indicator.
4162pub struct LinearProgressIndicatorScope {
4163    modifier: Modifier,
4164    progress: f32,
4165    on_motion_finished: Option<Box<dyn FnMut(MotionFinished)>>,
4166    done: bool,
4167}
4168
4169/// The extension widget the schema carries as its example.
4170pub fn LinearProgressIndicator(progress: f32) -> LinearProgressIndicatorScope {
4171    LinearProgressIndicatorScope {
4172        modifier: Modifier::new(),
4173        progress,
4174        on_motion_finished: None,
4175        done: false,
4176    }
4177}
4178
4179impl LinearProgressIndicatorScope {
4180    fn compose(&mut self, content: impl FnOnce()) {
4181        let modifier = std::mem::take(&mut self.modifier);
4182        let progress = self.progress;
4183        let motion = self.on_motion_finished.take();
4184        emit(
4185            widget_key("compose_rust::ui::LinearProgressIndicator"),
4186            WidgetKind::LinearProgressIndicator,
4187            |attrs| {
4188                push_modifiers(&modifier, Mods::None, attrs);
4189                attrs.push(("progress", OwnedAttr::Float(f64::from(progress))));
4190            },
4191            with_motion(Vec::new(), motion),
4192            content,
4193        );
4194    }
4195}
4196
4197composed_on_drop!(LinearProgressIndicatorScope);
4198motion_handler!(LinearProgressIndicatorScope);
4199
4200// ----- windows --------------------------------------------------------------------
4201
4202/// A `Window` and its builder.
4203pub struct WindowScope {
4204    on_close_request: Option<Box<dyn FnMut()>>,
4205    title: Option<String>,
4206    size: Option<(f32, f32)>,
4207    min_size: Option<(f32, f32)>,
4208    resizable: Option<bool>,
4209    report_size: Option<bool>,
4210    chrome: Option<crate::schema::Chrome>,
4211    title_bar: Option<crate::schema::TitleBar>,
4212    icon: Option<u32>,
4213    position: Option<(f32, f32)>,
4214    restore_key: Option<String>,
4215    zoom_level: Option<i8>,
4216    drag_from_pointer: Option<crate::windows::DragFromPointer>,
4217    theme: Option<crate::schema::Theme>,
4218    on_focus_changed: Option<Box<dyn FnMut(bool)>>,
4219    on_moved: Option<Box<dyn FnMut(crate::windows::WindowFrame)>>,
4220    on_drag: Option<Box<dyn FnMut(crate::windows::WindowDragEvent)>>,
4221    on_unavailable: Option<Box<dyn FnMut()>>,
4222    on_closed: Option<Box<dyn FnMut()>>,
4223    done: bool,
4224}
4225
4226/// A platform window, a child of the root, whose children are the window's content. Compose
4227/// Desktop's `Window`. The application has to be launched with
4228/// [`LaunchBuilder::windows`](crate::LaunchBuilder::windows).
4229///
4230/// `on_close_request` is called when the user asks to close the window. It does not close
4231/// it: the window closes when the application stops composing this `Window`, which is
4232/// where a dialog that asks about unsaved work goes.
4233///
4234/// ```ignore
4235/// Window(move || open.set(false)).title("Notes").size(900.0, 600.0).content(|| {
4236///     Text("Hello");
4237/// });
4238/// ```
4239pub fn Window(on_close_request: impl FnMut() + 'static) -> WindowScope {
4240    WindowScope {
4241        on_close_request: Some(std::boxed::Box::new(on_close_request)),
4242        title: None,
4243        size: None,
4244        min_size: None,
4245        resizable: None,
4246        report_size: None,
4247        chrome: None,
4248        title_bar: None,
4249        icon: None,
4250        position: None,
4251        restore_key: None,
4252        zoom_level: None,
4253        drag_from_pointer: None,
4254        theme: None,
4255        on_focus_changed: None,
4256        on_moved: None,
4257        on_drag: None,
4258        on_unavailable: None,
4259        on_closed: None,
4260        done: false,
4261    }
4262}
4263
4264impl Drop for WindowScope {
4265    fn drop(&mut self) {
4266        // A panic is already unwinding the composition, and composing on the way out would
4267        // only risk a second one.
4268        if !self.done && !std::thread::panicking() {
4269            self.done = true;
4270            self.compose(|| {});
4271        }
4272    }
4273}
4274
4275/// A window handler as the callback the runtime delivers events to.
4276fn window_callback(handler: impl FnMut(crate::windows::WindowEvent) + 'static) -> EventCallback {
4277    EventCallback::Window(Rc::new(RefCell::new(handler)))
4278}
4279
4280impl WindowScope {
4281    /// What the window calls itself.
4282    pub fn title(mut self, title: impl Into<String>) -> Self {
4283        self.title = Some(title.into());
4284        self
4285    }
4286
4287    /// The size the window opens at, in dp. A later change resizes it.
4288    pub fn size(mut self, width: f32, height: f32) -> Self {
4289        self.size = Some((width, height));
4290        self
4291    }
4292
4293    /// The smallest size the user can make it, in dp.
4294    pub fn min_size(mut self, width: f32, height: f32) -> Self {
4295        self.min_size = Some((width, height));
4296        self
4297    }
4298
4299    pub fn resizable(mut self, resizable: bool) -> Self {
4300        self.resizable = Some(resizable);
4301        self
4302    }
4303
4304    /// Asks to be told every time the window's width or height, rounded to whole dp,
4305    /// changes. Without it the size is reported only when its class or the safe area
4306    /// changes. Turn it on only for a window that lays out by its exact size: each
4307    /// whole-dp change while the user drags an edge costs one call into the Host.
4308    pub fn report_size(mut self, report: bool) -> Self {
4309        self.report_size = Some(report);
4310        self
4311    }
4312
4313    /// Who draws the caption.
4314    pub fn chrome(mut self, chrome: crate::schema::Chrome) -> Self {
4315        self.chrome = Some(chrome);
4316        self
4317    }
4318
4319    /// Which of the two title bars the window has.
4320    pub fn title_bar(mut self, title_bar: crate::schema::TitleBar) -> Self {
4321        self.title_bar = Some(title_bar);
4322        self
4323    }
4324
4325    /// The window's icon, as the id of a registered asset. Without one it wears the
4326    /// application's.
4327    pub fn icon(mut self, asset_id: u32) -> Self {
4328        self.icon = Some(asset_id);
4329        self
4330    }
4331
4332    /// Where the window sits, in screen dp from the top left of the main screen. Changing
4333    /// it moves the window; the position the user chose is not given back. Without it the
4334    /// platform places the window.
4335    pub fn position(mut self, x: f32, y: f32) -> Self {
4336        self.position = Some((x, y));
4337        self
4338    }
4339
4340    /// The application's stable name for the window, which matches a window the system
4341    /// brings back to the node that describes it.
4342    pub fn restore_key(mut self, key: impl Into<String>) -> Self {
4343        self.restore_key = Some(key.into());
4344        self
4345    }
4346
4347    /// The window's own application zoom level, kept inside its range.
4348    pub fn zoom_level(mut self, level: i8) -> Self {
4349        self.zoom_level = Some(crate::zoom::clamp_level(level));
4350        self
4351    }
4352
4353    /// Opens the window under a pointer that is held down and follows it until it is let
4354    /// go. Read when the window opens and not again.
4355    pub fn drag_from_pointer(mut self, drag: crate::windows::DragFromPointer) -> Self {
4356        self.drag_from_pointer = Some(drag);
4357        self
4358    }
4359
4360    /// A theme for this window over the application's.
4361    pub fn theme(mut self, theme: crate::schema::Theme) -> Self {
4362        self.theme = Some(theme);
4363        self
4364    }
4365
4366    /// The window became the key window or stopped being it.
4367    pub fn on_focus_changed(mut self, handler: impl FnMut(bool) + 'static) -> Self {
4368        self.on_focus_changed = Some(std::boxed::Box::new(handler));
4369        self
4370    }
4371
4372    /// The window's outer frame moved or changed size.
4373    pub fn on_moved(mut self, handler: impl FnMut(crate::windows::WindowFrame) + 'static) -> Self {
4374        self.on_moved = Some(std::boxed::Box::new(handler));
4375        self
4376    }
4377
4378    /// The window is being dragged out of a tab, and how that ended.
4379    pub fn on_drag(
4380        mut self,
4381        handler: impl FnMut(crate::windows::WindowDragEvent) + 'static,
4382    ) -> Self {
4383        self.on_drag = Some(std::boxed::Box::new(handler));
4384        self
4385    }
4386
4387    /// The platform could not open this window. Tell the user, or put the tab back.
4388    pub fn on_unavailable(mut self, handler: impl FnMut() + 'static) -> Self {
4389        self.on_unavailable = Some(std::boxed::Box::new(handler));
4390        self
4391    }
4392
4393    /// The system closed the window without asking. Stop composing it.
4394    pub fn on_closed(mut self, handler: impl FnMut() + 'static) -> Self {
4395        self.on_closed = Some(std::boxed::Box::new(handler));
4396        self
4397    }
4398
4399    /// Composes this window with `content` as its children.
4400    pub fn content(mut self, content: impl FnOnce()) {
4401        self.done = true;
4402        self.compose(content);
4403    }
4404
4405    fn compose(&mut self, content: impl FnOnce()) {
4406        use crate::windows::WindowEvent;
4407        let pair = |value: (f32, f32)| {
4408            let mut bytes = Vec::with_capacity(8);
4409            bytes.extend_from_slice(&value.0.to_bits().to_le_bytes());
4410            bytes.extend_from_slice(&value.1.to_bits().to_le_bytes());
4411            OwnedAttr::Bytes(bytes)
4412        };
4413        // Only what was said is written. A property left out is not a property sent as
4414        // nothing, and one that was said before and is not now is taken away.
4415        let mut properties: Attrs = Vec::new();
4416        if let Some(title) = self.title.take() {
4417            properties.push(("window_title", OwnedAttr::Text(title)));
4418        }
4419        if let Some(size) = self.size {
4420            properties.push(("window_size", pair(size)));
4421        }
4422        if let Some(size) = self.min_size {
4423            properties.push(("window_min_size", pair(size)));
4424        }
4425        if let Some(resizable) = self.resizable {
4426            properties.push(("window_resizable", OwnedAttr::Bool(resizable)));
4427        }
4428        if let Some(report) = self.report_size {
4429            properties.push(("report_size", OwnedAttr::Bool(report)));
4430        }
4431        if let Some(chrome) = self.chrome {
4432            properties.push(("window_chrome", OwnedAttr::Int(i64::from(chrome as u16))));
4433        }
4434        if let Some(title_bar) = self.title_bar {
4435            properties.push((
4436                "window_title_bar",
4437                OwnedAttr::Int(i64::from(title_bar as u16)),
4438            ));
4439        }
4440        if let Some(icon) = self.icon {
4441            properties.push(("window_icon", OwnedAttr::Int(i64::from(icon))));
4442        }
4443        if let Some(position) = self.position {
4444            properties.push(("window_position", pair(position)));
4445        }
4446        if let Some(key) = self.restore_key.take() {
4447            properties.push(("window_restore_key", OwnedAttr::Text(key)));
4448        }
4449        if let Some(level) = self.zoom_level {
4450            properties.push(("window_zoom_level", OwnedAttr::Int(i64::from(level))));
4451        }
4452        if let Some(drag) = self.drag_from_pointer {
4453            properties.push(("drag_from_pointer", OwnedAttr::Bytes(drag.to_bytes())));
4454        }
4455
4456        let mut listeners: Vec<(&'static str, EventCallback)> = Vec::new();
4457        let mut close = self.on_close_request.take();
4458        listeners.push((
4459            "onwindowclose",
4460            window_callback(move |event| {
4461                if let (WindowEvent::CloseRequested, Some(handler)) = (event, close.as_mut()) {
4462                    handler();
4463                }
4464            }),
4465        ));
4466        if let Some(mut handler) = self.on_focus_changed.take() {
4467            listeners.push((
4468                "onwindowfocus",
4469                window_callback(move |event| {
4470                    if let WindowEvent::FocusChanged { focused } = event {
4471                        handler(focused);
4472                    }
4473                }),
4474            ));
4475        }
4476        if let Some(mut handler) = self.on_moved.take() {
4477            listeners.push((
4478                "onwindowmoved",
4479                window_callback(move |event| {
4480                    if let WindowEvent::Moved {
4481                        x,
4482                        y,
4483                        width,
4484                        height,
4485                    } = event
4486                    {
4487                        handler(crate::windows::WindowFrame {
4488                            x,
4489                            y,
4490                            width,
4491                            height,
4492                        });
4493                    }
4494                }),
4495            ));
4496        }
4497        if let Some(mut handler) = self.on_drag.take() {
4498            listeners.push((
4499                "onwindowdrag",
4500                window_callback(move |event| {
4501                    if let WindowEvent::Drag {
4502                        phase,
4503                        screen_x,
4504                        screen_y,
4505                        over_window,
4506                    } = event
4507                    {
4508                        handler(crate::windows::WindowDragEvent {
4509                            phase,
4510                            screen_x,
4511                            screen_y,
4512                            over_window,
4513                        });
4514                    }
4515                }),
4516            ));
4517        }
4518        if let Some(mut handler) = self.on_unavailable.take() {
4519            listeners.push((
4520                "onwindowunavailable",
4521                window_callback(move |event| {
4522                    if event == WindowEvent::Unavailable {
4523                        handler();
4524                    }
4525                }),
4526            ));
4527        }
4528        if let Some(mut handler) = self.on_closed.take() {
4529            listeners.push((
4530                "onwindowclosed",
4531                window_callback(move |event| {
4532                    if event == WindowEvent::Closed {
4533                        handler();
4534                    }
4535                }),
4536            ));
4537        }
4538
4539        let theme = self.theme.take();
4540        emit(
4541            widget_key("compose_rust::ui::Window"),
4542            WidgetKind::Window,
4543            |attrs| attrs.append(&mut properties),
4544            listeners,
4545            move || {
4546                // The group has its node by now, so the window is known.
4547                if let (Some(theme), Some(window)) = (theme, crate::windows::current_window()) {
4548                    window.set_theme(theme);
4549                }
4550                content();
4551            },
4552        );
4553    }
4554}