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