Skip to main content

day_pieces/
inputs.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Native input pieces: `picker` (a typed one-of-N selector: menu, segmented, or inline) and
5//! `text_area` (a multi-line, auto-growing editor bound two-way to a `Signal<String>`).
6
7use std::cell::RefCell;
8use std::rc::Rc;
9
10use day_core::*;
11use day_reactive::{bind, bind_seeded};
12use day_spec::{Event, kinds};
13
14use crate::*;
15
16// ---------------------------------------------------------------------------
17// Picker (kinds::PICKER, docs/picker.md), built-in since 2026-07.
18// ---------------------------------------------------------------------------
19
20/// The options of a [`picker`]: `(value, title)` pairs, fixed or derived.
21pub enum PickerOptions<T: 'static> {
22    Fixed(Vec<(T, TextSource)>),
23    Derived(Rc<dyn Fn() -> Vec<(T, TextSource)>>),
24}
25
26impl<T: Clone + 'static> PickerOptions<T> {
27    /// The current `(values, titles)`: a tracked read, of the derived closure and of every
28    /// title (so a localized title follows the locale).
29    fn resolve(&self) -> (Vec<T>, Vec<String>) {
30        let pairs = match self {
31            PickerOptions::Fixed(v) => v.clone(),
32            PickerOptions::Derived(f) => f(),
33        };
34        let mut values = Vec::with_capacity(pairs.len());
35        let mut titles = Vec::with_capacity(pairs.len());
36        for (v, t) in pairs {
37            values.push(v);
38            titles.push(t.resolve());
39        }
40        (values, titles)
41    }
42}
43
44/// Anything [`picker`] takes as its options: an array or `Vec` of `(value, title)` pairs, or a
45/// closure that derives the list and re-runs whenever its reactive reads change. Titles take the
46/// same sources as a label. The two-level marker is the same E0119 dodge as
47/// [`IntoText`](crate::IntoText).
48pub trait IntoPickerOptions<T: 'static, M> {
49    fn into_picker_options(self) -> PickerOptions<T>;
50}
51
52/// Marker for a fixed list of options.
53pub struct FixedOptionsMark;
54/// Marker for a derived list of options.
55pub struct DerivedOptionsMark;
56
57impl<T: 'static, X: IntoText<M>, M, const N: usize> IntoPickerOptions<T, (FixedOptionsMark, M)>
58    for [(T, X); N]
59{
60    fn into_picker_options(self) -> PickerOptions<T> {
61        PickerOptions::Fixed(self.into_iter().map(|(v, t)| (v, t.into_text())).collect())
62    }
63}
64
65impl<T: 'static, X: IntoText<M>, M> IntoPickerOptions<T, (FixedOptionsMark, M)> for Vec<(T, X)> {
66    fn into_picker_options(self) -> PickerOptions<T> {
67        PickerOptions::Fixed(self.into_iter().map(|(v, t)| (v, t.into_text())).collect())
68    }
69}
70
71impl<T: 'static, X: IntoText<M>, M, F> IntoPickerOptions<T, (DerivedOptionsMark, M)> for F
72where
73    F: Fn() -> Vec<(T, X)> + 'static,
74{
75    fn into_picker_options(self) -> PickerOptions<T> {
76        PickerOptions::Derived(Rc::new(move || {
77            self()
78                .into_iter()
79                .map(|(v, t)| (v, t.into_text()))
80                .collect()
81        }))
82    }
83}
84
85/// How a picker reads and writes its selection: a required value ([`picker`]) or an optional
86/// one ([`picker_optional`]). Implemented by the two adapters below, never by apps.
87pub trait PickerSelection<T: 'static>: Clone + 'static {
88    /// Tracked read of the current value, `None` when nothing is chosen.
89    fn current(&self) -> Option<T>;
90    /// The user chose `value`.
91    fn choose(&self, value: T);
92}
93
94/// A [`picker`]'s selection: a binding to `T`.
95#[derive(Clone)]
96pub struct Required<Sel>(Sel);
97
98impl<T: 'static, Sel: Binding<T>> PickerSelection<T> for Required<Sel> {
99    fn current(&self) -> Option<T> {
100        Some(self.0.read())
101    }
102    fn choose(&self, value: T) {
103        self.0.write(value);
104    }
105}
106
107/// A [`picker_optional`]'s selection: a binding to `Option<T>`.
108#[derive(Clone)]
109pub struct Optional<Sel>(Sel);
110
111impl<T: 'static, Sel: Binding<Option<T>>> PickerSelection<T> for Optional<Sel> {
112    fn current(&self) -> Option<T> {
113        self.0.read()
114    }
115    fn choose(&self, value: T) {
116        self.0.write(Some(value));
117    }
118}
119
120/// A native one-of-N selector bound two-way to a typed value (docs/picker.md). Style via
121/// `.menu()`/`.segmented()`/`.inline()`.
122#[must_use]
123pub struct Picker<T: Clone + PartialEq + 'static, S: PickerSelection<T>> {
124    options: PickerOptions<T>,
125    separators_before: Vec<usize>,
126    selected: S,
127    style: day_spec::props::PickerStyle,
128    enabled: Reactive<bool>,
129}
130
131/// `picker(sort, [(Sort::Name, res::str::name()), (Sort::Date, res::str::date())]).segmented()`:
132/// `selected` is a two-way binding to the chosen value (a `Signal<T>`, a day-model `Field`, a
133/// `Mapped` view), and the options are `(value, title)` pairs, fixed or derived from a closure.
134/// The mapping between values and the native control's indexes lives here, once.
135///
136/// Selection rules (docs/picker.md): the picker never writes the binding on its own, only a
137/// user's choice does. A bound value that is not among the options shows no selection where
138/// the toolkit can show none, and the first option otherwise; empty options disable the
139/// control; when the options change, the native index is re-derived from the value, and a
140/// native choice that arrives after the options changed is mapped against the options the
141/// control was last given.
142pub fn picker<T, Sel, M>(
143    selected: Sel,
144    options: impl IntoPickerOptions<T, M>,
145) -> Picker<T, Required<Sel>>
146where
147    T: Clone + PartialEq + 'static,
148    Sel: Binding<T>,
149{
150    Picker {
151        options: options.into_picker_options(),
152        separators_before: Vec::new(),
153        selected: Required(selected),
154        style: day_spec::props::PickerStyle::Menu,
155        enabled: Reactive::Const(true),
156    }
157}
158
159/// [`picker`] over an optional value: `None` is "nothing chosen" (no selection where the
160/// toolkit can show none), and a user's choice writes `Some(value)`.
161pub fn picker_optional<T, Sel, M>(
162    selected: Sel,
163    options: impl IntoPickerOptions<T, M>,
164) -> Picker<T, Optional<Sel>>
165where
166    T: Clone + PartialEq + 'static,
167    Sel: Binding<Option<T>>,
168{
169    Picker {
170        options: options.into_picker_options(),
171        separators_before: Vec::new(),
172        selected: Optional(selected),
173        style: day_spec::props::PickerStyle::Menu,
174        enabled: Reactive::Const(true),
175    }
176}
177
178#[day_macros::builder(PickerBuilder)]
179impl<T: Clone + PartialEq + 'static, S: PickerSelection<T>> Picker<T, S> {
180    /// Whether the picker takes input (default `true`); a constant or a reactive `bool`.
181    pub fn enabled<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
182        self.enabled = v.into_reactive();
183        self
184    }
185    /// Insert native menu separators before these option indexes. Indexes still refer to
186    /// options, so separators never change the selection binding. AppKit/UIKit menu style
187    /// honors this; other backends and styles display the same options without grouping.
188    pub fn separators_before(mut self, indexes: impl IntoIterator<Item = usize>) -> Self {
189        self.separators_before = indexes.into_iter().collect();
190        self.separators_before.sort_unstable();
191        self.separators_before.dedup();
192        self
193    }
194    pub fn menu(mut self) -> Self {
195        self.style = day_spec::props::PickerStyle::Menu;
196        self
197    }
198    pub fn segmented(mut self) -> Self {
199        self.style = day_spec::props::PickerStyle::Segmented;
200        self
201    }
202    pub fn inline(mut self) -> Self {
203        self.style = day_spec::props::PickerStyle::Inline;
204        self
205    }
206    pub fn style(mut self, style: day_spec::props::PickerStyle) -> Self {
207        self.style = style;
208        self
209    }
210}
211
212impl<T: Clone + PartialEq + 'static, S: PickerSelection<T>> Piece for Picker<T, S> {
213    fn build(self, cx: &mut BuildCx) -> RNode {
214        let Picker {
215            options,
216            separators_before,
217            selected,
218            style,
219            enabled,
220        } = self;
221        let (values0, titles0) = day_reactive::untrack(|| options.resolve());
222        debug_assert!(
223            values0
224                .iter()
225                .enumerate()
226                .all(|(i, v)| !values0[..i].contains(v)),
227            "day: a picker's option values must be distinct"
228        );
229        // The options the control was last given: what a native index is mapped against.
230        let values: Rc<RefCell<Vec<T>>> = Rc::new(RefCell::new(values0));
231        let index_of = {
232            let values = values.clone();
233            move |v: Option<T>| -> Option<usize> {
234                let v = v?;
235                values.borrow().iter().position(|x| *x == v)
236            }
237        };
238        let initial_index = index_of(day_reactive::untrack(|| selected.current())).unwrap_or(0);
239        let enabled_now = enabled.get_untracked() && !titles0.is_empty();
240        let initial = day_spec::props::PickerProps {
241            options: titles0,
242            separators_before,
243            selected: initial_index,
244            style,
245            enabled: enabled_now,
246        };
247        let node = cx.leaf(kinds::PICKER, &initial, Flex::default());
248        let patch = move |p: day_spec::props::PickerPatch, affects_size: bool| {
249            with_tree(|t| t.patch(node, Box::new(p), affects_size));
250        };
251        // Availability: the app's value, and never with no options to choose from.
252        {
253            let enabled = enabled.clone();
254            let values = values.clone();
255            bind_seeded(
256                enabled_now,
257                move || enabled.get() && !values.borrow().is_empty(),
258                move |e: &bool| patch(day_spec::props::PickerPatch::Enabled(*e), false),
259            );
260        }
261        // A menu-style picker's intrinsic size follows the selected value (the collapsed
262        // control renders it), so its selection patch must remeasure; without that the
263        // control keeps the width of the build-time value and ellipsizes anything longer.
264        // Segmented and inline render every option at once; selection moves a mark only.
265        let affects_size = matches!(initial.style, day_spec::props::PickerStyle::Menu);
266        // The options, live: a derived closure re-running, or a title following the locale.
267        // The native items are patched (always a remeasure, since the option strings are the
268        // control's intrinsic width), and the selected index re-derived from the value, since
269        // the value's position may have moved.
270        {
271            let (values, sel) = (values.clone(), selected.clone());
272            let index_of = index_of.clone();
273            bind_seeded(
274                initial.options.clone(),
275                move || {
276                    let (vs, titles) = options.resolve();
277                    *values.borrow_mut() = vs;
278                    titles
279                },
280                move |titles: &Vec<String>| {
281                    patch(day_spec::props::PickerPatch::Options(titles.clone()), true);
282                    if let Some(i) = index_of(day_reactive::untrack(|| sel.current())) {
283                        patch(day_spec::props::PickerPatch::Selected(i), affects_size);
284                    }
285                },
286            );
287        }
288        // The value, live: the app writing its binding moves the native selection. A value
289        // absent from the options patches nothing (the control keeps showing what it shows).
290        {
291            let sel = selected.clone();
292            let index_of = index_of.clone();
293            bind_seeded(
294                Some(initial.selected),
295                move || index_of(sel.current()),
296                move |i: &Option<usize>| {
297                    if let Some(i) = i {
298                        patch(day_spec::props::PickerPatch::Selected(*i), affects_size);
299                    }
300                },
301            );
302        }
303        // The user's choice: a native index, mapped against the options the control was last
304        // given; an index outside them (a stale event) is dropped.
305        cx.on(node, move |ev| {
306            if let Event::SelectionChanged(i) = ev
307                && *i >= 0
308                && let Some(v) = values.borrow().get(*i as usize).cloned()
309            {
310                selected.choose(v);
311            }
312        });
313        node
314    }
315}
316
317// ---------------------------------------------------------------------------
318// Text area (kinds::TEXT_AREA, docs/textarea.md), built-in since 2026-07.
319// ---------------------------------------------------------------------------
320
321/// A native multi-line text editor bound two-way to `text`. Configure a prompt with
322/// `.placeholder(_)`, the auto-growing height band with `.min_lines(_)` / `.max_lines(_)`, and the
323/// native editor attributes with `.editable(_)` / `.selectable(_)` / `.spellcheck(_)` (each accepts
324/// a constant or a reactive `bool`, and updates live). A backend that can't honor an attribute
325/// answers the matching `Cap::Text{Editable,Selectable,SpellCheck}` with `Support::Unsupported`.
326#[must_use]
327pub struct TextArea<S: Binding<String>> {
328    text: S,
329    placeholder: Option<TextSource>,
330    min_lines: u32,
331    max_lines: u32,
332    editable: Reactive<bool>,
333    selectable: Reactive<bool>,
334    spellcheck: Reactive<bool>,
335    on_submit: Option<Rc<dyn Fn()>>,
336}
337
338/// `text_area(text)`: a native multi-line editor whose contents mirror `text` in both
339/// directions; `text` is a `Signal<String>` or any other two-way binding (a day-model `Field`).
340pub fn text_area<S: Binding<String>>(text: S) -> TextArea<S> {
341    TextArea {
342        text,
343        placeholder: None,
344        min_lines: 1,
345        max_lines: 0,
346        editable: true.into_reactive(),
347        selectable: true.into_reactive(),
348        spellcheck: true.into_reactive(),
349        on_submit: None,
350    }
351}
352
353#[day_macros::builder(TextAreaBuilder)]
354impl<S: Binding<String>> TextArea<S> {
355    /// The empty-state prompt shown when the editor is empty (a constant, `Signal<String>`, or
356    /// closure, evaluated once for the initial value; not reactive after build).
357    pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
358        self.placeholder = Some(t.into_text());
359        self
360    }
361
362    /// The minimum height, in text lines (default 1): the editor never shrinks below this.
363    pub fn min_lines(mut self, lines: u32) -> Self {
364        self.min_lines = lines.max(1);
365        self
366    }
367
368    /// The maximum height, in text lines, before the editor scrolls internally. `0` (the
369    /// default) means unbounded: the editor keeps growing and never scrolls.
370    pub fn max_lines(mut self, lines: u32) -> Self {
371        self.max_lines = lines;
372        self
373    }
374
375    /// Whether the user can edit the text (default `true`; `false` = read-only). Reactive.
376    pub fn editable<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
377        self.editable = v.into_reactive();
378        self
379    }
380
381    /// Whether the text can be selected and copied (default `true`). Reactive. `Unsupported` on
382    /// backends where selection is always on (GTK).
383    pub fn selectable<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
384        self.selectable = v.into_reactive();
385        self
386    }
387
388    /// Whether spell-check / autocorrect highlighting is on (default `true`). Reactive.
389    /// `Unsupported` on backends with no built-in spell-check (GTK, Qt).
390    pub fn spellcheck<M>(mut self, v: impl IntoReactive<bool, M>) -> Self {
391        self.spellcheck = v.into_reactive();
392        self
393    }
394
395    /// Submit on Enter: a plain Enter runs `f` instead of inserting a newline, the chat-composer
396    /// contract. Shift+Enter still inserts a line break on desktop and ArkUI; Android and
397    /// ArkUI show a Send action on the soft keyboard; iOS's return key submits. Backends without
398    /// the intercept (web-dom today) keep inserting newlines, so pair this with a visible send button. The
399    /// bound `text` signal is already up to date when `f` runs.
400    pub fn on_submit(mut self, f: impl Fn() + 'static) -> Self {
401        self.on_submit = Some(Rc::new(f));
402        self
403    }
404}
405
406impl<S: Binding<String>> Piece for TextArea<S> {
407    fn build(self, cx: &mut BuildCx) -> RNode {
408        let TextArea {
409            text,
410            placeholder,
411            min_lines,
412            max_lines,
413            editable,
414            selectable,
415            spellcheck,
416            on_submit,
417        } = self;
418        let initial = text.peek();
419        let ph = placeholder.map_or_default(|p| p.initial());
420        let node = cx.leaf(
421            kinds::TEXT_AREA,
422            &day_spec::props::TextAreaProps {
423                text: initial.clone(),
424                placeholder: ph,
425                min_lines,
426                // A 0 max is "unbounded"; a non-zero max is floored to min so the band is
427                // never inverted.
428                max_lines: if max_lines == 0 {
429                    0
430                } else {
431                    max_lines.max(min_lines)
432                },
433                editable: editable.get_untracked(),
434                selectable: selectable.get_untracked(),
435                spellcheck: spellcheck.get_untracked(),
436                submit_on_enter: on_submit.is_some(),
437            },
438            // A composer fills the available width; height is content-driven (the backend's
439            // measure grows it between min/max lines), so it is not a height-growing leaf.
440            Flex {
441                grow_w: true,
442                ..Default::default()
443            },
444        );
445        // Live attributes: only a reactive source needs a binding (a constant is applied once at
446        // realize). Each patches the backend when its value changes.
447        if let Reactive::Dyn(_) = &editable {
448            bind(
449                move || editable.get(),
450                move |v: &bool| {
451                    with_tree(|t| {
452                        t.patch(
453                            node,
454                            Box::new(day_spec::props::TextAreaPatch::SetEditable(*v)),
455                            false,
456                        );
457                    });
458                },
459            );
460        }
461        if let Reactive::Dyn(_) = &selectable {
462            bind(
463                move || selectable.get(),
464                move |v: &bool| {
465                    with_tree(|t| {
466                        t.patch(
467                            node,
468                            Box::new(day_spec::props::TextAreaPatch::SetSelectable(*v)),
469                            false,
470                        );
471                    });
472                },
473            );
474        }
475        if let Reactive::Dyn(_) = &spellcheck {
476            bind(
477                move || spellcheck.get(),
478                move |v: &bool| {
479                    with_tree(|t| {
480                        t.patch(
481                            node,
482                            Box::new(day_spec::props::TextAreaPatch::SetSpellCheck(*v)),
483                            false,
484                        );
485                    });
486                },
487            );
488        }
489        // Controlled input with origin tracking (§4.4): the echo guard remembers the last value
490        // that arrived from the native widget so bind_seeded does not patch it straight back.
491        let guard: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
492        let g = guard.clone();
493        let tx = text.clone();
494        bind_seeded(
495            initial,
496            move || tx.read(),
497            move |t: &String| {
498                let from_native = g.borrow_mut().take().as_deref() == Some(t.as_str());
499                if !from_native {
500                    with_tree(|tr| {
501                        tr.patch(
502                            node,
503                            Box::new(day_spec::props::TextAreaPatch::SetText(t.clone())),
504                            true,
505                        );
506                    });
507                }
508            },
509        );
510        cx.on(node, move |ev| match ev {
511            Event::TextChanged(t) => {
512                // Native edits skip the write-back patch below to preserve the caret/IME.
513                // Keep inspection/dayscript text current even when no toolkit patch is sent.
514                with_tree(|tree| tree.set_probe_value(node, 0.0, t.clone()));
515                *guard.borrow_mut() = Some(t.clone());
516                text.write(t.clone());
517            }
518            Event::Submitted => {
519                if let Some(f) = &on_submit {
520                    f();
521                }
522            }
523            _ => {}
524        });
525        node
526    }
527}
528
529// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
530
531// ---------------------------------------------------------------------------
532// Conformance cases (docs/testing.md)
533// ---------------------------------------------------------------------------
534
535/// The picker's and text area's `#[day::test]` cases, next to their constructors.
536#[cfg(feature = "conformance")]
537pub(crate) mod conformance {
538    use day_core::conformance::{Case, Drive};
539    use day_reactive::Signal;
540    use day_spec::{Cap, kinds};
541
542    use crate::*;
543
544    const FRUIT: [(usize, &str); 3] = [(0, "Apple"), (1, "Pear"), (2, "Plum")];
545
546    /// A menu picker shows its selection natively and reports a choice to its signal.
547    #[day_macros::test(day_core)]
548    fn picker_select() -> Case {
549        let choice = Signal::new(0usize);
550        Case::new()
551            .proves(kinds::PICKER)
552            .page(move || {
553                column((
554                    picker(choice, FRUIT).id(day_core::id!(picker)),
555                    label(move || choice.get().to_string()).id(day_core::id!(index)),
556                ))
557                .spacing(8.0)
558            })
559            .shot("default")
560            .drive(|d: Drive| async move {
561                d.assert_text("picker", "Apple").await?;
562                d.select("picker", 2).await?;
563                d.assert_text("index", "2").await?;
564                d.assert_text("picker", "Plum").await
565            })
566    }
567
568    /// A segmented picker selects the same way.
569    #[day_macros::test(day_core)]
570    fn picker_segmented() -> Case {
571        let choice = Signal::new(1usize);
572        Case::new()
573            .proves(kinds::PICKER)
574            .page(move || {
575                column((
576                    picker(choice, FRUIT).segmented().id(day_core::id!(picker)),
577                    label(move || choice.get().to_string()).id(day_core::id!(index)),
578                ))
579                .spacing(8.0)
580            })
581            .shot("default")
582            .drive(|d: Drive| async move {
583                d.assert_text("picker", "Pear").await?;
584                d.select("picker", 0).await?;
585                d.assert_text("index", "0").await?;
586                d.assert_text("picker", "Apple").await
587            })
588    }
589
590    /// An inline picker selects the same way.
591    #[day_macros::test(day_core)]
592    fn picker_inline() -> Case {
593        let choice = Signal::new(0usize);
594        Case::new()
595            .proves(kinds::PICKER)
596            .page(move || {
597                column((
598                    picker(choice, FRUIT).inline().id(day_core::id!(picker)),
599                    label(move || choice.get().to_string()).id(day_core::id!(index)),
600                ))
601                .spacing(8.0)
602            })
603            .drive(|d: Drive| async move {
604                d.select("picker", 1).await?;
605                d.assert_text("index", "1").await?;
606                d.assert_text("picker", "Pear").await
607            })
608    }
609
610    /// A write to the picker's signal moves the native selection.
611    #[day_macros::test(day_core)]
612    fn picker_follows_signal() -> Case {
613        let choice = Signal::new(0usize);
614        Case::new()
615            .proves(kinds::PICKER)
616            .page(move || {
617                column((
618                    picker(choice, FRUIT).id(day_core::id!(picker)),
619                    button("Plum")
620                        .action(move || choice.set(2))
621                        .id(day_core::id!(set)),
622                ))
623                .spacing(8.0)
624            })
625            .drive(|d: Drive| async move {
626                d.tap("set").await?;
627                d.assert_text("picker", "Plum").await
628            })
629    }
630
631    /// Options from data replace the native items and keep the selection where it exists.
632    #[day_macros::test(day_core)]
633    fn picker_options_reactive() -> Case {
634        let choice = Signal::new(1usize);
635        let more = Signal::new(false);
636        Case::new()
637            .proves(kinds::PICKER)
638            .page(move || {
639                column((
640                    picker(choice, move || {
641                        let mut v = vec![(0usize, "One"), (1, "Two")];
642                        if more.get() {
643                            v.push((2, "Three"));
644                        }
645                        v
646                    })
647                    .id(day_core::id!(picker)),
648                    button("More")
649                        .action(move || more.set(true))
650                        .id(day_core::id!(more)),
651                ))
652                .spacing(8.0)
653            })
654            .drive(|d: Drive| async move {
655                d.assert_text("picker", "Two").await?;
656                d.tap("more").await?;
657                d.select("picker", 2).await?;
658                d.assert_text("picker", "Three").await
659            })
660    }
661
662    /// A disabled picker reports itself disabled, natively too, in every style, until enabled.
663    #[day_macros::test(day_core)]
664    fn picker_disabled() -> Case {
665        let (a, b, c) = (
666            Signal::new(0usize),
667            Signal::new(0usize),
668            Signal::new(0usize),
669        );
670        let enabled = Signal::new(false);
671        Case::new()
672            .proves(kinds::PICKER)
673            .page(move || {
674                column((
675                    picker(a, FRUIT)
676                        .enabled(move || enabled.get())
677                        .id(day_core::id!(menu)),
678                    picker(b, FRUIT)
679                        .segmented()
680                        .enabled(move || enabled.get())
681                        .id(day_core::id!(segmented)),
682                    picker(c, FRUIT)
683                        .inline()
684                        .enabled(move || enabled.get())
685                        .id(day_core::id!(inline)),
686                    button("Enable")
687                        .action(move || enabled.set(true))
688                        .id(day_core::id!(enable)),
689                ))
690                .spacing(8.0)
691            })
692            .shot("disabled")
693            .drive(|d: Drive| async move {
694                for id in ["menu", "segmented", "inline"] {
695                    d.assert_enabled(id, false).await?;
696                }
697                d.tap("enable").await?;
698                for id in ["menu", "segmented", "inline"] {
699                    d.assert_enabled(id, true).await?;
700                }
701                Ok(())
702            })
703    }
704
705    /// A text area mirrors its signal both ways.
706    #[day_macros::test(day_core)]
707    fn text_area_binding() -> Case {
708        let text = Signal::new(String::new());
709        Case::new()
710            .proves(kinds::TEXT_AREA)
711            .page(move || {
712                column((
713                    text_area(text).placeholder("Notes").id(day_core::id!(area)),
714                    label(move || text.get().chars().count().to_string()).id(day_core::id!(len)),
715                    button("Set")
716                        .action(move || text.set("Set from Day".into()))
717                        .id(day_core::id!(set)),
718                ))
719                .spacing(8.0)
720            })
721            .drive(|d: Drive| async move {
722                d.input("area", "typed").await?;
723                d.assert_text("len", "5").await?;
724                d.tap("set").await?;
725                d.assert_text("area", "Set from Day").await
726            })
727    }
728
729    /// Lines survive the round trip: a text area holds and shows a newline as a newline.
730    #[day_macros::test(day_core)]
731    fn text_area_multiline() -> Case {
732        let text = Signal::new("first\nsecond".to_owned());
733        Case::new()
734            .proves(kinds::TEXT_AREA)
735            .page(move || text_area(text).min_lines(3).id(day_core::id!(area)))
736            .drive(|d: Drive| async move {
737                d.assert_text("area", "first\nsecond").await?;
738                d.input("area", "one\ntwo\nthree").await?;
739                d.assert_text("area", "one\ntwo\nthree").await
740            })
741    }
742
743    /// Submission observes the latest bound text and may clear the composer. This checks
744    /// the public event contract; native drivers separately prove keyboard/IME routing.
745    #[day_macros::test(day_core)]
746    fn text_area_submit() -> Case {
747        let text = Signal::new(String::new());
748        let sent = Signal::new(String::new());
749        let count = Signal::new(0u32);
750        Case::new()
751            .proves(kinds::TEXT_AREA)
752            .page(move || {
753                column((
754                    text_area(text)
755                        .min_lines(3)
756                        .on_submit(move || {
757                            sent.set(text.get_untracked());
758                            count.update(|n| *n += 1);
759                            text.set(String::new());
760                        })
761                        .id(day_core::id!(area)),
762                    label(move || sent.get()).id(day_core::id!(sent)),
763                    label(move || count.get().to_string()).id(day_core::id!(count)),
764                ))
765            })
766            .drive(|d: Drive| async move {
767                d.input("area", "first\n東京").await?;
768                d.assert_text("count", "0").await?;
769                d.submit("area").await?;
770                d.assert_text("sent", "first\n東京").await?;
771                d.assert_text("count", "1").await?;
772                d.assert_text("area", "").await?;
773                d.input("area", "next").await?;
774                d.submit("area").await?;
775                d.assert_text("sent", "next").await?;
776                d.assert_text("count", "2").await?;
777                d.assert_text("area", "").await
778            })
779    }
780
781    /// A read-only text area shows what its signal holds.
782    #[day_macros::test(day_core)]
783    fn text_area_read_only() -> Case {
784        let text = Signal::new("Read me".to_owned());
785        Case::new()
786            .proves(kinds::TEXT_AREA)
787            .proves_cap(Cap::TextEditable)
788            .requires(Cap::TextEditable)
789            .page(move || {
790                column((
791                    text_area(text).editable(false).id(day_core::id!(area)),
792                    button("Replace")
793                        .action(move || text.set("Replaced".into()))
794                        .id(day_core::id!(replace)),
795                ))
796                .spacing(8.0)
797            })
798            .drive(|d: Drive| async move {
799                d.assert_text("area", "Read me").await?;
800                d.tap("replace").await?;
801                d.assert_text("area", "Replaced").await
802            })
803    }
804
805    /// A text area whose selection is turned off still shows its text; skipped where the
806    /// toolkit's editor always allows selection (`Cap::TextSelectable`).
807    #[day_macros::test(day_core)]
808    fn text_area_unselectable() -> Case {
809        let text = Signal::new("Fixed".to_owned());
810        Case::new()
811            .proves(kinds::TEXT_AREA)
812            .proves_cap(Cap::TextSelectable)
813            .requires(Cap::TextSelectable)
814            .page(move || {
815                text_area(text)
816                    .selectable(false)
817                    .editable(false)
818                    .id(day_core::id!(area))
819            })
820            .drive(|d: Drive| async move { d.assert_text("area", "Fixed").await })
821    }
822
823    /// Changing editor policies must preserve content and programmatic updates. Native input
824    /// rejection/selection needs the OS-input drivers; `Drive::input` injects a Day event.
825    #[day_macros::test(day_core)]
826    fn text_area_attributes_reactive() -> Case {
827        let text = Signal::new("First\nsecond".to_owned());
828        let editable = Signal::new(true);
829        let selectable = Signal::new(true);
830        Case::new()
831            .proves(kinds::TEXT_AREA)
832            .requires(Cap::TextEditable)
833            .requires(Cap::TextSelectable)
834            .page(move || {
835                column((
836                    text_area(text)
837                        .editable(editable)
838                        .selectable(selectable)
839                        .id(day_core::id!(area)),
840                    label(move || text.get()).id(day_core::id!(model)),
841                    button("Lock").id(day_core::id!(lock)).action(move || {
842                        editable.set(false);
843                        selectable.set(false);
844                    }),
845                    button("Replace")
846                        .id(day_core::id!(replace))
847                        .action(move || text.set("Updated\n東京".into())),
848                    button("Unlock").id(day_core::id!(unlock)).action(move || {
849                        selectable.set(true);
850                        editable.set(true);
851                    }),
852                ))
853            })
854            .drive(|d: Drive| async move {
855                d.tap("lock").await?;
856                d.assert_text("area", "First\nsecond").await?;
857                d.tap("replace").await?;
858                d.assert_text("area", "Updated\n東京").await?;
859                d.assert_text("model", "Updated\n東京").await?;
860                d.tap("unlock").await?;
861                d.assert_text("area", "Updated\n東京").await?;
862                d.input("area", "Back to editing").await?;
863                d.assert_text("model", "Back to editing").await
864            })
865    }
866}