Skip to main content

day_pieces/
shapes.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! High-level vector shapes atop the canvas display list: `rectangle`, `circle`, `ellipse`,
5//! `capsule`, `rounded_rectangle`, `arc`, `line`, and `polygon`, combined with `shape_group`.
6//! Reactive fill/stroke, rotation/scale/translation transforms, and tap/drag gestures.
7
8use std::rc::Rc;
9
10use day_core::*;
11use day_spec::{Angle, Event, Ink, Paint, Point, Rect, Shape, Size, UnitPoint};
12
13use crate::*;
14
15// ---------------------------------------------------------------------------
16// Shapes (docs/shapes.md): high-level shape pieces atop the canvas display list. Frame-relative
17// geometry, reactive fill/stroke, rotation/scale/translation transforms, and tap/drag gestures.
18// ---------------------------------------------------------------------------
19
20use day_geometry::Affine;
21pub use day_spec::{DragPhase, GestureKind};
22
23/// A shape's geometry, resolved against the rect layout assigns it (frame-relative, SwiftUI-style).
24#[derive(Clone, Debug, PartialEq)]
25pub enum ShapeKind {
26    Rectangle,
27    RoundedRectangle {
28        corner: Corner,
29    },
30    Circle,
31    Ellipse,
32    Capsule,
33    /// A stroked arc of the inscribed ellipse; `start` from +x, both positive clockwise.
34    Arc {
35        start: Angle,
36        sweep: Angle,
37    },
38    /// A stroked segment between two unit points of the resolved rect (stroke-only; fills are
39    /// ignored). Unit points resolve unclamped, like every unit-space resolve.
40    Line {
41        from: UnitPoint,
42        to: UnitPoint,
43    },
44    /// A filled/stroked polygon of unit points resolved against the rect (unclamped: points may
45    /// sit outside 0..1).
46    Polygon {
47        points: Rc<[UnitPoint]>,
48    },
49}
50
51/// A corner radius, for a shape (`rounded_rectangle(..)`) and a view (`.corner_radius(..)`,
52/// [`Surface::corner_radius`]) alike: absolute points, or a `0..=1` fraction of half the
53/// shorter side, which follows the frame as it resizes. `f64` and [`Radius`] convert.
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub enum Corner {
56    Fixed(f64),
57    Fraction(f64),
58}
59impl From<f64> for Corner {
60    fn from(v: f64) -> Self {
61        Corner::Fixed(v)
62    }
63}
64impl From<Radius> for Corner {
65    fn from(r: Radius) -> Self {
66        Corner::Fixed(r.points())
67    }
68}
69impl Default for Corner {
70    /// Square.
71    fn default() -> Self {
72        Corner::Fixed(0.0)
73    }
74}
75impl Corner {
76    /// Round ends: half the shorter side, a capsule or a circle.
77    pub const CAPSULE: Corner = Corner::Fraction(1.0);
78
79    /// The radius in points in a frame of `size`: at most half the shorter side.
80    #[must_use]
81    pub fn points(self, size: Size) -> f64 {
82        let cap = (size.width.min(size.height) / 2.0).max(0.0);
83        match self {
84            Corner::Fixed(v) => v.clamp(0.0, cap),
85            Corner::Fraction(f) => f.clamp(0.0, 1.0) * cap,
86        }
87    }
88    /// Whether the radius depends on the frame.
89    #[must_use]
90    pub fn is_relative(self) -> bool {
91        matches!(self, Corner::Fraction(_))
92    }
93    fn resolve(self, rect: Rect) -> f64 {
94        self.points(rect.size)
95    }
96}
97impl ShapeKind {
98    /// Lower to a drawable geometry within `rect`.
99    fn geometry(self, rect: Rect) -> Shape {
100        match self {
101            ShapeKind::Rectangle => Shape::Rect(rect),
102            ShapeKind::RoundedRectangle { corner } => {
103                Shape::RoundedRect(rect, corner.resolve(rect))
104            }
105            ShapeKind::Ellipse => Shape::Ellipse(rect),
106            ShapeKind::Capsule => {
107                Shape::RoundedRect(rect, rect.size.width.min(rect.size.height) / 2.0)
108            }
109            ShapeKind::Circle => {
110                let d = rect.size.width.min(rect.size.height);
111                let c = rect.center();
112                Shape::Ellipse(Rect::new(c.x - d / 2.0, c.y - d / 2.0, d, d))
113            }
114            ShapeKind::Arc { start, sweep } => Shape::Arc { rect, start, sweep },
115            ShapeKind::Line { from, to } => Shape::Line(from.resolve(rect), to.resolve(rect)),
116            ShapeKind::Polygon { points } => {
117                Shape::Polygon(points.iter().map(|p| p.resolve(rect)).collect())
118            }
119        }
120    }
121    /// Point-in-shape test (in the shape's own, untransformed coordinates).
122    fn contains(self, rect: Rect, p: Point) -> bool {
123        fn in_rect(r: Rect, p: Point) -> bool {
124            p.x >= r.min_x() && p.x <= r.max_x() && p.y >= r.min_y() && p.y <= r.max_y()
125        }
126        fn in_ellipse(r: Rect, p: Point) -> bool {
127            if r.size.width <= 0.0 || r.size.height <= 0.0 {
128                return false;
129            }
130            let c = r.center();
131            let dx = (p.x - c.x) / (r.size.width / 2.0);
132            let dy = (p.y - c.y) / (r.size.height / 2.0);
133            dx * dx + dy * dy <= 1.0
134        }
135        /// Even-odd ray cast: count edge crossings of the +x ray from `p`.
136        fn in_polygon(pts: &[Point], p: Point) -> bool {
137            if pts.len() < 3 {
138                return false;
139            }
140            let mut inside = false;
141            let mut j = pts.len() - 1;
142            for i in 0..pts.len() {
143                let (a, b) = (pts[i], pts[j]);
144                if (a.y > p.y) != (b.y > p.y) {
145                    let x = a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x);
146                    if p.x < x {
147                        inside = !inside;
148                    }
149                }
150                j = i;
151            }
152            inside
153        }
154        match self.geometry(rect) {
155            Shape::Ellipse(r) => in_ellipse(r, p),
156            Shape::Rect(r) | Shape::RoundedRect(r, _) => in_rect(r, p),
157            Shape::Polygon(pts) => in_polygon(&pts, p),
158            _ => in_rect(rect, p), // arc / line: bounding-box fallback
159        }
160    }
161}
162
163/// Drag info delivered to an `.on_drag` handler (docs/gestures.md "Gestures").
164///
165/// `translation` is cumulative from where the pointer went down; `location` is where it is
166/// now, in the piece's own coordinates. The two are not redundant, because `Began` does not
167/// always arrive at the press: a backend whose recognizer has to watch a few events before it
168/// calls the gesture a drag (appkit raises `Began` on the first drag event) reports where it
169/// recognized the drag, with the translation from the press already applied. So the press is
170/// [`Drag::start`] (`location - translation`) on every backend and in every phase; take the
171/// anchor from there rather than from `Began`'s `location`, or a gesture measured from the
172/// anchor trails the pointer by however far it moved before the recognizer engaged.
173///
174/// `velocity` is how fast the pointer is moving, in points per second: at `Ended` it is the
175/// release velocity a fling or a spring starts from.
176#[derive(Clone, Copy, Debug, PartialEq)]
177#[non_exhaustive]
178pub struct Drag {
179    pub phase: DragPhase,
180    pub location: Point,
181    pub translation: Point,
182    /// Points per second along the piece's axes. The platform recognizer's own measurement
183    /// at the release where it has one, Day's estimate from the last tenth of a second of
184    /// movement otherwise; zero once the pointer has rested that long.
185    pub velocity: Point,
186}
187
188impl Drag {
189    /// A drag event with no velocity; [`Drag::with_velocity`] adds one.
190    #[must_use]
191    pub fn new(phase: DragPhase, location: Point, translation: Point) -> Drag {
192        Drag {
193            phase,
194            location,
195            translation,
196            velocity: Point::ZERO,
197        }
198    }
199
200    /// This event with a velocity, in points per second.
201    #[must_use]
202    pub fn with_velocity(mut self, velocity: Point) -> Drag {
203        self.velocity = velocity;
204        self
205    }
206
207    /// Where the pointer went down, in the piece's coordinates: `location - translation`.
208    #[must_use]
209    pub fn start(&self) -> Point {
210        Point::new(
211            self.location.x - self.translation.x,
212            self.location.y - self.translation.y,
213        )
214    }
215
216    /// The release speed, in points per second: the length of [`Drag::velocity`].
217    #[must_use]
218    pub fn speed(&self) -> f64 {
219        self.velocity.x.hypot(self.velocity.y)
220    }
221}
222
223/// One pinch-gesture event, delivered to a `.on_pinch(…)` handler (docs/shapes.md). `scale`
224/// is cumulative since `Began` (1.0 = unchanged); `location` is the centroid, the anchor a
225/// zoom keeps stationary.
226#[derive(Clone, Copy, Debug, PartialEq)]
227#[non_exhaustive]
228pub struct Pinch {
229    pub phase: DragPhase,
230    pub scale: f64,
231    pub location: Point,
232}
233
234impl Pinch {
235    /// A pinch event.
236    #[must_use]
237    pub fn new(phase: DragPhase, scale: f64, location: Point) -> Pinch {
238        Pinch {
239            phase,
240            scale,
241            location,
242        }
243    }
244}
245
246/// One rotation-gesture event, delivered to a `.on_rotate(…)` handler (docs/canvas.md "Zoom
247/// and pan").
248#[derive(Clone, Copy, Debug, PartialEq)]
249#[non_exhaustive]
250pub struct Rotate {
251    pub phase: DragPhase,
252    /// Cumulative since `Began` for a two-finger gesture; a trackpad tick is a lone `Changed`
253    /// carrying that tick's own angle. Positive is clockwise on screen.
254    pub rotation: Angle,
255    /// The gesture's centroid in canvas coordinates (`Point::ZERO` where unknown, as Pinch does).
256    pub location: Point,
257}
258
259impl Rotate {
260    /// A rotation event.
261    #[must_use]
262    pub fn new(phase: DragPhase, rotation: Angle, location: Point) -> Rotate {
263        Rotate {
264            phase,
265            rotation,
266            location,
267        }
268    }
269}
270
271/// One pan-gesture event, delivered to a `.on_pan(…)` handler (docs/shapes.md). `delta` is
272/// the movement since the previous event, so apply it incrementally; a discrete wheel tick
273/// arrives as a lone `Changed`. `velocity` is how fast the pan is moving, in points per
274/// second, measured the way [`Drag::velocity`] is.
275#[derive(Clone, Copy, Debug, PartialEq)]
276#[non_exhaustive]
277pub struct Pan {
278    pub phase: DragPhase,
279    pub delta: Point,
280    pub location: Point,
281    /// Points per second; see [`Drag::velocity`].
282    pub velocity: Point,
283}
284
285impl Pan {
286    /// A pan event with no velocity; [`Pan::with_velocity`] adds one.
287    #[must_use]
288    pub fn new(phase: DragPhase, delta: Point, location: Point) -> Pan {
289        Pan {
290            phase,
291            delta,
292            location,
293            velocity: Point::ZERO,
294        }
295    }
296
297    /// This event with a velocity, in points per second.
298    #[must_use]
299    pub fn with_velocity(mut self, velocity: Point) -> Pan {
300        self.velocity = velocity;
301        self
302    }
303}
304
305/// The drawable description of a shape: everything but gestures. Cloneable so [`shape_group`]
306/// can collect many descriptions into one canvas closure (docs/shapes.md §3.6).
307#[derive(Clone)]
308struct ShapeSpec {
309    kind: Reactive<ShapeKind>,
310    fill: Option<Reactive<Paint>>,
311    stroke: Option<(Reactive<Ink>, Reactive<f64>)>,
312    inset: Reactive<f64>,
313    rotation: Reactive<Angle>,
314    scale: Reactive<f64>,
315    translation: (Reactive<f64>, Reactive<f64>),
316    /// Unit-space sub-rect of the bounds this shape resolves in (`.at`).
317    at: Option<Rect>,
318}
319
320/// A shape piece: one data-oriented piece parameterized by `ShapeKind`, rendered atop the canvas.
321#[must_use]
322pub struct ShapePiece {
323    spec: ShapeSpec,
324    on_tap: Option<Rc<dyn Fn()>>,
325    on_drag: Option<Rc<dyn Fn(Drag)>>,
326}
327
328/// The unified constructor: `shape(ShapeKind::RoundedRectangle { corner: 12.0.into() })`.
329pub fn shape<M>(kind: impl IntoReactive<ShapeKind, M>) -> ShapePiece {
330    ShapePiece {
331        spec: ShapeSpec {
332            kind: kind.into_reactive(),
333            fill: None,
334            stroke: None,
335            inset: Reactive::Const(0.0),
336            rotation: Reactive::Const(Angle::ZERO),
337            scale: Reactive::Const(1.0),
338            translation: (Reactive::Const(0.0), Reactive::Const(0.0)),
339            at: None,
340        },
341        on_tap: None,
342        on_drag: None,
343    }
344}
345/// SwiftUI-ergonomic sugar; all build the same `ShapePiece`.
346pub fn rectangle() -> ShapePiece {
347    shape(ShapeKind::Rectangle)
348}
349pub fn circle() -> ShapePiece {
350    shape(ShapeKind::Circle)
351}
352pub fn ellipse() -> ShapePiece {
353    shape(ShapeKind::Ellipse)
354}
355pub fn capsule() -> ShapePiece {
356    shape(ShapeKind::Capsule)
357}
358pub fn rounded_rectangle(corner: impl Into<Corner>) -> ShapePiece {
359    shape(ShapeKind::RoundedRectangle {
360        corner: corner.into(),
361    })
362}
363/// A stroked arc of the frame's inscribed ellipse: `arc(Angle::deg(-90.0), Angle::deg(270.0))`.
364pub fn arc(start: Angle, sweep: Angle) -> ShapePiece {
365    shape(ShapeKind::Arc { start, sweep })
366}
367/// A stroked segment between two unit points of the frame: `line((0.16, 0.5), (0.84, 0.5))`.
368pub fn line(from: (f64, f64), to: (f64, f64)) -> ShapePiece {
369    shape(ShapeKind::Line {
370        from: UnitPoint::new(from.0, from.1),
371        to: UnitPoint::new(to.0, to.1),
372    })
373}
374/// A polygon of unit points of the frame: `polygon([(0.5, 0.0), (1.0, 1.0), (0.0, 1.0)])`.
375pub fn polygon(points: impl IntoIterator<Item = (f64, f64)>) -> ShapePiece {
376    shape(ShapeKind::Polygon {
377        points: points
378            .into_iter()
379            .map(|(x, y)| UnitPoint::new(x, y))
380            .collect(),
381    })
382}
383
384#[day_macros::builder(ShapePieceBuilder)]
385impl ShapePiece {
386    /// Fill with any [`Paint`]: a [`Color`](day_spec::Color), a
387    /// [`SystemColor`](day_spec::SystemColor), an [`Ink`], or a linear, radial or conic
388    /// gradient whose unit points resolve against the shape's bounds. Reactive like every
389    /// other property: `rectangle().fill(move || sky_gradient(state.get()))`.
390    pub fn fill<M>(mut self, paint: impl IntoReactive<Paint, M>) -> Self {
391        self.spec.fill = Some(paint.into_reactive());
392        self
393    }
394    pub fn stroke<M1, M2>(
395        mut self,
396        color: impl IntoReactive<Ink, M1>,
397        width: impl IntoReactive<f64, M2>,
398    ) -> Self {
399        self.spec.stroke = Some((color.into_reactive(), width.into_reactive()));
400        self
401    }
402    /// Uniform inset applied before resolving geometry (keeps strokes inside the frame).
403    pub fn inset<M>(mut self, v: impl IntoReactive<f64, M>) -> Self {
404        self.spec.inset = v.into_reactive();
405        self
406    }
407    /// Rotate the drawn shape clockwise about its center, as [`Decorate::rotation`] turns a
408    /// view.
409    pub fn rotation<M>(mut self, angle: impl IntoReactive<Angle, M>) -> Self {
410        self.spec.rotation = angle.into_reactive();
411        self
412    }
413    /// Scale the drawn shape about its center (uniform), as [`Decorate::scale`] scales a view.
414    pub fn scale<M>(mut self, s: impl IntoReactive<f64, M>) -> Self {
415        self.spec.scale = s.into_reactive();
416        self
417    }
418    /// Move the drawn shape within its frame by (`x`, `y`) points, as
419    /// [`Decorate::translation`] moves a view.
420    pub fn translation<M1, M2>(
421        mut self,
422        x: impl IntoReactive<f64, M1>,
423        y: impl IntoReactive<f64, M2>,
424    ) -> Self {
425        self.spec.translation = (x.into_reactive(), y.into_reactive());
426        self
427    }
428    /// Resolve this shape inside the fractional sub-rect `(fx, fy, fw, fh)` of its bounds
429    /// (unit-space, applied before [`Self::inset`]). The workhorse for composing glyphs in a
430    /// [`shape_group`], mirroring hand-drawn `Rect::new(ox + fx * s, oy + fy * s, …)` canvas code.
431    pub fn at(mut self, fx: f64, fy: f64, fw: f64, fh: f64) -> Self {
432        self.spec.at = Some(Rect::new(fx, fy, fw, fh));
433        self
434    }
435    /// Fire when the shape is tapped (path-precise: the tap is tested against the resolved path).
436    pub fn on_tap(mut self, f: impl Fn() + 'static) -> Self {
437        self.on_tap = Some(Rc::new(f));
438        self
439    }
440    /// Fire on each phase of a drag over the shape.
441    pub fn on_drag(mut self, f: impl Fn(Drag) + 'static) -> Self {
442        self.on_drag = Some(Rc::new(f));
443        self
444    }
445}
446
447/// Compose the shape's rotation/scale (about its center) + translation into one affine.
448fn shape_transform(rect: Rect, rotation: Angle, scale: f64, ox: f64, oy: f64) -> Affine {
449    let c = rect.center();
450    Affine::translate(-c.x, -c.y)
451        .then(Affine::scale(scale, scale))
452        .then(Affine::rotate(rotation))
453        .then(Affine::translate(c.x, c.y))
454        .then(Affine::translate(ox, oy))
455}
456
457/// Map an `.at` unit-space sub-rect into `bounds` (identity when unset).
458fn resolve_at(at: Option<Rect>, bounds: Rect) -> Rect {
459    match at {
460        Some(u) => Rect::new(
461            bounds.origin.x + u.origin.x * bounds.size.width,
462            bounds.origin.y + u.origin.y * bounds.size.height,
463            u.size.width * bounds.size.width,
464            u.size.height * bounds.size.height,
465        ),
466        None => bounds,
467    }
468}
469
470/// Record one shape description into `d`, resolved within `bounds`. Shared by
471/// [`ShapePiece`]'s canvas leaf and by [`shape_group`] / [`shape_group_fn`].
472fn record_shape(spec: &ShapeSpec, d: &mut Draw, bounds: Rect) {
473    let bounds = resolve_at(spec.at, bounds);
474    let kind = spec.kind.get();
475    // A centered stroke overflows the geometry by half its width; inset closed shapes by w/2 so
476    // the whole stroke stays inside the view bounds; backends that clip a canvas to its bounds
477    // (Qt/Android/XAML) would otherwise cut the stroke's outer edge. (SwiftUI `strokeBorder`
478    // behavior.) Fill-only shapes are unaffected (stroke_half = 0). Line/Polygon are exempt:
479    // they resolve exactly at their authored unit points, and a line's rect is legitimately
480    // degenerate (zero-height for a horizontal segment), so they skip the empty-rect bail too.
481    let open = matches!(kind, ShapeKind::Line { .. } | ShapeKind::Polygon { .. });
482    let stroke_half = if open {
483        0.0
484    } else {
485        spec.stroke.as_ref().map_or(0.0, |(_, w)| w.get() / 2.0)
486    };
487    let rect = bounds.inset(spec.inset.get() + stroke_half);
488    if !open && (rect.size.width <= 0.0 || rect.size.height <= 0.0) {
489        return;
490    }
491    let geom = kind.geometry(rect);
492    let m = shape_transform(
493        rect,
494        spec.rotation.get(),
495        spec.scale.get(),
496        spec.translation.0.get(),
497        spec.translation.1.get(),
498    );
499    let transformed = !m.is_identity();
500    if transformed {
501        d.save();
502        d.concat(m);
503    }
504    if !matches!(geom, Shape::Line(..))
505        && let Some(fill) = &spec.fill
506    {
507        d.fill(geom.clone(), fill.get());
508    }
509    if let Some((c, w)) = &spec.stroke {
510        d.stroke(geom, c.get(), w.get());
511    }
512    if transformed {
513        d.restore();
514    }
515}
516
517/// A shape greedily fills its proposed size (SwiftUI semantics).
518fn shape_flex() -> Flex {
519    Flex {
520        grow_w: true,
521        grow_h: true,
522        ..Default::default()
523    }
524}
525
526/// Flatten many shape descriptions into one canvas leaf: one native view no matter how many
527/// shapes (docs/shapes.md §3.6). Shapes draw in order; reactive properties re-record the group.
528/// Child gestures are not wired inside a group, so put `.on_tap` on the group via [`Decorate`].
529pub fn shape_group(shapes: impl IntoIterator<Item = ShapePiece>) -> impl Piece {
530    let specs: Vec<ShapeSpec> = shapes.into_iter().map(|s| s.spec).collect();
531    piece_fn(move |cx| {
532        canvas_leaf(cx, shape_flex(), move |d, size| {
533            let bounds = Rect::from_size(size);
534            for spec in &specs {
535                record_shape(spec, d, bounds);
536            }
537        })
538    })
539}
540
541/// Size-aware [`shape_group`]: the closure derives the shapes from the laid-out size and re-runs
542/// on `FrameChanged`, exactly like [`canvas`], for geometry that depends on the final size
543/// (e.g. data mapped along the width).
544pub fn shape_group_fn(shapes: impl Fn(Size) -> Vec<ShapePiece> + 'static) -> impl Piece {
545    piece_fn(move |cx| {
546        canvas_leaf(cx, shape_flex(), move |d, size| {
547            let bounds = Rect::from_size(size);
548            for piece in shapes(size) {
549                record_shape(&piece.spec, d, bounds);
550            }
551        })
552    })
553}
554
555impl Piece for ShapePiece {
556    fn build(self, cx: &mut BuildCx) -> RNode {
557        let ShapePiece {
558            spec,
559            on_tap,
560            on_drag,
561        } = self;
562
563        let draw_spec = spec.clone();
564        let node = canvas_leaf(cx, shape_flex(), move |d, size| {
565            record_shape(&draw_spec, d, Rect::from_size(size));
566        });
567
568        // Path-precise tap: inverse-transform the tap location, then test against the resolved
569        // geometry.
570        if let Some(on_tap) = on_tap {
571            with_tree(|t| t.enable_gesture(node, GestureKind::Tap));
572            cx.on(node, move |ev| {
573                if let Event::Tap(p) = ev
574                    && let Some(f) = with_tree(|t| t.node_frame(node))
575                {
576                    let bounds = resolve_at(spec.at, Rect::from_size(f.size));
577                    let rect = bounds.inset(spec.inset.get_untracked());
578                    let m = shape_transform(
579                        rect,
580                        spec.rotation.get_untracked(),
581                        spec.scale.get_untracked(),
582                        spec.translation.0.get_untracked(),
583                        spec.translation.1.get_untracked(),
584                    );
585                    let local = m.invert_apply(*p).unwrap_or(*p);
586                    if spec.kind.get_untracked().contains(rect, local) {
587                        on_tap();
588                    }
589                }
590            });
591        }
592        if let Some(on_drag) = on_drag {
593            with_tree(|t| t.enable_gesture(node, GestureKind::Drag));
594            cx.on(node, move |ev| {
595                if let Event::Drag {
596                    phase,
597                    location,
598                    translation,
599                } = ev
600                {
601                    let velocity =
602                        day_core::gesture::velocity(day_core::rnode_to_id(node), GestureKind::Drag);
603                    on_drag(Drag::new(*phase, *location, *translation).with_velocity(velocity));
604                }
605            });
606        }
607        node
608    }
609}
610
611// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
612
613// ---------------------------------------------------------------------------
614// Conformance cases (docs/testing.md)
615// ---------------------------------------------------------------------------
616
617/// The shapes' `#[day::test]` cases, next to their constructors.
618#[cfg(feature = "conformance")]
619pub(crate) mod conformance {
620    use day_core::Piece;
621    use day_core::conformance::{Case, Drive};
622    use day_spec::{Cap, Color};
623
624    use crate::*;
625
626    /// `shape` on a white ground, so a sample outside it reads white on every theme.
627    fn on_white(s: ShapePiece) -> impl Piece {
628        zstack((rectangle().fill(Color::WHITE), s))
629            .id(day_core::id!(ground))
630            .frame(80.0, 80.0)
631    }
632
633    /// A filled rectangle fills its frame.
634    #[day_macros::test(day_core)]
635    fn shape_fill() -> Case {
636        Case::new()
637            .proves_duty("snapshot_window")
638            .proves_duty("prepare_snapshot")
639            .proves_cap(Cap::Snapshot)
640            .requires(Cap::Snapshot)
641            .page(|| on_white(rectangle().fill(Color::rgb(1.0, 0.0, 0.0))))
642            .drive(|d: Drive| async move {
643                d.sample_pixel("ground", 0.5, 0.5, "#ff0000").await?;
644                d.sample_pixel("ground", 0.05, 0.05, "#ff0000").await
645            })
646    }
647
648    /// A circle fills its middle and leaves its frame's corners to what is below.
649    #[day_macros::test(day_core)]
650    fn shape_circle() -> Case {
651        Case::new()
652            .requires(Cap::Snapshot)
653            .page(|| on_white(circle().fill(Color::rgb(0.0, 0.0, 1.0))))
654            .shot("default")
655            .drive(|d: Drive| async move {
656                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
657                d.sample_pixel("ground", 0.04, 0.04, "#ffffff").await
658            })
659    }
660
661    /// A rounded rectangle's corners are cut, its middle filled.
662    #[day_macros::test(day_core)]
663    fn shape_rounded() -> Case {
664        Case::new()
665            .requires(Cap::Snapshot)
666            .page(|| on_white(rounded_rectangle(30.0).fill(Color::rgb(0.0, 0.0, 1.0))))
667            .drive(|d: Drive| async move {
668                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
669                d.sample_pixel("ground", 0.03, 0.03, "#ffffff").await?;
670                d.sample_pixel("ground", 0.5, 0.03, "#0000ff").await
671            })
672    }
673
674    /// A shape group places each shape in its own fraction of the frame.
675    #[day_macros::test(day_core)]
676    fn shape_group_places() -> Case {
677        Case::new()
678            .requires(Cap::Snapshot)
679            .page(|| {
680                shape_group([
681                    rectangle()
682                        .fill(Color::rgb(1.0, 0.0, 0.0))
683                        .at(0.0, 0.0, 0.5, 1.0),
684                    rectangle()
685                        .fill(Color::rgb(0.0, 0.0, 1.0))
686                        .at(0.5, 0.0, 0.5, 1.0),
687                ])
688                .id(day_core::id!(group))
689                .frame(80.0, 40.0)
690            })
691            .drive(|d: Drive| async move {
692                d.sample_pixel("group", 0.25, 0.5, "#ff0000").await?;
693                d.sample_pixel("group", 0.75, 0.5, "#0000ff").await
694            })
695    }
696}