Skip to main content

day_pieces/
decorators.rs

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