Skip to main content

day_pieces/
decorators.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! `Decorate`, the chainable modifiers every piece inherits: padding and sizing, background and
5//! corner radius, gestures (`on_tap`, drag), accessibility (`A11yBuilder`), and native-handle
6//! capture (`NativeRef`), plus the `Modifier` / `IntoInsets` supporting traits.
7//!
8//! Modifiers return [`Decorated<P>`], which keeps the decorated piece's type, so a chain
9//! never stops reaching that piece's builder methods (§5.2).
10
11use std::cell::Cell;
12use std::rc::Rc;
13
14use day_core::*;
15use day_reactive::{Scope, bind};
16use day_spec::props::*;
17use day_spec::{A11yProps, AnimSpec, Color, Cursor, Event, Insets, Role, Transform, kinds};
18
19use crate::menus::lower_menu_scoped;
20use crate::*;
21
22// ---------------------------------------------------------------------------
23// Decorators (§5.2 Decorate)
24// ---------------------------------------------------------------------------
25
26pub trait IntoInsets {
27    fn into_insets(self) -> Insets;
28}
29impl IntoInsets for f64 {
30    fn into_insets(self) -> Insets {
31        Insets::all(self)
32    }
33}
34impl IntoInsets for Insets {
35    fn into_insets(self) -> Insets {
36        self
37    }
38}
39
40/// A one-shot, by-value view transform (the SwiftUI `ViewModifier` analog): wrap a piece into a
41/// new one. Pure composition, with no per-backend work. A plain `FnOnce(AnyPiece) -> AnyPiece`
42/// closure is a `Modifier` too (the blanket impl below), so the common case needs no new type.
43/// Apply one with [`Decorate::modifier`].
44///
45/// **`AnyPiece` here is a trade, not a requirement.** It is not object safety: a `Modifier` is
46/// never stored as `dyn Modifier`, and [`Decorate::modifier`] takes `impl Modifier` and applies
47/// it on the spot. It is the closure impl below. A closure has one fixed parameter type, and
48/// Rust has no `for<P> FnOnce(P) -> _` bound (higher-ranked bounds range over lifetimes, not
49/// types), so making `apply` generic over the content (`fn apply<P: Piece>(self, c: P) ->
50/// Self::Out<P>`, which a named modifier can satisfy with a GAT) would leave no closure able to
51/// implement the trait at all. Pinning the input to the one piece type that accepts anything is
52/// what keeps `|p| …` a modifier, and the erasure is what that costs, which is why this is the
53/// single `Decorate` method that erases.
54///
55/// If a modifier ever needs to preserve its content's type, parameterize the trait rather than
56/// the method: `trait Modifier<P: Piece> { type Out: Piece; fn apply(self, c: P) -> Self::Out; }`.
57/// Closures survive that (`impl<P: Piece, O: Piece, F: FnOnce(P) -> O> Modifier<P> for F`, and
58/// their parameter still infers unannotated), while a named modifier such as day-piece-rating's
59/// `Card` becomes `impl<P: Piece> Modifier<P> for Card` with `type Out = Decorated<P>`. The bill
60/// is a `Decorate::modifier` whose return type varies per modifier, a generic impl for every
61/// named one, and a breaking change: not worth paying while the tree has two implementors.
62pub trait Modifier {
63    fn apply(self, content: AnyPiece) -> AnyPiece;
64}
65
66impl<F> Modifier for F
67where
68    F: FnOnce(AnyPiece) -> AnyPiece,
69{
70    fn apply(self, content: AnyPiece) -> AnyPiece {
71        self(content)
72    }
73}
74
75/// A liveness-checked reference to a mounted piece's realized node: the retained half of the
76/// tweaks API (docs/tweaks.md). Capture one with [`Decorate::native_ref`], then reach the native
77/// widget later (from event handlers, timers) through a toolkit ext accessor. `node`/`with` yield
78/// `None` before mount and after the node's subtree is disposed, so async races are safe no-ops.
79///
80/// Reads are reactive: inside a binding or memo, `node()` subscribes to the ref's mount/clear
81/// transitions (a `Trigger` underneath), so a label like
82/// `label(move || if r.node().is_some() { "live" } else { "cleared" })` updates when the
83/// referenced piece unmounts, as in the toggle demo on the showcase Tweaks page. (The
84/// `when`-arm's disposal lands at the turn boundary, after ordinary bindings re-ran;
85/// piggybacking on some other signal would read a stale mount state, while the trigger fires
86/// at the actual transition.) Main-thread only, like every realized-tree type.
87#[derive(Clone)]
88pub struct NativeRef {
89    cell: Rc<std::cell::Cell<Option<day_core::RNode>>>,
90    changed: day_reactive::Trigger,
91}
92
93impl Default for NativeRef {
94    fn default() -> Self {
95        Self::new()
96    }
97}
98
99impl NativeRef {
100    pub fn new() -> Self {
101        NativeRef {
102            cell: Rc::new(std::cell::Cell::new(None)),
103            changed: day_reactive::Trigger::new(),
104        }
105    }
106
107    /// The mounted node, if it is currently live. A tracked read (see the type docs).
108    pub fn node(&self) -> Option<day_core::RNode> {
109        self.changed.track();
110        let node = self.cell.get()?;
111        // Generational slotmap keys make a disposed node a clean miss, never a stale hit.
112        let live = day_core::try_with_tree(|t| t.node_kind(node).is_some()).unwrap_or(false);
113        live.then_some(node)
114    }
115
116    /// Run `f` with the live node (e.g. inside `day_toolkit_appkit::with_native`); `None` if disposed.
117    pub fn with<R>(&self, f: impl FnOnce(day_core::RNode) -> R) -> Option<R> {
118        self.node().map(f)
119    }
120
121    fn transition(&self, node: Option<day_core::RNode>) {
122        self.cell.set(node);
123        self.changed.notify();
124    }
125}
126
127/// A transparent native layer node (`CONTAINER`, no fill/clip/corner) used by the animatable
128/// modifiers (`.opacity`/`.transform`) to carry a per-node opacity or transform. Layout-transparent (`FillThrough`), so it never affects sizing and a
129/// granted stretch flows through to what it paints.
130fn layer_node(cx: &mut BuildCx) -> RNode {
131    cx.native(
132        kinds::CONTAINER,
133        &ContainerProps {
134            background: None,
135            corner_radius: 0.0,
136            clips: false,
137            role: None,
138        },
139        Rc::new(FillThrough),
140        Flex::default(),
141        Boundary::No,
142    )
143}
144
145// ---------------------------------------------------------------------------
146// Decorated: a piece plus its modifiers, with the piece's type kept (§5.2)
147// ---------------------------------------------------------------------------
148
149/// The build of a piece plus every modifier applied to it so far.
150type Build = Box<dyn FnOnce(&mut BuildCx) -> RNode>;
151
152/// A piece with modifiers chained onto it, keeping the decorated piece's type (§5.2).
153///
154/// Every [`Decorate`] modifier returns one of these rather than erasing to [`AnyPiece`], which is
155/// what lets a chain keep reaching the piece's builder methods: `label(…).padding(8.0)` is
156/// still a decorated `Label`, so `.font(…)` after it resolves. Modifiers applied to a `Decorated`
157/// append in place (the inherent methods below shadow the trait's), so a chain stays flat instead
158/// of nesting `Decorated<Decorated<…>>`.
159///
160/// Modifiers fall into three classes (docs/api-style.md "Modifier classes"), and only one of
161/// them is ordered:
162///
163/// - **Identity** (`id`, `id_of`) names the piece's own node, the one its build
164///   returns, wherever it sits in the chain: `label(t).padding(8.0).id(day_core::id!(x))` and
165///   `label(t).id(day_core::id!(x)).padding(8.0)` are the same tree.
166/// - **Wrapping** modifiers (`padding`, `frame`, `background`, `grow`, …) each add a node around
167///   what came before, so they compose outward in call order, as they read.
168/// - **Outer-layout facts** (`grid_span`, `grid_align`) describe the piece to the container it
169///   sits in, so they land on the outermost node whatever wrappers follow them.
170///
171/// `wrapper_id` is the one way to name a wrapper deliberately: it tags whatever node is
172/// outermost at the point it is called, for a frame assertion on a padded box.
173///
174/// Erase explicitly with `.any()` when a single [`AnyPiece`] is what's needed (a `Vec<AnyPiece>`, a
175/// `-> AnyPiece` signature).
176pub struct Decorated<P> {
177    inner: P,
178    /// Wrapping modifiers, applied outward in call order.
179    ops: Vec<Box<dyn FnOnce(Build) -> Build>>,
180    /// Identity modifiers, applied to the node the piece's own build returns.
181    node_ops: Vec<Box<dyn FnOnce(RNode)>>,
182    /// Outer-layout facts, applied to the outermost node once every wrapper is in place.
183    outer_ops: Vec<Box<dyn FnOnce(RNode)>>,
184}
185
186impl<P: Piece> Decorated<P> {
187    /// An undecorated piece, ready to have modifiers applied CONDITIONALLY. Starting here gives
188    /// every branch the same type, so an optional modifier needs no erasure:
189    ///
190    /// ```ignore
191    /// let leaf = Decorated::new(draw);
192    /// let leaf = match id { Some(id) => leaf.id(id), None => leaf };
193    /// let leaf = if editable { leaf.on_tap(f) } else { leaf };
194    /// ```
195    ///
196    /// [`apply_if`](Self::apply_if) and [`apply_some`](Self::apply_some) are the same move as a
197    /// chain step.
198    pub fn new(inner: P) -> Self {
199        Decorated {
200            inner,
201            ops: Vec::new(),
202            node_ops: Vec::new(),
203            outer_ops: Vec::new(),
204        }
205    }
206
207    fn push(mut self, op: impl FnOnce(Build) -> Build + 'static) -> Self {
208        self.ops.push(Box::new(op));
209        self
210    }
211
212    fn push_node(mut self, op: impl FnOnce(RNode) + 'static) -> Self {
213        self.node_ops.push(Box::new(op));
214        self
215    }
216
217    fn push_outer(mut self, op: impl FnOnce(RNode) + 'static) -> Self {
218        self.outer_ops.push(Box::new(op));
219        self
220    }
221
222    /// Replace the undecorated piece, keeping the modifier chain: how a typed builder trait
223    /// reaches through a decoration (docs/api-style.md "Typed builders"). `f` sees the piece as
224    /// it was before any modifier, which is why modifier order stops mattering.
225    pub fn map_inner<Q: Piece>(self, f: impl FnOnce(P) -> Q) -> Decorated<Q> {
226        Decorated {
227            inner: f(self.inner),
228            ops: self.ops,
229            node_ops: self.node_ops,
230            outer_ops: self.outer_ops,
231        }
232    }
233
234    /// Apply `f` to the chain when `cond` holds, else continue unchanged: the conditional
235    /// modifier, with no `let x = if c { x.m() } else { x }` rebinding and no erasure.
236    ///
237    /// ```ignore
238    /// nav(sel).apply_if(!primary, |n| n.local())
239    /// ```
240    ///
241    /// `cond` is a plain `bool` resolved at build, like the arms of a `match`; the modifiers
242    /// `f` applies may themselves be reactive.
243    pub fn apply_if(self, cond: bool, f: impl FnOnce(Self) -> Self) -> Self {
244        if cond { f(self) } else { self }
245    }
246
247    /// Apply `f` with the value when there is one, else continue unchanged:
248    /// `canvas(draw).apply_some(id, |c, id| c.id(id))`.
249    pub fn apply_some<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
250        match value {
251            Some(v) => f(self, v),
252            None => self,
253        }
254    }
255}
256
257impl<P: Piece> Piece for Decorated<P> {
258    fn build(self, cx: &mut BuildCx) -> RNode {
259        let Decorated {
260            inner,
261            ops,
262            node_ops,
263            outer_ops,
264        } = self;
265        // The piece's own node first, with its identity; then the wrappers, composed outward
266        // in call order (the first modifier is innermost); then the facts for the parent, on
267        // whatever ended up outermost.
268        let wraps = !ops.is_empty();
269        let own = Rc::new(Cell::new(None::<RNode>));
270        let own_out = own.clone();
271        let mut build: Build = Box::new(move |cx| {
272            let n = inner.build(cx);
273            for op in node_ops {
274                op(n);
275            }
276            own_out.set(Some(n));
277            n
278        });
279        for op in ops {
280            build = op(build);
281        }
282        let outer = build(cx);
283        // The span a gesture addressed to the piece's own node (where `.id` sits) climbs to
284        // reach a wrapper's `.on_tap` (day-core's `gesture_target`).
285        if wraps && let Some(n) = own.get() {
286            with_tree(|t| t.set_element_outer(n, outer));
287        }
288        for op in outer_ops {
289            op(outer);
290        }
291        outer
292    }
293}
294
295// --- The modifier bodies, written once and shared by the trait and the inherent impl ---
296
297fn op_id(id: day_core::ElementId) -> impl FnOnce(RNode) {
298    move |n| with_tree(|t| t.set_id(t.element_target(n), id.as_str().to_owned()))
299}
300
301fn op_id_of(id: impl Fn() -> day_core::ElementId + 'static) -> impl FnOnce(RNode) {
302    move |n| {
303        day_reactive::bind(id, move |s: &day_core::ElementId| {
304            let s = s.as_str().to_owned();
305            with_tree(|t| t.set_id(t.element_target(n), s));
306        });
307    }
308}
309
310/// Name whatever node is outermost at this point in the chain (see [`Decorated::wrapper_id`]).
311fn op_wrapper_id(id: day_core::ElementId) -> impl FnOnce(Build) -> Build {
312    move |inner| {
313        Box::new(move |cx| {
314            let n = inner(cx);
315            with_tree(|t| t.set_id(n, id.as_str().to_owned()));
316            n
317        })
318    }
319}
320
321fn op_tweak(f: impl FnOnce(day_core::RNode) + 'static) -> impl FnOnce(Build) -> Build {
322    move |inner| {
323        Box::new(move |cx| {
324            let n = inner(cx);
325            f(n);
326            // Mark the node so a later backing swap (`.selectable()` on a toolkit that
327            // rebuilds the widget) warns about the discarded tweak instead of losing it
328            // silently (docs/tweaks.md).
329            with_tree(|t| t.note_node_tweaked(n));
330            n
331        })
332    }
333}
334
335fn op_selectable() -> impl FnOnce(Build) -> Build {
336    move |inner| {
337        Box::new(move |cx| {
338            let n = inner(cx);
339            with_tree(|t| t.set_node_selectable(n, true));
340            n
341        })
342    }
343}
344
345fn op_cursor(cursor: Reactive<Cursor>) -> impl FnOnce(Build) -> Build {
346    move |inner| {
347        Box::new(move |cx| {
348            let n = inner(cx);
349            // Read before borrowing the tree: a reactive cursor is app code (a composed split's
350            // follows the app's axis closure), and app code may itself reach the tree.
351            let shape = cursor.get_untracked();
352            with_tree(|t| t.set_node_cursor(n, shape));
353            // Only a reactive source needs a binding; a constant shape is applied once at
354            // mount. The setter is idempotent, so a re-run costs one native call.
355            if let Reactive::Dyn(_) = &cursor {
356                bind(
357                    move || cursor.get(),
358                    move |c: &Cursor| {
359                        with_tree(|t| t.set_node_cursor(n, c.clone()));
360                    },
361                );
362            }
363            n
364        })
365    }
366}
367
368fn op_window_drag_region() -> impl FnOnce(Build) -> Build {
369    move |inner| {
370        Box::new(move |cx| {
371            let n = inner(cx);
372            with_tree(|t| t.set_node_drag_region(n, true));
373            n
374        })
375    }
376}
377
378fn op_native_ref(r: NativeRef) -> impl FnOnce(Build) -> Build {
379    move |inner| {
380        Box::new(move |cx| {
381            let n = inner(cx);
382            r.transition(Some(n));
383            let cleared = r.clone();
384            Scope::current().on_cleanup(move || cleared.transition(None));
385            n
386        })
387    }
388}
389
390fn op_padding(insets: Insets) -> impl FnOnce(Build) -> Build {
391    move |inner| {
392        Box::new(move |cx| {
393            let w = cx.layout_only(
394                Rc::new(PaddingLayout { insets }),
395                Flex::default(),
396                Boundary::No,
397            );
398            cx.under(w, |cx| {
399                let _ = inner(cx);
400            });
401            w
402        })
403    }
404}
405
406fn op_max_width(max: f64) -> impl FnOnce(Build) -> Build {
407    move |inner| {
408        Box::new(move |cx| {
409            let w = cx.layout_only(
410                Rc::new(MaxWidthLayout { max }),
411                Flex::default(),
412                Boundary::No,
413            );
414            cx.under(w, |cx| {
415                let _ = inner(cx);
416            });
417            w
418        })
419    }
420}
421
422fn op_max_height(max: f64) -> impl FnOnce(Build) -> Build {
423    move |inner| {
424        Box::new(move |cx| {
425            // Yielding, so a column sizes its other children first and gives this one what is
426            // left, up to `max`: a capped scroll gives way to the button under it on a short
427            // screen instead of pushing it out of the column, and the column still hugs.
428            let h = cx.layout_only(
429                Rc::new(day_core::MaxHeightLayout { max }),
430                Flex {
431                    yields_h: true,
432                    ..Flex::default()
433                },
434                Boundary::No,
435            );
436            cx.under(h, |cx| {
437                let _ = inner(cx);
438            });
439            h
440        })
441    }
442}
443
444fn op_min_width(min: f64) -> impl FnOnce(Build) -> Build {
445    move |inner| {
446        Box::new(move |cx| {
447            let w = cx.layout_only(
448                Rc::new(day_core::MinWidthLayout { min }),
449                Flex::default(),
450                Boundary::No,
451            );
452            cx.under(w, |cx| {
453                let _ = inner(cx);
454            });
455            w
456        })
457    }
458}
459
460fn op_min_height(min: f64) -> impl FnOnce(Build) -> Build {
461    move |inner| {
462        Box::new(move |cx| {
463            let node = cx.layout_only(
464                Rc::new(MinHeightLayout { min: min.max(0.0) }),
465                Flex::default(),
466                Boundary::No,
467            );
468            cx.under(node, |cx| {
469                let _ = inner(cx);
470            });
471            node
472        })
473    }
474}
475
476fn op_reserving(sample: TextSource) -> impl FnOnce(Build) -> Build {
477    move |inner| {
478        Box::new(move |cx| {
479            let wrapper = cx.layout_only(
480                Rc::new(day_core::ReserveLayout),
481                Flex::default(),
482                Boundary::No,
483            );
484            cx.under(wrapper, |cx| {
485                let content = inner(cx);
486                // Find the label through single-child wrappers after all typed builders have
487                // configured it. Multi-child pieces use the default Body font.
488                let font = with_tree(|tree| {
489                    let mut node = content;
490                    loop {
491                        if let Some(font) = tree.node_probe(node).and_then(|p| p.font) {
492                            break font;
493                        }
494                        if tree.child_count(node) != 1 {
495                            break day_spec::FontSpec::from(day_spec::Font::Body);
496                        }
497                        let Some(child) = tree.first_child(node) else {
498                            break day_spec::FontSpec::from(day_spec::Font::Body);
499                        };
500                        node = child;
501                    }
502                });
503                let sample_node = cx.leaf(
504                    day_spec::kinds::LABEL,
505                    &LabelProps {
506                        text: sample.initial(),
507                        font,
508                        wraps: false,
509                        ..Default::default()
510                    },
511                    Flex::default(),
512                );
513                with_tree(|tree| {
514                    tree.set_node_opacity(sample_node, 0.0);
515                    tree.set_a11y(
516                        sample_node,
517                        A11yProps {
518                            hidden: true,
519                            decorative: true,
520                            ..Default::default()
521                        },
522                    );
523                });
524                sample.bind_to(sample_node, |s| Box::new(LabelPatch::Text(s)), true);
525            });
526            wrapper
527        })
528    }
529}
530
531// The layout reads stored sizes, never signals. Bindings update those sizes outside the
532// tree borrow and invalidate measurement; native children and their scopes remain mounted.
533struct ReactiveFrameLayout {
534    size: Cell<(Option<f64>, Option<f64>)>,
535}
536impl ReactiveFrameLayout {
537    fn frame(&self) -> FrameLayout {
538        let (width, height) = self.size.get();
539        FrameLayout { width, height }
540    }
541}
542impl Layout for ReactiveFrameLayout {
543    fn measure(
544        &self,
545        cx: &mut dyn LayoutOps,
546        children: &[RNode],
547        p: day_spec::Proposal,
548    ) -> day_spec::Size {
549        self.frame().measure(cx, children, p)
550    }
551    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: day_spec::Rect) {
552        self.frame().place(cx, children, bounds);
553    }
554    fn baseline(
555        &self,
556        cx: &mut dyn LayoutOps,
557        children: &[RNode],
558        size: day_spec::Size,
559    ) -> Option<f64> {
560        self.frame().baseline(cx, children, size)
561    }
562}
563
564fn frame_extent(value: f64) -> f64 {
565    if value.is_finite() {
566        value.max(0.0)
567    } else {
568        0.0
569    }
570}
571
572fn op_frame(
573    width: Option<Reactive<f64>>,
574    height: Option<Reactive<f64>>,
575) -> impl FnOnce(Build) -> Build {
576    move |inner| {
577        Box::new(move |cx| {
578            let dynamic =
579                matches!(width, Some(Reactive::Dyn(_))) || matches!(height, Some(Reactive::Dyn(_)));
580            let read = move || {
581                (
582                    width.as_ref().map(|v| frame_extent(v.get())),
583                    height.as_ref().map(|v| frame_extent(v.get())),
584                )
585            };
586            let seed = day_reactive::untrack(&read);
587            let layout = Rc::new(ReactiveFrameLayout {
588                size: Cell::new(seed),
589            });
590            // Only a constant two-axis frame stops measurement propagation. A changing
591            // frame must invalidate ancestors too, so siblings move to their new positions.
592            let boundary = if !dynamic && seed.0.is_some() && seed.1.is_some() {
593                Boundary::Yes
594            } else {
595                Boundary::No
596            };
597            let node = cx.layout_only(layout.clone(), Flex::default(), boundary);
598            cx.under(node, |cx| {
599                let _ = inner(cx);
600            });
601            if dynamic {
602                day_reactive::bind_seeded(seed, read, move |size| {
603                    layout.size.set(*size);
604                    with_tree(|t| t.mark_needs_measure(node));
605                });
606            }
607            node
608        })
609    }
610}
611
612fn op_a11y(f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> impl FnOnce(Build) -> Build {
613    move |inner| {
614        Box::new(move |cx| {
615            let n = inner(cx);
616            let (props, live, selected) = f(A11yBuilder::default()).split();
617            let seed = props.selected;
618            with_tree(|t| t.set_a11y(n, props));
619            // The selected state follows its signal the same way: re-sent alone, merged by
620            // day-core onto the node's set.
621            if let Some(selected) = selected {
622                day_reactive::bind_seeded(
623                    seed.unwrap_or(false),
624                    move || selected.get(),
625                    move |on: &bool| {
626                        with_tree(|t| {
627                            t.set_a11y(
628                                n,
629                                A11yProps {
630                                    selected: Some(*on),
631                                    ..Default::default()
632                                },
633                            )
634                        })
635                    },
636                );
637            }
638            // A string that reads a signal or the locale re-sends itself alone; day-core
639            // merges it onto the node's set and re-applies the whole picture (§13).
640            for (src, patch) in live {
641                if let TextSource::Dyn(read) = src {
642                    let seed = day_reactive::untrack(|| read());
643                    day_reactive::bind_seeded(
644                        seed,
645                        move || read(),
646                        move |s: &String| with_tree(|t| t.set_a11y(n, patch(s.clone()))),
647                    );
648                }
649            }
650            n
651        })
652    }
653}
654
655fn op_on_tap(f: impl Fn() + 'static) -> impl FnOnce(Build) -> Build {
656    move |inner| {
657        Box::new(move |cx| {
658            let n = inner(cx);
659            with_tree(|t| t.enable_gesture(n, GestureKind::Tap));
660            cx.on(n, move |ev| {
661                if matches!(ev, Event::Tap(_)) {
662                    f();
663                }
664            });
665            n
666        })
667    }
668}
669
670fn op_on_tap_at(f: impl Fn(day_spec::Point) + 'static) -> impl FnOnce(Build) -> Build {
671    move |inner| {
672        Box::new(move |cx| {
673            let n = inner(cx);
674            with_tree(|t| t.enable_gesture(n, GestureKind::Tap));
675            cx.on(n, move |ev| {
676                if let Event::Tap(p) = ev {
677                    f(*p);
678                }
679            });
680            n
681        })
682    }
683}
684
685fn op_on_key(f: impl Fn(&day_spec::KeyEvent) + 'static) -> impl FnOnce(Build) -> Build {
686    move |inner| {
687        Box::new(move |cx| {
688            let n = inner(cx);
689            // Declare the intent as well as listening: a backend whose focused view would have
690            // to claim the key from the platform's dispatch checks this first. That check runs
691            // on the view, which sits below `n` when `n` is a layout wrapper (`.frame(..)`), so
692            // the view is marked too; the key it claims reaches this handler through the
693            // wrapper (day-core's dispatch).
694            day_spec::keys::mark(day_core::rnode_to_id(n));
695            if let Some(view) = with_tree(|t| t.native_view_of(n))
696                && view != n
697            {
698                day_spec::keys::mark(day_core::rnode_to_id(view));
699            }
700            cx.on(n, move |ev| {
701                if let Event::Key(k) = ev {
702                    f(k);
703                }
704            });
705            n
706        })
707    }
708}
709
710/// Declare toolbar items for the chrome this piece sits under (docs/toolbars.md).
711///
712/// The chrome is resolved where the piece is built, not where the modifier was written: the
713/// innermost navigation page being built, or the window when there is none. The design exists so
714/// that a command sits beside the content it acts on, and the app never says twice which bar it
715/// belongs to.
716fn op_toolbar(source: crate::ToolbarSource) -> impl FnOnce(Build) -> Build {
717    move |inner| {
718        Box::new(move |cx| {
719            let n = inner(cx);
720            crate::contribute(day_core::current_chrome(), source);
721            n
722        })
723    }
724}
725
726fn op_focusable() -> impl FnOnce(Build) -> Build {
727    move |inner| {
728        Box::new(move |cx| {
729            let n = inner(cx);
730            with_tree(|t| t.set_focusable(n, true));
731            n
732        })
733    }
734}
735
736fn op_keyboard() -> impl FnOnce(Build) -> Build {
737    move |inner| {
738        Box::new(move |cx| {
739            let n = inner(cx);
740            // The same two marks `on_key` leaves (the node and the native view under any
741            // layout wrapper), on the registry the full route reads.
742            day_spec::keys::mark_text(day_core::rnode_to_id(n));
743            if let Some(view) = with_tree(|t| t.native_view_of(n))
744                && view != n
745            {
746                day_spec::keys::mark_text(day_core::rnode_to_id(view));
747            }
748            n
749        })
750    }
751}
752
753fn op_focused(
754    want: Box<dyn Fn() -> bool>,
755    on_native: Box<dyn Fn(bool)>,
756) -> impl FnOnce(Build) -> Build {
757    move |inner| {
758        Box::new(move |cx| {
759            let n = inner(cx);
760            // Echo cell: the control's focus state as last reported by the native side. An
761            // apply whose desired state matches it is the echo of a native change (or already
762            // satisfied) and must not re-drive the toolkit: the nav host echo-cell rule.
763            let native = Rc::new(Cell::new(false));
764            {
765                let native = native.clone();
766                cx.on(n, move |ev| {
767                    if let Event::FocusChanged(f) = ev {
768                        native.set(*f);
769                        on_native(*f);
770                    }
771                });
772            }
773            // Signal → native, deferred one turn (`on_main`): focus is async by contract, and
774            // the deferral also lets a mount-time `Some(K::V)` land after the widget is in the
775            // window (dialog default focus). The initial `false` is not applied, because resigning
776            // focus the control never had would steal it from whoever has it.
777            let first = Cell::new(true);
778            bind(want, move |want: &bool| {
779                let want = *want;
780                if first.replace(false) && !want {
781                    return;
782                }
783                if native.get() == want {
784                    return;
785                }
786                day_reactive::on_main(move || with_tree(|t| t.focus_node(n, want)));
787            });
788            n
789        })
790    }
791}
792
793fn op_context_menu(items: Vec<MenuEntry>) -> impl FnOnce(Build) -> Build {
794    move |inner| {
795        Box::new(move |cx| {
796            // The overlay host places the decorated subtree at its own bounds and the
797            // composed-menu mount beside it (see `OverlayHost`; a plain sibling would sit
798            // under a single-child layout, never placed).
799            let w = cx.layout_only(Rc::new(OverlayHost), Flex::default(), Boundary::No);
800            let mut n = w;
801            cx.under(w, |cx| {
802                n = inner(cx);
803                // Scoped: the action closures die with the build scope, not the process;
804                // an unscoped registration here leaks one closure per remount.
805                let model = lower_menu_scoped(items);
806                with_tree(|t| t.set_context_menu(n, model.clone()));
807                // A backend with no native menu reports the summon instead; the composed
808                // presenter replays the same lowered model (docs/menus.md).
809                let model = std::rc::Rc::new(model);
810                crate::menus::mount_composed_menu(cx, n, Rc::new(move |_p| (*model).clone()));
811            });
812            // Sized by its content, so a platform row stays one through the menu's wrapper.
813            with_tree(|t| t.forward_whole_row(w, n));
814            // Later ops decorate the content node: ids, gestures and menus belong to it,
815            // while the wrapper only exists to keep the mount in the layout pass.
816            n
817        })
818    }
819}
820
821/// The `.context_menu*` wrapper's layout: the decorated subtree fills the wrapper; every
822/// other child (the composed menu's lazy mount) is layout-inert but must still be visited,
823/// because a cover lays its content out from the size the backend reports, but only if the
824/// place pass reaches it at all.
825pub(crate) struct OverlayHost;
826
827impl Layout for OverlayHost {
828    fn measure(
829        &self,
830        cx: &mut dyn LayoutOps,
831        children: &[day_core::RNode],
832        p: day_spec::Proposal,
833    ) -> day_spec::Size {
834        match children.first() {
835            Some(&c) => cx.measure_child(c, p),
836            None => day_spec::Size::ZERO,
837        }
838    }
839    fn place(&self, cx: &mut dyn LayoutOps, children: &[day_core::RNode], bounds: day_spec::Rect) {
840        let mut it = children.iter();
841        if let Some(&c) = it.next() {
842            cx.place_child(c, day_spec::Rect::from_size(bounds.size));
843        }
844        for &c in it {
845            cx.place_child(c, day_spec::Rect::ZERO);
846        }
847    }
848    fn baseline(
849        &self,
850        cx: &mut dyn LayoutOps,
851        children: &[day_core::RNode],
852        size: day_spec::Size,
853    ) -> Option<f64> {
854        children.first().and_then(|&c| cx.baseline_of(c, size))
855    }
856}
857
858fn op_context_menu_fn(
859    f: Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>,
860) -> impl FnOnce(Build) -> Build {
861    move |inner| {
862        Box::new(move |cx| {
863            let w = cx.layout_only(Rc::new(OverlayHost), Flex::default(), Boundary::No);
864            let mut out = w;
865            cx.under(w, |cx| {
866                out = op_context_menu_fn_body(inner, f, cx);
867            });
868            // Sized by its content, so a platform row stays one through the menu's wrapper.
869            with_tree(|t| t.forward_whole_row(w, out));
870            out
871        })
872    }
873}
874
875fn op_context_menu_fn_body(
876    inner: Build,
877    f: Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>,
878    cx: &mut day_core::BuildCx,
879) -> day_core::RNode {
880    {
881        {
882            let n = inner(cx);
883            // Each summon lowers a fresh menu whose action closures live in their own scope,
884            // disposed when the next summon replaces them (and with the build scope at
885            // teardown), so per-click menus never accumulate registrations.
886            let last: Rc<std::cell::RefCell<Option<day_reactive::Scope>>> = Rc::default();
887            {
888                let last = last.clone();
889                day_reactive::Scope::current().on_cleanup(move || {
890                    if let Some(s) = last.borrow_mut().take() {
891                        s.dispose();
892                    }
893                });
894            }
895            let provider: day_spec::ContextMenuFn = Rc::new(move |p| {
896                if let Some(s) = last.borrow_mut().take() {
897                    s.dispose();
898                }
899                let scope = day_reactive::Scope::child();
900                let items = scope.enter(|| crate::menus::lower_menu_scoped(f(p)));
901                *last.borrow_mut() = Some(scope);
902                items
903            });
904            with_tree(|t| t.set_context_menu_fn(n, provider.clone()));
905            // A backend with no native menu reports the summon instead; the composed
906            // presenter calls the same provider there (docs/menus.md).
907            crate::menus::mount_composed_menu(cx, n, provider);
908            n
909        }
910    }
911}
912
913fn op_on_drag(f: impl Fn(Drag) + 'static) -> impl FnOnce(Build) -> Build {
914    move |inner| {
915        Box::new(move |cx| {
916            let n = inner(cx);
917            with_tree(|t| t.enable_gesture(n, GestureKind::Drag));
918            cx.on(n, move |ev| {
919                if let Event::Drag {
920                    phase,
921                    location,
922                    translation,
923                } = ev
924                {
925                    f(Drag {
926                        phase: *phase,
927                        location: *location,
928                        translation: *translation,
929                    });
930                }
931            });
932            n
933        })
934    }
935}
936
937fn op_on_pinch(f: impl Fn(Pinch) + 'static) -> impl FnOnce(Build) -> Build {
938    move |inner| {
939        Box::new(move |cx| {
940            let n = inner(cx);
941            with_tree(|t| t.enable_gesture(n, GestureKind::Pinch));
942            cx.on(n, move |ev| {
943                if let Event::Pinch {
944                    phase,
945                    scale,
946                    location,
947                } = ev
948                {
949                    f(Pinch {
950                        phase: *phase,
951                        scale: *scale,
952                        location: *location,
953                    });
954                }
955            });
956            n
957        })
958    }
959}
960
961fn op_on_rotate(f: impl Fn(Rotate) + 'static) -> impl FnOnce(Build) -> Build {
962    move |inner| {
963        Box::new(move |cx| {
964            let n = inner(cx);
965            with_tree(|t| t.enable_gesture(n, GestureKind::Rotate));
966            cx.on(n, move |ev| {
967                if let Event::Rotate {
968                    phase,
969                    rotation,
970                    location,
971                } = ev
972                {
973                    f(Rotate {
974                        phase: *phase,
975                        rotation: *rotation,
976                        location: *location,
977                    });
978                }
979            });
980            n
981        })
982    }
983}
984
985fn op_on_hover(f: impl Fn(Option<day_spec::Point>) + 'static) -> impl FnOnce(Build) -> Build {
986    move |inner| {
987        Box::new(move |cx| {
988            let n = inner(cx);
989            with_tree(|t| t.enable_gesture(n, GestureKind::Hover));
990            cx.on(n, move |ev| {
991                if let Event::Hover { phase, location } = ev {
992                    // `None` on exit rather than a phase the caller has to match on: what a
993                    // hover handler wants to know is where the pointer IS, and "nowhere" is a
994                    // state, not an event kind. It is also what makes a handler that writes a
995                    // `Signal<Option<Point>>` a one-liner.
996                    f(match phase {
997                        day_spec::DragPhase::Ended => None,
998                        _ => Some(*location),
999                    });
1000                }
1001            });
1002            n
1003        })
1004    }
1005}
1006
1007fn op_on_pan(f: impl Fn(Pan) + 'static) -> impl FnOnce(Build) -> Build {
1008    move |inner| {
1009        Box::new(move |cx| {
1010            let n = inner(cx);
1011            with_tree(|t| t.enable_gesture(n, GestureKind::Pan));
1012            cx.on(n, move |ev| {
1013                if let Event::Pan {
1014                    phase,
1015                    delta,
1016                    location,
1017                } = ev
1018                {
1019                    f(Pan {
1020                        phase: *phase,
1021                        delta: *delta,
1022                        location: *location,
1023                    });
1024                }
1025            });
1026            n
1027        })
1028    }
1029}
1030
1031fn op_background(color: Reactive<Color>) -> impl FnOnce(Build) -> Build {
1032    move |inner| {
1033        Box::new(move |cx| {
1034            let node = cx.native(
1035                kinds::CONTAINER,
1036                &ContainerProps {
1037                    background: Some(color.get_untracked()),
1038                    corner_radius: 0.0,
1039                    clips: false,
1040                    role: None,
1041                },
1042                Rc::new(FillThrough),
1043                Flex::default(),
1044                Boundary::No,
1045            );
1046            cx.under(node, |cx| {
1047                let _ = inner(cx);
1048            });
1049            // Only a reactive source needs a binding; a constant fill is applied once at realize.
1050            if let Reactive::Dyn(_) = &color {
1051                bind(
1052                    move || color.get(),
1053                    move |c: &Color| {
1054                        with_tree(|t| {
1055                            t.patch(node, Box::new(ContainerPatch::Background(Some(*c))), false)
1056                        });
1057                    },
1058                );
1059            }
1060            node
1061        })
1062    }
1063}
1064
1065/// A semantic surface around the content: the toolkit's material for `role`, clipped to
1066/// `radius` corners.
1067fn op_surface(role: day_spec::SurfaceRole, radius: f64) -> impl FnOnce(Build) -> Build {
1068    move |inner| {
1069        Box::new(move |cx| {
1070            let w = cx.native(
1071                kinds::CONTAINER,
1072                &ContainerProps {
1073                    background: None,
1074                    corner_radius: radius,
1075                    clips: true,
1076                    role: Some(role),
1077                },
1078                Rc::new(FillThrough),
1079                Flex::default(),
1080                Boundary::No,
1081            );
1082            cx.under(w, |cx| {
1083                let _ = inner(cx);
1084            });
1085            w
1086        })
1087    }
1088}
1089
1090fn op_corner_radius(radius: f64) -> impl FnOnce(Build) -> Build {
1091    move |inner| {
1092        Box::new(move |cx| {
1093            let node = cx.native(
1094                kinds::CONTAINER,
1095                &ContainerProps {
1096                    background: None,
1097                    corner_radius: radius,
1098                    clips: true,
1099                    role: None,
1100                },
1101                Rc::new(FillThrough),
1102                Flex::default(),
1103                Boundary::No,
1104            );
1105            cx.under(node, |cx| {
1106                let _ = inner(cx);
1107            });
1108            node
1109        })
1110    }
1111}
1112
1113fn op_opacity(op: Reactive<f64>) -> impl FnOnce(Build) -> Build {
1114    move |inner| {
1115        Box::new(move |cx| {
1116            let node = layer_node(cx);
1117            cx.under(node, |cx| {
1118                let _ = inner(cx);
1119            });
1120            bind(
1121                move || op.get(),
1122                move |v: &f64| with_tree(|t| t.set_node_opacity(node, *v)),
1123            );
1124            node
1125        })
1126    }
1127}
1128
1129fn op_transform(t: Reactive<Transform>) -> impl FnOnce(Build) -> Build {
1130    move |inner| {
1131        Box::new(move |cx| {
1132            let node = layer_node(cx);
1133            cx.under(node, |cx| {
1134                let _ = inner(cx);
1135            });
1136            bind(
1137                move || t.get(),
1138                move |v: &Transform| with_tree(|tr| tr.set_node_transform(node, *v)),
1139            );
1140            node
1141        })
1142    }
1143}
1144
1145fn op_animation(anim: AnimSpec) -> impl FnOnce(Build) -> Build {
1146    move |inner| {
1147        Box::new(move |cx| {
1148            // Layout-only: the implicit animation is Day's own state, which the patches beneath
1149            // look up through their ancestors, and needs no native view. A native layer here
1150            // also clipped what it held on the toolkits whose containers clip their children
1151            // (Qt always, Android by default), so a translated or scaled view under
1152            // `.animation(..)` vanished past the layer's frame.
1153            let node = cx.layout_only(Rc::new(FillThrough), Flex::default(), Boundary::No);
1154            with_tree(|t| t.set_implicit_anim(node, Some(anim)));
1155            cx.under(node, |cx| {
1156                let _ = inner(cx);
1157            });
1158            node
1159        })
1160    }
1161}
1162
1163fn op_overlay_aligned(align: Alignment, over: impl Piece) -> impl FnOnce(Build) -> Build {
1164    move |inner| {
1165        Box::new(move |cx| {
1166            let node = cx.native(
1167                kinds::CONTAINER,
1168                &ContainerProps::default(),
1169                Rc::new(OverlayLayout {
1170                    align,
1171                    size_to_first: true,
1172                }),
1173                Flex::default(),
1174                Boundary::No,
1175            );
1176            cx.under(node, |cx| {
1177                let _ = inner(cx); // sizing content (bottom)
1178                let _ = over.build(cx); // annotation on top
1179            });
1180            node
1181        })
1182    }
1183}
1184
1185fn op_aspect_ratio(ratio: f64) -> impl FnOnce(Build) -> Build {
1186    move |inner| {
1187        Box::new(move |cx| {
1188            if !(ratio.is_finite() && ratio > 0.0) {
1189                return inner(cx);
1190            }
1191            let node = cx.layout_only(
1192                Rc::new(AspectRatioLayout { ratio }),
1193                Flex::default(),
1194                // Not a boundary: the child still measures itself, and the ratio only decides
1195                // the box it is offered.
1196                Boundary::No,
1197            );
1198            cx.under(node, |cx| {
1199                let _ = inner(cx);
1200            });
1201            node
1202        })
1203    }
1204}
1205
1206fn op_aligned(align: Alignment) -> impl FnOnce(Build) -> Build {
1207    move |inner| {
1208        Box::new(move |cx| {
1209            let node = cx.layout_only(
1210                Rc::new(AlignmentLayout { align }),
1211                Flex::default(),
1212                Boundary::No,
1213            );
1214            cx.under(node, |cx| {
1215                let _ = inner(cx);
1216            });
1217            node
1218        })
1219    }
1220}
1221
1222fn op_grow_axes(w: bool, h: bool) -> impl FnOnce(Build) -> Build {
1223    move |inner| {
1224        Box::new(move |cx| {
1225            let node = cx.layout_only(
1226                Rc::new(GrowLayout { w, h }),
1227                Flex {
1228                    grow_w: w,
1229                    grow_h: h,
1230                    ..Default::default()
1231                },
1232                Boundary::No,
1233            );
1234            cx.under(node, |cx| {
1235                let _ = inner(cx);
1236            });
1237            node
1238        })
1239    }
1240}
1241
1242fn op_grid_facts(facts: GridFacts) -> impl FnOnce(RNode) {
1243    move |node| with_tree(|t| t.set_grid_facts(node, facts))
1244}
1245
1246fn op_defers_system_gestures(edges: day_spec::Edges) -> impl FnOnce(Build) -> Build {
1247    move |inner| {
1248        Box::new(move |cx| {
1249            let token = day_core::shield::push_gesture_deferral(edges);
1250            Scope::current().on_cleanup(move || day_core::shield::pop_gesture_deferral(token));
1251            inner(cx)
1252        })
1253    }
1254}
1255
1256fn op_status_bar_hidden(hidden: Reactive<bool>) -> impl FnOnce(Build) -> Build {
1257    move |inner| {
1258        Box::new(move |cx| {
1259            let token = day_core::shield::push_status_bar_request(hidden.get_untracked());
1260            Scope::current().on_cleanup(move || day_core::shield::pop_status_bar_request(token));
1261            // A constant answer is registered once; a reactive one follows its source while
1262            // the subtree stays mounted (a reader's "hide status bar" setting).
1263            if let Reactive::Dyn(_) = &hidden {
1264                bind(
1265                    move || hidden.get(),
1266                    move |h: &bool| day_core::shield::set_status_bar_request(token, *h),
1267                );
1268            }
1269            inner(cx)
1270        })
1271    }
1272}
1273
1274fn op_on_system_back(
1275    enabled: Reactive<bool>,
1276    handler: Rc<dyn Fn()>,
1277) -> impl FnOnce(Build) -> Build {
1278    move |inner| {
1279        Box::new(move |cx| {
1280            crate::nav::install_back_handler(cx.parent(), enabled, handler);
1281            inner(cx)
1282        })
1283    }
1284}
1285
1286fn op_interactive_dismiss_disabled() -> impl FnOnce(Build) -> Build {
1287    move |inner| {
1288        Box::new(move |cx| {
1289            let token = day_core::shield::push_dismiss_disabled();
1290            Scope::current().on_cleanup(move || day_core::shield::pop_dismiss_disabled(token));
1291            inner(cx)
1292        })
1293    }
1294}
1295
1296// --- The chained modifier surface, on an already-decorated piece ---
1297//
1298// These inherent methods shadow the `Decorate` trait's (inherent wins method resolution), so a
1299// modifier applied to a `Decorated` appends to its op list instead of wrapping it in another
1300// `Decorated`. Each is the same one-liner the trait method is; the bodies live in the `op_*`
1301// functions above. Documentation stays on the trait, which is the surface every piece has.
1302impl<P: Piece> Decorated<P> {
1303    pub fn id(self, id: day_core::ElementId) -> Self {
1304        self.push_node(op_id(id))
1305    }
1306    pub fn id_of(self, id: impl Fn() -> day_core::ElementId + 'static) -> Self {
1307        self.push_node(op_id_of(id))
1308    }
1309    pub fn wrapper_id(self, id: day_core::ElementId) -> Self {
1310        self.push(op_wrapper_id(id))
1311    }
1312    pub fn tweak(self, f: impl FnOnce(day_core::RNode) + 'static) -> Self {
1313        self.push(op_tweak(f))
1314    }
1315    pub fn selectable(self) -> Self {
1316        self.push(op_selectable())
1317    }
1318    pub fn cursor<M>(self, cursor: impl IntoReactive<Cursor, M>) -> Self {
1319        self.push(op_cursor(cursor.into_reactive()))
1320    }
1321    pub fn native_ref(self, r: &NativeRef) -> Self {
1322        self.push(op_native_ref(r.clone()))
1323    }
1324    pub fn window_drag_region(self) -> Self {
1325        self.push(op_window_drag_region())
1326    }
1327    pub fn padding(self, insets: impl IntoInsets) -> Self {
1328        self.push(op_padding(insets.into_insets()))
1329    }
1330    pub fn max_width(self, max: f64) -> Self {
1331        self.push(op_max_width(max))
1332    }
1333    /// Never taller than `max`: the child is never proposed more height, so a scroll stops
1334    /// growing at `max` and still shrinks where the screen is shorter. In a column it is sized
1335    /// after its siblings and takes what they leave, up to `max`, so the controls around a
1336    /// capped scroll stay on screen.
1337    pub fn max_height(self, max: f64) -> Self {
1338        self.push(op_max_height(max))
1339    }
1340    /// Never narrower than `min`: a stretching control keeps a usable width, and a row that
1341    /// cannot give it that overflows, so a `labeled` row stacks the control under its label
1342    /// rather than squeezing it (docs/forms.md).
1343    pub fn min_width(self, min: f64) -> Self {
1344        self.push(op_min_width(min))
1345    }
1346    pub fn reserving<M>(self, sample: impl IntoText<M>) -> Self {
1347        self.push(op_reserving(sample.into_text()))
1348    }
1349    /// Set both dimensions from constants, signals, or reactive closures.
1350    /// Negative and non-finite sizes become zero. Updates preserve mounted content.
1351    pub fn frame<Mw, Mh>(
1352        self,
1353        width: impl IntoReactive<f64, Mw>,
1354        height: impl IntoReactive<f64, Mh>,
1355    ) -> Self {
1356        self.push(op_frame(
1357            Some(width.into_reactive()),
1358            Some(height.into_reactive()),
1359        ))
1360    }
1361    /// Set a constant or reactive width, leaving height flexible.
1362    pub fn width<M>(self, width: impl IntoReactive<f64, M>) -> Self {
1363        self.push(op_frame(Some(width.into_reactive()), None))
1364    }
1365    /// Set a constant or reactive height, leaving width flexible.
1366    pub fn height<M>(self, height: impl IntoReactive<f64, M>) -> Self {
1367        self.push(op_frame(None, Some(height.into_reactive())))
1368    }
1369    /// Keep at least `min` points of height, expanding for taller content.
1370    pub fn min_height(self, min: f64) -> Self {
1371        self.push(op_min_height(min))
1372    }
1373    pub fn a11y(self, f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> Self {
1374        self.push(op_a11y(f))
1375    }
1376    /// Handle a tap gesture on this piece.
1377    ///
1378    /// Do not use this to activate a native button; use [`crate::ButtonBuilder::action`].
1379    /// A separate gesture recognizer can delay pressed feedback and bypass native keyboard,
1380    /// accessibility, and disabled behavior. Day warns when it attaches a tap to a button.
1381    pub fn on_tap(self, f: impl Fn() + 'static) -> Self {
1382        self.push(op_on_tap(f))
1383    }
1384    /// Handle a tap with its local position. Like [`Self::on_tap`], this is a gesture,
1385    /// not native button activation; use [`crate::ButtonBuilder::action`] for buttons.
1386    pub fn on_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Self {
1387        self.push(op_on_tap_at(f))
1388    }
1389    pub fn focused<M>(self, binding: impl IntoFocusBinding<M>) -> Self {
1390        let (want, on_native) = binding.into_focus_binding();
1391        self.push(op_focused(want, on_native))
1392    }
1393    pub fn on_key(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Self {
1394        self.push(op_on_key(f))
1395    }
1396    pub fn focusable(self) -> Self {
1397        self.push(op_focusable())
1398    }
1399    pub fn keyboard(self) -> Self {
1400        self.push(op_keyboard())
1401    }
1402    pub fn toolbar<M>(self, content: impl crate::ToolbarContent<M>) -> Self {
1403        self.push(op_toolbar(content.into_source()))
1404    }
1405    /// See [`Decorate::searchable`].
1406    pub fn searchable(self, search: crate::Search) -> Self {
1407        self.push(move |inner| {
1408            Box::new(move |cx| {
1409                let n = inner(cx);
1410                crate::nav::install_page_search(search);
1411                n
1412            })
1413        })
1414    }
1415    /// Offer data through the platform's native drag session.
1416    pub fn drag_source(
1417        self,
1418        source: impl Fn(day_spec::Point) -> Option<day_spec::transfer::Offer> + 'static,
1419    ) -> Self {
1420        self.push(move |inner| {
1421            Box::new(move |cx| {
1422                let n = layer_node(cx);
1423                cx.under(n, |cx| {
1424                    inner(cx);
1425                });
1426                let source = scoped_drag_source(Rc::new(source));
1427                with_tree(|t| t.set_drag_source(n, source));
1428                n
1429            })
1430        })
1431    }
1432    /// Attach native drop acceptance policy and an owned-data receiver.
1433    pub fn drop_target(self, target: day_spec::transfer::Target) -> Self {
1434        self.push(move |inner| {
1435            Box::new(move |cx| {
1436                let n = layer_node(cx);
1437                cx.under(n, |cx| {
1438                    inner(cx);
1439                });
1440                let target = scoped_drop_target(target);
1441                with_tree(|t| t.set_drop_target(n, target));
1442                n
1443            })
1444        })
1445    }
1446    pub fn context_menu<M>(self, menu: impl ContextMenuContent<M>) -> Self {
1447        match menu.into_context_menu() {
1448            ContextMenuSource::Fixed(items) => self.push(op_context_menu(items)),
1449            ContextMenuSource::OnSummon(f) => self.push(op_context_menu_fn(f)),
1450        }
1451    }
1452    pub fn on_drag(self, f: impl Fn(Drag) + 'static) -> Self {
1453        self.push(op_on_drag(f))
1454    }
1455    pub fn on_pinch(self, f: impl Fn(Pinch) + 'static) -> Self {
1456        self.push(op_on_pinch(f))
1457    }
1458    pub fn on_rotate(self, f: impl Fn(Rotate) + 'static) -> Self {
1459        self.push(op_on_rotate(f))
1460    }
1461    pub fn on_pan(self, f: impl Fn(Pan) + 'static) -> Self {
1462        self.push(op_on_pan(f))
1463    }
1464    /// The pointer moving over this piece: `Some(point)` in its own coordinates while inside,
1465    /// `None` when it leaves (docs/canvas.md "Interaction").
1466    ///
1467    /// Pointer-only, which is not a gap: every desktop delivers it, an
1468    /// iPad does with a trackpad or pencil, an Android device with a mouse or stylus, and a
1469    /// touch-only phone delivers nothing at all. **Anything reachable by hover must also be
1470    /// reachable by a tap**: wire `on_tap_at` alongside it, exactly as a chart's selection does.
1471    pub fn on_hover(self, f: impl Fn(Option<day_spec::Point>) + 'static) -> Self {
1472        self.push(op_on_hover(f))
1473    }
1474    /// The platform's card: the grouped-content surface (`SurfaceRole::SectionCard`) with
1475    /// rounded corners and a `Space::M` inset. Drawn by the toolkit, so it follows the
1476    /// appearance and never steals hit testing from the content.
1477    pub fn card(self) -> Self {
1478        self.padding(crate::Space::M)
1479            .push(op_surface(day_spec::SurfaceRole::SectionCard, 10.0))
1480    }
1481    pub fn background<M>(self, color: impl IntoReactive<Color, M>) -> Self {
1482        self.push(op_background(color.into_reactive()))
1483    }
1484    pub fn corner_radius(self, radius: f64) -> Self {
1485        self.push(op_corner_radius(radius))
1486    }
1487    pub fn opacity<M>(self, opacity: impl IntoReactive<f64, M>) -> Self {
1488        self.push(op_opacity(opacity.into_reactive()))
1489    }
1490    pub fn transform<M>(self, t: impl IntoReactive<Transform, M>) -> Self {
1491        self.push(op_transform(t.into_reactive()))
1492    }
1493    pub fn scale<M>(self, factor: impl IntoReactive<f64, M>) -> Self {
1494        let f = factor.into_reactive();
1495        self.transform(move || Transform::scale(f.get(), f.get()))
1496    }
1497    pub fn rotation<M>(self, degrees: impl IntoReactive<f64, M>) -> Self {
1498        let d = degrees.into_reactive();
1499        self.transform(move || Transform::rotate(d.get()))
1500    }
1501    pub fn translation<Mx, My>(
1502        self,
1503        x: impl IntoReactive<f64, Mx>,
1504        y: impl IntoReactive<f64, My>,
1505    ) -> Self {
1506        let (x, y) = (x.into_reactive(), y.into_reactive());
1507        self.transform(move || Transform::translate(x.get(), y.get()))
1508    }
1509    pub fn animation(self, anim: AnimSpec) -> Self {
1510        self.push(op_animation(anim))
1511    }
1512    /// Erases, like [`Decorate::modifier`]: `Modifier` is defined over [`AnyPiece`].
1513    pub fn modifier(self, m: impl Modifier) -> AnyPiece {
1514        m.apply(self.any())
1515    }
1516    pub fn overlay(self, over: impl Piece) -> Self {
1517        self.overlay_aligned(Alignment::Center, over)
1518    }
1519    pub fn overlay_aligned(self, align: Alignment, over: impl Piece) -> Self {
1520        self.push(op_overlay_aligned(align, over))
1521    }
1522    pub fn aspect_ratio(self, ratio: f64) -> Self {
1523        self.push(op_aspect_ratio(ratio))
1524    }
1525    /// Position this piece within its assigned space; see [`Decorate::aligned`].
1526    pub fn aligned(self, alignment: Alignment) -> Self {
1527        self.push(op_aligned(alignment))
1528    }
1529    /// Expand in the selected dimensions; see [`Decorate::grow`].
1530    pub fn grow(self, dimension: Dimension) -> Self {
1531        self.push(op_grow_axes(
1532            matches!(dimension, Dimension::Width | Dimension::Both),
1533            matches!(dimension, Dimension::Height | Dimension::Both),
1534        ))
1535    }
1536    #[deprecated(note = "use .grow(Dimension::Width)")]
1537    pub fn grow_w(self) -> Self {
1538        self.grow(Dimension::Width)
1539    }
1540    #[deprecated(note = "use .grow(Dimension::Height)")]
1541    pub fn grow_h(self) -> Self {
1542        self.grow(Dimension::Height)
1543    }
1544    pub fn grid_span(self, n: usize) -> Self {
1545        self.push_outer(op_grid_facts(GridFacts {
1546            col_span: n.clamp(1, u16::MAX as usize) as u16,
1547            ..Default::default()
1548        }))
1549    }
1550    pub fn grid_align(self, a: Alignment) -> Self {
1551        self.push_outer(op_grid_facts(GridFacts {
1552            align: Some(a),
1553            ..Default::default()
1554        }))
1555    }
1556    pub fn defers_system_gestures(self, edges: day_spec::Edges) -> Self {
1557        self.push(op_defers_system_gestures(edges))
1558    }
1559    pub fn interactive_dismiss_disabled(self) -> Self {
1560        self.push(op_interactive_dismiss_disabled())
1561    }
1562    pub fn on_system_back<M>(
1563        self,
1564        enabled: impl IntoReactive<bool, M>,
1565        handler: impl Fn() + 'static,
1566    ) -> Self {
1567        self.push(op_on_system_back(enabled.into_reactive(), Rc::new(handler)))
1568    }
1569    pub fn status_bar_hidden<M>(self, hidden: impl IntoReactive<bool, M>) -> Self {
1570        self.push(op_status_bar_hidden(hidden.into_reactive()))
1571    }
1572    /// Erase to a single [`AnyPiece`].
1573    pub fn any(self) -> AnyPiece {
1574        AnyPiece::new(self)
1575    }
1576}
1577
1578/// Where a context menu's entries come from (see [`Decorate::context_menu`]).
1579pub enum ContextMenuSource {
1580    Fixed(Vec<MenuEntry>),
1581    OnSummon(Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>),
1582}
1583
1584/// Anything [`Decorate::context_menu`] accepts: a `Vec` or array of entries, a closure building
1585/// them on summon, or a closure given the summon point. The marker parameter is the same E0119
1586/// dodge as [`IntoText`].
1587pub trait ContextMenuContent<M> {
1588    fn into_context_menu(self) -> ContextMenuSource;
1589}
1590
1591/// Marker for a summon-time closure that takes the summon point.
1592pub struct AtPointMark;
1593
1594impl ContextMenuContent<crate::ManyMark> for Vec<MenuEntry> {
1595    fn into_context_menu(self) -> ContextMenuSource {
1596        ContextMenuSource::Fixed(self)
1597    }
1598}
1599
1600impl<const N: usize> ContextMenuContent<crate::ManyMark> for [MenuEntry; N] {
1601    fn into_context_menu(self) -> ContextMenuSource {
1602        ContextMenuSource::Fixed(Vec::from(self))
1603    }
1604}
1605
1606impl<C, F> ContextMenuContent<crate::DerivedMark> for F
1607where
1608    C: IntoIterator<Item = MenuEntry>,
1609    F: Fn() -> C + 'static,
1610{
1611    fn into_context_menu(self) -> ContextMenuSource {
1612        ContextMenuSource::OnSummon(Rc::new(move |_| self().into_iter().collect()))
1613    }
1614}
1615
1616impl<C, F> ContextMenuContent<AtPointMark> for F
1617where
1618    C: IntoIterator<Item = MenuEntry>,
1619    F: Fn(day_spec::Point) -> C + 'static,
1620{
1621    fn into_context_menu(self) -> ContextMenuSource {
1622        ContextMenuSource::OnSummon(Rc::new(move |p| self(p).into_iter().collect()))
1623    }
1624}
1625
1626pub trait Decorate: Piece + Sized {
1627    /// Stable element identifier: a11y identifier + dayscript locator + lint uniqueness (§5.5).
1628    ///
1629    /// Names the piece's own node wherever it sits in the chain (docs/api-style.md "Modifier
1630    /// classes"): `.padding(8.0).id(day_core::id!(x))` and `.id(day_core::id!(x)).padding(8.0)` tag the same node. To name
1631    /// a wrapper instead, use [`wrapper_id`](Self::wrapper_id).
1632    fn id(self, id: day_core::ElementId) -> Decorated<Self> {
1633        Decorated::new(self).id(id)
1634    }
1635
1636    /// Name the node that is outermost at this point in the chain: the padding box, the frame,
1637    /// the background, whichever wrapper the modifiers before it built. For a dayscript frame
1638    /// assertion on the wrapper rather than on the piece. Ordered, unlike [`id`](Self::id).
1639    fn wrapper_id(self, id: day_core::ElementId) -> Decorated<Self> {
1640        Decorated::new(self).wrapper_id(id)
1641    }
1642
1643    /// Apply `f` to the chain when `cond` holds, else continue unchanged
1644    /// (see [`Decorated::apply_if`]): `nav(sel).apply_if(!primary, |n| n.local())`. The
1645    /// closure receives the decorated piece, so forwarded builder methods and modifiers both
1646    /// chain inside it.
1647    fn apply_if(
1648        self,
1649        cond: bool,
1650        f: impl FnOnce(Decorated<Self>) -> Decorated<Self>,
1651    ) -> Decorated<Self> {
1652        Decorated::new(self).apply_if(cond, f)
1653    }
1654
1655    /// Apply `f` with the value when there is one, else continue unchanged
1656    /// (see [`Decorated::apply_some`]): `canvas(draw).apply_some(id, |c, id| c.id(id))`.
1657    fn apply_some<T>(
1658        self,
1659        value: Option<T>,
1660        f: impl FnOnce(Decorated<Self>, T) -> Decorated<Self>,
1661    ) -> Decorated<Self> {
1662        Decorated::new(self).apply_some(value, f)
1663    }
1664
1665    /// Reactive element id: the id for rows inside a recycling [`list`](crate::list). A plain
1666    /// [`id`](Self::id) is assigned once at build, but a recycled cell rebinds to different
1667    /// items over its life (and drag-to-reorder rebinds eagerly), so a static item-derived id
1668    /// keeps naming the first-bound item. This variant re-registers whenever the closure's
1669    /// value changes; read your `ItemSlot` inside it:
1670    /// `.id_of(move || day_core::id!(row_remove, slot.key()))`.
1671    fn id_of(self, id: impl Fn() -> day_core::ElementId + 'static) -> Decorated<Self> {
1672        Decorated::new(self).id_of(id)
1673    }
1674
1675    /// Apply a **tweak**: `f` runs once at mount, after the native widget exists, with the
1676    /// realized node (docs/tweaks.md). Reach the typed native handle through the compiled
1677    /// backend's ext accessor (`day_toolkit_appkit::with_native`, `day_toolkit_gtk::with_native`, …), or apply
1678    /// a packaged `day-tweak-*` crate's modifier instead of calling this directly. If the native
1679    /// change affects the widget's intrinsic size, follow it with
1680    /// [`day_core::invalidate_size`]. Day may overwrite *managed* properties (title, value,
1681    /// enabled, frame, a11y) on its next patch; unmanaged properties are stable.
1682    ///
1683    /// Order it after any modifier that can rebuild the backing widget; today that is
1684    /// [`selectable`](Decorate::selectable), which on UIKit realizes the label as a different
1685    /// native class. Chained before it, the tweak runs against the widget the rebuild discards
1686    /// (Day warns at runtime); chained after, it sees the widget that ships.
1687    fn tweak(self, f: impl FnOnce(day_core::RNode) + 'static) -> Decorated<Self> {
1688        Decorated::new(self).tweak(f)
1689    }
1690
1691    /// Make this piece's text **user-selectable**, so the reader can select and copy it
1692    /// (docs/text.md). Most useful on a [`label`](crate::label): text is not selectable by default
1693    /// on any backend, matching each platform's native behavior.
1694    ///
1695    /// Every backend honors it on a label: most flip the native widget's selection affordance
1696    /// (AppKit, GTK, Qt, XAML, HarmonyOS, Android, web); UIKit, whose `UILabel` has none,
1697    /// rebuilds the label as a read-only `UITextView` behind the same handle. On other widgets
1698    /// it is best-effort: a backing with no selection affordance leaves the text unselectable
1699    /// rather than erroring, and a container cascades only where the platform's affordance does
1700    /// (the web), so prefer the label itself. Selection visuals and the copy shortcut are the
1701    /// platform's own. Unmanaged: set once at mount, and it survives Day's text updates.
1702    fn selectable(self) -> Decorated<Self> {
1703        Decorated::new(self).selectable()
1704    }
1705
1706    /// Shape the pointer while it is over this piece and its descendants (docs/cursor.md): a
1707    /// [`Cursor`] constant, a `Signal<Cursor>`, or a closure, so a canvas tool or a busy state
1708    /// moves the shape without rebuilding the piece. The nearest ancestor's cursor wins, and
1709    /// `Cursor::Default` releases the piece back to the platform. `capability(Cap::Cursor)`
1710    /// says whether this toolkit draws the requested shapes, a nearest neighbor, or nothing;
1711    /// a touch-only host never shows one, which is correct rather than a failure.
1712    fn cursor<M>(self, cursor: impl IntoReactive<Cursor, M>) -> Decorated<Self> {
1713        Decorated::new(self).cursor(cursor)
1714    }
1715
1716    /// Let the user move the window by dragging this piece, as a title bar does
1717    /// (docs/window-chrome.md): what a custom title bar in a [`WindowChrome::Overlay`] or
1718    /// [`WindowChrome::Frameless`] window needs. The piece's own background starts the drag,
1719    /// with the platform's snapping and tiling; buttons and fields inside it keep their clicks;
1720    /// a double click does what the user's title-bar setting says (zoom, minimize, nothing).
1721    /// `capability(Cap::DragRegion)`; on a phone the piece is an ordinary view.
1722    ///
1723    /// [`WindowChrome::Overlay`]: day_spec::WindowChrome::Overlay
1724    /// [`WindowChrome::Frameless`]: day_spec::WindowChrome::Frameless
1725    fn window_drag_region(self) -> Decorated<Self> {
1726        Decorated::new(self).window_drag_region()
1727    }
1728
1729    /// Capture a [`NativeRef`] to this piece's realized node for later imperative access
1730    /// (docs/tweaks.md). The ref clears automatically when the piece's scope is disposed.
1731    fn native_ref(self, r: &NativeRef) -> Decorated<Self> {
1732        Decorated::new(self).native_ref(r)
1733    }
1734
1735    fn padding(self, insets: impl IntoInsets) -> Decorated<Self> {
1736        Decorated::new(self).padding(insets)
1737    }
1738
1739    /// Cap this piece's width at `max` points: the child is never PROPOSED more, so text
1740    /// wraps inside the cap (chat bubbles, readable columns) while narrower content hugs.
1741    fn max_width(self, max: f64) -> Decorated<Self> {
1742        Decorated::new(self).max_width(max)
1743    }
1744    /// Cap this piece's height at `max` points, the vertical twin of [`Decorate::max_width`]: a
1745    /// scroll or another piece that takes the height it is offered stops at `max`, and still
1746    /// gets less where its parent has less to give.
1747    fn max_height(self, max: f64) -> Decorated<Self> {
1748        Decorated::new(self).max_height(max)
1749    }
1750    /// See [`Decorated::min_width`].
1751    fn min_width(self, min: f64) -> Decorated<Self> {
1752        Decorated::new(self).min_width(min)
1753    }
1754
1755    /// Keep at least `min` points of height, expanding for taller content.
1756    fn min_height(self, min: f64) -> Decorated<Self> {
1757        Decorated::new(self).min_height(min)
1758    }
1759
1760    /// Reserve at least the space `sample` needs, so this piece's size stops changing with its
1761    /// content.
1762    ///
1763    /// For a numeric readout beside a slider: `label(move || value()).reserving("100")` keeps the
1764    /// row still while the number changes, because the reservation is a real measurement of
1765    /// `"100"` in this piece's own font: it scales with the platform's accessibility text size
1766    /// instead of being a point value that clips when someone turns text up.
1767    ///
1768    /// Pass the widest value the field can show (`"100"`, `"-99.9"`, `"88:88"`). Pair it with
1769    /// tabular numbers so the digits themselves stop shifting inside the reservation.
1770    /// Localized text, signals and closures update the reservation without rebuilding the label.
1771    /// Single-child wrappers preserve the label's font; other pieces use the default Body font.
1772    /// The sample is placed at zero size and hidden from assistive technology.
1773    fn reserving<M>(self, sample: impl IntoText<M>) -> Decorated<Self> {
1774        Decorated::new(self).reserving(sample)
1775    }
1776
1777    fn frame<Mw, Mh>(
1778        self,
1779        width: impl IntoReactive<f64, Mw>,
1780        height: impl IntoReactive<f64, Mh>,
1781    ) -> Decorated<Self> {
1782        Decorated::new(self).frame(width, height)
1783    }
1784
1785    /// Fix this piece's width to `width` points while its height stays flexible (hugging its
1786    /// content or filling on the cross axis). The single-axis complement to [`Self::frame`], e.g.
1787    /// a fixed-width sidebar pane in a `row` whose height fills the window.
1788    fn width<M>(self, width: impl IntoReactive<f64, M>) -> Decorated<Self> {
1789        Decorated::new(self).width(width)
1790    }
1791
1792    /// Fix this piece's height to `height` points while its width stays flexible. The single-axis
1793    /// complement to [`Self::frame`], e.g. a fixed-height header/toolbar bar that fills its width.
1794    fn height<M>(self, height: impl IntoReactive<f64, M>) -> Decorated<Self> {
1795        Decorated::new(self).height(height)
1796    }
1797
1798    fn a11y(self, f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> Decorated<Self> {
1799        Decorated::new(self).a11y(f)
1800    }
1801
1802    /// Fire when this piece is tapped (bounding-box; shapes override with path-precise testing).
1803    ///
1804    /// Do not use this to activate a native button; use [`crate::Button::action`] instead.
1805    /// A separate gesture recognizer can delay pressed feedback and bypass native keyboard,
1806    /// accessibility, and disabled behavior. Day warns when it attaches a tap to a button.
1807    fn on_tap(self, f: impl Fn() + 'static) -> Decorated<Self> {
1808        Decorated::new(self).on_tap(f)
1809    }
1810
1811    /// [`on_tap`](Self::on_tap), told where: the point in the piece's own coordinate space,
1812    /// origin at its top-leading corner.
1813    ///
1814    /// What a drawn control needs and a native one does not: a canvas showing a color wheel, a
1815    /// map, or a waveform has to turn "the user pressed here" into a value, and only the piece
1816    /// knows how. Pair it with [`on_drag`](Self::on_drag), which already reports a location, to
1817    /// track a press that turns into a drag; the two are idempotent together, so a backend that
1818    /// reports a tap as a zero-length drag costs nothing.
1819    ///
1820    /// `Event::Tap` has always carried the point; this is the decorator that stops throwing it
1821    /// away.
1822    ///
1823    /// For native buttons use [`crate::Button::action`], not this gesture decorator.
1824    fn on_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Decorated<Self> {
1825        Decorated::new(self).on_tap_at(f)
1826    }
1827
1828    /// Bind this control's keyboard focus to a signal (docs/focus.md), two-way like every other
1829    /// binding: native focus changes write the signal; writing the signal moves focus. Takes a
1830    /// `Signal<bool>` for one control, or `(Signal<Option<K>>, K::Variant)` binding one control
1831    /// of a group; writing `false`/`None` resigns focus (dismissing the soft keyboard on
1832    /// mobile). Focus applies asynchronously: a write is a request, resolved on the next turn,
1833    /// and the signal always ends up reflecting what the platform actually did.
1834    fn focused<M>(self, binding: impl IntoFocusBinding<M>) -> Decorated<Self> {
1835        Decorated::new(self).focused(binding)
1836    }
1837
1838    /// Handle the non-text keys (the arrows) that reach this piece while it has focus
1839    /// (docs/menus.md). Keys follow focus, so pair it with [`Decorate::focused`] or with a
1840    /// piece the user can click into: a canvas takes focus on a press, and only the focused
1841    /// piece hears the keys, so a nudge handler can never fire while a text field, a list or a
1842    /// sidebar is the one being typed into.
1843    ///
1844    /// Which pieces can hold focus is the platform's to answer (docs/focus.md): a `canvas`
1845    /// is focusable on the backends that draw one from a real view (appkit, web-dom today).
1846    fn on_key(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Decorated<Self> {
1847        Decorated::new(self).on_key(f)
1848    }
1849
1850    /// Declare toolbar items on the chrome this piece sits under (docs/toolbars.md).
1851    ///
1852    /// Takes one item, a list of them, or a closure that derives the list and re-runs whenever
1853    /// its reactive reads change:
1854    ///
1855    /// ```ignore
1856    /// page.toolbar(toolbar_button(day_core::id!(share), tr("share")).icon(Symbol::Share).action(share))
1857    /// page.toolbar([reply, forward, archive])
1858    /// page.toolbar(move || vec![toolbar_button(day_core::id!(undo), tr("undo")).enabled(can_undo)])
1859    /// ```
1860    ///
1861    /// Which chrome carries them follows from where this piece is built (a destination page's
1862    /// own bar, a content-list pane's, or the window's if it is under no page at all), and the
1863    /// items are withdrawn when this piece is disposed. Where on that chrome they sit is
1864    /// [`ToolbarEntry::placement`](crate::ToolbarEntry::placement).
1865    fn toolbar<M>(self, content: impl crate::ToolbarContent<M>) -> Decorated<Self> {
1866        Decorated::new(self).toolbar(content)
1867    }
1868
1869    /// A search field for this navigation page (docs/search.md, "Page search"), drawn where the
1870    /// platform puts a page's search: the window toolbar on a desktop, the page's navigation bar
1871    /// on iOS (a `UISearchController`), its app bar on Android. It shows while this page does, and
1872    /// its text is the app's `query` both ways. For a search the server runs, act on
1873    /// [`crate::Search::on_submit`]; for a local filter, read the query. Declare it on a
1874    /// `nav_stack` destination, as `.toolbar(…)` is declared; a whole navigation surface takes
1875    /// [`crate::Nav::searchable`] instead.
1876    fn searchable(self, search: crate::Search) -> Decorated<Self> {
1877        Decorated::new(self).searchable(search)
1878    }
1879
1880    /// Opt this piece into the platform's focus system (docs/focus.md): the canvas contract
1881    /// for anything composed: it joins the key loop, takes focus on a press, reports through
1882    /// `.focused(…)`, and hears the arrows through `.on_key(…)` while focused. A composed
1883    /// list column is the motivating case (docs/navigation.md). On a backend without the
1884    /// `set_focusable` duty the piece renders normally and never takes focus.
1885    fn focusable(self) -> Decorated<Self> {
1886        Decorated::new(self).focusable()
1887    }
1888
1889    /// Take the whole keyboard while this piece is focused (docs/menus.md "The full route"):
1890    /// every key the platform delivers reaches [`Decorate::on_key`], not only the arrows and
1891    /// digits. A key that types nothing is named by its web name, a key that types by its
1892    /// unmodified character, and what it typed rides in [`day_spec::KeyEvent::text`]: the
1893    /// character, or the whole string an input method committed (a dead-key accent, a
1894    /// Japanese phrase), delivered once, after the composition. Control chords arrive with
1895    /// [`day_spec::KeyEvent::CONTROL`] set and no text; only the platform's own command
1896    /// chords (⌘ on Apple platforms) stay with the menu. On a phone, focusing the piece
1897    /// raises the soft keyboard, the way focusing a text field does, and what it types
1898    /// arrives the same way. For a terminal, a code editor or a game that reads letters, on
1899    /// a `canvas`:
1900    ///
1901    /// ```ignore
1902    /// canvas(draw).keyboard().on_key(move |k| match k.typed() {
1903    ///     Some(text) => term.type_text(text),
1904    ///     None => term.press(&k.key, k.modifiers),
1905    /// })
1906    /// ```
1907    ///
1908    /// Pair it with [`Decorate::on_key`]: it declares the route, the handler hears it, and a
1909    /// declaration with no handler claims nothing. The route is the canvas's (the one piece
1910    /// with no native control under it); a `.focusable()` container keeps the short route.
1911    /// A piece that takes the whole keyboard also takes the Tab key, so it leaves the
1912    /// platform's focus walking: a press elsewhere, or writing `.focused(false)`, gives the
1913    /// keyboard back.
1914    fn keyboard(self) -> Decorated<Self> {
1915        Decorated::new(self).keyboard()
1916    }
1917
1918    /// Attach a context menu, shown with the platform's native affordance on secondary-click (desktop)
1919    /// or long-press (mobile). Items are built with [`menu_item`]/[`sub_menu`]/[`menu_role`]/
1920    /// [`menu_separator`]. Passing an empty `Vec` removes any menu.
1921    fn drag_source(
1922        self,
1923        source: impl Fn(day_spec::Point) -> Option<day_spec::transfer::Offer> + 'static,
1924    ) -> Decorated<Self> {
1925        Decorated::new(self).drag_source(source)
1926    }
1927    fn drop_target(self, target: day_spec::transfer::Target) -> Decorated<Self> {
1928        Decorated::new(self).drop_target(target)
1929    }
1930    /// A context menu (docs/menus.md): shown on secondary-click / long-press, built from the
1931    /// same `menu_item`/`sub_menu` entries as everywhere else. Takes a fixed list, or a closure
1932    /// built when the menu is summoned ("Dynamic context menus"): with no argument, or with the
1933    /// summon point in this piece's own coordinates, so a canvas can select what is under the
1934    /// pointer and offer commands for that selection. An empty result shows nothing.
1935    ///
1936    /// ```ignore
1937    /// label(t).context_menu([menu_item(res::str::copy()).action(copy)])
1938    /// canvas(draw).context_menu(move |at: Point| commands_for(hit_test(at)))
1939    /// ```
1940    fn context_menu<M>(self, menu: impl ContextMenuContent<M>) -> Decorated<Self> {
1941        Decorated::new(self).context_menu(menu)
1942    }
1943
1944    fn on_drag(self, f: impl Fn(Drag) + 'static) -> Decorated<Self> {
1945        Decorated::new(self).on_drag(f)
1946    }
1947
1948    /// Fire on each phase of a pinch/magnify over this piece (docs/canvas.md "Zoom and
1949    /// pan"). Only backends with a native recognizer wired emit it; pair a zoom with
1950    /// visible controls.
1951    fn on_pinch(self, f: impl Fn(Pinch) + 'static) -> Decorated<Self> {
1952        Decorated::new(self).on_pinch(f)
1953    }
1954
1955    /// Fire on each phase of a two-finger rotation over this piece (docs/canvas.md "Zoom and
1956    /// pan"). `rotation` is in radians, cumulative within a gesture, positive clockwise; a
1957    /// trackpad tick arrives as a lone `Changed`. Pair it with a visible way back to north.
1958    fn on_rotate(self, f: impl Fn(Rotate) + 'static) -> Decorated<Self> {
1959        Decorated::new(self).on_rotate(f)
1960    }
1961
1962    /// Fire on each viewport-pan event over this piece (docs/canvas.md "Zoom and pan"):
1963    /// trackpad two-finger scroll, two-finger touch pan. `delta` is incremental; apply it
1964    /// as it arrives.
1965    fn on_pan(self, f: impl Fn(Pan) + 'static) -> Decorated<Self> {
1966        Decorated::new(self).on_pan(f)
1967    }
1968
1969    /// The pointer moving over this piece: `Some(point)` in its own coordinates while inside,
1970    /// `None` when it leaves (docs/canvas.md "Interaction"). Pointer-only; wire `on_tap_at`
1971    /// alongside it so a touch-only device can reach the same thing.
1972    fn on_hover(self, f: impl Fn(Option<day_spec::Point>) + 'static) -> Decorated<Self> {
1973        Decorated::new(self).on_hover(f)
1974    }
1975
1976    /// Fill the piece's bounds with a solid color painted behind it: a message-bubble / card /
1977    /// badge surface. Accepts a constant [`Color`], a `Signal<Color>`, or a `Fn() -> Color`; a
1978    /// reactive color repaints the surface when its source changes. Wraps the piece in a native
1979    /// container that carries the fill, so it composes with [`Self::corner_radius`] for a rounded
1980    /// colored surface and with [`Self::padding`] for interior inset.
1981    /// The platform's card around this piece: the grouped-content surface with rounded
1982    /// corners and a `Space::M` inset (see [`Decorated::card`]).
1983    fn card(self) -> Decorated<Self> {
1984        Decorated::new(self).card()
1985    }
1986
1987    fn background<M>(self, color: impl IntoReactive<Color, M>) -> Decorated<Self> {
1988        Decorated::new(self).background(color)
1989    }
1990
1991    /// Round the piece's corners to `radius` points, clipping its background and content to the
1992    /// rounded rectangle. Compose after [`Self::background`] for a rounded colored surface, or use
1993    /// alone to round a clipped child (e.g. an avatar image).
1994    fn corner_radius(self, radius: f64) -> Decorated<Self> {
1995        Decorated::new(self).corner_radius(radius)
1996    }
1997
1998    /// Animate/set the piece's opacity (`0.0` transparent … `1.0` opaque). Wrapped in a native
1999    /// layer so it composes with `.background`; the change animates when made inside
2000    /// [`with_animation`] or under a `.animation` ancestor (§8.4).
2001    fn opacity<M>(self, opacity: impl IntoReactive<f64, M>) -> Decorated<Self> {
2002        Decorated::new(self).opacity(opacity)
2003    }
2004
2005    /// Apply an animatable [`Transform`] (translate/scale/rotate about the center): the cheap
2006    /// movement/scaling channel that never triggers relayout (§8.4). Prefer this over `.offset`
2007    /// for animated motion.
2008    fn transform<M>(self, t: impl IntoReactive<Transform, M>) -> Decorated<Self> {
2009        Decorated::new(self).transform(t)
2010    }
2011
2012    /// Uniformly scale the piece by `factor` about its center (animatable). Convenience over
2013    /// [`Self::transform`].
2014    fn scale<M>(self, factor: impl IntoReactive<f64, M>) -> Decorated<Self> {
2015        Decorated::new(self).scale(factor)
2016    }
2017
2018    /// Rotate the piece by `degrees` clockwise about its center (animatable).
2019    fn rotation<M>(self, degrees: impl IntoReactive<f64, M>) -> Decorated<Self> {
2020        Decorated::new(self).rotation(degrees)
2021    }
2022
2023    /// Translate the piece by (`x`, `y`) points without relayout (animatable): the
2024    /// animation-friendly sibling of `.offset`.
2025    fn translation<Mx, My>(
2026        self,
2027        x: impl IntoReactive<f64, Mx>,
2028        y: impl IntoReactive<f64, My>,
2029    ) -> Decorated<Self> {
2030        Decorated::new(self).translation(x, y)
2031    }
2032
2033    /// Attach an implicit animation (§8.4): changes to this piece's (and its descendants')
2034    /// animatable properties animate with `anim` even outside a [`with_animation`]. SwiftUI's
2035    /// `.animation`. The ambient `with_animation` takes precedence when both apply.
2036    fn animation(self, anim: AnimSpec) -> Decorated<Self> {
2037        Decorated::new(self).animation(anim)
2038    }
2039
2040    /// Apply a [`Modifier`] (or, via the blanket impl, a plain `FnOnce(AnyPiece) -> AnyPiece`
2041    /// closure) to this piece. Pure composition: `content.modifier(m) == m.apply(content.any())`.
2042    ///
2043    /// The one modifier that erases: `Modifier` is defined over [`AnyPiece`], so the piece's own
2044    /// type cannot survive it.
2045    fn modifier(self, m: impl Modifier) -> AnyPiece {
2046        m.apply(self.any())
2047    }
2048
2049    /// Draw `over` on top of this piece, centered, without affecting layout size: a badge /
2050    /// annotation overlay. `self` is the sizing content (bottom of the z-order); `over` is proposed
2051    /// `self`'s size and drawn on top. For an explicit alignment use [`Self::overlay_aligned`]; for
2052    /// a stack that sizes to the union of its children use [`zstack`].
2053    fn overlay(self, over: impl Piece) -> Decorated<Self> {
2054        Decorated::new(self).overlay(over)
2055    }
2056
2057    /// [`Self::overlay`] with an explicit [`Alignment`] for the annotation (e.g. a corner badge with
2058    /// [`Alignment::TopTrailing`]).
2059    fn overlay_aligned(self, align: Alignment, over: impl Piece) -> Decorated<Self> {
2060        Decorated::new(self).overlay_aligned(align, over)
2061    }
2062
2063    /// Constrain this piece to a `width / height` ratio: the largest box of that shape which
2064    /// fits whatever the parent offers (SwiftUI's `.aspectRatio(_:contentMode: .fit)`).
2065    ///
2066    /// Pair it with [`Self::grow`] and [`Dimension::Width`] to take the available width and
2067    /// derive the height from it: a `canvas` whose drawing keeps its proportions as the window
2068    /// resizes, say. `image` has carried this since it shipped; this is the same layout, for any
2069    /// piece.
2070    ///
2071    /// A ratio that is not finite and positive describes no box, so it is ignored.
2072    fn aspect_ratio(self, ratio: f64) -> Decorated<Self> {
2073        Decorated::new(self).aspect_ratio(ratio)
2074    }
2075
2076    /// Position this piece within its assigned space without stretching its content.
2077    ///
2078    /// Alignment alone hugs the content. Apply growth or a frame afterward to provide room:
2079    /// `piece.aligned(Alignment::Center).grow(Dimension::Width)` centers a naturally sized
2080    /// piece across the available width. Reversing that order centers already-expanded content.
2081    /// Leading and trailing follow the locale's layout direction. This adds no native view,
2082    /// accessibility role, or focus stop; text alignment remains a separate piece setting.
2083    fn aligned(self, alignment: Alignment) -> Decorated<Self> {
2084        Decorated::new(self).aligned(alignment)
2085    }
2086
2087    /// Expand to fill the space offered in the selected dimensions.
2088    ///
2089    /// Other dimensions hug the content. An unbounded proposal (such as a scroll view's
2090    /// scrolling axis) keeps the content's measured size. This layout-only wrapper carries
2091    /// grow [`Flex`] so its parent can allocate extra space; it adds no native view.
2092    fn grow(self, dimension: Dimension) -> Decorated<Self> {
2093        Decorated::new(self).grow(dimension)
2094    }
2095
2096    #[deprecated(note = "use .grow(Dimension::Width)")]
2097    fn grow_w(self) -> Decorated<Self> {
2098        Decorated::new(self).grow(Dimension::Width)
2099    }
2100
2101    #[deprecated(note = "use .grow(Dimension::Height)")]
2102    fn grow_h(self) -> Decorated<Self> {
2103        Decorated::new(self).grow(Dimension::Height)
2104    }
2105
2106    #[doc(hidden)]
2107    /// Span `n` columns (n ≥ 1) of the enclosing [`grid`] (docs/grid.md). Grid modifiers apply
2108    /// to the outermost layout node after wrapping modifiers, regardless of their chain position.
2109    fn grid_span(self, n: usize) -> Decorated<Self> {
2110        Decorated::new(self).grid_span(n)
2111    }
2112
2113    /// Override this cell's alignment within its cell rect of the enclosing [`grid`]
2114    /// (docs/grid.md). Like [`Decorated::grid_span`], this applies outside wrapping modifiers
2115    /// regardless of its position in the chain.
2116    fn grid_align(self, a: Alignment) -> Decorated<Self> {
2117        Decorated::new(self).grid_align(a)
2118    }
2119
2120    /// While this subtree is mounted, ask the OS to require a second swipe for its edge
2121    /// gestures on `edges` (docs/cover.md), the SwiftUI `defersSystemGestures(on:)`
2122    /// analogue. Put it on a game or drawing surface whose touches run to the screen edge,
2123    /// so a swipe up from the bottom doesn't leave the app. iOS defers the chosen edges'
2124    /// system gestures; Android enters swipe-to-reveal immersive mode while any subtree
2125    /// requests deferral; desktop backends no-op.
2126    fn defers_system_gestures(self, edges: day_spec::Edges) -> Decorated<Self> {
2127        Decorated::new(self).defers_system_gestures(edges)
2128    }
2129
2130    /// While this subtree is mounted and `hidden` is true, hide the system status bar, the
2131    /// SwiftUI `statusBarHidden(_:)` analogue (docs/cover.md). `hidden` is a constant, a
2132    /// `Signal`, or a closure, so a setting can turn it on and off in place. Put it on a page
2133    /// that wants the whole screen (a reader, a game, a photo viewer); the bar returns when
2134    /// the page unmounts. Any mounted request that answers true hides the bar. iOS, Android and
2135    /// HarmonyOS hide it (`Cap::StatusBarHidden`); desktop and web have none and ignore it.
2136    fn status_bar_hidden<M>(self, hidden: impl IntoReactive<bool, M>) -> Decorated<Self> {
2137        Decorated::new(self).status_bar_hidden(hidden)
2138    }
2139
2140    /// While this subtree is mounted, the enclosing [`cover`] (or other modal surface) must
2141    /// not be dismissed interactively, the SwiftUI `interactiveDismissDisabled()` analogue
2142    /// (docs/cover.md). System back / sheet gestures are ignored; only programmatic writes
2143    /// (an explicit close control) dismiss it.
2144    fn interactive_dismiss_disabled(self) -> Decorated<Self> {
2145        Decorated::new(self).interactive_dismiss_disabled()
2146    }
2147
2148    /// While this subtree is mounted and `enabled` holds, a back nothing else takes runs
2149    /// `handler` instead of the platform's default: Jetpack Compose's `BackHandler(enabled)`
2150    /// (docs/navigation.md "Handling the system Back"). `enabled` is a constant, a `Signal`, or
2151    /// a closure, followed as it changes.
2152    ///
2153    /// The back is Android's system back button and gesture (predictive back included),
2154    /// HarmonyOS's back gesture, [`nav_back()`](crate::nav_back), and dayscript's `nav_back`
2155    /// step in both forms. Navigation answers first: a presented [`cover`] closes and a pushed
2156    /// page pops before any handler runs, so the handler takes only the back that would have
2157    /// left the app (on a phone) or done nothing (on a desktop). Among several, the handler in
2158    /// the topmost cover wins, then the one nested most deeply in the piece tree, then the most
2159    /// recently mounted. A page's own "leave this page?" policy belongs on
2160    /// [`NavStack::on_back`] instead.
2161    ///
2162    /// Disabled (or unmounted) on Android, the system back is released again, so the
2163    /// predictive "back to home" preview shows whenever the press would leave the app.
2164    ///
2165    /// ```ignore
2166    /// // A browser: Back goes back in the page's history while the tab can.
2167    /// page_view(tab).on_system_back(move || tab.can_go_back(), move || tab.go_back())
2168    /// ```
2169    fn on_system_back<M>(
2170        self,
2171        enabled: impl IntoReactive<bool, M>,
2172        handler: impl Fn() + 'static,
2173    ) -> Decorated<Self> {
2174        Decorated::new(self).on_system_back(enabled, handler)
2175    }
2176
2177    /// Erase to a single [`AnyPiece`]: for a `Vec<AnyPiece>`, a `-> AnyPiece` signature, or any other
2178    /// place one concrete type is required. [`AnyPiece::any`] is inherent and returns `self`, so
2179    /// erasing an already-erased piece costs nothing.
2180    fn any(self) -> AnyPiece {
2181        AnyPiece::new(self)
2182    }
2183}
2184
2185impl<P: Piece> Decorate for P {}
2186
2187/// One a11y string that reads a signal or the locale, with the patch that re-sends it alone.
2188type LiveA11yString = (TextSource, fn(String) -> A11yProps);
2189
2190/// The annotations `.a11y(|a| …)` collects (docs/accessibility.md). The three strings are
2191/// [`TextSource`]s, so each takes a literal, a `String`, a `Signal<String>` or a closure: a
2192/// gauge's value follows the gauge, and a localized label follows the locale.
2193#[derive(Default)]
2194pub struct A11yBuilder {
2195    label: Option<TextSource>,
2196    hint: Option<TextSource>,
2197    value: Option<TextSource>,
2198    /// The selected state, reactive so a tab or row follows the selection.
2199    selected: Option<Reactive<bool>>,
2200    props: A11yProps,
2201}
2202
2203impl A11yBuilder {
2204    /// What the screen reader calls the element.
2205    pub fn label<M>(mut self, s: impl IntoText<M>) -> Self {
2206        self.label = Some(s.into_text());
2207        self
2208    }
2209    /// A longer description of what the element does.
2210    pub fn hint<M>(mut self, s: impl IntoText<M>) -> Self {
2211        self.hint = Some(s.into_text());
2212        self
2213    }
2214    /// The control's current value read aloud by the screen reader (e.g. a `Meter`'s "72%").
2215    /// Reactive like the others: `.value(move || format!("{:.0}%", level.get()))` re-sends the
2216    /// value whenever `level` changes.
2217    pub fn value<M>(mut self, s: impl IntoText<M>) -> Self {
2218        self.value = Some(s.into_text());
2219        self
2220    }
2221    pub fn role(mut self, r: Role) -> Self {
2222        self.props.role = r;
2223        self
2224    }
2225    /// Whether this element is the selected one among its peers (a `Role::Tab`, a row): the
2226    /// platform's selected state, which a screen reader reads as "selected". Reactive like the
2227    /// strings: `.selected(move || current.get() == key)` re-sends it when the selection moves.
2228    pub fn selected<M>(mut self, on: impl IntoReactive<bool, M>) -> Self {
2229        self.selected = Some(on.into_reactive());
2230        self
2231    }
2232    /// Hide this element from assistive tech (still visible on screen), e.g. a redundant chrome
2233    /// element already announced by its labeled sibling.
2234    pub fn hidden(mut self) -> Self {
2235        self.props.hidden = true;
2236        self
2237    }
2238    /// Purely decorative (a background flourish): hidden from assistive tech and, for images,
2239    /// exempt from the "needs a label" lint (§13).
2240    pub fn decorative(mut self) -> Self {
2241        self.props.decorative = true;
2242        self.props.hidden = true;
2243        self
2244    }
2245
2246    /// The annotations as first applied, with every string resolved once, the sources that
2247    /// can change, each paired with the patch that re-sends it, and the selected state when it
2248    /// reads a signal.
2249    fn split(self) -> (A11yProps, Vec<LiveA11yString>, Option<Reactive<bool>>) {
2250        let mut props = self.props;
2251        let mut live = Vec::new();
2252        let selected = match self.selected {
2253            Some(Reactive::Const(on)) => {
2254                props.selected = Some(on);
2255                None
2256            }
2257            Some(dynamic @ Reactive::Dyn(_)) => {
2258                props.selected = Some(day_reactive::untrack(|| dynamic.get()));
2259                Some(dynamic)
2260            }
2261            None => None,
2262        };
2263        let mut take =
2264            |src: Option<TextSource>, slot: &mut Option<String>, patch: fn(String) -> A11yProps| {
2265                if let Some(src) = src {
2266                    *slot = Some(src.initial());
2267                    if matches!(src, TextSource::Dyn(_)) {
2268                        live.push((src, patch));
2269                    }
2270                }
2271            };
2272        take(self.label, &mut props.label, |label| A11yProps {
2273            label: Some(label),
2274            ..Default::default()
2275        });
2276        take(self.hint, &mut props.hint, |hint| A11yProps {
2277            hint: Some(hint),
2278            ..Default::default()
2279        });
2280        take(self.value, &mut props.value, |value| A11yProps {
2281            value: Some(value),
2282            ..Default::default()
2283        });
2284        (props, live, selected)
2285    }
2286}
2287
2288// Native callbacks arrive outside the event dispatcher. Enter their owning scope so
2289// window ambient state resolves correctly, and reject callbacks retained after disposal.
2290fn scoped_drag_source(source: day_spec::transfer::Source) -> day_spec::transfer::Source {
2291    let scope = Scope::current();
2292    let alive = Rc::new(Cell::new(true));
2293    let cleanup = alive.clone();
2294    scope.on_cleanup(move || cleanup.set(false));
2295    Rc::new(move |point| alive.get().then(|| scope.enter(|| source(point))).flatten())
2296}
2297fn scoped_drop_target(target: day_spec::transfer::Target) -> day_spec::transfer::Target {
2298    let scope = Scope::current();
2299    let alive = Rc::new(Cell::new(true));
2300    let cleanup = alive.clone();
2301    scope.on_cleanup(move || cleanup.set(false));
2302    let accept_alive = alive.clone();
2303    day_spec::transfer::Target {
2304        types: target.types,
2305        accept: Rc::new(move |location| {
2306            if accept_alive.get() {
2307                scope.enter(|| (target.accept)(location))
2308            } else {
2309                day_spec::transfer::Operation::None
2310            }
2311        }),
2312        receive: Rc::new(move |drop| alive.get() && scope.enter(|| (target.receive)(drop))),
2313    }
2314}
2315
2316// ---------------------------------------------------------------------------
2317// Conformance cases (docs/testing.md)
2318// ---------------------------------------------------------------------------
2319
2320/// The modifiers' `#[day::test]` cases, next to the `Decorate` methods they prove.
2321#[cfg(feature = "conformance")]
2322pub(crate) mod conformance {
2323    use day_core::AnyPiece;
2324    use day_core::conformance::{Case, Drive, FrameExpect};
2325    use day_reactive::Signal;
2326    use day_spec::{Cap, Color, DragPhase, Transform};
2327
2328    use crate::*;
2329
2330    fn size(width: f64, height: f64) -> FrameExpect {
2331        FrameExpect {
2332            width: Some(width),
2333            height: Some(height),
2334            ..Default::default()
2335        }
2336    }
2337
2338    #[day_macros::test(day_core)]
2339    fn reactive_frame_and_minimum_height() -> Case {
2340        let width = Signal::new(80.0);
2341        let height = Signal::new(44.0);
2342        Case::new()
2343            .proves_modifier("width")
2344            .proves_modifier("height")
2345            .proves_modifier("frame")
2346            .proves_modifier("min_height")
2347            .page(move || {
2348                column((
2349                    rectangle()
2350                        .fill(day_spec::Color::hex(0x336699))
2351                        .frame(width, height)
2352                        .id(day_core::id!(resizing)),
2353                    rectangle()
2354                        .fill(day_spec::Color::hex(0x663399))
2355                        .width(width)
2356                        .height(20.0)
2357                        .min_height(44.0)
2358                        .id(day_core::id!(minimum)),
2359                    button("Resize fixture")
2360                        .action(move || {
2361                            width.set(120.0);
2362                            height.set(64.0);
2363                        })
2364                        .id(day_core::id!(resize)),
2365                ))
2366                .spacing(0.0)
2367            })
2368            .drive(|d: Drive| async move {
2369                d.assert_frame("resizing", size(80.0, 44.0)).await?;
2370                d.assert_frame("minimum", size(80.0, 44.0)).await?;
2371                d.tap("resize").await?;
2372                d.assert_frame("resizing", size(120.0, 64.0)).await?;
2373                d.assert_frame("minimum", size(120.0, 44.0)).await
2374            })
2375    }
2376
2377    #[day_macros::test(day_core)]
2378    fn text_reservation() -> Case {
2379        let value = Signal::new("1".to_owned());
2380        let sample = Signal::new("8888".to_owned());
2381        Case::new()
2382            .proves_modifier("reserving")
2383            .page(move || {
2384                column((
2385                    label(value)
2386                        .reserving(sample)
2387                        .font(day_spec::Font::Title2)
2388                        .tabular()
2389                        .id(day_core::id!(reserved_readout)),
2390                    label("8888")
2391                        .font(day_spec::Font::Title2)
2392                        .tabular()
2393                        .id(day_core::id!(reservation_reference)),
2394                    label("88888888")
2395                        .font(day_spec::Font::Title2)
2396                        .tabular()
2397                        .id(day_core::id!(reservation_expanded)),
2398                    button("Update fixture value")
2399                        .action(move || value.set("88".into()))
2400                        .id(day_core::id!(reservation_update)),
2401                    button("Expand fixture sample")
2402                        .action(move || sample.set("88888888".into()))
2403                        .id(day_core::id!(reservation_expand)),
2404                ))
2405                .align(HAlign::Leading)
2406            })
2407            .drive(|d: Drive| async move {
2408                let dimensions = |id: &str| {
2409                    day_core::with_tree(|tree| {
2410                        tree.node_frame(tree.find_by_id(id).unwrap()).unwrap().size
2411                    })
2412                };
2413                let reference = dimensions("reservation_reference");
2414                d.assert_frame("reserved_readout", size(reference.width, reference.height))
2415                    .await?;
2416                d.tap("reservation_update").await?;
2417                d.assert_text("reserved_readout", "88").await?;
2418                d.assert_frame("reserved_readout", size(reference.width, reference.height))
2419                    .await?;
2420                d.tap("reservation_expand").await?;
2421                let expanded = dimensions("reservation_expanded");
2422                d.assert_frame("reserved_readout", size(expanded.width, expanded.height))
2423                    .await?;
2424                d.assert_text("reserved_readout", "88").await
2425            })
2426    }
2427
2428    /// Padding grows the frame by its insets and moves the content in by them.
2429    #[day_macros::test(day_core)]
2430    fn padding_insets() -> Case {
2431        Case::new()
2432            .proves_modifier("padding")
2433            .proves_modifier("wrapper_id")
2434            .page(|| {
2435                // `id` names the rectangle wherever it sits; the padding box is a wrapper, so
2436                // it is named with `wrapper_id`, the one ordered identity modifier.
2437                rectangle()
2438                    .fill(Color::rgb(1.0, 0.0, 0.0))
2439                    .id(day_core::id!(inner))
2440                    .frame(40.0, 20.0)
2441                    .padding(10.0)
2442                    .wrapper_id(day_core::id!(outer))
2443            })
2444            .drive(|d: Drive| async move {
2445                d.assert_frame("outer", size(60.0, 40.0)).await?;
2446                d.assert_frame(
2447                    "inner",
2448                    FrameExpect {
2449                        x: Some(10.0),
2450                        y: Some(10.0),
2451                        relative_to: Some("outer".into()),
2452                        ..Default::default()
2453                    },
2454                )
2455                .await
2456            })
2457    }
2458
2459    /// A minimum width widens a narrow piece; a maximum narrows a wide one.
2460    #[day_macros::test(day_core)]
2461    fn min_max_width() -> Case {
2462        Case::new()
2463            .proves_modifier("min_width")
2464            .proves_modifier("max_width")
2465            .page(|| {
2466                column((
2467                    // The widened box, not the label's own node.
2468                    label("Hi").min_width(120.0).wrapper_id(day_core::id!(min)),
2469                    label("A label long enough that it would run past eighty points")
2470                        .max_width(80.0)
2471                        .wrapper_id(day_core::id!(max)),
2472                ))
2473                .align(HAlign::Leading)
2474            })
2475            .drive(|d: Drive| async move {
2476                d.assert_frame(
2477                    "min",
2478                    FrameExpect {
2479                        width: Some(120.0),
2480                        ..Default::default()
2481                    },
2482                )
2483                .await?;
2484                d.assert_frame(
2485                    "max",
2486                    FrameExpect {
2487                        width: Some(80.0),
2488                        ..Default::default()
2489                    },
2490                )
2491                .await
2492            })
2493    }
2494
2495    /// A maximum height stops a scroll, which takes all the height it is offered, at the cap.
2496    #[day_macros::test(day_core)]
2497    fn max_height_caps_a_scroll() -> Case {
2498        Case::new()
2499            .proves_modifier("max_height")
2500            .page(|| {
2501                column((
2502                    scroll(column((
2503                        label("One"),
2504                        label("Two"),
2505                        label("Three"),
2506                        label("Four"),
2507                        label("Five"),
2508                        label("Six"),
2509                    )))
2510                    .max_height(60.0)
2511                    .wrapper_id(day_core::id!(capped)),
2512                    spacer(),
2513                ))
2514                .align(HAlign::Leading)
2515            })
2516            .drive(|d: Drive| async move {
2517                d.assert_frame(
2518                    "capped",
2519                    FrameExpect {
2520                        height: Some(60.0),
2521                        ..Default::default()
2522                    },
2523                )
2524                .await
2525            })
2526    }
2527
2528    /// An aspect ratio sets the height from the width.
2529    #[day_macros::test(day_core)]
2530    fn aspect_ratio_height() -> Case {
2531        Case::new()
2532            .proves_modifier("aspect_ratio")
2533            .page(|| {
2534                rectangle()
2535                    .fill(Color::rgb(0.0, 0.0, 1.0))
2536                    .aspect_ratio(2.0)
2537                    .id(day_core::id!(shape))
2538                    .width(100.0)
2539            })
2540            .drive(|d: Drive| async move { d.assert_frame("shape", size(100.0, 50.0)).await })
2541    }
2542
2543    /// A growing child takes the row's remaining width.
2544    #[day_macros::test(day_core)]
2545    fn grow_width() -> Case {
2546        Case::new()
2547            .proves_modifier("grow")
2548            .page(|| {
2549                row((
2550                    rectangle()
2551                        .fill(Color::rgb(1.0, 0.0, 0.0))
2552                        .frame(40.0, 20.0),
2553                    rectangle()
2554                        .fill(Color::rgb(0.0, 0.0, 1.0))
2555                        .height(20.0)
2556                        .grow(Dimension::Width)
2557                        .id(day_core::id!(grower)),
2558                ))
2559                .spacing(0.0)
2560                .width(200.0)
2561            })
2562            .drive(|d: Drive| async move {
2563                d.assert_frame(
2564                    "grower",
2565                    FrameExpect {
2566                        width: Some(160.0),
2567                        ..Default::default()
2568                    },
2569                )
2570                .await
2571            })
2572    }
2573
2574    /// Alignment preserves the child's size inside an explicitly sized area.
2575    #[day_macros::test(day_core)]
2576    fn aligned_intrinsic_frame() -> Case {
2577        Case::new()
2578            .proves_modifier("aligned")
2579            .page(|| {
2580                // A native container gives both layout and toolkit probes the same origin,
2581                // independent of window chrome and mobile safe-area insets.
2582                zstack((rectangle()
2583                    .fill(Color::rgb(0.2, 0.5, 0.8))
2584                    .frame(40.0, 20.0)
2585                    .id(day_core::id!(aligned_child))
2586                    .aligned(day_core::Alignment::BottomTrailing)
2587                    .frame(200.0, 100.0),))
2588                .id(day_core::id!(aligned_container))
2589                .frame(200.0, 100.0)
2590            })
2591            .drive(|d: Drive| async move {
2592                d.assert_frame("aligned_container", size(200.0, 100.0))
2593                    .await?;
2594                d.assert_frame(
2595                    "aligned_child",
2596                    FrameExpect {
2597                        x: Some(160.0),
2598                        y: Some(80.0),
2599                        width: Some(40.0),
2600                        height: Some(20.0),
2601                        relative_to: Some("aligned_container".into()),
2602                        ..Default::default()
2603                    },
2604                )
2605                .await
2606            })
2607    }
2608
2609    /// An aligned overlay draws over its base, in the corner it names.
2610    #[day_macros::test(day_core)]
2611    fn overlay_aligned_corner() -> Case {
2612        Case::new()
2613            .proves_modifier("overlay_aligned")
2614            .requires(Cap::Snapshot)
2615            .page(|| {
2616                rectangle()
2617                    .fill(Color::rgb(1.0, 0.0, 0.0))
2618                    .frame(100.0, 60.0)
2619                    .overlay_aligned(
2620                        day_core::Alignment::BottomTrailing,
2621                        rectangle()
2622                            .fill(Color::rgb(0.0, 0.0, 1.0))
2623                            .frame(20.0, 20.0),
2624                    )
2625                    .id(day_core::id!(base))
2626            })
2627            .drive(|d: Drive| async move {
2628                d.sample_pixel("base", 0.95, 0.9, "#0000ff").await?;
2629                d.sample_pixel("base", 0.1, 0.1, "#ff0000").await
2630            })
2631    }
2632
2633    /// A background fills the piece's frame.
2634    #[day_macros::test(day_core)]
2635    fn background_fill() -> Case {
2636        Case::new()
2637            .proves_modifier("background")
2638            .requires(Cap::Snapshot)
2639            .page(|| {
2640                label("")
2641                    .frame(80.0, 40.0)
2642                    .background(Color::rgb(1.0, 0.0, 0.0))
2643                    .id(day_core::id!(filled))
2644            })
2645            .drive(|d: Drive| async move { d.sample_pixel("filled", 0.5, 0.5, "#ff0000").await })
2646    }
2647
2648    /// A corner radius cuts a background's corners and keeps its middle.
2649    #[day_macros::test(day_core)]
2650    fn corner_radius_cuts() -> Case {
2651        Case::new()
2652            .proves_modifier("corner_radius")
2653            .requires(Cap::Snapshot)
2654            .page(|| {
2655                zstack((
2656                    rectangle().fill(Color::WHITE),
2657                    label("")
2658                        .frame(80.0, 80.0)
2659                        .background(Color::rgb(0.0, 0.0, 1.0))
2660                        .corner_radius(30.0),
2661                ))
2662                .id(day_core::id!(ground))
2663                .frame(80.0, 80.0)
2664            })
2665            .drive(|d: Drive| async move {
2666                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
2667                d.sample_pixel("ground", 0.03, 0.03, "#ffffff").await
2668            })
2669    }
2670
2671    /// Opacity zero leaves what is below showing.
2672    #[day_macros::test(day_core)]
2673    fn opacity_hides() -> Case {
2674        Case::new()
2675            .proves_duty("set_opacity")
2676            .proves_modifier("opacity")
2677            .requires(Cap::Snapshot)
2678            .page(|| {
2679                zstack((
2680                    rectangle().fill(Color::WHITE),
2681                    rectangle().fill(Color::rgb(1.0, 0.0, 0.0)).opacity(0.0),
2682                ))
2683                .id(day_core::id!(ground))
2684                .frame(80.0, 40.0)
2685            })
2686            .drive(|d: Drive| async move { d.sample_pixel("ground", 0.5, 0.5, "#ffffff").await })
2687    }
2688
2689    /// A translation moves what is drawn without moving the layout.
2690    #[day_macros::test(day_core)]
2691    fn translation_moves_drawing() -> Case {
2692        Case::new()
2693            .proves_modifier("translation")
2694            .requires(Cap::Snapshot)
2695            .page(|| {
2696                zstack((
2697                    rectangle().fill(Color::WHITE),
2698                    rectangle()
2699                        .fill(Color::rgb(0.0, 0.0, 1.0))
2700                        .frame(40.0, 40.0)
2701                        .translation(40.0, 0.0),
2702                ))
2703                .align(day_core::Alignment::Leading)
2704                .id(day_core::id!(ground))
2705                .frame(120.0, 40.0)
2706            })
2707            .drive(|d: Drive| async move {
2708                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
2709                d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
2710            })
2711    }
2712
2713    /// A translation moves a plain view's drawing too, not only a canvas's.
2714    #[day_macros::test(day_core)]
2715    fn translation_moves_view() -> Case {
2716        Case::new()
2717            .proves_modifier("translation")
2718            .requires(Cap::Snapshot)
2719            .page(|| {
2720                zstack((
2721                    rectangle().fill(Color::WHITE),
2722                    label("")
2723                        .frame(40.0, 40.0)
2724                        .background(Color::rgb(0.0, 0.0, 1.0))
2725                        .translation(40.0, 0.0),
2726                ))
2727                .align(day_core::Alignment::Leading)
2728                .id(day_core::id!(ground))
2729                .frame(120.0, 40.0)
2730            })
2731            .drive(|d: Drive| async move {
2732                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
2733                d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
2734            })
2735    }
2736
2737    /// A scale grows the drawing about its center without moving the layout.
2738    #[day_macros::test(day_core)]
2739    fn scale_grows_drawing() -> Case {
2740        Case::new()
2741            .proves_modifier("scale")
2742            .requires(Cap::Snapshot)
2743            .page(|| {
2744                zstack((
2745                    rectangle().fill(Color::WHITE),
2746                    label("")
2747                        .frame(40.0, 40.0)
2748                        .background(Color::rgb(0.0, 0.0, 1.0))
2749                        .scale(2.0),
2750                ))
2751                .id(day_core::id!(ground))
2752                .frame(120.0, 80.0)
2753            })
2754            .drive(|d: Drive| async move {
2755                // Unscaled, the square spans x 40..80 of 120; scaled twice it spans 20..100.
2756                d.sample_pixel("ground", 0.25, 0.5, "#0000ff").await?;
2757                d.sample_pixel("ground", 0.08, 0.5, "#ffffff").await
2758            })
2759    }
2760
2761    /// A rotation turns the drawing clockwise (y points down): a bar red on the left and blue
2762    /// on the right, turned 90°, is red on top and blue below.
2763    #[day_macros::test(day_core)]
2764    fn rotation_turns_clockwise() -> Case {
2765        Case::new()
2766            .proves_modifier("rotation")
2767            .requires(Cap::Snapshot)
2768            .page(|| {
2769                zstack((
2770                    rectangle().fill(Color::WHITE),
2771                    shape_group([
2772                        rectangle()
2773                            .fill(Color::rgb(1.0, 0.0, 0.0))
2774                            .at(0.0, 0.0, 0.5, 1.0),
2775                        rectangle()
2776                            .fill(Color::rgb(0.0, 0.0, 1.0))
2777                            .at(0.5, 0.0, 0.5, 1.0),
2778                    ])
2779                    .frame(80.0, 40.0)
2780                    .rotation(90.0),
2781                ))
2782                .id(day_core::id!(ground))
2783                .frame(120.0, 120.0)
2784            })
2785            .shot("default")
2786            .drive(|d: Drive| async move {
2787                d.sample_pixel("ground", 0.5, 0.4, "#ff0000").await?;
2788                d.sample_pixel("ground", 0.5, 0.6, "#0000ff").await
2789            })
2790    }
2791
2792    // ---- input: every op injects Day's own event, the stream a native recognizer delivers,
2793    // so these prove the routing and the handler, not that the platform's recognizer fires
2794    // (docs/testing.md "Known gaps").
2795
2796    /// A plain target for gestures: a filled rectangle of a known size.
2797    fn pad(id: day_core::ElementId) -> Decorated<ShapePiece> {
2798        rectangle()
2799            .fill(Color::rgb(0.2, 0.4, 0.9))
2800            .frame(120.0, 80.0)
2801            .id(id)
2802    }
2803
2804    /// A tap runs `.on_tap`'s work, once per tap.
2805    #[day_macros::test(day_core)]
2806    fn on_tap_runs() -> Case {
2807        Case::new()
2808            .proves_modifier("on_tap")
2809            .page(|| {
2810                let taps = Signal::new(0i64);
2811                column((
2812                    label(move || format!("taps {}", taps.get())).id(day_core::id!(taps)),
2813                    label("Tap me")
2814                        .padding(12.0)
2815                        .on_tap(move || taps.update(|n| *n += 1))
2816                        .id(day_core::id!(target)),
2817                ))
2818            })
2819            .drive(|d: Drive| async move {
2820                d.tap("target").await?;
2821                d.tap("target").await?;
2822                d.assert_text("taps", "taps 2").await
2823            })
2824    }
2825
2826    /// `.on_tap_at` hears where in the element the tap landed.
2827    #[day_macros::test(day_core)]
2828    fn on_tap_at_reports_point() -> Case {
2829        Case::new()
2830            .proves_modifier("on_tap_at")
2831            .page(|| {
2832                let at = Signal::new(String::from("none"));
2833                column((
2834                    label(move || format!("at {}", at.get())).id(day_core::id!(at)),
2835                    rectangle()
2836                        .fill(Color::rgb(0.2, 0.4, 0.9))
2837                        .frame(120.0, 80.0)
2838                        .on_tap_at(move |p| at.set(format!("{:.0},{:.0}", p.x, p.y)))
2839                        .id(day_core::id!(target)),
2840                ))
2841            })
2842            .drive(|d: Drive| async move {
2843                d.tap_at("target", 30.0, 20.0).await?;
2844                d.assert_text("at", "at 30,20").await
2845            })
2846    }
2847
2848    /// A drag reports its phases, and its translation from where it began.
2849    #[day_macros::test(day_core)]
2850    fn on_drag_reports_translation() -> Case {
2851        Case::new()
2852            .proves_duty("enable_gesture")
2853            .proves_modifier("on_drag")
2854            .page(|| {
2855                let state = Signal::new(String::from("idle"));
2856                column((
2857                    label(move || state.get()).id(day_core::id!(state)),
2858                    pad(day_core::id!(target)).on_drag(move |d: Drag| {
2859                        state.set(match d.phase {
2860                            DragPhase::Began => "began".into(),
2861                            DragPhase::Changed => "moving".into(),
2862                            DragPhase::Ended => {
2863                                format!("moved {:.0},{:.0}", d.translation.x, d.translation.y)
2864                            }
2865                        })
2866                    }),
2867                ))
2868            })
2869            .drive(|d: Drive| async move {
2870                d.drag("target", (10.0, 10.0), (50.0, 30.0)).await?;
2871                d.assert_text("state", "moved 40,20").await
2872            })
2873    }
2874
2875    /// Hover reports the pointer's place while it is over the element, and `None` on leaving.
2876    #[day_macros::test(day_core)]
2877    fn on_hover_enters_and_leaves() -> Case {
2878        Case::new()
2879            .proves_modifier("on_hover")
2880            .page(|| {
2881                let state = Signal::new(String::from("out"));
2882                column((
2883                    label(move || state.get()).id(day_core::id!(state)),
2884                    pad(day_core::id!(target)).on_hover(move |p| {
2885                        state.set(match p {
2886                            Some(p) => format!("over {:.0},{:.0}", p.x, p.y),
2887                            None => "out".into(),
2888                        })
2889                    }),
2890                ))
2891            })
2892            .drive(|d: Drive| async move {
2893                d.hover("target", Some((5.0, 6.0))).await?;
2894                d.assert_text("state", "over 5,6").await?;
2895                d.hover_leave("target").await?;
2896                d.assert_text("state", "out").await
2897            })
2898    }
2899
2900    /// A pan delivers incremental deltas that add up to the whole movement.
2901    #[day_macros::test(day_core)]
2902    fn on_pan_adds_deltas() -> Case {
2903        Case::new()
2904            .proves_modifier("on_pan")
2905            .page(|| {
2906                let total = Signal::new((0.0f64, 0.0f64));
2907                column((
2908                    label(move || {
2909                        let (x, y) = total.get();
2910                        format!("pan {x:.0},{y:.0}")
2911                    })
2912                    .id(day_core::id!(total)),
2913                    pad(day_core::id!(target)).on_pan(move |p: Pan| {
2914                        total.update(|(x, y)| {
2915                            *x += p.delta.x;
2916                            *y += p.delta.y;
2917                        })
2918                    }),
2919                ))
2920            })
2921            .drive(|d: Drive| async move {
2922                d.pan("target", 40.0, -20.0).await?;
2923                d.assert_text("total", "pan 40,-20").await
2924            })
2925    }
2926
2927    /// A pinch's scale is cumulative from where it began; its end carries the final scale.
2928    #[day_macros::test(day_core)]
2929    fn on_pinch_reports_scale() -> Case {
2930        Case::new()
2931            .proves_modifier("on_pinch")
2932            .page(|| {
2933                let scale = Signal::new(String::from("none"));
2934                column((
2935                    label(move || format!("scale {}", scale.get())).id(day_core::id!(scale)),
2936                    pad(day_core::id!(target)).on_pinch(move |p: Pinch| {
2937                        if p.phase == DragPhase::Ended {
2938                            scale.set(format!("{:.1}", p.scale));
2939                        }
2940                    }),
2941                ))
2942            })
2943            .drive(|d: Drive| async move {
2944                d.pinch("target", 2.5).await?;
2945                d.assert_text("scale", "scale 2.5").await
2946            })
2947    }
2948
2949    /// A rotation is cumulative from where it began, in radians; its end carries the final
2950    /// angle.
2951    #[day_macros::test(day_core)]
2952    fn on_rotate_reports_rotation() -> Case {
2953        Case::new()
2954            .proves_modifier("on_rotate")
2955            .page(|| {
2956                let angle = Signal::new(String::from("none"));
2957                column((
2958                    label(move || format!("rotation {}", angle.get())).id(day_core::id!(angle)),
2959                    pad(day_core::id!(target)).on_rotate(move |r: Rotate| {
2960                        if r.phase == DragPhase::Ended {
2961                            angle.set(format!("{:.2}", r.rotation));
2962                        }
2963                    }),
2964                ))
2965            })
2966            .drive(|d: Drive| async move {
2967                d.rotate("target", 0.75).await?;
2968                d.assert_text("angle", "rotation 0.75").await
2969            })
2970    }
2971
2972    /// A focusable element takes focus, and the keys pressed while it holds it reach `.on_key`.
2973    #[day_macros::test(day_core)]
2974    fn on_key_reaches_focused() -> Case {
2975        Case::new()
2976            .proves_duty("focus")
2977            .proves_duty("set_focusable")
2978            .proves_modifier("on_key")
2979            .proves_modifier("focusable")
2980            .page(|| {
2981                let last = Signal::new(String::from("none"));
2982                column((
2983                    label(move || format!("key {}", last.get())).id(day_core::id!(last)),
2984                    pad(day_core::id!(target))
2985                        .focusable()
2986                        .on_key(move |k| last.set(k.key.clone())),
2987                ))
2988            })
2989            .drive(|d: Drive| async move {
2990                // Focus, then a key to whatever holds focus: the route a real press takes.
2991                d.focus("target").await?;
2992                d.assert_focused("target", true).await?;
2993                d.key(None, "ArrowRight").await?;
2994                d.assert_text("last", "key ArrowRight").await
2995            })
2996    }
2997
2998    /// A focus binding moves focus when the app sets it, and follows the field when it is
2999    /// focused natively.
3000    #[day_macros::test(day_core)]
3001    fn focused_binding_moves_focus() -> Case {
3002        Case::new()
3003            .proves_modifier("focused")
3004            .page(|| {
3005                let want = Signal::new(false);
3006                column((
3007                    label(move || format!("focused {}", want.get())).id(day_core::id!(state)),
3008                    button("Focus")
3009                        .action(move || want.set(true))
3010                        .id(day_core::id!(go)),
3011                    text_field(Signal::new(String::new()))
3012                        .focused(want)
3013                        .id(day_core::id!(field)),
3014                ))
3015            })
3016            .drive(|d: Drive| async move {
3017                d.assert_focused("field", false).await?;
3018                d.tap("go").await?;
3019                d.assert_focused("field", true).await?;
3020                d.assert_text("state", "focused true").await
3021            })
3022    }
3023
3024    /// Destroy a focused input and its containing page without first moving focus to a
3025    /// button. Win32 GTK must detach the IME filter before the input loses its native root.
3026    #[day_macros::test(day_core)]
3027    fn focused_inputs_survive_page_removal() -> Case {
3028        Case::new()
3029            .proves_duty("focus")
3030            .page(|| {
3031                let shown = Signal::new(true);
3032                column((
3033                    button("Toggle page")
3034                        .action(move || shown.set(!shown.get()))
3035                        .id(day_core::id!(toggle)),
3036                    text_field(Signal::new(String::new())).id(day_core::id!(survivor)),
3037                    when(
3038                        move || shown.get(),
3039                        || {
3040                            column((
3041                                text_field(Signal::new(String::new())).id(day_core::id!(entry)),
3042                            ))
3043                            .background(Color::rgb(0.5, 0.5, 0.5))
3044                        },
3045                    ),
3046                ))
3047            })
3048            .drive(|d: Drive| async move {
3049                for _ in 0..4 {
3050                    d.focus("entry").await?;
3051                    d.assert_focused("entry", true).await?;
3052                    // Scripted activation doesn't move native focus to the button first.
3053                    d.tap("toggle").await?;
3054                    d.assert_missing("entry").await?;
3055                    d.wait_idle().await?;
3056                    d.tap("toggle").await?;
3057                }
3058                d.focus("survivor").await?;
3059                d.tap("toggle").await?;
3060                d.assert_focused("survivor", true).await?;
3061                d.input("survivor", "still editable").await?;
3062                d.assert_text("survivor", "still editable").await
3063            })
3064    }
3065
3066    // ---- layout and the remaining modifiers -------------------------------------------------
3067
3068    /// `.height` fixes the height and leaves the width to the layout.
3069    #[day_macros::test(day_core)]
3070    fn height_fixes_height() -> Case {
3071        Case::new()
3072            .proves_modifier("height")
3073            .page(|| {
3074                column((rectangle()
3075                    .fill(Color::rgb(1.0, 0.0, 0.0))
3076                    .id(day_core::id!(bar))
3077                    .height(37.0),))
3078                .width(100.0)
3079            })
3080            .drive(|d: Drive| async move {
3081                d.assert_frame(
3082                    "bar",
3083                    FrameExpect {
3084                        height: Some(37.0),
3085                        ..Default::default()
3086                    },
3087                )
3088                .await
3089            })
3090    }
3091
3092    /// `.grow(Dimension::Height)` takes the height its column has left, in a column and in a row alike.
3093    #[day_macros::test(day_core)]
3094    fn grow_vertical_fills_column() -> Case {
3095        Case::new()
3096            .proves_modifier("grow")
3097            .page(|| {
3098                row((
3099                    column((
3100                        rectangle()
3101                            .fill(Color::rgb(1.0, 0.0, 0.0))
3102                            .id(day_core::id!(top))
3103                            .frame(40.0, 20.0),
3104                        rectangle()
3105                            .fill(Color::rgb(0.0, 0.0, 1.0))
3106                            .id(day_core::id!(rest))
3107                            .width(40.0)
3108                            .grow(Dimension::Height),
3109                    ))
3110                    .spacing(0.0)
3111                    .height(120.0),
3112                    rectangle()
3113                        .fill(Color::rgb(0.0, 1.0, 0.0))
3114                        .id(day_core::id!(both))
3115                        .width(30.0)
3116                        .grow(Dimension::Height),
3117                ))
3118                .spacing(0.0)
3119                .align(VAlign::Top)
3120                .height(120.0)
3121            })
3122            .drive(|d: Drive| async move {
3123                d.assert_frame(
3124                    "rest",
3125                    FrameExpect {
3126                        height: Some(100.0),
3127                        ..Default::default()
3128                    },
3129                )
3130                .await?;
3131                d.assert_frame(
3132                    "both",
3133                    FrameExpect {
3134                        height: Some(120.0),
3135                        ..Default::default()
3136                    },
3137                )
3138                .await
3139            })
3140    }
3141
3142    /// A grid cell spans the columns it asks for, and aligns within its cell as asked.
3143    #[day_macros::test(day_core)]
3144    fn grid_span_and_align() -> Case {
3145        Case::new()
3146            .proves_modifier("grid_span")
3147            .proves_modifier("grid_align")
3148            .page(|| {
3149                let cell = |id: day_core::ElementId, w: f64| {
3150                    rectangle()
3151                        .fill(Color::rgb(0.2, 0.4, 0.9))
3152                        .id(id)
3153                        .frame(w, 20.0)
3154                };
3155                grid((
3156                    grid_row((cell(day_core::id!(a), 40.0), cell(day_core::id!(b), 60.0))),
3157                    grid_row((cell(day_core::id!(wide), 30.0)
3158                        .grid_align(day_core::Alignment::TopTrailing)
3159                        .grid_span(2),)),
3160                ))
3161                .spacing(0.0)
3162                .align(day_core::Alignment::TopLeading)
3163            })
3164            .drive(|d: Drive| async move {
3165                // The spanning cell's rect is both columns, 100 wide; trailing puts its
3166                // 30-wide content at x 70 from the first column's start.
3167                d.assert_frame(
3168                    "wide",
3169                    FrameExpect {
3170                        x: Some(70.0),
3171                        relative_to: Some("a".into()),
3172                        ..Default::default()
3173                    },
3174                )
3175                .await
3176            })
3177    }
3178
3179    /// `.overlay` draws its piece centered over the content.
3180    #[day_macros::test(day_core)]
3181    fn overlay_centers() -> Case {
3182        Case::new()
3183            .proves_modifier("overlay")
3184            .requires(Cap::Snapshot)
3185            .page(|| {
3186                rectangle()
3187                    .fill(Color::rgb(1.0, 0.0, 0.0))
3188                    .frame(90.0, 90.0)
3189                    .overlay(
3190                        rectangle()
3191                            .fill(Color::rgb(0.0, 0.0, 1.0))
3192                            .frame(30.0, 30.0),
3193                    )
3194                    .id(day_core::id!(base))
3195            })
3196            .drive(|d: Drive| async move {
3197                d.sample_pixel("base", 0.5, 0.5, "#0000ff").await?;
3198                d.sample_pixel("base", 0.1, 0.1, "#ff0000").await
3199            })
3200    }
3201
3202    /// `.transform` takes a whole transform: here a translation and a scale together.
3203    #[day_macros::test(day_core)]
3204    fn transform_applies_whole() -> Case {
3205        Case::new()
3206            .proves_duty("set_transform")
3207            .proves_modifier("transform")
3208            .requires(Cap::Snapshot)
3209            .page(|| {
3210                zstack((
3211                    rectangle().fill(Color::WHITE),
3212                    label("")
3213                        .frame(20.0, 20.0)
3214                        .background(Color::rgb(0.0, 0.0, 1.0))
3215                        .transform(Transform {
3216                            tx: 30.0,
3217                            sx: 2.0,
3218                            sy: 2.0,
3219                            ..Transform::default()
3220                        }),
3221                ))
3222                .id(day_core::id!(ground))
3223                .frame(120.0, 60.0)
3224            })
3225            .drive(|d: Drive| async move {
3226                // Centered at x 60, moved to 90, scaled to 40 wide: 70..110 of 120.
3227                d.sample_pixel("ground", 0.75, 0.5, "#0000ff").await?;
3228                d.sample_pixel("ground", 0.5, 0.5, "#ffffff").await
3229            })
3230    }
3231
3232    /// An implicit animation still lands on the final value: a square slid across by an
3233    /// animated translation ends where the translation says.
3234    #[day_macros::test(day_core)]
3235    fn animation_lands_on_final() -> Case {
3236        Case::new()
3237            .proves_modifier("animation")
3238            .requires(Cap::Snapshot)
3239            .page(|| {
3240                let moved = Signal::new(false);
3241                column((
3242                    button("Move")
3243                        .action(move || moved.set(true))
3244                        .id(day_core::id!(move_button)),
3245                    zstack((
3246                        rectangle().fill(Color::WHITE),
3247                        label("")
3248                            .frame(40.0, 40.0)
3249                            .background(Color::rgb(0.0, 0.0, 1.0))
3250                            .translation(move || if moved.get() { 80.0 } else { 0.0 }, 0.0)
3251                            .animation(day_spec::AnimSpec::linear(150)),
3252                    ))
3253                    .align(day_core::Alignment::Leading)
3254                    .id(day_core::id!(ground))
3255                    .frame(120.0, 40.0),
3256                ))
3257            })
3258            .drive(|d: Drive| async move {
3259                d.sample_pixel("ground", 0.1, 0.5, "#0000ff").await?;
3260                d.tap("move_button").await?;
3261                d.wait_idle().await?;
3262                d.pause(0.4).await?;
3263                d.sample_pixel("ground", 0.85, 0.5, "#0000ff").await?;
3264                d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
3265            })
3266    }
3267
3268    /// Each way of naming an element finds it: a fixed id, a derived one, a keyed one.
3269    #[day_macros::test(day_core)]
3270    fn ids_name_elements() -> Case {
3271        Case::new()
3272            .proves_modifier("id")
3273            .proves_modifier("id_of")
3274            .page(|| {
3275                let n = Signal::new(1i64);
3276                column((
3277                    label("Fixed").id(day_core::id!(fixed)),
3278                    label("Derived").id_of(move || day_core::id!(derived, n.get())),
3279                    label("Keyed").id(day_core::id!(keyed, 7)),
3280                    button("Next")
3281                        .action(move || n.set(2))
3282                        .id(day_core::id!(next)),
3283                ))
3284            })
3285            .drive(|d: Drive| async move {
3286                d.assert_text("fixed", "Fixed").await?;
3287                d.assert_text("keyed:7", "Keyed").await?;
3288                d.assert_text("derived:1", "Derived").await?;
3289                d.tap("next").await?;
3290                d.assert_missing("derived:1").await?;
3291                d.assert_text("derived:2", "Derived").await
3292            })
3293    }
3294
3295    /// `.tweak` runs with the realized node, and `.native_ref` holds it while the piece lives.
3296    #[day_macros::test(day_core)]
3297    fn tweak_and_native_ref_see_node() -> Case {
3298        Case::new()
3299            .proves_modifier("tweak")
3300            .proves_modifier("native_ref")
3301            .page(|| {
3302                let tweaked = Signal::new(false);
3303                let r = NativeRef::new();
3304                let held = r.clone();
3305                column((
3306                    label(move || format!("tweaked {}", tweaked.get())).id(day_core::id!(tweaked)),
3307                    label(move || format!("held {}", held.node().is_some()))
3308                        .id(day_core::id!(held)),
3309                    label("Target")
3310                        .tweak(move |_node| tweaked.set(true))
3311                        .native_ref(&r),
3312                ))
3313            })
3314            .drive(|d: Drive| async move {
3315                d.assert_text("tweaked", "tweaked true").await?;
3316                d.assert_text("held", "held true").await
3317            })
3318    }
3319
3320    /// `.modifier` applies a reusable modifier: here, a closure that pads.
3321    #[day_macros::test(day_core)]
3322    fn modifier_applies() -> Case {
3323        Case::new()
3324            .proves_modifier("modifier")
3325            .page(|| {
3326                let padded = |content: AnyPiece| content.padding(10.0).any();
3327                column((label("Inner")
3328                    .id(day_core::id!(inner))
3329                    .modifier(padded)
3330                    .id(day_core::id!(outer)),))
3331                .align(HAlign::Leading)
3332            })
3333            .drive(|d: Drive| async move {
3334                d.assert_frame(
3335                    "inner",
3336                    FrameExpect {
3337                        x: Some(10.0),
3338                        y: Some(10.0),
3339                        relative_to: Some("outer".into()),
3340                        ..Default::default()
3341                    },
3342                )
3343                .await
3344            })
3345    }
3346
3347    /// An announcement reaches the screen reader (the toolkit's `announce`) and the run.
3348    #[day_macros::test(day_core)]
3349    fn announce_reaches_reader() -> Case {
3350        Case::new()
3351            .proves_duty("announce")
3352            .proves_cap(Cap::Announce)
3353            .page(|| {
3354                button("Save")
3355                    .action(|| day_core::announce("Saved"))
3356                    .id(day_core::id!(save))
3357            })
3358            .drive(|d: Drive| async move {
3359                d.tap("save").await?;
3360                d.assert_announced("Saved").await
3361            })
3362    }
3363}
3364
3365#[cfg(test)]
3366mod transfer_tests {
3367    use super::*;
3368    use day_spec::transfer::*;
3369
3370    #[test]
3371    fn transfer_callbacks_restore_owner_scope_and_reject_after_disposal() {
3372        let owner = Scope::child();
3373        let foreign = Scope::child();
3374        foreign.provide(22u32);
3375        let (source, target) = owner.enter(|| {
3376            owner.provide(11u32);
3377            let check = || assert_eq!(day_core::environment::<u32>(), Some(11));
3378            (
3379                scoped_drag_source(Rc::new(move |_| {
3380                    check();
3381                    Some(Offer::default())
3382                })),
3383                scoped_drop_target(Target {
3384                    types: vec![],
3385                    accept: Rc::new(move |_| {
3386                        check();
3387                        Operation::Copy
3388                    }),
3389                    receive: Rc::new(move |_| {
3390                        check();
3391                        true
3392                    }),
3393                }),
3394            )
3395        });
3396        let location = || Location {
3397            position: day_spec::Point::new(40., 20.),
3398            types: vec![],
3399            allowed: vec![Operation::Copy],
3400            local: true,
3401        };
3402        foreign.enter(|| {
3403            assert!(source(day_spec::Point::new(0., 0.)).is_some());
3404            assert!(target.deliver(location(), Offer::default()));
3405            assert_eq!(day_core::environment::<u32>(), Some(22));
3406            owner.dispose();
3407            assert!(source(day_spec::Point::new(0., 0.)).is_none());
3408            assert_eq!(target.proposal(&location()), Operation::None);
3409            assert!(!(target.receive)(Drop {
3410                local: true,
3411                position: day_spec::Point::new(0., 0.),
3412                operation: Operation::Copy,
3413                items: vec![]
3414            }));
3415        });
3416        foreign.dispose();
3417    }
3418}