Skip to main content

day_pieces/
stepper.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! `day_pieces::stepper`: a numeric stepper field, a text field with increment/decrement arrows,
5//! bound two-way to any `Binding<f64>` (docs/stepper.md).
6//!
7//! Two idioms, decided automatically. `Native` realizes a leaf where the platform ships the
8//! widget: an `NSTextField` + `NSStepper` composite on AppKit (macOS has no combined
9//! control; the pair is the platform idiom, see any inspector in Keynote), `GtkSpinButton`,
10//! and a `QDoubleSpinBox` shim. `Composed` builds the same field from ordinary Day pieces
11//! (a − button, a text field, a + button), which is what every backend without an arm gets
12//! (uikit, material, arkui, dom, xaml and mock), so the piece works on all nine targets.
13//!
14//! The native leaf also accepts `Event::TextChanged` (a typed value, dayscript's `input:`
15//! step) and `Event::ValueChanged`/`ValueCommitted` (dayscript's `set_value:`), and mirrors
16//! its state into the dayscript probe (`assert_text` sees the display text, `assert_value`
17//! the number); the frontend reports that explicitly, because day-core's probe
18//! inspection only knows the builtin patch types.
19
20use crate::prelude::*;
21use day_core::{BuildCx, Flex, Piece, RNode, with_tree};
22use day_reactive::{Binding, bind_seeded};
23use day_spec::{Event, Support};
24use std::rc::Rc;
25
26pub use day_spec::controls::stepper::*;
27
28/// Which control this stepper renders as (the colorpicker's idiom shape).
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum StepperIdiom {
31    /// The platform's own widget, taken literally: on a toolkit with no renderer it draws Day's
32    /// visible placeholder. Pin it only behind a [`support`] check.
33    Native,
34    /// Day's own − / field / + row, identical on every target.
35    Composed,
36    /// [`Native`](StepperIdiom::Native) where an arm exists, otherwise
37    /// [`Composed`](StepperIdiom::Composed). The default.
38    #[default]
39    Automatic,
40}
41
42/// Whether the compiled backend has a native stepper arm, which is what
43/// [`StepperIdiom::Automatic`] resolves against. [`Support::Native`] on appkit, gtk and qt;
44/// [`Support::Emulated`] everywhere else, where `Automatic` composes the field instead.
45#[must_use]
46pub fn support() -> day_spec::Support {
47    let support = day_core::capability(day_spec::Cap::Stepper);
48    if support == day_spec::Support::Unsupported {
49        day_spec::Support::Emulated
50    } else {
51        support
52    }
53}
54
55type ParseValue = Rc<dyn Fn(&str) -> Option<f64>>;
56
57#[derive(Clone)]
58struct ValueFormat {
59    display: Rc<dyn Fn(f64) -> String>,
60    parse: ParseValue,
61}
62
63/// A stepper field bound two-way to a numeric binding. Build with [`stepper`].
64#[must_use]
65pub struct Stepper<V: Binding<f64>> {
66    value: V,
67    min: f64,
68    max: f64,
69    step: f64,
70    decimals: u32,
71    format: Option<ValueFormat>,
72    idiom: StepperIdiom,
73    key: day_core::ElementId,
74}
75
76/// `stepper(value)`: a numeric field with increment/decrement arrows. `value` is a
77/// `Signal<f64>`, a day-model `Field`, or any other two-way binding; a step click commits one
78/// unit through it (`write_commit`), so under an undo stack each click is one undoable step.
79pub fn stepper<V: Binding<f64>>(value: V) -> Stepper<V> {
80    Stepper {
81        value,
82        min: 0.0,
83        max: 100.0,
84        step: 1.0,
85        decimals: 0,
86        format: None,
87        idiom: StepperIdiom::Automatic,
88        key: day_core::id!(stepper),
89    }
90}
91
92#[day_macros::builder(StepperBuilder)]
93impl<V: Binding<f64>> Stepper<V> {
94    /// The value's bounds (default `0.0..=100.0`). Typed and stepped values both clamp.
95    pub fn range(mut self, range: std::ops::RangeInclusive<f64>) -> Self {
96        self.min = *range.start();
97        self.max = *range.end();
98        self
99    }
100    /// One arrow click's increment (default 1).
101    pub fn step(mut self, step: f64) -> Self {
102        self.step = step.max(f64::EPSILON);
103        self
104    }
105    /// Fraction digits shown (default 0, integers).
106    pub fn decimals(mut self, decimals: u32) -> Self {
107        self.decimals = decimals;
108        self
109    }
110    /// Format the editable text and parse committed edits back to the bound number.
111    /// `display` can return a generated Fluent message (`Into<String>`). Reads made by
112    /// the formatter, including the locale, are reactive. `parse` returns `None` for
113    /// invalid input; non-finite results are rejected and finite results clamp to the range.
114    /// Return or focus loss restores the formatted value, including after a rejected edit.
115    ///
116    /// Custom formatting uses the composed − / field / + control on every toolkit,
117    /// overriding the idiom and `.decimals()` settings. Numeric stepping and scripted
118    /// `set_value` still use the bound number, not the displayed units.
119    pub fn format_with<T: Into<String>>(
120        mut self,
121        display: impl Fn(f64) -> T + 'static,
122        parse: impl Fn(&str) -> Option<f64> + 'static,
123    ) -> Self {
124        self.format = Some(ValueFormat {
125            display: Rc::new(move |v| display(v).into()),
126            parse: Rc::new(parse),
127        });
128        self
129    }
130    /// Use one locale-aware format for display and editing. Uses the composed idiom.
131    pub fn format(self, format: day_localization::NumberFormat) -> Self {
132        self.format_with(move |v| format.format(v), move |s| format.parse(s))
133    }
134
135    /// Which control this renders as (see [`StepperIdiom`]).
136    pub fn idiom(mut self, idiom: StepperIdiom) -> Self {
137        self.idiom = idiom;
138        self
139    }
140    /// Pin the platform's own widget, [`StepperIdiom::Native`], unless `.format()` or `.format_with()` is set.
141    pub fn native(self) -> Self {
142        self.idiom(StepperIdiom::Native)
143    }
144    /// Pin Day's composed row, [`StepperIdiom::Composed`].
145    pub fn composed(self) -> Self {
146        self.idiom(StepperIdiom::Composed)
147    }
148    /// The field's dayscript id (default `"stepper"`; its − and + buttons are
149    /// `<id>-dec` and `<id>-inc`). Names the interactive field in both idioms, rather than
150    /// the composed layout row that a generic `Decorate::id` would tag.
151    pub fn id(mut self, id: day_core::ElementId) -> Self {
152        self.key = id;
153        self
154    }
155}
156
157impl<V: Binding<f64>> Piece for Stepper<V> {
158    fn build(self, cx: &mut BuildCx) -> RNode {
159        let native = match self.idiom {
160            StepperIdiom::Composed => false,
161            StepperIdiom::Native => true,
162            StepperIdiom::Automatic => support() == Support::Native,
163        };
164        if native && self.format.is_none() {
165            build_native(self, cx)
166        } else {
167            build_composed(self, cx)
168        }
169    }
170}
171
172/// The native idiom: one leaf of [`KIND`], bound two-way, probe kept current by hand.
173fn build_native<V: Binding<f64>>(stepper: Stepper<V>, cx: &mut BuildCx) -> RNode {
174    let Stepper {
175        value,
176        min,
177        max,
178        step,
179        decimals,
180        key,
181        ..
182    } = stepper;
183    let clamp = move |v: f64| v.clamp(min, max);
184    let initial = clamp(value.peek());
185    let node = cx.leaf(
186        KIND,
187        &StepperProps {
188            value: initial,
189            min,
190            max,
191            step,
192            decimals,
193        },
194        Flex::default(),
195    );
196    // The leaf's dayscript id: one `.key` drives both idioms (`Decorate::id` on the piece
197    // would tag the wrapper the composed row returns, which no toolkit realizes).
198    with_tree(|t| t.set_id(node, key.as_str().to_owned()));
199    let note_probe = move |v: f64| {
200        with_tree(|t| t.set_probe_value(node, v, fmt_value(v, decimals)));
201    };
202    note_probe(initial);
203    // App writes → the native widget. Every arm no-ops on an unchanged value, so a step
204    // echoing back through the binding never loops.
205    {
206        let v = value.clone();
207        bind_seeded(
208            initial,
209            move || clamp(v.read()),
210            move |val: &f64| {
211                with_tree(|t| t.patch(node, Box::new(StepperPatch::SetValue(*val)), false));
212                note_probe(*val);
213            },
214        );
215    }
216    // Native steps and typed edits (`Custom`), dayscript's `input:` (`TextChanged`) and
217    // `set_value:` (`ValueChanged`/`ValueCommitted`) → the binding. A step or a settled edit
218    // is a commit, one undoable unit per click, exactly like a built-in slider's committed
219    // value; only `ValueChanged` stays a preview.
220    cx.on(node, move |ev| {
221        match ev {
222            // Other custom events include SYNTHESIZED_TEXT, the paint half of scripted
223            // typing. TextChanged below owns that edit; accepting both commits it twice.
224            Event::Custom { tag, text, .. } if *tag == VALUE_TAG || tag.is_empty() => {
225                if let Ok(v) = text.trim().parse::<f64>() {
226                    value.write_commit(clamp(v));
227                }
228            }
229            Event::TextChanged(s) => {
230                if let Ok(v) = s.trim().parse::<f64>() {
231                    value.write_commit(clamp(v));
232                }
233            }
234            Event::ValueChanged(v) => value.write_preview(clamp(*v)),
235            Event::ValueCommitted(v) => value.write_commit(clamp(*v)),
236            _ => {}
237        }
238    });
239    node
240}
241
242/// The field's binding: reads format the bound value, keystrokes are previews the value
243/// must not follow (half-typed numbers are not values), and the committed text (Return,
244/// focus loss, dayscript `submit:`) parses, clamps, and writes through.
245struct FieldBinding<V: Binding<f64>> {
246    value: V,
247    min: f64,
248    max: f64,
249    decimals: u32,
250    format: Option<ValueFormat>,
251}
252impl<V: Binding<f64>> Clone for FieldBinding<V> {
253    fn clone(&self) -> Self {
254        FieldBinding {
255            value: self.value.clone(),
256            min: self.min,
257            max: self.max,
258            decimals: self.decimals,
259            format: self.format.clone(),
260        }
261    }
262}
263impl<V: Binding<f64>> Binding<String> for FieldBinding<V> {
264    fn read(&self) -> String {
265        let value = self.value.read().clamp(self.min, self.max);
266        match &self.format {
267            Some(format) => (format.display)(value),
268            None => fmt_value(value, self.decimals),
269        }
270    }
271    fn peek(&self) -> String {
272        day_reactive::untrack(|| self.read())
273    }
274    fn write(&self, s: String) {
275        self.write_commit(s);
276    }
277    fn write_preview(&self, _s: String) {}
278    fn write_commit(&self, s: String) {
279        let parsed = match &self.format {
280            Some(format) => (format.parse)(&s).filter(|v| v.is_finite()),
281            None => s.trim().parse::<f64>().ok().filter(|v| v.is_finite()),
282        };
283        if let Some(v) = parsed {
284            self.value.write_commit(v.clamp(self.min, self.max));
285        }
286    }
287}
288
289/// The composed idiom: a − button, a text field and a + button, ordinary pieces on every target.
290fn build_composed<V: Binding<f64>>(stepper: Stepper<V>, cx: &mut BuildCx) -> RNode {
291    let Stepper {
292        value,
293        min,
294        max,
295        step,
296        decimals,
297        format,
298        key,
299        ..
300    } = stepper;
301    let clamp = move |v: f64| v.clamp(min, max);
302    let stepped = {
303        let value = value.clone();
304        move |dir: f64| {
305            let v = clamp(value.peek() + dir * step);
306            value.write_commit(v);
307        }
308    };
309    let dec = {
310        let stepped = stepped.clone();
311        move || stepped(-1.0)
312    };
313    let inc = move || stepped(1.0);
314
315    // Glyph-sized buttons: a stock Material button is 88 dp wide, and two of them beside the
316    // field made the composed stepper a 240 dp control that clipped in a 280 dp inspector.
317    // The buttons carry ids derived from the key, so a script can press them as a person would.
318    let (dec_id, inc_id) = (
319        day_core::id!(stepper_decrement, key.as_str()),
320        day_core::id!(stepper_increment, key.as_str()),
321    );
322    // dayscript's `set_value:` lands `ValueChanged`/`ValueCommitted` on the id, which the
323    // field itself has no use for (it carries text); the composed idiom takes them the way
324    // the native leaf does, so a scripted value reaches the binding on every toolkit.
325    // The id goes on the field itself, before the width (which wraps it in a frame node), so
326    // the events land on the node the handler is on.
327    let binding = FieldBinding {
328        value: value.clone(),
329        min,
330        max,
331        decimals,
332        format,
333    };
334    // A rejected edit or a differently spelled version of the same number does not
335    // change the signal. Restore the formatted text explicitly at the end of editing.
336    let restore = binding.format.as_ref().map(|_| {
337        let binding = binding.clone();
338        Rc::new(move || binding.peek()) as Rc<dyn Fn() -> String>
339    });
340    let target = Rc::new(std::cell::Cell::new(None));
341    let field_target = target.clone();
342    let field = Valued {
343        inner: text_field(binding).id(key),
344        value,
345        clamp,
346        restore,
347    };
348    let field = day_core::piece_fn(move |cx| {
349        let node = field.build(cx);
350        field_target.set(Some(node));
351        node
352    })
353    .width(56.0);
354    let row = row((
355        button("−").compact().action(dec).id(dec_id),
356        field,
357        button("+").compact().action(inc).id(inc_id),
358    ))
359    .spacing(4.0)
360    .align(VAlign::Center)
361    .build(cx);
362    with_tree(|tree| tree.set_element_target(row, target.get().expect("the field was built")));
363    row
364}
365
366/// An editable number without step buttons. Edits commit on Return or focus loss.
367/// Incomplete or invalid input leaves the bound value unchanged and restores its display.
368#[must_use]
369pub struct NumberField<V: Binding<f64>> {
370    value: V,
371    min: f64,
372    max: f64,
373    format: day_localization::NumberFormat,
374    key: day_core::ElementId,
375    placeholder: Option<crate::TextSource>,
376    enabled: Reactive<bool>,
377    read_only: Reactive<bool>,
378    purpose: day_spec::InputPurpose,
379    submit_label: day_spec::SubmitLabel,
380    on_submit: Option<Rc<dyn Fn()>>,
381}
382
383/// A locale-aware numeric text field, initially using [`NumberFormat::decimal`].
384pub fn number_field<V: Binding<f64>>(value: V) -> NumberField<V> {
385    NumberField {
386        value,
387        min: -f64::MAX,
388        max: f64::MAX,
389        format: NumberFormat::decimal(),
390        key: day_core::id!(number_field),
391        placeholder: None,
392        enabled: Reactive::Const(true),
393        read_only: Reactive::Const(false),
394        purpose: day_spec::InputPurpose::Decimal,
395        submit_label: day_spec::SubmitLabel::Return,
396        on_submit: None,
397    }
398}
399
400#[day_macros::builder(NumberFieldBuilder)]
401impl<V: Binding<f64>> NumberField<V> {
402    /// Whether the field accepts input and focus. Reactive; defaults to true.
403    pub fn enabled<M>(mut self, enabled: impl IntoReactive<bool, M>) -> Self {
404        self.enabled = enabled.into_reactive();
405        self
406    }
407    /// Allow selection and copying while preventing edits. Reactive; defaults to false.
408    pub fn read_only<M>(mut self, read_only: impl IntoReactive<bool, M>) -> Self {
409        self.read_only = read_only.into_reactive();
410        self
411    }
412    /// Localized hint shown when the editable text is empty.
413    pub fn placeholder<M>(mut self, text: impl IntoText<M>) -> Self {
414        self.placeholder = Some(text.into_text());
415        self
416    }
417    /// The keyboard purpose. Defaults to Decimal; use Number for unsigned integer entry.
418    pub fn input_purpose(mut self, purpose: day_spec::InputPurpose) -> Self {
419        self.purpose = purpose;
420        self
421    }
422    /// The label on the keyboard's submit key.
423    pub fn submit_label(mut self, label: day_spec::SubmitLabel) -> Self {
424        self.submit_label = label;
425        self
426    }
427    /// Run after the numeric edit has committed and its formatted text has been restored.
428    pub fn on_submit(mut self, action: impl Fn() + 'static) -> Self {
429        self.on_submit = Some(Rc::new(action));
430        self
431    }
432
433    /// Clamp committed input to this inclusive range.
434    pub fn range(mut self, range: std::ops::RangeInclusive<f64>) -> Self {
435        self.min = *range.start();
436        self.max = *range.end();
437        self
438    }
439    /// Set the format shared by display and input parsing.
440    pub fn format(mut self, format: day_localization::NumberFormat) -> Self {
441        self.format = format;
442        self
443    }
444    /// Identify the editable native text field for UI automation.
445    pub fn id(mut self, key: day_core::ElementId) -> Self {
446        self.key = key;
447        self
448    }
449}
450
451impl<V: Binding<f64>> Piece for NumberField<V> {
452    fn build(self, cx: &mut BuildCx) -> RNode {
453        let Self {
454            value,
455            min,
456            max,
457            format,
458            key,
459            placeholder,
460            enabled,
461            read_only,
462            purpose,
463            submit_label,
464            on_submit,
465        } = self;
466        let binding = FieldBinding {
467            value: value.clone(),
468            min,
469            max,
470            decimals: 0,
471            format: Some(ValueFormat {
472                display: Rc::new(move |v| format.format(v)),
473                parse: Rc::new(move |s| format.parse(s)),
474            }),
475        };
476        let restore = binding.clone();
477        let field_enabled = enabled.clone();
478        let field_read_only = read_only.clone();
479        let mut field = text_field(binding)
480            .enabled(move || field_enabled.get())
481            .read_only(move || field_read_only.get())
482            .input_purpose(purpose)
483            .submit_label(submit_label);
484        if let Some(placeholder) = placeholder {
485            field = field.placeholder(placeholder);
486        }
487        let node = Valued {
488            inner: field.id(key),
489            value,
490            clamp: move |v: f64| v.clamp(min, max),
491            restore: Some(Rc::new(move || restore.peek())),
492        }
493        .build(cx);
494        if let Some(on_submit) = on_submit {
495            cx.on(node, move |event| {
496                if matches!(event, Event::Submitted)
497                    && enabled.get_untracked()
498                    && !read_only.get_untracked()
499                {
500                    on_submit();
501                }
502            });
503        }
504        node
505    }
506}
507
508/// The composed field with the numeric value events the native leaf answers (`set_value:`).
509struct Valued<P: Piece, V: Binding<f64>, C: Fn(f64) -> f64 + 'static> {
510    inner: P,
511    value: V,
512    clamp: C,
513    restore: Option<Rc<dyn Fn() -> String>>,
514}
515
516impl<P: Piece, V: Binding<f64>, C: Fn(f64) -> f64 + 'static> Piece for Valued<P, V, C> {
517    fn build(self, cx: &mut BuildCx) -> RNode {
518        let Valued {
519            inner,
520            value,
521            clamp,
522            restore,
523        } = self;
524        let node = inner.build(cx);
525        cx.on(node, move |ev| match ev {
526            Event::ValueChanged(v) => value.write_preview(clamp(*v)),
527            Event::ValueCommitted(v) => value.write_commit(clamp(*v)),
528            Event::Submitted | Event::FocusChanged(false) => {
529                if let Some(display) = &restore {
530                    let text = display();
531                    with_tree(|t| {
532                        t.patch(
533                            node,
534                            Box::new(day_spec::props::TextFieldPatch::Text {
535                                text,
536                                from_native: false,
537                            }),
538                            false,
539                        );
540                    });
541                }
542            }
543            _ => {}
544        });
545        node
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552    use day_mock::MockToolkit;
553    use day_reactive::{Signal, flush_sync};
554    use day_spec::WindowOptions;
555    use std::cell::RefCell;
556    use std::rc::Rc;
557
558    /// Records binding writes even when the value is unchanged: a duplicate commit creates
559    /// a second history unit in bindings such as Day-Sketch's inspector.
560    #[derive(Clone)]
561    struct Writes {
562        value: Signal<f64>,
563        events: Rc<RefCell<Vec<(&'static str, f64)>>>,
564    }
565
566    impl Binding<f64> for Writes {
567        fn read(&self) -> f64 {
568            self.value.get()
569        }
570        fn peek(&self) -> f64 {
571            self.value.get_untracked()
572        }
573        fn write(&self, value: f64) {
574            self.write_commit(value);
575        }
576        fn write_preview(&self, value: f64) {
577            self.events.borrow_mut().push(("preview", value));
578            self.value.set(value);
579        }
580        fn write_commit(&self, value: f64) {
581            self.events.borrow_mut().push(("commit", value));
582            self.value.set(value);
583        }
584    }
585
586    fn boot(native: bool) -> (Writes, RNode) {
587        day_core::uninstall_tree();
588        let writes = Writes {
589            value: Signal::new(3.0),
590            events: Rc::default(),
591        };
592        let binding = writes.clone();
593        let (mock, _) = MockToolkit::new();
594        day_core::launch_with(mock, WindowOptions::default(), move || {
595            let field = stepper(binding).range(0.0..=10.0);
596            if native {
597                field.native()
598            } else {
599                field.composed()
600            }
601            .id(day_core::id!(fixture_stepper))
602            .any()
603        });
604        let node = with_tree(|t| t.find_by_id(day_core::id!(fixture_stepper).as_str())).unwrap();
605        (writes, node)
606    }
607
608    fn emit(node: RNode, event: Event) {
609        day_core::enqueue_event(day_core::rnode_to_id(node), event);
610        flush_sync();
611    }
612
613    #[test]
614    fn localized_numeric_controls_preserve_drafts_commit_once_and_refresh_locale() {
615        for field_only in [false, true] {
616            day_core::uninstall_tree();
617            let writes = Writes {
618                value: Signal::new(0.4),
619                events: Rc::default(),
620            };
621            let binding = writes.clone();
622            let (mock, probe) = MockToolkit::new();
623            day_core::launch_with(mock, WindowOptions::default(), move || {
624                if field_only {
625                    number_field(binding)
626                        .format(NumberFormat::percent().fraction_digits(1))
627                        .range(0.0..=1.0)
628                        .id(day_core::id!(numeric_fixture))
629                        .any()
630                } else {
631                    stepper(binding)
632                        .format(NumberFormat::percent().fraction_digits(1))
633                        .range(0.0..=1.0)
634                        .id(day_core::id!(numeric_fixture))
635                        .any()
636                }
637            });
638            day_localization::locale().set("de".to_owned());
639            flush_sync();
640            let node = with_tree(|t| t.find_by_id("numeric_fixture")).unwrap();
641            let display = || probe.find_by_kind("day.text_field")[0].1.text.clone();
642            assert_eq!(
643                display(),
644                NumberFormat::percent()
645                    .fraction_digits(1)
646                    .format_in("de", 0.4)
647            );
648            emit(node, Event::TextChanged("-".into()));
649            assert_eq!(writes.peek(), 0.4);
650            assert!(writes.events.borrow().is_empty());
651            emit(node, Event::TextChanged("72,5 %".into()));
652            emit(node, Event::Submitted);
653            emit(node, Event::FocusChanged(false));
654            assert_eq!(*writes.events.borrow(), [("commit", 0.725)]);
655            emit(node, Event::TextChanged("1.5".into())); // Invalid German grouping.
656            emit(node, Event::Submitted);
657            assert_eq!(writes.peek(), 0.725);
658            assert_eq!(writes.events.borrow().len(), 1);
659            day_localization::locale().set("ar-EG".to_owned());
660            flush_sync();
661            assert_eq!(
662                display(),
663                NumberFormat::percent()
664                    .fraction_digits(1)
665                    .format_in("ar-EG", 0.725)
666            );
667            emit(node, Event::TextChanged("١٥٠٪".into()));
668            emit(node, Event::FocusChanged(false));
669            assert_eq!(writes.peek(), 1.0);
670        }
671        day_localization::locale().set("en".to_owned());
672    }
673
674    #[test]
675    fn formatted_edits_commit_once_clamp_and_restore_rejected_text() {
676        for idiom in [
677            StepperIdiom::Automatic,
678            StepperIdiom::Native,
679            StepperIdiom::Composed,
680        ] {
681            day_core::uninstall_tree();
682            let writes = Writes {
683                value: Signal::new(0.4),
684                events: Rc::default(),
685            };
686            let binding = writes.clone();
687            let (mock, probe) = MockToolkit::new();
688            day_core::launch_with(mock, WindowOptions::default(), move || {
689                // Synthetic formatting fixture; the website app exercises real Fluent messages.
690                stepper(binding)
691                    .range(0.0..=1.0)
692                    .step(0.01)
693                    .format_with(
694                        |v| format!("{:.0}%", v * 100.0),
695                        |text| {
696                            text.trim()
697                                .trim_end_matches('%')
698                                .trim()
699                                .parse::<f64>()
700                                .ok()
701                                .map(|v| v / 100.0)
702                        },
703                    )
704                    .idiom(idiom)
705                    .id(day_core::id!(fixture_stepper))
706                    .any()
707            });
708            let node = with_tree(|t| t.find_by_id("fixture_stepper")).unwrap();
709            let text = || probe.find_by_kind("day.text_field")[0].1.text.clone();
710            assert_eq!(text(), "40%");
711            assert!(
712                probe.find_by_kind(KIND).is_empty(),
713                "custom text always uses the composed control"
714            );
715            emit(node, Event::TextChanged("73%".into()));
716            assert!(
717                writes.events.borrow().is_empty(),
718                "unfinished typing is not a numeric edit"
719            );
720            emit(node, Event::Submitted);
721            emit(node, Event::FocusChanged(false));
722            assert_eq!(*writes.events.borrow(), [("commit", 0.73)]);
723            assert_eq!(text(), "73%");
724            for invalid in ["invalid", "NaN%", "inf%", "-inf%"] {
725                emit(node, Event::TextChanged(invalid.into()));
726                emit(node, Event::Submitted);
727                assert_eq!(writes.peek(), 0.73);
728                assert_eq!(text(), "73%");
729                assert_eq!(writes.events.borrow().len(), 1);
730            }
731            emit(node, Event::TextChanged("150%".into()));
732            emit(node, Event::FocusChanged(false));
733            assert_eq!(writes.peek(), 1.0);
734            assert_eq!(text(), "100%");
735            emit(node, Event::TextChanged("100".into()));
736            emit(node, Event::Submitted);
737            assert_eq!(
738                text(),
739                "100%",
740                "canonical text is restored even when the number is unchanged"
741            );
742            assert_eq!(writes.events.borrow().len(), 3);
743        }
744    }
745
746    #[test]
747    fn formatted_reads_track_dependencies_and_numeric_events_keep_bound_units() {
748        day_core::uninstall_tree();
749        let value = Signal::new(0.4);
750        let suffix = Signal::new("%");
751        let (mock, probe) = MockToolkit::new();
752        day_core::launch_with(mock, WindowOptions::default(), move || {
753            stepper(value)
754                .range(0.0..=1.0)
755                .step(0.01)
756                .format_with(
757                    move |v| format!("{:.0}{}", v * 100.0, suffix.get()),
758                    |_| None,
759                )
760                .id(day_core::id!(fixture_stepper))
761                .any()
762        });
763        let text = || probe.find_by_kind("day.text_field")[0].1.text.clone();
764        suffix.set(" %");
765        flush_sync();
766        assert_eq!(
767            text(),
768            "40 %",
769            "formatter dependencies update without a numeric change"
770        );
771        let node = with_tree(|t| t.find_by_id("fixture_stepper")).unwrap();
772        emit(node, Event::ValueChanged(0.6));
773        assert_eq!(value.get(), 0.6);
774        assert_eq!(text(), "60 %");
775        emit(node, Event::ValueCommitted(0.7));
776        assert_eq!(text(), "70 %");
777        let inc = day_core::id!(stepper_increment, "fixture_stepper");
778        let button = with_tree(|t| t.find_by_id(inc.as_str())).unwrap();
779        emit(button, Event::Pressed);
780        assert!((value.get() - 0.71).abs() < 1e-10);
781        assert_eq!(text(), "71 %");
782    }
783
784    #[test]
785    fn scripted_typing_commits_once_in_both_idioms() {
786        for native in [true, false] {
787            let (writes, node) = boot(native);
788            // Use the actual dayscript input path: a native leaf receives SYNTHESIZED_TEXT
789            // to paint the characters, followed by TextChanged for the edit itself.
790            day_core::synthesize_text(node, "7".into());
791            flush_sync();
792            emit(node, Event::Submitted);
793            assert_eq!(writes.peek(), 7.0);
794            assert_eq!(
795                *writes.events.borrow(),
796                [("commit", 7.0)],
797                "native={native}"
798            );
799        }
800    }
801
802    #[test]
803    fn native_custom_events_accept_only_value_tags_and_the_legacy_bridge() {
804        let (writes, node) = boot(true);
805        emit(node, Event::custom(day_core::SYNTHESIZED_TEXT, "8"));
806        emit(node, Event::custom("fixture:unrelated", "9"));
807        assert_eq!(writes.peek(), 3.0);
808        assert!(writes.events.borrow().is_empty());
809        emit(node, Event::custom(VALUE_TAG, "6"));
810        emit(node, Event::custom("", "12"));
811        assert_eq!(*writes.events.borrow(), [("commit", 6.0), ("commit", 10.0)]);
812        assert_eq!(writes.peek(), 10.0);
813    }
814
815    #[test]
816    fn scripted_values_keep_the_preview_and_commit_boundary() {
817        for native in [true, false] {
818            let (writes, node) = boot(native);
819            emit(node, Event::ValueChanged(12.0));
820            emit(node, Event::ValueCommitted(12.0));
821            assert_eq!(
822                *writes.events.borrow(),
823                [("preview", 10.0), ("commit", 10.0)],
824                "native={native}"
825            );
826            assert_eq!(writes.peek(), 10.0);
827        }
828    }
829}
830
831/// The stepper's conformance cases (docs/testing.md), in both idioms.
832#[cfg(feature = "conformance")]
833pub mod conformance {
834    #[day_macros::test(day_core)]
835    fn localized_numeric_input() -> day_core::conformance::Case {
836        use crate::prelude::*;
837        let value = Signal::new(0.4);
838        let submitted = Signal::new(0.0);
839        let enabled = Signal::new(true);
840        Case::new()
841            .proves(day_spec::kinds::TEXT_FIELD)
842            .page(move || {
843                column((
844                    stepper(value)
845                        .padding(4.0)
846                        .range(0.0..=1.0)
847                        .format(NumberFormat::percent())
848                        .id(day_core::id!(percent_stepper)),
849                    number_field(value)
850                        .padding(4.0)
851                        .range(0.0..=1.0)
852                        .format(NumberFormat::percent())
853                        .placeholder("Fixture percentage")
854                        .submit_label(SubmitLabel::Done)
855                        .enabled(enabled)
856                        .on_submit(move || submitted.set(value.get()))
857                        .id(day_core::id!(percent_field)),
858                    label(move || NumberFormat::percent().format(submitted.get()))
859                        .id(day_core::id!(percent_submitted)),
860                    button("Disable fixture field")
861                        .action(move || enabled.set(false))
862                        .id(day_core::id!(percent_disable)),
863                ))
864            })
865            .drive(|d: Drive| async move {
866                d.input("percent_field", "73%").await?;
867                d.submit("percent_field").await?;
868                d.assert_text("percent_submitted", &NumberFormat::percent().format(0.73))
869                    .await?;
870                d.assert_text("percent_stepper", &NumberFormat::percent().format(0.73))
871                    .await?;
872                d.input("percent_stepper", "invalid").await?;
873                d.submit("percent_stepper").await?;
874                d.assert_text("percent_stepper", &NumberFormat::percent().format(0.73))
875                    .await?;
876                d.set_value("percent_stepper", 0.4).await?;
877                d.assert_text("percent_field", &NumberFormat::percent().format(0.4))
878                    .await?;
879                d.tap("percent_disable").await?;
880                d.assert_enabled("percent_field", false).await
881            })
882    }
883
884    use crate::*;
885    use day_core::AnyPiece;
886    use day_core::conformance::{Case, Drive};
887    use day_reactive::Signal;
888
889    use super::{KIND, stepper};
890
891    fn page(composed: bool) -> AnyPiece {
892        let value = Signal::new(3.0f64);
893        // Each idiom asked for explicitly: a toolkit with no native arm renders a placeholder
894        // for `.native()`, and the native cases skip there.
895        let field = stepper(value)
896            .range(0.0..=10.0)
897            .id(day_core::id!(stepper::count));
898        column((
899            label(move || format!("value {}", value.get())).id(day_core::id!(stepper::value)),
900            if composed {
901                field.composed().any()
902            } else {
903                field.native().any()
904            },
905        ))
906        .any()
907    }
908
909    /// A value set on the stepper reaches its binding and shows in the field.
910    #[day_macros::test(day_core)]
911    fn stepper_sets_value() -> Case {
912        Case::new()
913            .proves(KIND)
914            .page(|| page(false))
915            .drive(|d: Drive| async move {
916                d.assert_text("stepper::count", "3").await?;
917                d.set_value("stepper::count", 7.0).await?;
918                d.assert_text("stepper::value", "value 7").await?;
919                d.assert_text("stepper::count", "7").await
920            })
921    }
922
923    /// The range holds: a value past the top lands on it.
924    #[day_macros::test(day_core)]
925    fn stepper_clamps_to_range() -> Case {
926        Case::new()
927            .proves(KIND)
928            .page(|| page(false))
929            .drive(|d: Drive| async move {
930                d.set_value("stepper::count", 42.0).await?;
931                d.assert_text("stepper::value", "value 10").await
932            })
933    }
934
935    /// The composed idiom (− / field / +) behaves the same on every toolkit.
936    #[day_macros::test(day_core)]
937    fn stepper_composed_sets_value() -> Case {
938        // Proves no kind: the composed idiom is ordinary pieces, never the native leaf.
939        Case::new()
940            .page(|| page(true))
941            .drive(|d: Drive| async move {
942                // Typed text commits on submit, as Return does.
943                d.input("stepper::count", "5").await?;
944                d.submit("stepper::count").await?;
945                d.assert_text("stepper::value", "value 5").await?;
946                d.tap(day_core::id!(stepper_increment, "stepper::count").as_str())
947                    .await?;
948                d.assert_text("stepper::value", "value 6").await?;
949                d.assert_text("stepper::count", "6").await?;
950                // A scripted value lands on the field's id, as it does on the native leaf.
951                d.set_value("stepper::count", 9.0).await?;
952                d.assert_text("stepper::value", "value 9").await?;
953                d.assert_text("stepper::count", "9").await
954            })
955    }
956}