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