day-pieces 0.7.3

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! day_pieces::stepper: a numeric stepper field, a text field with increment/decrement arrows,
//! bound two-way to any `Binding<f64>` (docs/stepper.md).
//!
//! Two idioms, decided automatically. `Native` realizes a leaf where the platform ships the
//! widget: an `NSTextField` + `NSStepper` composite on AppKit (macOS has no combined
//! control; the pair is the platform idiom, see any inspector in Keynote), `GtkSpinButton`,
//! and a `QDoubleSpinBox` shim. `Composed` builds the same field from ordinary Day pieces
//! (a − button, a text field, a + button), which is what every backend without an arm gets
//! (uikit, material, arkui, dom, xaml and mock), so the piece works on all nine targets.
//!
//! The native leaf also accepts `Event::TextChanged` (a typed value, dayscript's `input:`
//! step) and `Event::ValueChanged`/`ValueCommitted` (dayscript's `set_value:`), and mirrors
//! its state into the dayscript probe (`assert_text` sees the display text, `assert_value`
//! the number); the frontend reports that explicitly, because day-core's probe
//! inspection only knows the builtin patch types.

use crate::prelude::*;
use day_core::{BuildCx, Flex, Piece, RNode, with_tree};
use day_reactive::{Binding, bind_seeded};
use day_spec::{Event, Support};
use std::rc::Rc;

pub use day_spec::controls::stepper::*;

/// Which control this stepper renders as (the colorpicker's idiom shape).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StepperIdiom {
    /// The platform's own widget, taken literally: on a toolkit with no renderer it draws Day's
    /// visible placeholder. Pin it only behind a [`support`] check.
    Native,
    /// Day's own − / field / + row, identical on every target.
    Composed,
    /// [`Native`](StepperIdiom::Native) where an arm exists, otherwise
    /// [`Composed`](StepperIdiom::Composed). The default.
    #[default]
    Automatic,
}

/// Whether the compiled backend has a native stepper arm, which is what
/// [`StepperIdiom::Automatic`] resolves against. [`Support::Native`] on appkit, gtk and qt;
/// [`Support::Emulated`] everywhere else, where `Automatic` composes the field instead.
pub fn support() -> day_spec::Support {
    let support = day_core::capability(day_spec::Cap::Stepper);
    if support == day_spec::Support::Unsupported {
        day_spec::Support::Emulated
    } else {
        support
    }
}

/// The display form of `v` at `decimals` fraction digits: what the field shows, what the
/// probe's text reports, and what the composed field parses back.
pub fn fmt_value(v: f64, decimals: u32) -> String {
    format!("{v:.prec$}", prec = decimals as usize)
}

type ParseValue = Rc<dyn Fn(&str) -> Option<f64>>;

#[derive(Clone)]
struct ValueFormat {
    display: Rc<dyn Fn(f64) -> String>,
    parse: ParseValue,
}

/// A stepper field bound two-way to a numeric binding. Build with [`stepper`].
pub struct Stepper<V: Binding<f64>> {
    value: V,
    min: f64,
    max: f64,
    step: f64,
    decimals: u32,
    format: Option<ValueFormat>,
    idiom: StepperIdiom,
    key: day_core::ElementId,
}

/// `stepper(value)`: a numeric field with increment/decrement arrows. `value` is a
/// `Signal<f64>`, a day-model `Field`, or any other two-way binding; a step click commits one
/// unit through it (`write_commit`), so under an undo stack each click is one undoable step.
pub fn stepper<V: Binding<f64>>(value: V) -> Stepper<V> {
    Stepper {
        value,
        min: 0.0,
        max: 100.0,
        step: 1.0,
        decimals: 0,
        format: None,
        idiom: StepperIdiom::Automatic,
        key: day_core::id!(stepper),
    }
}

#[day_macros::builder(StepperBuilder)]
impl<V: Binding<f64>> Stepper<V> {
    /// The value's bounds (default `0.0..=100.0`). Typed and stepped values both clamp.
    pub fn range(mut self, range: std::ops::RangeInclusive<f64>) -> Self {
        self.min = *range.start();
        self.max = *range.end();
        self
    }
    /// One arrow click's increment (default 1).
    pub fn step(mut self, step: f64) -> Self {
        self.step = step.max(f64::EPSILON);
        self
    }
    /// Fraction digits shown (default 0, integers).
    pub fn decimals(mut self, decimals: u32) -> Self {
        self.decimals = decimals;
        self
    }
    /// Format the editable text and parse committed edits back to the bound number.
    /// `display` can return a generated Fluent message (`Into<String>`). Reads made by
    /// the formatter, including the locale, are reactive. `parse` returns `None` for
    /// invalid input; non-finite results are rejected and finite results clamp to the range.
    /// Return or focus loss restores the formatted value, including after a rejected edit.
    ///
    /// Custom formatting uses the composed − / field / + control on every toolkit,
    /// overriding the idiom and `.decimals()` settings. Numeric stepping and scripted
    /// `set_value` still use the bound number, not the displayed units.
    pub fn format_with<T: Into<String>>(
        mut self,
        display: impl Fn(f64) -> T + 'static,
        parse: impl Fn(&str) -> Option<f64> + 'static,
    ) -> Self {
        self.format = Some(ValueFormat {
            display: Rc::new(move |v| display(v).into()),
            parse: Rc::new(parse),
        });
        self
    }
    /// Use one locale-aware format for display and editing. Uses the composed idiom.
    pub fn format(self, format: day_localization::NumberFormat) -> Self {
        self.format_with(move |v| format.format(v), move |s| format.parse(s))
    }

    /// Which control this renders as (see [`StepperIdiom`]).
    pub fn idiom(mut self, idiom: StepperIdiom) -> Self {
        self.idiom = idiom;
        self
    }
    /// Pin the platform's own widget, [`StepperIdiom::Native`], unless `.format()` or `.format_with()` is set.
    pub fn native(self) -> Self {
        self.idiom(StepperIdiom::Native)
    }
    /// Pin Day's composed row, [`StepperIdiom::Composed`].
    pub fn composed(self) -> Self {
        self.idiom(StepperIdiom::Composed)
    }
    /// The field's dayscript id (default `"stepper"`; its − and + buttons are
    /// `<id>-dec` and `<id>-inc`). Names the interactive field in both idioms, rather than
    /// the composed layout row that a generic `Decorate::id` would tag.
    pub fn id(mut self, id: day_core::ElementId) -> Self {
        self.key = id;
        self
    }
}

impl<V: Binding<f64>> Piece for Stepper<V> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let native = match self.idiom {
            StepperIdiom::Composed => false,
            StepperIdiom::Native => true,
            StepperIdiom::Automatic => support() == Support::Native,
        };
        if native && self.format.is_none() {
            build_native(self, cx)
        } else {
            build_composed(self, cx)
        }
    }
}

/// The native idiom: one leaf of [`KIND`], bound two-way, probe kept current by hand.
fn build_native<V: Binding<f64>>(stepper: Stepper<V>, cx: &mut BuildCx) -> RNode {
    let Stepper {
        value,
        min,
        max,
        step,
        decimals,
        key,
        ..
    } = stepper;
    let clamp = move |v: f64| v.clamp(min, max);
    let initial = clamp(value.peek());
    let node = cx.leaf(
        KIND,
        &StepperProps {
            value: initial,
            min,
            max,
            step,
            decimals,
        },
        Flex::default(),
    );
    // The leaf's dayscript id: one `.key` drives both idioms (`Decorate::id` on the piece
    // would tag the wrapper the composed row returns, which no toolkit realizes).
    with_tree(|t| t.set_id(node, key.as_str().to_owned()));
    let note_probe = move |v: f64| {
        with_tree(|t| t.set_probe_value(node, v, fmt_value(v, decimals)));
    };
    note_probe(initial);
    // App writes → the native widget. Every arm no-ops on an unchanged value, so a step
    // echoing back through the binding never loops.
    {
        let v = value.clone();
        bind_seeded(
            initial,
            move || clamp(v.read()),
            move |val: &f64| {
                with_tree(|t| t.patch(node, Box::new(StepperPatch::SetValue(*val)), false));
                note_probe(*val);
            },
        );
    }
    // Native steps and typed edits (`Custom`), dayscript's `input:` (`TextChanged`) and
    // `set_value:` (`ValueChanged`/`ValueCommitted`) → the binding. A step or a settled edit
    // is a commit, one undoable unit per click, exactly like a built-in slider's committed
    // value; only `ValueChanged` stays a preview.
    cx.on(node, move |ev| {
        match ev {
            // Other custom events include SYNTHESIZED_TEXT, the paint half of scripted
            // typing. TextChanged below owns that edit; accepting both commits it twice.
            Event::Custom { tag, text, .. } if *tag == VALUE_TAG || tag.is_empty() => {
                if let Ok(v) = text.trim().parse::<f64>() {
                    value.write_commit(clamp(v));
                }
            }
            Event::TextChanged(s) => {
                if let Ok(v) = s.trim().parse::<f64>() {
                    value.write_commit(clamp(v));
                }
            }
            Event::ValueChanged(v) => value.write_preview(clamp(*v)),
            Event::ValueCommitted(v) => value.write_commit(clamp(*v)),
            _ => {}
        };
    });
    node
}

/// The field's binding: reads format the bound value, keystrokes are previews the value
/// must not follow (half-typed numbers are not values), and the committed text (Return,
/// focus loss, dayscript `submit:`) parses, clamps, and writes through.
struct FieldBinding<V: Binding<f64>> {
    value: V,
    min: f64,
    max: f64,
    decimals: u32,
    format: Option<ValueFormat>,
}
impl<V: Binding<f64>> Clone for FieldBinding<V> {
    fn clone(&self) -> Self {
        FieldBinding {
            value: self.value.clone(),
            min: self.min,
            max: self.max,
            decimals: self.decimals,
            format: self.format.clone(),
        }
    }
}
impl<V: Binding<f64>> Binding<String> for FieldBinding<V> {
    fn read(&self) -> String {
        let value = self.value.read().clamp(self.min, self.max);
        match &self.format {
            Some(format) => (format.display)(value),
            None => fmt_value(value, self.decimals),
        }
    }
    fn peek(&self) -> String {
        day_reactive::untrack(|| self.read())
    }
    fn write(&self, s: String) {
        self.write_commit(s);
    }
    fn write_preview(&self, _s: String) {}
    fn write_commit(&self, s: String) {
        let parsed = match &self.format {
            Some(format) => (format.parse)(&s).filter(|v| v.is_finite()),
            None => s.trim().parse::<f64>().ok().filter(|v| v.is_finite()),
        };
        if let Some(v) = parsed {
            self.value.write_commit(v.clamp(self.min, self.max));
        }
    }
}

/// The composed idiom: a − button, a text field and a + button, ordinary pieces on every target.
fn build_composed<V: Binding<f64>>(stepper: Stepper<V>, cx: &mut BuildCx) -> RNode {
    let Stepper {
        value,
        min,
        max,
        step,
        decimals,
        format,
        key,
        ..
    } = stepper;
    let clamp = move |v: f64| v.clamp(min, max);
    let stepped = {
        let value = value.clone();
        move |dir: f64| {
            let v = clamp(value.peek() + dir * step);
            value.write_commit(v);
        }
    };
    let dec = {
        let stepped = stepped.clone();
        move || stepped(-1.0)
    };
    let inc = move || stepped(1.0);

    // Glyph-sized buttons: a stock Material button is 88 dp wide, and two of them beside the
    // field made the composed stepper a 240 dp control that clipped in a 280 dp inspector.
    // The buttons carry ids derived from the key, so a script can press them as a person would.
    let (dec_id, inc_id) = (
        day_core::id!(stepper_decrement, key.as_str()),
        day_core::id!(stepper_increment, key.as_str()),
    );
    // dayscript's `set_value:` lands `ValueChanged`/`ValueCommitted` on the id, which the
    // field itself has no use for (it carries text); the composed idiom takes them the way
    // the native leaf does, so a scripted value reaches the binding on every toolkit.
    // The id goes on the field itself, before the width (which wraps it in a frame node), so
    // the events land on the node the handler is on.
    let binding = FieldBinding {
        value: value.clone(),
        min,
        max,
        decimals,
        format,
    };
    // A rejected edit or a differently spelled version of the same number does not
    // change the signal. Restore the formatted text explicitly at the end of editing.
    let restore = binding.format.as_ref().map(|_| {
        let binding = binding.clone();
        Rc::new(move || binding.peek()) as Rc<dyn Fn() -> String>
    });
    let target = Rc::new(std::cell::Cell::new(None));
    let field_target = target.clone();
    let field = Valued {
        inner: text_field(binding).id(key),
        value,
        clamp,
        restore,
    };
    let field = day_core::piece_fn(move |cx| {
        let node = field.build(cx);
        field_target.set(Some(node));
        node
    })
    .width(56.0);
    let row = row((
        button("−").compact().action(dec).id(dec_id),
        field,
        button("+").compact().action(inc).id(inc_id),
    ))
    .spacing(4.0)
    .align(VAlign::Center)
    .build(cx);
    with_tree(|tree| tree.set_element_target(row, target.get().expect("the field was built")));
    row
}

/// An editable number without step buttons. Edits commit on Return or focus loss.
/// Incomplete or invalid input leaves the bound value unchanged and restores its display.
pub struct NumberField<V: Binding<f64>> {
    value: V,
    min: f64,
    max: f64,
    format: day_localization::NumberFormat,
    key: day_core::ElementId,
    placeholder: Option<crate::TextSource>,
    enabled: Reactive<bool>,
    read_only: Reactive<bool>,
    purpose: day_spec::InputPurpose,
    submit_label: day_spec::SubmitLabel,
    on_submit: Option<Rc<dyn Fn()>>,
}

/// A locale-aware numeric text field, initially using [`NumberFormat::decimal`].
pub fn number_field<V: Binding<f64>>(value: V) -> NumberField<V> {
    NumberField {
        value,
        min: -f64::MAX,
        max: f64::MAX,
        format: NumberFormat::decimal(),
        key: day_core::id!(number_field),
        placeholder: None,
        enabled: Reactive::Const(true),
        read_only: Reactive::Const(false),
        purpose: day_spec::InputPurpose::Decimal,
        submit_label: day_spec::SubmitLabel::Return,
        on_submit: None,
    }
}

#[day_macros::builder(NumberFieldBuilder)]
impl<V: Binding<f64>> NumberField<V> {
    /// Whether the field accepts input and focus. Reactive; defaults to true.
    pub fn enabled<M>(mut self, enabled: impl IntoReactive<bool, M>) -> Self {
        self.enabled = enabled.into_reactive();
        self
    }
    /// Allow selection and copying while preventing edits. Reactive; defaults to false.
    pub fn read_only<M>(mut self, read_only: impl IntoReactive<bool, M>) -> Self {
        self.read_only = read_only.into_reactive();
        self
    }
    /// Localized hint shown when the editable text is empty.
    pub fn placeholder<M>(mut self, text: impl IntoText<M>) -> Self {
        self.placeholder = Some(text.into_text());
        self
    }
    /// The keyboard purpose. Defaults to Decimal; use Number for unsigned integer entry.
    pub fn input_purpose(mut self, purpose: day_spec::InputPurpose) -> Self {
        self.purpose = purpose;
        self
    }
    /// The label on the keyboard's submit key.
    pub fn submit_label(mut self, label: day_spec::SubmitLabel) -> Self {
        self.submit_label = label;
        self
    }
    /// Run after the numeric edit has committed and its formatted text has been restored.
    pub fn on_submit(mut self, action: impl Fn() + 'static) -> Self {
        self.on_submit = Some(Rc::new(action));
        self
    }

    /// Clamp committed input to this inclusive range.
    pub fn range(mut self, range: std::ops::RangeInclusive<f64>) -> Self {
        self.min = *range.start();
        self.max = *range.end();
        self
    }
    /// Set the format shared by display and input parsing.
    pub fn format(mut self, format: day_localization::NumberFormat) -> Self {
        self.format = format;
        self
    }
    /// Identify the editable native text field for UI automation.
    pub fn id(mut self, key: day_core::ElementId) -> Self {
        self.key = key;
        self
    }
}

impl<V: Binding<f64>> Piece for NumberField<V> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let Self {
            value,
            min,
            max,
            format,
            key,
            placeholder,
            enabled,
            read_only,
            purpose,
            submit_label,
            on_submit,
        } = self;
        let binding = FieldBinding {
            value: value.clone(),
            min,
            max,
            decimals: 0,
            format: Some(ValueFormat {
                display: Rc::new(move |v| format.format(v)),
                parse: Rc::new(move |s| format.parse(s)),
            }),
        };
        let restore = binding.clone();
        let field_enabled = enabled.clone();
        let field_read_only = read_only.clone();
        let mut field = text_field(binding)
            .enabled(move || field_enabled.get())
            .read_only(move || field_read_only.get())
            .input_purpose(purpose)
            .submit_label(submit_label);
        if let Some(placeholder) = placeholder {
            field = field.placeholder(placeholder);
        }
        let node = Valued {
            inner: field.id(key),
            value,
            clamp: move |v: f64| v.clamp(min, max),
            restore: Some(Rc::new(move || restore.peek())),
        }
        .build(cx);
        if let Some(on_submit) = on_submit {
            cx.on(node, move |event| {
                if matches!(event, Event::Submitted)
                    && enabled.get_untracked()
                    && !read_only.get_untracked()
                {
                    on_submit();
                }
            });
        }
        node
    }
}

/// The composed field with the numeric value events the native leaf answers (`set_value:`).
struct Valued<P: Piece, V: Binding<f64>, C: Fn(f64) -> f64 + 'static> {
    inner: P,
    value: V,
    clamp: C,
    restore: Option<Rc<dyn Fn() -> String>>,
}

impl<P: Piece, V: Binding<f64>, C: Fn(f64) -> f64 + 'static> Piece for Valued<P, V, C> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let Valued {
            inner,
            value,
            clamp,
            restore,
        } = self;
        let node = inner.build(cx);
        cx.on(node, move |ev| match ev {
            Event::ValueChanged(v) => value.write_preview(clamp(*v)),
            Event::ValueCommitted(v) => value.write_commit(clamp(*v)),
            Event::Submitted | Event::FocusChanged(false) => {
                if let Some(display) = &restore {
                    let text = display();
                    with_tree(|t| {
                        t.patch(
                            node,
                            Box::new(day_spec::props::TextFieldPatch::Text {
                                text,
                                from_native: false,
                            }),
                            false,
                        )
                    });
                }
            }
            _ => {}
        });
        node
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use day_mock::MockToolkit;
    use day_reactive::{Signal, flush_sync};
    use day_spec::WindowOptions;
    use std::cell::RefCell;
    use std::rc::Rc;

    /// Records binding writes even when the value is unchanged: a duplicate commit creates
    /// a second history unit in bindings such as Day-Sketch's inspector.
    #[derive(Clone)]
    struct Writes {
        value: Signal<f64>,
        events: Rc<RefCell<Vec<(&'static str, f64)>>>,
    }

    impl Binding<f64> for Writes {
        fn read(&self) -> f64 {
            self.value.get()
        }
        fn peek(&self) -> f64 {
            self.value.get_untracked()
        }
        fn write(&self, value: f64) {
            self.write_commit(value);
        }
        fn write_preview(&self, value: f64) {
            self.events.borrow_mut().push(("preview", value));
            self.value.set(value);
        }
        fn write_commit(&self, value: f64) {
            self.events.borrow_mut().push(("commit", value));
            self.value.set(value);
        }
    }

    fn boot(native: bool) -> (Writes, RNode) {
        day_core::uninstall_tree();
        let writes = Writes {
            value: Signal::new(3.0),
            events: Rc::default(),
        };
        let binding = writes.clone();
        let (mock, _) = MockToolkit::new();
        day_core::launch_with(mock, WindowOptions::default(), move || {
            let field = stepper(binding).range(0.0..=10.0);
            if native {
                field.native()
            } else {
                field.composed()
            }
            .id(day_core::id!(fixture_stepper))
            .any()
        });
        let node = with_tree(|t| t.find_by_id(day_core::id!(fixture_stepper).as_str())).unwrap();
        (writes, node)
    }

    fn emit(node: RNode, event: Event) {
        day_core::enqueue_event(day_core::rnode_to_id(node), event);
        flush_sync();
    }

    #[test]
    fn localized_numeric_controls_preserve_drafts_commit_once_and_refresh_locale() {
        for field_only in [false, true] {
            day_core::uninstall_tree();
            let writes = Writes {
                value: Signal::new(0.4),
                events: Rc::default(),
            };
            let binding = writes.clone();
            let (mock, probe) = MockToolkit::new();
            day_core::launch_with(mock, WindowOptions::default(), move || {
                if field_only {
                    number_field(binding)
                        .format(NumberFormat::percent().fraction_digits(1))
                        .range(0.0..=1.0)
                        .id(day_core::id!(numeric_fixture))
                        .any()
                } else {
                    stepper(binding)
                        .format(NumberFormat::percent().fraction_digits(1))
                        .range(0.0..=1.0)
                        .id(day_core::id!(numeric_fixture))
                        .any()
                }
            });
            day_localization::locale().set("de".to_owned());
            flush_sync();
            let node = with_tree(|t| t.find_by_id("numeric_fixture")).unwrap();
            let display = || probe.find_by_kind("day.text_field")[0].1.text.clone();
            assert_eq!(
                display(),
                NumberFormat::percent()
                    .fraction_digits(1)
                    .format_in("de", 0.4)
            );
            emit(node, Event::TextChanged("-".into()));
            assert_eq!(writes.peek(), 0.4);
            assert!(writes.events.borrow().is_empty());
            emit(node, Event::TextChanged("72,5 %".into()));
            emit(node, Event::Submitted);
            emit(node, Event::FocusChanged(false));
            assert_eq!(*writes.events.borrow(), [("commit", 0.725)]);
            emit(node, Event::TextChanged("1.5".into())); // Invalid German grouping.
            emit(node, Event::Submitted);
            assert_eq!(writes.peek(), 0.725);
            assert_eq!(writes.events.borrow().len(), 1);
            day_localization::locale().set("ar-EG".to_owned());
            flush_sync();
            assert_eq!(
                display(),
                NumberFormat::percent()
                    .fraction_digits(1)
                    .format_in("ar-EG", 0.725)
            );
            emit(node, Event::TextChanged("١٥٠٪".into()));
            emit(node, Event::FocusChanged(false));
            assert_eq!(writes.peek(), 1.0);
        }
        day_localization::locale().set("en".to_owned());
    }

    #[test]
    fn formatted_edits_commit_once_clamp_and_restore_rejected_text() {
        for idiom in [
            StepperIdiom::Automatic,
            StepperIdiom::Native,
            StepperIdiom::Composed,
        ] {
            day_core::uninstall_tree();
            let writes = Writes {
                value: Signal::new(0.4),
                events: Rc::default(),
            };
            let binding = writes.clone();
            let (mock, probe) = MockToolkit::new();
            day_core::launch_with(mock, WindowOptions::default(), move || {
                // Synthetic formatting fixture; the website app exercises real Fluent messages.
                stepper(binding)
                    .range(0.0..=1.0)
                    .step(0.01)
                    .format_with(
                        |v| format!("{:.0}%", v * 100.0),
                        |text| {
                            text.trim()
                                .trim_end_matches('%')
                                .trim()
                                .parse::<f64>()
                                .ok()
                                .map(|v| v / 100.0)
                        },
                    )
                    .idiom(idiom)
                    .id(day_core::id!(fixture_stepper))
                    .any()
            });
            let node = with_tree(|t| t.find_by_id("fixture_stepper")).unwrap();
            let text = || probe.find_by_kind("day.text_field")[0].1.text.clone();
            assert_eq!(text(), "40%");
            assert!(
                probe.find_by_kind(KIND).is_empty(),
                "custom text always uses the composed control"
            );
            emit(node, Event::TextChanged("73%".into()));
            assert!(
                writes.events.borrow().is_empty(),
                "unfinished typing is not a numeric edit"
            );
            emit(node, Event::Submitted);
            emit(node, Event::FocusChanged(false));
            assert_eq!(*writes.events.borrow(), [("commit", 0.73)]);
            assert_eq!(text(), "73%");
            for invalid in ["invalid", "NaN%", "inf%", "-inf%"] {
                emit(node, Event::TextChanged(invalid.into()));
                emit(node, Event::Submitted);
                assert_eq!(writes.peek(), 0.73);
                assert_eq!(text(), "73%");
                assert_eq!(writes.events.borrow().len(), 1);
            }
            emit(node, Event::TextChanged("150%".into()));
            emit(node, Event::FocusChanged(false));
            assert_eq!(writes.peek(), 1.0);
            assert_eq!(text(), "100%");
            emit(node, Event::TextChanged("100".into()));
            emit(node, Event::Submitted);
            assert_eq!(
                text(),
                "100%",
                "canonical text is restored even when the number is unchanged"
            );
            assert_eq!(writes.events.borrow().len(), 3);
        }
    }

    #[test]
    fn formatted_reads_track_dependencies_and_numeric_events_keep_bound_units() {
        day_core::uninstall_tree();
        let value = Signal::new(0.4);
        let suffix = Signal::new("%");
        let (mock, probe) = MockToolkit::new();
        day_core::launch_with(mock, WindowOptions::default(), move || {
            stepper(value)
                .range(0.0..=1.0)
                .step(0.01)
                .format_with(
                    move |v| format!("{:.0}{}", v * 100.0, suffix.get()),
                    |_| None,
                )
                .id(day_core::id!(fixture_stepper))
                .any()
        });
        let text = || probe.find_by_kind("day.text_field")[0].1.text.clone();
        suffix.set(" %");
        flush_sync();
        assert_eq!(
            text(),
            "40 %",
            "formatter dependencies update without a numeric change"
        );
        let node = with_tree(|t| t.find_by_id("fixture_stepper")).unwrap();
        emit(node, Event::ValueChanged(0.6));
        assert_eq!(value.get(), 0.6);
        assert_eq!(text(), "60 %");
        emit(node, Event::ValueCommitted(0.7));
        assert_eq!(text(), "70 %");
        let inc = day_core::id!(stepper_increment, "fixture_stepper");
        let button = with_tree(|t| t.find_by_id(inc.as_str())).unwrap();
        emit(button, Event::Pressed);
        assert!((value.get() - 0.71).abs() < 1e-10);
        assert_eq!(text(), "71 %");
    }

    #[test]
    fn scripted_typing_commits_once_in_both_idioms() {
        for native in [true, false] {
            let (writes, node) = boot(native);
            // Use the actual dayscript input path: a native leaf receives SYNTHESIZED_TEXT
            // to paint the characters, followed by TextChanged for the edit itself.
            day_core::synthesize_text(node, "7".into());
            flush_sync();
            emit(node, Event::Submitted);
            assert_eq!(writes.peek(), 7.0);
            assert_eq!(
                *writes.events.borrow(),
                [("commit", 7.0)],
                "native={native}"
            );
        }
    }

    #[test]
    fn native_custom_events_accept_only_value_tags_and_the_legacy_bridge() {
        let (writes, node) = boot(true);
        emit(node, Event::custom(day_core::SYNTHESIZED_TEXT, "8"));
        emit(node, Event::custom("fixture:unrelated", "9"));
        assert_eq!(writes.peek(), 3.0);
        assert!(writes.events.borrow().is_empty());
        emit(node, Event::custom(VALUE_TAG, "6"));
        emit(node, Event::custom("", "12"));
        assert_eq!(*writes.events.borrow(), [("commit", 6.0), ("commit", 10.0)]);
        assert_eq!(writes.peek(), 10.0);
    }

    #[test]
    fn scripted_values_keep_the_preview_and_commit_boundary() {
        for native in [true, false] {
            let (writes, node) = boot(native);
            emit(node, Event::ValueChanged(12.0));
            emit(node, Event::ValueCommitted(12.0));
            assert_eq!(
                *writes.events.borrow(),
                [("preview", 10.0), ("commit", 10.0)],
                "native={native}"
            );
            assert_eq!(writes.peek(), 10.0);
        }
    }
}

/// The stepper's conformance cases (docs/testing.md), in both idioms.
#[cfg(feature = "conformance")]
pub mod conformance {
    #[day_macros::test(day_core)]
    fn localized_numeric_input() -> day_core::conformance::Case {
        use crate::prelude::*;
        let value = Signal::new(0.4);
        let submitted = Signal::new(0.0);
        let enabled = Signal::new(true);
        Case::new()
            .proves(day_spec::kinds::TEXT_FIELD)
            .page(move || {
                column((
                    stepper(value)
                        .padding(4.0)
                        .range(0.0..=1.0)
                        .format(NumberFormat::percent())
                        .id(day_core::id!(percent_stepper)),
                    number_field(value)
                        .padding(4.0)
                        .range(0.0..=1.0)
                        .format(NumberFormat::percent())
                        .placeholder("Fixture percentage")
                        .submit_label(SubmitLabel::Done)
                        .enabled(enabled)
                        .on_submit(move || submitted.set(value.get()))
                        .id(day_core::id!(percent_field)),
                    label(move || NumberFormat::percent().format(submitted.get()))
                        .id(day_core::id!(percent_submitted)),
                    button("Disable fixture field")
                        .action(move || enabled.set(false))
                        .id(day_core::id!(percent_disable)),
                ))
            })
            .drive(|d: Drive| async move {
                d.input("percent_field", "73%").await?;
                d.submit("percent_field").await?;
                d.assert_text("percent_submitted", &NumberFormat::percent().format(0.73))
                    .await?;
                d.assert_text("percent_stepper", &NumberFormat::percent().format(0.73))
                    .await?;
                d.input("percent_stepper", "invalid").await?;
                d.submit("percent_stepper").await?;
                d.assert_text("percent_stepper", &NumberFormat::percent().format(0.73))
                    .await?;
                d.set_value("percent_stepper", 0.4).await?;
                d.assert_text("percent_field", &NumberFormat::percent().format(0.4))
                    .await?;
                d.tap("percent_disable").await?;
                d.assert_enabled("percent_field", false).await
            })
    }

    use crate::*;
    use day_core::AnyPiece;
    use day_core::conformance::{Case, Drive};
    use day_reactive::Signal;

    use super::{KIND, stepper};

    fn page(composed: bool) -> AnyPiece {
        let value = Signal::new(3.0f64);
        // Each idiom asked for explicitly: a toolkit with no native arm renders a placeholder
        // for `.native()`, and the native cases skip there.
        let field = stepper(value)
            .range(0.0..=10.0)
            .id(day_core::id!(stepper::count));
        column((
            label(move || format!("value {}", value.get())).id(day_core::id!(stepper::value)),
            if composed {
                field.composed().any()
            } else {
                field.native().any()
            },
        ))
        .any()
    }

    /// A value set on the stepper reaches its binding and shows in the field.
    #[day_macros::test(day_core)]
    fn stepper_sets_value() -> Case {
        Case::new()
            .proves(KIND)
            .page(|| page(false))
            .drive(|d: Drive| async move {
                d.assert_text("stepper::count", "3").await?;
                d.set_value("stepper::count", 7.0).await?;
                d.assert_text("stepper::value", "value 7").await?;
                d.assert_text("stepper::count", "7").await
            })
    }

    /// The range holds: a value past the top lands on it.
    #[day_macros::test(day_core)]
    fn stepper_clamps_to_range() -> Case {
        Case::new()
            .proves(KIND)
            .page(|| page(false))
            .drive(|d: Drive| async move {
                d.set_value("stepper::count", 42.0).await?;
                d.assert_text("stepper::value", "value 10").await
            })
    }

    /// The composed idiom (− / field / +) behaves the same on every toolkit.
    #[day_macros::test(day_core)]
    fn stepper_composed_sets_value() -> Case {
        // Proves no kind: the composed idiom is ordinary pieces, never the native leaf.
        Case::new()
            .page(|| page(true))
            .drive(|d: Drive| async move {
                // Typed text commits on submit, as Return does.
                d.input("stepper::count", "5").await?;
                d.submit("stepper::count").await?;
                d.assert_text("stepper::value", "value 5").await?;
                d.tap(day_core::id!(stepper_increment, "stepper::count").as_str())
                    .await?;
                d.assert_text("stepper::value", "value 6").await?;
                d.assert_text("stepper::count", "6").await?;
                // A scripted value lands on the field's id, as it does on the native leaf.
                d.set_value("stepper::count", 9.0).await?;
                d.assert_text("stepper::value", "value 9").await?;
                d.assert_text("stepper::count", "9").await
            })
    }
}