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