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