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: any ink, so `SystemColor::Destructive` or a light/dark pair follows
114    /// the appearance.
115    pub fn colored(self, s: &str, color: impl Into<day_spec::Ink>) -> Self {
116        let base = self.base;
117        let color = color.into();
118        self.run(s, move |range| day_spec::TextRun {
119            range,
120            font: day_spec::FontSpec::from(base),
121            color: Some(color),
122            ..day_spec::TextRun::default()
123        })
124    }
125    /// Underlined with one solid line in the text color.
126    pub fn underline(self, s: &str) -> Self {
127        self.underline_styled(s, day_spec::Decoration::SINGLE)
128    }
129    /// Underlined with a line of your choosing: `Decoration::wavy()`, `double()` or
130    /// `dotted()`, with `.color(c)` for a line that is not the text color. A diagnostic mark is
131    /// `.underline_styled("unresolved", Decoration::wavy().color(red))`. A `DecorationStyle` converts.
132    pub fn underline_styled(self, s: &str, decoration: impl Into<day_spec::Decoration>) -> Self {
133        let base = self.base;
134        let decoration = decoration.into();
135        self.run(s, move |range| day_spec::TextRun {
136            range,
137            font: day_spec::FontSpec::from(base),
138            underline: Some(decoration),
139            ..day_spec::TextRun::default()
140        })
141    }
142    /// Lowercase letters drawn as small capitals
143    /// ([`FontSpec::small_caps`](day_spec::FontSpec::small_caps)).
144    pub fn small_caps(self, s: &str) -> Self {
145        let base = self.base;
146        self.run(s, move |range| {
147            day_spec::TextRun::font(
148                range,
149                day_spec::FontSpec {
150                    style: base,
151                    small_caps: true,
152                    ..Default::default()
153                },
154            )
155        })
156    }
157    /// Highlighted: a color painted behind the glyphs, for a search hit or a review mark.
158    ///
159    /// Sets the foreground too, through the same readable-on-a-fill rule `Button::tint` uses: a
160    /// highlight is usually a pale wash, and the label's own text color is chosen for the window's
161    /// background rather than for the swatch now sitting under it. On a dark theme that pairing
162    /// puts light text on pale amber, which is the one combination a highlight must not produce.
163    /// Use [`TextBuilder::run`] where an app wants to state both itself.
164    pub fn highlight(self, s: &str, color: impl Into<day_spec::Ink>) -> Self {
165        let base = self.base;
166        let color = color.into();
167        let on = color.map(day_spec::props::ButtonStyleSpec::on_tint);
168        self.run(s, move |range| day_spec::TextRun {
169            range,
170            font: day_spec::FontSpec::from(base),
171            background: Some(color),
172            color: Some(on),
173            ..day_spec::TextRun::default()
174        })
175    }
176    /// A relative size: `1.5` is half again the base style's, `0.8` smaller
177    /// ([`FontSpec::scale`](day_spec::FontSpec::scale)). Relative rather than a point size so the
178    /// phrase still tracks the reader's accessibility text-size setting.
179    pub fn sized(self, s: &str, scale: f64) -> Self {
180        let base = self.base;
181        self.run(s, move |range| day_spec::TextRun {
182            range,
183            font: day_spec::FontSpec::from(base).scaled(scale),
184            ..day_spec::TextRun::default()
185        })
186    }
187    /// Struck through with one solid line in the text color.
188    pub fn strikethrough(self, s: &str) -> Self {
189        self.strikethrough_styled(s, day_spec::Decoration::SINGLE)
190    }
191    /// Struck through with a line of your choosing, as [`TextBuilder::underline_styled`].
192    pub fn strikethrough_styled(
193        self,
194        s: &str,
195        decoration: impl Into<day_spec::Decoration>,
196    ) -> Self {
197        let base = self.base;
198        let decoration = decoration.into();
199        self.run(s, move |range| day_spec::TextRun {
200            range,
201            font: day_spec::FontSpec::from(base),
202            strikethrough: Some(decoration),
203            ..day_spec::TextRun::default()
204        })
205    }
206    /// A link run. A `#route` target navigates in-app, as with [`link`].
207    /// Rendering it is `Cap::TextRuns`; activating it is `Cap::TextLinks`, which
208    /// fewer backends have, so check before relying on the tap (docs/text-runs.md).
209    pub fn link(self, s: &str, target: &str) -> Self {
210        let base = self.base;
211        let target = target.to_string();
212        self.run(s, move |range| day_spec::TextRun {
213            range,
214            font: day_spec::FontSpec::from(base),
215            link: Some(target),
216            ..day_spec::TextRun::default()
217        })
218    }
219    /// The assembled text and its runs.
220    #[must_use]
221    pub fn build(self) -> (String, Vec<day_spec::TextRun>) {
222        (self.text, self.runs)
223    }
224}
225
226#[must_use]
227pub struct Label {
228    pub(crate) text: TextSource,
229    pub(crate) font: Font,
230    pub(crate) font_scale: Reactive<f64>,
231    pub(crate) max_text_scale: Option<f64>,
232    pub(crate) weight: Option<day_spec::FontWeight>,
233    pub(crate) italic: bool,
234    pub(crate) tabular: bool,
235    pub(crate) monospace: bool,
236    pub(crate) small_caps: bool,
237    pub(crate) oldstyle_figures: bool,
238    pub(crate) wraps: bool,
239    pub(crate) max_lines: Reactive<u32>,
240    pub(crate) truncation: Reactive<Truncation>,
241    pub(crate) letter_spacing: Reactive<f64>,
242    pub(crate) line_height: Reactive<f64>,
243    pub(crate) color: Option<Reactive<day_spec::Ink>>,
244    /// What the text means, for the color the platform gives it (docs/text.md).
245    pub(crate) role: day_spec::props::TextRole,
246    /// Styled spans over `text` (docs/text-runs.md); empty is an ordinary uniform label.
247    pub(crate) runs: Vec<day_spec::TextRun>,
248    /// Parse the text as inline markdown instead of taking it literally (docs/text-runs.md).
249    pub(crate) markdown: bool,
250    /// How wrapped lines sit within the label's own width (docs/text.md).
251    pub(crate) align: day_spec::props::TextAlign,
252    /// A line under the whole text.
253    pub(crate) underline: Option<day_spec::Decoration>,
254    /// A line through the whole text.
255    pub(crate) strikethrough: Option<day_spec::Decoration>,
256    /// The target the whole label links to ([`link`]).
257    pub(crate) link: Option<String>,
258    /// What a tapped link run does. `None` uses [`open_link`].
259    pub(crate) on_link: Option<LinkHandler>,
260    /// Told when the reader's selection changes; setting it makes the label selectable.
261    pub(crate) on_selection: Option<SelectionHandler>,
262}
263
264/// An app's handler for a tapped link run, shared because `Label` is cloned into its build.
265pub(crate) type LinkHandler = Rc<dyn Fn(&str)>;
266
267/// An app's handler for a selection change in a selectable label.
268pub(crate) type SelectionHandler = Rc<dyn Fn(&SelectedText)>;
269
270/// What the reader has selected in a label ([`Label::on_selection`]).
271#[derive(Clone, Debug, Default, PartialEq, Eq)]
272pub struct SelectedText {
273    /// The selected text, as the label displays it (Markdown markers already stripped).
274    /// Empty when the selection was cleared.
275    pub text: String,
276    /// The selection as a byte range into the displayed text. Empty when nothing is selected.
277    pub range: std::ops::Range<usize>,
278}
279
280impl SelectedText {
281    /// Whether nothing is selected.
282    #[must_use]
283    pub fn is_empty(&self) -> bool {
284        self.range.is_empty()
285    }
286}
287
288pub fn label<M>(text: impl IntoText<M>) -> Label {
289    Label::from_source(text.into_text())
290}
291
292impl Label {
293    /// A plain `Body` label over an already converted text source.
294    pub(crate) fn from_source(text: TextSource) -> Label {
295        Label {
296            text,
297            font: Font::Body,
298            font_scale: Reactive::Const(1.0),
299            max_text_scale: None,
300            weight: None,
301            italic: false,
302            tabular: false,
303            monospace: false,
304            small_caps: false,
305            oldstyle_figures: false,
306            wraps: true,
307            max_lines: Reactive::Const(0),
308            truncation: Reactive::Const(Truncation::Tail),
309            letter_spacing: Reactive::Const(0.0),
310            line_height: Reactive::Const(0.0),
311            color: None,
312            role: TextRole::default(),
313            runs: Vec::new(),
314            markdown: false,
315            align: day_spec::props::TextAlign::Leading,
316            underline: None,
317            strikethrough: None,
318            link: None,
319            on_link: None,
320            on_selection: None,
321        }
322    }
323}
324
325#[day_macros::builder(LabelBuilder)]
326impl Label {
327    /// Keep the text on one line and end it with an ellipsis when it does not fit
328    /// ([`Label::truncation`] says where). Constrain the width through the enclosing layout.
329    pub fn single_line(mut self) -> Self {
330        self.wraps = false;
331        self
332    }
333    /// Show at most this many lines, ending the last one with an ellipsis when text is left
334    /// over. Zero means unlimited. The label measures no taller than the limit, on every
335    /// toolkit. A constant, a `Signal<u32>` or a closure: a "Show more" toggle is
336    /// `.max_lines(move || if expanded.get() { 0 } else { 3 })`.
337    pub fn max_lines<M>(mut self, lines: impl IntoReactive<u32, M>) -> Self {
338        self.max_lines = lines.into_reactive();
339        self
340    }
341    /// Where the ellipsis goes when the text does not fit: `Truncation::Tail` (the default),
342    /// `Head`, or `Middle` for a file path or an identifier whose two ends both matter.
343    /// Applies to a label held to one line or to [`Label::max_lines`]; `Head` and `Middle`
344    /// are guaranteed on one line (docs/text.md "Truncation").
345    pub fn truncation<M>(mut self, mode: impl IntoReactive<Truncation, M>) -> Self {
346        self.truncation = mode.into_reactive();
347        self
348    }
349    /// Extra space after each character, in ems: `0.05` adds 5% of the font size, a negative
350    /// value tightens. Relative, so the tracking follows the reader's text size.
351    pub fn letter_spacing<M>(mut self, ems: impl IntoReactive<f64, M>) -> Self {
352        self.letter_spacing = ems.into_reactive();
353        self
354    }
355    /// The distance between baselines as a multiple of the font size: `1.5` for airy body
356    /// text, `1.0` for tightly set display type. The font's own line height (about `1.2`)
357    /// applies until this is set, and again for a value of zero.
358    pub fn line_height<M>(mut self, multiple: impl IntoReactive<f64, M>) -> Self {
359        self.line_height = multiple.into_reactive();
360        self
361    }
362    /// The semantic text style (`Font::Title`, `Font::Footnote`, …) or a custom `Font::System(pt)`.
363    /// Backends render it with the platform's native style + accessibility text scaling.
364    pub fn font(mut self, f: Font) -> Self {
365        self.font = f;
366        self
367    }
368    /// Scale the resolved native font, preserving its semantic style and accessibility size.
369    /// A constant, a signal or a closure. Applies to the label's base font; explicit styled
370    /// runs retain their own descriptors. A nonpositive or nonfinite factor reads as 1.0.
371    pub fn font_scale<M>(mut self, scale: impl IntoReactive<f64, M>) -> Self {
372        self.font_scale = scale.into_reactive();
373        self
374    }
375    /// Stop this label growing with the reader's text-size setting past `cap` times its
376    /// default size: `1.3` lets a tab label or a badge grow 30% and no further, `1.0` opts
377    /// it out of growth. Text smaller than the default is never affected. Use it only where
378    /// the layout cannot give the text more room; body text should scale without a cap
379    /// (docs/text.md "Text scale").
380    pub fn max_text_scale(mut self, cap: f64) -> Self {
381        self.max_text_scale = (cap.is_finite() && cap > 0.0).then_some(cap);
382        self
383    }
384    /// Override the font weight (e.g. `FontWeight::Semibold`). See also [`Label::bold`].
385    pub fn weight(mut self, w: day_spec::FontWeight) -> Self {
386        self.weight = Some(w);
387        self
388    }
389    /// Shorthand for `.weight(FontWeight::Bold)`.
390    pub fn bold(self) -> Self {
391        self.weight(day_spec::FontWeight::Bold)
392    }
393    /// De-emphasize the text: the platform's secondary label color, whatever that is here
394    /// (`secondaryLabelColor` on Apple, `?android:textColorSecondary`, a dim label on GTK).
395    ///
396    /// Semantic rather than a literal grey, for the reason a literal grey cannot solve: one that
397    /// reads well on white is wrong on black, so an app that hard-codes it gets a label that is
398    /// either washed out or nearly invisible in the other appearance. This is what an empty
399    /// state's "nothing selected", a hint under a field, or a caption should wear.
400    pub fn secondary(mut self) -> Self {
401        self.role = day_spec::props::TextRole::Secondary;
402        self
403    }
404    /// Render the text italic (slanted).
405    pub fn italic(mut self) -> Self {
406        self.italic = true;
407        self
408    }
409    /// Ask for tabular (monospaced) figures, so a changing number stops changing width.
410    ///
411    /// Pair it with [`Decorate::reserving`] for a readout beside a slider: reserving stops the box
412    /// resizing when the digit count changes, tabular stops the digits shifting inside it because
413    /// `1` is narrower than `8`. See [`day_spec::FontSpec::tabular`].
414    pub fn tabular(mut self) -> Self {
415        self.tabular = true;
416        self
417    }
418    /// Ask for the platform's monospaced face at this style's size, which is what inline code
419    /// wants.
420    pub fn monospace(mut self) -> Self {
421        self.monospace = true;
422        self
423    }
424    /// Draw lowercase letters as small capitals, for an eyebrow heading or an acronym in
425    /// running text. A face without small capitals draws its ordinary lowercase. See
426    /// [`day_spec::FontSpec::small_caps`].
427    pub fn small_caps(mut self) -> Self {
428        self.small_caps = true;
429        self
430    }
431    /// Ask for oldstyle figures, digits that sit in running text like lowercase letters. A
432    /// face without them draws its ordinary figures. Combines with [`Label::tabular`].
433    pub fn oldstyle_figures(mut self) -> Self {
434        self.oldstyle_figures = true;
435        self
436    }
437    /// Underline the whole text. `Decoration::SINGLE` is the plain line; `Decoration::wavy()`,
438    /// `double()` and `dotted()` draw the other styles, and `.color(c)` gives the line a
439    /// color of its own: `.underline(Decoration::wavy().color(Color::hex(0xD0021B)))`. A
440    /// `DecorationStyle` converts, so `.underline(DecorationStyle::Double)` works too. For
441    /// part of the text, use [`TextBuilder::underline_styled`].
442    pub fn underline(mut self, decoration: impl Into<day_spec::Decoration>) -> Self {
443        self.underline = Some(decoration.into());
444        self
445    }
446    /// Strike the whole text through, with the same styles and color as [`Label::underline`].
447    pub fn strikethrough(mut self, decoration: impl Into<day_spec::Decoration>) -> Self {
448        self.strikethrough = Some(decoration.into());
449        self
450    }
451    /// Style spans within this label's text (docs/text-runs.md): one wrapping paragraph with
452    /// emphasis, color, code or a link inside it, rather than several labels in a row.
453    ///
454    /// Ranges are byte offsets into the label's text, ascending and non-overlapping; text not
455    /// covered by a run draws with the label's own font. Invalid runs are rejected at build
456    /// time with a warning and the label renders plain, because the alternative is eight
457    /// different wrong renderings (and a panic on the backends that slice `str`).
458    ///
459    /// [`TextBuilder`] is the ergonomic way in; this is the direct one.
460    pub fn runs(mut self, runs: Vec<day_spec::TextRun>) -> Self {
461        self.runs = runs;
462        self
463    }
464    /// Take both the text and its runs from a [`TextBuilder`], replacing whatever text the label
465    /// was built with. This is the intended entry point: the builder guarantees the ranges match
466    /// the string, which is the invariant hand-written runs get wrong.
467    pub fn runs_from(mut self, b: TextBuilder) -> Self {
468        let (text, runs) = b.build();
469        self.text = TextSource::Static(text);
470        self.runs = runs;
471        self
472    }
473    /// Center (or trail, or justify) this label's lines within its own width, for the short
474    /// wrapped block a welcome screen or an empty state uses. Only observable on a label that
475    /// wraps, since a single line already fills its box.
476    pub fn align(mut self, align: day_spec::props::TextAlign) -> Self {
477        self.align = align;
478        self
479    }
480    /// Read the label's text as inline Markdown (docs/text-runs.md): `**bold**`, `*italic*`,
481    /// `` `code` ``, `~~strike~~` and `[text](url)` become styled runs, and the markers themselves
482    /// are stripped.
483    ///
484    /// The parse happens at run time, on every change, so it works on a translated string chosen
485    /// from the locale bundle, a value off the network, or text a user is typing, none of which a
486    /// compile-time macro can see. The cost is a parse per update of a string that is a label's
487    /// worth of text.
488    ///
489    /// ```ignore
490    /// label(res::str::release_note()).markdown()
491    /// label(move || draft.get()).markdown()   // live as the user types
492    /// ```
493    ///
494    /// Unrecognized markup stays literal, so a half-typed `**` reads as two asterisks rather than
495    /// flickering. Block constructs (headings, lists, quotes, code blocks) are not parsed
496    /// here: a label is one paragraph. [`markdown`](crate::markdown()) is the piece for a
497    /// document.
498    pub fn markdown(mut self) -> Self {
499        self.markdown = true;
500        self
501    }
502    /// Handle a tapped link run yourself instead of opening its target.
503    ///
504    /// Without this, a `#route` target navigates in-app and other targets open in the platform's
505    /// default handler, the same as the [`link`] piece. This handler overrides both behaviors;
506    /// call [`open_link`] to delegate targets you do not handle back to the default.
507    ///
508    /// Activation is `Cap::TextLinks`, which is narrower than run rendering: on a backend
509    /// without it the link still draws, and nothing calls this (docs/text-runs.md).
510    pub fn on_link(mut self, f: impl Fn(&str) + 'static) -> Self {
511        self.on_link = Some(Rc::new(f));
512        self
513    }
514    /// Make the label selectable and hear about the reader's selection as it changes: the
515    /// selected text and its byte range in the displayed text, empty when the selection is
516    /// cleared. For a "Quote selection" button or a lookup panel beside the text.
517    ///
518    /// `capability(Cap::LabelSelection)` says whether this toolkit reports selections. Where
519    /// it does not, the label is still selectable and the callback never runs.
520    pub fn on_selection(mut self, f: impl Fn(&SelectedText) + 'static) -> Self {
521        self.on_selection = Some(Rc::new(f));
522        self
523    }
524    /// The text color: any ink (a [`Color`](day_spec::Color), a
525    /// [`SystemColor`](day_spec::SystemColor), `Ink::adaptive(light, dark)`), or a signal or
526    /// closure of one. An ink follows the appearance by itself; a reactive source recolors the
527    /// native label when it changes.
528    pub fn color<M>(mut self, c: impl IntoReactive<day_spec::Ink, M>) -> Self {
529        self.color = Some(c.into_reactive());
530        self
531    }
532    /// Apply a named [`TextPreset`](crate::TextPreset): the font, weight, scale, emphasis,
533    /// spacing and color an app defined once (`label(t).preset(&CAPTION)`).
534    pub fn preset(mut self, preset: &crate::TextPreset) -> Self {
535        self.font = preset.font;
536        self.font_scale = Reactive::Const(preset.font_scale);
537        if preset.weight.is_some() {
538            self.weight = preset.weight;
539        }
540        self.italic |= preset.italic;
541        self.tabular |= preset.tabular;
542        self.monospace |= preset.monospace;
543        self.small_caps |= preset.small_caps;
544        if preset.secondary {
545            self.role = day_spec::props::TextRole::Secondary;
546        }
547        if preset.single_line {
548            self.wraps = false;
549        }
550        if let Some(c) = preset.color {
551            self.color = Some(Reactive::Const(c));
552        }
553        if let Some(ems) = preset.letter_spacing {
554            self.letter_spacing = Reactive::Const(ems);
555        }
556        if let Some(multiple) = preset.line_height {
557            self.line_height = Reactive::Const(multiple);
558        }
559        if preset.max_text_scale.is_some() {
560            self.max_text_scale = preset.max_text_scale;
561        }
562        self
563    }
564}
565
566/// What a label's build keeps for its bindings: the styles that cover the whole text, and the
567/// text it currently shows.
568struct LabelState {
569    markdown: bool,
570    font: Font,
571    /// The label's resolved base font, which whole-text runs are drawn in.
572    spec: std::cell::Cell<day_spec::FontSpec>,
573    color: Option<day_spec::Ink>,
574    underline: Option<day_spec::Decoration>,
575    strikethrough: Option<day_spec::Decoration>,
576    link: Option<String>,
577    /// The source text last given, before Markdown markers were stripped.
578    source: RefCell<String>,
579    /// The text the label displays, which a selection's byte range addresses.
580    displayed: RefCell<String>,
581}
582
583impl LabelState {
584    /// Does any style cover the whole text, so that text always travels with runs?
585    fn covers(&self) -> bool {
586        self.link.is_some() || self.underline.is_some() || self.strikethrough.is_some()
587    }
588
589    /// The text to display for `source` and the runs over it. `fixed` are the label's own
590    /// `.runs(…)`, which address the text it was built with.
591    fn shape(&self, source: &str, fixed: &[day_spec::TextRun]) -> (String, Vec<day_spec::TextRun>) {
592        let (text, runs) = if self.markdown {
593            day_spec::markdown::parse(source, self.font)
594        } else {
595            (source.to_owned(), fixed.to_vec())
596        };
597        // Validate once here rather than in eight backends: an overlapping or mid-character
598        // range renders differently wrong on each, and panics on the ones that slice `str`.
599        let runs = match day_spec::runs_are_valid(&text, &runs) {
600            Ok(()) => runs,
601            Err(why) => {
602                log::warn!("label runs ignored: {why}; the text renders unstyled");
603                Vec::new()
604            }
605        };
606        let runs = if self.covers() {
607            self.cover(&text, runs)
608        } else {
609            runs
610        };
611        source.clone_into(&mut self.source.borrow_mut());
612        text.clone_into(&mut self.displayed.borrow_mut());
613        (text, runs)
614    }
615
616    /// Spread the whole-text styles over `text`: runs that exist take them where they say
617    /// nothing of their own, and the gaps between runs become runs in the label's font.
618    fn cover(&self, text: &str, runs: Vec<day_spec::TextRun>) -> Vec<day_spec::TextRun> {
619        let fill = |range: std::ops::Range<usize>| day_spec::TextRun {
620            range,
621            font: self.spec.get(),
622            color: self.color,
623            underline: self.underline,
624            strikethrough: self.strikethrough,
625            link: self.link.clone(),
626            ..day_spec::TextRun::default()
627        };
628        let mut out = Vec::with_capacity(runs.len() * 2 + 1);
629        let mut at = 0usize;
630        for mut run in runs {
631            if run.range.start > at {
632                out.push(fill(at..run.range.start));
633            }
634            at = run.range.end;
635            run.underline = run.underline.or(self.underline);
636            run.strikethrough = run.strikethrough.or(self.strikethrough);
637            if run.link.is_none() {
638                run.link.clone_from(&self.link);
639            }
640            out.push(run);
641        }
642        if at < text.len() {
643            out.push(fill(at..text.len()));
644        }
645        out
646    }
647}
648
649/// The scale a label's font takes: its own factor, held under its text-scale cap. Both reads
650/// are tracked, so a binding around this follows a reactive factor and the system setting.
651fn label_font_scale(scale: &Reactive<f64>, font: Font, cap: Option<f64>) -> f64 {
652    let own = scale.get();
653    let own = if own.is_finite() && own > 0.0 {
654        own
655    } else {
656        1.0
657    };
658    match cap {
659        Some(cap) => {
660            let system = day_core::text_scale_of(font);
661            if system > cap {
662                own * cap / system
663            } else {
664                own
665            }
666        }
667        None => own,
668    }
669}
670
671impl Piece for Label {
672    fn build(mut self, cx: &mut BuildCx) -> RNode {
673        // A link on a toolkit without activatable link runs is accent text with a tap handler
674        // and a button role, which every toolkit can do.
675        if self.link.is_some()
676            && day_core::capability(day_spec::Cap::TextLinks) != day_spec::Support::Native
677            && let Some(url) = self.link.take()
678        {
679            if self.color.is_none() {
680                self.color = Some(Reactive::Const(LINK_INK));
681            }
682            let handler = self.on_link.clone();
683            return self
684                .on_tap(move || match &handler {
685                    Some(f) => f(&url),
686                    None => open_link(&url),
687                })
688                .a11y(|b| b.role(Role::Button))
689                .build(cx);
690        }
691        let scale = label_font_scale_untracked(&self.font_scale, self.font, self.max_text_scale);
692        let spec = |scale: f64| day_spec::FontSpec {
693            style: self.font,
694            scale,
695            weight: self.weight,
696            italic: self.italic,
697            tabular: self.tabular,
698            monospace: self.monospace,
699            small_caps: self.small_caps,
700            oldstyle_figures: self.oldstyle_figures,
701        };
702        let color = self
703            .color
704            .as_ref()
705            .map(super::canvas::Reactive::get_untracked);
706        let state = Rc::new(LabelState {
707            markdown: self.markdown,
708            font: self.font,
709            spec: std::cell::Cell::new(spec(scale)),
710            color,
711            underline: self.underline,
712            strikethrough: self.strikethrough,
713            link: self.link.clone(),
714            source: RefCell::new(String::new()),
715            displayed: RefCell::new(String::new()),
716        });
717        let (initial, runs) = state.shape(&self.text.initial(), &self.runs);
718        let paragraph = {
719            let (max_lines, truncation) = (self.max_lines.clone(), self.truncation.clone());
720            let (letter_spacing, line_height) =
721                (self.letter_spacing.clone(), self.line_height.clone());
722            move || LabelParagraph {
723                max_lines: max_lines.get(),
724                truncation: truncation.get(),
725                letter_spacing: letter_spacing.get(),
726                line_height: line_height.get(),
727            }
728        };
729        let seed = day_reactive::untrack(&paragraph);
730        let node = cx.leaf(
731            kinds::LABEL,
732            &LabelProps {
733                align: self.align,
734                text: initial,
735                font: state.spec.get(),
736                color,
737                role: self.role,
738                wraps: self.wraps,
739                max_lines: seed.max_lines,
740                truncation: seed.truncation,
741                letter_spacing: seed.letter_spacing,
742                line_height: seed.line_height,
743                reports_selection: self.on_selection.is_some(),
744                runs,
745            },
746            Flex::default(),
747        );
748        // A label that can carry link runs listens for their activation. Markdown labels qualify
749        // whatever they currently hold, since a later parse may produce a link that this one did
750        // not. Labels without any prospect of a link register nothing.
751        let could_link = self.markdown
752            || self.link.is_some()
753            || self.on_link.is_some()
754            || self.runs.iter().any(|r| r.link.is_some());
755        if could_link {
756            let handler = self.on_link.clone();
757            let whole = self.link.clone();
758            cx.on(node, move |ev| match ev {
759                Event::LinkActivated(url) => match &handler {
760                    Some(f) => f(url),
761                    None => open_link(url),
762                },
763                // A synthesized tap on a whole-label link follows the same policy; the native
764                // activation arrives as `LinkActivated`.
765                Event::Tap(_) => {
766                    if let Some(url) = &whole {
767                        match &handler {
768                            Some(f) => f(url),
769                            None => open_link(url),
770                        }
771                    }
772                }
773                _ => {}
774            });
775        }
776        // Reporting a selection needs a selection: the label becomes selectable, and the byte
777        // range the toolkit reports is read against the text on display.
778        if let Some(handler) = self.on_selection.clone() {
779            with_tree(|t| t.set_node_selectable(node, true));
780            let state = state.clone();
781            cx.on(node, move |ev| {
782                if let Event::TextSelected { start, end } = ev {
783                    let shown = state.displayed.borrow();
784                    let range = (*start).min(shown.len())..(*end).min(shown.len());
785                    let text = shown.get(range.clone()).unwrap_or_default().to_owned();
786                    drop(shown);
787                    let range = if text.is_empty() { 0..0 } else { range };
788                    handler(&SelectedText { text, range });
789                }
790            });
791        }
792        // Text and runs travel together whenever the label has any: a range only means
793        // something against the string it was computed from.
794        let styled = self.markdown || state.covers();
795        {
796            let state = state.clone();
797            self.text.bind_to(
798                node,
799                move |t| {
800                    let (text, runs) = state.shape(&t, &[]);
801                    if styled {
802                        Box::new(LabelPatch::Runs(text, runs))
803                    } else {
804                        Box::new(LabelPatch::Text(text))
805                    }
806                },
807                true,
808            );
809        }
810        // The font follows a reactive scale and, under a cap, the system text size.
811        if matches!(self.font_scale, Reactive::Dyn(_)) || self.max_text_scale.is_some() {
812            let (font_scale, font, cap) = (self.font_scale.clone(), self.font, self.max_text_scale);
813            let state = state.clone();
814            // Seeded with the scale the label was realized at, so only a change patches.
815            bind_seeded(
816                scale,
817                move || label_font_scale(&font_scale, font, cap),
818                move |scale: &f64| {
819                    let mut next = state.spec.get();
820                    next.scale = *scale;
821                    state.spec.set(next);
822                    with_tree(|t| t.patch(node, Box::new(LabelPatch::Font(next)), true));
823                    // Whole-text runs are drawn in the label's font, so they follow it.
824                    if state.covers() {
825                        let source = state.source.borrow().clone();
826                        let (text, runs) = state.shape(&source, &[]);
827                        with_tree(|t| t.patch(node, Box::new(LabelPatch::Runs(text, runs)), true));
828                    }
829                },
830            );
831        }
832        // The paragraph attributes follow their sources as one patch.
833        let reactive_paragraph = matches!(self.max_lines, Reactive::Dyn(_))
834            || matches!(self.truncation, Reactive::Dyn(_))
835            || matches!(self.letter_spacing, Reactive::Dyn(_))
836            || matches!(self.line_height, Reactive::Dyn(_));
837        if reactive_paragraph {
838            bind_seeded(seed, paragraph, move |p: &LabelParagraph| {
839                with_tree(|t| t.patch(node, Box::new(LabelPatch::Paragraph(*p)), true));
840            });
841        }
842        // A reactive color recolors in place; a constant was applied once at realize.
843        if let Some(Reactive::Dyn(f)) = self.color {
844            bind(
845                move || f(),
846                move |c: &day_spec::Ink| {
847                    with_tree(|t| t.patch(node, Box::new(LabelPatch::Color(Some(*c))), false));
848                },
849            );
850        }
851        node
852    }
853}
854
855/// [`label_font_scale`] without subscribing, for the value a label is realized with.
856fn label_font_scale_untracked(scale: &Reactive<f64>, font: Font, cap: Option<f64>) -> f64 {
857    day_reactive::untrack(|| label_font_scale(scale, font, cap))
858}
859
860/// The platform's link color a [`link`] takes on a toolkit with no native link runs. Override
861/// per link with [`Label::color`] to match an app's accent.
862const LINK_INK: day_spec::Ink = day_spec::Ink::system(day_spec::SystemColor::Link);
863
864/// Activate a link target, using the same policy as [`link`] and markdown labels.
865///
866/// A leading `#` denotes an in-app route: `#settings` calls [`navigate`](crate::navigate) with
867/// `settings`. Route paths, percent escapes, and query parameters use the navigation system's
868/// existing rules; `#` alone navigates to the empty route (pop to root). An unknown route is
869/// ignored, never handed to an external application. All other targets go to
870/// [`day_core::open_url`] unchanged, including URLs with fragments such as `https://daybrite.dev/#docs`.
871///
872/// Use this from [`Label::on_link`] to keep the default behavior for targets your handler does
873/// not override.
874pub fn open_link(target: &str) {
875    if let Some(route) = target.strip_prefix('#') {
876        let _ = day_core::navigate(route);
877    } else {
878        day_core::open_url(target);
879    }
880}
881
882/// A label whose whole text is a link: it navigates to a `#route`, or opens a URL in the
883/// platform's default handler (the system browser for `http`/`https`, the mail client for
884/// `mailto:`, and so on).
885///
886/// The result is a [`Label`], so every label builder applies: `.font`, `.bold`, `.color`
887/// (reactive), `.max_lines`, `.truncation`, `.underline`, `.on_link` to handle the tap
888/// yourself. Where the toolkit has activatable link runs (`Cap::TextLinks`) the text is a
889/// native link run, with the platform's link color, hover and pressed states, keyboard focus
890/// and accessibility. Elsewhere it is accent-colored text with a tap handler and a button
891/// role.
892///
893/// ```ignore
894/// link(res::str::project_site(), "https://daybrite.dev")
895/// link(res::str::settings(), "#settings").bold()
896/// link(res::str::email_us(), "mailto:hi@example.com").font(Font::Footnote)
897/// ```
898pub fn link<M>(text: impl IntoText<M>, url: impl Into<String>) -> Label {
899    let mut label = label(text);
900    label.link = Some(url.into());
901    label
902}
903
904#[must_use]
905pub struct Button {
906    title: TextSource,
907    icon: Reactive<Option<day_spec::Icon>>,
908    icon_only: bool,
909    action: Option<Rc<dyn Fn()>>,
910    native_style: day_spec::props::ButtonStyleSpec,
911    /// A reactive tint, kept apart from `native_style` so the color can follow a signal. Set by
912    /// [`Button::tint`]; it wins over `bordered`/`prominent` because it is the more specific ask.
913    tint: Option<Reactive<day_spec::Ink>>,
914    enabled: Reactive<bool>,
915    selected: Reactive<bool>,
916}
917
918pub fn button<M>(title: impl IntoText<M>) -> Button {
919    Button {
920        title: title.into_text(),
921        icon: Reactive::Const(None),
922        icon_only: false,
923        action: None,
924        native_style: day_spec::props::ButtonStyleSpec::Automatic,
925        tint: None,
926        enabled: true.into_reactive(),
927        selected: false.into_reactive(),
928    }
929}
930
931#[day_macros::builder(ButtonBuilder)]
932impl Button {
933    /// Show a platform symbol. A signal or closure updates it without replacing the button.
934    pub fn icon<M>(mut self, symbol: impl IntoReactive<day_spec::Symbol, M>) -> Self {
935        let symbol = symbol.into_reactive();
936        self.icon = match symbol {
937            Reactive::Const(s) => Reactive::Const(Some(day_spec::Icon::Symbol(s))),
938            Reactive::Dyn(f) => Reactive::Dyn(Rc::new(move || Some(day_spec::Icon::Symbol(f())))),
939        };
940        self
941    }
942
943    /// Show a bundled image or vector alongside the label.
944    pub fn image(mut self, name: impl Into<day_spec::ImageName>) -> Self {
945        self.icon = Reactive::Const(Some(day_spec::Icon::Image(name.into().as_str().to_owned())));
946        self
947    }
948
949    /// Hide the visible label when an icon is available; retain it for accessibility and help.
950    pub fn icon_only(mut self) -> Self {
951        self.icon_only = true;
952        self
953    }
954
955    /// Handle native button activation by pointer, keyboard, or accessibility action.
956    /// Disabled buttons do not invoke this callback.
957    ///
958    /// Use this instead of [`Decorate::on_tap`]. A tap decorator adds a separate gesture
959    /// recognizer that can delay pressed feedback and bypass native control behavior.
960    /// Day logs a warning when a tap gesture is attached to a native button.
961    pub fn action(mut self, f: impl Fn() + 'static) -> Self {
962        self.action = Some(Rc::new(f));
963        self
964    }
965
966    /// Ask for a visually CONTAINED native button on toolkits whose stock look is borderless
967    /// (iOS's plain system button reads as a link); a no-op where buttons are already bordered.
968    pub fn bordered(mut self) -> Self {
969        self.native_style = day_spec::props::ButtonStyleSpec::Bordered;
970        self
971    }
972
973    /// Whether the button is interactive (default `true`; `false` = disabled/grayed by the native
974    /// control). Reactive, so it can follow app state, e.g. `.enabled(move || !busy.get())` to
975    /// lock a control while a long operation runs.
976    ///
977    /// This drives the platform's own disabled rendering through `ButtonPatch::Enabled`; it is not
978    /// a painted imitation, and a disabled button stops delivering `Event::Pressed` at the source.
979    pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
980        self.enabled = v.into_reactive();
981        self
982    }
983
984    /// The platform's accent-filled / default-action button (iOS bordered-prominent, macOS
985    /// return-key blue, GTK suggested-action, XAML accent style). Use for the one primary
986    /// action of a view.
987    pub fn prominent(mut self) -> Self {
988        self.native_style = day_spec::props::ButtonStyleSpec::Prominent;
989        self
990    }
991
992    /// A filled button in a color of your choosing, still drawn by the native control.
993    ///
994    /// The platform keeps everything that makes a button a button: its pressed and hover
995    /// rendering, its focus ring, its disabled look, its accessibility role, and keyboard
996    /// activation. Only the fill is yours. The label color is chosen for contrast against the
997    /// fill, so a pale tint gets dark text and a saturated one white.
998    ///
999    /// Reactive, so the color can follow app state: `.tint(move || if recording { RUST } else
1000    /// { SKY })` recolors in place rather than rebuilding the button.
1001    ///
1002    /// A backend that cannot recolor its button ignores the tint and draws its ordinary button
1003    /// (docs/buttons.md), because a plain button on one platform is a far smaller loss than a
1004    /// colored rectangle that is no longer a button.
1005    pub fn tint<M>(mut self, color: impl IntoReactive<day_spec::Ink, M>) -> Self {
1006        self.tint = Some(color.into_reactive());
1007        self
1008    }
1009
1010    /// A button no wider than its title: a stepper's "−" and "+", a chip's "×". Drops the
1011    /// minimum width and wide insets of toolkits that have them (Material); a no-op where the
1012    /// stock button already hugs its title. A [`plain`](Self::plain) button stays plain: it
1013    /// already hugs its title everywhere, and Material's compact button is a filled one.
1014    pub fn compact(mut self) -> Self {
1015        if self.native_style != day_spec::props::ButtonStyleSpec::Plain {
1016            self.native_style = day_spec::props::ButtonStyleSpec::Compact;
1017        }
1018        self
1019    }
1020
1021    /// Borderless native action button for toolbars and list-row accessories.
1022    /// Preserves native interaction, focus, disabled rendering, and accessibility.
1023    pub fn plain(mut self) -> Self {
1024        self.native_style = day_spec::props::ButtonStyleSpec::Plain;
1025        self
1026    }
1027
1028    /// Mark this button as the current choice among its peers: a document tab, one view of a
1029    /// switcher. The platform draws its own checked or selected look (an `NSButton`'s on state,
1030    /// `UIButton.isSelected`, GTK's `:checked`, a checked `QPushButton`, a checked
1031    /// `MaterialButton`, `aria-pressed` on the web) and announces it as selected, while the
1032    /// button stays enabled, focusable and activatable, which a disabled stand-in is not.
1033    ///
1034    /// Reactive, so it follows the selection: `.selected(move || current.get() == key)`. A press
1035    /// never toggles the state natively; the app's handler decides, and the next value of the
1036    /// closure is what the control shows.
1037    pub fn selected<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1038        self.selected = v.into_reactive();
1039        self
1040    }
1041}
1042
1043impl Piece for Button {
1044    fn build(self, cx: &mut BuildCx) -> RNode {
1045        let initial = self.title.initial();
1046        // A tint is the most specific style ask, so it wins over bordered/prominent.
1047        let style = match &self.tint {
1048            Some(c) => day_spec::props::ButtonStyleSpec::Tinted(c.get_untracked()),
1049            None => self.native_style,
1050        };
1051        let node = cx.leaf(
1052            kinds::BUTTON,
1053            &ButtonProps {
1054                title: initial.clone(),
1055                icon: self.icon.get_untracked(),
1056                icon_only: self.icon_only,
1057                enabled: self.enabled.get_untracked(),
1058                style,
1059                selected: self.selected.get_untracked(),
1060            },
1061            Flex::default(),
1062        );
1063        // A reactive `selected` patches on change, like `enabled` below.
1064        if let selected @ Reactive::Dyn(_) = self.selected {
1065            bind(
1066                move || selected.get(),
1067                move |on: &bool| {
1068                    with_tree(|t| t.patch(node, Box::new(ButtonPatch::Selected(*on)), false));
1069                },
1070            );
1071        }
1072        // A reactive tint recolors in place; a constant one was applied at realize above.
1073        if let Some(c @ Reactive::Dyn(_)) = self.tint.clone() {
1074            bind(
1075                move || c.get(),
1076                move |col: &day_spec::Ink| {
1077                    with_tree(|t| {
1078                        t.patch(
1079                            node,
1080                            Box::new(ButtonPatch::Style(
1081                                day_spec::props::ButtonStyleSpec::Tinted(*col),
1082                            )),
1083                            false,
1084                        );
1085                    });
1086                },
1087            );
1088        }
1089        // A reactive `enabled` patches on change; a constant is applied once at realize, the same
1090        // shape `Toggle` uses.
1091        let enabled = self.enabled;
1092        let enabled_gate = enabled.clone();
1093        if let Reactive::Dyn(_) = &enabled {
1094            bind(
1095                move || enabled.get(),
1096                move |e: &bool| {
1097                    with_tree(|t| t.patch(node, Box::new(ButtonPatch::Enabled(*e)), false));
1098                },
1099            );
1100        }
1101        if let Some(action) = self.action {
1102            // Gate the action on `enabled` as well as telling the native control. A real touch on a
1103            // disabled UIButton/MaterialButton never produces `Pressed`, so this is belt-and-braces
1104            // for users, but an event delivered by another route (a dayscript `tap`, which
1105            // dispatches to the node rather than simulating a touch) would otherwise fire an action
1106            // the user cannot reach. `.enabled(false)` should mean "cannot fire", not "looks gray".
1107            let gate = enabled_gate;
1108            cx.on(node, move |ev| {
1109                if matches!(ev, Event::Pressed) && gate.get() {
1110                    action();
1111                }
1112            });
1113        }
1114        if matches!(&self.icon, Reactive::Const(None)) {
1115            // Preserve the existing patch contract for plain buttons and external toolkits.
1116            self.title
1117                .bind_to(node, |t| Box::new(ButtonPatch::Title(t)), true);
1118        } else {
1119            let icon = self.icon;
1120            let icon_only = self.icon_only;
1121            let seed = day_spec::props::ButtonContent {
1122                title: initial,
1123                icon: icon.get_untracked(),
1124                icon_only,
1125            };
1126            let title = self.title;
1127            bind_seeded(
1128                seed,
1129                move || day_spec::props::ButtonContent {
1130                    title: title.resolve(),
1131                    icon: icon.get(),
1132                    icon_only,
1133                },
1134                move |content: &day_spec::props::ButtonContent| {
1135                    with_tree(|t| {
1136                        t.patch(node, Box::new(ButtonPatch::Content(content.clone())), true);
1137                    });
1138                },
1139            );
1140        }
1141        node
1142    }
1143}
1144
1145#[must_use]
1146pub struct Toggle<S: Binding<bool>> {
1147    value: S,
1148    enabled: Reactive<bool>,
1149}
1150
1151pub fn toggle<S: Binding<bool>>(value: S) -> Toggle<S> {
1152    Toggle {
1153        value,
1154        enabled: true.into_reactive(),
1155    }
1156}
1157
1158#[day_macros::builder(ToggleBuilder)]
1159impl<S: Binding<bool>> Toggle<S> {
1160    /// Whether the toggle is interactive (default `true`; `false` = disabled/grayed). Reactive,
1161    /// e.g. `.enabled(capability(Cap::TextSpellCheck) == Support::Native)` to gray it out where a
1162    /// backend can't honor the thing it controls.
1163    pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1164        self.enabled = v.into_reactive();
1165        self
1166    }
1167}
1168
1169impl<S: Binding<bool>> Piece for Toggle<S> {
1170    fn build(self, cx: &mut BuildCx) -> RNode {
1171        let initial = self.value.peek();
1172        let node = cx.leaf(
1173            kinds::TOGGLE,
1174            &ToggleProps {
1175                on: initial,
1176                enabled: self.enabled.get_untracked(),
1177            },
1178            Flex::default(),
1179        );
1180        let v = self.value.clone();
1181        bind_seeded(
1182            initial,
1183            move || v.read(),
1184            move |on: &bool| {
1185                with_tree(|t| t.patch(node, Box::new(TogglePatch::On(*on)), false));
1186            },
1187        );
1188        // A reactive `enabled` patches on change; a constant is applied once at realize.
1189        let enabled = self.enabled;
1190        if let Reactive::Dyn(_) = &enabled {
1191            bind(
1192                move || enabled.get(),
1193                move |e: &bool| {
1194                    with_tree(|t| t.patch(node, Box::new(TogglePatch::Enabled(*e)), false));
1195                },
1196            );
1197        }
1198        let v = self.value;
1199        cx.on(node, move |ev| {
1200            // A report of the value the binding already holds changes nothing: it is the
1201            // control echoing the app's own write (GTK's `notify::active`, Qt's `toggled` and
1202            // Android's checked listener all fire for a programmatic set), the second layer of
1203            // echo suppression (DESIGN.md §4.4). Written anyway, it would notify every watcher
1204            // of the binding a second time for one change.
1205            if let Event::ToggleChanged(on) = ev
1206                && v.peek() != *on
1207            {
1208                v.write(*on);
1209            }
1210        });
1211        node
1212    }
1213}
1214
1215#[must_use]
1216pub struct Slider<S: Binding<f64>> {
1217    value: S,
1218    min: f64,
1219    max: f64,
1220    step: Option<f64>,
1221    enabled: Reactive<bool>,
1222}
1223
1224pub fn slider<S: Binding<f64>>(value: S) -> Slider<S> {
1225    Slider {
1226        value,
1227        min: 0.0,
1228        max: 1.0,
1229        step: None,
1230        enabled: Reactive::Const(true),
1231    }
1232}
1233
1234#[day_macros::builder(SliderBuilder)]
1235impl<S: Binding<f64>> Slider<S> {
1236    /// Whether the slider takes input (default `true`); a constant or a reactive `bool`.
1237    pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1238        self.enabled = v.into_reactive();
1239        self
1240    }
1241    pub fn range(mut self, r: std::ops::RangeInclusive<f64>) -> Self {
1242        self.min = *r.start();
1243        self.max = *r.end();
1244        self
1245    }
1246    pub fn step(mut self, s: f64) -> Self {
1247        self.step = Some(s);
1248        self
1249    }
1250}
1251
1252impl<S: Binding<f64>> Piece for Slider<S> {
1253    fn build(self, cx: &mut BuildCx) -> RNode {
1254        let initial = self.value.peek();
1255        let node = cx.leaf(
1256            kinds::SLIDER,
1257            &SliderProps {
1258                value: initial,
1259                min: self.min,
1260                max: self.max,
1261                step: self.step,
1262                enabled: self.enabled.get_untracked(),
1263            },
1264            Flex {
1265                grow_w: true,
1266                ..Default::default()
1267            },
1268        );
1269        let enabled = self.enabled;
1270        if let Reactive::Dyn(_) = &enabled {
1271            bind(
1272                move || enabled.get(),
1273                move |e: &bool| {
1274                    with_tree(|t| t.patch(node, Box::new(SliderPatch::Enabled(*e)), false));
1275                },
1276            );
1277        }
1278        let v = self.value.clone();
1279        bind_seeded(
1280            initial,
1281            move || v.read(),
1282            move |val: &f64| {
1283                with_tree(|t| t.patch(node, Box::new(SliderPatch::Value(*val)), false));
1284            },
1285        );
1286        let v = self.value;
1287        let (step, min, max) = (self.step, self.min, self.max);
1288        cx.on(node, move |ev| {
1289            // Honor `.step(_)` at the framework layer so every backend produces stepped values:
1290            // several native sliders (e.g. iOS `UISlider`) have no native step and emit a
1291            // continuous stream while dragging. Snapping here keeps the bound signal (and the
1292            // thumb, via `bind_seeded` above) on the step grid, and stops a `.step`-bound consumer
1293            // from being hammered ~60×/s with sub-step deltas during a drag.
1294            let snap = |val: f64| match step {
1295                Some(s) if s > 0.0 => (min + ((val - min) / s).round() * s).clamp(min, max),
1296                _ => val,
1297            };
1298            match ev {
1299                // The live half of the pair: readers follow the thumb; nothing durable keys
1300                // off it (a day-model field opens a preview session here).
1301                Event::ValueChanged(val) => v.write_preview(snap(*val)),
1302                // The settled value: One record for the whole drag. A backend that cannot
1303                // tell the two apart never sends this, and the preview default (a plain
1304                // write) keeps it correct: chattier, never wrong.
1305                Event::ValueCommitted(val) => v.write_commit(snap(*val)),
1306                _ => {}
1307            }
1308        });
1309        node
1310    }
1311}
1312
1313/// A single-line text input bound to a `String` (docs/textfield.md).
1314///
1315/// How it takes its text is set with `.secure(_)`, `.read_only(_)`, `.input_purpose(_)`,
1316/// `.submit_label(_)` and `.max_length(_)`; [`secure_field`] is the password-field shorthand.
1317#[must_use]
1318pub struct TextField<S: Binding<String>> {
1319    value: S,
1320    placeholder: Option<TextSource>,
1321    on_submit: Option<Rc<dyn Fn()>>,
1322    secure: Reactive<bool>,
1323    read_only: Reactive<bool>,
1324    purpose: day_spec::InputPurpose,
1325    submit_label: day_spec::SubmitLabel,
1326    max_length: Option<u32>,
1327    enabled: Reactive<bool>,
1328    select: Option<(day_reactive::Trigger, Rc<dyn Fn() -> TextSelection>)>,
1329}
1330
1331pub fn text_field<S: Binding<String>>(value: S) -> TextField<S> {
1332    TextField {
1333        value,
1334        placeholder: None,
1335        on_submit: None,
1336        secure: Reactive::Const(false),
1337        read_only: Reactive::Const(false),
1338        purpose: day_spec::InputPurpose::Text,
1339        submit_label: day_spec::SubmitLabel::Return,
1340        max_length: None,
1341        enabled: Reactive::Const(true),
1342        select: None,
1343    }
1344}
1345
1346/// A password field: a [`text_field`] that hides its characters and tells the platform it
1347/// holds a password, so the password manager offers to fill it (docs/textfield.md).
1348///
1349/// It is the same piece, so every `text_field` builder applies. `.secure(shown)` with a signal
1350/// makes a show-password switch; `.input_purpose(InputPurpose::NewPassword)` marks a sign-up
1351/// form's field.
1352pub fn secure_field<S: Binding<String>>(value: S) -> TextField<S> {
1353    text_field(value)
1354        .secure(true)
1355        .input_purpose(day_spec::InputPurpose::Password)
1356}
1357
1358#[day_macros::builder(TextFieldBuilder)]
1359impl<S: Binding<String>> TextField<S> {
1360    /// Whether the field takes input (default `true`); a constant or a reactive `bool`. A
1361    /// disabled field neither edits nor focuses; [`TextField::read_only`] keeps it selectable.
1362    pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1363        self.enabled = v.into_reactive();
1364        self
1365    }
1366    pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
1367        self.placeholder = Some(t.into_text());
1368        self
1369    }
1370    /// Fire when the user submits the field (Return / the keyboard's action key). Field
1371    /// chaining is a focus write inside the handler: `focus.set(Some(Field::Next))`
1372    /// (docs/focus.md).
1373    pub fn on_submit(mut self, f: impl Fn() + 'static) -> Self {
1374        self.on_submit = Some(Rc::new(f));
1375        self
1376    }
1377    /// Hide the characters as they are typed (default `false`). Reactive: bind it to a signal
1378    /// for a show-password switch. The text, the placeholder and the focus carry across the
1379    /// change on every backend, including the two whose secure field is a different native
1380    /// class.
1381    pub fn secure<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1382        self.secure = v.into_reactive();
1383        self
1384    }
1385    /// Show the text and let it be selected and copied, and take no edits (default `false`).
1386    /// Reactive. Unlike `.disabled(true)` the field keeps its ordinary look and still takes
1387    /// focus.
1388    pub fn read_only<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
1389        self.read_only = v.into_reactive();
1390        self
1391    }
1392    /// What the field collects: the on-screen keyboard, capitalization and correction, and
1393    /// what the system offers to fill in all follow from it.
1394    pub fn input_purpose(mut self, purpose: day_spec::InputPurpose) -> Self {
1395        self.purpose = purpose;
1396        self
1397    }
1398    /// What the on-screen keyboard's action key says. The key fires `on_submit` either way.
1399    pub fn submit_label(mut self, label: day_spec::SubmitLabel) -> Self {
1400        self.submit_label = label;
1401        self
1402    }
1403    /// The most characters the field takes. Typing or pasting past it is cut to fit before
1404    /// the bound value sees it.
1405    pub fn max_length(mut self, characters: u32) -> Self {
1406        self.max_length = Some(characters);
1407        self
1408    }
1409    /// Select part of the text, or place the caret, each time `trigger` fires
1410    /// (docs/textfield.md "Selection"). `range` is read once the turn settles, after any text
1411    /// the same turn wrote has reached the field, and counts characters (Unicode scalar
1412    /// values): `..` selects everything, `3..` from the fourth character to the end, `3..3`
1413    /// puts the caret after the third. Ends past the text are held to it.
1414    ///
1415    /// An address bar's inline completion writes the completed text and selects what the user
1416    /// did not type, so the next keystroke replaces it:
1417    ///
1418    /// ```ignore
1419    /// let complete = Trigger::new();
1420    /// let typed = Signal::new(0usize);
1421    /// text_field(address).select(complete, move || typed.get_untracked()..)
1422    /// // on input "git": typed.set(3); address.set("github.com".into()); complete.notify();
1423    /// ```
1424    ///
1425    /// The selection is for a focused field; fire it from the same turn that focuses the field,
1426    /// or from a [`Decorate::focused`] change, to select everything on focus.
1427    pub fn select<R: std::ops::RangeBounds<usize> + 'static>(
1428        mut self,
1429        trigger: day_reactive::Trigger,
1430        range: impl Fn() -> R + 'static,
1431    ) -> Self {
1432        self.select = Some((
1433            trigger,
1434            Rc::new(move || {
1435                use std::ops::Bound;
1436                let r = range();
1437                let start = match r.start_bound() {
1438                    Bound::Included(&n) => n,
1439                    Bound::Excluded(&n) => n.saturating_add(1),
1440                    Bound::Unbounded => 0,
1441                };
1442                let end = match r.end_bound() {
1443                    Bound::Included(&n) => n.saturating_add(1),
1444                    Bound::Excluded(&n) => n,
1445                    Bound::Unbounded => usize::MAX,
1446                };
1447                TextSelection::new(start, end)
1448            }),
1449        ));
1450        self
1451    }
1452}
1453
1454impl<S: Binding<String>> Piece for TextField<S> {
1455    fn build(self, cx: &mut BuildCx) -> RNode {
1456        let initial = self.value.peek();
1457        let ph = self
1458            .placeholder
1459            .as_ref()
1460            .map_or_default(super::sources::TextSource::initial);
1461        let node = cx.leaf(
1462            kinds::TEXT_FIELD,
1463            &TextFieldProps {
1464                text: initial.clone(),
1465                placeholder: ph,
1466                enabled: self.enabled.get_untracked(),
1467            },
1468            Flex {
1469                grow_w: true,
1470                ..Default::default()
1471            },
1472        );
1473        if let Reactive::Dyn(_) = &self.enabled {
1474            let enabled = self.enabled.clone();
1475            bind(
1476                move || enabled.get(),
1477                move |e: &bool| {
1478                    with_tree(|t| t.patch(node, Box::new(TextFieldPatch::Enabled(*e)), false));
1479                },
1480            );
1481        }
1482        // Text entry traits (docs/textfield.md). The duty is skipped for a field that asks for
1483        // nothing, so a plain field costs what it did; a reactive member re-sends the whole
1484        // set, which is what lets a backend rebuild the widget as its secure class and dress
1485        // the replacement in one call.
1486        let (secure, read_only) = (self.secure, self.read_only);
1487        let (purpose, submit_label, max_length) =
1488            (self.purpose, self.submit_label, self.max_length);
1489        let traits = move |secure: bool, read_only: bool| day_spec::InputTraits {
1490            secure,
1491            read_only,
1492            purpose,
1493            submit_label,
1494            max_length,
1495        };
1496        let initial_traits = traits(secure.get_untracked(), read_only.get_untracked());
1497        let reactive_traits =
1498            matches!(secure, Reactive::Dyn(_)) || matches!(read_only, Reactive::Dyn(_));
1499        if initial_traits != day_spec::InputTraits::default() {
1500            with_tree(|t| t.set_node_input_traits(node, &initial_traits));
1501        }
1502        if reactive_traits {
1503            bind_seeded(
1504                initial_traits,
1505                move || traits(secure.get(), read_only.get()),
1506                move |tr: &day_spec::InputTraits| {
1507                    with_tree(|t| t.set_node_input_traits(node, tr));
1508                },
1509            );
1510        }
1511        // Controlled input with origin-tagged writes (§4.4): the echo guard remembers the
1512        // last value that came from the native widget so its own change is not written back.
1513        let guard: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
1514        // The typing session's latest text, sealed on Return or focus loss (below).
1515        let last: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
1516        let v = self.value.clone();
1517        let session = self.value.clone();
1518        let (g, typed) = (guard.clone(), last.clone());
1519        bind_seeded(
1520            initial,
1521            move || v.read(),
1522            move |t: &String| {
1523                let from_native = g.borrow_mut().take().as_deref() == Some(t.as_str());
1524                if !from_native && typed.borrow_mut().take().is_some() {
1525                    // An app write (an address bar's completion, Escape putting the URL back)
1526                    // replaces the typing session: sealing it later would write the typed
1527                    // text back over this one, and the binding's open preview session still
1528                    // holds the text from before the typing. The app's write recorded its own
1529                    // change; close the session so the next keystroke starts from it.
1530                    session.end_preview();
1531                }
1532                with_tree(|tr| {
1533                    tr.patch(
1534                        node,
1535                        Box::new(TextFieldPatch::Text {
1536                            text: t.clone(),
1537                            from_native,
1538                        }),
1539                        false,
1540                    );
1541                });
1542            },
1543        );
1544        let value = self.value.clone();
1545        let v = self.value;
1546        let submit = self.on_submit;
1547        // Typing is a session: each keystroke is a preview (readers follow, nothing durable
1548        // fires), sealed into one committed change on Return or focus loss by the typing
1549        // coalescer. For a plain Signal binding preview defaults to write, so nothing changes
1550        // where no session semantics exist. Teardown seals too: navigating away from a page
1551        // mid-type must not leave the last burst outside the change log.
1552        {
1553            let (v, last) = (v.clone(), last.clone());
1554            day_reactive::Scope::current().on_cleanup(move || {
1555                if let Some(t) = last.borrow_mut().take() {
1556                    v.write_teardown(t);
1557                }
1558            });
1559        }
1560        cx.on(node, move |ev| match ev {
1561            Event::TextChanged(t) => {
1562                // The length bound, held here so it counts the same characters on every
1563                // backend, whatever unit a native limit would count. The cut text is painted back as
1564                // an app write: the native field is showing the longer one, and the bound
1565                // value may not change at all (typing at the limit), so no binding would.
1566                let cut = max_length
1567                    .and_then(|max| t.char_indices().nth(max as usize))
1568                    .map(|(at, _)| t[..at].to_string());
1569                let t = match cut {
1570                    Some(cut) => {
1571                        with_tree(|tr| {
1572                            tr.patch(
1573                                node,
1574                                Box::new(TextFieldPatch::Text {
1575                                    text: cut.clone(),
1576                                    from_native: false,
1577                                }),
1578                                false,
1579                            );
1580                        });
1581                        cut
1582                    }
1583                    None => t.clone(),
1584                };
1585                *guard.borrow_mut() = Some(t.clone());
1586                *last.borrow_mut() = Some(t.clone());
1587                v.write_preview(t);
1588            }
1589            Event::Submitted => {
1590                if let Some(t) = last.borrow_mut().take() {
1591                    v.write_commit(t);
1592                }
1593                if let Some(f) = &submit {
1594                    f();
1595                }
1596            }
1597            Event::FocusChanged(false) => {
1598                if let Some(t) = last.borrow_mut().take() {
1599                    v.write_commit(t);
1600                }
1601            }
1602            _ => {}
1603        });
1604        if let Some(p) = self.placeholder {
1605            p.bind_to(node, |t| Box::new(TextFieldPatch::Placeholder(t)), false);
1606        }
1607        // Selection requests (docs/textfield.md "Selection"). Each firing is a request, so the
1608        // same range applies again on the next one (select-all on every focus). The range is
1609        // read once the turn settles, so the text written in the same turn has reached the
1610        // field first, whatever order the app wrote the two in, and it is held to that text.
1611        // The patch itself is posted, as a focus request is (`Decorate::focused`): one made in
1612        // the same turn lands first, and AppKit and UIKit select only in a focused field.
1613        if let Some((trigger, range)) = self.select {
1614            let scope = day_reactive::Scope::current();
1615            day_reactive::watch(
1616                move || trigger.track(),
1617                move |(), _| {
1618                    let (range, value) = (range.clone(), value.clone());
1619                    day_reactive::at_turn_end(move || {
1620                        if !scope.is_alive() {
1621                            return;
1622                        }
1623                        let sel = range().clamped(&value.peek());
1624                        day_reactive::on_main(move || {
1625                            with_tree(|t| {
1626                                t.patch(node, Box::new(TextFieldPatch::Select(sel)), false);
1627                            });
1628                        });
1629                    });
1630                },
1631            );
1632        }
1633        node
1634    }
1635}
1636
1637/// A progress indicator: a determinate bar (from [`progress`]) or an indeterminate spinner
1638/// (from [`spinner`]). See docs/progress.md.
1639#[must_use]
1640pub struct Progress {
1641    /// `None` = indeterminate (spinner); `Some` = a determinate fraction source.
1642    value: Option<FractionSource>,
1643    animating: crate::Reactive<bool>,
1644    large: bool,
1645}
1646
1647/// An indeterminate, animated progress indicator (a spinner / busy bar) for work with no
1648/// known extent.
1649pub fn spinner() -> Progress {
1650    Progress {
1651        value: None,
1652        animating: crate::Reactive::Const(true),
1653        large: false,
1654    }
1655}
1656
1657/// A determinate progress bar. `fraction` is the completed portion in `0.0..=1.0`; pass a
1658/// constant, a `Signal<f64>`, or a closure and it tracks reactively (out-of-range values are
1659/// clamped).
1660pub fn progress<M>(fraction: impl IntoFraction<M>) -> Progress {
1661    Progress {
1662        value: Some(fraction.into_fraction()),
1663        animating: crate::Reactive::Const(true),
1664        large: false,
1665    }
1666}
1667
1668#[day_macros::builder(ProgressBuilder)]
1669impl Progress {
1670    /// Start or stop an indeterminate indicator, keeping its layout space.
1671    pub fn animating<M>(mut self, source: impl crate::IntoReactive<bool, M>) -> Self {
1672        self.animating = source.into_reactive();
1673        self
1674    }
1675    /// Use the platform's large indeterminate indicator.
1676    pub fn large(mut self) -> Self {
1677        self.large = true;
1678        self
1679    }
1680}
1681
1682impl Piece for Progress {
1683    fn build(self, cx: &mut BuildCx) -> RNode {
1684        let determinate = self.value.is_some();
1685        let initial = self
1686            .value
1687            .as_ref()
1688            .map(super::sources::FractionSource::initial);
1689        let node = cx.leaf(
1690            kinds::PROGRESS,
1691            &ProgressProps {
1692                value: initial,
1693                animating: self.animating.get_untracked(),
1694                large: self.large,
1695            },
1696            // A determinate bar fills the available width (like a slider); a spinner keeps its
1697            // fixed intrinsic size.
1698            Flex {
1699                grow_w: determinate,
1700                ..Default::default()
1701            },
1702        );
1703        if !determinate && let crate::Reactive::Dyn(f) = self.animating {
1704            day_reactive::bind_seeded(
1705                f(),
1706                move || f(),
1707                move |on| {
1708                    day_core::with_tree(|t| {
1709                        t.patch(node, Box::new(ProgressPatch::Animating(*on)), false);
1710                    });
1711                },
1712            );
1713        }
1714        if let Some(src) = self.value {
1715            src.bind_to(node);
1716        }
1717        node
1718    }
1719}
1720
1721/// A hairline between neighbors: across a column's width by default, down a row's height
1722/// with [`Divider::vertical`].
1723#[must_use]
1724pub struct Divider {
1725    vertical: bool,
1726}
1727
1728pub fn divider() -> Divider {
1729    Divider { vertical: false }
1730}
1731
1732#[day_macros::builder(DividerBuilder)]
1733impl Divider {
1734    /// Turn the rule on its side: a thin vertical line that fills the row's height, the way the
1735    /// horizontal one fills a column's width. Between a row's panes, where a horizontal rule
1736    /// would draw a stray line across one of them.
1737    pub fn vertical(mut self) -> Self {
1738        self.vertical = true;
1739        self
1740    }
1741}
1742
1743impl Piece for Divider {
1744    fn build(self, cx: &mut BuildCx) -> RNode {
1745        let props = DividerProps {
1746            vertical: self.vertical,
1747        };
1748        if self.vertical {
1749            cx.native(
1750                kinds::DIVIDER,
1751                &props,
1752                Rc::new(VerticalLeaf),
1753                Flex {
1754                    grow_h: true,
1755                    ..Default::default()
1756                },
1757                Boundary::No,
1758            )
1759        } else {
1760            cx.leaf(
1761                kinds::DIVIDER,
1762                &props,
1763                Flex {
1764                    grow_w: true,
1765                    ..Default::default()
1766                },
1767            )
1768        }
1769    }
1770}
1771
1772/// A native leaf measured with its axes swapped: the toolkit answers as it does for a
1773/// horizontal rule (the offered width, by its hairline thickness), and the vertical rule is that
1774/// answer turned on its side. One measurement arm per toolkit, whichever way the line runs.
1775struct VerticalLeaf;
1776
1777impl Layout for VerticalLeaf {
1778    fn measure(&self, cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
1779        let s = cx.measure_leaf(Proposal::new(p.height, p.width));
1780        Size::new(s.height, s.width)
1781    }
1782    fn place(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _bounds: Rect) {}
1783}
1784
1785pub struct Spacer;
1786
1787#[must_use]
1788pub fn spacer() -> Spacer {
1789    Spacer
1790}
1791
1792impl Piece for Spacer {
1793    fn build(self, cx: &mut BuildCx) -> RNode {
1794        cx.layout_only(
1795            Rc::new(PassThrough),
1796            Flex {
1797                is_spacer: true,
1798                ..Default::default()
1799            },
1800            Boundary::No,
1801        )
1802    }
1803}
1804
1805// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
1806
1807// ---------------------------------------------------------------------------
1808// Conformance cases (docs/testing.md): each leaf's behavior on the real toolkit
1809// ---------------------------------------------------------------------------
1810
1811/// The leaves' `#[day::test]` cases, next to the constructors they prove. Compiled only under
1812/// the `conformance` feature, so a shipping app links none of it.
1813#[cfg(feature = "conformance")]
1814pub(crate) mod conformance {
1815    use day_core::Piece;
1816    use day_core::conformance::{Case, Drive, FrameExpect, NativeExpect};
1817    use day_reactive::Signal;
1818    use day_spec::props::Truncation;
1819    use day_spec::{Cap, Font, Role, kinds};
1820
1821    use crate::*;
1822
1823    /// A button fires its action on each press and counts it.
1824    #[day_macros::test(day_core)]
1825    fn button_press() -> Case {
1826        let presses = Signal::new(0i64);
1827        Case::new()
1828            .proves(kinds::BUTTON)
1829            .page(move || {
1830                column((
1831                    button("Press")
1832                        .action(move || presses.update(|n| *n += 1))
1833                        .id(day_core::id!(press)),
1834                    label(move || presses.get().to_string()).id(day_core::id!(count)),
1835                ))
1836                .spacing(8.0)
1837            })
1838            .shot("default")
1839            .drive(|d: Drive| async move {
1840                d.assert_text("press", "Press").await?;
1841                d.tap("press").await?;
1842                d.assert_text("count", "1").await?;
1843                d.tap("press").await?;
1844                d.assert_text("count", "2").await
1845            })
1846    }
1847
1848    /// A disabled button reports itself disabled, in Day and natively, and takes presses once
1849    /// enabled. (A tap on a disabled button is not drivable: the `tap` step waits for the
1850    /// element to be enabled, as a person would.)
1851    #[day_macros::test(day_core)]
1852    fn button_disabled() -> Case {
1853        let presses = Signal::new(0i64);
1854        let enabled = Signal::new(false);
1855        Case::new()
1856            .proves(kinds::BUTTON)
1857            .proves_duty("set_enabled")
1858            .page(move || {
1859                column((
1860                    button("Off")
1861                        .enabled(move || enabled.get())
1862                        .action(move || presses.update(|n| *n += 1))
1863                        .id(day_core::id!(off)),
1864                    label(move || presses.get().to_string()).id(day_core::id!(count)),
1865                    button("Enable")
1866                        .action(move || enabled.set(true))
1867                        .id(day_core::id!(enable)),
1868                ))
1869                .spacing(8.0)
1870            })
1871            .drive(|d: Drive| async move {
1872                d.assert_enabled("off", false).await?;
1873                d.assert_text("count", "0").await?;
1874                d.tap("enable").await?;
1875                d.assert_enabled("off", true).await?;
1876                d.tap("off").await?;
1877                d.assert_text("count", "1").await
1878            })
1879    }
1880
1881    /// A toggle reports its flips to its signal, and a write to the signal reaches it.
1882    #[day_macros::test(day_core)]
1883    fn toggle_binding() -> Case {
1884        let on = Signal::new(false);
1885        Case::new()
1886            .proves(kinds::TOGGLE)
1887            .page(move || {
1888                column((
1889                    toggle(on).id(day_core::id!(tgl_switch)),
1890                    label(move || if on.get() { "on" } else { "off" }.to_owned())
1891                        .id(day_core::id!(tgl_state)),
1892                    button("Set on")
1893                        .action(move || on.set(true))
1894                        .id(day_core::id!(tgl_set)),
1895                ))
1896                .spacing(8.0)
1897            })
1898            .drive(|d: Drive| async move {
1899                d.toggle("tgl_switch", true).await?;
1900                d.assert_text("tgl_state", "on").await?;
1901                d.toggle("tgl_switch", false).await?;
1902                d.assert_text("tgl_state", "off").await?;
1903                d.tap("tgl_set").await?;
1904                d.assert_on("tgl_switch", true).await
1905            })
1906    }
1907
1908    /// One flip is one change (DESIGN.md §4.4): the control echoing a value written to it, by
1909    /// the flip itself or by the app, does not notify the binding's watchers a second time. A
1910    /// watcher that toggles something on each change (reverse a list) would undo its own work.
1911    #[day_macros::test(day_core)]
1912    fn toggle_flip_is_one_change() -> Case {
1913        let on = Signal::new(false);
1914        let changes = Signal::new(0u32);
1915        Case::new()
1916            .proves(kinds::TOGGLE)
1917            .page(move || {
1918                day_reactive::watch(move || on.get(), move |_, _| changes.update(|n| *n += 1));
1919                column((
1920                    toggle(on).id(day_core::id!(tgl_once)),
1921                    button("Set on")
1922                        .action(move || on.set(true))
1923                        .id(day_core::id!(tgl_once_set)),
1924                    label(move || format!("changes {}", changes.get()))
1925                        .id(day_core::id!(tgl_once_changes)),
1926                ))
1927                .spacing(8.0)
1928            })
1929            .drive(|d: Drive| async move {
1930                d.toggle("tgl_once", true).await?;
1931                d.wait_idle().await?;
1932                d.pause(0.3).await?;
1933                d.assert_text("tgl_once_changes", "changes 1").await?;
1934                d.toggle("tgl_once", false).await?;
1935                d.wait_idle().await?;
1936                d.pause(0.3).await?;
1937                d.assert_text("tgl_once_changes", "changes 2").await?;
1938                d.tap("tgl_once_set").await?;
1939                d.wait_idle().await?;
1940                d.pause(0.3).await?;
1941                d.assert_on("tgl_once", true).await?;
1942                d.assert_text("tgl_once_changes", "changes 3").await
1943            })
1944    }
1945
1946    /// A text field writes what is typed to its signal, and shows what the signal is set to.
1947    #[day_macros::test(day_core)]
1948    fn text_field_binding() -> Case {
1949        let name = Signal::new(String::new());
1950        Case::new()
1951            .proves(kinds::TEXT_FIELD)
1952            .page(move || {
1953                column((
1954                    text_field(name)
1955                        .placeholder("Name")
1956                        .id(day_core::id!(tf_field)),
1957                    label(move || name.get()).id(day_core::id!(tf_echo)),
1958                    button("Set")
1959                        .action(move || name.set("Ada".into()))
1960                        .id(day_core::id!(tf_set)),
1961                ))
1962                .spacing(8.0)
1963            })
1964            .drive(|d: Drive| async move {
1965                d.input("tf_field", "Grace").await?;
1966                d.assert_text("tf_echo", "Grace").await?;
1967                d.tap("tf_set").await?;
1968                d.assert_text("tf_field", "Ada").await
1969            })
1970    }
1971
1972    /// A secure field keeps its text and its focus across a show-password flip: on AppKit and
1973    /// WinUI the flip rebuilds the widget as its other native class (docs/textfield.md).
1974    #[day_macros::test(day_core)]
1975    fn text_field_secure() -> Case {
1976        let password = Signal::new(String::new());
1977        let shown = Signal::new(false);
1978        Case::new()
1979            .proves(kinds::TEXT_FIELD)
1980            .proves_duty("set_input_traits")
1981            .page(move || {
1982                column((
1983                    secure_field(password)
1984                        .secure(move || !shown.get())
1985                        .placeholder("Password")
1986                        .id(day_core::id!(tfs_pass)),
1987                    toggle(shown).id(day_core::id!(tfs_show)),
1988                    label(move || password.get().chars().count().to_string())
1989                        .id(day_core::id!(tfs_len)),
1990                ))
1991                .spacing(8.0)
1992            })
1993            .shot("masked")
1994            .drive(|d: Drive| async move {
1995                d.input("tfs_pass", "correct horse").await?;
1996                d.assert_text("tfs_len", "13").await?;
1997                d.focus("tfs_pass").await?;
1998                d.toggle("tfs_show", true).await?;
1999                d.wait_idle().await?;
2000                d.shot("shown").await?;
2001                d.assert_focused("tfs_pass", true).await?;
2002                d.input("tfs_pass", "battery").await?;
2003                d.assert_text("tfs_len", "7").await?;
2004                d.toggle("tfs_show", false).await?;
2005                d.wait_idle().await?;
2006                d.assert_text("tfs_pass", "battery").await
2007            })
2008    }
2009
2010    /// A field held to four characters cuts what is typed past them, on every toolkit alike.
2011    #[day_macros::test(day_core)]
2012    fn text_field_max_length() -> Case {
2013        let pin = Signal::new(String::new());
2014        Case::new()
2015            .proves(kinds::TEXT_FIELD)
2016            .page(move || {
2017                column((
2018                    text_field(pin).max_length(4).id(day_core::id!(tfm_pin)),
2019                    label(move || pin.get()).id(day_core::id!(tfm_echo)),
2020                ))
2021                .spacing(8.0)
2022            })
2023            .drive(|d: Drive| async move {
2024                d.input("tfm_pin", "123456").await?;
2025                d.assert_text("tfm_echo", "1234").await?;
2026                d.assert_text("tfm_pin", "1234").await
2027            })
2028    }
2029
2030    /// A slider's value reaches its signal on the step grid the piece declares, whatever the
2031    /// native control's own stepping.
2032    #[day_macros::test(day_core)]
2033    fn slider_range() -> Case {
2034        let value = Signal::new(40.0f64);
2035        Case::new()
2036            .proves(kinds::SLIDER)
2037            .page(move || {
2038                column((
2039                    slider(value)
2040                        .range(0.0..=100.0)
2041                        .step(10.0)
2042                        .id(day_core::id!(sl_slider)),
2043                    label(move || format!("{:.0}", value.get())).id(day_core::id!(sl_value)),
2044                ))
2045                .spacing(8.0)
2046            })
2047            .drive(|d: Drive| async move {
2048                d.set_value("sl_slider", 72.0).await?;
2049                d.assert_text("sl_value", "70").await?;
2050                d.assert_value("sl_slider", 70.0).await
2051            })
2052    }
2053
2054    /// A label shows its text, follows a signal, and reports its explicit role natively where
2055    /// the toolkit reads its tree back.
2056    #[day_macros::test(day_core)]
2057    fn label_heading() -> Case {
2058        let text = Signal::new("Hello".to_owned());
2059        Case::new()
2060            .proves(kinds::LABEL)
2061            .proves_duty("set_a11y")
2062            .page(move || {
2063                column((
2064                    label(move || text.get())
2065                        .font(Font::Headline)
2066                        .a11y(|a| a.role(Role::Heading(2)))
2067                        .id(day_core::id!(lbl_heading)),
2068                    button("Rename")
2069                        .action(move || text.set("Renamed".into()))
2070                        .id(day_core::id!(lbl_rename)),
2071                ))
2072                .spacing(8.0)
2073            })
2074            .drive(|d: Drive| async move {
2075                d.assert_text("lbl_heading", "Hello").await?;
2076                d.tap("lbl_rename").await?;
2077                d.assert_text("lbl_heading", "Renamed").await?;
2078                d.a11y_audit(Some("lbl_heading")).await
2079            })
2080    }
2081
2082    /// A label shows its text, natively too.
2083    #[day_macros::test(day_core)]
2084    fn label_text() -> Case {
2085        Case::new()
2086            .proves(kinds::LABEL)
2087            .page(|| label("Plain text").id(day_core::id!(text)))
2088            .drive(|d: Drive| async move { d.assert_text("text", "Plain text").await })
2089    }
2090
2091    /// A label bound to a signal follows every write.
2092    #[day_macros::test(day_core)]
2093    fn label_reactive() -> Case {
2094        let count = Signal::new(0i64);
2095        Case::new()
2096            .proves(kinds::LABEL)
2097            .proves_duty("update")
2098            .proves_duty("read_native")
2099            .page(move || {
2100                column((
2101                    label(move || format!("Count {}", count.get())).id(day_core::id!(text)),
2102                    button("Add")
2103                        .action(move || count.update(|n| *n += 1))
2104                        .id(day_core::id!(add)),
2105                ))
2106                .spacing(8.0)
2107            })
2108            .drive(|d: Drive| async move {
2109                d.assert_text("text", "Count 0").await?;
2110                d.tap("add").await?;
2111                d.tap("add").await?;
2112                d.assert_text("text", "Count 2").await
2113            })
2114    }
2115
2116    /// Styled runs draw as one string: the native text is the runs joined, without markup.
2117    #[day_macros::test(day_core)]
2118    fn label_runs() -> Case {
2119        Case::new()
2120            .proves(kinds::LABEL)
2121            .proves_cap(Cap::TextRuns)
2122            .requires(Cap::TextRuns)
2123            .page(|| {
2124                label("")
2125                    .runs_from(
2126                        TextBuilder::new()
2127                            .text("Plain, ")
2128                            .strong("strong")
2129                            .text(" and ")
2130                            .emphasis("emphasized"),
2131                    )
2132                    .id(day_core::id!(runs))
2133            })
2134            .shot("default")
2135            .drive(|d: Drive| async move {
2136                d.assert_text("runs", "Plain, strong and emphasized").await
2137            })
2138    }
2139
2140    /// A label's own color stays under its runs when new runs replace the old ones.
2141    #[day_macros::test(day_core)]
2142    fn label_runs_keep_the_label_color() -> Case {
2143        let text = Signal::new(
2144            "\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588} **\u{2588}**".to_string(),
2145        );
2146        Case::new()
2147            .proves(kinds::LABEL)
2148            .requires(Cap::TextRuns)
2149            .requires(Cap::Snapshot)
2150            .page(move || {
2151                column((
2152                    label(text)
2153                        .markdown()
2154                        .color(day_spec::Color::rgb(1.0, 0.0, 0.0))
2155                        .id(day_core::id!(colored)),
2156                    button("Restyle")
2157                        .id(day_core::id!(restyle))
2158                        .action(move || {
2159                            text.set(
2160                                "\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588} *\u{2588}*"
2161                                    .into(),
2162                            );
2163                        }),
2164                ))
2165            })
2166            .drive(|d: Drive| async move {
2167                d.sample_pixel("colored", 0.1, 0.5, "#ff0000").await?;
2168                d.tap("restyle").await?;
2169                d.sample_pixel("colored", 0.1, 0.5, "#ff0000").await
2170            })
2171    }
2172
2173    /// Replacing link runs, clearing them and restoring them preserves the native text.
2174    /// Native input suites separately exercise each platform's span hit testing.
2175    #[day_macros::test(day_core)]
2176    fn label_link_runs_reactive() -> Case {
2177        let text = Signal::new("😀 [Alpha](#alpha) / [Beta](#beta)".to_string());
2178        Case::new()
2179            .proves(kinds::LABEL)
2180            .requires(Cap::TextRuns)
2181            .page(move || {
2182                column((
2183                    label(text).markdown().id(day_core::id!(links)),
2184                    button("Replace")
2185                        .id(day_core::id!(replace))
2186                        .action(move || {
2187                            text.set("[東京](#tokyo) then [again](#again)".into());
2188                        }),
2189                    button("Plain")
2190                        .id(day_core::id!(plain))
2191                        .action(move || text.set("Plain 😀".into())),
2192                    button("Restore")
2193                        .id(day_core::id!(restore))
2194                        .action(move || text.set("[Restored](#restored)".into())),
2195                ))
2196            })
2197            .drive(|d: Drive| async move {
2198                d.assert_text("links", "😀 Alpha / Beta").await?;
2199                d.tap("replace").await?;
2200                d.assert_text("links", "東京 then again").await?;
2201                d.tap("plain").await?;
2202                d.assert_text("links", "Plain 😀").await?;
2203                d.tap("restore").await?;
2204                d.assert_text("links", "Restored").await
2205            })
2206    }
2207
2208    /// A marker box under a label, so a case can compare two labels' heights by where their
2209    /// markers sit.
2210    fn foot(id: day_core::ElementId) -> impl Piece {
2211        rectangle()
2212            .fill(day_spec::Color::hex(0x0033_6699))
2213            .frame(10.0, 4.0)
2214            .id(id)
2215    }
2216
2217    const LONG: &str = "Day lays this sentence out over many lines when its label is narrow, \
2218        so a line limit has plenty of text to cut and the ellipsis has something to stand for.";
2219
2220    /// A line limit caps the label's height on every toolkit: held to two lines, a long label
2221    /// is exactly as tall as a two-line one, and held to one, as tall as a one-line one. The
2222    /// limit follows its signal, and the text Day reports stays whole.
2223    #[day_macros::test(day_core)]
2224    fn label_max_lines() -> Case {
2225        let limit = Signal::new(0u32);
2226        Case::new()
2227            .proves(kinds::LABEL)
2228            .page(move || {
2229                column((
2230                    row((
2231                        column((
2232                            label(LONG)
2233                                .max_lines(limit)
2234                                .width(100.0)
2235                                .id(day_core::id!(ml_text)),
2236                            foot(day_core::id!(ml_foot)),
2237                        ))
2238                        .align(HAlign::Leading),
2239                        column((label("Ag\nAg").width(100.0), foot(day_core::id!(ml_two))))
2240                            .align(HAlign::Leading),
2241                        column((label("Ag").width(100.0), foot(day_core::id!(ml_one))))
2242                            .align(HAlign::Leading),
2243                    ))
2244                    .align(VAlign::Top),
2245                    button("Two lines")
2246                        .action(move || limit.set(2))
2247                        .id(day_core::id!(ml_set_two)),
2248                    button("One line")
2249                        .action(move || limit.set(1))
2250                        .id(day_core::id!(ml_set_one)),
2251                ))
2252                .align(HAlign::Leading)
2253                .spacing(8.0)
2254            })
2255            .shot("unlimited")
2256            .drive(|d: Drive| async move {
2257                let level_with = |other: &str| FrameExpect {
2258                    y: Some(0.0),
2259                    relative_to: Some(other.into()),
2260                    ..Default::default()
2261                };
2262                d.tap("ml_set_two").await?;
2263                d.wait_idle().await?;
2264                d.assert_frame("ml_foot", level_with("ml_two")).await?;
2265                d.shot("two").await?;
2266                d.tap("ml_set_one").await?;
2267                d.wait_idle().await?;
2268                d.assert_frame("ml_foot", level_with("ml_one")).await?;
2269                d.assert_text("ml_text", LONG).await
2270            })
2271    }
2272
2273    /// A one-line label stays one line tall and as wide as its box in each truncation mode,
2274    /// and the text Day reports is the whole text. Where the ellipsis sits is for the capture.
2275    #[day_macros::test(day_core)]
2276    fn label_truncation_modes() -> Case {
2277        let mode = Signal::new(Truncation::Middle);
2278        Case::new()
2279            .proves(kinds::LABEL)
2280            .page(move || {
2281                column((
2282                    row((
2283                        column((
2284                            label("/usr/local/share/day/templates/app/src/pages.rs")
2285                                .single_line()
2286                                .truncation(mode)
2287                                .width(120.0)
2288                                .id(day_core::id!(tr_path)),
2289                            foot(day_core::id!(tr_foot)),
2290                        ))
2291                        .align(HAlign::Leading),
2292                        column((label("Ag").width(120.0), foot(day_core::id!(tr_one))))
2293                            .align(HAlign::Leading),
2294                    ))
2295                    .align(VAlign::Top),
2296                    button("Head")
2297                        .action(move || mode.set(Truncation::Head))
2298                        .id(day_core::id!(tr_head)),
2299                    button("Tail")
2300                        .action(move || mode.set(Truncation::Tail))
2301                        .id(day_core::id!(tr_tail)),
2302                ))
2303                .align(HAlign::Leading)
2304                .spacing(8.0)
2305            })
2306            .shot("middle")
2307            .drive(|d: Drive| async move {
2308                let one_line = || FrameExpect {
2309                    y: Some(0.0),
2310                    relative_to: Some("tr_one".into()),
2311                    ..Default::default()
2312                };
2313                d.assert_frame("tr_foot", one_line()).await?;
2314                d.tap("tr_head").await?;
2315                d.wait_idle().await?;
2316                d.assert_frame("tr_foot", one_line()).await?;
2317                d.shot("head").await?;
2318                d.tap("tr_tail").await?;
2319                d.wait_idle().await?;
2320                d.assert_frame("tr_foot", one_line()).await?;
2321                d.assert_text("tr_path", "/usr/local/share/day/templates/app/src/pages.rs")
2322                    .await
2323            })
2324    }
2325
2326    /// Line height is a multiple of the em, the font size as drawn, compared here without
2327    /// assuming how many units a point is. Two one-line labels at 2.0 (four ems) end level with
2328    /// three lines at 4/3 and with two lines at 2.0; a change of the multiple to 1.5 re-measures
2329    /// both, so the pair (three ems) ends level with two lines at 1.5. Every reference stays at
2330    /// or above a font's natural line height, so no platform floor gets in the way.
2331    #[day_macros::test(day_core)]
2332    fn label_line_height() -> Case {
2333        let multiple = Signal::new(2.0);
2334        let line = |text: &'static str| label(text).font(Font::System(20.0));
2335        Case::new()
2336            .proves(kinds::LABEL)
2337            .page(move || {
2338                column((
2339                    row((
2340                        column((
2341                            line("Ag").line_height(multiple).id(day_core::id!(lh_one)),
2342                            line("Ag").line_height(multiple),
2343                            foot(day_core::id!(lh_pair_end)),
2344                        ))
2345                        .spacing(0.0),
2346                        column((
2347                            line("Ag\nAg\nAg").line_height(4.0 / 3.0),
2348                            foot(day_core::id!(lh_four_end)),
2349                        ))
2350                        .spacing(0.0),
2351                        column((
2352                            line("Ag\nAg").line_height(2.0).id(day_core::id!(lh_two)),
2353                            foot(day_core::id!(lh_two_end)),
2354                        ))
2355                        .spacing(0.0),
2356                        column((
2357                            line("Ag\nAg").line_height(1.5),
2358                            foot(day_core::id!(lh_three_end)),
2359                        ))
2360                        .spacing(0.0),
2361                    ))
2362                    .spacing(8.0)
2363                    .align(VAlign::Top),
2364                    button("Tighter")
2365                        .action(move || multiple.set(1.5))
2366                        .id(day_core::id!(lh_tighter)),
2367                ))
2368                .align(HAlign::Leading)
2369                .spacing(8.0)
2370            })
2371            .shot("default")
2372            .drive(|d: Drive| async move {
2373                let level_with = |reference: &str| FrameExpect {
2374                    y: Some(0.0),
2375                    relative_to: Some(reference.into()),
2376                    tolerance: Some(2.0),
2377                    ..Default::default()
2378                };
2379                d.assert_frame("lh_pair_end", level_with("lh_four_end"))
2380                    .await?;
2381                d.assert_frame("lh_two_end", level_with("lh_four_end"))
2382                    .await?;
2383                d.tap("lh_tighter").await?;
2384                d.wait_idle().await?;
2385                d.assert_frame("lh_pair_end", level_with("lh_three_end"))
2386                    .await
2387            })
2388    }
2389
2390    /// Letter spacing is in ems of the label's own font as drawn, compared without assuming
2391    /// how many units a point is. Every row holds two labels, so a label's own inset (AppKit's
2392    /// text field cell adds two points a side) and its rounding cancel, and every spaced label
2393    /// has a spaced partner of the same length, so it does not matter whether a platform adds
2394    /// the spacing after the last character too.
2395    ///
2396    /// Three characters of a 40-point font spaced by 0.75 em gain exactly what three of a
2397    /// 20-point font spaced by 1.5 em gain, so the two rows end level within a point of
2398    /// rounding; spacing that ignored the font's size would not. Then the size of the em: eight
2399    /// characters spaced by a quarter em gain one em more than four, which one em space
2400    /// (U+2003) stands in for, so an em taken as a point where the font draws larger (Linux
2401    /// draws a 20-point font 26.7 units tall) falls a quarter of an em short. An em space is a
2402    /// font's em by definition but not always to the unit (San Francisco's is 0.98 em at 20
2403    /// points), so that comparison allows half a point more than rounding.
2404    #[day_macros::test(day_core)]
2405    fn label_letter_spacing() -> Case {
2406        let at = |text: &'static str, points: f64| label(text).font(Font::System(points));
2407        let level = |reference: &str, tolerance: f64| FrameExpect {
2408            x: Some(0.0),
2409            relative_to: Some(reference.into()),
2410            tolerance: Some(tolerance),
2411            ..Default::default()
2412        };
2413        Case::new()
2414            .proves(kinds::LABEL)
2415            .page(move || {
2416                column((
2417                    row((
2418                        at("HHH", 40.0).letter_spacing(0.75),
2419                        at("HHH", 20.0),
2420                        foot(day_core::id!(ls_large_end)),
2421                    )),
2422                    row((
2423                        at("HHH", 40.0),
2424                        at("HHH", 20.0).letter_spacing(1.5),
2425                        foot(day_core::id!(ls_small_end)),
2426                    )),
2427                    row((
2428                        at("HHHHHHHH", 20.0)
2429                            .letter_spacing(0.25)
2430                            .id(day_core::id!(ls_spaced)),
2431                        at("HH", 20.0),
2432                        foot(day_core::id!(ls_spaced_end)),
2433                    )),
2434                    row((
2435                        at("HHHH", 20.0).letter_spacing(0.25),
2436                        at("HH\u{2003}HHHH", 20.0),
2437                        foot(day_core::id!(ls_plain_end)),
2438                    )),
2439                ))
2440                .align(HAlign::Leading)
2441                .spacing(8.0)
2442            })
2443            .shot("default")
2444            .drive(move |d: Drive| async move {
2445                d.assert_frame("ls_large_end", level("ls_small_end", 1.0))
2446                    .await?;
2447                d.assert_frame("ls_spaced_end", level("ls_plain_end", 1.5))
2448                    .await?;
2449                d.assert_text("ls_spaced", "HHHHHHHH").await
2450            })
2451    }
2452
2453    /// Decorations and font features change how text draws, never what it says: a label with a
2454    /// wavy colored underline on one word, a double underline over the whole text, small caps
2455    /// and oldstyle figures still reports its plain text.
2456    #[day_macros::test(day_core)]
2457    fn label_decorations_and_features() -> Case {
2458        Case::new()
2459            .proves(kinds::LABEL)
2460            .requires(Cap::TextRuns)
2461            .page(|| {
2462                column((
2463                    label("")
2464                        .runs_from(
2465                            TextBuilder::new()
2466                                .text("Check ")
2467                                .underline_styled(
2468                                    "unknown",
2469                                    day_spec::Decoration::wavy()
2470                                        .color(day_spec::Color::hex(0x00D0_021B)),
2471                                )
2472                                .text(" and ")
2473                                .strikethrough_styled("old", day_spec::DecorationStyle::Double)
2474                                .text(" in ")
2475                                .small_caps("Small Caps"),
2476                        )
2477                        .id(day_core::id!(dec_runs)),
2478                    label("Doubly underlined")
2479                        .underline(day_spec::Decoration::double())
2480                        .id(day_core::id!(dec_whole)),
2481                    label("Struck in red")
2482                        .strikethrough(
2483                            day_spec::Decoration::SINGLE.color(day_spec::Color::hex(0x00D0_021B)),
2484                        )
2485                        .id(day_core::id!(dec_struck)),
2486                    label("Chapter 1234567890")
2487                        .small_caps()
2488                        .oldstyle_figures()
2489                        .id(day_core::id!(dec_features)),
2490                ))
2491                .align(HAlign::Leading)
2492                .spacing(8.0)
2493            })
2494            .shot("default")
2495            .drive(|d: Drive| async move {
2496                d.assert_text("dec_runs", "Check unknown and old in Small Caps")
2497                    .await?;
2498                d.assert_text("dec_whole", "Doubly underlined").await?;
2499                d.assert_text("dec_struck", "Struck in red").await?;
2500                d.assert_text("dec_features", "Chapter 1234567890").await
2501            })
2502    }
2503
2504    /// A label that asks for selection reports is selectable and still shows its text. The
2505    /// reports themselves need a native selection gesture, which each toolkit's native input
2506    /// suite makes; the mock harness raises the event directly (`tests/text_mock.rs`).
2507    #[day_macros::test(day_core)]
2508    fn label_on_selection() -> Case {
2509        let chosen = Signal::new(String::new());
2510        Case::new()
2511            .proves(kinds::LABEL)
2512            .proves_duty("set_selectable")
2513            .page(move || {
2514                column((
2515                    label("Select part of this sentence")
2516                        .on_selection(move |s| chosen.set(s.text.clone()))
2517                        .id(day_core::id!(sel_text)),
2518                    label(move || chosen.get()).id(day_core::id!(sel_echo)),
2519                ))
2520                .align(HAlign::Leading)
2521                .spacing(8.0)
2522            })
2523            .drive(|d: Drive| async move {
2524                d.assert_text("sel_text", "Select part of this sentence")
2525                    .await?;
2526                d.assert_text("sel_echo", "").await
2527            })
2528    }
2529
2530    /// The system text scale is a positive number, the same for `Body` through either reader.
2531    #[day_macros::test(day_core)]
2532    fn text_scale_reads() -> Case {
2533        Case::new()
2534            .proves_duty("text_scale")
2535            .page(|| {
2536                label(|| format!("{:.2}", day_core::text_scale()))
2537                    .max_text_scale(1.0)
2538                    .id(day_core::id!(ts_scale))
2539            })
2540            .drive(|d: Drive| async move {
2541                let scale = day_core::text_scale();
2542                d.check(
2543                    scale.is_finite() && scale > 0.0,
2544                    "the text scale is positive",
2545                )?;
2546                d.check_eq(scale, day_core::text_scale_of(Font::Body))?;
2547                d.assert_text("ts_scale", &format!("{scale:.2}")).await
2548            })
2549    }
2550
2551    /// A link is a label: it takes the label's builders, follows a reactive text, and a
2552    /// handler set with `on_link` replaces the default opening.
2553    #[day_macros::test(day_core)]
2554    fn link_takes_label_builders() -> Case {
2555        let title = Signal::new("Read the guide".to_owned());
2556        let handled = Signal::new(String::new());
2557        Case::new()
2558            .proves_duty("open_url")
2559            .page(move || {
2560                column((
2561                    link(title, "https://daybrite.dev/docs")
2562                        .font(Font::Footnote)
2563                        .bold()
2564                        .single_line()
2565                        .truncation(Truncation::Middle)
2566                        .id(day_core::id!(lk_default)),
2567                    link("Handled here", "app:custom")
2568                        .on_link(move |target| handled.set(target.to_owned()))
2569                        .id(day_core::id!(lk_handled)),
2570                    label(move || handled.get()).id(day_core::id!(lk_echo)),
2571                    button("Retitle")
2572                        .action(move || title.set("Open the guide".into()))
2573                        .id(day_core::id!(lk_retitle)),
2574                ))
2575                .align(HAlign::Leading)
2576                .spacing(8.0)
2577            })
2578            .drive(|d: Drive| async move {
2579                d.assert_text("lk_default", "Read the guide").await?;
2580                d.tap("lk_retitle").await?;
2581                d.assert_text("lk_default", "Open the guide").await?;
2582                d.tap("lk_default").await?;
2583                d.assert_opened_url("https://daybrite.dev/docs").await?;
2584                d.tap("lk_handled").await?;
2585                d.assert_text("lk_echo", "app:custom").await
2586            })
2587    }
2588
2589    /// A selectable label still shows its text. Every toolkit implements label selection
2590    /// (`set_selectable`); `Cap::TextSelectable` is the text area's toggle, not this.
2591    #[day_macros::test(day_core)]
2592    fn label_selectable() -> Case {
2593        Case::new()
2594            .proves(kinds::LABEL)
2595            .proves_modifier("selectable")
2596            .proves_duty("set_selectable")
2597            .page(|| label("Copy me").selectable().id(day_core::id!(text)))
2598            .drive(|d: Drive| async move { d.assert_text("text", "Copy me").await })
2599    }
2600
2601    /// A button's title shows natively, and a title bound to a signal follows it.
2602    #[day_macros::test(day_core)]
2603    fn button_title() -> Case {
2604        let saved = Signal::new(false);
2605        Case::new()
2606            .proves(kinds::BUTTON)
2607            .page(move || {
2608                button(move || if saved.get() { "Saved" } else { "Save" }.to_owned())
2609                    .action(move || saved.set(true))
2610                    .id(day_core::id!(save))
2611            })
2612            .drive(|d: Drive| async move {
2613                d.assert_text("save", "Save").await?;
2614                d.tap("save").await?;
2615                d.assert_text("save", "Saved").await
2616            })
2617    }
2618
2619    /// A button's accessibility label, as the platform reports it.
2620    #[day_macros::test(day_core)]
2621    fn button_a11y() -> Case {
2622        Case::new()
2623            .proves(kinds::BUTTON)
2624            .proves_modifier("a11y")
2625            .page(|| {
2626                button("Send")
2627                    .a11y(|a| a.label("Send the message"))
2628                    .id(day_core::id!(send))
2629            })
2630            .drive(|d: Drive| async move { d.a11y_audit(Some("send")).await })
2631    }
2632
2633    /// An app's accessibility label survives a title change on a button with an icon (Windows
2634    /// and Android used to replace it with the new title).
2635    #[day_macros::test(day_core)]
2636    fn button_a11y_survives_title_change() -> Case {
2637        let playing = Signal::new(false);
2638        Case::new()
2639            .proves(kinds::BUTTON)
2640            .proves_modifier("a11y")
2641            .page(move || {
2642                button(move || if playing.get() { "Pause" } else { "Play" }.to_owned())
2643                    .icon(day_spec::Symbol::Play)
2644                    .action(move || playing.set(true))
2645                    .a11y(|a| a.label("Playback"))
2646                    .id(day_core::id!(play))
2647            })
2648            .drive(|d: Drive| async move {
2649                d.a11y_audit(Some("play")).await?;
2650                d.tap("play").await?;
2651                d.assert_text("play", "Pause").await?;
2652                d.a11y_audit(Some("play")).await
2653            })
2654    }
2655
2656    /// A disabled toggle reports itself disabled, natively too, until it is enabled.
2657    #[day_macros::test(day_core)]
2658    fn toggle_disabled() -> Case {
2659        let on = Signal::new(false);
2660        let enabled = Signal::new(false);
2661        Case::new()
2662            .proves(kinds::TOGGLE)
2663            .page(move || {
2664                column((
2665                    toggle(on)
2666                        .enabled(move || enabled.get())
2667                        .id(day_core::id!(switch)),
2668                    button("Enable")
2669                        .action(move || enabled.set(true))
2670                        .id(day_core::id!(enable)),
2671                ))
2672                .spacing(8.0)
2673            })
2674            .drive(|d: Drive| async move {
2675                d.assert_enabled("switch", false).await?;
2676                d.tap("enable").await?;
2677                d.assert_enabled("switch", true).await?;
2678                d.toggle("switch", true).await?;
2679                d.assert_on("switch", true).await
2680            })
2681    }
2682
2683    /// A toggle built disabled from a constant is disabled from the start.
2684    #[day_macros::test(day_core)]
2685    fn toggle_disabled_constant() -> Case {
2686        let on = Signal::new(true);
2687        Case::new()
2688            .proves(kinds::TOGGLE)
2689            .page(move || toggle(on).enabled(false).id(day_core::id!(switch)))
2690            .drive(|d: Drive| async move {
2691                d.assert_enabled("switch", false).await?;
2692                d.assert_on("switch", true).await
2693            })
2694    }
2695
2696    /// A toggle's accessibility label, as the platform reports it.
2697    #[day_macros::test(day_core)]
2698    fn toggle_a11y() -> Case {
2699        let on = Signal::new(false);
2700        Case::new()
2701            .proves(kinds::TOGGLE)
2702            .page(move || {
2703                toggle(on)
2704                    .a11y(|a| a.label("Notifications"))
2705                    .id(day_core::id!(switch))
2706            })
2707            .drive(|d: Drive| async move { d.a11y_audit(Some("switch")).await })
2708    }
2709
2710    /// A disabled slider reports itself disabled, natively too, until it is enabled.
2711    #[day_macros::test(day_core)]
2712    fn slider_disabled() -> Case {
2713        let value = Signal::new(0.5f64);
2714        let enabled = Signal::new(false);
2715        Case::new()
2716            .proves(kinds::SLIDER)
2717            .page(move || {
2718                column((
2719                    slider(value)
2720                        .enabled(move || enabled.get())
2721                        .id(day_core::id!(slider)),
2722                    button("Enable")
2723                        .action(move || enabled.set(true))
2724                        .id(day_core::id!(enable)),
2725                ))
2726                .spacing(8.0)
2727            })
2728            .drive(|d: Drive| async move {
2729                d.assert_enabled("slider", false).await?;
2730                d.tap("enable").await?;
2731                d.assert_enabled("slider", true).await?;
2732                d.set_value("slider", 0.25).await?;
2733                d.assert_value("slider", 0.25).await
2734            })
2735    }
2736
2737    /// A write to a slider's signal moves the native thumb.
2738    #[day_macros::test(day_core)]
2739    fn slider_follows_signal() -> Case {
2740        let value = Signal::new(10.0f64);
2741        Case::new()
2742            .proves(kinds::SLIDER)
2743            .page(move || {
2744                column((
2745                    slider(value).range(0.0..=50.0).id(day_core::id!(slider)),
2746                    button("Set 40")
2747                        .action(move || value.set(40.0))
2748                        .id(day_core::id!(set)),
2749                ))
2750                .spacing(8.0)
2751            })
2752            .drive(|d: Drive| async move {
2753                d.assert_value("slider", 10.0).await?;
2754                d.tap("set").await?;
2755                d.assert_value("slider", 40.0).await
2756            })
2757    }
2758
2759    /// The app moving a slider is not the reader moving it (DESIGN.md §4.4): the native value
2760    /// changes, and nothing comes back through the binding as if a hand had dragged the thumb.
2761    /// A media scrubber that echoed its own position would seek on every tick.
2762    #[day_macros::test(day_core)]
2763    fn slider_set_by_the_app_is_not_echoed() -> Case {
2764        /// A slider value that counts the writes the slider makes to it.
2765        #[derive(Clone, Copy)]
2766        struct Counted {
2767            value: Signal<f64>,
2768            writes: Signal<u32>,
2769        }
2770        impl Binding<f64> for Counted {
2771            fn read(&self) -> f64 {
2772                self.value.get()
2773            }
2774            fn peek(&self) -> f64 {
2775                self.value.get_untracked()
2776            }
2777            fn write(&self, v: f64) {
2778                self.writes.update(|n| *n += 1);
2779                self.value.set(v);
2780            }
2781        }
2782        let value = Signal::new(10.0f64);
2783        let writes = Signal::new(0u32);
2784        Case::new()
2785            .proves(kinds::SLIDER)
2786            .page(move || {
2787                column((
2788                    slider(Counted { value, writes })
2789                        .range(0.0..=50.0)
2790                        .id(day_core::id!(slider)),
2791                    button("Step")
2792                        .action(move || value.update(|v| *v += 7.5))
2793                        .id(day_core::id!(step)),
2794                    label(move || format!("writes {}", writes.get())).id(day_core::id!(writes)),
2795                ))
2796                .spacing(8.0)
2797            })
2798            .drive(|d: Drive| async move {
2799                d.assert_value("slider", 10.0).await?;
2800                for _ in 0..3 {
2801                    d.tap("step").await?;
2802                }
2803                d.assert_value("slider", 32.5).await?;
2804                d.wait_idle().await?;
2805                d.pause(0.3).await?;
2806                d.assert_text("writes", "writes 0").await
2807            })
2808    }
2809
2810    /// A slider's accessibility label, as the platform reports it.
2811    #[day_macros::test(day_core)]
2812    fn slider_a11y() -> Case {
2813        let value = Signal::new(0.5f64);
2814        Case::new()
2815            .proves(kinds::SLIDER)
2816            .page(move || {
2817                slider(value)
2818                    .a11y(|a| a.label("Volume"))
2819                    .id(day_core::id!(slider))
2820            })
2821            .drive(|d: Drive| async move { d.a11y_audit(Some("slider")).await })
2822    }
2823
2824    /// A disabled text field reports itself disabled, natively too, until it is enabled.
2825    #[day_macros::test(day_core)]
2826    fn text_field_disabled() -> Case {
2827        let text = Signal::new("Fixed".to_owned());
2828        let enabled = Signal::new(false);
2829        Case::new()
2830            .proves(kinds::TEXT_FIELD)
2831            .page(move || {
2832                column((
2833                    text_field(text)
2834                        .enabled(move || enabled.get())
2835                        .id(day_core::id!(field)),
2836                    button("Enable")
2837                        .action(move || enabled.set(true))
2838                        .id(day_core::id!(enable)),
2839                ))
2840                .spacing(8.0)
2841            })
2842            .drive(|d: Drive| async move {
2843                d.assert_enabled("field", false).await?;
2844                d.assert_text("field", "Fixed").await?;
2845                d.tap("enable").await?;
2846                d.assert_enabled("field", true).await?;
2847                d.input("field", "Changed").await?;
2848                d.assert_text("field", "Changed").await
2849            })
2850    }
2851
2852    /// A read-only field shows what its signal holds and stays enabled (selectable).
2853    #[day_macros::test(day_core)]
2854    fn text_field_read_only() -> Case {
2855        let text = Signal::new("Shown".to_owned());
2856        Case::new()
2857            .proves(kinds::TEXT_FIELD)
2858            .proves_duty("set_input_traits")
2859            .page(move || {
2860                column((
2861                    text_field(text).read_only(true).id(day_core::id!(field)),
2862                    button("Replace")
2863                        .action(move || text.set("Replaced".into()))
2864                        .id(day_core::id!(replace)),
2865                ))
2866                .spacing(8.0)
2867            })
2868            .drive(|d: Drive| async move {
2869                d.assert_text("field", "Shown").await?;
2870                d.assert_enabled("field", true).await?;
2871                d.tap("replace").await?;
2872                d.assert_text("field", "Replaced").await
2873            })
2874    }
2875
2876    /// Return in a field runs its submit action.
2877    #[day_macros::test(day_core)]
2878    fn text_field_submit() -> Case {
2879        let text = Signal::new(String::new());
2880        let sent = Signal::new(String::new());
2881        Case::new()
2882            .proves(kinds::TEXT_FIELD)
2883            .page(move || {
2884                column((
2885                    text_field(text)
2886                        .submit_label(day_spec::SubmitLabel::Send)
2887                        .on_submit(move || sent.set(text.get_untracked()))
2888                        .id(day_core::id!(field)),
2889                    label(move || sent.get()).id(day_core::id!(sent)),
2890                ))
2891                .spacing(8.0)
2892            })
2893            .drive(|d: Drive| async move {
2894                d.input("field", "hello").await?;
2895                d.submit("field").await?;
2896                d.assert_text("sent", "hello").await
2897            })
2898    }
2899
2900    /// A determinate bar shows its fraction natively and follows its signal.
2901    #[day_macros::test(day_core)]
2902    fn progress_value() -> Case {
2903        let done = Signal::new(0.25f64);
2904        Case::new()
2905            .proves(kinds::PROGRESS)
2906            .page(move || {
2907                column((
2908                    progress(done).id(day_core::id!(bar)),
2909                    button("Advance")
2910                        .action(move || done.set(0.75))
2911                        .id(day_core::id!(advance)),
2912                ))
2913                .spacing(8.0)
2914            })
2915            .drive(|d: Drive| async move {
2916                d.assert_value("bar", 0.25).await?;
2917                d.tap("advance").await?;
2918                d.assert_value("bar", 0.75).await
2919            })
2920    }
2921
2922    /// A spinner shows, and stays shown under reduced motion (it keeps moving).
2923    #[day_macros::test(day_core)]
2924    fn spinner_renders() -> Case {
2925        Case::new()
2926            .proves(kinds::PROGRESS)
2927            .page(|| spinner().id(day_core::id!(spin)))
2928            .drive(|d: Drive| async move {
2929                d.assert_visible("spin").await?;
2930                d.assert_native(
2931                    "spin",
2932                    NativeExpect {
2933                        visible: Some(true),
2934                        ..Default::default()
2935                    },
2936                )
2937                .await
2938            })
2939    }
2940
2941    /// Synthetic fixture: large indicators retain their native size when animation stops.
2942    #[day_macros::test(day_core)]
2943    fn spinner_size_and_animation() -> Case {
2944        Case::new()
2945            .proves(kinds::PROGRESS)
2946            .page(|| {
2947                let running = Signal::new(true);
2948                column((
2949                    spinner()
2950                        .animating(running)
2951                        .id(day_core::id!(spinner_fixture::small)),
2952                    spinner()
2953                        .animating(running)
2954                        .large()
2955                        .id(day_core::id!(spinner_fixture::large)),
2956                    button("Stop fixture")
2957                        .action(move || running.set(false))
2958                        .id(day_core::id!(spinner_fixture::stop)),
2959                ))
2960            })
2961            .drive(|d: Drive| async move {
2962                let sizes = match day_core::toolkit_key() {
2963                    Some("appkit") => Some((20.0, 32.0)),
2964                    Some("uikit") => Some((20.0, 37.0)),
2965                    Some("gtk") => Some((24.0, 48.0)),
2966                    Some("arkui") => Some((32.0, 64.0)),
2967                    Some("xaml" | "winui") => Some((32.0, 48.0)),
2968                    Some("dom") => Some((22.0, 48.0)),
2969                    _ => None, // Qt uses a busy bar; Android uses its theme's dimensions.
2970                };
2971                for stopped in [false, true] {
2972                    if stopped {
2973                        d.tap("spinner_fixture::stop").await?;
2974                    }
2975                    d.assert_visible("spinner_fixture::small").await?;
2976                    d.assert_visible("spinner_fixture::large").await?;
2977                    if let Some((small, large)) = sizes {
2978                        d.assert_size("spinner_fixture::small", small, small)
2979                            .await?;
2980                        d.assert_size("spinner_fixture::large", large, large)
2981                            .await?;
2982                    }
2983                }
2984                Ok(())
2985            })
2986    }
2987
2988    /// A divider takes the width it is given and draws as a thin rule.
2989    #[day_macros::test(day_core)]
2990    fn divider_renders() -> Case {
2991        Case::new()
2992            .proves(kinds::DIVIDER)
2993            .page(|| {
2994                column((
2995                    label("Above"),
2996                    divider().id(day_core::id!(rule)),
2997                    label("Below"),
2998                ))
2999                .spacing(8.0)
3000                .width(200.0)
3001            })
3002            .drive(|d: Drive| async move {
3003                d.assert_visible("rule").await?;
3004                d.assert_frame(
3005                    "rule",
3006                    FrameExpect {
3007                        width: Some(200.0),
3008                        ..Default::default()
3009                    },
3010                )
3011                .await
3012            })
3013    }
3014
3015    /// A vertical divider takes the height it is given, with a width of its own: a hairline
3016    /// down a row, not across it.
3017    #[day_macros::test(day_core)]
3018    fn vertical_divider_fills_height() -> Case {
3019        Case::new()
3020            .proves(kinds::DIVIDER)
3021            .page(|| {
3022                row((
3023                    label("Left"),
3024                    divider().vertical().id(day_core::id!(rule)),
3025                    label("Right"),
3026                ))
3027                .spacing(8.0)
3028                .height(120.0)
3029                .id(day_core::id!(row))
3030            })
3031            .drive(|d: Drive| async move {
3032                d.assert_visible("rule").await?;
3033                // The thickness is the toolkit's (a point or a few); the height is the row's.
3034                d.assert_frame(
3035                    "rule",
3036                    FrameExpect {
3037                        height: Some(120.0),
3038                        ..Default::default()
3039                    },
3040                )
3041                .await
3042            })
3043    }
3044
3045    /// A spacer takes the room between its neighbors.
3046    #[day_macros::test(day_core)]
3047    fn spacer_fills() -> Case {
3048        Case::new()
3049            .proves_modifier("width")
3050            .page(|| {
3051                row((
3052                    // The sized boxes, not the labels' own nodes.
3053                    label("A").width(50.0).wrapper_id(day_core::id!(first)),
3054                    spacer(),
3055                    label("B").width(50.0).wrapper_id(day_core::id!(last)),
3056                ))
3057                .width(300.0)
3058                .wrapper_id(day_core::id!(row))
3059            })
3060            .drive(|d: Drive| async move {
3061                d.assert_frame(
3062                    "last",
3063                    FrameExpect {
3064                        width: Some(50.0),
3065                        x: Some(250.0),
3066                        relative_to: Some("row".into()),
3067                        ..Default::default()
3068                    },
3069                )
3070                .await
3071            })
3072    }
3073
3074    /// A link opens its URL (recorded during a test run, so nothing opens).
3075    #[day_macros::test(day_core)]
3076    fn link_opens_url() -> Case {
3077        Case::new()
3078            .proves_duty("open_url")
3079            .page(|| link("daybrite.dev", "https://daybrite.dev/").id(day_core::id!(link)))
3080            .drive(|d: Drive| async move {
3081                d.assert_text("link", "daybrite.dev").await?;
3082                d.tap("link").await?;
3083                d.assert_opened_url("https://daybrite.dev/").await
3084            })
3085    }
3086}
3087
3088#[cfg(test)]
3089mod button_style_tests {
3090    use super::*;
3091    use day_spec::props::ButtonStyleSpec;
3092
3093    #[test]
3094    fn compact_keeps_a_plain_button_plain() {
3095        assert_eq!(
3096            button("×").plain().compact().native_style,
3097            ButtonStyleSpec::Plain
3098        );
3099        assert_eq!(button("−").compact().native_style, ButtonStyleSpec::Compact);
3100        // The last style asked for still wins otherwise.
3101        assert_eq!(
3102            button("+").compact().plain().native_style,
3103            ButtonStyleSpec::Plain
3104        );
3105    }
3106}