Skip to main content

day_pieces/
leaves.rs

1// Copyright Β© The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Leaf pieces, the childless primitives: `label`, `link`, `button`, `toggle`, `slider`,
5//! `text_field`, `progress`/`spinner`, `divider`, and `spacer`.
6
7use std::cell::RefCell;
8use std::rc::Rc;
9
10use day_core::*;
11use day_reactive::{bind, bind_seeded};
12use day_spec::props::*;
13use day_spec::{Event, Font, Proposal, Rect, Role, Size, kinds};
14
15use crate::*;
16
17// ---------------------------------------------------------------------------
18// Leaves
19// ---------------------------------------------------------------------------
20
21/// Build a styled paragraph run by run (docs/text-runs.md).
22///
23/// A builder exists because byte ranges are error-prone to write by hand and meaningless to
24/// read: `TextRun { range: 12..19, .. }` says nothing about which word it covers. Appending text
25/// and its style together keeps the two from drifting apart.
26///
27/// ```ignore
28/// label("").runs_from(
29///     TextBuilder::new()
30///         .text("Saved to ")
31///         .code("~/Documents")
32///         .text(" just now β€” ")
33///         .strong("do not close")
34///         .text(" the window."),
35/// )
36/// ```
37#[derive(Clone, Debug, Default)]
38#[must_use]
39pub struct TextBuilder {
40    text: String,
41    runs: Vec<day_spec::TextRun>,
42    base: Font,
43}
44
45impl TextBuilder {
46    pub fn new() -> Self {
47        Self::default()
48    }
49    /// The style the emphasis variants build on. Set it to the label's font so a bold run
50    /// inside a `Footnote` paragraph stays footnote-sized.
51    pub fn base(mut self, font: Font) -> Self {
52        self.base = font;
53        self
54    }
55    /// Unstyled text: it draws with the label's own font.
56    pub fn text(mut self, s: &str) -> Self {
57        self.text.push_str(s);
58        self
59    }
60    /// A run with a fully specified style.
61    pub fn run(
62        mut self,
63        s: &str,
64        run: impl FnOnce(std::ops::Range<usize>) -> day_spec::TextRun,
65    ) -> Self {
66        let start = self.text.len();
67        self.text.push_str(s);
68        self.runs.push(run(start..self.text.len()));
69        self
70    }
71    /// Bold.
72    pub fn strong(self, s: &str) -> Self {
73        let base = self.base;
74        self.run(s, move |range| {
75            day_spec::TextRun::font(
76                range,
77                day_spec::FontSpec {
78                    style: base,
79                    weight: Some(day_spec::FontWeight::Bold),
80                    ..Default::default()
81                },
82            )
83        })
84    }
85    /// Italic.
86    pub fn emphasis(self, s: &str) -> Self {
87        let base = self.base;
88        self.run(s, move |range| {
89            day_spec::TextRun::font(
90                range,
91                day_spec::FontSpec {
92                    style: base,
93                    italic: true,
94                    ..Default::default()
95                },
96            )
97        })
98    }
99    /// Inline code: the platform's monospaced face at this style's size.
100    pub fn code(self, s: &str) -> Self {
101        let base = self.base;
102        self.run(s, move |range| {
103            day_spec::TextRun::font(
104                range,
105                day_spec::FontSpec {
106                    style: base,
107                    monospace: true,
108                    ..Default::default()
109                },
110            )
111        })
112    }
113    /// A colored phrase.
114    pub fn colored(self, s: &str, color: day_spec::Color) -> Self {
115        let base = self.base;
116        self.run(s, move |range| day_spec::TextRun {
117            range,
118            font: day_spec::FontSpec::from(base),
119            color: Some(color),
120            ..day_spec::TextRun::default()
121        })
122    }
123    /// Underlined.
124    pub fn underline(self, s: &str) -> Self {
125        let base = self.base;
126        self.run(s, move |range| day_spec::TextRun {
127            range,
128            font: day_spec::FontSpec::from(base),
129            underline: day_spec::Underline::Single,
130            ..day_spec::TextRun::default()
131        })
132    }
133    /// Highlighted: a color painted behind the glyphs, for a search hit or a review mark.
134    ///
135    /// Sets the foreground too, through the same readable-on-a-fill rule `Button::tint` uses: a
136    /// highlight is usually a pale wash, and the label's own text color is chosen for the window's
137    /// background rather than for the swatch now sitting under it. On a dark theme that pairing
138    /// puts light text on pale amber, which is the one combination a highlight must not produce.
139    /// Use [`TextBuilder::run`] where an app wants to state both itself.
140    pub fn highlight(self, s: &str, color: day_spec::Color) -> Self {
141        let base = self.base;
142        self.run(s, move |range| day_spec::TextRun {
143            range,
144            font: day_spec::FontSpec::from(base),
145            background: Some(color),
146            color: Some(day_spec::props::ButtonStyleSpec::on_tint(color)),
147            ..day_spec::TextRun::default()
148        })
149    }
150    /// A relative size: `1.5` is half again the base style's, `0.8` smaller
151    /// ([`FontSpec::scale`](day_spec::FontSpec::scale)). Relative rather than a point size so the
152    /// phrase still tracks the reader's accessibility text-size setting.
153    pub fn sized(self, s: &str, scale: f64) -> Self {
154        let base = self.base;
155        self.run(s, move |range| day_spec::TextRun {
156            range,
157            font: day_spec::FontSpec::from(base).scaled(scale),
158            ..day_spec::TextRun::default()
159        })
160    }
161    /// Struck through.
162    pub fn strikethrough(self, s: &str) -> Self {
163        let base = self.base;
164        self.run(s, move |range| day_spec::TextRun {
165            range,
166            font: day_spec::FontSpec::from(base),
167            strikethrough: true,
168            ..day_spec::TextRun::default()
169        })
170    }
171    /// A link run. A `#route` target navigates in-app, as with [`link`].
172    /// Rendering it is `Cap::TextRuns`; activating it is `Cap::TextLinks`, which
173    /// fewer backends have, so check before relying on the tap (docs/text-runs.md).
174    pub fn link(self, s: &str, target: &str) -> Self {
175        let base = self.base;
176        let target = target.to_string();
177        self.run(s, move |range| day_spec::TextRun {
178            range,
179            font: day_spec::FontSpec::from(base),
180            link: Some(target),
181            ..day_spec::TextRun::default()
182        })
183    }
184    /// The assembled text and its runs.
185    #[must_use]
186    pub fn build(self) -> (String, Vec<day_spec::TextRun>) {
187        (self.text, self.runs)
188    }
189}
190
191#[must_use]
192pub struct Label {
193    // pub(crate): `forms` builds Label literals directly (they were co-located before the split).
194    pub(crate) text: TextSource,
195    pub(crate) font: Font,
196    pub(crate) font_scale: f64,
197    pub(crate) weight: Option<day_spec::FontWeight>,
198    pub(crate) italic: bool,
199    pub(crate) tabular: bool,
200    pub(crate) monospace: bool,
201    pub(crate) wraps: bool,
202    pub(crate) max_lines: u32,
203    pub(crate) color: Option<Reactive<day_spec::Color>>,
204    /// What the text means, for the color the platform gives it (docs/text.md).
205    pub(crate) role: day_spec::props::TextRole,
206    /// Styled spans over `text` (docs/text-runs.md); empty is an ordinary uniform label.
207    pub(crate) runs: Vec<day_spec::TextRun>,
208    /// Parse the text as inline markdown instead of taking it literally (docs/markdown.md).
209    pub(crate) markdown: bool,
210    /// How wrapped lines sit within the label's own width (docs/text.md).
211    pub(crate) align: day_spec::props::TextAlign,
212    /// What a tapped link run does. `None` uses [`open_link`].
213    pub(crate) on_link: Option<LinkHandler>,
214}
215
216/// An app's handler for a tapped link run, shared because `Label` is cloned into its build.
217pub(crate) type LinkHandler = Rc<dyn Fn(&str)>;
218
219pub fn label<M>(text: impl IntoText<M>) -> Label {
220    Label {
221        text: text.into_text(),
222        font: Font::Body,
223        font_scale: 1.0,
224        weight: None,
225        italic: false,
226        tabular: false,
227        monospace: false,
228        wraps: true,
229        max_lines: 0,
230        color: None,
231        role: TextRole::default(),
232        runs: Vec::new(),
233        markdown: false,
234        align: day_spec::props::TextAlign::Leading,
235        on_link: None,
236    }
237}
238
239#[day_macros::builder(LabelBuilder)]
240impl Label {
241    /// Keep plain text on one line. UIKit, Android, GTK, AppKit and DOM truncate with an ellipsis.
242    pub fn single_line(mut self) -> Self {
243        self.wraps = false;
244        self
245    }
246    /// Limit a plain label to this many lines, truncating the last line on Apple and Android
247    /// backends. Zero means unlimited. Rebuild the label to change its line limit.
248    pub fn max_lines(mut self, lines: u32) -> Self {
249        self.max_lines = lines;
250        self
251    }
252    /// The semantic text style (`Font::Title`, `Font::Footnote`, …) or a custom `Font::System(pt)`.
253    /// Backends render it with the platform's native style + accessibility text scaling.
254    pub fn font(mut self, f: Font) -> Self {
255        self.font = f;
256        self
257    }
258    /// Scale the resolved native font, preserving its semantic style and accessibility size.
259    /// Applies to the label's base font; explicit styled runs retain their own descriptors.
260    pub fn font_scale(mut self, scale: f64) -> Self {
261        self.font_scale = if scale.is_finite() && scale > 0.0 {
262            scale
263        } else {
264            1.0
265        };
266        self
267    }
268    /// Override the font weight (e.g. `FontWeight::Semibold`). See also [`Label::bold`].
269    pub fn weight(mut self, w: day_spec::FontWeight) -> Self {
270        self.weight = Some(w);
271        self
272    }
273    /// Shorthand for `.weight(FontWeight::Bold)`.
274    pub fn bold(self) -> Self {
275        self.weight(day_spec::FontWeight::Bold)
276    }
277    /// De-emphasize the text: the platform's secondary label color, whatever that is here
278    /// (`secondaryLabelColor` on Apple, `?android:textColorSecondary`, a dim label on GTK).
279    ///
280    /// Semantic rather than a literal grey, for the reason a literal grey cannot solve: one that
281    /// reads well on white is wrong on black, so an app that hard-codes it gets a label that is
282    /// either washed out or nearly invisible in the other appearance. This is what an empty
283    /// state's "nothing selected", a hint under a field, or a caption should wear.
284    pub fn secondary(mut self) -> Self {
285        self.role = day_spec::props::TextRole::Secondary;
286        self
287    }
288    /// Render the text italic (slanted).
289    pub fn italic(mut self) -> Self {
290        self.italic = true;
291        self
292    }
293    /// Ask for tabular (monospaced) figures, so a changing number stops changing width.
294    ///
295    /// Pair it with [`Decorate::reserving`] for a readout beside a slider: reserving stops the box
296    /// resizing when the digit count changes, tabular stops the digits shifting inside it because
297    /// `1` is narrower than `8`. See [`day_spec::FontSpec::tabular`].
298    pub fn tabular(mut self) -> Self {
299        self.tabular = true;
300        self
301    }
302    /// Ask for the platform's monospaced face at this style's size, which is what inline code
303    /// wants.
304    pub fn monospace(mut self) -> Self {
305        self.monospace = true;
306        self
307    }
308    /// Style spans within this label's text (docs/text-runs.md): one wrapping paragraph with
309    /// emphasis, color, code or a link inside it, rather than several labels in a row.
310    ///
311    /// Ranges are byte offsets into the label's text, ascending and non-overlapping; text not
312    /// covered by a run draws with the label's own font. Invalid runs are REJECTED at build time
313    /// with a warning and the label renders plain, because the alternative is eight different
314    /// wrong renderings (and a panic on the backends that slice `str`).
315    ///
316    /// [`TextBuilder`] is the ergonomic way in; this is the direct one.
317    pub fn runs(mut self, runs: Vec<day_spec::TextRun>) -> Self {
318        self.runs = runs;
319        self
320    }
321    /// Take both the text and its runs from a [`TextBuilder`], replacing whatever text the label
322    /// was built with. This is the intended entry point: the builder guarantees the ranges match
323    /// the string, which is the invariant hand-written runs get wrong.
324    pub fn runs_from(mut self, b: TextBuilder) -> Self {
325        let (text, runs) = b.build();
326        self.text = TextSource::Static(text);
327        self.runs = runs;
328        self
329    }
330    /// Read the label's text as inline Markdown (docs/markdown.md): `**bold**`, `*italic*`,
331    /// `` `code` ``, `~~strike~~` and `[text](url)` become styled runs, and the markers themselves
332    /// are stripped.
333    ///
334    /// The parse happens at run time, on every change, so it works on a translated string chosen
335    /// from the locale bundle, a value off the network, or text a user is typing, none of which a
336    /// compile-time macro can see. The cost is a parse per update of a string that is a label's
337    /// worth of text.
338    ///
339    /// ```ignore
340    /// label(tr("release-note")).markdown()
341    /// label(move || draft.get()).markdown()   // live as the user types
342    /// ```
343    ///
344    /// Unrecognized markup stays literal, so a half-typed `**` reads as two asterisks rather than
345    /// flickering. Block constructs (headings, lists, quotes) are not parsed: they are layout,
346    /// which is `column`/`form`/`list`.
347    /// Center (or trail) this label's lines within its own width, for the short wrapped block
348    /// a welcome screen or an empty state uses. Only observable on a label that wraps, since a
349    /// single line already fills its box.
350    pub fn align(mut self, align: day_spec::props::TextAlign) -> Self {
351        self.align = align;
352        self
353    }
354    pub fn markdown(mut self) -> Self {
355        self.markdown = true;
356        self
357    }
358    /// Handle a tapped link run yourself instead of opening its target.
359    ///
360    /// Without this, a `#route` target navigates in-app and other targets open in the platform's
361    /// default handler, the same as the [`link`] piece. This handler overrides both behaviors;
362    /// call [`open_link`] to delegate targets you do not handle back to the default.
363    ///
364    /// Activation is `Cap::TextLinks`, which is narrower than run rendering: on a backend
365    /// without it the link still draws, and nothing calls this (docs/text-runs.md).
366    pub fn on_link(mut self, f: impl Fn(&str) + 'static) -> Self {
367        self.on_link = Some(Rc::new(f));
368        self
369    }
370    /// The text color: a constant, a `Signal<Color>`, or a `Fn() -> Color`. A reactive
371    /// source recolors the native label when it changes (theme systems ride this).
372    pub fn color<M>(mut self, c: impl IntoReactive<day_spec::Color, M>) -> Self {
373        self.color = Some(c.into_reactive());
374        self
375    }
376    /// Apply a named [`TextPreset`](crate::TextPreset): the font, weight, scale, emphasis and
377    /// color an app defined once (`label(t).preset(&CAPTION)`).
378    pub fn preset(mut self, preset: &crate::TextPreset) -> Self {
379        self.font = preset.font;
380        self.font_scale = preset.font_scale;
381        if preset.weight.is_some() {
382            self.weight = preset.weight;
383        }
384        self.italic |= preset.italic;
385        self.tabular |= preset.tabular;
386        self.monospace |= preset.monospace;
387        if preset.secondary {
388            self.role = day_spec::props::TextRole::Secondary;
389        }
390        if preset.single_line {
391            self.wraps = false;
392        }
393        if let Some(c) = preset.color {
394            self.color = Some(Reactive::Const(c));
395        }
396        self
397    }
398}
399
400impl Piece for Label {
401    fn build(self, cx: &mut BuildCx) -> RNode {
402        // `.markdown()` replaces both the text and the runs: the markers are stripped from what
403        // the label shows, so the two have to be produced together.
404        let (initial, runs) = if self.markdown {
405            crate::markdown::parse(&self.text.initial(), self.font)
406        } else {
407            (self.text.initial(), self.runs.clone())
408        };
409        // Validate once here rather than in eight backends: an overlapping or mid-character
410        // range renders differently wrong on each, and panics on the ones that slice `str`.
411        let runs = match day_spec::runs_are_valid(&initial, &runs) {
412            Ok(()) => runs,
413            Err(why) => {
414                log::warn!("label runs ignored β€” {why}; the text renders unstyled");
415                Vec::new()
416            }
417        };
418        let node = cx.leaf(
419            kinds::LABEL,
420            &LabelProps {
421                align: self.align,
422                text: initial,
423                font: day_spec::FontSpec {
424                    style: self.font,
425                    scale: self.font_scale,
426                    weight: self.weight,
427                    italic: self.italic,
428                    tabular: self.tabular,
429                    monospace: self.monospace,
430                },
431                color: self
432                    .color
433                    .as_ref()
434                    .map(super::canvas::Reactive::get_untracked),
435                role: self.role,
436                wraps: self.wraps,
437                max_lines: self.max_lines,
438                runs,
439            },
440            Flex::default(),
441        );
442        // A label that can carry link runs listens for their activation. Markdown labels qualify
443        // whatever they currently hold, since a later parse may produce a link that this one did
444        // not. Labels without any prospect of a link register nothing.
445        let could_link =
446            self.markdown || self.on_link.is_some() || self.runs.iter().any(|r| r.link.is_some());
447        if could_link {
448            let handler = self.on_link.clone();
449            cx.on(node, move |ev| {
450                if let Event::LinkActivated(url) = ev {
451                    match &handler {
452                        Some(f) => f(url),
453                        None => open_link(url),
454                    }
455                }
456            });
457        }
458        // A reactive markdown label re-parses on every change and patches text and runs together,
459        // since the ranges only mean anything against the string they were parsed from.
460        let font = self.font;
461        let md = self.markdown;
462        self.text.bind_to(
463            node,
464            move |t| {
465                if md {
466                    let (text, runs) = crate::markdown::parse(&t, font);
467                    Box::new(LabelPatch::Runs(text, runs))
468                } else {
469                    Box::new(LabelPatch::Text(t))
470                }
471            },
472            true,
473        );
474        // A reactive color recolors in place; a constant was applied once at realize.
475        if let Some(Reactive::Dyn(f)) = self.color {
476            bind(
477                move || f(),
478                move |c: &day_spec::Color| {
479                    with_tree(|t| t.patch(node, Box::new(LabelPatch::Color(Some(*c))), false));
480                },
481            );
482        }
483        node
484    }
485}
486
487/// The platform "tint" blue (iOS system blue, `#007AFF`) used as the default [`link`] color.
488/// Override per-link with [`Link::color`] to match an app's accent.
489const LINK_BLUE: day_spec::Color = day_spec::Color::rgb(0.0, 0.478, 1.0);
490
491/// Activate a link target, using the same policy as [`link`] and markdown labels.
492///
493/// A leading `#` denotes an in-app route: `#settings` calls [`navigate`](crate::navigate) with
494/// `settings`. Route paths, percent escapes, and query parameters use the navigation system's
495/// existing rules; `#` alone navigates to the empty route (pop to root). An unknown route is
496/// ignored, never handed to an external application. All other targets go to
497/// [`day_core::open_url`] unchanged, including URLs with fragments such as `https://daybrite.dev/#docs`.
498///
499/// Use this from [`Label::on_link`] to keep the default behavior for targets your handler does
500/// not override.
501pub fn open_link(target: &str) {
502    if let Some(route) = target.strip_prefix('#') {
503        let _ = day_core::navigate(route);
504    } else {
505        day_core::open_url(target);
506    }
507}
508
509/// A tappable run of text that navigates to a `#route` or opens a URL in the platform's default
510/// handler: the system browser for `http`/`https`, the mail client for `mailto:`, and so on.
511///
512/// It renders as accent-colored [`label`] text and announces itself as actionable to assistive
513/// technology. The opening itself is delegated to the running backend
514/// ([`Toolkit::open_url`](day_spec::Toolkit::open_url)), so it works the same on
515/// every platform.
516///
517/// ```ignore
518/// link(res::str::project_site(), "https://daybrite.dev")
519/// link(res::str::settings(), "#settings")
520/// link(res::str::email_us(), "mailto:hi@example.com").font(Font::Footnote)
521/// ```
522#[must_use]
523pub struct Link {
524    label: Label,
525    url: String,
526}
527
528/// Build a [`Link`] that activates `url` through [`open_link`] when tapped.
529pub fn link<M>(text: impl IntoText<M>, url: impl Into<String>) -> Link {
530    Link {
531        label: label(text),
532        url: url.into(),
533    }
534}
535
536#[day_macros::builder(LinkBuilder)]
537impl Link {
538    /// The text style (default [`Font::Body`]).
539    pub fn font(mut self, f: Font) -> Self {
540        self.label = self.label.font(f);
541        self
542    }
543    /// Override the link color (default the platform tint blue).
544    pub fn color(mut self, c: day_spec::Color) -> Self {
545        self.label = self.label.color(c);
546        self
547    }
548    /// Render the link text bold.
549    pub fn bold(mut self) -> Self {
550        self.label = self.label.bold();
551        self
552    }
553}
554
555impl Piece for Link {
556    fn build(self, cx: &mut BuildCx) -> RNode {
557        let url = self.url;
558        let mut label = self.label;
559        if day_core::capability(day_spec::Cap::TextLinks) == day_spec::Support::Native {
560            // Use native link runs for theme colors, hover/pressed states, keyboard focus
561            // and accessibility. Keep ranges together with localized/reactive text.
562            let source = label.text.clone();
563            let font = day_spec::FontSpec {
564                style: label.font,
565                scale: label.font_scale,
566                weight: label.weight,
567                italic: label.italic,
568                ..Default::default()
569            };
570            let color = label
571                .color
572                .as_ref()
573                .map(super::canvas::Reactive::get_untracked);
574            let target = url.clone();
575            let runs = move |text: &str| {
576                vec![day_spec::TextRun {
577                    range: 0..text.len(),
578                    font,
579                    color,
580                    link: Some(target.clone()),
581                    ..Default::default()
582                }]
583            };
584            let initial = source.initial();
585            label.runs = runs(&initial);
586            label.text = TextSource::Static(initial);
587            let node = label.build(cx);
588            source.bind_to(
589                node,
590                move |text| {
591                    let spans = runs(&text);
592                    Box::new(LabelPatch::Runs(text, spans))
593                },
594                true,
595            );
596            // Synthetic taps still exercise link policy; native activation is LinkActivated.
597            cx.on(node, move |ev| {
598                if matches!(ev, Event::Tap(_)) {
599                    open_link(&url);
600                }
601            });
602            node
603        } else {
604            if label.color.is_none() {
605                label = label.color(LINK_BLUE);
606            }
607            label
608                .on_tap(move || open_link(&url))
609                .a11y(|b| b.role(Role::Button))
610                .build(cx)
611        }
612    }
613}
614
615#[must_use]
616pub struct Button {
617    title: TextSource,
618    icon: Reactive<Option<day_spec::Icon>>,
619    icon_only: bool,
620    action: Option<Rc<dyn Fn()>>,
621    native_style: day_spec::props::ButtonStyleSpec,
622    /// A reactive tint, kept apart from `native_style` so the color can follow a signal. Set by
623    /// [`Button::tint`]; it wins over `bordered`/`prominent` because it is the more specific ask.
624    tint: Option<Reactive<day_spec::Color>>,
625    enabled: Reactive<bool>,
626    selected: Reactive<bool>,
627}
628
629pub fn button<M>(title: impl IntoText<M>) -> Button {
630    Button {
631        title: title.into_text(),
632        icon: Reactive::Const(None),
633        icon_only: false,
634        action: None,
635        native_style: day_spec::props::ButtonStyleSpec::Automatic,
636        tint: None,
637        enabled: true.into_reactive(),
638        selected: false.into_reactive(),
639    }
640}
641
642#[day_macros::builder(ButtonBuilder)]
643impl Button {
644    /// Show a platform symbol. A signal or closure updates it without replacing the button.
645    pub fn icon<M>(mut self, symbol: impl IntoReactive<day_spec::Symbol, M>) -> Self {
646        let symbol = symbol.into_reactive();
647        self.icon = match symbol {
648            Reactive::Const(s) => Reactive::Const(Some(day_spec::Icon::Symbol(s))),
649            Reactive::Dyn(f) => Reactive::Dyn(Rc::new(move || Some(day_spec::Icon::Symbol(f())))),
650        };
651        self
652    }
653
654    /// Show a bundled image or vector alongside the label.
655    pub fn image(mut self, name: impl Into<day_spec::ImageName>) -> Self {
656        self.icon = Reactive::Const(Some(day_spec::Icon::Image(name.into().as_str().to_owned())));
657        self
658    }
659
660    /// Hide the visible label when an icon is available; retain it for accessibility and help.
661    pub fn icon_only(mut self) -> Self {
662        self.icon_only = true;
663        self
664    }
665
666    /// Handle native button activation by pointer, keyboard, or accessibility action.
667    /// Disabled buttons do not invoke this callback.
668    ///
669    /// Use this instead of [`Decorate::on_tap`]. A tap decorator adds a separate gesture
670    /// recognizer that can delay pressed feedback and bypass native control behavior.
671    /// Day logs a warning when a tap gesture is attached to a native button.
672    pub fn action(mut self, f: impl Fn() + 'static) -> Self {
673        self.action = Some(Rc::new(f));
674        self
675    }
676
677    /// Ask for a visually CONTAINED native button on toolkits whose stock look is borderless
678    /// (iOS's plain system button reads as a link); a no-op where buttons are already bordered.
679    pub fn bordered(mut self) -> Self {
680        self.native_style = day_spec::props::ButtonStyleSpec::Bordered;
681        self
682    }
683
684    /// Whether the button is interactive (default `true`; `false` = disabled/grayed by the native
685    /// control). Reactive, so it can follow app state, e.g. `.enabled(move || !busy.get())` to
686    /// lock a control while a long operation runs.
687    ///
688    /// This drives the platform's own disabled rendering through `ButtonPatch::Enabled`; it is not
689    /// a painted imitation, and a disabled button stops delivering `Event::Pressed` at the source.
690    pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
691        self.enabled = v.into_reactive();
692        self
693    }
694
695    /// The platform's accent-filled / default-action button (iOS bordered-prominent, macOS
696    /// return-key blue, GTK suggested-action, XAML accent style). Use for the one primary
697    /// action of a view.
698    pub fn prominent(mut self) -> Self {
699        self.native_style = day_spec::props::ButtonStyleSpec::Prominent;
700        self
701    }
702
703    /// A filled button in a color of your choosing, still drawn by the native control.
704    ///
705    /// The platform keeps everything that makes a button a button: its pressed and hover
706    /// rendering, its focus ring, its disabled look, its accessibility role, and keyboard
707    /// activation. Only the fill is yours. The label color is chosen for contrast against the
708    /// fill, so a pale tint gets dark text and a saturated one white.
709    ///
710    /// Reactive, so the color can follow app state: `.tint(move || if recording { RUST } else
711    /// { SKY })` recolors in place rather than rebuilding the button.
712    ///
713    /// A backend that cannot recolor its button ignores the tint and draws its ordinary button
714    /// (docs/buttons.md), because a plain button on one platform is a far smaller loss than a
715    /// colored rectangle that is no longer a button.
716    pub fn tint<M>(mut self, color: impl IntoReactive<day_spec::Color, M>) -> Self {
717        self.tint = Some(color.into_reactive());
718        self
719    }
720
721    /// A button no wider than its title: a stepper's "βˆ’" and "+", a chip's "Γ—". Drops the
722    /// minimum width and wide insets of toolkits that have them (Material); a no-op where the
723    /// stock button already hugs its title. A [`plain`](Self::plain) button stays plain: it
724    /// already hugs its title everywhere, and Material's compact button is a filled one.
725    pub fn compact(mut self) -> Self {
726        if self.native_style != day_spec::props::ButtonStyleSpec::Plain {
727            self.native_style = day_spec::props::ButtonStyleSpec::Compact;
728        }
729        self
730    }
731
732    /// Borderless native action button for toolbars and list-row accessories.
733    /// Preserves native interaction, focus, disabled rendering, and accessibility.
734    pub fn plain(mut self) -> Self {
735        self.native_style = day_spec::props::ButtonStyleSpec::Plain;
736        self
737    }
738
739    /// Mark this button as the current choice among its peers: a document tab, one view of a
740    /// switcher. The platform draws its own checked or selected look (an `NSButton`'s on state,
741    /// `UIButton.isSelected`, GTK's `:checked`, a checked `QPushButton`, a checked
742    /// `MaterialButton`, `aria-pressed` on the web) and announces it as selected, while the
743    /// button stays enabled, focusable and activatable, which a disabled stand-in is not.
744    ///
745    /// Reactive, so it follows the selection: `.selected(move || current.get() == key)`. A press
746    /// never toggles the state natively; the app's handler decides, and the next value of the
747    /// closure is what the control shows.
748    pub fn selected<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
749        self.selected = v.into_reactive();
750        self
751    }
752}
753
754impl Piece for Button {
755    fn build(self, cx: &mut BuildCx) -> RNode {
756        let initial = self.title.initial();
757        // A tint is the most specific style ask, so it wins over bordered/prominent.
758        let style = match &self.tint {
759            Some(c) => day_spec::props::ButtonStyleSpec::Tinted(c.get_untracked()),
760            None => self.native_style,
761        };
762        let node = cx.leaf(
763            kinds::BUTTON,
764            &ButtonProps {
765                title: initial.clone(),
766                icon: self.icon.get_untracked(),
767                icon_only: self.icon_only,
768                enabled: self.enabled.get_untracked(),
769                style,
770                selected: self.selected.get_untracked(),
771            },
772            Flex::default(),
773        );
774        // A reactive `selected` patches on change, like `enabled` below.
775        if let selected @ Reactive::Dyn(_) = self.selected {
776            bind(
777                move || selected.get(),
778                move |on: &bool| {
779                    with_tree(|t| t.patch(node, Box::new(ButtonPatch::Selected(*on)), false));
780                },
781            );
782        }
783        // A reactive tint recolors in place; a constant one was applied at realize above.
784        if let Some(c @ Reactive::Dyn(_)) = self.tint.clone() {
785            bind(
786                move || c.get(),
787                move |col: &day_spec::Color| {
788                    with_tree(|t| {
789                        t.patch(
790                            node,
791                            Box::new(ButtonPatch::Style(
792                                day_spec::props::ButtonStyleSpec::Tinted(*col),
793                            )),
794                            false,
795                        );
796                    });
797                },
798            );
799        }
800        // A reactive `enabled` patches on change; a constant is applied once at realize, the same
801        // shape `Toggle` uses.
802        let enabled = self.enabled;
803        let enabled_gate = enabled.clone();
804        if let Reactive::Dyn(_) = &enabled {
805            bind(
806                move || enabled.get(),
807                move |e: &bool| {
808                    with_tree(|t| t.patch(node, Box::new(ButtonPatch::Enabled(*e)), false));
809                },
810            );
811        }
812        if let Some(action) = self.action {
813            // Gate the action on `enabled` as well as telling the native control. A real touch on a
814            // disabled UIButton/MaterialButton never produces `Pressed`, so this is belt-and-braces
815            // for users, but an event delivered by another route (a dayscript `tap`, which
816            // dispatches to the node rather than simulating a touch) would otherwise fire an action
817            // the user cannot reach. `.enabled(false)` should mean "cannot fire", not "looks gray".
818            let gate = enabled_gate;
819            cx.on(node, move |ev| {
820                if matches!(ev, Event::Pressed) && gate.get() {
821                    action();
822                }
823            });
824        }
825        if matches!(&self.icon, Reactive::Const(None)) {
826            // Preserve the existing patch contract for plain buttons and external toolkits.
827            self.title
828                .bind_to(node, |t| Box::new(ButtonPatch::Title(t)), true);
829        } else {
830            let icon = self.icon;
831            let icon_only = self.icon_only;
832            let seed = day_spec::props::ButtonContent {
833                title: initial,
834                icon: icon.get_untracked(),
835                icon_only,
836            };
837            let title = self.title;
838            bind_seeded(
839                seed,
840                move || day_spec::props::ButtonContent {
841                    title: title.resolve(),
842                    icon: icon.get(),
843                    icon_only,
844                },
845                move |content: &day_spec::props::ButtonContent| {
846                    with_tree(|t| {
847                        t.patch(node, Box::new(ButtonPatch::Content(content.clone())), true);
848                    });
849                },
850            );
851        }
852        node
853    }
854}
855
856#[must_use]
857pub struct Toggle<S: Binding<bool>> {
858    value: S,
859    enabled: Reactive<bool>,
860}
861
862pub fn toggle<S: Binding<bool>>(value: S) -> Toggle<S> {
863    Toggle {
864        value,
865        enabled: true.into_reactive(),
866    }
867}
868
869#[day_macros::builder(ToggleBuilder)]
870impl<S: Binding<bool>> Toggle<S> {
871    /// Whether the toggle is interactive (default `true`; `false` = disabled/grayed). Reactive,
872    /// e.g. `.enabled(capability(Cap::TextSpellCheck) == Support::Native)` to gray it out where a
873    /// backend can't honor the thing it controls.
874    pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
875        self.enabled = v.into_reactive();
876        self
877    }
878}
879
880impl<S: Binding<bool>> Piece for Toggle<S> {
881    fn build(self, cx: &mut BuildCx) -> RNode {
882        let initial = self.value.peek();
883        let node = cx.leaf(
884            kinds::TOGGLE,
885            &ToggleProps {
886                on: initial,
887                enabled: self.enabled.get_untracked(),
888            },
889            Flex::default(),
890        );
891        let v = self.value.clone();
892        bind_seeded(
893            initial,
894            move || v.read(),
895            move |on: &bool| {
896                with_tree(|t| t.patch(node, Box::new(TogglePatch::On(*on)), false));
897            },
898        );
899        // A reactive `enabled` patches on change; a constant is applied once at realize.
900        let enabled = self.enabled;
901        if let Reactive::Dyn(_) = &enabled {
902            bind(
903                move || enabled.get(),
904                move |e: &bool| {
905                    with_tree(|t| t.patch(node, Box::new(TogglePatch::Enabled(*e)), false));
906                },
907            );
908        }
909        let v = self.value;
910        cx.on(node, move |ev| {
911            if let Event::ToggleChanged(on) = ev {
912                v.write(*on);
913            }
914        });
915        node
916    }
917}
918
919#[must_use]
920pub struct Slider<S: Binding<f64>> {
921    value: S,
922    min: f64,
923    max: f64,
924    step: Option<f64>,
925    enabled: Reactive<bool>,
926}
927
928pub fn slider<S: Binding<f64>>(value: S) -> Slider<S> {
929    Slider {
930        value,
931        min: 0.0,
932        max: 1.0,
933        step: None,
934        enabled: Reactive::Const(true),
935    }
936}
937
938#[day_macros::builder(SliderBuilder)]
939impl<S: Binding<f64>> Slider<S> {
940    /// Whether the slider takes input (default `true`); a constant or a reactive `bool`.
941    pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
942        self.enabled = v.into_reactive();
943        self
944    }
945    pub fn range(mut self, r: std::ops::RangeInclusive<f64>) -> Self {
946        self.min = *r.start();
947        self.max = *r.end();
948        self
949    }
950    pub fn step(mut self, s: f64) -> Self {
951        self.step = Some(s);
952        self
953    }
954}
955
956impl<S: Binding<f64>> Piece for Slider<S> {
957    fn build(self, cx: &mut BuildCx) -> RNode {
958        let initial = self.value.peek();
959        let node = cx.leaf(
960            kinds::SLIDER,
961            &SliderProps {
962                value: initial,
963                min: self.min,
964                max: self.max,
965                step: self.step,
966                enabled: self.enabled.get_untracked(),
967            },
968            Flex {
969                grow_w: true,
970                ..Default::default()
971            },
972        );
973        let enabled = self.enabled;
974        if let Reactive::Dyn(_) = &enabled {
975            bind(
976                move || enabled.get(),
977                move |e: &bool| {
978                    with_tree(|t| t.patch(node, Box::new(SliderPatch::Enabled(*e)), false));
979                },
980            );
981        }
982        let v = self.value.clone();
983        bind_seeded(
984            initial,
985            move || v.read(),
986            move |val: &f64| {
987                with_tree(|t| t.patch(node, Box::new(SliderPatch::Value(*val)), false));
988            },
989        );
990        let v = self.value;
991        let (step, min, max) = (self.step, self.min, self.max);
992        cx.on(node, move |ev| {
993            // Honor `.step(_)` at the framework layer so every backend produces stepped values:
994            // several native sliders (e.g. iOS `UISlider`) have no native step and emit a
995            // continuous stream while dragging. Snapping here keeps the bound signal (and the
996            // thumb, via `bind_seeded` above) on the step grid, and stops a `.step`-bound consumer
997            // from being hammered ~60Γ—/s with sub-step deltas during a drag.
998            let snap = |val: f64| match step {
999                Some(s) if s > 0.0 => (min + ((val - min) / s).round() * s).clamp(min, max),
1000                _ => val,
1001            };
1002            match ev {
1003                // The live half of the pair: readers follow the thumb; nothing durable keys
1004                // off it (a day-model field opens a preview session here).
1005                Event::ValueChanged(val) => v.write_preview(snap(*val)),
1006                // The settled value: One record for the whole drag. A backend that cannot
1007                // tell the two apart never sends this, and the preview default (a plain
1008                // write) keeps it correct: chattier, never wrong.
1009                Event::ValueCommitted(val) => v.write_commit(snap(*val)),
1010                _ => {}
1011            }
1012        });
1013        node
1014    }
1015}
1016
1017/// A single-line text input bound to a `String` (docs/textfield.md).
1018///
1019/// How it takes its text is set with `.secure(_)`, `.read_only(_)`, `.input_purpose(_)`,
1020/// `.submit_label(_)` and `.max_length(_)`; [`secure_field`] is the password-field shorthand.
1021#[must_use]
1022pub struct TextField<S: Binding<String>> {
1023    value: S,
1024    placeholder: Option<TextSource>,
1025    on_submit: Option<Rc<dyn Fn()>>,
1026    secure: Reactive<bool>,
1027    read_only: Reactive<bool>,
1028    purpose: day_spec::InputPurpose,
1029    submit_label: day_spec::SubmitLabel,
1030    max_length: Option<u32>,
1031    enabled: Reactive<bool>,
1032    select: Option<(day_reactive::Trigger, Rc<dyn Fn() -> TextSelection>)>,
1033}
1034
1035pub fn text_field<S: Binding<String>>(value: S) -> TextField<S> {
1036    TextField {
1037        value,
1038        placeholder: None,
1039        on_submit: None,
1040        secure: Reactive::Const(false),
1041        read_only: Reactive::Const(false),
1042        purpose: day_spec::InputPurpose::Text,
1043        submit_label: day_spec::SubmitLabel::Return,
1044        max_length: None,
1045        enabled: Reactive::Const(true),
1046        select: None,
1047    }
1048}
1049
1050/// A password field: a [`text_field`] that hides its characters and tells the platform it
1051/// holds a password, so the password manager offers to fill it (docs/textfield.md).
1052///
1053/// It is the same piece, so every `text_field` builder applies. `.secure(shown)` with a signal
1054/// makes a show-password switch; `.input_purpose(InputPurpose::NewPassword)` marks a sign-up
1055/// form's field.
1056pub fn secure_field<S: Binding<String>>(value: S) -> TextField<S> {
1057    text_field(value)
1058        .secure(true)
1059        .input_purpose(day_spec::InputPurpose::Password)
1060}
1061
1062#[day_macros::builder(TextFieldBuilder)]
1063impl<S: Binding<String>> TextField<S> {
1064    /// Whether the field takes input (default `true`); a constant or a reactive `bool`. A
1065    /// disabled field neither edits nor focuses; [`TextField::read_only`] keeps it selectable.
1066    pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1067        self.enabled = v.into_reactive();
1068        self
1069    }
1070    pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
1071        self.placeholder = Some(t.into_text());
1072        self
1073    }
1074    /// Fire when the user submits the field (Return / the keyboard's action key). Field
1075    /// chaining is a focus write inside the handler: `focus.set(Some(Field::Next))`
1076    /// (docs/focus.md).
1077    pub fn on_submit(mut self, f: impl Fn() + 'static) -> Self {
1078        self.on_submit = Some(Rc::new(f));
1079        self
1080    }
1081    /// Hide the characters as they are typed (default `false`). Reactive: bind it to a signal
1082    /// for a show-password switch. The text, the placeholder and the focus carry across the
1083    /// change on every backend, including the two whose secure field is a different native
1084    /// class.
1085    pub fn secure<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1086        self.secure = v.into_reactive();
1087        self
1088    }
1089    /// Show the text and let it be selected and copied, and take no edits (default `false`).
1090    /// Reactive. Unlike `.disabled(true)` the field keeps its ordinary look and still takes
1091    /// focus.
1092    pub fn read_only<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1093        self.read_only = v.into_reactive();
1094        self
1095    }
1096    /// What the field collects: the on-screen keyboard, capitalization and correction, and
1097    /// what the system offers to fill in all follow from it.
1098    pub fn input_purpose(mut self, purpose: day_spec::InputPurpose) -> Self {
1099        self.purpose = purpose;
1100        self
1101    }
1102    /// What the on-screen keyboard's action key says. The key fires `on_submit` either way.
1103    pub fn submit_label(mut self, label: day_spec::SubmitLabel) -> Self {
1104        self.submit_label = label;
1105        self
1106    }
1107    /// The most characters the field takes. Typing or pasting past it is cut to fit before
1108    /// the bound value sees it.
1109    pub fn max_length(mut self, characters: u32) -> Self {
1110        self.max_length = Some(characters);
1111        self
1112    }
1113    /// Select part of the text, or place the caret, each time `trigger` fires
1114    /// (docs/textfield.md "Selection"). `range` is read once the turn settles, after any text
1115    /// the same turn wrote has reached the field, and counts characters (Unicode scalar
1116    /// values): `..` selects everything, `3..` from the fourth character to the end, `3..3`
1117    /// puts the caret after the third. Ends past the text are held to it.
1118    ///
1119    /// An address bar's inline completion writes the completed text and selects what the user
1120    /// did not type, so the next keystroke replaces it:
1121    ///
1122    /// ```ignore
1123    /// let complete = Trigger::new();
1124    /// let typed = Signal::new(0usize);
1125    /// text_field(address).select(complete, move || typed.get_untracked()..)
1126    /// // on input "git": typed.set(3); address.set("github.com".into()); complete.notify();
1127    /// ```
1128    ///
1129    /// The selection is for a focused field; fire it from the same turn that focuses the field,
1130    /// or from a [`Decorate::focused`] change, to select everything on focus.
1131    pub fn select<R: std::ops::RangeBounds<usize> + 'static>(
1132        mut self,
1133        trigger: day_reactive::Trigger,
1134        range: impl Fn() -> R + 'static,
1135    ) -> Self {
1136        self.select = Some((
1137            trigger,
1138            Rc::new(move || {
1139                use std::ops::Bound;
1140                let r = range();
1141                let start = match r.start_bound() {
1142                    Bound::Included(&n) => n,
1143                    Bound::Excluded(&n) => n.saturating_add(1),
1144                    Bound::Unbounded => 0,
1145                };
1146                let end = match r.end_bound() {
1147                    Bound::Included(&n) => n.saturating_add(1),
1148                    Bound::Excluded(&n) => n,
1149                    Bound::Unbounded => usize::MAX,
1150                };
1151                TextSelection::new(start, end)
1152            }),
1153        ));
1154        self
1155    }
1156}
1157
1158impl<S: Binding<String>> Piece for TextField<S> {
1159    fn build(self, cx: &mut BuildCx) -> RNode {
1160        let initial = self.value.peek();
1161        let ph = self
1162            .placeholder
1163            .as_ref()
1164            .map_or_default(super::sources::TextSource::initial);
1165        let node = cx.leaf(
1166            kinds::TEXT_FIELD,
1167            &TextFieldProps {
1168                text: initial.clone(),
1169                placeholder: ph,
1170                enabled: self.enabled.get_untracked(),
1171            },
1172            Flex {
1173                grow_w: true,
1174                ..Default::default()
1175            },
1176        );
1177        if let Reactive::Dyn(_) = &self.enabled {
1178            let enabled = self.enabled.clone();
1179            bind(
1180                move || enabled.get(),
1181                move |e: &bool| {
1182                    with_tree(|t| t.patch(node, Box::new(TextFieldPatch::Enabled(*e)), false));
1183                },
1184            );
1185        }
1186        // Text entry traits (docs/textfield.md). The duty is skipped for a field that asks for
1187        // nothing, so a plain field costs what it did; a reactive member re-sends the whole
1188        // set, which is what lets a backend rebuild the widget as its secure class and dress
1189        // the replacement in one call.
1190        let (secure, read_only) = (self.secure, self.read_only);
1191        let (purpose, submit_label, max_length) =
1192            (self.purpose, self.submit_label, self.max_length);
1193        let traits = move |secure: bool, read_only: bool| day_spec::InputTraits {
1194            secure,
1195            read_only,
1196            purpose,
1197            submit_label,
1198            max_length,
1199        };
1200        let initial_traits = traits(secure.get_untracked(), read_only.get_untracked());
1201        let reactive_traits =
1202            matches!(secure, Reactive::Dyn(_)) || matches!(read_only, Reactive::Dyn(_));
1203        if initial_traits != day_spec::InputTraits::default() {
1204            with_tree(|t| t.set_node_input_traits(node, &initial_traits));
1205        }
1206        if reactive_traits {
1207            bind_seeded(
1208                initial_traits,
1209                move || traits(secure.get(), read_only.get()),
1210                move |tr: &day_spec::InputTraits| {
1211                    with_tree(|t| t.set_node_input_traits(node, tr));
1212                },
1213            );
1214        }
1215        // Controlled input with origin-tagged writes (Β§4.4): the echo guard remembers the
1216        // last value that came from the native widget so its own change is not written back.
1217        let guard: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
1218        // The typing session's latest text, sealed on Return or focus loss (below).
1219        let last: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
1220        let v = self.value.clone();
1221        let session = self.value.clone();
1222        let (g, typed) = (guard.clone(), last.clone());
1223        bind_seeded(
1224            initial,
1225            move || v.read(),
1226            move |t: &String| {
1227                let from_native = g.borrow_mut().take().as_deref() == Some(t.as_str());
1228                if !from_native && typed.borrow_mut().take().is_some() {
1229                    // An app write (an address bar's completion, Escape putting the URL back)
1230                    // replaces the typing session: sealing it later would write the typed
1231                    // text back over this one, and the binding's open preview session still
1232                    // holds the text from before the typing. The app's write recorded its own
1233                    // change; close the session so the next keystroke starts from it.
1234                    session.end_preview();
1235                }
1236                with_tree(|tr| {
1237                    tr.patch(
1238                        node,
1239                        Box::new(TextFieldPatch::Text {
1240                            text: t.clone(),
1241                            from_native,
1242                        }),
1243                        false,
1244                    );
1245                });
1246            },
1247        );
1248        let value = self.value.clone();
1249        let v = self.value;
1250        let submit = self.on_submit;
1251        // Typing is a session: each keystroke is a preview (readers follow, nothing durable
1252        // fires), sealed into one committed change on Return or focus loss by the typing
1253        // coalescer. For a plain Signal binding preview defaults to write, so nothing changes
1254        // where no session semantics exist. Teardown seals too: navigating away from a page
1255        // mid-type must not leave the last burst outside the change log.
1256        {
1257            let (v, last) = (v.clone(), last.clone());
1258            day_reactive::Scope::current().on_cleanup(move || {
1259                if let Some(t) = last.borrow_mut().take() {
1260                    v.write_teardown(t);
1261                }
1262            });
1263        }
1264        cx.on(node, move |ev| match ev {
1265            Event::TextChanged(t) => {
1266                // The length bound, held here so it counts the same characters on every
1267                // backend, whatever unit a native limit would count. The cut text is painted back as
1268                // an app write: the native field is showing the longer one, and the bound
1269                // value may not change at all (typing at the limit), so no binding would.
1270                let cut = max_length
1271                    .and_then(|max| t.char_indices().nth(max as usize))
1272                    .map(|(at, _)| t[..at].to_string());
1273                let t = match cut {
1274                    Some(cut) => {
1275                        with_tree(|tr| {
1276                            tr.patch(
1277                                node,
1278                                Box::new(TextFieldPatch::Text {
1279                                    text: cut.clone(),
1280                                    from_native: false,
1281                                }),
1282                                false,
1283                            );
1284                        });
1285                        cut
1286                    }
1287                    None => t.clone(),
1288                };
1289                *guard.borrow_mut() = Some(t.clone());
1290                *last.borrow_mut() = Some(t.clone());
1291                v.write_preview(t);
1292            }
1293            Event::Submitted => {
1294                if let Some(t) = last.borrow_mut().take() {
1295                    v.write_commit(t);
1296                }
1297                if let Some(f) = &submit {
1298                    f();
1299                }
1300            }
1301            Event::FocusChanged(false) => {
1302                if let Some(t) = last.borrow_mut().take() {
1303                    v.write_commit(t);
1304                }
1305            }
1306            _ => {}
1307        });
1308        if let Some(p) = self.placeholder {
1309            p.bind_to(node, |t| Box::new(TextFieldPatch::Placeholder(t)), false);
1310        }
1311        // Selection requests (docs/textfield.md "Selection"). Each firing is a request, so the
1312        // same range applies again on the next one (select-all on every focus). The range is
1313        // read once the turn settles, so the text written in the same turn has reached the
1314        // field first, whatever order the app wrote the two in, and it is held to that text.
1315        // The patch itself is posted, as a focus request is (`Decorate::focused`): one made in
1316        // the same turn lands first, and AppKit and UIKit select only in a focused field.
1317        if let Some((trigger, range)) = self.select {
1318            let scope = day_reactive::Scope::current();
1319            day_reactive::watch(
1320                move || trigger.track(),
1321                move |(), _| {
1322                    let (range, value) = (range.clone(), value.clone());
1323                    day_reactive::at_turn_end(move || {
1324                        if !scope.is_alive() {
1325                            return;
1326                        }
1327                        let sel = range().clamped(&value.peek());
1328                        day_reactive::on_main(move || {
1329                            with_tree(|t| {
1330                                t.patch(node, Box::new(TextFieldPatch::Select(sel)), false);
1331                            });
1332                        });
1333                    });
1334                },
1335            );
1336        }
1337        node
1338    }
1339}
1340
1341/// A progress indicator: a determinate bar (from [`progress`]) or an indeterminate spinner
1342/// (from [`spinner`]). See docs/progress.md.
1343#[must_use]
1344pub struct Progress {
1345    /// `None` = indeterminate (spinner); `Some` = a determinate fraction source.
1346    value: Option<FractionSource>,
1347    animating: crate::Reactive<bool>,
1348    large: bool,
1349}
1350
1351/// An indeterminate, animated progress indicator (a spinner / busy bar) for work with no
1352/// known extent.
1353pub fn spinner() -> Progress {
1354    Progress {
1355        value: None,
1356        animating: crate::Reactive::Const(true),
1357        large: false,
1358    }
1359}
1360
1361/// A determinate progress bar. `fraction` is the completed portion in `0.0..=1.0`; pass a
1362/// constant, a `Signal<f64>`, or a closure and it tracks reactively (out-of-range values are
1363/// clamped).
1364pub fn progress<M>(fraction: impl IntoFraction<M>) -> Progress {
1365    Progress {
1366        value: Some(fraction.into_fraction()),
1367        animating: crate::Reactive::Const(true),
1368        large: false,
1369    }
1370}
1371
1372#[day_macros::builder(ProgressBuilder)]
1373impl Progress {
1374    /// Start or stop an indeterminate indicator, keeping its layout space.
1375    pub fn animating<M>(mut self, source: impl crate::IntoReactive<bool, M>) -> Self {
1376        self.animating = source.into_reactive();
1377        self
1378    }
1379    /// Use the platform's large indeterminate indicator.
1380    pub fn large(mut self) -> Self {
1381        self.large = true;
1382        self
1383    }
1384}
1385
1386impl Piece for Progress {
1387    fn build(self, cx: &mut BuildCx) -> RNode {
1388        let determinate = self.value.is_some();
1389        let initial = self
1390            .value
1391            .as_ref()
1392            .map(super::sources::FractionSource::initial);
1393        let node = cx.leaf(
1394            kinds::PROGRESS,
1395            &ProgressProps {
1396                value: initial,
1397                animating: self.animating.get_untracked(),
1398                large: self.large,
1399            },
1400            // A determinate bar fills the available width (like a slider); a spinner keeps its
1401            // fixed intrinsic size.
1402            Flex {
1403                grow_w: determinate,
1404                ..Default::default()
1405            },
1406        );
1407        if !determinate && let crate::Reactive::Dyn(f) = self.animating {
1408            day_reactive::bind_seeded(
1409                f(),
1410                move || f(),
1411                move |on| {
1412                    day_core::with_tree(|t| {
1413                        t.patch(node, Box::new(ProgressPatch::Animating(*on)), false);
1414                    });
1415                },
1416            );
1417        }
1418        if let Some(src) = self.value {
1419            src.bind_to(node);
1420        }
1421        node
1422    }
1423}
1424
1425/// A hairline between neighbors: across a column's width by default, down a row's height
1426/// with [`Divider::vertical`].
1427#[must_use]
1428pub struct Divider {
1429    vertical: bool,
1430}
1431
1432pub fn divider() -> Divider {
1433    Divider { vertical: false }
1434}
1435
1436#[day_macros::builder(DividerBuilder)]
1437impl Divider {
1438    /// Turn the rule on its side: a thin vertical line that fills the row's height, the way the
1439    /// horizontal one fills a column's width. Between a row's panes, where a horizontal rule
1440    /// would draw a stray line across one of them.
1441    pub fn vertical(mut self) -> Self {
1442        self.vertical = true;
1443        self
1444    }
1445}
1446
1447impl Piece for Divider {
1448    fn build(self, cx: &mut BuildCx) -> RNode {
1449        let props = DividerProps {
1450            vertical: self.vertical,
1451        };
1452        if self.vertical {
1453            cx.native(
1454                kinds::DIVIDER,
1455                &props,
1456                Rc::new(VerticalLeaf),
1457                Flex {
1458                    grow_h: true,
1459                    ..Default::default()
1460                },
1461                Boundary::No,
1462            )
1463        } else {
1464            cx.leaf(
1465                kinds::DIVIDER,
1466                &props,
1467                Flex {
1468                    grow_w: true,
1469                    ..Default::default()
1470                },
1471            )
1472        }
1473    }
1474}
1475
1476/// A native leaf measured with its axes swapped: the toolkit answers as it does for a
1477/// horizontal rule (the offered width, by its hairline thickness), and the vertical rule is that
1478/// answer turned on its side. One measurement arm per toolkit, whichever way the line runs.
1479struct VerticalLeaf;
1480
1481impl Layout for VerticalLeaf {
1482    fn measure(&self, cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
1483        let s = cx.measure_leaf(Proposal::new(p.height, p.width));
1484        Size::new(s.height, s.width)
1485    }
1486    fn place(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _bounds: Rect) {}
1487}
1488
1489pub struct Spacer;
1490
1491#[must_use]
1492pub fn spacer() -> Spacer {
1493    Spacer
1494}
1495
1496impl Piece for Spacer {
1497    fn build(self, cx: &mut BuildCx) -> RNode {
1498        cx.layout_only(
1499            Rc::new(PassThrough),
1500            Flex {
1501                is_spacer: true,
1502                ..Default::default()
1503            },
1504            Boundary::No,
1505        )
1506    }
1507}
1508
1509// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
1510
1511// ---------------------------------------------------------------------------
1512// Conformance cases (docs/testing.md): each leaf's behavior on the real toolkit
1513// ---------------------------------------------------------------------------
1514
1515/// The leaves' `#[day::test]` cases, next to the constructors they prove. Compiled only under
1516/// the `conformance` feature, so a shipping app links none of it.
1517#[cfg(feature = "conformance")]
1518pub(crate) mod conformance {
1519    use day_core::conformance::{Case, Drive, FrameExpect, NativeExpect};
1520    use day_reactive::Signal;
1521    use day_spec::{Cap, Font, Role, kinds};
1522
1523    use crate::*;
1524
1525    /// A button fires its action on each press and counts it.
1526    #[day_macros::test(day_core)]
1527    fn button_press() -> Case {
1528        let presses = Signal::new(0i64);
1529        Case::new()
1530            .proves(kinds::BUTTON)
1531            .page(move || {
1532                column((
1533                    button("Press")
1534                        .action(move || presses.update(|n| *n += 1))
1535                        .id(day_core::id!(press)),
1536                    label(move || presses.get().to_string()).id(day_core::id!(count)),
1537                ))
1538                .spacing(8.0)
1539            })
1540            .shot("default")
1541            .drive(|d: Drive| async move {
1542                d.assert_text("press", "Press").await?;
1543                d.tap("press").await?;
1544                d.assert_text("count", "1").await?;
1545                d.tap("press").await?;
1546                d.assert_text("count", "2").await
1547            })
1548    }
1549
1550    /// A disabled button reports itself disabled, in Day and natively, and takes presses once
1551    /// enabled. (A tap on a disabled button is not drivable: the `tap` step waits for the
1552    /// element to be enabled, as a person would.)
1553    #[day_macros::test(day_core)]
1554    fn button_disabled() -> Case {
1555        let presses = Signal::new(0i64);
1556        let enabled = Signal::new(false);
1557        Case::new()
1558            .proves(kinds::BUTTON)
1559            .proves_duty("set_enabled")
1560            .page(move || {
1561                column((
1562                    button("Off")
1563                        .enabled(move || enabled.get())
1564                        .action(move || presses.update(|n| *n += 1))
1565                        .id(day_core::id!(off)),
1566                    label(move || presses.get().to_string()).id(day_core::id!(count)),
1567                    button("Enable")
1568                        .action(move || enabled.set(true))
1569                        .id(day_core::id!(enable)),
1570                ))
1571                .spacing(8.0)
1572            })
1573            .drive(|d: Drive| async move {
1574                d.assert_enabled("off", false).await?;
1575                d.assert_text("count", "0").await?;
1576                d.tap("enable").await?;
1577                d.assert_enabled("off", true).await?;
1578                d.tap("off").await?;
1579                d.assert_text("count", "1").await
1580            })
1581    }
1582
1583    /// A toggle reports its flips to its signal, and a write to the signal reaches it.
1584    #[day_macros::test(day_core)]
1585    fn toggle_binding() -> Case {
1586        let on = Signal::new(false);
1587        Case::new()
1588            .proves(kinds::TOGGLE)
1589            .page(move || {
1590                column((
1591                    toggle(on).id(day_core::id!(tgl_switch)),
1592                    label(move || if on.get() { "on" } else { "off" }.to_owned())
1593                        .id(day_core::id!(tgl_state)),
1594                    button("Set on")
1595                        .action(move || on.set(true))
1596                        .id(day_core::id!(tgl_set)),
1597                ))
1598                .spacing(8.0)
1599            })
1600            .drive(|d: Drive| async move {
1601                d.toggle("tgl_switch", true).await?;
1602                d.assert_text("tgl_state", "on").await?;
1603                d.toggle("tgl_switch", false).await?;
1604                d.assert_text("tgl_state", "off").await?;
1605                d.tap("tgl_set").await?;
1606                d.assert_on("tgl_switch", true).await
1607            })
1608    }
1609
1610    /// A text field writes what is typed to its signal, and shows what the signal is set to.
1611    #[day_macros::test(day_core)]
1612    fn text_field_binding() -> Case {
1613        let name = Signal::new(String::new());
1614        Case::new()
1615            .proves(kinds::TEXT_FIELD)
1616            .page(move || {
1617                column((
1618                    text_field(name)
1619                        .placeholder("Name")
1620                        .id(day_core::id!(tf_field)),
1621                    label(move || name.get()).id(day_core::id!(tf_echo)),
1622                    button("Set")
1623                        .action(move || name.set("Ada".into()))
1624                        .id(day_core::id!(tf_set)),
1625                ))
1626                .spacing(8.0)
1627            })
1628            .drive(|d: Drive| async move {
1629                d.input("tf_field", "Grace").await?;
1630                d.assert_text("tf_echo", "Grace").await?;
1631                d.tap("tf_set").await?;
1632                d.assert_text("tf_field", "Ada").await
1633            })
1634    }
1635
1636    /// A secure field keeps its text and its focus across a show-password flip: on AppKit and
1637    /// WinUI the flip rebuilds the widget as its other native class (docs/textfield.md).
1638    #[day_macros::test(day_core)]
1639    fn text_field_secure() -> Case {
1640        let password = Signal::new(String::new());
1641        let shown = Signal::new(false);
1642        Case::new()
1643            .proves(kinds::TEXT_FIELD)
1644            .proves_duty("set_input_traits")
1645            .page(move || {
1646                column((
1647                    secure_field(password)
1648                        .secure(move || !shown.get())
1649                        .placeholder("Password")
1650                        .id(day_core::id!(tfs_pass)),
1651                    toggle(shown).id(day_core::id!(tfs_show)),
1652                    label(move || password.get().chars().count().to_string())
1653                        .id(day_core::id!(tfs_len)),
1654                ))
1655                .spacing(8.0)
1656            })
1657            .shot("masked")
1658            .drive(|d: Drive| async move {
1659                d.input("tfs_pass", "correct horse").await?;
1660                d.assert_text("tfs_len", "13").await?;
1661                d.focus("tfs_pass").await?;
1662                d.toggle("tfs_show", true).await?;
1663                d.wait_idle().await?;
1664                d.shot("shown").await?;
1665                d.assert_focused("tfs_pass", true).await?;
1666                d.input("tfs_pass", "battery").await?;
1667                d.assert_text("tfs_len", "7").await?;
1668                d.toggle("tfs_show", false).await?;
1669                d.wait_idle().await?;
1670                d.assert_text("tfs_pass", "battery").await
1671            })
1672    }
1673
1674    /// A field held to four characters cuts what is typed past them, on every toolkit alike.
1675    #[day_macros::test(day_core)]
1676    fn text_field_max_length() -> Case {
1677        let pin = Signal::new(String::new());
1678        Case::new()
1679            .proves(kinds::TEXT_FIELD)
1680            .page(move || {
1681                column((
1682                    text_field(pin).max_length(4).id(day_core::id!(tfm_pin)),
1683                    label(move || pin.get()).id(day_core::id!(tfm_echo)),
1684                ))
1685                .spacing(8.0)
1686            })
1687            .drive(|d: Drive| async move {
1688                d.input("tfm_pin", "123456").await?;
1689                d.assert_text("tfm_echo", "1234").await?;
1690                d.assert_text("tfm_pin", "1234").await
1691            })
1692    }
1693
1694    /// A slider's value reaches its signal on the step grid the piece declares, whatever the
1695    /// native control's own stepping.
1696    #[day_macros::test(day_core)]
1697    fn slider_range() -> Case {
1698        let value = Signal::new(40.0f64);
1699        Case::new()
1700            .proves(kinds::SLIDER)
1701            .page(move || {
1702                column((
1703                    slider(value)
1704                        .range(0.0..=100.0)
1705                        .step(10.0)
1706                        .id(day_core::id!(sl_slider)),
1707                    label(move || format!("{:.0}", value.get())).id(day_core::id!(sl_value)),
1708                ))
1709                .spacing(8.0)
1710            })
1711            .drive(|d: Drive| async move {
1712                d.set_value("sl_slider", 72.0).await?;
1713                d.assert_text("sl_value", "70").await?;
1714                d.assert_value("sl_slider", 70.0).await
1715            })
1716    }
1717
1718    /// A label shows its text, follows a signal, and reports its explicit role natively where
1719    /// the toolkit reads its tree back.
1720    #[day_macros::test(day_core)]
1721    fn label_heading() -> Case {
1722        let text = Signal::new("Hello".to_owned());
1723        Case::new()
1724            .proves(kinds::LABEL)
1725            .proves_duty("set_a11y")
1726            .page(move || {
1727                column((
1728                    label(move || text.get())
1729                        .font(Font::Headline)
1730                        .a11y(|a| a.role(Role::Heading(2)))
1731                        .id(day_core::id!(lbl_heading)),
1732                    button("Rename")
1733                        .action(move || text.set("Renamed".into()))
1734                        .id(day_core::id!(lbl_rename)),
1735                ))
1736                .spacing(8.0)
1737            })
1738            .drive(|d: Drive| async move {
1739                d.assert_text("lbl_heading", "Hello").await?;
1740                d.tap("lbl_rename").await?;
1741                d.assert_text("lbl_heading", "Renamed").await?;
1742                d.a11y_audit(Some("lbl_heading")).await
1743            })
1744    }
1745
1746    /// A label shows its text, natively too.
1747    #[day_macros::test(day_core)]
1748    fn label_text() -> Case {
1749        Case::new()
1750            .proves(kinds::LABEL)
1751            .page(|| label("Plain text").id(day_core::id!(text)))
1752            .drive(|d: Drive| async move { d.assert_text("text", "Plain text").await })
1753    }
1754
1755    /// A label bound to a signal follows every write.
1756    #[day_macros::test(day_core)]
1757    fn label_reactive() -> Case {
1758        let count = Signal::new(0i64);
1759        Case::new()
1760            .proves(kinds::LABEL)
1761            .proves_duty("update")
1762            .proves_duty("read_native")
1763            .page(move || {
1764                column((
1765                    label(move || format!("Count {}", count.get())).id(day_core::id!(text)),
1766                    button("Add")
1767                        .action(move || count.update(|n| *n += 1))
1768                        .id(day_core::id!(add)),
1769                ))
1770                .spacing(8.0)
1771            })
1772            .drive(|d: Drive| async move {
1773                d.assert_text("text", "Count 0").await?;
1774                d.tap("add").await?;
1775                d.tap("add").await?;
1776                d.assert_text("text", "Count 2").await
1777            })
1778    }
1779
1780    /// Styled runs draw as one string: the native text is the runs joined, without markup.
1781    #[day_macros::test(day_core)]
1782    fn label_runs() -> Case {
1783        Case::new()
1784            .proves(kinds::LABEL)
1785            .proves_cap(Cap::TextRuns)
1786            .requires(Cap::TextRuns)
1787            .page(|| {
1788                label("")
1789                    .runs_from(
1790                        TextBuilder::new()
1791                            .text("Plain, ")
1792                            .strong("strong")
1793                            .text(" and ")
1794                            .emphasis("emphasized"),
1795                    )
1796                    .id(day_core::id!(runs))
1797            })
1798            .shot("default")
1799            .drive(|d: Drive| async move {
1800                d.assert_text("runs", "Plain, strong and emphasized").await
1801            })
1802    }
1803
1804    /// Replacing link runs, clearing them and restoring them preserves the native text.
1805    /// Native input suites separately exercise each platform's span hit testing.
1806    #[day_macros::test(day_core)]
1807    fn label_link_runs_reactive() -> Case {
1808        let text = Signal::new("πŸ˜€ [Alpha](#alpha) / [Beta](#beta)".to_string());
1809        Case::new()
1810            .proves(kinds::LABEL)
1811            .requires(Cap::TextRuns)
1812            .page(move || {
1813                column((
1814                    label(text).markdown().id(day_core::id!(links)),
1815                    button("Replace")
1816                        .id(day_core::id!(replace))
1817                        .action(move || {
1818                            text.set("[東京](#tokyo) then [again](#again)".into());
1819                        }),
1820                    button("Plain")
1821                        .id(day_core::id!(plain))
1822                        .action(move || text.set("Plain πŸ˜€".into())),
1823                    button("Restore")
1824                        .id(day_core::id!(restore))
1825                        .action(move || text.set("[Restored](#restored)".into())),
1826                ))
1827            })
1828            .drive(|d: Drive| async move {
1829                d.assert_text("links", "πŸ˜€ Alpha / Beta").await?;
1830                d.tap("replace").await?;
1831                d.assert_text("links", "東京 then again").await?;
1832                d.tap("plain").await?;
1833                d.assert_text("links", "Plain πŸ˜€").await?;
1834                d.tap("restore").await?;
1835                d.assert_text("links", "Restored").await
1836            })
1837    }
1838
1839    /// A selectable label still shows its text. Every toolkit implements label selection
1840    /// (`set_selectable`); `Cap::TextSelectable` is the text area's toggle, not this.
1841    #[day_macros::test(day_core)]
1842    fn label_selectable() -> Case {
1843        Case::new()
1844            .proves(kinds::LABEL)
1845            .proves_modifier("selectable")
1846            .proves_duty("set_selectable")
1847            .page(|| label("Copy me").selectable().id(day_core::id!(text)))
1848            .drive(|d: Drive| async move { d.assert_text("text", "Copy me").await })
1849    }
1850
1851    /// A button's title shows natively, and a title bound to a signal follows it.
1852    #[day_macros::test(day_core)]
1853    fn button_title() -> Case {
1854        let saved = Signal::new(false);
1855        Case::new()
1856            .proves(kinds::BUTTON)
1857            .page(move || {
1858                button(move || if saved.get() { "Saved" } else { "Save" }.to_owned())
1859                    .action(move || saved.set(true))
1860                    .id(day_core::id!(save))
1861            })
1862            .drive(|d: Drive| async move {
1863                d.assert_text("save", "Save").await?;
1864                d.tap("save").await?;
1865                d.assert_text("save", "Saved").await
1866            })
1867    }
1868
1869    /// A button's accessibility label, as the platform reports it.
1870    #[day_macros::test(day_core)]
1871    fn button_a11y() -> Case {
1872        Case::new()
1873            .proves(kinds::BUTTON)
1874            .proves_modifier("a11y")
1875            .page(|| {
1876                button("Send")
1877                    .a11y(|a| a.label("Send the message"))
1878                    .id(day_core::id!(send))
1879            })
1880            .drive(|d: Drive| async move { d.a11y_audit(Some("send")).await })
1881    }
1882
1883    /// An app's accessibility label survives a title change on a button with an icon (Windows
1884    /// and Android used to replace it with the new title).
1885    #[day_macros::test(day_core)]
1886    fn button_a11y_survives_title_change() -> Case {
1887        let playing = Signal::new(false);
1888        Case::new()
1889            .proves(kinds::BUTTON)
1890            .proves_modifier("a11y")
1891            .page(move || {
1892                button(move || if playing.get() { "Pause" } else { "Play" }.to_owned())
1893                    .icon(day_spec::Symbol::Play)
1894                    .action(move || playing.set(true))
1895                    .a11y(|a| a.label("Playback"))
1896                    .id(day_core::id!(play))
1897            })
1898            .drive(|d: Drive| async move {
1899                d.a11y_audit(Some("play")).await?;
1900                d.tap("play").await?;
1901                d.assert_text("play", "Pause").await?;
1902                d.a11y_audit(Some("play")).await
1903            })
1904    }
1905
1906    /// A disabled toggle reports itself disabled, natively too, until it is enabled.
1907    #[day_macros::test(day_core)]
1908    fn toggle_disabled() -> Case {
1909        let on = Signal::new(false);
1910        let enabled = Signal::new(false);
1911        Case::new()
1912            .proves(kinds::TOGGLE)
1913            .page(move || {
1914                column((
1915                    toggle(on)
1916                        .enabled(move || enabled.get())
1917                        .id(day_core::id!(switch)),
1918                    button("Enable")
1919                        .action(move || enabled.set(true))
1920                        .id(day_core::id!(enable)),
1921                ))
1922                .spacing(8.0)
1923            })
1924            .drive(|d: Drive| async move {
1925                d.assert_enabled("switch", false).await?;
1926                d.tap("enable").await?;
1927                d.assert_enabled("switch", true).await?;
1928                d.toggle("switch", true).await?;
1929                d.assert_on("switch", true).await
1930            })
1931    }
1932
1933    /// A toggle built disabled from a constant is disabled from the start.
1934    #[day_macros::test(day_core)]
1935    fn toggle_disabled_constant() -> Case {
1936        let on = Signal::new(true);
1937        Case::new()
1938            .proves(kinds::TOGGLE)
1939            .page(move || toggle(on).enabled(false).id(day_core::id!(switch)))
1940            .drive(|d: Drive| async move {
1941                d.assert_enabled("switch", false).await?;
1942                d.assert_on("switch", true).await
1943            })
1944    }
1945
1946    /// A toggle's accessibility label, as the platform reports it.
1947    #[day_macros::test(day_core)]
1948    fn toggle_a11y() -> Case {
1949        let on = Signal::new(false);
1950        Case::new()
1951            .proves(kinds::TOGGLE)
1952            .page(move || {
1953                toggle(on)
1954                    .a11y(|a| a.label("Notifications"))
1955                    .id(day_core::id!(switch))
1956            })
1957            .drive(|d: Drive| async move { d.a11y_audit(Some("switch")).await })
1958    }
1959
1960    /// A disabled slider reports itself disabled, natively too, until it is enabled.
1961    #[day_macros::test(day_core)]
1962    fn slider_disabled() -> Case {
1963        let value = Signal::new(0.5f64);
1964        let enabled = Signal::new(false);
1965        Case::new()
1966            .proves(kinds::SLIDER)
1967            .page(move || {
1968                column((
1969                    slider(value)
1970                        .enabled(move || enabled.get())
1971                        .id(day_core::id!(slider)),
1972                    button("Enable")
1973                        .action(move || enabled.set(true))
1974                        .id(day_core::id!(enable)),
1975                ))
1976                .spacing(8.0)
1977            })
1978            .drive(|d: Drive| async move {
1979                d.assert_enabled("slider", false).await?;
1980                d.tap("enable").await?;
1981                d.assert_enabled("slider", true).await?;
1982                d.set_value("slider", 0.25).await?;
1983                d.assert_value("slider", 0.25).await
1984            })
1985    }
1986
1987    /// A write to a slider's signal moves the native thumb.
1988    #[day_macros::test(day_core)]
1989    fn slider_follows_signal() -> Case {
1990        let value = Signal::new(10.0f64);
1991        Case::new()
1992            .proves(kinds::SLIDER)
1993            .page(move || {
1994                column((
1995                    slider(value).range(0.0..=50.0).id(day_core::id!(slider)),
1996                    button("Set 40")
1997                        .action(move || value.set(40.0))
1998                        .id(day_core::id!(set)),
1999                ))
2000                .spacing(8.0)
2001            })
2002            .drive(|d: Drive| async move {
2003                d.assert_value("slider", 10.0).await?;
2004                d.tap("set").await?;
2005                d.assert_value("slider", 40.0).await
2006            })
2007    }
2008
2009    /// A slider's accessibility label, as the platform reports it.
2010    #[day_macros::test(day_core)]
2011    fn slider_a11y() -> Case {
2012        let value = Signal::new(0.5f64);
2013        Case::new()
2014            .proves(kinds::SLIDER)
2015            .page(move || {
2016                slider(value)
2017                    .a11y(|a| a.label("Volume"))
2018                    .id(day_core::id!(slider))
2019            })
2020            .drive(|d: Drive| async move { d.a11y_audit(Some("slider")).await })
2021    }
2022
2023    /// A disabled text field reports itself disabled, natively too, until it is enabled.
2024    #[day_macros::test(day_core)]
2025    fn text_field_disabled() -> Case {
2026        let text = Signal::new("Fixed".to_owned());
2027        let enabled = Signal::new(false);
2028        Case::new()
2029            .proves(kinds::TEXT_FIELD)
2030            .page(move || {
2031                column((
2032                    text_field(text)
2033                        .enabled(move || enabled.get())
2034                        .id(day_core::id!(field)),
2035                    button("Enable")
2036                        .action(move || enabled.set(true))
2037                        .id(day_core::id!(enable)),
2038                ))
2039                .spacing(8.0)
2040            })
2041            .drive(|d: Drive| async move {
2042                d.assert_enabled("field", false).await?;
2043                d.assert_text("field", "Fixed").await?;
2044                d.tap("enable").await?;
2045                d.assert_enabled("field", true).await?;
2046                d.input("field", "Changed").await?;
2047                d.assert_text("field", "Changed").await
2048            })
2049    }
2050
2051    /// A read-only field shows what its signal holds and stays enabled (selectable).
2052    #[day_macros::test(day_core)]
2053    fn text_field_read_only() -> Case {
2054        let text = Signal::new("Shown".to_owned());
2055        Case::new()
2056            .proves(kinds::TEXT_FIELD)
2057            .proves_duty("set_input_traits")
2058            .page(move || {
2059                column((
2060                    text_field(text).read_only(true).id(day_core::id!(field)),
2061                    button("Replace")
2062                        .action(move || text.set("Replaced".into()))
2063                        .id(day_core::id!(replace)),
2064                ))
2065                .spacing(8.0)
2066            })
2067            .drive(|d: Drive| async move {
2068                d.assert_text("field", "Shown").await?;
2069                d.assert_enabled("field", true).await?;
2070                d.tap("replace").await?;
2071                d.assert_text("field", "Replaced").await
2072            })
2073    }
2074
2075    /// Return in a field runs its submit action.
2076    #[day_macros::test(day_core)]
2077    fn text_field_submit() -> Case {
2078        let text = Signal::new(String::new());
2079        let sent = Signal::new(String::new());
2080        Case::new()
2081            .proves(kinds::TEXT_FIELD)
2082            .page(move || {
2083                column((
2084                    text_field(text)
2085                        .submit_label(day_spec::SubmitLabel::Send)
2086                        .on_submit(move || sent.set(text.get_untracked()))
2087                        .id(day_core::id!(field)),
2088                    label(move || sent.get()).id(day_core::id!(sent)),
2089                ))
2090                .spacing(8.0)
2091            })
2092            .drive(|d: Drive| async move {
2093                d.input("field", "hello").await?;
2094                d.submit("field").await?;
2095                d.assert_text("sent", "hello").await
2096            })
2097    }
2098
2099    /// A determinate bar shows its fraction natively and follows its signal.
2100    #[day_macros::test(day_core)]
2101    fn progress_value() -> Case {
2102        let done = Signal::new(0.25f64);
2103        Case::new()
2104            .proves(kinds::PROGRESS)
2105            .page(move || {
2106                column((
2107                    progress(done).id(day_core::id!(bar)),
2108                    button("Advance")
2109                        .action(move || done.set(0.75))
2110                        .id(day_core::id!(advance)),
2111                ))
2112                .spacing(8.0)
2113            })
2114            .drive(|d: Drive| async move {
2115                d.assert_value("bar", 0.25).await?;
2116                d.tap("advance").await?;
2117                d.assert_value("bar", 0.75).await
2118            })
2119    }
2120
2121    /// A spinner shows, and stays shown under reduced motion (it keeps moving).
2122    #[day_macros::test(day_core)]
2123    fn spinner_renders() -> Case {
2124        Case::new()
2125            .proves(kinds::PROGRESS)
2126            .page(|| spinner().id(day_core::id!(spin)))
2127            .drive(|d: Drive| async move {
2128                d.assert_visible("spin").await?;
2129                d.assert_native(
2130                    "spin",
2131                    NativeExpect {
2132                        visible: Some(true),
2133                        ..Default::default()
2134                    },
2135                )
2136                .await
2137            })
2138    }
2139
2140    /// Synthetic fixture: large indicators retain their native size when animation stops.
2141    #[day_macros::test(day_core)]
2142    fn spinner_size_and_animation() -> Case {
2143        Case::new()
2144            .proves(kinds::PROGRESS)
2145            .page(|| {
2146                let running = Signal::new(true);
2147                column((
2148                    spinner()
2149                        .animating(running)
2150                        .id(day_core::id!(spinner_fixture::small)),
2151                    spinner()
2152                        .animating(running)
2153                        .large()
2154                        .id(day_core::id!(spinner_fixture::large)),
2155                    button("Stop fixture")
2156                        .action(move || running.set(false))
2157                        .id(day_core::id!(spinner_fixture::stop)),
2158                ))
2159            })
2160            .drive(|d: Drive| async move {
2161                let sizes = match day_core::toolkit_key() {
2162                    Some("appkit") => Some((20.0, 32.0)),
2163                    Some("uikit") => Some((20.0, 37.0)),
2164                    Some("gtk") => Some((24.0, 48.0)),
2165                    Some("arkui") => Some((32.0, 64.0)),
2166                    Some("xaml" | "winui") => Some((32.0, 48.0)),
2167                    Some("dom") => Some((22.0, 48.0)),
2168                    _ => None, // Qt uses a busy bar; Android uses its theme's dimensions.
2169                };
2170                for stopped in [false, true] {
2171                    if stopped {
2172                        d.tap("spinner_fixture::stop").await?;
2173                    }
2174                    d.assert_visible("spinner_fixture::small").await?;
2175                    d.assert_visible("spinner_fixture::large").await?;
2176                    if let Some((small, large)) = sizes {
2177                        d.assert_size("spinner_fixture::small", small, small)
2178                            .await?;
2179                        d.assert_size("spinner_fixture::large", large, large)
2180                            .await?;
2181                    }
2182                }
2183                Ok(())
2184            })
2185    }
2186
2187    /// A divider takes the width it is given and draws as a thin rule.
2188    #[day_macros::test(day_core)]
2189    fn divider_renders() -> Case {
2190        Case::new()
2191            .proves(kinds::DIVIDER)
2192            .page(|| {
2193                column((
2194                    label("Above"),
2195                    divider().id(day_core::id!(rule)),
2196                    label("Below"),
2197                ))
2198                .spacing(8.0)
2199                .width(200.0)
2200            })
2201            .drive(|d: Drive| async move {
2202                d.assert_visible("rule").await?;
2203                d.assert_frame(
2204                    "rule",
2205                    FrameExpect {
2206                        width: Some(200.0),
2207                        ..Default::default()
2208                    },
2209                )
2210                .await
2211            })
2212    }
2213
2214    /// A vertical divider takes the height it is given, with a width of its own: a hairline
2215    /// down a row, not across it.
2216    #[day_macros::test(day_core)]
2217    fn vertical_divider_fills_height() -> Case {
2218        Case::new()
2219            .proves(kinds::DIVIDER)
2220            .page(|| {
2221                row((
2222                    label("Left"),
2223                    divider().vertical().id(day_core::id!(rule)),
2224                    label("Right"),
2225                ))
2226                .spacing(8.0)
2227                .height(120.0)
2228                .id(day_core::id!(row))
2229            })
2230            .drive(|d: Drive| async move {
2231                d.assert_visible("rule").await?;
2232                // The thickness is the toolkit's (a point or a few); the height is the row's.
2233                d.assert_frame(
2234                    "rule",
2235                    FrameExpect {
2236                        height: Some(120.0),
2237                        ..Default::default()
2238                    },
2239                )
2240                .await
2241            })
2242    }
2243
2244    /// A spacer takes the room between its neighbors.
2245    #[day_macros::test(day_core)]
2246    fn spacer_fills() -> Case {
2247        Case::new()
2248            .proves_modifier("width")
2249            .page(|| {
2250                row((
2251                    // The sized boxes, not the labels' own nodes.
2252                    label("A").width(50.0).wrapper_id(day_core::id!(first)),
2253                    spacer(),
2254                    label("B").width(50.0).wrapper_id(day_core::id!(last)),
2255                ))
2256                .width(300.0)
2257                .wrapper_id(day_core::id!(row))
2258            })
2259            .drive(|d: Drive| async move {
2260                d.assert_frame(
2261                    "last",
2262                    FrameExpect {
2263                        width: Some(50.0),
2264                        x: Some(250.0),
2265                        relative_to: Some("row".into()),
2266                        ..Default::default()
2267                    },
2268                )
2269                .await
2270            })
2271    }
2272
2273    /// A link opens its URL (recorded during a test run, so nothing opens).
2274    #[day_macros::test(day_core)]
2275    fn link_opens_url() -> Case {
2276        Case::new()
2277            .proves_duty("open_url")
2278            .page(|| link("daybrite.dev", "https://daybrite.dev/").id(day_core::id!(link)))
2279            .drive(|d: Drive| async move {
2280                d.assert_text("link", "daybrite.dev").await?;
2281                d.tap("link").await?;
2282                d.assert_opened_url("https://daybrite.dev/").await
2283            })
2284    }
2285}
2286
2287#[cfg(test)]
2288mod button_style_tests {
2289    use super::*;
2290    use day_spec::props::ButtonStyleSpec;
2291
2292    #[test]
2293    fn compact_keeps_a_plain_button_plain() {
2294        assert_eq!(
2295            button("Γ—").plain().compact().native_style,
2296            ButtonStyleSpec::Plain
2297        );
2298        assert_eq!(button("βˆ’").compact().native_style, ButtonStyleSpec::Compact);
2299        // The last style asked for still wins otherwise.
2300        assert_eq!(
2301            button("+").compact().plain().native_style,
2302            ButtonStyleSpec::Plain
2303        );
2304    }
2305}