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` supporting trait.
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, Signal, bind};
16use day_spec::props::*;
17use day_spec::{
18    A11yProps, Angle, AnimSpec, Cursor, Event, Ink, Insets, Paint, Role, Transform, kinds,
19};
20
21use crate::menus::lower_menu_scoped;
22use crate::*;
23
24// ---------------------------------------------------------------------------
25// Decorators (§5.2 Decorate)
26// ---------------------------------------------------------------------------
27
28/// A one-shot, by-value view transform (the SwiftUI `ViewModifier` analog): wrap a piece into a
29/// new one. Pure composition, with no per-backend work. A plain `FnOnce(AnyPiece) -> AnyPiece`
30/// closure is a `Modifier` too (the blanket impl below), so the common case needs no new type.
31/// Apply one with [`Decorate::modifier`].
32///
33/// **`AnyPiece` here is a trade, not a requirement.** It is not object safety: a `Modifier` is
34/// never stored as `dyn Modifier`, and [`Decorate::modifier`] takes `impl Modifier` and applies
35/// it on the spot. It is the closure impl below. A closure has one fixed parameter type, and
36/// Rust has no `for<P> FnOnce(P) -> _` bound (higher-ranked bounds range over lifetimes, not
37/// types), so making `apply` generic over the content (`fn apply<P: Piece>(self, c: P) ->
38/// Self::Out<P>`, which a named modifier can satisfy with a GAT) would leave no closure able to
39/// implement the trait at all. Pinning the input to the one piece type that accepts anything is
40/// what keeps `|p| …` a modifier, and the erasure is what that costs, which is why this is the
41/// single `Decorate` method that erases.
42///
43/// If a modifier ever needs to preserve its content's type, parameterize the trait rather than
44/// the method: `trait Modifier<P: Piece> { type Out: Piece; fn apply(self, c: P) -> Self::Out; }`.
45/// Closures survive that (`impl<P: Piece, O: Piece, F: FnOnce(P) -> O> Modifier<P> for F`, and
46/// their parameter still infers unannotated), while a named modifier such as day-piece-rating's
47/// `Card` becomes `impl<P: Piece> Modifier<P> for Card` with `type Out = Decorated<P>`. The bill
48/// is a `Decorate::modifier` whose return type varies per modifier, a generic impl for every
49/// named one, and a breaking change: not worth paying while the tree has two implementors.
50pub trait Modifier {
51    fn apply(self, content: AnyPiece) -> AnyPiece;
52}
53
54impl<F> Modifier for F
55where
56    F: FnOnce(AnyPiece) -> AnyPiece,
57{
58    fn apply(self, content: AnyPiece) -> AnyPiece {
59        self(content)
60    }
61}
62
63/// A liveness-checked reference to a mounted piece's realized node: the retained half of the
64/// tweaks API (docs/tweaks.md). Capture one with [`Decorate::native_ref`], then reach the native
65/// widget later (from event handlers, timers) through a toolkit ext accessor. `node`/`with` yield
66/// `None` before mount and after the node's subtree is disposed, so async races are safe no-ops.
67///
68/// Reads are reactive: inside a binding or memo, `node()` subscribes to the ref's mount/clear
69/// transitions (a `Trigger` underneath), so a label like
70/// `label(move || if r.node().is_some() { "live" } else { "cleared" })` updates when the
71/// referenced piece unmounts, as in the toggle demo on the showcase Tweaks page. (The
72/// `when`-arm's disposal lands at the turn boundary, after ordinary bindings re-ran;
73/// piggybacking on some other signal would read a stale mount state, while the trigger fires
74/// at the actual transition.) Main-thread only, like every realized-tree type.
75#[derive(Clone)]
76pub struct NativeRef {
77    cell: Rc<std::cell::Cell<Option<day_core::RNode>>>,
78    changed: day_reactive::Trigger,
79}
80
81impl Default for NativeRef {
82    fn default() -> Self {
83        Self::new()
84    }
85}
86
87impl NativeRef {
88    #[must_use]
89    pub fn new() -> Self {
90        NativeRef {
91            cell: Rc::new(std::cell::Cell::new(None)),
92            changed: day_reactive::Trigger::new(),
93        }
94    }
95
96    /// The mounted node, if it is currently live. A tracked read (see the type docs).
97    #[must_use]
98    pub fn node(&self) -> Option<day_core::RNode> {
99        self.changed.track();
100        let node = self.cell.get()?;
101        // Generational slotmap keys make a disposed node a clean miss, never a stale hit.
102        let live = day_core::try_with_tree(|t| t.node_kind(node).is_some()).unwrap_or(false);
103        live.then_some(node)
104    }
105
106    /// Run `f` with the live node (e.g. inside `day_toolkit_appkit::with_native`); `None` if disposed.
107    pub fn with<R>(&self, f: impl FnOnce(day_core::RNode) -> R) -> Option<R> {
108        self.node().map(f)
109    }
110
111    fn transition(&self, node: Option<day_core::RNode>) {
112        self.cell.set(node);
113        self.changed.notify();
114    }
115}
116
117/// A transparent native layer node (`CONTAINER`, no fill/clip/corner) used by the animatable
118/// modifiers (`.opacity`/`.transform`) to carry a per-node opacity or transform. Layout-transparent (`FillThrough`), so it never affects sizing and a
119/// granted stretch flows through to what it paints.
120fn layer_node(cx: &mut BuildCx) -> RNode {
121    cx.native(
122        kinds::CONTAINER,
123        &ContainerProps {
124            corner_radius: 0.0,
125            clips: false,
126            role: None,
127            ..Default::default()
128        },
129        Rc::new(FillThrough),
130        Flex::default(),
131        Boundary::No,
132    )
133}
134
135// ---------------------------------------------------------------------------
136// Decorated: a piece plus its modifiers, with the piece's type kept (§5.2)
137// ---------------------------------------------------------------------------
138
139/// The build of a piece plus every modifier applied to it so far.
140type Build = Box<dyn FnOnce(&mut BuildCx) -> RNode>;
141
142/// A piece with modifiers chained onto it, keeping the decorated piece's type (§5.2).
143///
144/// Every [`Decorate`] modifier returns one of these rather than erasing to [`AnyPiece`], which is
145/// what lets a chain keep reaching the piece's builder methods: `label(…).padding(8.0)` is
146/// still a decorated `Label`, so `.font(…)` after it resolves. Modifiers applied to a `Decorated`
147/// append in place (the inherent methods below shadow the trait's), so a chain stays flat instead
148/// of nesting `Decorated<Decorated<…>>`.
149///
150/// Modifiers fall into three classes (docs/api-style.md "Modifier classes"), and only one of
151/// them is ordered:
152///
153/// - **Identity** (`id`, `id_of`) names the piece's own node, the one its build
154///   returns, wherever it sits in the chain: `label(t).padding(8.0).id(day_core::id!(x))` and
155///   `label(t).id(day_core::id!(x)).padding(8.0)` are the same tree.
156/// - **Wrapping** modifiers (`padding`, `frame`, `background`, `grow`, …) each add a node around
157///   what came before, so they compose outward in call order, as they read.
158/// - **Outer-layout facts** (`grid_span`, `grid_align`) describe the piece to the container it
159///   sits in, so they land on the outermost node whatever wrappers follow them.
160///
161/// `wrapper_id` is the one way to name a wrapper deliberately: it tags whatever node is
162/// outermost at the point it is called, for a frame assertion on a padded box.
163///
164/// Erase explicitly with `.any()` when a single [`AnyPiece`] is what's needed (a `Vec<AnyPiece>`, a
165/// `-> AnyPiece` signature).
166#[must_use]
167pub struct Decorated<P> {
168    inner: P,
169    /// Wrapping modifiers, applied outward in call order.
170    ops: Vec<Box<dyn FnOnce(Build) -> Build>>,
171    /// Identity modifiers, applied to the node the piece's own build returns.
172    node_ops: Vec<Box<dyn FnOnce(RNode)>>,
173    /// Outer-layout facts, applied to the outermost node once every wrapper is in place.
174    outer_ops: Vec<Box<dyn FnOnce(RNode)>>,
175}
176
177impl<P: Piece> Decorated<P> {
178    /// An undecorated piece, ready to have modifiers applied CONDITIONALLY. Starting here gives
179    /// every branch the same type, so an optional modifier needs no erasure:
180    ///
181    /// ```ignore
182    /// let leaf = Decorated::new(draw);
183    /// let leaf = match id { Some(id) => leaf.id(id), None => leaf };
184    /// let leaf = if editable { leaf.on_tap(f) } else { leaf };
185    /// ```
186    ///
187    /// [`apply_if`](Self::apply_if) and [`apply_some`](Self::apply_some) are the same move as a
188    /// chain step.
189    pub fn new(inner: P) -> Self {
190        Decorated {
191            inner,
192            ops: Vec::new(),
193            node_ops: Vec::new(),
194            outer_ops: Vec::new(),
195        }
196    }
197
198    fn push(mut self, op: impl FnOnce(Build) -> Build + 'static) -> Self {
199        self.ops.push(Box::new(op));
200        self
201    }
202
203    fn push_node(mut self, op: impl FnOnce(RNode) + 'static) -> Self {
204        self.node_ops.push(Box::new(op));
205        self
206    }
207
208    fn push_outer(mut self, op: impl FnOnce(RNode) + 'static) -> Self {
209        self.outer_ops.push(Box::new(op));
210        self
211    }
212
213    /// Replace the undecorated piece, keeping the modifier chain: how a typed builder trait
214    /// reaches through a decoration (docs/api-style.md "Typed builders"). `f` sees the piece as
215    /// it was before any modifier, which is why modifier order stops mattering.
216    pub fn map_inner<Q: Piece>(self, f: impl FnOnce(P) -> Q) -> Decorated<Q> {
217        Decorated {
218            inner: f(self.inner),
219            ops: self.ops,
220            node_ops: self.node_ops,
221            outer_ops: self.outer_ops,
222        }
223    }
224
225    /// Apply `f` to the chain when `cond` holds, else continue unchanged: the conditional
226    /// modifier, with no `let x = if c { x.m() } else { x }` rebinding and no erasure.
227    ///
228    /// ```ignore
229    /// nav(sel).apply_if(!primary, |n| n.local())
230    /// ```
231    ///
232    /// `cond` is a plain `bool` resolved at build, like the arms of a `match`; the modifiers
233    /// `f` applies may themselves be reactive.
234    pub fn apply_if(self, cond: bool, f: impl FnOnce(Self) -> Self) -> Self {
235        if cond { f(self) } else { self }
236    }
237
238    /// Apply `f` with the value when there is one, else continue unchanged:
239    /// `canvas(draw).apply_some(id, |c, id| c.id(id))`.
240    pub fn apply_some<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
241        match value {
242            Some(v) => f(self, v),
243            None => self,
244        }
245    }
246}
247
248impl<P: Piece> Piece for Decorated<P> {
249    fn build(self, cx: &mut BuildCx) -> RNode {
250        let Decorated {
251            inner,
252            ops,
253            node_ops,
254            outer_ops,
255        } = self;
256        // The piece's own node first, with its identity; then the wrappers, composed outward
257        // in call order (the first modifier is innermost); then the facts for the parent, on
258        // whatever ended up outermost.
259        let wraps = !ops.is_empty();
260        let own = Rc::new(Cell::new(None::<RNode>));
261        let own_out = own.clone();
262        let mut build: Build = Box::new(move |cx| {
263            let n = inner.build(cx);
264            for op in node_ops {
265                op(n);
266            }
267            own_out.set(Some(n));
268            n
269        });
270        for op in ops {
271            build = op(build);
272        }
273        let outer = build(cx);
274        // The span a gesture addressed to the piece's own node (where `.id` sits) climbs to
275        // reach a wrapper's `.on_tap` (day-core's `gesture_target`).
276        if wraps && let Some(n) = own.get() {
277            with_tree(|t| t.set_element_outer(n, outer));
278        }
279        for op in outer_ops {
280            op(outer);
281        }
282        outer
283    }
284}
285
286// --- The modifier bodies, written once and shared by the trait and the inherent impl ---
287
288fn op_id(id: day_core::ElementId) -> impl FnOnce(RNode) {
289    move |n| with_tree(|t| t.set_id(t.element_target(n), id.as_str().to_owned()))
290}
291
292fn op_id_of(id: impl Fn() -> day_core::ElementId + 'static) -> impl FnOnce(RNode) {
293    move |n| {
294        day_reactive::bind(id, move |s: &day_core::ElementId| {
295            let s = s.as_str().to_owned();
296            with_tree(|t| t.set_id(t.element_target(n), s));
297        });
298    }
299}
300
301/// Name whatever node is outermost at this point in the chain (see [`Decorated::wrapper_id`]).
302fn op_wrapper_id(id: day_core::ElementId) -> impl FnOnce(Build) -> Build {
303    move |inner| {
304        Box::new(move |cx| {
305            let n = inner(cx);
306            with_tree(|t| t.set_id(n, id.as_str().to_owned()));
307            n
308        })
309    }
310}
311
312fn op_tweak(f: impl FnOnce(day_core::RNode) + 'static) -> impl FnOnce(Build) -> Build {
313    move |inner| {
314        Box::new(move |cx| {
315            let n = inner(cx);
316            f(n);
317            // Mark the node so a later backing swap (`.selectable()` on a toolkit that
318            // rebuilds the widget) warns about the discarded tweak instead of losing it
319            // silently (docs/tweaks.md).
320            with_tree(|t| t.note_node_tweaked(n));
321            n
322        })
323    }
324}
325
326fn op_selectable() -> impl FnOnce(Build) -> Build {
327    move |inner| {
328        Box::new(move |cx| {
329            let n = inner(cx);
330            with_tree(|t| t.set_node_selectable(n, true));
331            n
332        })
333    }
334}
335
336fn op_cursor(cursor: Reactive<Cursor>) -> impl FnOnce(Build) -> Build {
337    move |inner| {
338        Box::new(move |cx| {
339            let n = inner(cx);
340            // Read before borrowing the tree: a reactive cursor is app code (a composed split's
341            // follows the app's axis closure), and app code may itself reach the tree.
342            let shape = cursor.get_untracked();
343            with_tree(|t| t.set_node_cursor(n, shape));
344            // Only a reactive source needs a binding; a constant shape is applied once at
345            // mount. The setter is idempotent, so a re-run costs one native call.
346            if let Reactive::Dyn(_) = &cursor {
347                bind(
348                    move || cursor.get(),
349                    move |c: &Cursor| {
350                        with_tree(|t| t.set_node_cursor(n, c.clone()));
351                    },
352                );
353            }
354            n
355        })
356    }
357}
358
359fn op_layout_direction(
360    direction: Reactive<day_spec::LayoutDirection>,
361) -> impl FnOnce(Build) -> Build {
362    move |inner| {
363        Box::new(move |cx| {
364            let n = inner(cx);
365            let seed = direction.get_untracked();
366            with_tree(|t| t.set_node_direction(n, Some(seed)));
367            if let Reactive::Dyn(_) = &direction {
368                bind(
369                    move || direction.get(),
370                    move |d: &day_spec::LayoutDirection| {
371                        with_tree(|t| {
372                            t.set_node_direction(n, Some(*d));
373                            t.layout_if_needed();
374                        });
375                    },
376                );
377            }
378            n
379        })
380    }
381}
382
383fn op_window_drag_region() -> impl FnOnce(Build) -> Build {
384    move |inner| {
385        Box::new(move |cx| {
386            let n = inner(cx);
387            with_tree(|t| t.set_node_drag_region(n, true));
388            n
389        })
390    }
391}
392
393fn op_native_ref(r: NativeRef) -> impl FnOnce(Build) -> Build {
394    move |inner| {
395        Box::new(move |cx| {
396            let n = inner(cx);
397            r.transition(Some(n));
398            let cleared = r.clone();
399            Scope::current().on_cleanup(move || cleared.transition(None));
400            n
401        })
402    }
403}
404
405fn op_padding(insets: Reactive<Insets>) -> impl FnOnce(Build) -> Build {
406    move |inner| {
407        Box::new(move |cx| {
408            let seed = insets.get_untracked();
409            let layout = Rc::new(PaddingLayout {
410                insets: Cell::new(seed),
411            });
412            let w = cx.layout_only(layout.clone(), Flex::default(), Boundary::No);
413            cx.under(w, |cx| {
414                let _ = inner(cx);
415            });
416            // A constant pads once; a signal or a closure (`move || day::safe_area()`) re-pads
417            // in place when it changes, a rotation included.
418            if let Reactive::Dyn(_) = &insets {
419                day_reactive::bind_seeded(
420                    seed,
421                    move || insets.get(),
422                    move |v: &Insets| {
423                        layout.insets.set(*v);
424                        with_tree(|t| t.mark_needs_measure(w));
425                    },
426                );
427            }
428            w
429        })
430    }
431}
432
433/// Follow a reactive length into the `Cell` a layout reads it from, re-measuring on change. A
434/// constant needs no binding.
435fn bind_length(value: Reactive<f64>, cell: impl Fn(f64) + 'static, node: RNode) {
436    if let Reactive::Dyn(_) = &value {
437        let seed = value.get_untracked();
438        day_reactive::bind_seeded(
439            seed,
440            move || value.get(),
441            move |v: &f64| {
442                cell(*v);
443                with_tree(|t| t.mark_needs_measure(node));
444            },
445        );
446    }
447}
448
449fn op_max_width(max: Reactive<f64>) -> impl FnOnce(Build) -> Build {
450    move |inner| {
451        Box::new(move |cx| {
452            let layout = Rc::new(MaxWidthLayout {
453                max: Cell::new(max.get_untracked()),
454            });
455            let w = cx.layout_only(layout.clone(), Flex::default(), Boundary::No);
456            cx.under(w, |cx| {
457                let _ = inner(cx);
458            });
459            bind_length(max, move |v| layout.max.set(v), w);
460            w
461        })
462    }
463}
464
465fn op_max_height(max: Reactive<f64>) -> impl FnOnce(Build) -> Build {
466    move |inner| {
467        Box::new(move |cx| {
468            // Yielding, so a column sizes its other children first and gives this one what is
469            // left, up to `max`: a capped scroll gives way to the button under it on a short
470            // screen instead of pushing it out of the column, and the column still hugs.
471            let layout = Rc::new(day_core::MaxHeightLayout {
472                max: Cell::new(max.get_untracked()),
473            });
474            let h = cx.layout_only(
475                layout.clone(),
476                Flex {
477                    yields_h: true,
478                    ..Flex::default()
479                },
480                Boundary::No,
481            );
482            cx.under(h, |cx| {
483                let _ = inner(cx);
484            });
485            bind_length(max, move |v| layout.max.set(v), h);
486            h
487        })
488    }
489}
490
491fn op_min_width(min: Reactive<f64>) -> impl FnOnce(Build) -> Build {
492    move |inner| {
493        Box::new(move |cx| {
494            let layout = Rc::new(day_core::MinWidthLayout {
495                min: Cell::new(min.get_untracked()),
496            });
497            let w = cx.layout_only(layout.clone(), Flex::default(), Boundary::No);
498            cx.under(w, |cx| {
499                let _ = inner(cx);
500            });
501            bind_length(min, move |v| layout.min.set(v), w);
502            w
503        })
504    }
505}
506
507fn op_min_height(min: Reactive<f64>) -> impl FnOnce(Build) -> Build {
508    move |inner| {
509        Box::new(move |cx| {
510            let layout = Rc::new(MinHeightLayout {
511                min: Cell::new(min.get_untracked().max(0.0)),
512            });
513            let node = cx.layout_only(layout.clone(), Flex::default(), Boundary::No);
514            cx.under(node, |cx| {
515                let _ = inner(cx);
516            });
517            bind_length(min, move |v| layout.min.set(v.max(0.0)), node);
518            node
519        })
520    }
521}
522
523fn op_reserving(sample: TextSource) -> impl FnOnce(Build) -> Build {
524    move |inner| {
525        Box::new(move |cx| {
526            let wrapper = cx.layout_only(
527                Rc::new(day_core::ReserveLayout),
528                Flex::default(),
529                Boundary::No,
530            );
531            cx.under(wrapper, |cx| {
532                let content = inner(cx);
533                // Find the label through single-child wrappers after all typed builders have
534                // configured it. Multi-child pieces use the default Body font.
535                let font = with_tree(|tree| {
536                    let mut node = content;
537                    loop {
538                        if let Some(font) = tree.node_probe(node).and_then(|p| p.font) {
539                            break font;
540                        }
541                        if tree.child_count(node) != 1 {
542                            break day_spec::FontSpec::from(day_spec::Font::Body);
543                        }
544                        let Some(child) = tree.first_child(node) else {
545                            break day_spec::FontSpec::from(day_spec::Font::Body);
546                        };
547                        node = child;
548                    }
549                });
550                let sample_node = cx.leaf(
551                    day_spec::kinds::LABEL,
552                    &LabelProps {
553                        text: sample.initial(),
554                        font,
555                        wraps: false,
556                        ..Default::default()
557                    },
558                    Flex::default(),
559                );
560                with_tree(|tree| {
561                    tree.set_node_opacity(sample_node, 0.0);
562                    tree.set_a11y(
563                        sample_node,
564                        A11yProps {
565                            hidden: true,
566                            decorative: true,
567                            ..Default::default()
568                        },
569                    );
570                });
571                sample.bind_to(sample_node, |s| Box::new(LabelPatch::Text(s)), true);
572            });
573            wrapper
574        })
575    }
576}
577
578// The layout reads stored sizes, never signals. Bindings update those sizes outside the
579// tree borrow and invalidate measurement; native children and their scopes remain mounted.
580struct ReactiveFrameLayout {
581    size: Cell<(Option<f64>, Option<f64>)>,
582}
583impl ReactiveFrameLayout {
584    fn frame(&self) -> FrameLayout {
585        let (width, height) = self.size.get();
586        FrameLayout { width, height }
587    }
588}
589impl Layout for ReactiveFrameLayout {
590    fn measure(
591        &self,
592        cx: &mut dyn LayoutOps,
593        children: &[RNode],
594        p: day_spec::Proposal,
595    ) -> day_spec::Size {
596        self.frame().measure(cx, children, p)
597    }
598    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: day_spec::Rect) {
599        self.frame().place(cx, children, bounds);
600    }
601    fn baseline(
602        &self,
603        cx: &mut dyn LayoutOps,
604        children: &[RNode],
605        size: day_spec::Size,
606    ) -> Option<f64> {
607        self.frame().baseline(cx, children, size)
608    }
609}
610
611fn frame_extent(value: f64) -> f64 {
612    if value.is_finite() {
613        value.max(0.0)
614    } else {
615        0.0
616    }
617}
618
619fn op_frame(
620    width: Option<Reactive<f64>>,
621    height: Option<Reactive<f64>>,
622) -> impl FnOnce(Build) -> Build {
623    move |inner| {
624        Box::new(move |cx| {
625            let dynamic =
626                matches!(width, Some(Reactive::Dyn(_))) || matches!(height, Some(Reactive::Dyn(_)));
627            let read = move || {
628                (
629                    width.as_ref().map(|v| frame_extent(v.get())),
630                    height.as_ref().map(|v| frame_extent(v.get())),
631                )
632            };
633            let seed = day_reactive::untrack(&read);
634            let layout = Rc::new(ReactiveFrameLayout {
635                size: Cell::new(seed),
636            });
637            // Only a constant two-axis frame stops measurement propagation. A changing
638            // frame must invalidate ancestors too, so siblings move to their new positions.
639            let boundary = if !dynamic && seed.0.is_some() && seed.1.is_some() {
640                Boundary::Yes
641            } else {
642                Boundary::No
643            };
644            let node = cx.layout_only(layout.clone(), Flex::default(), boundary);
645            cx.under(node, |cx| {
646                let _ = inner(cx);
647            });
648            if dynamic {
649                day_reactive::bind_seeded(seed, read, move |size| {
650                    layout.size.set(*size);
651                    with_tree(|t| t.mark_needs_measure(node));
652                });
653            }
654            node
655        })
656    }
657}
658
659fn op_a11y(f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> impl FnOnce(Build) -> Build {
660    move |inner| {
661        Box::new(move |cx| {
662            let n = inner(cx);
663            let (props, live, selected) = f(A11yBuilder::default()).split();
664            let seed = props.selected;
665            with_tree(|t| t.set_a11y(n, props));
666            // The selected state follows its signal the same way: re-sent alone, merged by
667            // day-core onto the node's set.
668            if let Some(selected) = selected {
669                day_reactive::bind_seeded(
670                    seed.unwrap_or(false),
671                    move || selected.get(),
672                    move |on: &bool| {
673                        with_tree(|t| {
674                            t.set_a11y(
675                                n,
676                                A11yProps {
677                                    selected: Some(*on),
678                                    ..Default::default()
679                                },
680                            );
681                        });
682                    },
683                );
684            }
685            // A string that reads a signal or the locale re-sends itself alone; day-core
686            // merges it onto the node's set and re-applies the whole picture (§13).
687            for (src, patch) in live {
688                if let TextSource::Dyn(read) = src {
689                    let seed = day_reactive::untrack(|| read());
690                    day_reactive::bind_seeded(
691                        seed,
692                        move || read(),
693                        move |s: &String| with_tree(|t| t.set_a11y(n, patch(s.clone()))),
694                    );
695                }
696            }
697            n
698        })
699    }
700}
701
702fn op_on_tap(f: impl Fn() + 'static) -> impl FnOnce(Build) -> Build {
703    move |inner| {
704        Box::new(move |cx| {
705            let n = inner(cx);
706            with_tree(|t| t.enable_gesture(n, GestureKind::Tap));
707            cx.on(n, move |ev| {
708                if matches!(ev, Event::Tap(_)) {
709                    f();
710                }
711            });
712            n
713        })
714    }
715}
716
717fn op_on_tap_at(f: impl Fn(day_spec::Point) + 'static) -> impl FnOnce(Build) -> Build {
718    move |inner| {
719        Box::new(move |cx| {
720            let n = inner(cx);
721            with_tree(|t| t.enable_gesture(n, GestureKind::Tap));
722            cx.on(n, move |ev| {
723                if let Event::Tap(p) = ev {
724                    f(*p);
725                }
726            });
727            n
728        })
729    }
730}
731
732/// A key handler for presses (`released: false`, which includes repeats) or releases.
733fn op_on_key(
734    released: bool,
735    f: impl Fn(&day_spec::KeyEvent) + 'static,
736) -> impl FnOnce(Build) -> Build {
737    move |inner| {
738        Box::new(move |cx| {
739            let n = inner(cx);
740            // Declare the intent as well as listening: a backend whose focused view would have
741            // to claim the key from the platform's dispatch checks this first. That check runs
742            // on the view, which sits below `n` when `n` is a layout wrapper (`.frame(..)`), so
743            // the view is marked too; the key it claims reaches this handler through the
744            // wrapper (day-core's dispatch).
745            day_spec::keys::mark(day_core::rnode_to_id(n));
746            if let Some(view) = with_tree(|t| t.native_view_of(n))
747                && view != n
748            {
749                day_spec::keys::mark(day_core::rnode_to_id(view));
750            }
751            cx.on(n, move |ev| {
752                if let Event::Key(k) = ev
753                    && k.is_release() == released
754                {
755                    f(k);
756                }
757            });
758            n
759        })
760    }
761}
762
763/// Declare toolbar items for the chrome this piece sits under (docs/toolbars.md).
764///
765/// The chrome is resolved where the piece is built, not where the modifier was written: the
766/// innermost navigation page being built, or the window when there is none. The design exists so
767/// that a command sits beside the content it acts on, and the app never says twice which bar it
768/// belongs to.
769fn op_toolbar(source: crate::ToolbarSource) -> impl FnOnce(Build) -> Build {
770    move |inner| {
771        Box::new(move |cx| {
772            let n = inner(cx);
773            crate::contribute(day_core::current_chrome(), source);
774            n
775        })
776    }
777}
778
779fn op_focusable() -> impl FnOnce(Build) -> Build {
780    move |inner| {
781        Box::new(move |cx| {
782            let n = inner(cx);
783            with_tree(|t| t.set_focusable(n, true));
784            n
785        })
786    }
787}
788
789fn op_keyboard() -> impl FnOnce(Build) -> Build {
790    move |inner| {
791        Box::new(move |cx| {
792            let n = inner(cx);
793            // The same two marks `on_key` leaves (the node and the native view under any
794            // layout wrapper), on the registry the full route reads.
795            day_spec::keys::mark_text(day_core::rnode_to_id(n));
796            if let Some(view) = with_tree(|t| t.native_view_of(n))
797                && view != n
798            {
799                day_spec::keys::mark_text(day_core::rnode_to_id(view));
800            }
801            n
802        })
803    }
804}
805
806fn op_focused(
807    want: Box<dyn Fn() -> bool>,
808    on_native: Box<dyn Fn(bool)>,
809) -> impl FnOnce(Build) -> Build {
810    move |inner| {
811        Box::new(move |cx| {
812            let n = inner(cx);
813            // Echo cell: the control's focus state as last reported by the native side. An
814            // apply whose desired state matches it is the echo of a native change (or already
815            // satisfied) and must not re-drive the toolkit: the nav host echo-cell rule.
816            let native = Rc::new(Cell::new(false));
817            {
818                let native = native.clone();
819                cx.on(n, move |ev| {
820                    if let Event::FocusChanged(f) = ev {
821                        native.set(*f);
822                        on_native(*f);
823                    }
824                });
825            }
826            // Signal → native, deferred one turn (`on_main`): focus is async by contract, and
827            // the deferral also lets a mount-time `Some(K::V)` land after the widget is in the
828            // window (dialog default focus). The initial `false` is not applied, because resigning
829            // focus the control never had would steal it from whoever has it.
830            let first = Cell::new(true);
831            bind(want, move |want: &bool| {
832                let want = *want;
833                if first.replace(false) && !want {
834                    return;
835                }
836                if native.get() == want {
837                    return;
838                }
839                day_reactive::on_main(move || with_tree(|t| t.focus_node(n, want)));
840            });
841            n
842        })
843    }
844}
845
846fn op_context_menu(items: Vec<MenuEntry>) -> impl FnOnce(Build) -> Build {
847    move |inner| {
848        Box::new(move |cx| {
849            // The overlay host places the decorated subtree at its own bounds and the
850            // composed-menu mount beside it (see `OverlayHost`; a plain sibling would sit
851            // under a single-child layout, never placed).
852            let w = cx.layout_only(Rc::new(OverlayHost), Flex::default(), Boundary::No);
853            let mut n = w;
854            cx.under(w, |cx| {
855                n = inner(cx);
856                // Scoped: the action closures die with the build scope, not the process;
857                // an unscoped registration here leaks one closure per remount.
858                let model = lower_menu_scoped(items);
859                with_tree(|t| t.set_context_menu(n, model.clone()));
860                // A backend with no native menu reports the summon instead; the composed
861                // presenter replays the same lowered model (docs/menus.md).
862                let model = std::rc::Rc::new(model);
863                crate::menus::mount_composed_menu(cx, n, Rc::new(move |_p| (*model).clone()));
864            });
865            // Sized by its content, so a platform row stays one through the menu's wrapper.
866            with_tree(|t| t.forward_whole_row(w, n));
867            // Later ops decorate the content node: ids, gestures and menus belong to it,
868            // while the wrapper only exists to keep the mount in the layout pass.
869            n
870        })
871    }
872}
873
874/// The `.context_menu*` wrapper's layout: the decorated subtree fills the wrapper; every
875/// other child (the composed menu's lazy mount) is layout-inert but must still be visited,
876/// because a cover lays its content out from the size the backend reports, but only if the
877/// place pass reaches it at all.
878pub(crate) struct OverlayHost;
879
880impl Layout for OverlayHost {
881    fn measure(
882        &self,
883        cx: &mut dyn LayoutOps,
884        children: &[day_core::RNode],
885        p: day_spec::Proposal,
886    ) -> day_spec::Size {
887        match children.first() {
888            Some(&c) => cx.measure_child(c, p),
889            None => day_spec::Size::ZERO,
890        }
891    }
892    fn place(&self, cx: &mut dyn LayoutOps, children: &[day_core::RNode], bounds: day_spec::Rect) {
893        let mut it = children.iter();
894        if let Some(&c) = it.next() {
895            cx.place_child(c, day_spec::Rect::from_size(bounds.size));
896        }
897        for &c in it {
898            cx.place_child(c, day_spec::Rect::ZERO);
899        }
900    }
901    fn baseline(
902        &self,
903        cx: &mut dyn LayoutOps,
904        children: &[day_core::RNode],
905        size: day_spec::Size,
906    ) -> Option<f64> {
907        children.first().and_then(|&c| cx.baseline_of(c, size))
908    }
909}
910
911fn op_context_menu_fn(
912    f: Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>,
913) -> impl FnOnce(Build) -> Build {
914    move |inner| {
915        Box::new(move |cx| {
916            let w = cx.layout_only(Rc::new(OverlayHost), Flex::default(), Boundary::No);
917            let mut out = w;
918            cx.under(w, |cx| {
919                out = op_context_menu_fn_body(inner, f, cx);
920            });
921            // Sized by its content, so a platform row stays one through the menu's wrapper.
922            with_tree(|t| t.forward_whole_row(w, out));
923            out
924        })
925    }
926}
927
928fn op_context_menu_fn_body(
929    inner: Build,
930    f: Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>,
931    cx: &mut day_core::BuildCx,
932) -> day_core::RNode {
933    {
934        {
935            let n = inner(cx);
936            // Each summon lowers a fresh menu whose action closures live in their own scope,
937            // disposed when the next summon replaces them (and with the build scope at
938            // teardown), so per-click menus never accumulate registrations.
939            let last: Rc<std::cell::RefCell<Option<day_reactive::Scope>>> = Rc::default();
940            {
941                let last = last.clone();
942                day_reactive::Scope::current().on_cleanup(move || {
943                    if let Some(s) = last.borrow_mut().take() {
944                        s.dispose();
945                    }
946                });
947            }
948            let provider: day_spec::ContextMenuFn = Rc::new(move |p| {
949                if let Some(s) = last.borrow_mut().take() {
950                    s.dispose();
951                }
952                let scope = day_reactive::Scope::child();
953                let items = scope.enter(|| crate::menus::lower_menu_scoped(f(p)));
954                *last.borrow_mut() = Some(scope);
955                items
956            });
957            with_tree(|t| t.set_context_menu_fn(n, provider.clone()));
958            // A backend with no native menu reports the summon instead; the composed
959            // presenter calls the same provider there (docs/menus.md).
960            crate::menus::mount_composed_menu(cx, n, provider);
961            n
962        }
963    }
964}
965
966/// Enable `kind` on the node the modifier wraps and hand its events to `on`.
967fn op_gesture(
968    kind: GestureKind,
969    on: impl Fn(RNode, &Event) + 'static,
970) -> impl FnOnce(Build) -> Build {
971    move |inner| {
972        Box::new(move |cx| {
973            let n = inner(cx);
974            with_tree(|t| t.enable_gesture(n, kind));
975            cx.on(n, move |ev| on(n, ev));
976            n
977        })
978    }
979}
980
981fn op_on_drag(
982    axis: Option<day_spec::DragAxis>,
983    f: impl Fn(Drag) + 'static,
984) -> impl FnOnce(Build) -> Build {
985    move |inner| {
986        Box::new(move |cx| {
987            let n = inner(cx);
988            with_tree(|t| {
989                t.enable_gesture(n, GestureKind::Drag);
990                if axis.is_some() {
991                    t.set_drag_axis(n, axis);
992                }
993            });
994            cx.on(n, move |ev| {
995                if let Event::Drag {
996                    phase,
997                    location,
998                    translation,
999                } = ev
1000                {
1001                    let velocity =
1002                        day_core::gesture::velocity(day_core::rnode_to_id(n), GestureKind::Drag);
1003                    f(Drag::new(*phase, *location, *translation).with_velocity(velocity));
1004                }
1005            });
1006            n
1007        })
1008    }
1009}
1010
1011fn op_on_pinch(f: impl Fn(Pinch) + 'static) -> impl FnOnce(Build) -> Build {
1012    op_gesture(GestureKind::Pinch, move |_, ev| {
1013        if let Event::Pinch {
1014            phase,
1015            scale,
1016            location,
1017        } = ev
1018        {
1019            f(Pinch::new(*phase, *scale, *location));
1020        }
1021    })
1022}
1023
1024fn op_on_rotate(f: impl Fn(Rotate) + 'static) -> impl FnOnce(Build) -> Build {
1025    op_gesture(GestureKind::Rotate, move |_, ev| {
1026        if let Event::Rotate {
1027            phase,
1028            rotation,
1029            location,
1030        } = ev
1031        {
1032            f(Rotate::new(*phase, Angle::rad(*rotation), *location));
1033        }
1034    })
1035}
1036
1037fn op_on_hover(f: impl Fn(Option<day_spec::Point>) + 'static) -> impl FnOnce(Build) -> Build {
1038    op_gesture(GestureKind::Hover, move |_, ev| {
1039        if let Event::Hover { phase, location } = ev {
1040            // `None` on exit rather than a phase the caller has to match on: what a hover
1041            // handler wants to know is where the pointer IS, and "nowhere" is a state, not an
1042            // event kind. It is also what makes a handler that writes a
1043            // `Signal<Option<Point>>` a one-liner.
1044            f(match phase {
1045                day_spec::DragPhase::Ended => None,
1046                _ => Some(*location),
1047            });
1048        }
1049    })
1050}
1051
1052fn op_on_pan(f: impl Fn(Pan) + 'static) -> impl FnOnce(Build) -> Build {
1053    op_gesture(GestureKind::Pan, move |n, ev| {
1054        if let Event::Pan {
1055            phase,
1056            delta,
1057            location,
1058        } = ev
1059        {
1060            let velocity = day_core::gesture::velocity(day_core::rnode_to_id(n), GestureKind::Pan);
1061            f(Pan::new(*phase, *delta, *location).with_velocity(velocity));
1062        }
1063    })
1064}
1065
1066fn op_on_long_press(f: impl Fn(day_spec::Point) + 'static) -> impl FnOnce(Build) -> Build {
1067    op_gesture(GestureKind::LongPress, move |_, ev| {
1068        if let Event::LongPress(at) = ev {
1069            f(*at);
1070        }
1071    })
1072}
1073
1074fn op_on_double_tap(f: impl Fn() + 'static) -> impl FnOnce(Build) -> Build {
1075    op_gesture(GestureKind::DoubleTap, move |_, ev| {
1076        if matches!(ev, Event::DoubleTap(_)) {
1077            f();
1078        }
1079    })
1080}
1081
1082fn op_on_double_tap_at(f: impl Fn(day_spec::Point) + 'static) -> impl FnOnce(Build) -> Build {
1083    op_gesture(GestureKind::DoubleTap, move |_, ev| {
1084        if let Event::DoubleTap(at) = ev {
1085            f(*at);
1086        }
1087    })
1088}
1089
1090fn op_on_pressed(f: impl Fn(bool) + 'static) -> impl FnOnce(Build) -> Build {
1091    op_gesture(GestureKind::Press, move |_, ev| {
1092        if let Event::Press { pressed, .. } = ev {
1093            f(*pressed);
1094        }
1095    })
1096}
1097
1098fn op_on_touches(f: impl Fn(&[day_spec::Touch]) + 'static) -> impl FnOnce(Build) -> Build {
1099    op_gesture(GestureKind::Touches, move |_, ev| {
1100        if let Event::Touches(touches) = ev {
1101            f(touches);
1102        }
1103    })
1104}
1105
1106fn op_hit_slop(slop: Insets) -> impl FnOnce(Build) -> Build {
1107    move |inner| {
1108        Box::new(move |cx| {
1109            let n = inner(cx);
1110            with_tree(|t| t.set_hit_slop(n, slop));
1111            n
1112        })
1113    }
1114}
1115
1116fn op_interaction(state: InteractionState) -> impl FnOnce(Build) -> Build {
1117    move |inner| {
1118        Box::new(move |cx| {
1119            let n = inner(cx);
1120            with_tree(|t| {
1121                t.enable_gesture(n, GestureKind::Hover);
1122                t.enable_gesture(n, GestureKind::Press);
1123            });
1124            cx.on(n, move |ev| match ev {
1125                Event::Hover { phase, .. } => {
1126                    state.hovered.set(*phase != day_spec::DragPhase::Ended);
1127                }
1128                Event::Press { pressed, .. } => state.pressed.set(*pressed),
1129                Event::FocusChanged(focused) => state.focused.set(*focused),
1130                _ => {}
1131            });
1132            n
1133        })
1134    }
1135}
1136
1137fn op_enabled(enabled: Reactive<bool>) -> impl FnOnce(Build) -> Build {
1138    move |inner| {
1139        Box::new(move |cx| {
1140            let n = inner(cx);
1141            let apply = move |on: bool| {
1142                day_core::gesture::set_subtree_enabled(n, on);
1143                // The hover a disabled piece can no longer end is not left standing.
1144                if !on {
1145                    day_core::enqueue_event(
1146                        day_core::rnode_to_id(n),
1147                        Event::Hover {
1148                            phase: day_spec::DragPhase::Ended,
1149                            location: day_spec::Point::ZERO,
1150                        },
1151                    );
1152                }
1153            };
1154            // Only a reactive source needs a binding, and only a disabled start needs a call.
1155            if !enabled.get_untracked() {
1156                apply(false);
1157            }
1158            if let Reactive::Dyn(_) = &enabled {
1159                bind(move || enabled.get(), move |on: &bool| apply(*on));
1160            }
1161            n
1162        })
1163    }
1164}
1165
1166/// The tracked interaction state of one piece: whether the pointer is over it, whether it is
1167/// pressed, and whether it has the keyboard (docs/gestures.md "State styling").
1168///
1169/// Create one, attach it with [`Decorate::interaction`], and read it from any reactive
1170/// modifier. Each read is tracked, so the modifier follows the state with no handler in between:
1171///
1172/// ```ignore
1173/// let state = InteractionState::new();
1174/// row((icon, title))
1175///     .interaction(state)
1176///     .background(move || if state.pressed() { PRESSED } else if state.hovered() { HOVER } else { REST })
1177///     .opacity(move || if state.pressed() { 0.7 } else { 1.0 })
1178/// ```
1179///
1180/// `hovered` follows the pointer where one exists and stays `false` on a touch-only device.
1181/// `pressed` is `true` from the pointer-down itself until the release, the pointer leaving, or
1182/// the platform taking the gesture away. `focused` follows keyboard focus on a piece that can
1183/// take it ([`Decorate::focusable`], or a control inside). All three read `false` while the
1184/// piece is disabled ([`Decorate::enabled`]).
1185#[derive(Clone, Copy)]
1186pub struct InteractionState {
1187    hovered: Signal<bool>,
1188    pressed: Signal<bool>,
1189    focused: Signal<bool>,
1190}
1191
1192impl Default for InteractionState {
1193    fn default() -> Self {
1194        Self::new()
1195    }
1196}
1197
1198impl InteractionState {
1199    /// A state with nothing hovered, pressed or focused, owned by the scope it is created in.
1200    #[must_use]
1201    pub fn new() -> Self {
1202        InteractionState {
1203            hovered: Signal::new(false),
1204            pressed: Signal::new(false),
1205            focused: Signal::new(false),
1206        }
1207    }
1208    /// Whether the pointer is over the piece. Tracked.
1209    #[must_use]
1210    pub fn hovered(&self) -> bool {
1211        self.hovered.get()
1212    }
1213    /// Whether the piece is pressed. Tracked.
1214    #[must_use]
1215    pub fn pressed(&self) -> bool {
1216        self.pressed.get()
1217    }
1218    /// Whether the piece has keyboard focus. Tracked.
1219    #[must_use]
1220    pub fn focused(&self) -> bool {
1221        self.focused.get()
1222    }
1223}
1224
1225fn op_background(fill: Reactive<Paint>) -> impl FnOnce(Build) -> Build {
1226    move |inner| {
1227        Box::new(move |cx| {
1228            let seed = fill.get_untracked();
1229            let node = cx.native(
1230                kinds::CONTAINER,
1231                &ContainerProps {
1232                    fill: Some(seed.clone()),
1233                    ..Default::default()
1234                },
1235                Rc::new(FillThrough),
1236                Flex::default(),
1237                Boundary::No,
1238            );
1239            cx.under(node, |cx| {
1240                let _ = inner(cx);
1241            });
1242            // Only a reactive source needs a binding; a constant fill is applied once at
1243            // realize, and an ink that follows the appearance is the toolkit's to follow.
1244            if let Reactive::Dyn(_) = &fill {
1245                day_reactive::bind_seeded(
1246                    seed,
1247                    move || fill.get(),
1248                    move |p: &Paint| {
1249                        with_tree(|t| {
1250                            t.patch(node, Box::new(ContainerPatch::Fill(Some(p.clone()))), false);
1251                        });
1252                    },
1253                );
1254            }
1255            node
1256        })
1257    }
1258}
1259
1260/// A semantic surface around the content: the toolkit's material for `role`, clipped to
1261/// `radius` corners.
1262fn op_surface(role: day_spec::SurfaceRole, radius: f64) -> impl FnOnce(Build) -> Build {
1263    move |inner| {
1264        Box::new(move |cx| {
1265            let w = cx.native(
1266                kinds::CONTAINER,
1267                &ContainerProps {
1268                    corner_radius: radius,
1269                    clips: true,
1270                    role: Some(role),
1271                    ..Default::default()
1272                },
1273                Rc::new(FillThrough),
1274                Flex::default(),
1275                Boundary::No,
1276            );
1277            cx.under(w, |cx| {
1278                let _ = inner(cx);
1279            });
1280            w
1281        })
1282    }
1283}
1284
1285/// A styled native surface behind a piece: fill, rounded corners, border and shadow on one
1286/// native view (docs/surfaces.md).
1287///
1288/// The single-purpose modifiers each wrap the piece in a view of their own, so a border added
1289/// after `.corner_radius(..)` is a square border around a rounded view. A surface is one view
1290/// that carries all of it, which is what lets the border follow the corners and the shadow take
1291/// their shape:
1292///
1293/// ```ignore
1294/// label("Sale")
1295///     .padding(Space::M)
1296///     .surface(
1297///         Surface::new()
1298///             .fill(LinearGradient::vertical(top, bottom))
1299///             .corner_radius(Radius::L)
1300///             .corners(Corners::TOP)
1301///             .border(SystemColor::Separator, 1.0),
1302///     )
1303/// ```
1304///
1305/// Every color is an [`Ink`], so a surface follows the appearance with no rebuild. A surface
1306/// with a corner radius clips its content to the rounded rectangle, as `.corner_radius(..)`
1307/// does. A surface with a shadow does not clip: the shadow lies outside the frame a clip would
1308/// cut to. Put a clipping `.corner_radius(..)` inside it when the content must be cut as well.
1309/// The border is drawn over the content.
1310#[derive(Clone, Debug, Default, PartialEq)]
1311#[must_use]
1312pub struct Surface {
1313    fill: Option<Paint>,
1314    radius: crate::Corner,
1315    corners: day_spec::Corners,
1316    border: Option<day_spec::Border>,
1317    shadow: Option<day_spec::Shadow>,
1318}
1319
1320impl Surface {
1321    /// A surface with nothing on it yet: transparent, square, no border, no shadow.
1322    pub fn new() -> Self {
1323        Surface::default()
1324    }
1325    /// Fill with a [`Paint`]: a color, a [`SystemColor`](day_spec::SystemColor), an [`Ink`],
1326    /// or a linear, radial or conic gradient. A gradient's unit points resolve against the
1327    /// surface's frame and follow it as it resizes.
1328    pub fn fill(mut self, fill: impl Into<Paint>) -> Self {
1329        self.fill = Some(fill.into());
1330        self
1331    }
1332    /// Round the corners (all four, unless [`Self::corners`] says which): points, a
1333    /// [`Radius`](crate::Radius) step, or a frame-relative [`Corner`](crate::Corner) such as
1334    /// [`Corner::CAPSULE`](crate::Corner::CAPSULE).
1335    pub fn corner_radius(mut self, radius: impl Into<crate::Corner>) -> Self {
1336        self.radius = radius.into();
1337        self
1338    }
1339    /// Which corners the radius rounds; the others stay square.
1340    pub fn corners(mut self, corners: day_spec::Corners) -> Self {
1341        self.corners = corners;
1342        self
1343    }
1344    /// A line of `color`, `width` points wide, around the edge, inside the frame and over the
1345    /// content.
1346    pub fn border(mut self, color: impl Into<Ink>, width: f64) -> Self {
1347        self.border = (width > 0.0).then(|| day_spec::Border::new(color, width));
1348        self
1349    }
1350    /// A shadow of the surface's rounded rectangle, outside its frame. It takes no room in
1351    /// layout, so leave space around the piece for it, and it stops the surface clipping its
1352    /// content.
1353    pub fn shadow(mut self, shadow: day_spec::Shadow) -> Self {
1354        self.shadow = Some(shadow);
1355        self
1356    }
1357
1358    /// The realize props in a frame of `size` (zero before the first layout, which only
1359    /// matters to a frame-relative radius).
1360    fn props(&self, size: day_spec::Size, clip: Clip) -> ContainerProps {
1361        let radius = match self.radius {
1362            crate::Corner::Fixed(points) => points.max(0.0),
1363            relative @ crate::Corner::Fraction(_) => relative.points(size),
1364        };
1365        let rounded = radius > 0.0 || self.radius.is_relative();
1366        ContainerProps {
1367            fill: self.fill.clone(),
1368            corner_radius: radius,
1369            corners: self.corners,
1370            border: self.border,
1371            shadow: self.shadow,
1372            clips: match clip {
1373                Clip::Always => true,
1374                Clip::WhenRounded => rounded && self.shadow.is_none(),
1375            },
1376            role: None,
1377        }
1378    }
1379}
1380
1381/// When a surface clips its content.
1382#[derive(Clone, Copy)]
1383enum Clip {
1384    /// A rounded surface without a shadow clips: what `.surface(..)` does.
1385    WhenRounded,
1386    /// Always, square or not: what `.corner_radius(..)` does, so a radius that animates down
1387    /// to zero keeps the content inside the frame.
1388    Always,
1389}
1390
1391/// The one surface op: realize the style, follow a reactive one with `ContainerPatch::Surface`,
1392/// and re-resolve a frame-relative radius as layout resizes the view. A constant surface with a
1393/// fixed radius binds nothing.
1394fn op_styled_surface(surface: Reactive<Surface>, clip: Clip) -> impl FnOnce(Build) -> Build {
1395    move |inner| {
1396        Box::new(move |cx| {
1397            let seed = surface.get_untracked();
1398            let size = Rc::new(Cell::new(day_spec::Size::ZERO));
1399            let node = cx.native(
1400                kinds::CONTAINER,
1401                &seed.props(size.get(), clip),
1402                Rc::new(FillThrough),
1403                Flex::default(),
1404                Boundary::No,
1405            );
1406            cx.under(node, |cx| {
1407                let _ = inner(cx);
1408            });
1409            let current = Rc::new(std::cell::RefCell::new(seed.clone()));
1410            let send = {
1411                let (size, current) = (size.clone(), current.clone());
1412                move || {
1413                    let props = current.borrow().props(size.get(), clip);
1414                    with_tree(|t| {
1415                        t.patch(
1416                            node,
1417                            Box::new(ContainerPatch::Surface(Box::new(props))),
1418                            false,
1419                        );
1420                    });
1421                }
1422            };
1423            let relative = match &surface {
1424                Reactive::Const(s) => s.radius.is_relative(),
1425                // A reactive surface may turn relative later; it watches its frame throughout.
1426                Reactive::Dyn(_) => true,
1427            };
1428            if relative {
1429                // Resolved in the layout pass that sizes the view, with its frame, so the first
1430                // frame the surface is shown at is already round.
1431                let (size, current) = (size.clone(), current.clone());
1432                day_core::patch_on_frame(
1433                    node,
1434                    Rc::new(move |new: day_spec::Size| {
1435                        if new.approx_eq(size.get(), 0.25) {
1436                            return None;
1437                        }
1438                        size.set(new);
1439                        let surface = current.try_borrow().ok()?;
1440                        surface.radius.is_relative().then(|| {
1441                            Box::new(ContainerPatch::Surface(Box::new(surface.props(new, clip))))
1442                                as Box<dyn std::any::Any>
1443                        })
1444                    }),
1445                );
1446                day_reactive::Scope::current()
1447                    .on_cleanup(move || day_core::stop_frame_patches(node));
1448            }
1449            if let Reactive::Dyn(_) = &surface {
1450                day_reactive::bind_seeded(
1451                    seed,
1452                    move || surface.get(),
1453                    move |s: &Surface| {
1454                        *current.borrow_mut() = s.clone();
1455                        send();
1456                    },
1457                );
1458            }
1459            node
1460        })
1461    }
1462}
1463
1464/// Combine reactive parts into one reactive value: constant when every part is.
1465fn reactive_map2<A: Clone + 'static, B: Clone + 'static, T: Clone + 'static>(
1466    a: Reactive<A>,
1467    b: Reactive<B>,
1468    f: impl Fn(A, B) -> T + 'static,
1469) -> Reactive<T> {
1470    match (&a, &b) {
1471        (Reactive::Const(x), Reactive::Const(y)) => Reactive::Const(f(x.clone(), y.clone())),
1472        _ => Reactive::Dyn(Rc::new(move || f(a.get(), b.get()))),
1473    }
1474}
1475
1476/// A reactive value mapped: constant when the source is.
1477fn reactive_map<A: Clone + 'static, T: Clone + 'static>(
1478    a: Reactive<A>,
1479    f: impl Fn(A) -> T + 'static,
1480) -> Reactive<T> {
1481    match &a {
1482        Reactive::Const(x) => Reactive::Const(f(x.clone())),
1483        Reactive::Dyn(_) => Reactive::Dyn(Rc::new(move || f(a.get()))),
1484    }
1485}
1486
1487fn op_opacity(op: Reactive<f64>) -> impl FnOnce(Build) -> Build {
1488    move |inner| {
1489        Box::new(move |cx| {
1490            let node = layer_node(cx);
1491            cx.under(node, |cx| {
1492                let _ = inner(cx);
1493            });
1494            bind(
1495                move || op.get(),
1496                move |v: &f64| with_tree(|t| t.set_node_opacity(node, *v)),
1497            );
1498            node
1499        })
1500    }
1501}
1502
1503fn op_transform(t: Reactive<Transform>) -> impl FnOnce(Build) -> Build {
1504    move |inner| {
1505        Box::new(move |cx| {
1506            let node = layer_node(cx);
1507            cx.under(node, |cx| {
1508                let _ = inner(cx);
1509            });
1510            bind(
1511                move || t.get(),
1512                move |v: &Transform| with_tree(|tr| tr.set_node_transform(node, *v)),
1513            );
1514            node
1515        })
1516    }
1517}
1518
1519fn op_animation(anim: AnimSpec) -> impl FnOnce(Build) -> Build {
1520    move |inner| {
1521        Box::new(move |cx| {
1522            // Layout-only: the implicit animation is Day's own state, which the patches beneath
1523            // look up through their ancestors, and needs no native view. A native layer here
1524            // also clipped what it held on the toolkits whose containers clip their children
1525            // (Qt always, Android by default), so a translated or scaled view under
1526            // `.animation(..)` vanished past the layer's frame.
1527            let node = cx.layout_only(Rc::new(FillThrough), Flex::default(), Boundary::No);
1528            with_tree(|t| t.set_implicit_anim(node, Some(anim)));
1529            cx.under(node, |cx| {
1530                let _ = inner(cx);
1531            });
1532            node
1533        })
1534    }
1535}
1536
1537fn op_overlay_aligned(align: Alignment, over: impl Piece) -> impl FnOnce(Build) -> Build {
1538    move |inner| {
1539        Box::new(move |cx| {
1540            let node = cx.native(
1541                kinds::CONTAINER,
1542                &ContainerProps::default(),
1543                Rc::new(OverlayLayout {
1544                    align,
1545                    size_to_first: true,
1546                }),
1547                Flex::default(),
1548                Boundary::No,
1549            );
1550            cx.under(node, |cx| {
1551                let _ = inner(cx); // sizing content (bottom)
1552                let _ = over.build(cx); // annotation on top
1553            });
1554            node
1555        })
1556    }
1557}
1558
1559fn op_aspect_ratio(ratio: Reactive<f64>) -> impl FnOnce(Build) -> Build {
1560    move |inner| {
1561        Box::new(move |cx| {
1562            if let Reactive::Const(r) = &ratio
1563                && !(r.is_finite() && *r > 0.0)
1564            {
1565                return inner(cx);
1566            }
1567            let layout = Rc::new(AspectRatioLayout {
1568                ratio: Cell::new(ratio.get_untracked()),
1569            });
1570            let node = cx.layout_only(
1571                layout.clone(),
1572                Flex::default(),
1573                // Not a boundary: the child still measures itself, and the ratio only decides
1574                // the box it is offered.
1575                Boundary::No,
1576            );
1577            cx.under(node, |cx| {
1578                let _ = inner(cx);
1579            });
1580            bind_length(ratio, move |v| layout.ratio.set(v), node);
1581            node
1582        })
1583    }
1584}
1585
1586fn op_aligned(align: Alignment) -> impl FnOnce(Build) -> Build {
1587    move |inner| {
1588        Box::new(move |cx| {
1589            let node = cx.layout_only(
1590                Rc::new(AlignmentLayout { align }),
1591                Flex::default(),
1592                Boundary::No,
1593            );
1594            cx.under(node, |cx| {
1595                let _ = inner(cx);
1596            });
1597            node
1598        })
1599    }
1600}
1601
1602fn op_grow(grow: Grow) -> impl FnOnce(Build) -> Build {
1603    let w = matches!(grow.dimension, Dimension::Width | Dimension::Both);
1604    let h = matches!(grow.dimension, Dimension::Height | Dimension::Both);
1605    move |inner| {
1606        Box::new(move |cx| {
1607            let node = cx.layout_only(
1608                Rc::new(GrowLayout { w, h }),
1609                Flex {
1610                    grow_w: w,
1611                    grow_h: h,
1612                    grow_weight: grow.weight,
1613                    ..Default::default()
1614                },
1615                Boundary::No,
1616            );
1617            cx.under(node, |cx| {
1618                let _ = inner(cx);
1619            });
1620            node
1621        })
1622    }
1623}
1624
1625fn op_grid_facts(facts: GridFacts) -> impl FnOnce(RNode) {
1626    move |node| with_tree(|t| t.set_grid_facts(node, facts))
1627}
1628
1629fn op_defers_system_gestures(edges: day_spec::Edges) -> impl FnOnce(Build) -> Build {
1630    move |inner| {
1631        Box::new(move |cx| {
1632            let token = day_core::shield::push_gesture_deferral(edges);
1633            Scope::current().on_cleanup(move || day_core::shield::pop_gesture_deferral(token));
1634            inner(cx)
1635        })
1636    }
1637}
1638
1639fn op_status_bar_hidden(hidden: Reactive<bool>) -> impl FnOnce(Build) -> Build {
1640    move |inner| {
1641        Box::new(move |cx| {
1642            let token = day_core::shield::push_status_bar_request(hidden.get_untracked());
1643            Scope::current().on_cleanup(move || day_core::shield::pop_status_bar_request(token));
1644            // A constant answer is registered once; a reactive one follows its source while
1645            // the subtree stays mounted (a reader's "hide status bar" setting).
1646            if let Reactive::Dyn(_) = &hidden {
1647                bind(
1648                    move || hidden.get(),
1649                    move |h: &bool| day_core::shield::set_status_bar_request(token, *h),
1650                );
1651            }
1652            inner(cx)
1653        })
1654    }
1655}
1656
1657fn op_on_system_back(
1658    enabled: Reactive<bool>,
1659    handler: Rc<dyn Fn()>,
1660) -> impl FnOnce(Build) -> Build {
1661    move |inner| {
1662        Box::new(move |cx| {
1663            crate::nav::install_back_handler(cx.parent(), enabled, handler);
1664            inner(cx)
1665        })
1666    }
1667}
1668
1669fn op_interactive_dismiss_disabled() -> impl FnOnce(Build) -> Build {
1670    move |inner| {
1671        Box::new(move |cx| {
1672            let token = day_core::shield::push_dismiss_disabled();
1673            Scope::current().on_cleanup(move || day_core::shield::pop_dismiss_disabled(token));
1674            inner(cx)
1675        })
1676    }
1677}
1678
1679// --- The chained modifier surface, on an already-decorated piece ---
1680//
1681// These inherent methods shadow the `Decorate` trait's (inherent wins method resolution), so a
1682// modifier applied to a `Decorated` appends to its op list instead of wrapping it in another
1683// `Decorated`. Each is the same one-liner the trait method is; the bodies live in the `op_*`
1684// functions above. Documentation stays on the trait, which is the surface every piece has.
1685impl<P: Piece> Decorated<P> {
1686    pub fn id(self, id: day_core::ElementId) -> Self {
1687        self.push_node(op_id(id))
1688    }
1689    pub fn id_of(self, id: impl Fn() -> day_core::ElementId + 'static) -> Self {
1690        self.push_node(op_id_of(id))
1691    }
1692    pub fn wrapper_id(self, id: day_core::ElementId) -> Self {
1693        self.push(op_wrapper_id(id))
1694    }
1695    pub fn tweak(self, f: impl FnOnce(day_core::RNode) + 'static) -> Self {
1696        self.push(op_tweak(f))
1697    }
1698    pub fn selectable(self) -> Self {
1699        self.push(op_selectable())
1700    }
1701    pub fn cursor<M>(self, cursor: impl IntoReactive<Cursor, M>) -> Self {
1702        self.push(op_cursor(cursor.into_reactive()))
1703    }
1704    pub fn layout_direction<M>(
1705        self,
1706        direction: impl IntoReactive<day_spec::LayoutDirection, M>,
1707    ) -> Self {
1708        self.push(op_layout_direction(direction.into_reactive()))
1709    }
1710    pub fn native_ref(self, r: &NativeRef) -> Self {
1711        self.push(op_native_ref(r.clone()))
1712    }
1713    pub fn window_drag_region(self) -> Self {
1714        self.push(op_window_drag_region())
1715    }
1716    pub fn padding<M>(self, insets: impl IntoReactive<Insets, M>) -> Self {
1717        self.push(op_padding(insets.into_reactive()))
1718    }
1719    pub fn max_width<M>(self, max: impl IntoReactive<f64, M>) -> Self {
1720        self.push(op_max_width(max.into_reactive()))
1721    }
1722    /// Never taller than `max`: the child is never proposed more height, so a scroll stops
1723    /// growing at `max` and still shrinks where the screen is shorter. In a column it is sized
1724    /// after its siblings and takes what they leave, up to `max`, so the controls around a
1725    /// capped scroll stay on screen.
1726    pub fn max_height<M>(self, max: impl IntoReactive<f64, M>) -> Self {
1727        self.push(op_max_height(max.into_reactive()))
1728    }
1729    /// Never narrower than `min`: a stretching control keeps a usable width, and a row that
1730    /// cannot give it that overflows, so a `labeled` row stacks the control under its label
1731    /// rather than squeezing it (docs/forms.md).
1732    pub fn min_width<M>(self, min: impl IntoReactive<f64, M>) -> Self {
1733        self.push(op_min_width(min.into_reactive()))
1734    }
1735    pub fn reserving<M>(self, sample: impl IntoText<M>) -> Self {
1736        self.push(op_reserving(sample.into_text()))
1737    }
1738    /// Set both dimensions from constants, signals, or reactive closures.
1739    /// Negative and non-finite sizes become zero. Updates preserve mounted content.
1740    pub fn frame<Mw, Mh>(
1741        self,
1742        width: impl IntoReactive<f64, Mw>,
1743        height: impl IntoReactive<f64, Mh>,
1744    ) -> Self {
1745        self.push(op_frame(
1746            Some(width.into_reactive()),
1747            Some(height.into_reactive()),
1748        ))
1749    }
1750    /// Set a constant or reactive width, leaving height flexible.
1751    pub fn width<M>(self, width: impl IntoReactive<f64, M>) -> Self {
1752        self.push(op_frame(Some(width.into_reactive()), None))
1753    }
1754    /// Set a constant or reactive height, leaving width flexible.
1755    pub fn height<M>(self, height: impl IntoReactive<f64, M>) -> Self {
1756        self.push(op_frame(None, Some(height.into_reactive())))
1757    }
1758    /// Keep at least `min` points of height, expanding for taller content.
1759    pub fn min_height<M>(self, min: impl IntoReactive<f64, M>) -> Self {
1760        self.push(op_min_height(min.into_reactive()))
1761    }
1762    pub fn a11y(self, f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> Self {
1763        self.push(op_a11y(f))
1764    }
1765    /// Handle a tap gesture on this piece.
1766    ///
1767    /// Do not use this to activate a native button; use [`crate::ButtonBuilder::action`].
1768    /// A separate gesture recognizer can delay pressed feedback and bypass native keyboard,
1769    /// accessibility, and disabled behavior. Day warns when it attaches a tap to a button.
1770    pub fn on_tap(self, f: impl Fn() + 'static) -> Self {
1771        self.push(op_on_tap(f))
1772    }
1773    /// Handle a tap with its local position. Like [`Self::on_tap`], this is a gesture,
1774    /// not native button activation; use [`crate::ButtonBuilder::action`] for buttons.
1775    pub fn on_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Self {
1776        self.push(op_on_tap_at(f))
1777    }
1778    pub fn focused<M>(self, binding: impl IntoFocusBinding<M>) -> Self {
1779        let (want, on_native) = binding.into_focus_binding();
1780        self.push(op_focused(want, on_native))
1781    }
1782    pub fn on_key(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Self {
1783        self.push(op_on_key(false, f))
1784    }
1785    pub fn on_key_up(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Self {
1786        self.push(op_on_key(true, f))
1787    }
1788    pub fn focusable(self) -> Self {
1789        self.push(op_focusable())
1790    }
1791    pub fn keyboard(self) -> Self {
1792        self.push(op_keyboard())
1793    }
1794    pub fn toolbar<M>(self, content: impl crate::ToolbarContent<M>) -> Self {
1795        self.push(op_toolbar(content.into_source()))
1796    }
1797    /// See [`Decorate::searchable`].
1798    pub fn searchable(self, search: crate::Search) -> Self {
1799        self.push(move |inner| {
1800            Box::new(move |cx| {
1801                let n = inner(cx);
1802                crate::nav::install_page_search(search);
1803                n
1804            })
1805        })
1806    }
1807    /// Offer data through the platform's native drag session.
1808    pub fn drag_source(
1809        self,
1810        source: impl Fn(day_spec::Point) -> Option<day_spec::transfer::Offer> + 'static,
1811    ) -> Self {
1812        self.push(move |inner| {
1813            Box::new(move |cx| {
1814                let n = layer_node(cx);
1815                cx.under(n, |cx| {
1816                    inner(cx);
1817                });
1818                let source = scoped_drag_source(Rc::new(source));
1819                with_tree(|t| t.set_drag_source(n, source));
1820                n
1821            })
1822        })
1823    }
1824    /// Accept drops through the platform's native drag session (docs/drag-and-drop.md).
1825    pub fn drop_target(self, target: day_spec::transfer::Target) -> Self {
1826        self.push(move |inner| {
1827            Box::new(move |cx| {
1828                let n = layer_node(cx);
1829                cx.under(n, |cx| {
1830                    inner(cx);
1831                });
1832                let target = scoped_drop_target(target);
1833                with_tree(|t| t.set_drop_target(n, target));
1834                n
1835            })
1836        })
1837    }
1838    pub fn context_menu<M>(self, menu: impl ContextMenuContent<M>) -> Self {
1839        match menu.into_context_menu() {
1840            ContextMenuSource::Fixed(items) => self.push(op_context_menu(items)),
1841            ContextMenuSource::OnSummon(f) => self.push(op_context_menu_fn(f)),
1842        }
1843    }
1844    pub fn on_drag(self, f: impl Fn(Drag) + 'static) -> Self {
1845        self.push(op_on_drag(None, f))
1846    }
1847    pub fn on_drag_along(self, axis: day_spec::DragAxis, f: impl Fn(Drag) + 'static) -> Self {
1848        self.push(op_on_drag(Some(axis), f))
1849    }
1850    pub fn on_long_press(self, f: impl Fn(day_spec::Point) + 'static) -> Self {
1851        self.push(op_on_long_press(f))
1852    }
1853    pub fn on_double_tap(self, f: impl Fn() + 'static) -> Self {
1854        self.push(op_on_double_tap(f))
1855    }
1856    /// See [`Decorate::on_double_tap_at`].
1857    pub fn on_double_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Self {
1858        self.push(op_on_double_tap_at(f))
1859    }
1860    pub fn on_pressed(self, f: impl Fn(bool) + 'static) -> Self {
1861        self.push(op_on_pressed(f))
1862    }
1863    pub fn on_touches(self, f: impl Fn(&[day_spec::Touch]) + 'static) -> Self {
1864        self.push(op_on_touches(f))
1865    }
1866    pub fn hit_slop(self, slop: impl Into<Insets>) -> Self {
1867        self.push(op_hit_slop(slop.into()))
1868    }
1869    pub fn interaction(self, state: InteractionState) -> Self {
1870        self.push(op_interaction(state))
1871    }
1872    pub fn enabled<M>(self, enabled: impl IntoReactive<bool, M>) -> Self {
1873        self.push(op_enabled(enabled.into_reactive()))
1874    }
1875    pub fn on_files_dropped(self, f: impl Fn(Vec<std::path::PathBuf>) + 'static) -> Self {
1876        self.drop_target(day_spec::transfer::Target::files().on_drop(move |drop| {
1877            let paths = drop.file_paths();
1878            let any = !paths.is_empty();
1879            if any {
1880                f(paths);
1881            }
1882            any
1883        }))
1884    }
1885    pub fn on_pinch(self, f: impl Fn(Pinch) + 'static) -> Self {
1886        self.push(op_on_pinch(f))
1887    }
1888    pub fn on_rotate(self, f: impl Fn(Rotate) + 'static) -> Self {
1889        self.push(op_on_rotate(f))
1890    }
1891    pub fn on_pan(self, f: impl Fn(Pan) + 'static) -> Self {
1892        self.push(op_on_pan(f))
1893    }
1894    /// The pointer moving over this piece: `Some(point)` in its own coordinates while inside,
1895    /// `None` when it leaves (docs/canvas.md "Interaction").
1896    ///
1897    /// Pointer-only, which is not a gap: every desktop delivers it, an
1898    /// iPad does with a trackpad or pencil, an Android device with a mouse or stylus, and a
1899    /// touch-only phone delivers nothing at all. **Anything reachable by hover must also be
1900    /// reachable by a tap**: wire `on_tap_at` alongside it, exactly as a chart's selection does.
1901    pub fn on_hover(self, f: impl Fn(Option<day_spec::Point>) + 'static) -> Self {
1902        self.push(op_on_hover(f))
1903    }
1904    /// The platform's card: the grouped-content surface (`SurfaceRole::SectionCard`) with
1905    /// rounded corners and a `Space::M` inset. Drawn by the toolkit, so it follows the
1906    /// appearance and never steals hit testing from the content.
1907    pub fn card(self) -> Self {
1908        self.padding(crate::Space::M).push(op_surface(
1909            day_spec::SurfaceRole::SectionCard,
1910            crate::Radius::M.points(),
1911        ))
1912    }
1913    pub fn background<M>(self, fill: impl IntoReactive<Paint, M>) -> Self {
1914        self.push(op_background(fill.into_reactive()))
1915    }
1916    pub fn corner_radius<M>(self, radius: impl IntoReactive<crate::Corner, M>) -> Self {
1917        let surface = reactive_map(radius.into_reactive(), |r| Surface::new().corner_radius(r));
1918        self.push(op_styled_surface(surface, Clip::Always))
1919    }
1920    pub fn surface<M>(self, surface: impl IntoReactive<Surface, M>) -> Self {
1921        self.push(op_styled_surface(
1922            surface.into_reactive(),
1923            Clip::WhenRounded,
1924        ))
1925    }
1926    pub fn border<Mc, Mw>(
1927        self,
1928        color: impl IntoReactive<Ink, Mc>,
1929        width: impl IntoReactive<f64, Mw>,
1930    ) -> Self {
1931        let surface = reactive_map2(color.into_reactive(), width.into_reactive(), |c, w| {
1932            Surface::new().border(c, w)
1933        });
1934        self.push(op_styled_surface(surface, Clip::WhenRounded))
1935    }
1936    pub fn shadow<M>(self, shadow: impl IntoReactive<day_spec::Shadow, M>) -> Self {
1937        let surface = reactive_map(shadow.into_reactive(), |s| Surface::new().shadow(s));
1938        self.push(op_styled_surface(surface, Clip::WhenRounded))
1939    }
1940    pub fn opacity<M>(self, opacity: impl IntoReactive<f64, M>) -> Self {
1941        self.push(op_opacity(opacity.into_reactive()))
1942    }
1943    pub fn transform<M>(self, t: impl IntoReactive<Transform, M>) -> Self {
1944        self.push(op_transform(t.into_reactive()))
1945    }
1946    pub fn scale<M>(self, factor: impl IntoReactive<f64, M>) -> Self {
1947        let f = factor.into_reactive();
1948        self.transform(move || Transform::scale(f.get(), f.get()))
1949    }
1950    pub fn rotation<M>(self, angle: impl IntoReactive<Angle, M>) -> Self {
1951        let a = angle.into_reactive();
1952        self.transform(move || Transform::rotate(a.get()))
1953    }
1954    pub fn translation<Mx, My>(
1955        self,
1956        x: impl IntoReactive<f64, Mx>,
1957        y: impl IntoReactive<f64, My>,
1958    ) -> Self {
1959        let (x, y) = (x.into_reactive(), y.into_reactive());
1960        self.transform(move || Transform::translate(x.get(), y.get()))
1961    }
1962    pub fn animation(self, anim: AnimSpec) -> Self {
1963        self.push(op_animation(anim))
1964    }
1965    /// Erases, like [`Decorate::modifier`]: `Modifier` is defined over [`AnyPiece`].
1966    pub fn modifier(self, m: impl Modifier) -> AnyPiece {
1967        m.apply(self.any())
1968    }
1969    pub fn overlay(self, over: impl Piece) -> Self {
1970        self.overlay_aligned(Alignment::Center, over)
1971    }
1972    pub fn overlay_aligned(self, align: Alignment, over: impl Piece) -> Self {
1973        self.push(op_overlay_aligned(align, over))
1974    }
1975    pub fn aspect_ratio<M>(self, ratio: impl IntoReactive<f64, M>) -> Self {
1976        self.push(op_aspect_ratio(ratio.into_reactive()))
1977    }
1978    /// Position this piece within its assigned space; see [`Decorate::aligned`].
1979    pub fn aligned(self, alignment: Alignment) -> Self {
1980        self.push(op_aligned(alignment))
1981    }
1982    /// Expand in the selected dimensions; see [`Decorate::grow`].
1983    pub fn grow(self, grow: impl Into<Grow>) -> Self {
1984        self.push(op_grow(grow.into()))
1985    }
1986    #[deprecated(note = "use .grow(Dimension::Width)")]
1987    pub fn grow_w(self) -> Self {
1988        self.grow(Dimension::Width)
1989    }
1990    #[deprecated(note = "use .grow(Dimension::Height)")]
1991    pub fn grow_h(self) -> Self {
1992        self.grow(Dimension::Height)
1993    }
1994    pub fn grid_span(self, n: usize) -> Self {
1995        self.push_outer(op_grid_facts(GridFacts {
1996            col_span: n.clamp(1, u16::MAX as usize) as u16,
1997            ..Default::default()
1998        }))
1999    }
2000    pub fn grid_align(self, a: Alignment) -> Self {
2001        self.push_outer(op_grid_facts(GridFacts {
2002            align: Some(a),
2003            ..Default::default()
2004        }))
2005    }
2006    pub fn defers_system_gestures(self, edges: day_spec::Edges) -> Self {
2007        self.push(op_defers_system_gestures(edges))
2008    }
2009    pub fn interactive_dismiss_disabled(self) -> Self {
2010        self.push(op_interactive_dismiss_disabled())
2011    }
2012    pub fn on_system_back<M>(
2013        self,
2014        enabled: impl IntoReactive<bool, M>,
2015        handler: impl Fn() + 'static,
2016    ) -> Self {
2017        self.push(op_on_system_back(enabled.into_reactive(), Rc::new(handler)))
2018    }
2019    pub fn status_bar_hidden<M>(self, hidden: impl IntoReactive<bool, M>) -> Self {
2020        self.push(op_status_bar_hidden(hidden.into_reactive()))
2021    }
2022    /// Erase to a single [`AnyPiece`].
2023    pub fn any(self) -> AnyPiece {
2024        AnyPiece::new(self)
2025    }
2026}
2027
2028/// Where a context menu's entries come from (see [`Decorate::context_menu`]).
2029pub enum ContextMenuSource {
2030    Fixed(Vec<MenuEntry>),
2031    OnSummon(Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>),
2032}
2033
2034/// Anything [`Decorate::context_menu`] accepts: a `Vec` or array of entries, a closure building
2035/// them on summon, or a closure given the summon point. The marker parameter is the same E0119
2036/// dodge as [`IntoText`].
2037pub trait ContextMenuContent<M> {
2038    fn into_context_menu(self) -> ContextMenuSource;
2039}
2040
2041/// Marker for a summon-time closure that takes the summon point.
2042pub struct AtPointMark;
2043
2044impl ContextMenuContent<crate::ManyMark> for Vec<MenuEntry> {
2045    fn into_context_menu(self) -> ContextMenuSource {
2046        ContextMenuSource::Fixed(self)
2047    }
2048}
2049
2050impl<const N: usize> ContextMenuContent<crate::ManyMark> for [MenuEntry; N] {
2051    fn into_context_menu(self) -> ContextMenuSource {
2052        ContextMenuSource::Fixed(Vec::from(self))
2053    }
2054}
2055
2056impl<C, F> ContextMenuContent<crate::DerivedMark> for F
2057where
2058    C: IntoIterator<Item = MenuEntry>,
2059    F: Fn() -> C + 'static,
2060{
2061    fn into_context_menu(self) -> ContextMenuSource {
2062        ContextMenuSource::OnSummon(Rc::new(move |_| self().into_iter().collect()))
2063    }
2064}
2065
2066impl<C, F> ContextMenuContent<AtPointMark> for F
2067where
2068    C: IntoIterator<Item = MenuEntry>,
2069    F: Fn(day_spec::Point) -> C + 'static,
2070{
2071    fn into_context_menu(self) -> ContextMenuSource {
2072        ContextMenuSource::OnSummon(Rc::new(move |p| self(p).into_iter().collect()))
2073    }
2074}
2075
2076pub trait Decorate: Piece + Sized {
2077    /// Stable element identifier: a11y identifier + dayscript locator + lint uniqueness (§5.5).
2078    ///
2079    /// Names the piece's own node wherever it sits in the chain (docs/api-style.md "Modifier
2080    /// classes"): `.padding(8.0).id(day_core::id!(x))` and `.id(day_core::id!(x)).padding(8.0)` tag the same node. To name
2081    /// a wrapper instead, use [`wrapper_id`](Self::wrapper_id).
2082    fn id(self, id: day_core::ElementId) -> Decorated<Self> {
2083        Decorated::new(self).id(id)
2084    }
2085
2086    /// Name the node that is outermost at this point in the chain: the padding box, the frame,
2087    /// the background, whichever wrapper the modifiers before it built. For a dayscript frame
2088    /// assertion on the wrapper rather than on the piece. Ordered, unlike [`id`](Self::id).
2089    fn wrapper_id(self, id: day_core::ElementId) -> Decorated<Self> {
2090        Decorated::new(self).wrapper_id(id)
2091    }
2092
2093    /// Apply `f` to the chain when `cond` holds, else continue unchanged
2094    /// (see [`Decorated::apply_if`]): `nav(sel).apply_if(!primary, |n| n.local())`. The
2095    /// closure receives the decorated piece, so forwarded builder methods and modifiers both
2096    /// chain inside it.
2097    fn apply_if(
2098        self,
2099        cond: bool,
2100        f: impl FnOnce(Decorated<Self>) -> Decorated<Self>,
2101    ) -> Decorated<Self> {
2102        Decorated::new(self).apply_if(cond, f)
2103    }
2104
2105    /// Apply `f` with the value when there is one, else continue unchanged
2106    /// (see [`Decorated::apply_some`]): `canvas(draw).apply_some(id, |c, id| c.id(id))`.
2107    fn apply_some<T>(
2108        self,
2109        value: Option<T>,
2110        f: impl FnOnce(Decorated<Self>, T) -> Decorated<Self>,
2111    ) -> Decorated<Self> {
2112        Decorated::new(self).apply_some(value, f)
2113    }
2114
2115    /// Reactive element id: the id for rows inside a recycling [`list`](crate::list). A plain
2116    /// [`id`](Self::id) is assigned once at build, but a recycled cell rebinds to different
2117    /// items over its life (and drag-to-reorder rebinds eagerly), so a static item-derived id
2118    /// keeps naming the first-bound item. This variant re-registers whenever the closure's
2119    /// value changes; read your `ItemSlot` inside it:
2120    /// `.id_of(move || day_core::id!(row_remove, slot.key()))`.
2121    fn id_of(self, id: impl Fn() -> day_core::ElementId + 'static) -> Decorated<Self> {
2122        Decorated::new(self).id_of(id)
2123    }
2124
2125    /// Apply a **tweak**: `f` runs once at mount, after the native widget exists, with the
2126    /// realized node (docs/tweaks.md). Reach the typed native handle through the compiled
2127    /// backend's ext accessor (`day_toolkit_appkit::with_native`, `day_toolkit_gtk::with_native`, …), or apply
2128    /// a packaged `day-tweak-*` crate's modifier instead of calling this directly. If the native
2129    /// change affects the widget's intrinsic size, follow it with
2130    /// [`day_core::invalidate_size`]. Day may overwrite *managed* properties (title, value,
2131    /// enabled, frame, a11y) on its next patch; unmanaged properties are stable.
2132    ///
2133    /// Order it after any modifier that can rebuild the backing widget; today that is
2134    /// [`selectable`](Decorate::selectable), which on UIKit realizes the label as a different
2135    /// native class. Chained before it, the tweak runs against the widget the rebuild discards
2136    /// (Day warns at runtime); chained after, it sees the widget that ships.
2137    fn tweak(self, f: impl FnOnce(day_core::RNode) + 'static) -> Decorated<Self> {
2138        Decorated::new(self).tweak(f)
2139    }
2140
2141    /// Make this piece's text **user-selectable**, so the reader can select and copy it
2142    /// (docs/text.md). Most useful on a [`label`](crate::label): text is not selectable by default
2143    /// on any backend, matching each platform's native behavior.
2144    ///
2145    /// Every backend honors it on a label: most flip the native widget's selection affordance
2146    /// (AppKit, GTK, Qt, XAML, HarmonyOS, Android, web); UIKit, whose `UILabel` has none,
2147    /// rebuilds the label as a read-only `UITextView` behind the same handle. On other widgets
2148    /// it is best-effort: a backing with no selection affordance leaves the text unselectable
2149    /// rather than erroring, and a container cascades only where the platform's affordance does
2150    /// (the web), so prefer the label itself. Selection visuals and the copy shortcut are the
2151    /// platform's own. Unmanaged: set once at mount, and it survives Day's text updates.
2152    fn selectable(self) -> Decorated<Self> {
2153        Decorated::new(self).selectable()
2154    }
2155
2156    /// Shape the pointer while it is over this piece and its descendants (docs/cursor.md): a
2157    /// [`Cursor`] constant, a `Signal<Cursor>`, or a closure, so a canvas tool or a busy state
2158    /// moves the shape without rebuilding the piece. The nearest ancestor's cursor wins, and
2159    /// `Cursor::Default` releases the piece back to the platform. `capability(Cap::Cursor)`
2160    /// says whether this toolkit draws the requested shapes, a nearest neighbor, or nothing;
2161    /// a touch-only host never shows one, which is correct rather than a failure.
2162    fn cursor<M>(self, cursor: impl IntoReactive<Cursor, M>) -> Decorated<Self> {
2163        Decorated::new(self).cursor(cursor)
2164    }
2165
2166    /// Lay this piece and everything inside it out in one reading direction, whatever the
2167    /// app's is (docs/localization.md "Direction of a subtree"): `LayoutDirection::Ltr` for a
2168    /// phone number, a code sample or a media transport inside a right-to-left app,
2169    /// `LayoutDirection::Rtl` for a preview of Arabic content inside a left-to-right one.
2170    ///
2171    /// Day mirrors placement itself: inside the subtree leading means the direction's start
2172    /// edge, so rows run the other way, leading and trailing insets swap sides and
2173    /// alignments flip. Each native widget in the subtree is given the direction too, so text
2174    /// takes that base writing direction and controls draw their own insides to match. The
2175    /// piece keeps its place in its parent, which follows the parent's direction. A nested
2176    /// `.layout_direction` overrides an outer one. A signal or closure re-lays the subtree out
2177    /// when it changes.
2178    ///
2179    /// A canvas draws in its own coordinates and is not mirrored; `day::is_rtl()` answers for
2180    /// the app, not for a subtree.
2181    fn layout_direction<M>(
2182        self,
2183        direction: impl IntoReactive<day_spec::LayoutDirection, M>,
2184    ) -> Decorated<Self> {
2185        Decorated::new(self).layout_direction(direction)
2186    }
2187
2188    /// Let the user move the window by dragging this piece, as a title bar does
2189    /// (docs/window-chrome.md): what a custom title bar in a [`WindowChrome::Overlay`] or
2190    /// [`WindowChrome::Frameless`] window needs. The piece's own background starts the drag,
2191    /// with the platform's snapping and tiling; buttons and fields inside it keep their clicks;
2192    /// a double click does what the user's title-bar setting says (zoom, minimize, nothing).
2193    /// `capability(Cap::DragRegion)`; on a phone the piece is an ordinary view.
2194    ///
2195    /// [`WindowChrome::Overlay`]: day_spec::WindowChrome::Overlay
2196    /// [`WindowChrome::Frameless`]: day_spec::WindowChrome::Frameless
2197    fn window_drag_region(self) -> Decorated<Self> {
2198        Decorated::new(self).window_drag_region()
2199    }
2200
2201    /// Capture a [`NativeRef`] to this piece's realized node for later imperative access
2202    /// (docs/tweaks.md). The ref clears automatically when the piece's scope is disposed.
2203    fn native_ref(self, r: &NativeRef) -> Decorated<Self> {
2204        Decorated::new(self).native_ref(r)
2205    }
2206
2207    /// Space between the piece and its frame: points on all four sides, a
2208    /// [`Space`](crate::Space) step, an [`Insets`], or a signal or closure of any of them. A
2209    /// reactive inset re-pads in place, so `.padding(move || day::safe_area())` follows a
2210    /// rotation or a title bar that grows (docs/window-chrome.md "Safe area").
2211    fn padding<M>(self, insets: impl IntoReactive<Insets, M>) -> Decorated<Self> {
2212        Decorated::new(self).padding(insets)
2213    }
2214
2215    /// Cap this piece's width at `max` points: the child is never PROPOSED more, so text
2216    /// wraps inside the cap (chat bubbles, readable columns) while narrower content hugs.
2217    /// Takes points, a [`Space`](crate::Space) step, a signal or a closure; a change re-lays
2218    /// the piece out without rebuilding it.
2219    fn max_width<M>(self, max: impl IntoReactive<f64, M>) -> Decorated<Self> {
2220        Decorated::new(self).max_width(max)
2221    }
2222    /// Cap this piece's height at `max` points, the vertical twin of [`Decorate::max_width`]: a
2223    /// scroll or another piece that takes the height it is offered stops at `max`, and still
2224    /// gets less where its parent has less to give. Reactive like [`Decorate::max_width`].
2225    fn max_height<M>(self, max: impl IntoReactive<f64, M>) -> Decorated<Self> {
2226        Decorated::new(self).max_height(max)
2227    }
2228    /// Never narrower than `min` points: a stretching control keeps a usable width, and a row
2229    /// that cannot give it that overflows, so a `labeled` row stacks the control under its
2230    /// label rather than squeezing it (docs/forms.md). Reactive like [`Decorate::max_width`].
2231    fn min_width<M>(self, min: impl IntoReactive<f64, M>) -> Decorated<Self> {
2232        Decorated::new(self).min_width(min)
2233    }
2234
2235    /// Keep at least `min` points of height, expanding for taller content. Reactive like
2236    /// [`Decorate::max_width`].
2237    fn min_height<M>(self, min: impl IntoReactive<f64, M>) -> Decorated<Self> {
2238        Decorated::new(self).min_height(min)
2239    }
2240
2241    /// Reserve at least the space `sample` needs, so this piece's size stops changing with its
2242    /// content.
2243    ///
2244    /// For a numeric readout beside a slider: `label(move || value()).reserving("100")` keeps the
2245    /// row still while the number changes, because the reservation is a real measurement of
2246    /// `"100"` in this piece's own font: it scales with the platform's accessibility text size
2247    /// instead of being a point value that clips when someone turns text up.
2248    ///
2249    /// Pass the widest value the field can show (`"100"`, `"-99.9"`, `"88:88"`). Pair it with
2250    /// tabular numbers so the digits themselves stop shifting inside the reservation.
2251    /// Localized text, signals and closures update the reservation without rebuilding the label.
2252    /// Single-child wrappers preserve the label's font; other pieces use the default Body font.
2253    /// The sample is placed at zero size and hidden from assistive technology.
2254    fn reserving<M>(self, sample: impl IntoText<M>) -> Decorated<Self> {
2255        Decorated::new(self).reserving(sample)
2256    }
2257
2258    fn frame<Mw, Mh>(
2259        self,
2260        width: impl IntoReactive<f64, Mw>,
2261        height: impl IntoReactive<f64, Mh>,
2262    ) -> Decorated<Self> {
2263        Decorated::new(self).frame(width, height)
2264    }
2265
2266    /// Fix this piece's width to `width` points while its height stays flexible (hugging its
2267    /// content or filling on the cross axis). The single-axis complement to [`Self::frame`], e.g.
2268    /// a fixed-width sidebar pane in a `row` whose height fills the window.
2269    fn width<M>(self, width: impl IntoReactive<f64, M>) -> Decorated<Self> {
2270        Decorated::new(self).width(width)
2271    }
2272
2273    /// Fix this piece's height to `height` points while its width stays flexible. The single-axis
2274    /// complement to [`Self::frame`], e.g. a fixed-height header/toolbar bar that fills its width.
2275    fn height<M>(self, height: impl IntoReactive<f64, M>) -> Decorated<Self> {
2276        Decorated::new(self).height(height)
2277    }
2278
2279    fn a11y(self, f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> Decorated<Self> {
2280        Decorated::new(self).a11y(f)
2281    }
2282
2283    /// Fire when this piece is tapped (bounding-box; shapes override with path-precise testing).
2284    ///
2285    /// Do not use this to activate a native button; use [`crate::Button::action`] instead.
2286    /// A separate gesture recognizer can delay pressed feedback and bypass native keyboard,
2287    /// accessibility, and disabled behavior. Day warns when it attaches a tap to a button.
2288    fn on_tap(self, f: impl Fn() + 'static) -> Decorated<Self> {
2289        Decorated::new(self).on_tap(f)
2290    }
2291
2292    /// [`on_tap`](Self::on_tap), told where: the point in the piece's own coordinate space,
2293    /// origin at its top-leading corner.
2294    ///
2295    /// What a drawn control needs and a native one does not: a canvas showing a color wheel, a
2296    /// map, or a waveform has to turn "the user pressed here" into a value, and only the piece
2297    /// knows how. Pair it with [`on_drag`](Self::on_drag), which already reports a location, to
2298    /// track a press that turns into a drag; the two are idempotent together, so a backend that
2299    /// reports a tap as a zero-length drag costs nothing.
2300    ///
2301    /// `Event::Tap` has always carried the point; this is the decorator that stops throwing it
2302    /// away.
2303    ///
2304    /// For native buttons use [`crate::Button::action`], not this gesture decorator.
2305    fn on_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Decorated<Self> {
2306        Decorated::new(self).on_tap_at(f)
2307    }
2308
2309    /// Bind this control's keyboard focus to a signal (docs/focus.md), two-way like every other
2310    /// binding: native focus changes write the signal; writing the signal moves focus. Takes a
2311    /// `Signal<bool>` for one control, or `(Signal<Option<K>>, K::Variant)` binding one control
2312    /// of a group; writing `false`/`None` resigns focus (dismissing the soft keyboard on
2313    /// mobile). Focus applies asynchronously: a write is a request, resolved on the next turn,
2314    /// and the signal always ends up reflecting what the platform actually did.
2315    fn focused<M>(self, binding: impl IntoFocusBinding<M>) -> Decorated<Self> {
2316        Decorated::new(self).focused(binding)
2317    }
2318
2319    /// Handle the non-text keys (the arrows) that reach this piece while it has focus
2320    /// (docs/menus.md). Keys follow focus, so pair it with [`Decorate::focused`] or with a
2321    /// piece the user can click into: a canvas takes focus on a press, and only the focused
2322    /// piece hears the keys, so a nudge handler can never fire while a text field, a list or a
2323    /// sidebar is the one being typed into.
2324    ///
2325    /// Which pieces can hold focus is the platform's to answer (docs/focus.md): a `canvas`
2326    /// is focusable on the backends that draw one from a real view (appkit, web-dom today).
2327    ///
2328    /// The handler hears each press and each repeat while the key is held
2329    /// ([`KeyEvent::is_repeat`](day_spec::KeyEvent::is_repeat) tells them apart, so an action
2330    /// that should fire once per press skips the repeats). The key is a typed
2331    /// [`Key`](day_spec::Key):
2332    ///
2333    /// ```ignore
2334    /// canvas(draw).focusable().on_key(move |k| match k.key {
2335    ///     Key::ArrowLeft => nudge(-1.0),
2336    ///     Key::ArrowRight => nudge(1.0),
2337    ///     Key::Character(' ') if !k.is_repeat() => fire(),
2338    ///     _ => {}
2339    /// })
2340    /// ```
2341    fn on_key(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Decorated<Self> {
2342        Decorated::new(self).on_key(f)
2343    }
2344
2345    /// Handle the release of a key this piece heard go down (docs/menus.md "Keys"): the other
2346    /// half of held-key movement, where [`Decorate::on_key`] starts moving and this stops.
2347    /// Delivered where `Cap::KeyPhases` is supported; elsewhere it never fires, so step per
2348    /// press there instead.
2349    fn on_key_up(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Decorated<Self> {
2350        Decorated::new(self).on_key_up(f)
2351    }
2352
2353    /// Declare toolbar items on the chrome this piece sits under (docs/toolbars.md).
2354    ///
2355    /// Takes one item, a list of them, or a closure that derives the list and re-runs whenever
2356    /// its reactive reads change:
2357    ///
2358    /// ```ignore
2359    /// page.toolbar(toolbar_button(day_core::id!(share), tr("share")).icon(Symbol::Share).action(share))
2360    /// page.toolbar([reply, forward, archive])
2361    /// page.toolbar(move || vec![toolbar_button(day_core::id!(undo), tr("undo")).enabled(can_undo)])
2362    /// ```
2363    ///
2364    /// Which chrome carries them follows from where this piece is built (a destination page's
2365    /// own bar, a content-list pane's, or the window's if it is under no page at all), and the
2366    /// items are withdrawn when this piece is disposed. Where on that chrome they sit is
2367    /// [`ToolbarEntry::placement`](crate::ToolbarEntry::placement).
2368    fn toolbar<M>(self, content: impl crate::ToolbarContent<M>) -> Decorated<Self> {
2369        Decorated::new(self).toolbar(content)
2370    }
2371
2372    /// A search field for this navigation page (docs/search.md, "Page search"), drawn where the
2373    /// platform puts a page's search: the window toolbar on a desktop, the page's navigation bar
2374    /// on iOS (a `UISearchController`), its app bar on Android. It shows while this page does, and
2375    /// its text is the app's `query` both ways. For a search the server runs, act on
2376    /// [`crate::Search::on_submit`]; for a local filter, read the query. Declare it on a
2377    /// `nav_stack` destination, as `.toolbar(…)` is declared; a whole navigation surface takes
2378    /// [`crate::Nav::searchable`] instead.
2379    fn searchable(self, search: crate::Search) -> Decorated<Self> {
2380        Decorated::new(self).searchable(search)
2381    }
2382
2383    /// Opt this piece into the platform's focus system (docs/focus.md): the canvas contract
2384    /// for anything composed: it joins the key loop, takes focus on a press, reports through
2385    /// `.focused(…)`, and hears the arrows through `.on_key(…)` while focused. A composed
2386    /// list column is the motivating case (docs/navigation.md). On a backend without the
2387    /// `set_focusable` duty the piece renders normally and never takes focus.
2388    fn focusable(self) -> Decorated<Self> {
2389        Decorated::new(self).focusable()
2390    }
2391
2392    /// Take the whole keyboard while this piece is focused (docs/menus.md "The full route"):
2393    /// every key the platform delivers reaches [`Decorate::on_key`], not only the arrows and
2394    /// digits. A key that types nothing is named by its web name, a key that types by its
2395    /// unmodified character, and what it typed rides in [`day_spec::KeyEvent::text`]: the
2396    /// character, or the whole string an input method committed (a dead-key accent, a
2397    /// Japanese phrase), delivered once, after the composition. Control chords arrive with
2398    /// [`day_spec::Modifiers::CONTROL`] set and no text; only the platform's own command
2399    /// chords (⌘ on Apple platforms) stay with the menu. On a phone, focusing the piece
2400    /// raises the soft keyboard, the way focusing a text field does, and what it types
2401    /// arrives the same way. For a terminal, a code editor or a game that reads letters, on
2402    /// a `canvas`:
2403    ///
2404    /// ```ignore
2405    /// canvas(draw).keyboard().on_key(move |k| match k.typed() {
2406    ///     Some(text) => term.type_text(text),
2407    ///     None => term.press(&k.key, k.modifiers),
2408    /// })
2409    /// ```
2410    ///
2411    /// Pair it with [`Decorate::on_key`]: it declares the route, the handler hears it, and a
2412    /// declaration with no handler claims nothing. The route is the canvas's (the one piece
2413    /// with no native control under it); a `.focusable()` container keeps the short route.
2414    /// A piece that takes the whole keyboard also takes the Tab key, so it leaves the
2415    /// platform's focus walking: a press elsewhere, or writing `.focused(false)`, gives the
2416    /// keyboard back.
2417    fn keyboard(self) -> Decorated<Self> {
2418        Decorated::new(self).keyboard()
2419    }
2420
2421    /// Offer data when a drag starts on this piece (docs/drag-and-drop.md "Offering data"):
2422    /// `source` gets the press point in the piece's own coordinates and answers what to carry,
2423    /// or `None` to let the press be something else (a tap, a scroll).
2424    fn drag_source(
2425        self,
2426        source: impl Fn(day_spec::Point) -> Option<day_spec::transfer::Offer> + 'static,
2427    ) -> Decorated<Self> {
2428        Decorated::new(self).drag_source(source)
2429    }
2430    /// Accept drops through the platform's native drag session (docs/drag-and-drop.md
2431    /// "Accepting drops"). The target is one value: its types, an optional acceptance policy,
2432    /// and what runs as a drag enters, leaves and drops.
2433    ///
2434    /// ```ignore
2435    /// column(rows).drop_target(
2436    ///     DropTarget::new(["text/plain"])
2437    ///         .on_enter(move |_| hovering.set(true))
2438    ///         .on_leave(move || hovering.set(false))
2439    ///         .on_drop(move |drop| take(drop.items)),
2440    /// )
2441    /// ```
2442    fn drop_target(self, target: day_spec::transfer::Target) -> Decorated<Self> {
2443        Decorated::new(self).drop_target(target)
2444    }
2445
2446    /// Accept files dropped on this piece: `f` receives their local paths. The short form of
2447    /// [`Decorate::drop_target`] for the common case; use the full target for a hover
2448    /// highlight or another data type.
2449    fn on_files_dropped(self, f: impl Fn(Vec<std::path::PathBuf>) + 'static) -> Decorated<Self> {
2450        Decorated::new(self).on_files_dropped(f)
2451    }
2452    /// A context menu (docs/menus.md): shown on secondary-click / long-press, built from the
2453    /// same `menu_item`/`sub_menu` entries as everywhere else. Takes a fixed list, or a closure
2454    /// built when the menu is summoned ("Dynamic context menus"): with no argument, or with the
2455    /// summon point in this piece's own coordinates, so a canvas can select what is under the
2456    /// pointer and offer commands for that selection. An empty result shows nothing.
2457    ///
2458    /// ```ignore
2459    /// label(t).context_menu([menu_item(res::str::copy()).action(copy)])
2460    /// canvas(draw).context_menu(move |at: Point| commands_for(hit_test(at)))
2461    /// ```
2462    fn context_menu<M>(self, menu: impl ContextMenuContent<M>) -> Decorated<Self> {
2463        Decorated::new(self).context_menu(menu)
2464    }
2465
2466    /// Fire on each phase of a press-drag over this piece (docs/gestures.md "Gestures"). The
2467    /// [`Drag`] carries where the pointer is, how far it has come, and how fast it is moving;
2468    /// at `Ended` the velocity is the release velocity. Once the drag has begun it belongs to
2469    /// this piece: an enclosing scroll view does not take it over.
2470    fn on_drag(self, f: impl Fn(Drag) + 'static) -> Decorated<Self> {
2471        Decorated::new(self).on_drag(f)
2472    }
2473
2474    /// [`Decorate::on_drag`] for a drag that follows one axis, inside a scroll view that
2475    /// scrolls along the other: a horizontal swipe on a row of a vertical list. A pointer that
2476    /// sets off along `axis` is this piece's drag; one that sets off across it scrolls, and
2477    /// the handler hears nothing of it.
2478    ///
2479    /// ```ignore
2480    /// row(content).on_drag_along(DragAxis::Horizontal, move |d| offset.set(d.translation.x))
2481    /// ```
2482    fn on_drag_along(
2483        self,
2484        axis: day_spec::DragAxis,
2485        f: impl Fn(Drag) + 'static,
2486    ) -> Decorated<Self> {
2487        Decorated::new(self).on_drag_along(axis, f)
2488    }
2489
2490    /// Fire when a press is held still on this piece (docs/gestures.md "Long press"), with the
2491    /// press point in the piece's coordinates. It fires while the pointer is still down, and
2492    /// the release that follows is not a tap, so `.on_tap(..).on_long_press(..)` are
2493    /// alternatives. Pair it with another route to the same command (a menu, a button): a
2494    /// long press is not discoverable.
2495    fn on_long_press(self, f: impl Fn(day_spec::Point) + 'static) -> Decorated<Self> {
2496        Decorated::new(self).on_long_press(f)
2497    }
2498
2499    /// Fire on two taps in quick succession (docs/gestures.md "Double tap"). On a piece that
2500    /// also has [`Decorate::on_tap`], a single tap waits out the double-tap interval and the
2501    /// two never both fire; with a double tap alone nothing waits.
2502    fn on_double_tap(self, f: impl Fn() + 'static) -> Decorated<Self> {
2503        Decorated::new(self).on_double_tap(f)
2504    }
2505
2506    /// [`on_double_tap`](Self::on_double_tap), told where: the second tap's point in the
2507    /// piece's own coordinate space, origin at its top-leading corner. What a map or an image
2508    /// viewer zooms around.
2509    fn on_double_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Decorated<Self> {
2510        Decorated::new(self).on_double_tap_at(f)
2511    }
2512
2513    /// Follow the press on this piece: `true` at the pointer-down itself, `false` when the
2514    /// press ends (the release, the pointer leaving, or the platform taking the gesture away).
2515    /// Every `true` is followed by one `false`, so a handler that writes a `Signal<bool>` is a
2516    /// one-liner, and it never delays or cancels a tap or a drag on the same piece
2517    /// (docs/gestures.md "Press"). For styling, [`Decorate::interaction`] already tracks it.
2518    fn on_pressed(self, f: impl Fn(bool) + 'static) -> Decorated<Self> {
2519        Decorated::new(self).on_pressed(f)
2520    }
2521
2522    /// Receive the raw contacts on this piece (docs/gestures.md "Touches"): every finger that is
2523    /// down, each with a stable id, plus the ones that lifted in this event. For a drawing
2524    /// surface, a multi-finger instrument or a recognizer of your own. Where the platform
2525    /// reports one pointer (`day::gesture_support(GestureKind::Touches)` is `Emulated`), the
2526    /// list holds that one contact with id 0.
2527    fn on_touches(self, f: impl Fn(&[day_spec::Touch]) + 'static) -> Decorated<Self> {
2528        Decorated::new(self).on_touches(f)
2529    }
2530
2531    /// Grow the area in which this piece takes pointer input by `slop` points on each edge,
2532    /// without moving or resizing it (docs/gestures.md "Hit slop"): a 12-point dot with
2533    /// `.hit_slop(16.0)` is a 44-point target. Layout and drawing do not change. Where
2534    /// `Cap::HitSlop` is unsupported the piece keeps its own bounds.
2535    fn hit_slop(self, slop: impl Into<Insets>) -> Decorated<Self> {
2536        Decorated::new(self).hit_slop(slop)
2537    }
2538
2539    /// Track this piece's hover, press and focus in `state` (docs/gestures.md "State styling"),
2540    /// for reactive modifiers to read. See [`InteractionState`].
2541    fn interaction(self, state: InteractionState) -> Decorated<Self> {
2542        Decorated::new(self).interaction(state)
2543    }
2544
2545    /// Enable or disable this piece and everything in it (docs/forms.md "Disabling a group").
2546    /// While disabled, the controls inside are disabled the platform's way (dimmed, out of
2547    /// the focus order, reported disabled to assistive technology) and no tap, drag, hover,
2548    /// press or key reaches a handler in the subtree. Takes a constant, a signal or a closure:
2549    ///
2550    /// ```ignore
2551    /// form((name_field, email_field, send_button)).enabled(move || !sending.get())
2552    /// ```
2553    ///
2554    /// A control's own `.enabled(..)` builder still applies inside: a control is enabled when
2555    /// it and every group around it are.
2556    fn enabled<M>(self, enabled: impl IntoReactive<bool, M>) -> Decorated<Self> {
2557        Decorated::new(self).enabled(enabled)
2558    }
2559
2560    /// Fire on each phase of a pinch/magnify over this piece (docs/canvas.md "Zoom and
2561    /// pan"). Only backends with a native recognizer wired emit it; pair a zoom with
2562    /// visible controls.
2563    fn on_pinch(self, f: impl Fn(Pinch) + 'static) -> Decorated<Self> {
2564        Decorated::new(self).on_pinch(f)
2565    }
2566
2567    /// Fire on each phase of a two-finger rotation over this piece (docs/canvas.md "Zoom and
2568    /// pan"). [`Rotate::rotation`] is an [`Angle`], cumulative within a gesture, positive
2569    /// clockwise; a trackpad tick arrives as a lone `Changed`. Pair it with a visible way back
2570    /// to north.
2571    fn on_rotate(self, f: impl Fn(Rotate) + 'static) -> Decorated<Self> {
2572        Decorated::new(self).on_rotate(f)
2573    }
2574
2575    /// Fire on each viewport-pan event over this piece (docs/canvas.md "Zoom and pan"):
2576    /// trackpad two-finger scroll, two-finger touch pan. `delta` is incremental; apply it
2577    /// as it arrives.
2578    fn on_pan(self, f: impl Fn(Pan) + 'static) -> Decorated<Self> {
2579        Decorated::new(self).on_pan(f)
2580    }
2581
2582    /// The pointer moving over this piece: `Some(point)` in its own coordinates while inside,
2583    /// `None` when it leaves (docs/canvas.md "Interaction"). Pointer-only; wire `on_tap_at`
2584    /// alongside it so a touch-only device can reach the same thing.
2585    fn on_hover(self, f: impl Fn(Option<day_spec::Point>) + 'static) -> Decorated<Self> {
2586        Decorated::new(self).on_hover(f)
2587    }
2588
2589    /// The platform's card around this piece: the grouped-content surface with
2590    /// [`Radius::M`](crate::Radius::M) corners and a `Space::M` inset. Drawn by the toolkit, so
2591    /// it follows the appearance and never steals hit testing from the content.
2592    fn card(self) -> Decorated<Self> {
2593        Decorated::new(self).card()
2594    }
2595
2596    /// Fill the piece's bounds with a [`Paint`] painted behind it: a message-bubble / card /
2597    /// badge surface. Takes a [`Color`](day_spec::Color), a
2598    /// [`SystemColor`](day_spec::SystemColor), an [`Ink`] (`Ink::adaptive(light, dark)`), a
2599    /// gradient, or a signal or closure of any of them. An ink follows the appearance without a
2600    /// rebuild or a closure; a reactive source repaints when it changes. Wraps the piece in a
2601    /// native container that carries the fill, so it composes with [`Self::corner_radius`] for
2602    /// a rounded colored surface and with [`Self::padding`] for interior inset.
2603    fn background<M>(self, fill: impl IntoReactive<Paint, M>) -> Decorated<Self> {
2604        Decorated::new(self).background(fill)
2605    }
2606
2607    /// Round the piece's corners, clipping its background and content to the rounded
2608    /// rectangle. Takes points, a [`Radius`](crate::Radius) step, a frame-relative
2609    /// [`Corner`](crate::Corner) (`Corner::CAPSULE` for round ends), or a signal or closure
2610    /// of any of them; a change patches the view in place. Compose after [`Self::background`]
2611    /// for a rounded colored surface, or use alone to round a clipped child (an avatar image).
2612    fn corner_radius<M>(self, radius: impl IntoReactive<crate::Corner, M>) -> Decorated<Self> {
2613        Decorated::new(self).corner_radius(radius)
2614    }
2615
2616    /// Put a styled native [`Surface`] behind the piece: fill (any [`Paint`]), rounded corners
2617    /// (all or some), a border and a shadow, all on one native view so the border follows the
2618    /// corners and the shadow takes their shape (docs/surfaces.md). Takes a surface, or a
2619    /// signal or closure of one; a change patches the view in place.
2620    fn surface<M>(self, surface: impl IntoReactive<Surface, M>) -> Decorated<Self> {
2621        Decorated::new(self).surface(surface)
2622    }
2623
2624    /// A square line of `color`, `width` points wide, around the piece's frame, inside it and
2625    /// over its content. Either argument may be a signal or a closure. For a border that
2626    /// follows rounded corners, use [`Self::surface`].
2627    fn border<Mc, Mw>(
2628        self,
2629        color: impl IntoReactive<Ink, Mc>,
2630        width: impl IntoReactive<f64, Mw>,
2631    ) -> Decorated<Self> {
2632        Decorated::new(self).border(color, width)
2633    }
2634
2635    /// A shadow of the piece's frame, drawn outside it by the toolkit. Takes a
2636    /// [`Shadow`](day_spec::Shadow), or a signal or closure of one. For a rounded shadow, or
2637    /// one under a filled surface, use [`Self::surface`].
2638    fn shadow<M>(self, shadow: impl IntoReactive<day_spec::Shadow, M>) -> Decorated<Self> {
2639        Decorated::new(self).shadow(shadow)
2640    }
2641
2642    /// Animate/set the piece's opacity (`0.0` transparent … `1.0` opaque). Wrapped in a native
2643    /// layer so it composes with `.background`; the change animates when made inside
2644    /// [`with_animation`] or under a `.animation` ancestor (§8.4).
2645    fn opacity<M>(self, opacity: impl IntoReactive<f64, M>) -> Decorated<Self> {
2646        Decorated::new(self).opacity(opacity)
2647    }
2648
2649    /// Apply an animatable [`Transform`] (translate/scale/rotate about the center): the cheap
2650    /// movement/scaling channel that never triggers relayout (§8.4). [`Self::translation`],
2651    /// [`Self::scale`] and [`Self::rotation`] are its one-property forms.
2652    fn transform<M>(self, t: impl IntoReactive<Transform, M>) -> Decorated<Self> {
2653        Decorated::new(self).transform(t)
2654    }
2655
2656    /// Uniformly scale the piece by `factor` about its center (animatable). Convenience over
2657    /// [`Self::transform`].
2658    fn scale<M>(self, factor: impl IntoReactive<f64, M>) -> Decorated<Self> {
2659        Decorated::new(self).scale(factor)
2660    }
2661
2662    /// Rotate the piece by `angle` clockwise about its center (animatable):
2663    /// `.rotation(Angle::deg(15.0))`.
2664    fn rotation<M>(self, angle: impl IntoReactive<Angle, M>) -> Decorated<Self> {
2665        Decorated::new(self).rotation(angle)
2666    }
2667
2668    /// Translate the piece by (`x`, `y`) points without relayout (animatable). Layout still
2669    /// places the piece where it was; only what is drawn moves.
2670    fn translation<Mx, My>(
2671        self,
2672        x: impl IntoReactive<f64, Mx>,
2673        y: impl IntoReactive<f64, My>,
2674    ) -> Decorated<Self> {
2675        Decorated::new(self).translation(x, y)
2676    }
2677
2678    /// Attach an implicit animation (§8.4): changes to this piece's (and its descendants')
2679    /// animatable properties animate with `anim` even outside a [`with_animation`]. SwiftUI's
2680    /// `.animation`. The ambient `with_animation` takes precedence when both apply.
2681    fn animation(self, anim: AnimSpec) -> Decorated<Self> {
2682        Decorated::new(self).animation(anim)
2683    }
2684
2685    /// Apply a [`Modifier`] (or, via the blanket impl, a plain `FnOnce(AnyPiece) -> AnyPiece`
2686    /// closure) to this piece. Pure composition: `content.modifier(m) == m.apply(content.any())`.
2687    ///
2688    /// The one modifier that erases: `Modifier` is defined over [`AnyPiece`], so the piece's own
2689    /// type cannot survive it.
2690    fn modifier(self, m: impl Modifier) -> AnyPiece {
2691        m.apply(self.any())
2692    }
2693
2694    /// Draw `over` on top of this piece, centered, without affecting layout size: a badge /
2695    /// annotation overlay. `self` is the sizing content (bottom of the z-order); `over` is proposed
2696    /// `self`'s size and drawn on top. For an explicit alignment use [`Self::overlay_aligned`]; for
2697    /// a stack that sizes to the union of its children use [`zstack`].
2698    fn overlay(self, over: impl Piece) -> Decorated<Self> {
2699        Decorated::new(self).overlay(over)
2700    }
2701
2702    /// [`Self::overlay`] with an explicit [`Alignment`] for the annotation (e.g. a corner badge with
2703    /// [`Alignment::TopTrailing`]).
2704    fn overlay_aligned(self, align: Alignment, over: impl Piece) -> Decorated<Self> {
2705        Decorated::new(self).overlay_aligned(align, over)
2706    }
2707
2708    /// Constrain this piece to a `width / height` ratio: the largest box of that shape which
2709    /// fits whatever the parent offers (SwiftUI's `.aspectRatio(_:contentMode: .fit)`).
2710    ///
2711    /// Pair it with [`Self::grow`] and [`Dimension::Width`] to take the available width and
2712    /// derive the height from it: a `canvas` whose drawing keeps its proportions as the window
2713    /// resizes, say. `image` has carried this since it shipped; this is the same layout, for any
2714    /// piece.
2715    ///
2716    /// A ratio that is not finite and positive describes no box, so it is ignored. The ratio
2717    /// may be a signal or a closure; a change re-lays the piece out.
2718    fn aspect_ratio<M>(self, ratio: impl IntoReactive<f64, M>) -> Decorated<Self> {
2719        Decorated::new(self).aspect_ratio(ratio)
2720    }
2721
2722    /// Position this piece within its assigned space without stretching its content.
2723    ///
2724    /// Alignment alone hugs the content. Apply growth or a frame afterward to provide room:
2725    /// `piece.aligned(Alignment::Center).grow(Dimension::Width)` centers a naturally sized
2726    /// piece across the available width. Reversing that order centers already-expanded content.
2727    /// Leading and trailing follow the locale's layout direction. This adds no native view,
2728    /// accessibility role, or focus stop; text alignment remains a separate piece setting.
2729    fn aligned(self, alignment: Alignment) -> Decorated<Self> {
2730        Decorated::new(self).aligned(alignment)
2731    }
2732
2733    /// Expand to fill the space offered in the selected dimensions.
2734    ///
2735    /// Other dimensions hug the content. An unbounded proposal (such as a scroll view's
2736    /// scrolling axis) keeps the content's measured size. This layout-only wrapper carries
2737    /// grow [`Flex`] so its parent can allocate extra space; it adds no native view.
2738    ///
2739    /// Siblings that grow along the same line share the spare space equally. Give one a
2740    /// larger share with a weight: `.grow(Dimension::Width.weight(2.0))` beside a plain
2741    /// `.grow(Dimension::Width)` takes two thirds. In a wrapping row
2742    /// (`row(..).fit(RowFit::Wrap { .. })`) a line breaks on the children's natural widths
2743    /// and the growing ones then share what the line has left, so
2744    /// `.min_width(50.0).grow(Dimension::Width)` reads "at least 50 points, then share the
2745    /// line".
2746    fn grow(self, grow: impl Into<Grow>) -> Decorated<Self> {
2747        Decorated::new(self).grow(grow)
2748    }
2749
2750    #[deprecated(note = "use .grow(Dimension::Width)")]
2751    fn grow_w(self) -> Decorated<Self> {
2752        Decorated::new(self).grow(Dimension::Width)
2753    }
2754
2755    #[deprecated(note = "use .grow(Dimension::Height)")]
2756    fn grow_h(self) -> Decorated<Self> {
2757        Decorated::new(self).grow(Dimension::Height)
2758    }
2759
2760    /// Span `n` columns (n ≥ 1) of the enclosing [`grid`] (docs/grid.md). Grid modifiers apply
2761    /// to the outermost layout node after wrapping modifiers, regardless of their chain position.
2762    fn grid_span(self, n: usize) -> Decorated<Self> {
2763        Decorated::new(self).grid_span(n)
2764    }
2765
2766    /// Override this cell's alignment within its cell rect of the enclosing [`grid`]
2767    /// (docs/grid.md). Like [`Decorated::grid_span`], this applies outside wrapping modifiers
2768    /// regardless of its position in the chain.
2769    fn grid_align(self, a: Alignment) -> Decorated<Self> {
2770        Decorated::new(self).grid_align(a)
2771    }
2772
2773    /// While this subtree is mounted, ask the OS to require a second swipe for its edge
2774    /// gestures on `edges` (docs/cover.md), the SwiftUI `defersSystemGestures(on:)`
2775    /// analogue. Put it on a game or drawing surface whose touches run to the screen edge,
2776    /// so a swipe up from the bottom doesn't leave the app. iOS defers the chosen edges'
2777    /// system gestures; Android enters swipe-to-reveal immersive mode while any subtree
2778    /// requests deferral; desktop backends no-op.
2779    fn defers_system_gestures(self, edges: day_spec::Edges) -> Decorated<Self> {
2780        Decorated::new(self).defers_system_gestures(edges)
2781    }
2782
2783    /// While this subtree is mounted and `hidden` is true, hide the system status bar, the
2784    /// SwiftUI `statusBarHidden(_:)` analogue (docs/cover.md). `hidden` is a constant, a
2785    /// `Signal`, or a closure, so a setting can turn it on and off in place. Put it on a page
2786    /// that wants the whole screen (a reader, a game, a photo viewer); the bar returns when
2787    /// the page unmounts. Any mounted request that answers true hides the bar. iOS, Android and
2788    /// HarmonyOS hide it (`Cap::StatusBarHidden`); desktop and web have none and ignore it.
2789    fn status_bar_hidden<M>(self, hidden: impl IntoReactive<bool, M>) -> Decorated<Self> {
2790        Decorated::new(self).status_bar_hidden(hidden)
2791    }
2792
2793    /// While this subtree is mounted, the enclosing [`cover`] (or other modal surface) must
2794    /// not be dismissed interactively, the SwiftUI `interactiveDismissDisabled()` analogue
2795    /// (docs/cover.md). System back / sheet gestures are ignored; only programmatic writes
2796    /// (an explicit close control) dismiss it.
2797    fn interactive_dismiss_disabled(self) -> Decorated<Self> {
2798        Decorated::new(self).interactive_dismiss_disabled()
2799    }
2800
2801    /// While this subtree is mounted and `enabled` holds, a back nothing else takes runs
2802    /// `handler` instead of the platform's default: Jetpack Compose's `BackHandler(enabled)`
2803    /// (docs/navigation.md "Handling the system Back"). `enabled` is a constant, a `Signal`, or
2804    /// a closure, followed as it changes.
2805    ///
2806    /// The back is Android's system back button and gesture (predictive back included),
2807    /// HarmonyOS's back gesture, [`nav_back()`](crate::nav_back), and dayscript's `nav_back`
2808    /// step in both forms. Navigation answers first: a presented [`cover`] closes and a pushed
2809    /// page pops before any handler runs, so the handler takes only the back that would have
2810    /// left the app (on a phone) or done nothing (on a desktop). Among several, the handler in
2811    /// the topmost cover wins, then the one nested most deeply in the piece tree, then the most
2812    /// recently mounted. A page's own "leave this page?" policy belongs on
2813    /// [`NavStack::on_back`] instead.
2814    ///
2815    /// Disabled (or unmounted) on Android, the system back is released again, so the
2816    /// predictive "back to home" preview shows whenever the press would leave the app.
2817    ///
2818    /// ```ignore
2819    /// // A browser: Back goes back in the page's history while the tab can.
2820    /// page_view(tab).on_system_back(move || tab.can_go_back(), move || tab.go_back())
2821    /// ```
2822    fn on_system_back<M>(
2823        self,
2824        enabled: impl IntoReactive<bool, M>,
2825        handler: impl Fn() + 'static,
2826    ) -> Decorated<Self> {
2827        Decorated::new(self).on_system_back(enabled, handler)
2828    }
2829
2830    /// Erase to a single [`AnyPiece`]: for a `Vec<AnyPiece>`, a `-> AnyPiece` signature, or any other
2831    /// place one concrete type is required. [`AnyPiece::any`] is inherent and returns `self`, so
2832    /// erasing an already-erased piece costs nothing.
2833    fn any(self) -> AnyPiece {
2834        AnyPiece::new(self)
2835    }
2836}
2837
2838impl<P: Piece> Decorate for P {}
2839
2840/// One a11y string that reads a signal or the locale, with the patch that re-sends it alone.
2841type LiveA11yString = (TextSource, fn(String) -> A11yProps);
2842
2843/// The annotations `.a11y(|a| …)` collects (docs/accessibility.md). The three strings are
2844/// [`TextSource`]s, so each takes a literal, a `String`, a `Signal<String>` or a closure: a
2845/// gauge's value follows the gauge, and a localized label follows the locale.
2846#[derive(Default)]
2847#[must_use]
2848pub struct A11yBuilder {
2849    label: Option<TextSource>,
2850    hint: Option<TextSource>,
2851    value: Option<TextSource>,
2852    /// The selected state, reactive so a tab or row follows the selection.
2853    selected: Option<Reactive<bool>>,
2854    props: A11yProps,
2855}
2856
2857impl A11yBuilder {
2858    /// What the screen reader calls the element.
2859    pub fn label<M>(mut self, s: impl IntoText<M>) -> Self {
2860        self.label = Some(s.into_text());
2861        self
2862    }
2863    /// A longer description of what the element does.
2864    pub fn hint<M>(mut self, s: impl IntoText<M>) -> Self {
2865        self.hint = Some(s.into_text());
2866        self
2867    }
2868    /// The control's current value read aloud by the screen reader (e.g. a `Meter`'s "72%").
2869    /// Reactive like the others: `.value(move || format!("{:.0}%", level.get()))` re-sends the
2870    /// value whenever `level` changes.
2871    pub fn value<M>(mut self, s: impl IntoText<M>) -> Self {
2872        self.value = Some(s.into_text());
2873        self
2874    }
2875    pub fn role(mut self, r: Role) -> Self {
2876        self.props.role = r;
2877        self
2878    }
2879    /// Whether this element is the selected one among its peers (a `Role::Tab`, a row): the
2880    /// platform's selected state, which a screen reader reads as "selected". Reactive like the
2881    /// strings: `.selected(move || current.get() == key)` re-sends it when the selection moves.
2882    pub fn selected<M>(mut self, on: impl IntoReactive<bool, M>) -> Self {
2883        self.selected = Some(on.into_reactive());
2884        self
2885    }
2886    /// Hide this element from assistive tech (still visible on screen), e.g. a redundant chrome
2887    /// element already announced by its labeled sibling.
2888    pub fn hidden(mut self) -> Self {
2889        self.props.hidden = true;
2890        self
2891    }
2892    /// Purely decorative (a background flourish): hidden from assistive tech and, for images,
2893    /// exempt from the "needs a label" lint (§13).
2894    pub fn decorative(mut self) -> Self {
2895        self.props.decorative = true;
2896        self.props.hidden = true;
2897        self
2898    }
2899
2900    /// The annotations as first applied, with every string resolved once, the sources that
2901    /// can change, each paired with the patch that re-sends it, and the selected state when it
2902    /// reads a signal.
2903    fn split(self) -> (A11yProps, Vec<LiveA11yString>, Option<Reactive<bool>>) {
2904        let mut props = self.props;
2905        let mut live = Vec::new();
2906        let selected = match self.selected {
2907            Some(Reactive::Const(on)) => {
2908                props.selected = Some(on);
2909                None
2910            }
2911            Some(dynamic @ Reactive::Dyn(_)) => {
2912                props.selected = Some(day_reactive::untrack(|| dynamic.get()));
2913                Some(dynamic)
2914            }
2915            None => None,
2916        };
2917        let mut take =
2918            |src: Option<TextSource>, slot: &mut Option<String>, patch: fn(String) -> A11yProps| {
2919                if let Some(src) = src {
2920                    *slot = Some(src.initial());
2921                    if matches!(src, TextSource::Dyn(_)) {
2922                        live.push((src, patch));
2923                    }
2924                }
2925            };
2926        take(self.label, &mut props.label, |label| A11yProps {
2927            label: Some(label),
2928            ..Default::default()
2929        });
2930        take(self.hint, &mut props.hint, |hint| A11yProps {
2931            hint: Some(hint),
2932            ..Default::default()
2933        });
2934        take(self.value, &mut props.value, |value| A11yProps {
2935            value: Some(value),
2936            ..Default::default()
2937        });
2938        (props, live, selected)
2939    }
2940}
2941
2942// Native callbacks arrive outside the event dispatcher. Enter their owning scope so
2943// window ambient state resolves correctly, and reject callbacks retained after disposal.
2944fn scoped_drag_source(source: day_spec::transfer::Source) -> day_spec::transfer::Source {
2945    let scope = Scope::current();
2946    let alive = Rc::new(Cell::new(true));
2947    let cleanup = alive.clone();
2948    scope.on_cleanup(move || cleanup.set(false));
2949    Rc::new(move |point| alive.get().then(|| scope.enter(|| source(point))).flatten())
2950}
2951fn scoped_drop_target(target: day_spec::transfer::Target) -> day_spec::transfer::Target {
2952    let scope = Scope::current();
2953    let alive = Rc::new(Cell::new(true));
2954    let cleanup = alive.clone();
2955    scope.on_cleanup(move || cleanup.set(false));
2956    target.guarded(Rc::new(move |run: &mut dyn FnMut()| {
2957        if alive.get() {
2958            scope.enter(run);
2959        }
2960    }))
2961}
2962
2963// ---------------------------------------------------------------------------
2964// Conformance cases (docs/testing.md)
2965// ---------------------------------------------------------------------------
2966
2967/// The modifiers' `#[day::test]` cases, next to the `Decorate` methods they prove.
2968#[cfg(feature = "conformance")]
2969pub(crate) mod conformance {
2970    use day_core::AnyPiece;
2971    use day_core::conformance::{Case, Drive, FrameExpect, NativeExpect};
2972    use day_reactive::{Signal, untrack};
2973    use day_spec::{Cap, Color, DragPhase, Point, Transform};
2974
2975    use crate::*;
2976
2977    fn size(width: f64, height: f64) -> FrameExpect {
2978        FrameExpect {
2979            width: Some(width),
2980            height: Some(height),
2981            ..Default::default()
2982        }
2983    }
2984
2985    #[day_macros::test(day_core)]
2986    fn reactive_frame_and_minimum_height() -> Case {
2987        let width = Signal::new(80.0);
2988        let height = Signal::new(44.0);
2989        Case::new()
2990            .proves_modifier("width")
2991            .proves_modifier("height")
2992            .proves_modifier("frame")
2993            .proves_modifier("min_height")
2994            .page(move || {
2995                column((
2996                    rectangle()
2997                        .fill(day_spec::Color::hex(0x0033_6699))
2998                        .frame(width, height)
2999                        .id(day_core::id!(resizing)),
3000                    rectangle()
3001                        .fill(day_spec::Color::hex(0x0066_3399))
3002                        .width(width)
3003                        .height(20.0)
3004                        .min_height(44.0)
3005                        .id(day_core::id!(minimum)),
3006                    button("Resize fixture")
3007                        .action(move || {
3008                            width.set(120.0);
3009                            height.set(64.0);
3010                        })
3011                        .id(day_core::id!(resize)),
3012                ))
3013                .spacing(0.0)
3014            })
3015            .drive(|d: Drive| async move {
3016                d.assert_frame("resizing", size(80.0, 44.0)).await?;
3017                d.assert_frame("minimum", size(80.0, 44.0)).await?;
3018                d.tap("resize").await?;
3019                d.assert_frame("resizing", size(120.0, 64.0)).await?;
3020                d.assert_frame("minimum", size(120.0, 44.0)).await
3021            })
3022    }
3023
3024    /// A subtree's reading direction mirrors its placement and nothing outside it: in a
3025    /// right-to-left subtree the first box sits at the right edge, a left-to-right subtree
3026    /// nested inside it runs the usual way again, and a flip of the signal re-lays it out.
3027    #[day_macros::test(day_core)]
3028    fn layout_direction_mirrors_a_subtree() -> Case {
3029        let direction = Signal::new(day_spec::LayoutDirection::Rtl);
3030        let pair = |first: day_core::ElementId, second: day_core::ElementId| {
3031            row((
3032                rectangle()
3033                    .fill(Color::hex(0x0033_6699))
3034                    .frame(40.0, 20.0)
3035                    .id(first),
3036                rectangle()
3037                    .fill(Color::hex(0x0099_3366))
3038                    .frame(60.0, 20.0)
3039                    .id(second),
3040            ))
3041        };
3042        Case::new()
3043            .proves_modifier("layout_direction")
3044            .proves_duty("set_layout_direction")
3045            .page(move || {
3046                column((
3047                    column((
3048                        pair(day_core::id!(dir_a), day_core::id!(dir_b))
3049                            .width(200.0)
3050                            .wrapper_id(day_core::id!(dir_outer)),
3051                        pair(day_core::id!(dir_c), day_core::id!(dir_d))
3052                            .width(200.0)
3053                            .wrapper_id(day_core::id!(dir_inner))
3054                            .layout_direction(day_spec::LayoutDirection::Ltr),
3055                        label("Text in the subtree").id(day_core::id!(dir_text)),
3056                    ))
3057                    .align(HAlign::Leading)
3058                    .layout_direction(direction),
3059                    button("Flip")
3060                        .action(move || direction.set(day_spec::LayoutDirection::Ltr))
3061                        .id(day_core::id!(dir_flip)),
3062                ))
3063                .align(HAlign::Leading)
3064                .spacing(8.0)
3065            })
3066            .shot("rtl")
3067            .drive(|d: Drive| async move {
3068                let at = |x: f64, outer: &str| FrameExpect {
3069                    x: Some(x),
3070                    relative_to: Some(outer.into()),
3071                    ..Default::default()
3072                };
3073                // Right to left: the first box ends at the row's right edge.
3074                d.assert_frame("dir_a", at(160.0, "dir_outer")).await?;
3075                d.assert_frame("dir_b", at(100.0, "dir_outer")).await?;
3076                // The nested left-to-right row is not mirrored.
3077                d.assert_frame("dir_c", at(0.0, "dir_inner")).await?;
3078                d.assert_frame("dir_d", at(40.0, "dir_inner")).await?;
3079                d.assert_text("dir_text", "Text in the subtree").await?;
3080                d.tap("dir_flip").await?;
3081                d.wait_idle().await?;
3082                d.assert_frame("dir_a", at(0.0, "dir_outer")).await?;
3083                d.assert_frame("dir_b", at(40.0, "dir_outer")).await
3084            })
3085    }
3086
3087    #[day_macros::test(day_core)]
3088    fn text_reservation() -> Case {
3089        let value = Signal::new("1".to_owned());
3090        let sample = Signal::new("8888".to_owned());
3091        Case::new()
3092            .proves_modifier("reserving")
3093            .page(move || {
3094                column((
3095                    label(value)
3096                        .reserving(sample)
3097                        .font(day_spec::Font::Title2)
3098                        .tabular()
3099                        .id(day_core::id!(reserved_readout)),
3100                    label("8888")
3101                        .font(day_spec::Font::Title2)
3102                        .tabular()
3103                        .id(day_core::id!(reservation_reference)),
3104                    label("88888888")
3105                        .font(day_spec::Font::Title2)
3106                        .tabular()
3107                        .id(day_core::id!(reservation_expanded)),
3108                    button("Update fixture value")
3109                        .action(move || value.set("88".into()))
3110                        .id(day_core::id!(reservation_update)),
3111                    button("Expand fixture sample")
3112                        .action(move || sample.set("88888888".into()))
3113                        .id(day_core::id!(reservation_expand)),
3114                ))
3115                .align(HAlign::Leading)
3116            })
3117            .drive(|d: Drive| async move {
3118                let dimensions = |id: &str| {
3119                    day_core::with_tree(|tree| {
3120                        tree.node_frame(tree.find_by_id(id).unwrap()).unwrap().size
3121                    })
3122                };
3123                let reference = dimensions("reservation_reference");
3124                d.assert_frame("reserved_readout", size(reference.width, reference.height))
3125                    .await?;
3126                d.tap("reservation_update").await?;
3127                d.assert_text("reserved_readout", "88").await?;
3128                d.assert_frame("reserved_readout", size(reference.width, reference.height))
3129                    .await?;
3130                d.tap("reservation_expand").await?;
3131                let expanded = dimensions("reservation_expanded");
3132                d.assert_frame("reserved_readout", size(expanded.width, expanded.height))
3133                    .await?;
3134                d.assert_text("reserved_readout", "88").await
3135            })
3136    }
3137
3138    /// Padding grows the frame by its insets and moves the content in by them.
3139    #[day_macros::test(day_core)]
3140    fn padding_insets() -> Case {
3141        Case::new()
3142            .proves_modifier("padding")
3143            .proves_modifier("wrapper_id")
3144            .page(|| {
3145                // `id` names the rectangle wherever it sits; the padding box is a wrapper, so
3146                // it is named with `wrapper_id`, the one ordered identity modifier.
3147                rectangle()
3148                    .fill(Color::rgb(1.0, 0.0, 0.0))
3149                    .id(day_core::id!(inner))
3150                    .frame(40.0, 20.0)
3151                    .padding(10.0)
3152                    .wrapper_id(day_core::id!(outer))
3153            })
3154            .drive(|d: Drive| async move {
3155                d.assert_frame("outer", size(60.0, 40.0)).await?;
3156                d.assert_frame(
3157                    "inner",
3158                    FrameExpect {
3159                        x: Some(10.0),
3160                        y: Some(10.0),
3161                        relative_to: Some("outer".into()),
3162                        ..Default::default()
3163                    },
3164                )
3165                .await
3166            })
3167    }
3168
3169    /// A minimum width widens a narrow piece; a maximum narrows a wide one.
3170    #[day_macros::test(day_core)]
3171    fn min_max_width() -> Case {
3172        Case::new()
3173            .proves_modifier("min_width")
3174            .proves_modifier("max_width")
3175            .page(|| {
3176                column((
3177                    // The widened box, not the label's own node.
3178                    label("Hi").min_width(120.0).wrapper_id(day_core::id!(min)),
3179                    label("A label long enough that it would run past eighty points")
3180                        .max_width(80.0)
3181                        .wrapper_id(day_core::id!(max)),
3182                ))
3183                .align(HAlign::Leading)
3184            })
3185            .drive(|d: Drive| async move {
3186                d.assert_frame(
3187                    "min",
3188                    FrameExpect {
3189                        width: Some(120.0),
3190                        ..Default::default()
3191                    },
3192                )
3193                .await?;
3194                d.assert_frame(
3195                    "max",
3196                    FrameExpect {
3197                        width: Some(80.0),
3198                        ..Default::default()
3199                    },
3200                )
3201                .await
3202            })
3203    }
3204
3205    /// A maximum height stops a scroll, which takes all the height it is offered, at the cap.
3206    #[day_macros::test(day_core)]
3207    fn max_height_caps_a_scroll() -> Case {
3208        Case::new()
3209            .proves_modifier("max_height")
3210            .page(|| {
3211                column((
3212                    scroll(column((
3213                        label("One"),
3214                        label("Two"),
3215                        label("Three"),
3216                        label("Four"),
3217                        label("Five"),
3218                        label("Six"),
3219                    )))
3220                    .max_height(60.0)
3221                    .wrapper_id(day_core::id!(capped)),
3222                    spacer(),
3223                ))
3224                .align(HAlign::Leading)
3225            })
3226            .drive(|d: Drive| async move {
3227                d.assert_frame(
3228                    "capped",
3229                    FrameExpect {
3230                        height: Some(60.0),
3231                        ..Default::default()
3232                    },
3233                )
3234                .await
3235            })
3236    }
3237
3238    /// An aspect ratio sets the height from the width.
3239    #[day_macros::test(day_core)]
3240    fn aspect_ratio_height() -> Case {
3241        Case::new()
3242            .proves_modifier("aspect_ratio")
3243            .page(|| {
3244                rectangle()
3245                    .fill(Color::rgb(0.0, 0.0, 1.0))
3246                    .aspect_ratio(2.0)
3247                    .id(day_core::id!(shape))
3248                    .width(100.0)
3249            })
3250            .drive(|d: Drive| async move { d.assert_frame("shape", size(100.0, 50.0)).await })
3251    }
3252
3253    /// A growing child takes the row's remaining width.
3254    #[day_macros::test(day_core)]
3255    fn grow_width() -> Case {
3256        Case::new()
3257            .proves_modifier("grow")
3258            .page(|| {
3259                row((
3260                    rectangle()
3261                        .fill(Color::rgb(1.0, 0.0, 0.0))
3262                        .frame(40.0, 20.0),
3263                    rectangle()
3264                        .fill(Color::rgb(0.0, 0.0, 1.0))
3265                        .height(20.0)
3266                        .grow(Dimension::Width)
3267                        .id(day_core::id!(grower)),
3268                ))
3269                .spacing(0.0)
3270                .width(200.0)
3271            })
3272            .drive(|d: Drive| async move {
3273                d.assert_frame(
3274                    "grower",
3275                    FrameExpect {
3276                        width: Some(160.0),
3277                        ..Default::default()
3278                    },
3279                )
3280                .await
3281            })
3282    }
3283
3284    /// Alignment preserves the child's size inside an explicitly sized area.
3285    #[day_macros::test(day_core)]
3286    fn aligned_intrinsic_frame() -> Case {
3287        Case::new()
3288            .proves_modifier("aligned")
3289            .page(|| {
3290                // A native container gives both layout and toolkit probes the same origin,
3291                // independent of window chrome and mobile safe-area insets.
3292                zstack((rectangle()
3293                    .fill(Color::rgb(0.2, 0.5, 0.8))
3294                    .frame(40.0, 20.0)
3295                    .id(day_core::id!(aligned_child))
3296                    .aligned(day_core::Alignment::BottomTrailing)
3297                    .frame(200.0, 100.0),))
3298                .id(day_core::id!(aligned_container))
3299                .frame(200.0, 100.0)
3300            })
3301            .drive(|d: Drive| async move {
3302                d.assert_frame("aligned_container", size(200.0, 100.0))
3303                    .await?;
3304                d.assert_frame(
3305                    "aligned_child",
3306                    FrameExpect {
3307                        x: Some(160.0),
3308                        y: Some(80.0),
3309                        width: Some(40.0),
3310                        height: Some(20.0),
3311                        relative_to: Some("aligned_container".into()),
3312                        ..Default::default()
3313                    },
3314                )
3315                .await
3316            })
3317    }
3318
3319    /// An aligned overlay draws over its base, in the corner it names.
3320    #[day_macros::test(day_core)]
3321    fn overlay_aligned_corner() -> Case {
3322        Case::new()
3323            .proves_modifier("overlay_aligned")
3324            .requires(Cap::Snapshot)
3325            .page(|| {
3326                rectangle()
3327                    .fill(Color::rgb(1.0, 0.0, 0.0))
3328                    .frame(100.0, 60.0)
3329                    .overlay_aligned(
3330                        day_core::Alignment::BottomTrailing,
3331                        rectangle()
3332                            .fill(Color::rgb(0.0, 0.0, 1.0))
3333                            .frame(20.0, 20.0),
3334                    )
3335                    .id(day_core::id!(base))
3336            })
3337            .drive(|d: Drive| async move {
3338                d.sample_pixel("base", 0.95, 0.9, "#0000ff").await?;
3339                d.sample_pixel("base", 0.1, 0.1, "#ff0000").await
3340            })
3341    }
3342
3343    /// A background fills the piece's frame.
3344    #[day_macros::test(day_core)]
3345    fn background_fill() -> Case {
3346        Case::new()
3347            .proves_modifier("background")
3348            .requires(Cap::Snapshot)
3349            .page(|| {
3350                label("")
3351                    .frame(80.0, 40.0)
3352                    .background(Color::rgb(1.0, 0.0, 0.0))
3353                    .id(day_core::id!(filled))
3354            })
3355            .drive(|d: Drive| async move { d.sample_pixel("filled", 0.5, 0.5, "#ff0000").await })
3356    }
3357
3358    /// A corner radius cuts a background's corners and keeps its middle.
3359    #[day_macros::test(day_core)]
3360    fn corner_radius_cuts() -> Case {
3361        Case::new()
3362            .proves_modifier("corner_radius")
3363            .requires(Cap::Snapshot)
3364            .page(|| {
3365                zstack((
3366                    rectangle().fill(Color::WHITE),
3367                    label("")
3368                        .frame(80.0, 80.0)
3369                        .background(Color::rgb(0.0, 0.0, 1.0))
3370                        .corner_radius(30.0),
3371                ))
3372                .id(day_core::id!(ground))
3373                .frame(80.0, 80.0)
3374            })
3375            .drive(|d: Drive| async move {
3376                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
3377                d.sample_pixel("ground", 0.03, 0.03, "#ffffff").await
3378            })
3379    }
3380
3381    /// A surface's border is drawn inside its frame, over the fill's edge and not its middle.
3382    #[day_macros::test(day_core)]
3383    fn surface_border_frames_fill() -> Case {
3384        Case::new()
3385            .proves_modifier("surface")
3386            .proves_modifier("border")
3387            .requires(Cap::Snapshot)
3388            .page(|| {
3389                label("")
3390                    .frame(80.0, 80.0)
3391                    .surface(
3392                        Surface::new()
3393                            .fill(Color::rgb(0.0, 0.0, 1.0))
3394                            .border(Color::rgb(1.0, 0.0, 0.0), 8.0),
3395                    )
3396                    .id(day_core::id!(framed))
3397            })
3398            .drive(|d: Drive| async move {
3399                d.sample_pixel("framed", 0.5, 0.5, "#0000ff").await?;
3400                d.sample_pixel("framed", 0.5, 0.05, "#ff0000").await?;
3401                d.sample_pixel("framed", 0.05, 0.5, "#ff0000").await?;
3402                d.sample_pixel("framed", 0.95, 0.5, "#ff0000").await?;
3403                d.sample_pixel("framed", 0.5, 0.95, "#ff0000").await
3404            })
3405    }
3406
3407    /// A surface rounds only the corners it is told to: the top two are cut, the bottom two
3408    /// are still filled.
3409    #[day_macros::test(day_core)]
3410    fn surface_rounds_named_corners() -> Case {
3411        Case::new()
3412            .proves_modifier("surface")
3413            .requires(Cap::Snapshot)
3414            .page(|| {
3415                zstack((
3416                    rectangle().fill(Color::WHITE),
3417                    label("").frame(80.0, 80.0).surface(
3418                        Surface::new()
3419                            .fill(Color::rgb(0.0, 0.0, 1.0))
3420                            .corner_radius(30.0)
3421                            .corners(day_spec::Corners::TOP),
3422                    ),
3423                ))
3424                .id(day_core::id!(ground))
3425                .frame(80.0, 80.0)
3426            })
3427            .drive(|d: Drive| async move {
3428                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
3429                d.sample_pixel("ground", 0.03, 0.03, "#ffffff").await?;
3430                d.sample_pixel("ground", 0.97, 0.03, "#ffffff").await?;
3431                d.sample_pixel("ground", 0.03, 0.97, "#0000ff").await?;
3432                d.sample_pixel("ground", 0.97, 0.97, "#0000ff").await
3433            })
3434    }
3435
3436    /// A surface's gradient runs from its first stop at one edge to its last at the other.
3437    #[day_macros::test(day_core)]
3438    fn surface_gradient_fill() -> Case {
3439        Case::new()
3440            .proves_modifier("surface")
3441            .requires(Cap::Snapshot)
3442            .page(|| {
3443                label("")
3444                    .frame(80.0, 80.0)
3445                    .surface(Surface::new().fill(day_spec::LinearGradient::vertical(
3446                        Color::rgb(1.0, 0.0, 0.0),
3447                        Color::rgb(0.0, 0.0, 1.0),
3448                    )))
3449                    .id(day_core::id!(graded))
3450            })
3451            .drive(|d: Drive| async move {
3452                d.sample_pixel("graded", 0.5, 0.06, "#ff0000").await?;
3453                d.sample_pixel("graded", 0.5, 0.5, "#800080").await?;
3454                d.sample_pixel("graded", 0.5, 0.94, "#0000ff").await
3455            })
3456    }
3457
3458    /// A surface's shadow is drawn outside its frame, moved by its offset, and leaves the
3459    /// surface itself and the ground beyond the shadow alone.
3460    #[day_macros::test(day_core)]
3461    fn surface_shadow_falls_outside() -> Case {
3462        Case::new()
3463            .proves_modifier("surface")
3464            .proves_modifier("shadow")
3465            .requires(Cap::Snapshot)
3466            .page(|| {
3467                // The surface is the middle 60 points of a 120-point ground, so its shadow,
3468                // 16 points down, shows in the band from 90 to 106.
3469                zstack((
3470                    rectangle().fill(Color::WHITE),
3471                    label("").frame(60.0, 60.0).surface(
3472                        Surface::new().fill(Color::rgb(0.0, 0.0, 1.0)).shadow(
3473                            day_spec::Shadow::new(Color::rgb(0.0, 0.0, 0.0), 4.0).offset(0.0, 16.0),
3474                        ),
3475                    ),
3476                ))
3477                .id(day_core::id!(ground))
3478                .frame(120.0, 120.0)
3479            })
3480            .drive(|d: Drive| async move {
3481                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
3482                d.sample_pixel("ground", 0.5, 0.815, "#000000").await?;
3483                d.sample_pixel("ground", 0.5, 0.97, "#ffffff").await?;
3484                d.sample_pixel("ground", 0.5, 0.1, "#ffffff").await
3485            })
3486    }
3487
3488    /// Buttons that switch the app's appearance, for the cases that prove a view follows it.
3489    fn appearance_switches() -> impl day_core::Piece {
3490        row((
3491            button("Light")
3492                .action(|| day_core::set_appearance(Some(false)))
3493                .id(day_core::id!(appearance::light)),
3494            button("Dark")
3495                .action(|| day_core::set_appearance(Some(true)))
3496                .id(day_core::id!(appearance::dark)),
3497            button("System")
3498                .action(|| day_core::set_appearance(None))
3499                .id(day_core::id!(appearance::system)),
3500        ))
3501        .spacing(8.0)
3502    }
3503
3504    /// A fill given as an ink follows an appearance switch with no app code running: no
3505    /// closure, no signal, no rebuild. A light/dark pair recolors in place, and a platform
3506    /// role shows what `day::resolve` answers for it in each appearance (docs/color.md).
3507    #[day_macros::test(day_core)]
3508    fn ink_follows_the_appearance() -> Case {
3509        const PAIR: day_spec::Ink =
3510            day_spec::Ink::adaptive(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
3511        Case::new()
3512            .proves_modifier("background")
3513            .proves_cap(Cap::Appearance)
3514            .requires(Cap::Appearance)
3515            .page(|| {
3516                column((
3517                    label("")
3518                        .frame(80.0, 40.0)
3519                        .background(PAIR)
3520                        .id(day_core::id!(paired)),
3521                    label("")
3522                        .frame(80.0, 40.0)
3523                        .background(day_spec::SystemColor::Background)
3524                        .border(day_spec::SystemColor::Separator, 2.0)
3525                        .id(day_core::id!(role)),
3526                    appearance_switches(),
3527                ))
3528                .spacing(8.0)
3529            })
3530            .drive(|d: Drive| async move {
3531                let shown = |c: Color| day_core::conformance::DisplayedExpect {
3532                    background: Some(c),
3533                    ..Default::default()
3534                };
3535                d.tap("appearance::light").await?;
3536                d.sample_pixel("paired", 0.5, 0.5, "#ff0000").await?;
3537                d.assert_displayed("paired", shown(Color::rgb(1.0, 0.0, 0.0)))
3538                    .await?;
3539                let light = day_core::resolve(day_spec::SystemColor::Background);
3540                d.assert_displayed("role", shown(light)).await?;
3541                d.tap("appearance::dark").await?;
3542                d.sample_pixel("paired", 0.5, 0.5, "#0000ff").await?;
3543                d.assert_displayed("paired", shown(Color::rgb(0.0, 0.0, 1.0)))
3544                    .await?;
3545                let dark = day_core::resolve(day_spec::SystemColor::Background);
3546                d.assert_displayed("role", shown(dark)).await?;
3547                d.tap("appearance::system").await
3548            })
3549    }
3550
3551    /// A canvas that draws with an ink records the color of the current appearance and draws
3552    /// again when the appearance changes (docs/canvas.md "Colors").
3553    #[day_macros::test(day_core)]
3554    fn canvas_ink_follows_the_appearance() -> Case {
3555        Case::new()
3556            .proves(day_spec::kinds::CANVAS)
3557            .requires(Cap::Appearance)
3558            .requires(Cap::Snapshot)
3559            .page(|| {
3560                column((
3561                    canvas(|d, size| {
3562                        d.fill(
3563                            day_spec::Shape::Rect(day_spec::Rect::from_size(size)),
3564                            day_spec::Ink::adaptive(
3565                                Color::rgb(1.0, 0.0, 0.0),
3566                                Color::rgb(0.0, 0.0, 1.0),
3567                            ),
3568                        );
3569                    })
3570                    .frame(80.0, 40.0)
3571                    .id(day_core::id!(drawn)),
3572                    appearance_switches(),
3573                ))
3574                .spacing(8.0)
3575            })
3576            .drive(|d: Drive| async move {
3577                d.tap("appearance::light").await?;
3578                d.sample_pixel("drawn", 0.5, 0.5, "#ff0000").await?;
3579                d.tap("appearance::dark").await?;
3580                d.sample_pixel("drawn", 0.5, 0.5, "#0000ff").await?;
3581                d.tap("appearance::system").await
3582            })
3583    }
3584
3585    /// A surface's border is drawn over its content: a child that fills the surface edge to
3586    /// edge never covers the border (docs/surfaces.md "Rules").
3587    #[day_macros::test(day_core)]
3588    fn surface_border_over_content() -> Case {
3589        Case::new()
3590            .proves_modifier("surface")
3591            .proves_modifier("border")
3592            .requires(Cap::Snapshot)
3593            .page(|| {
3594                rectangle()
3595                    .fill(Color::rgb(0.0, 0.0, 1.0))
3596                    .frame(80.0, 80.0)
3597                    .surface(
3598                        Surface::new()
3599                            .corner_radius(12.0)
3600                            .border(Color::rgb(1.0, 0.0, 0.0), 8.0),
3601                    )
3602                    .id(day_core::id!(framed))
3603            })
3604            .drive(|d: Drive| async move {
3605                d.sample_pixel("framed", 0.5, 0.5, "#0000ff").await?;
3606                d.sample_pixel("framed", 0.5, 0.04, "#ff0000").await?;
3607                d.sample_pixel("framed", 0.04, 0.5, "#ff0000").await?;
3608                d.sample_pixel("framed", 0.5, 0.96, "#ff0000").await
3609            })
3610    }
3611
3612    /// A surface takes a radial and a conic paint like a shape does: the radial gradient's
3613    /// first stop at the middle and its last at the edge; the conic gradient's quarters
3614    /// clockwise from +x (docs/surfaces.md).
3615    #[day_macros::test(day_core)]
3616    fn surface_radial_and_conic_fill() -> Case {
3617        Case::new()
3618            .proves_modifier("surface")
3619            .requires(Cap::Snapshot)
3620            .page(|| {
3621                let quarter = |at: f64, c: Color| [(at, c), (at + 0.25, c)];
3622                let conic = [
3623                    quarter(0.0, Color::rgb(1.0, 0.0, 0.0)),
3624                    quarter(0.25, Color::rgb(0.0, 1.0, 0.0)),
3625                    quarter(0.5, Color::rgb(0.0, 0.0, 1.0)),
3626                    quarter(0.75, Color::rgb(1.0, 1.0, 0.0)),
3627                ]
3628                .concat();
3629                row((
3630                    label("")
3631                        .frame(80.0, 80.0)
3632                        .surface(Surface::new().fill(day_spec::RadialGradient::new(
3633                            day_spec::UnitPoint::CENTER,
3634                            0.5,
3635                            [
3636                                (0.0, Color::rgb(1.0, 0.0, 0.0)),
3637                                (0.2, Color::rgb(1.0, 0.0, 0.0)),
3638                                (0.8, Color::rgb(0.0, 0.0, 1.0)),
3639                                (1.0, Color::rgb(0.0, 0.0, 1.0)),
3640                            ],
3641                        )))
3642                        .id(day_core::id!(radial)),
3643                    label("")
3644                        .frame(80.0, 80.0)
3645                        .background(day_spec::ConicGradient::centered(
3646                            day_spec::Angle::ZERO,
3647                            conic,
3648                        ))
3649                        .id(day_core::id!(conic)),
3650                ))
3651                .spacing(8.0)
3652            })
3653            .drive(|d: Drive| async move {
3654                d.sample_pixel("radial", 0.5, 0.5, "#ff0000").await?;
3655                d.sample_pixel("radial", 0.5, 0.97, "#0000ff").await?;
3656                // Clockwise from +x on screen: right-below red, left-below green, left-above
3657                // blue, right-above yellow.
3658                d.sample_pixel("conic", 0.8, 0.6, "#ff0000").await?;
3659                d.sample_pixel("conic", 0.2, 0.6, "#00ff00").await?;
3660                d.sample_pixel("conic", 0.2, 0.4, "#0000ff").await?;
3661                d.sample_pixel("conic", 0.8, 0.4, "#ffff00").await
3662            })
3663    }
3664
3665    /// Corner radius, border and shadow follow their signals in place, and a capsule radius
3666    /// follows the frame as it resizes (docs/surfaces.md "Reactive surfaces").
3667    #[day_macros::test(day_core)]
3668    fn surface_follows_its_signals() -> Case {
3669        Case::new()
3670            .proves_modifier("corner_radius")
3671            .proves_modifier("border")
3672            .requires(Cap::Snapshot)
3673            .page(|| {
3674                let styled = Signal::new(false);
3675                let width = Signal::new(80.0);
3676                column((
3677                    zstack((
3678                        rectangle().fill(Color::WHITE),
3679                        label("")
3680                            .frame(80.0, 80.0)
3681                            .background(Color::rgb(0.0, 0.0, 1.0))
3682                            .border(Color::rgb(1.0, 0.0, 0.0), move || {
3683                                if styled.get() { 8.0 } else { 0.0 }
3684                            })
3685                            .corner_radius(move || if styled.get() { 30.0 } else { 0.0 }),
3686                    ))
3687                    .frame(80.0, 80.0)
3688                    .id(day_core::id!(styled)),
3689                    zstack((
3690                        rectangle().fill(Color::WHITE),
3691                        label("")
3692                            .frame(width, 40.0)
3693                            .background(Color::rgb(0.0, 0.0, 1.0))
3694                            .corner_radius(crate::Corner::CAPSULE),
3695                    ))
3696                    .frame(160.0, 40.0)
3697                    .id(day_core::id!(pill)),
3698                    button("Style")
3699                        .action(move || {
3700                            styled.set(true);
3701                            width.set(160.0);
3702                        })
3703                        .id(day_core::id!(restyle)),
3704                ))
3705                .spacing(8.0)
3706            })
3707            .drive(|d: Drive| async move {
3708                d.sample_pixel("styled", 0.03, 0.03, "#0000ff").await?;
3709                d.sample_pixel("styled", 0.5, 0.04, "#0000ff").await?;
3710                d.sample_pixel("pill", 0.02, 0.06, "#ffffff").await?;
3711                d.tap("restyle").await?;
3712                d.sample_pixel("styled", 0.03, 0.03, "#ffffff").await?;
3713                d.sample_pixel("styled", 0.5, 0.04, "#ff0000").await?;
3714                d.sample_pixel("styled", 0.5, 0.5, "#0000ff").await?;
3715                // The capsule's ends stay round at the new width.
3716                d.sample_pixel("pill", 0.01, 0.06, "#ffffff").await?;
3717                d.sample_pixel("pill", 0.99, 0.94, "#ffffff").await?;
3718                d.sample_pixel("pill", 0.5, 0.5, "#0000ff").await
3719            })
3720    }
3721
3722    /// Size limits and an aspect ratio follow their signals: the piece is laid out again at
3723    /// the new limit, without being rebuilt (docs/layout.md).
3724    #[day_macros::test(day_core)]
3725    fn size_limits_follow_their_signals() -> Case {
3726        Case::new()
3727            .proves_modifier("max_width")
3728            .proves_modifier("min_height")
3729            .proves_modifier("aspect_ratio")
3730            .page(|| {
3731                let wide = Signal::new(false);
3732                column((
3733                    rectangle()
3734                        .fill(Color::rgb(0.2, 0.4, 0.9))
3735                        .max_width(move || if wide.get() { 120.0 } else { 60.0 })
3736                        .min_height(move || if wide.get() { 30.0 } else { 20.0 })
3737                        .frame(200.0, 10.0)
3738                        .id(day_core::id!(capped)),
3739                    rectangle()
3740                        .fill(Color::rgb(0.9, 0.4, 0.2))
3741                        .aspect_ratio(move || if wide.get() { 4.0 } else { 2.0 })
3742                        .width(80.0)
3743                        .id(day_core::id!(ratio)),
3744                    button("Widen")
3745                        .action(move || wide.set(true))
3746                        .id(day_core::id!(widen)),
3747                ))
3748                .spacing(8.0)
3749            })
3750            .drive(|d: Drive| async move {
3751                d.assert_size("capped", 60.0, 20.0).await?;
3752                d.assert_size("ratio", 80.0, 40.0).await?;
3753                d.tap("widen").await?;
3754                d.assert_size("capped", 120.0, 30.0).await?;
3755                d.assert_size("ratio", 80.0, 20.0).await
3756            })
3757    }
3758
3759    /// An `Angle` means the same turn in either unit: a quarter turn given in radians turns a
3760    /// two-color bar exactly as `Angle::deg(90.0)` does (`rotation_turns_clockwise`).
3761    #[day_macros::test(day_core)]
3762    fn rotation_takes_an_angle_in_either_unit() -> Case {
3763        Case::new()
3764            .proves_modifier("rotation")
3765            .requires(Cap::Snapshot)
3766            .page(|| {
3767                zstack((
3768                    rectangle().fill(Color::WHITE),
3769                    shape_group([
3770                        rectangle()
3771                            .fill(Color::rgb(1.0, 0.0, 0.0))
3772                            .at(0.0, 0.0, 0.5, 1.0),
3773                        rectangle()
3774                            .fill(Color::rgb(0.0, 0.0, 1.0))
3775                            .at(0.5, 0.0, 0.5, 1.0),
3776                    ])
3777                    .frame(80.0, 40.0)
3778                    .rotation(day_spec::Angle::rad(std::f64::consts::FRAC_PI_2)),
3779                ))
3780                .id(day_core::id!(ground))
3781                .frame(120.0, 120.0)
3782            })
3783            .drive(|d: Drive| async move {
3784                d.sample_pixel("ground", 0.5, 0.4, "#ff0000").await?;
3785                d.sample_pixel("ground", 0.5, 0.6, "#0000ff").await
3786            })
3787    }
3788
3789    /// Opacity zero leaves what is below showing.
3790    #[day_macros::test(day_core)]
3791    fn opacity_hides() -> Case {
3792        Case::new()
3793            .proves_duty("set_opacity")
3794            .proves_modifier("opacity")
3795            .requires(Cap::Snapshot)
3796            .page(|| {
3797                zstack((
3798                    rectangle().fill(Color::WHITE),
3799                    rectangle().fill(Color::rgb(1.0, 0.0, 0.0)).opacity(0.0),
3800                ))
3801                .id(day_core::id!(ground))
3802                .frame(80.0, 40.0)
3803            })
3804            .drive(|d: Drive| async move { d.sample_pixel("ground", 0.5, 0.5, "#ffffff").await })
3805    }
3806
3807    /// A translation moves what is drawn without moving the layout.
3808    #[day_macros::test(day_core)]
3809    fn translation_moves_drawing() -> Case {
3810        Case::new()
3811            .proves_modifier("translation")
3812            .requires(Cap::Snapshot)
3813            .page(|| {
3814                zstack((
3815                    rectangle().fill(Color::WHITE),
3816                    rectangle()
3817                        .fill(Color::rgb(0.0, 0.0, 1.0))
3818                        .frame(40.0, 40.0)
3819                        .translation(40.0, 0.0),
3820                ))
3821                .align(day_core::Alignment::Leading)
3822                .id(day_core::id!(ground))
3823                .frame(120.0, 40.0)
3824            })
3825            .drive(|d: Drive| async move {
3826                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
3827                d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
3828            })
3829    }
3830
3831    /// A translation moves a plain view's drawing too, not only a canvas's.
3832    #[day_macros::test(day_core)]
3833    fn translation_moves_view() -> Case {
3834        Case::new()
3835            .proves_modifier("translation")
3836            .requires(Cap::Snapshot)
3837            .page(|| {
3838                zstack((
3839                    rectangle().fill(Color::WHITE),
3840                    label("")
3841                        .frame(40.0, 40.0)
3842                        .background(Color::rgb(0.0, 0.0, 1.0))
3843                        .translation(40.0, 0.0),
3844                ))
3845                .align(day_core::Alignment::Leading)
3846                .id(day_core::id!(ground))
3847                .frame(120.0, 40.0)
3848            })
3849            .drive(|d: Drive| async move {
3850                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
3851                d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
3852            })
3853    }
3854
3855    /// A scale grows the drawing about its center without moving the layout.
3856    #[day_macros::test(day_core)]
3857    fn scale_grows_drawing() -> Case {
3858        Case::new()
3859            .proves_modifier("scale")
3860            .requires(Cap::Snapshot)
3861            .page(|| {
3862                zstack((
3863                    rectangle().fill(Color::WHITE),
3864                    label("")
3865                        .frame(40.0, 40.0)
3866                        .background(Color::rgb(0.0, 0.0, 1.0))
3867                        .scale(2.0),
3868                ))
3869                .id(day_core::id!(ground))
3870                .frame(120.0, 80.0)
3871            })
3872            .drive(|d: Drive| async move {
3873                // Unscaled, the square spans x 40..80 of 120; scaled twice it spans 20..100.
3874                d.sample_pixel("ground", 0.25, 0.5, "#0000ff").await?;
3875                d.sample_pixel("ground", 0.08, 0.5, "#ffffff").await
3876            })
3877    }
3878
3879    /// A rotation turns the drawing clockwise (y points down): a bar red on the left and blue
3880    /// on the right, turned 90°, is red on top and blue below.
3881    #[day_macros::test(day_core)]
3882    fn rotation_turns_clockwise() -> Case {
3883        Case::new()
3884            .proves_modifier("rotation")
3885            .requires(Cap::Snapshot)
3886            .page(|| {
3887                zstack((
3888                    rectangle().fill(Color::WHITE),
3889                    shape_group([
3890                        rectangle()
3891                            .fill(Color::rgb(1.0, 0.0, 0.0))
3892                            .at(0.0, 0.0, 0.5, 1.0),
3893                        rectangle()
3894                            .fill(Color::rgb(0.0, 0.0, 1.0))
3895                            .at(0.5, 0.0, 0.5, 1.0),
3896                    ])
3897                    .frame(80.0, 40.0)
3898                    .rotation(day_spec::Angle::QUARTER),
3899                ))
3900                .id(day_core::id!(ground))
3901                .frame(120.0, 120.0)
3902            })
3903            .shot("default")
3904            .drive(|d: Drive| async move {
3905                d.sample_pixel("ground", 0.5, 0.4, "#ff0000").await?;
3906                d.sample_pixel("ground", 0.5, 0.6, "#0000ff").await
3907            })
3908    }
3909
3910    // ---- input: every op injects Day's own event, the stream a native recognizer delivers,
3911    // so these prove the routing and the handler, not that the platform's recognizer fires
3912    // (docs/testing.md "Known gaps").
3913
3914    /// A plain target for gestures: a filled rectangle of a known size.
3915    fn pad(id: day_core::ElementId) -> Decorated<ShapePiece> {
3916        rectangle()
3917            .fill(Color::rgb(0.2, 0.4, 0.9))
3918            .frame(120.0, 80.0)
3919            .id(id)
3920    }
3921
3922    /// A tap runs `.on_tap`'s work, once per tap.
3923    #[day_macros::test(day_core)]
3924    fn on_tap_runs() -> Case {
3925        Case::new()
3926            .proves_modifier("on_tap")
3927            .page(|| {
3928                let taps = Signal::new(0i64);
3929                column((
3930                    label(move || format!("taps {}", taps.get())).id(day_core::id!(taps)),
3931                    label("Tap me")
3932                        .padding(12.0)
3933                        .on_tap(move || taps.update(|n| *n += 1))
3934                        .id(day_core::id!(target)),
3935                ))
3936            })
3937            .drive(|d: Drive| async move {
3938                d.tap("target").await?;
3939                d.tap("target").await?;
3940                d.assert_text("taps", "taps 2").await
3941            })
3942    }
3943
3944    /// `.on_tap_at` hears where in the element the tap landed.
3945    #[day_macros::test(day_core)]
3946    fn on_tap_at_reports_point() -> Case {
3947        Case::new()
3948            .proves_modifier("on_tap_at")
3949            .page(|| {
3950                let at = Signal::new(String::from("none"));
3951                column((
3952                    label(move || format!("at {}", at.get())).id(day_core::id!(at)),
3953                    rectangle()
3954                        .fill(Color::rgb(0.2, 0.4, 0.9))
3955                        .frame(120.0, 80.0)
3956                        .on_tap_at(move |p| at.set(format!("{:.0},{:.0}", p.x, p.y)))
3957                        .id(day_core::id!(target)),
3958                ))
3959            })
3960            .drive(|d: Drive| async move {
3961                d.tap_at("target", 30.0, 20.0).await?;
3962                d.assert_text("at", "at 30,20").await
3963            })
3964    }
3965
3966    /// A drag reports its phases, and its translation from where it began.
3967    #[day_macros::test(day_core)]
3968    fn on_drag_reports_translation() -> Case {
3969        Case::new()
3970            .proves_duty("enable_gesture")
3971            .proves_modifier("on_drag")
3972            .page(|| {
3973                let state = Signal::new(String::from("idle"));
3974                column((
3975                    label(move || state.get()).id(day_core::id!(state)),
3976                    pad(day_core::id!(target)).on_drag(move |d: Drag| {
3977                        state.set(match d.phase {
3978                            DragPhase::Began => "began".into(),
3979                            DragPhase::Changed => "moving".into(),
3980                            DragPhase::Ended => {
3981                                format!("moved {:.0},{:.0}", d.translation.x, d.translation.y)
3982                            }
3983                        });
3984                    }),
3985                ))
3986            })
3987            .drive(|d: Drive| async move {
3988                d.drag("target", (10.0, 10.0), (50.0, 30.0)).await?;
3989                d.assert_text("state", "moved 40,20").await
3990            })
3991    }
3992
3993    /// Hover reports the pointer's place while it is over the element, and `None` on leaving.
3994    #[day_macros::test(day_core)]
3995    fn on_hover_enters_and_leaves() -> Case {
3996        Case::new()
3997            .proves_modifier("on_hover")
3998            .page(|| {
3999                let state = Signal::new(String::from("out"));
4000                column((
4001                    label(move || state.get()).id(day_core::id!(state)),
4002                    pad(day_core::id!(target)).on_hover(move |p| {
4003                        state.set(match p {
4004                            Some(p) => format!("over {:.0},{:.0}", p.x, p.y),
4005                            None => "out".into(),
4006                        });
4007                    }),
4008                ))
4009            })
4010            .drive(|d: Drive| async move {
4011                d.hover("target", Some((5.0, 6.0))).await?;
4012                d.assert_text("state", "over 5,6").await?;
4013                d.hover_leave("target").await?;
4014                d.assert_text("state", "out").await
4015            })
4016    }
4017
4018    /// A pan delivers incremental deltas that add up to the whole movement.
4019    #[day_macros::test(day_core)]
4020    fn on_pan_adds_deltas() -> Case {
4021        Case::new()
4022            .proves_modifier("on_pan")
4023            .page(|| {
4024                let total = Signal::new((0.0f64, 0.0f64));
4025                column((
4026                    label(move || {
4027                        let (x, y) = total.get();
4028                        format!("pan {x:.0},{y:.0}")
4029                    })
4030                    .id(day_core::id!(total)),
4031                    pad(day_core::id!(target)).on_pan(move |p: Pan| {
4032                        total.update(|(x, y)| {
4033                            *x += p.delta.x;
4034                            *y += p.delta.y;
4035                        });
4036                    }),
4037                ))
4038            })
4039            .drive(|d: Drive| async move {
4040                d.pan("target", 40.0, -20.0).await?;
4041                d.assert_text("total", "pan 40,-20").await
4042            })
4043    }
4044
4045    /// A pinch's scale is cumulative from where it began; its end carries the final scale.
4046    #[day_macros::test(day_core)]
4047    fn on_pinch_reports_scale() -> Case {
4048        Case::new()
4049            .proves_modifier("on_pinch")
4050            .page(|| {
4051                let scale = Signal::new(String::from("none"));
4052                column((
4053                    label(move || format!("scale {}", scale.get())).id(day_core::id!(scale)),
4054                    pad(day_core::id!(target)).on_pinch(move |p: Pinch| {
4055                        if p.phase == DragPhase::Ended {
4056                            scale.set(format!("{:.1}", p.scale));
4057                        }
4058                    }),
4059                ))
4060            })
4061            .drive(|d: Drive| async move {
4062                d.pinch("target", 2.5).await?;
4063                d.assert_text("scale", "scale 2.5").await
4064            })
4065    }
4066
4067    /// A rotation is cumulative from where it began, in radians; its end carries the final
4068    /// angle.
4069    #[day_macros::test(day_core)]
4070    fn on_rotate_reports_rotation() -> Case {
4071        Case::new()
4072            .proves_modifier("on_rotate")
4073            .page(|| {
4074                let angle = Signal::new(String::from("none"));
4075                column((
4076                    label(move || format!("rotation {}", angle.get())).id(day_core::id!(angle)),
4077                    pad(day_core::id!(target)).on_rotate(move |r: Rotate| {
4078                        if r.phase == DragPhase::Ended {
4079                            angle.set(format!("{:.2}", r.rotation.radians()));
4080                        }
4081                    }),
4082                ))
4083            })
4084            .drive(|d: Drive| async move {
4085                d.rotate("target", 0.75).await?;
4086                d.assert_text("angle", "rotation 0.75").await
4087            })
4088    }
4089
4090    /// A focusable element takes focus, and the keys pressed while it holds it reach `.on_key`.
4091    #[day_macros::test(day_core)]
4092    fn on_key_reaches_focused() -> Case {
4093        Case::new()
4094            .proves_duty("focus")
4095            .proves_duty("set_focusable")
4096            .proves_modifier("on_key")
4097            .proves_modifier("focusable")
4098            .page(|| {
4099                let last = Signal::new(String::from("none"));
4100                column((
4101                    label(move || format!("key {}", last.get())).id(day_core::id!(last)),
4102                    pad(day_core::id!(target))
4103                        .focusable()
4104                        .on_key(move |k| last.set(k.key.name())),
4105                ))
4106            })
4107            .drive(|d: Drive| async move {
4108                // Focus, then a key to whatever holds focus: the route a real press takes.
4109                d.focus("target").await?;
4110                d.assert_focused("target", true).await?;
4111                d.key(None, "ArrowRight").await?;
4112                d.assert_text("last", "key ArrowRight").await
4113            })
4114    }
4115
4116    /// A drag's release carries the velocity the platform's recognizer measured, and the
4117    /// press point is `location - translation` in every phase.
4118    #[day_macros::test(day_core)]
4119    fn on_drag_reports_release_velocity() -> Case {
4120        Case::new()
4121            .proves_modifier("on_drag")
4122            .page(|| {
4123                let state = Signal::new(String::from("idle"));
4124                column((
4125                    label(move || state.get()).id(day_core::id!(state)),
4126                    pad(day_core::id!(target)).on_drag(move |d: Drag| {
4127                        if d.phase == DragPhase::Ended {
4128                            state.set(format!(
4129                                "from {:.0},{:.0} at {:.0},{:.0} speed {:.0}",
4130                                d.start().x,
4131                                d.start().y,
4132                                d.velocity.x,
4133                                d.velocity.y,
4134                                d.speed()
4135                            ));
4136                        }
4137                    }),
4138                ))
4139            })
4140            .drive(|d: Drive| async move {
4141                d.fling("target", (10.0, 20.0), (70.0, 20.0), (600.0, -800.0))
4142                    .await?;
4143                d.assert_text("state", "from 10,20 at 600,-800 speed 1000")
4144                    .await?;
4145                // A drag whose samples measure nothing reports no velocity, not a stale one.
4146                d.drag("target", (10.0, 20.0), (70.0, 20.0)).await?;
4147                d.assert_text("state", "from 10,20 at 0,0 speed 0").await
4148            })
4149    }
4150
4151    /// A drag declared along one axis hears the drags that set off along it, and none of the
4152    /// ones that set off across it.
4153    #[day_macros::test(day_core)]
4154    fn on_drag_along_withholds_cross_axis() -> Case {
4155        Case::new()
4156            .proves_modifier("on_drag_along")
4157            .proves_duty("set_drag_axis")
4158            .page(|| {
4159                let state = Signal::new(String::from("none"));
4160                let events = Signal::new(0i64);
4161                column((
4162                    label(move || format!("{} after {}", state.get(), events.get()))
4163                        .id(day_core::id!(state)),
4164                    pad(day_core::id!(target)).on_drag_along(
4165                        day_spec::DragAxis::Horizontal,
4166                        move |d: Drag| {
4167                            events.update(|n| *n += 1);
4168                            if d.phase == DragPhase::Ended {
4169                                state.set(format!("moved {:.0}", d.translation.x));
4170                            }
4171                        },
4172                    ),
4173                ))
4174            })
4175            .drive(|d: Drive| async move {
4176                d.drag("target", (60.0, 10.0), (60.0, 70.0)).await?;
4177                d.assert_text("state", "none after 0").await?;
4178                d.drag("target", (10.0, 40.0), (90.0, 44.0)).await?;
4179                // Began, four samples and Ended: the whole drag, from its first event.
4180                d.assert_text("state", "moved 80 after 6").await
4181            })
4182    }
4183
4184    /// A long press reports the press point, and a piece with a tap handler too hears the
4185    /// long press alone.
4186    #[day_macros::test(day_core)]
4187    fn on_long_press_fires() -> Case {
4188        Case::new()
4189            .proves_modifier("on_long_press")
4190            .proves_duty("gesture_support")
4191            .page(|| {
4192                let held = Signal::new(String::from("none"));
4193                let taps = Signal::new(0i64);
4194                column((
4195                    label(move || format!("held {} taps {}", held.get(), taps.get()))
4196                        .id(day_core::id!(state)),
4197                    pad(day_core::id!(target))
4198                        .on_tap(move || taps.update(|n| *n += 1))
4199                        .on_long_press(move |at| held.set(format!("{:.0},{:.0}", at.x, at.y))),
4200                ))
4201            })
4202            .drive(|d: Drive| async move {
4203                d.long_press("target").await?;
4204                d.assert_text("state", "held 60,40 taps 0").await
4205            })
4206    }
4207
4208    /// A double tap runs its handler and not the single tap's.
4209    #[day_macros::test(day_core)]
4210    fn on_double_tap_fires() -> Case {
4211        Case::new()
4212            .proves_modifier("on_double_tap")
4213            .page(|| {
4214                let doubles = Signal::new(0i64);
4215                let taps = Signal::new(0i64);
4216                column((
4217                    label(move || format!("doubles {} taps {}", doubles.get(), taps.get()))
4218                        .id(day_core::id!(state)),
4219                    pad(day_core::id!(target))
4220                        .on_tap(move || taps.update(|n| *n += 1))
4221                        .on_double_tap(move || doubles.update(|n| *n += 1)),
4222                ))
4223            })
4224            .drive(|d: Drive| async move {
4225                d.double_tap("target").await?;
4226                d.assert_text("state", "doubles 1 taps 0").await
4227            })
4228    }
4229
4230    /// A double tap tells `.on_double_tap_at` where it landed, in the piece's coordinates.
4231    #[day_macros::test(day_core)]
4232    fn on_double_tap_at_reports_the_point() -> Case {
4233        Case::new()
4234            .proves_modifier("on_double_tap_at")
4235            .page(|| {
4236                let at = Signal::new(String::from("none"));
4237                column((
4238                    label(move || format!("double at {}", at.get())).id(day_core::id!(state)),
4239                    pad(day_core::id!(target))
4240                        .on_double_tap_at(move |p| at.set(format!("{:.0},{:.0}", p.x, p.y))),
4241                ))
4242            })
4243            .drive(|d: Drive| async move {
4244                d.double_tap("target").await?;
4245                d.assert_text("state", "double at 60,40").await
4246            })
4247    }
4248
4249    /// Press-in and press-out reach `.on_pressed`, one of each per press.
4250    #[day_macros::test(day_core)]
4251    fn on_pressed_follows_press() -> Case {
4252        Case::new()
4253            .proves_modifier("on_pressed")
4254            .page(|| {
4255                let down = Signal::new(false);
4256                let changes = Signal::new(0i64);
4257                column((
4258                    label(move || {
4259                        let state = if down.get() { "down" } else { "up" };
4260                        format!("{state} after {}", changes.get())
4261                    })
4262                    .id(day_core::id!(state)),
4263                    pad(day_core::id!(target)).on_pressed(move |pressed| {
4264                        down.set(pressed);
4265                        changes.update(|n| *n += 1);
4266                    }),
4267                ))
4268            })
4269            .drive(|d: Drive| async move {
4270                d.press("target", true).await?;
4271                d.assert_text("state", "down after 1").await?;
4272                d.press("target", false).await?;
4273                d.assert_text("state", "up after 2").await
4274            })
4275    }
4276
4277    /// Raw contacts arrive as a list, each with its own id, and say when they lift.
4278    #[day_macros::test(day_core)]
4279    fn on_touches_reports_contacts() -> Case {
4280        Case::new()
4281            .proves_modifier("on_touches")
4282            .page(|| {
4283                let state = Signal::new(String::from("none"));
4284                column((
4285                    label(move || state.get()).id(day_core::id!(state)),
4286                    pad(day_core::id!(target)).on_touches(move |touches: &[day_spec::Touch]| {
4287                        let down = touches.iter().filter(|t| t.is_down()).count();
4288                        let ids: Vec<String> = touches.iter().map(|t| t.id.to_string()).collect();
4289                        let last = touches.last().map_or(Point::ZERO, |t| t.location);
4290                        state.set(format!(
4291                            "{down} down ids {} last {:.0},{:.0}",
4292                            ids.join("+"),
4293                            last.x,
4294                            last.y
4295                        ));
4296                    }),
4297                ))
4298            })
4299            .drive(|d: Drive| async move {
4300                let points = [(10.0, 10.0), (50.0, 30.0)];
4301                d.touches("target", &points, day_spec::TouchPhase::Began)
4302                    .await?;
4303                d.assert_text("state", "2 down ids 0+1 last 50,30").await?;
4304                d.touches("target", &points, day_spec::TouchPhase::Ended)
4305                    .await?;
4306                d.assert_text("state", "0 down ids 0+1 last 50,30").await
4307            })
4308    }
4309
4310    /// A hit slop changes neither the piece's frame nor its neighbor's, and the piece still
4311    /// takes its tap. That a press in the slop area lands on it is the platform's hit test,
4312    /// which injected input does not exercise (docs/gestures.md "Hit slop").
4313    #[day_macros::test(day_core)]
4314    fn hit_slop_leaves_layout_alone() -> Case {
4315        Case::new()
4316            .proves_modifier("hit_slop")
4317            .proves_duty("set_hit_slop")
4318            .proves_cap(Cap::HitSlop)
4319            .page(|| {
4320                let taps = Signal::new(0i64);
4321                column((
4322                    label(move || format!("taps {}", taps.get())).id(day_core::id!(taps)),
4323                    row((
4324                        rectangle()
4325                            .fill(Color::rgb(0.9, 0.2, 0.2))
4326                            .frame(12.0, 12.0)
4327                            .hit_slop(30.0)
4328                            .on_tap(move || taps.update(|n| *n += 1))
4329                            .id(day_core::id!(dot)),
4330                        rectangle()
4331                            .fill(Color::rgb(0.2, 0.4, 0.9))
4332                            .frame(12.0, 12.0)
4333                            .id(day_core::id!(next)),
4334                    ))
4335                    .spacing(4.0),
4336                ))
4337                .align(HAlign::Leading)
4338            })
4339            .drive(|d: Drive| async move {
4340                d.assert_frame("dot", size(12.0, 12.0)).await?;
4341                d.assert_frame(
4342                    "next",
4343                    FrameExpect {
4344                        x: Some(16.0),
4345                        y: Some(0.0),
4346                        relative_to: Some("dot".into()),
4347                        ..FrameExpect::default()
4348                    },
4349                )
4350                .await?;
4351                d.tap("dot").await?;
4352                d.assert_text("taps", "taps 1").await
4353            })
4354    }
4355
4356    /// An interaction state follows hover, press and focus, each on its own.
4357    #[day_macros::test(day_core)]
4358    fn interaction_state_tracks_hover_press_focus() -> Case {
4359        Case::new()
4360            .proves_modifier("interaction")
4361            .page(|| {
4362                let state = InteractionState::new();
4363                column((
4364                    label(move || {
4365                        format!(
4366                            "hovered {} pressed {} focused {}",
4367                            state.hovered(),
4368                            state.pressed(),
4369                            state.focused()
4370                        )
4371                    })
4372                    .id(day_core::id!(state)),
4373                    pad(day_core::id!(target)).focusable().interaction(state),
4374                ))
4375            })
4376            .drive(|d: Drive| async move {
4377                d.assert_text("state", "hovered false pressed false focused false")
4378                    .await?;
4379                d.hover("target", None).await?;
4380                d.assert_text("state", "hovered true pressed false focused false")
4381                    .await?;
4382                d.press("target", true).await?;
4383                d.assert_text("state", "hovered true pressed true focused false")
4384                    .await?;
4385                d.press("target", false).await?;
4386                d.hover_leave("target").await?;
4387                d.assert_text("state", "hovered false pressed false focused false")
4388                    .await?;
4389                d.focus("target").await?;
4390                d.assert_text("state", "hovered false pressed false focused true")
4391                    .await
4392            })
4393    }
4394
4395    /// A reactive modifier reads the interaction state: the background follows the press.
4396    #[day_macros::test(day_core)]
4397    fn interaction_state_drives_background() -> Case {
4398        Case::new()
4399            .proves_modifier("interaction")
4400            .requires(Cap::Snapshot)
4401            .page(|| {
4402                let state = InteractionState::new();
4403                label("")
4404                    .frame(80.0, 40.0)
4405                    .interaction(state)
4406                    .background(move || {
4407                        if state.pressed() {
4408                            Color::rgb(1.0, 0.0, 0.0)
4409                        } else {
4410                            Color::rgb(0.0, 0.0, 1.0)
4411                        }
4412                    })
4413                    .id(day_core::id!(card))
4414            })
4415            .drive(|d: Drive| async move {
4416                d.sample_pixel("card", 0.5, 0.5, "#0000ff").await?;
4417                d.press("card", true).await?;
4418                d.sample_pixel("card", 0.5, 0.5, "#ff0000").await?;
4419                d.press("card", false).await?;
4420                d.sample_pixel("card", 0.5, 0.5, "#0000ff").await
4421            })
4422    }
4423
4424    /// `.enabled(false)` disables the controls in a subtree natively and stops its gestures;
4425    /// enabling it again restores both.
4426    #[day_macros::test(day_core)]
4427    fn enabled_disables_subtree() -> Case {
4428        Case::new()
4429            .proves_modifier("enabled")
4430            .proves_duty("set_subtree_enabled")
4431            .page(|| {
4432                let on = Signal::new(true);
4433                let presses = Signal::new(0i64);
4434                let drags = Signal::new(0i64);
4435                let pressed = Signal::new(false);
4436                column((
4437                    label(move || {
4438                        format!(
4439                            "presses {} drags {} pressed {}",
4440                            presses.get(),
4441                            drags.get(),
4442                            pressed.get()
4443                        )
4444                    })
4445                    .id(day_core::id!(state)),
4446                    button("Flip")
4447                        .action(move || on.update(|v| *v = !*v))
4448                        .id(day_core::id!(flip)),
4449                    column((
4450                        button("Inner")
4451                            .action(move || presses.update(|n| *n += 1))
4452                            .id(day_core::id!(inner)),
4453                        pad(day_core::id!(target))
4454                            .on_pressed(move |down| pressed.set(down))
4455                            .on_drag(move |d: Drag| {
4456                                if d.phase == DragPhase::Ended {
4457                                    drags.update(|n| *n += 1);
4458                                }
4459                            }),
4460                    ))
4461                    .enabled(on),
4462                ))
4463            })
4464            .drive(|d: Drive| async move {
4465                let native = |enabled| NativeExpect {
4466                    enabled: Some(enabled),
4467                    ..NativeExpect::default()
4468                };
4469                d.assert_enabled("inner", true).await?;
4470                d.drag("target", (10.0, 10.0), (60.0, 10.0)).await?;
4471                d.assert_text("state", "presses 0 drags 1 pressed false")
4472                    .await?;
4473                // Disabled while pressed: the press ends, and nothing more arrives.
4474                d.press("target", true).await?;
4475                d.assert_text("state", "presses 0 drags 1 pressed true")
4476                    .await?;
4477                d.tap("flip").await?;
4478                d.assert_text("state", "presses 0 drags 1 pressed false")
4479                    .await?;
4480                d.assert_enabled("inner", false).await?;
4481                d.assert_native("inner", native(false)).await?;
4482                d.drag("target", (10.0, 10.0), (60.0, 10.0)).await?;
4483                d.press("target", true).await?;
4484                d.assert_text("state", "presses 0 drags 1 pressed false")
4485                    .await?;
4486                d.tap("flip").await?;
4487                d.assert_enabled("inner", true).await?;
4488                d.assert_native("inner", native(true)).await?;
4489                d.tap("inner").await?;
4490                d.drag("target", (10.0, 10.0), (60.0, 10.0)).await?;
4491                d.assert_text("state", "presses 1 drags 2 pressed false")
4492                    .await
4493            })
4494    }
4495
4496    /// A key reports each phase of its press: down and repeat reach `.on_key`, the release
4497    /// reaches `.on_key_up`, and the key is typed.
4498    #[day_macros::test(day_core)]
4499    fn key_phases_reach_their_handlers() -> Case {
4500        Case::new()
4501            .proves_modifier("on_key_up")
4502            .proves_cap(Cap::KeyPhases)
4503            .page(|| {
4504                let counts = Signal::new((0i64, 0i64, 0i64));
4505                column((
4506                    label(move || {
4507                        let (down, repeat, up) = counts.get();
4508                        format!("down {down} repeat {repeat} up {up}")
4509                    })
4510                    .id(day_core::id!(state)),
4511                    pad(day_core::id!(target))
4512                        .focusable()
4513                        .on_key(move |k| {
4514                            if k.key == day_spec::Key::ArrowRight {
4515                                counts.update(|c| {
4516                                    if k.is_repeat() {
4517                                        c.1 += 1;
4518                                    } else {
4519                                        c.0 += 1;
4520                                    }
4521                                });
4522                            }
4523                        })
4524                        .on_key_up(move |k| {
4525                            if k.key == day_spec::Key::ArrowRight && k.is_release() {
4526                                counts.update(|c| c.2 += 1);
4527                            }
4528                        }),
4529                ))
4530            })
4531            .drive(|d: Drive| async move {
4532                d.focus("target").await?;
4533                d.key(None, "ArrowRight").await?;
4534                d.assert_text("state", "down 1 repeat 0 up 0").await?;
4535                d.key_phase(None, "ArrowRight", day_spec::KeyPhase::Repeat)
4536                    .await?;
4537                d.key_phase(None, "ArrowRight", day_spec::KeyPhase::Repeat)
4538                    .await?;
4539                d.assert_text("state", "down 1 repeat 2 up 0").await?;
4540                d.key_phase(None, "ArrowRight", day_spec::KeyPhase::Up)
4541                    .await?;
4542                d.assert_text("state", "down 1 repeat 2 up 1").await
4543            })
4544    }
4545
4546    /// A focusable piece joins the focus system: it takes focus, says so, hears keys while
4547    /// it holds it, and gives it up to the next control.
4548    #[day_macros::test(day_core)]
4549    fn focusable_piece_holds_and_yields_focus() -> Case {
4550        Case::new()
4551            .proves_cap(Cap::Focusable)
4552            .proves_duty("set_focusable")
4553            .requires(Cap::Focusable)
4554            .page(|| {
4555                let focused = Signal::new(false);
4556                let keys = Signal::new(0i64);
4557                let text = Signal::new(String::new());
4558                column((
4559                    label(move || format!("focused {} keys {}", focused.get(), keys.get()))
4560                        .id(day_core::id!(state)),
4561                    pad(day_core::id!(target))
4562                        .focusable()
4563                        .focused(focused)
4564                        .on_key(move |_| keys.update(|n| *n += 1)),
4565                    text_field(text).id(day_core::id!(field)),
4566                ))
4567            })
4568            .drive(|d: Drive| async move {
4569                d.assert_text("state", "focused false keys 0").await?;
4570                d.focus("target").await?;
4571                d.assert_focused("target", true).await?;
4572                d.assert_text("state", "focused true keys 0").await?;
4573                d.key(None, "ArrowDown").await?;
4574                d.assert_text("state", "focused true keys 1").await?;
4575                // Focus moves to the field: the piece reports the loss.
4576                d.focus("field").await?;
4577                d.assert_focused("field", true).await?;
4578                d.assert_focused("target", false).await?;
4579                d.assert_text("state", "focused false keys 1").await
4580            })
4581    }
4582
4583    /// The input kind follows what the platform reports, and readers of it update.
4584    #[day_macros::test(day_core)]
4585    fn primary_pointer_follows_input() -> Case {
4586        Case::new()
4587            .proves_duty("primary_pointer")
4588            .page(|| label(move || day_core::primary_pointer().name()).id(day_core::id!(kind)))
4589            .drive(|d: Drive| async move {
4590                let before = untrack(day_core::primary_pointer);
4591                d.pointer(day_spec::PointerKind::Touch).await?;
4592                d.assert_text("kind", "touch").await?;
4593                d.pointer(day_spec::PointerKind::Stylus).await?;
4594                d.assert_text("kind", "stylus").await?;
4595                d.pointer(day_spec::PointerKind::Mouse).await?;
4596                d.assert_text("kind", "mouse").await?;
4597                // Leave the app as the platform had it.
4598                d.pointer(before).await
4599            })
4600    }
4601
4602    /// A drop target hears the drag come over it, leave, and drop, and each hover ends once.
4603    #[day_macros::test(day_core)]
4604    fn drop_target_reports_enter_leave_drop() -> Case {
4605        Case::new()
4606            .proves_modifier("drop_target")
4607            .proves_duty("set_drop_target")
4608            .page(|| {
4609                let hovering = Signal::new(0i64);
4610                let got = Signal::new(String::from("nothing"));
4611                column((
4612                    label(move || format!("hovering {} got {}", hovering.get(), got.get()))
4613                        .id(day_core::id!(state)),
4614                    pad(day_core::id!(zone)).drop_target(
4615                        DropTarget::new(["text/plain"])
4616                            .on_enter(move |_| hovering.update(|n| *n += 1))
4617                            .on_leave(move || hovering.update(|n| *n -= 1))
4618                            .on_drop(move |drop| {
4619                                let text = drop
4620                                    .items
4621                                    .first()
4622                                    .and_then(|item| item.get("text/plain"))
4623                                    .and_then(|bytes| std::str::from_utf8(bytes).ok());
4624                                got.set(text.unwrap_or("?").to_owned());
4625                                text.is_some()
4626                            }),
4627                    ),
4628                ))
4629            })
4630            .drive(|d: Drive| async move {
4631                d.drag_enter("zone", "hello").await?;
4632                // The platform asks again as the drag moves: still one hover.
4633                d.drag_enter("zone", "hello").await?;
4634                d.assert_text("state", "hovering 1 got nothing").await?;
4635                d.drag_leave("zone").await?;
4636                d.assert_text("state", "hovering 0 got nothing").await?;
4637                d.drop_text("zone", "hello").await?;
4638                d.assert_text("state", "hovering 0 got hello").await
4639            })
4640    }
4641
4642    /// `.on_files_dropped` hands over the local paths of the dropped files.
4643    #[day_macros::test(day_core)]
4644    fn on_files_dropped_receives_paths() -> Case {
4645        Case::new()
4646            .proves_modifier("on_files_dropped")
4647            .page(|| {
4648                let got = Signal::new(String::from("none"));
4649                column((
4650                    label(move || format!("files {}", got.get())).id(day_core::id!(state)),
4651                    pad(day_core::id!(zone)).on_files_dropped(move |paths| {
4652                        let names: Vec<String> = paths
4653                            .iter()
4654                            .filter_map(|p| p.file_name())
4655                            .map(|n| n.to_string_lossy().into_owned())
4656                            .collect();
4657                        got.set(names.join("+"));
4658                    }),
4659                ))
4660            })
4661            .drive(|d: Drive| async move {
4662                d.drop_files("zone", &["/work/first.txt", "/work/second%20draft.md"])
4663                    .await?;
4664                d.assert_text("state", "files first.txt+second draft.md")
4665                    .await
4666            })
4667    }
4668
4669    /// A focus binding moves focus when the app sets it, and follows the field when it is
4670    /// focused natively.
4671    #[day_macros::test(day_core)]
4672    fn focused_binding_moves_focus() -> Case {
4673        Case::new()
4674            .proves_modifier("focused")
4675            .page(|| {
4676                let want = Signal::new(false);
4677                column((
4678                    label(move || format!("focused {}", want.get())).id(day_core::id!(state)),
4679                    button("Focus")
4680                        .action(move || want.set(true))
4681                        .id(day_core::id!(go)),
4682                    text_field(Signal::new(String::new()))
4683                        .focused(want)
4684                        .id(day_core::id!(field)),
4685                ))
4686            })
4687            .drive(|d: Drive| async move {
4688                d.assert_focused("field", false).await?;
4689                d.tap("go").await?;
4690                d.assert_focused("field", true).await?;
4691                d.assert_text("state", "focused true").await
4692            })
4693    }
4694
4695    /// Destroy a focused input and its containing page without first moving focus to a
4696    /// button. Win32 GTK must detach the IME filter before the input loses its native root.
4697    #[day_macros::test(day_core)]
4698    fn focused_inputs_survive_page_removal() -> Case {
4699        Case::new()
4700            .proves_duty("focus")
4701            .page(|| {
4702                let shown = Signal::new(true);
4703                column((
4704                    button("Toggle page")
4705                        .action(move || shown.set(!shown.get()))
4706                        .id(day_core::id!(toggle)),
4707                    text_field(Signal::new(String::new())).id(day_core::id!(survivor)),
4708                    when(
4709                        move || shown.get(),
4710                        || {
4711                            column((
4712                                text_field(Signal::new(String::new())).id(day_core::id!(entry)),
4713                            ))
4714                            .background(Color::rgb(0.5, 0.5, 0.5))
4715                        },
4716                    ),
4717                ))
4718            })
4719            .drive(|d: Drive| async move {
4720                for _ in 0..4 {
4721                    d.focus("entry").await?;
4722                    d.assert_focused("entry", true).await?;
4723                    // Scripted activation doesn't move native focus to the button first.
4724                    d.tap("toggle").await?;
4725                    d.assert_missing("entry").await?;
4726                    d.wait_idle().await?;
4727                    d.tap("toggle").await?;
4728                }
4729                d.focus("survivor").await?;
4730                d.tap("toggle").await?;
4731                d.assert_focused("survivor", true).await?;
4732                d.input("survivor", "still editable").await?;
4733                d.assert_text("survivor", "still editable").await
4734            })
4735    }
4736
4737    // ---- layout and the remaining modifiers -------------------------------------------------
4738
4739    /// `.height` fixes the height and leaves the width to the layout.
4740    #[day_macros::test(day_core)]
4741    fn height_fixes_height() -> Case {
4742        Case::new()
4743            .proves_modifier("height")
4744            .page(|| {
4745                column((rectangle()
4746                    .fill(Color::rgb(1.0, 0.0, 0.0))
4747                    .id(day_core::id!(bar))
4748                    .height(37.0),))
4749                .width(100.0)
4750            })
4751            .drive(|d: Drive| async move {
4752                d.assert_frame(
4753                    "bar",
4754                    FrameExpect {
4755                        height: Some(37.0),
4756                        ..Default::default()
4757                    },
4758                )
4759                .await
4760            })
4761    }
4762
4763    /// `.grow(Dimension::Height)` takes the height its column has left, in a column and in a row alike.
4764    #[day_macros::test(day_core)]
4765    fn grow_vertical_fills_column() -> Case {
4766        Case::new()
4767            .proves_modifier("grow")
4768            .page(|| {
4769                row((
4770                    column((
4771                        rectangle()
4772                            .fill(Color::rgb(1.0, 0.0, 0.0))
4773                            .id(day_core::id!(top))
4774                            .frame(40.0, 20.0),
4775                        rectangle()
4776                            .fill(Color::rgb(0.0, 0.0, 1.0))
4777                            .id(day_core::id!(rest))
4778                            .width(40.0)
4779                            .grow(Dimension::Height),
4780                    ))
4781                    .spacing(0.0)
4782                    .height(120.0),
4783                    rectangle()
4784                        .fill(Color::rgb(0.0, 1.0, 0.0))
4785                        .id(day_core::id!(both))
4786                        .width(30.0)
4787                        .grow(Dimension::Height),
4788                ))
4789                .spacing(0.0)
4790                .align(VAlign::Top)
4791                .height(120.0)
4792            })
4793            .drive(|d: Drive| async move {
4794                d.assert_frame(
4795                    "rest",
4796                    FrameExpect {
4797                        height: Some(100.0),
4798                        ..Default::default()
4799                    },
4800                )
4801                .await?;
4802                d.assert_frame(
4803                    "both",
4804                    FrameExpect {
4805                        height: Some(120.0),
4806                        ..Default::default()
4807                    },
4808                )
4809                .await
4810            })
4811    }
4812
4813    /// A grid cell spans the columns it asks for, and aligns within its cell as asked.
4814    #[day_macros::test(day_core)]
4815    fn grid_span_and_align() -> Case {
4816        Case::new()
4817            .proves_modifier("grid_span")
4818            .proves_modifier("grid_align")
4819            .page(|| {
4820                let cell = |id: day_core::ElementId, w: f64| {
4821                    rectangle()
4822                        .fill(Color::rgb(0.2, 0.4, 0.9))
4823                        .id(id)
4824                        .frame(w, 20.0)
4825                };
4826                grid((
4827                    grid_row((cell(day_core::id!(a), 40.0), cell(day_core::id!(b), 60.0))),
4828                    grid_row((cell(day_core::id!(wide), 30.0)
4829                        .grid_align(day_core::Alignment::TopTrailing)
4830                        .grid_span(2),)),
4831                ))
4832                .spacing(0.0)
4833                .align(day_core::Alignment::TopLeading)
4834            })
4835            .drive(|d: Drive| async move {
4836                // The spanning cell's rect is both columns, 100 wide; trailing puts its
4837                // 30-wide content at x 70 from the first column's start.
4838                d.assert_frame(
4839                    "wide",
4840                    FrameExpect {
4841                        x: Some(70.0),
4842                        relative_to: Some("a".into()),
4843                        ..Default::default()
4844                    },
4845                )
4846                .await
4847            })
4848    }
4849
4850    /// `.overlay` draws its piece centered over the content.
4851    #[day_macros::test(day_core)]
4852    fn overlay_centers() -> Case {
4853        Case::new()
4854            .proves_modifier("overlay")
4855            .requires(Cap::Snapshot)
4856            .page(|| {
4857                rectangle()
4858                    .fill(Color::rgb(1.0, 0.0, 0.0))
4859                    .frame(90.0, 90.0)
4860                    .overlay(
4861                        rectangle()
4862                            .fill(Color::rgb(0.0, 0.0, 1.0))
4863                            .frame(30.0, 30.0),
4864                    )
4865                    .id(day_core::id!(base))
4866            })
4867            .drive(|d: Drive| async move {
4868                d.sample_pixel("base", 0.5, 0.5, "#0000ff").await?;
4869                d.sample_pixel("base", 0.1, 0.1, "#ff0000").await
4870            })
4871    }
4872
4873    /// `.transform` takes a whole transform: here a translation and a scale together.
4874    #[day_macros::test(day_core)]
4875    fn transform_applies_whole() -> Case {
4876        Case::new()
4877            .proves_duty("set_transform")
4878            .proves_modifier("transform")
4879            .requires(Cap::Snapshot)
4880            .page(|| {
4881                zstack((
4882                    rectangle().fill(Color::WHITE),
4883                    label("")
4884                        .frame(20.0, 20.0)
4885                        .background(Color::rgb(0.0, 0.0, 1.0))
4886                        .transform(Transform {
4887                            tx: 30.0,
4888                            sx: 2.0,
4889                            sy: 2.0,
4890                            ..Transform::default()
4891                        }),
4892                ))
4893                .id(day_core::id!(ground))
4894                .frame(120.0, 60.0)
4895            })
4896            .drive(|d: Drive| async move {
4897                // Centered at x 60, moved to 90, scaled to 40 wide: 70..110 of 120.
4898                d.sample_pixel("ground", 0.75, 0.5, "#0000ff").await?;
4899                d.sample_pixel("ground", 0.5, 0.5, "#ffffff").await
4900            })
4901    }
4902
4903    /// An implicit animation still lands on the final value: a square slid across by an
4904    /// animated translation ends where the translation says.
4905    #[day_macros::test(day_core)]
4906    fn animation_lands_on_final() -> Case {
4907        Case::new()
4908            .proves_modifier("animation")
4909            .requires(Cap::Snapshot)
4910            .page(|| {
4911                let moved = Signal::new(false);
4912                column((
4913                    button("Move")
4914                        .action(move || moved.set(true))
4915                        .id(day_core::id!(move_button)),
4916                    zstack((
4917                        rectangle().fill(Color::WHITE),
4918                        label("")
4919                            .frame(40.0, 40.0)
4920                            .background(Color::rgb(0.0, 0.0, 1.0))
4921                            .translation(move || if moved.get() { 80.0 } else { 0.0 }, 0.0)
4922                            .animation(day_spec::AnimSpec::linear(150)),
4923                    ))
4924                    .align(day_core::Alignment::Leading)
4925                    .id(day_core::id!(ground))
4926                    .frame(120.0, 40.0),
4927                ))
4928            })
4929            .drive(|d: Drive| async move {
4930                d.sample_pixel("ground", 0.1, 0.5, "#0000ff").await?;
4931                d.tap("move_button").await?;
4932                d.wait_idle().await?;
4933                d.pause(0.4).await?;
4934                d.sample_pixel("ground", 0.85, 0.5, "#0000ff").await?;
4935                d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
4936            })
4937    }
4938
4939    /// Each way of naming an element finds it: a fixed id, a derived one, a keyed one.
4940    #[day_macros::test(day_core)]
4941    fn ids_name_elements() -> Case {
4942        Case::new()
4943            .proves_modifier("id")
4944            .proves_modifier("id_of")
4945            .page(|| {
4946                let n = Signal::new(1i64);
4947                column((
4948                    label("Fixed").id(day_core::id!(fixed)),
4949                    label("Derived").id_of(move || day_core::id!(derived, n.get())),
4950                    label("Keyed").id(day_core::id!(keyed, 7)),
4951                    button("Next")
4952                        .action(move || n.set(2))
4953                        .id(day_core::id!(next)),
4954                ))
4955            })
4956            .drive(|d: Drive| async move {
4957                d.assert_text("fixed", "Fixed").await?;
4958                d.assert_text("keyed:7", "Keyed").await?;
4959                d.assert_text("derived:1", "Derived").await?;
4960                d.tap("next").await?;
4961                d.assert_missing("derived:1").await?;
4962                d.assert_text("derived:2", "Derived").await
4963            })
4964    }
4965
4966    /// `.tweak` runs with the realized node, and `.native_ref` holds it while the piece lives.
4967    #[day_macros::test(day_core)]
4968    fn tweak_and_native_ref_see_node() -> Case {
4969        Case::new()
4970            .proves_modifier("tweak")
4971            .proves_modifier("native_ref")
4972            .page(|| {
4973                let tweaked = Signal::new(false);
4974                let r = NativeRef::new();
4975                let held = r.clone();
4976                column((
4977                    label(move || format!("tweaked {}", tweaked.get())).id(day_core::id!(tweaked)),
4978                    label(move || format!("held {}", held.node().is_some()))
4979                        .id(day_core::id!(held)),
4980                    label("Target")
4981                        .tweak(move |_node| tweaked.set(true))
4982                        .native_ref(&r),
4983                ))
4984            })
4985            .drive(|d: Drive| async move {
4986                d.assert_text("tweaked", "tweaked true").await?;
4987                d.assert_text("held", "held true").await
4988            })
4989    }
4990
4991    /// `.modifier` applies a reusable modifier: here, a closure that pads.
4992    #[day_macros::test(day_core)]
4993    fn modifier_applies() -> Case {
4994        Case::new()
4995            .proves_modifier("modifier")
4996            .page(|| {
4997                let padded = |content: AnyPiece| content.padding(10.0).any();
4998                column((label("Inner")
4999                    .id(day_core::id!(inner))
5000                    .modifier(padded)
5001                    .id(day_core::id!(outer)),))
5002                .align(HAlign::Leading)
5003            })
5004            .drive(|d: Drive| async move {
5005                d.assert_frame(
5006                    "inner",
5007                    FrameExpect {
5008                        x: Some(10.0),
5009                        y: Some(10.0),
5010                        relative_to: Some("outer".into()),
5011                        ..Default::default()
5012                    },
5013                )
5014                .await
5015            })
5016    }
5017
5018    /// An announcement reaches the screen reader (the toolkit's `announce`) and the run.
5019    #[day_macros::test(day_core)]
5020    fn announce_reaches_reader() -> Case {
5021        Case::new()
5022            .proves_duty("announce")
5023            .proves_cap(Cap::Announce)
5024            .page(|| {
5025                button("Save")
5026                    .action(|| day_core::announce("Saved"))
5027                    .id(day_core::id!(save))
5028            })
5029            .drive(|d: Drive| async move {
5030                d.tap("save").await?;
5031                d.assert_announced("Saved").await
5032            })
5033    }
5034}
5035
5036#[cfg(test)]
5037mod transfer_tests {
5038    use super::*;
5039    use day_spec::transfer::*;
5040
5041    #[test]
5042    fn transfer_callbacks_restore_owner_scope_and_reject_after_disposal() {
5043        let owner = Scope::child();
5044        let foreign = Scope::child();
5045        foreign.provide(22u32);
5046        let hovers = Rc::new(Cell::new(0i32));
5047        let leaves = Rc::new(Cell::new(0i32));
5048        let counts = (hovers.clone(), leaves.clone());
5049        let (source, target) = owner.enter(|| {
5050            owner.provide(11u32);
5051            let check = || assert_eq!(day_core::environment::<u32>(), Some(11));
5052            let (hovers, leaves) = counts;
5053            let entered = hovers.clone();
5054            (
5055                scoped_drag_source(Rc::new(move |_| {
5056                    check();
5057                    Some(Offer::default())
5058                })),
5059                scoped_drop_target(
5060                    Target::new(Vec::<String>::new())
5061                        .accept(move |_| {
5062                            check();
5063                            Operation::Copy
5064                        })
5065                        .on_enter(move |_| {
5066                            check();
5067                            entered.set(entered.get() + 1);
5068                        })
5069                        .on_leave(move || {
5070                            check();
5071                            hovers.set(hovers.get() - 1);
5072                            leaves.set(leaves.get() + 1);
5073                        })
5074                        .on_drop(move |_| {
5075                            check();
5076                            true
5077                        }),
5078                ),
5079            )
5080        });
5081        let location = || Location {
5082            position: day_spec::Point::new(40., 20.),
5083            types: vec![],
5084            allowed: vec![Operation::Copy],
5085            local: true,
5086        };
5087        foreign.enter(|| {
5088            assert!(source(day_spec::Point::new(0., 0.)).is_some());
5089            // The hover is entered once however often the platform asks, and left once: by
5090            // the session leaving, and again by the drop that ends the next hover.
5091            assert_eq!(target.proposal(&location()), Operation::Copy);
5092            assert_eq!(target.proposal(&location()), Operation::Copy);
5093            assert_eq!((hovers.get(), leaves.get()), (1, 0));
5094            assert!(target.is_hovering());
5095            target.leave();
5096            target.leave();
5097            assert_eq!((hovers.get(), leaves.get()), (0, 1));
5098            assert_eq!(target.proposal(&location()), Operation::Copy);
5099            assert!(target.deliver(location(), Offer::default()));
5100            assert_eq!((hovers.get(), leaves.get()), (0, 2));
5101            assert!(!target.is_hovering());
5102            assert_eq!(day_core::environment::<u32>(), Some(22));
5103            owner.dispose();
5104            assert!(source(day_spec::Point::new(0., 0.)).is_none());
5105            assert_eq!(target.proposal(&location()), Operation::None);
5106            assert!(!target.deliver(location(), Offer::default()));
5107            assert_eq!((hovers.get(), leaves.get()), (0, 2));
5108        });
5109        foreign.dispose();
5110    }
5111}