Skip to main content

day_pieces/
image.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The `image` piece: loads a named asset (resolved from the dev asset root, the app bundle, or
5//! Android's `AssetManager`) with content-mode and aspect-ratio fitting.
6
7use day_core::*;
8use day_spec::kinds;
9
10use crate::Decorated;
11use day_spec::props::*;
12
13// ---------------------------------------------------------------------------
14// Image (§18.2, MVP): sources resolve via DAY_ASSET_ROOT (desktop dev), the app
15// bundle (ios), or AssetManager (android).
16// ---------------------------------------------------------------------------
17
18/// An image: a bundled asset resolved by name through the backend's native image pipeline
19/// (§18.3), encoded bytes the app already holds, or an image decoded once and shared
20/// (docs/images.md). Scales with [`ContentMode::Fit`] by default (never stretches); tune with
21/// `.content_mode()` / `.fill()` / `.stretch()`, and optionally constrain the frame with
22/// `.aspect_ratio(w/h)`.
23#[must_use]
24pub struct Image {
25    source: crate::Reactive<day_spec::ImageSource>,
26    content_mode: ContentMode,
27    aspect_ratio: Option<f64>,
28    decorative: bool,
29    template: bool,
30    /// The tint the view is REALIZED with (`sidebar_image`'s rows): a patch sent before the node
31    /// has a native view is dropped, so a row built in a not-yet-realized cell would otherwise
32    /// come up in the template default until its tint next changed.
33    tint: Option<day_spec::Color>,
34}
35
36/// Draw an image from any [`ImageSource`](day_spec::ImageSource): a staged asset name, encoded
37/// bytes, or a decoded [`Bitmap`](day_core::Bitmap).
38///
39/// ```ignore
40/// image(res::images::cover)                 // a staged asset, as it always was
41/// image(png_bytes)                          // Vec<u8> / Arc<Vec<u8>> the app fetched or picked
42/// image(&bitmap)                            // one decode, shared by several nodes
43/// image(move || shot.get())                 // reactive: swapping the source patches in place
44/// ```
45///
46/// Bytes and decoded sources need [`Cap::ImageDecode`](day_spec::Cap::ImageDecode); a backend
47/// without it draws nothing rather than guessing. A name still resolves the way it always has,
48/// on every backend.
49pub fn image<M>(source: impl IntoImageSource<M>) -> Image {
50    Image {
51        source: source.into_image_source(),
52        content_mode: ContentMode::default(),
53        aspect_ratio: None,
54        decorative: false,
55        template: false,
56        tint: None,
57    }
58}
59
60/// Disjoint-marker conversion into an image source (the same shape as
61/// [`IntoText`](crate::IntoText), and for the same coherence reason): a staged name, a byte
62/// buffer, a decoded [`Bitmap`](day_core::Bitmap), a `Signal`, or a closure all convert, each
63/// under its own marker.
64///
65/// A blanket `impl<S: Into<ImageSource>>` over the existing
66/// [`IntoReactive`](crate::IntoReactive) would be ambiguous for `ImageSource` itself (the
67/// static blanket and the converting one would both apply and leave the marker unconstrained),
68/// so the conversions are spelled per concrete type instead.
69pub trait IntoImageSource<M> {
70    fn into_image_source(self) -> crate::Reactive<day_spec::ImageSource>;
71}
72
73/// Marker for the by-value conversions (a name, bytes, a bitmap, a source).
74pub struct ImageValueMark;
75/// Marker for `Signal<ImageSource>`.
76pub struct ImageSignalMark;
77/// Marker for `Fn() -> ImageSource`.
78pub struct ImageFnMark;
79
80macro_rules! image_source_from_value {
81    ($($t:ty),* $(,)?) => {
82        $(impl IntoImageSource<ImageValueMark> for $t {
83            fn into_image_source(self) -> crate::Reactive<day_spec::ImageSource> {
84                crate::Reactive::Const(self.into())
85            }
86        })*
87    };
88}
89
90image_source_from_value!(
91    day_spec::ImageSource,
92    day_spec::ImageName,
93    day_spec::VectorName,
94    day_spec::BitmapId,
95    // An owned string is a runtime-computed name (`ImageName::dynamic`'s spelling), never bytes.
96    // `&str` is absent so that `image("typo")` still fails to compile.
97    String,
98    Vec<u8>,
99    std::sync::Arc<Vec<u8>>,
100);
101
102/// A decoded image draws by id, so several nodes (and the canvas) share one decode.
103/// A decoded handle. The piece keeps a clone alive for the node's life: the closure below owns
104/// it, the binding owns the closure, and the node's scope owns the binding, so the toolkit's
105/// image outlives the view that shows it however the app juggles its own handle. Without this an
106/// `image(&bitmap)` would carry only the id, and on the web the `<img>` would point at an object
107/// URL that `release_image` had already revoked.
108impl IntoImageSource<ImageValueMark> for &day_core::Bitmap {
109    fn into_image_source(self) -> crate::Reactive<day_spec::ImageSource> {
110        let keep = self.clone();
111        crate::Reactive::Dyn(std::rc::Rc::new(move || {
112            day_spec::ImageSource::Decoded(keep.id())
113        }))
114    }
115}
116
117impl IntoImageSource<ImageSignalMark> for day_reactive::Signal<day_spec::ImageSource> {
118    fn into_image_source(self) -> crate::Reactive<day_spec::ImageSource> {
119        crate::Reactive::Dyn(std::rc::Rc::new(move || self.get()))
120    }
121}
122
123impl<F: Fn() -> day_spec::ImageSource + 'static> IntoImageSource<ImageFnMark> for F {
124    fn into_image_source(self) -> crate::Reactive<day_spec::ImageSource> {
125        crate::Reactive::Dyn(std::rc::Rc::new(self))
126    }
127}
128
129#[day_macros::builder(ImageBuilder)]
130impl Image {
131    /// How the image scales within its frame (default [`ContentMode::Fit`]).
132    pub fn content_mode(mut self, m: ContentMode) -> Self {
133        self.content_mode = m;
134        self
135    }
136    /// Scale to fit entirely inside the frame, preserving aspect ratio (the default).
137    pub fn fit(self) -> Self {
138        self.content_mode(ContentMode::Fit)
139    }
140    /// Scale to fill the frame, preserving aspect ratio and cropping the overflow.
141    pub fn fill(self) -> Self {
142        self.content_mode(ContentMode::Fill)
143    }
144    /// Stretch to fill the frame exactly, ignoring aspect ratio.
145    pub fn stretch(self) -> Self {
146        self.content_mode(ContentMode::Stretch)
147    }
148    /// Constrain the view to a `width / height` ratio (e.g. `16.0 / 9.0`).
149    pub fn aspect_ratio(mut self, ratio: f64) -> Self {
150        if ratio > 0.0 {
151            self.aspect_ratio = Some(ratio);
152        }
153        self
154    }
155    /// Mark the image decorative (hidden from accessibility).
156    pub fn decorative(mut self) -> Self {
157        self.decorative = true;
158        self
159    }
160    /// Draw a monochrome glyph as a template (docs/vectors.md "Template"): in the foreground
161    /// of the surface it sits on, following the theme, rather than in its authored colors.
162    /// What a row icon in a sidebar wants; a photo does not.
163    pub fn template(mut self) -> Self {
164        self.template = true;
165        self
166    }
167    /// The tint to realize with; later changes go through `ImagePatch::Tint` (docs/vectors.md).
168    pub(crate) fn initial_tint(mut self, tint: Option<day_spec::Color>) -> Self {
169        self.tint = tint;
170        self
171    }
172}
173
174impl Piece for Image {
175    fn build(self, cx: &mut BuildCx) -> day_core::RNode {
176        let source = self.source;
177        let seed = source.get_untracked();
178        let props = ImageProps {
179            source: seed.clone(),
180            decorative: self.decorative,
181            content_mode: self.content_mode,
182            aspect_ratio: self.aspect_ratio,
183            tint: self.tint,
184            template: self.template,
185        };
186        let node = match self.aspect_ratio {
187            Some(ratio) => cx.native(
188                kinds::IMAGE,
189                &props,
190                std::rc::Rc::new(AspectRatioLayout { ratio }),
191                Flex::default(),
192                day_core::Boundary::No,
193            ),
194            None => cx.leaf(kinds::IMAGE, &props, Flex::default()),
195        };
196        // A constant source reads the same value forever, so this seeds once and never patches;
197        // a signal or closure replaces the pixels in the view that is already on screen rather
198        // than realizing a second one, which would flash (docs/images.md).
199        day_reactive::bind_seeded(
200            seed,
201            move || source.get(),
202            move |s: &day_spec::ImageSource| {
203                day_core::with_tree(|t| {
204                    t.patch(node, Box::new(ImagePatch::Source(s.clone())), true);
205                });
206            },
207        );
208        node
209    }
210}
211
212// ---------------------------------------------------------------------------
213// Vector (docs/vectors.md): a bundled vector glyph from `resource/vectors/`.
214// ---------------------------------------------------------------------------
215
216/// A bundled vector glyph, resolved by name through whatever form the backend loads natively
217/// (§18.3: a `VectorDrawable` on Android, a catalog entry on Apple, an SVG on the web, a
218/// build-rasterized PNG where the toolkit has no vector path). Distinct from [`image()`] on
219/// purpose: only a typed [`VectorName`](day_spec::VectorName) is accepted, and the modifiers
220/// are the vector-appropriate ones: [`tint`](Vector::tint) recolors a monochrome glyph where
221/// the backend can (template rendering on Apple, drawable tint on Android, pixel recolor on
222/// GTK; backends without a tint path draw the authored colors).
223#[must_use]
224pub struct Vector {
225    source: crate::Reactive<day_spec::VectorName>,
226    tint: Option<crate::Reactive<day_spec::Color>>,
227    weight: VectorWeight,
228    decorative: bool,
229    template: bool,
230}
231
232/// A vector glyph's stroke weight (docs/vectors.md). Template-form sources (SF template SVGs,
233/// `.symbolset` bundles) carry true per-weight art; plain SVGs alias every weight to the same
234/// glyph, so `.weight(…)` degrades to Regular rather than to a missing asset.
235#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
236pub enum VectorWeight {
237    Light,
238    #[default]
239    Regular,
240    Bold,
241}
242
243pub fn vector<M>(name: impl crate::IntoReactive<day_spec::VectorName, M>) -> Vector {
244    Vector {
245        source: name.into_reactive(),
246        tint: None,
247        weight: VectorWeight::Regular,
248        decorative: false,
249        template: false,
250    }
251}
252
253#[day_macros::builder(VectorBuilder)]
254impl Vector {
255    /// Recolor the glyph (monochrome art) where the backend supports tinting.
256    ///
257    /// Takes a plain [`Color`](day_spec::Color) or anything reactive: a signal or closure repaints
258    /// the realized glyph through [`ImagePatch::Tint`](day_spec::props::ImagePatch) instead of
259    /// rebuilding it, so a glyph that follows the selection or the theme keeps its native view.
260    pub fn tint<M>(mut self, color: impl crate::IntoReactive<day_spec::Color, M>) -> Self {
261        self.tint = Some(color.into_reactive());
262        self
263    }
264    /// Select the glyph's weight (template-form sources render true weights; plain SVGs
265    /// degrade to Regular; see [`VectorWeight`]).
266    pub fn weight(mut self, w: VectorWeight) -> Self {
267        self.weight = w;
268        self
269    }
270    /// Mark the glyph decorative (hidden from accessibility).
271    pub fn decorative(mut self) -> Self {
272        self.decorative = true;
273        self
274    }
275    /// Draw the glyph as a template (docs/vectors.md "Template"): untinted, it takes the
276    /// foreground of the surface it sits on and follows the theme, instead of its authored
277    /// colors. A `.tint(…)` still wins while it is set.
278    pub fn template(mut self) -> Self {
279        self.template = true;
280        self
281    }
282}
283
284impl Piece for Vector {
285    fn build(self, cx: &mut BuildCx) -> day_core::RNode {
286        // Weight variants stage under suffixed resolution names (docs/vectors.md).
287        let weight = self.weight;
288        let resolved = move |name: day_spec::VectorName| {
289            let name = name.as_str();
290            day_spec::ImageSource::Named(match weight {
291                VectorWeight::Regular => name.to_owned(),
292                VectorWeight::Light => format!("{name}__light"),
293                VectorWeight::Bold => format!("{name}__bold"),
294            })
295        };
296        let source = self.source;
297        let source_seed = resolved(source.get_untracked());
298        let tint = self.tint;
299        let seed = tint.as_ref().map(super::canvas::Reactive::get_untracked);
300        let props = ImageProps {
301            source: source_seed.clone(),
302            decorative: self.decorative,
303            content_mode: ContentMode::Fit,
304            aspect_ratio: None,
305            tint: seed,
306            template: self.template,
307        };
308        let node = cx.leaf(kinds::IMAGE, &props, Flex::default());
309        // A reactive name swaps the glyph in the view already on screen, keeping its template
310        // and tint (a recycled row's icon following its row), as `image` does.
311        if let crate::Reactive::Dyn(_) = source {
312            day_reactive::bind_seeded(
313                source_seed,
314                move || resolved(source.get()),
315                move |s: &day_spec::ImageSource| {
316                    day_core::with_tree(|t| {
317                        t.patch(node, Box::new(ImagePatch::Source(s.clone())), true);
318                    });
319                },
320            );
321        }
322        // A constant tint reads the same value forever, so this seeds once and never patches; a
323        // signal or closure re-runs and repaints the realized glyph.
324        if let Some(tint) = tint
325            && let Some(seed) = seed
326        {
327            day_reactive::bind_seeded(
328                seed,
329                move || tint.get(),
330                move |c: &day_spec::Color| {
331                    day_core::with_tree(|t| {
332                        t.patch(
333                            node,
334                            Box::new(day_spec::props::ImagePatch::Tint(Some(*c))),
335                            false,
336                        );
337                    });
338                },
339            );
340        }
341        node
342    }
343}
344
345// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
346
347// ---------------------------------------------------------------------------
348// Conformance cases (docs/testing.md)
349// ---------------------------------------------------------------------------
350
351/// The image piece's `#[day::test]` cases, next to its constructor.
352#[cfg(feature = "conformance")]
353pub(crate) mod conformance {
354    use day_core::conformance::{Case, Drive};
355    use day_spec::{Cap, kinds};
356
357    use crate::*;
358
359    /// A 4×2 PNG: the left half red, the right half blue. Encoded once by hand (zlib level 9),
360    /// so the case needs no image resource and every toolkit decodes the same bytes.
361    pub(crate) const RED_BLUE: [u8; 76] = [
362        0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,
363        0x52, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02, 0x08, 0x02, 0x00, 0x00, 0x00, 0xf0,
364        0xca, 0xea, 0x34, 0x00, 0x00, 0x00, 0x13, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0xf8,
365        0xcf, 0xc0, 0x00, 0x44, 0x60, 0xe2, 0x3f, 0x03, 0x32, 0x07, 0x00, 0x67, 0xb2, 0x07, 0xf9,
366        0xf7, 0x92, 0x56, 0x82, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60,
367        0x82,
368    ];
369
370    /// Encoded bytes decode natively and draw at the frame Day gives them, each half its color.
371    #[day_macros::test(day_core)]
372    fn image_bytes() -> Case {
373        Case::new()
374            .proves(kinds::IMAGE)
375            .proves_cap(Cap::ImageDecode)
376            .proves_modifier("frame")
377            .page(|| {
378                image(RED_BLUE.to_vec())
379                    .stretch()
380                    .id(day_core::id!(image))
381                    .frame(120.0, 60.0)
382            })
383            .shot("default")
384            .drive(|d: Drive| async move {
385                d.assert_size("image", 120.0, 60.0).await?;
386                d.sample_pixel("image", 0.2, 0.5, "#ff0000").await?;
387                d.sample_pixel("image", 0.8, 0.5, "#0000ff").await
388            })
389    }
390
391    /// Fit keeps the image's 2:1 shape inside a square frame: the middle row still shows both
392    /// halves, in order.
393    #[day_macros::test(day_core)]
394    fn image_fit() -> Case {
395        Case::new()
396            .proves(kinds::IMAGE)
397            .page(|| {
398                image(RED_BLUE.to_vec())
399                    .fit()
400                    .id(day_core::id!(image))
401                    .frame(100.0, 100.0)
402            })
403            .drive(|d: Drive| async move {
404                d.assert_size("image", 100.0, 100.0).await?;
405                d.sample_pixel("image", 0.25, 0.5, "#ff0000").await?;
406                d.sample_pixel("image", 0.75, 0.5, "#0000ff").await
407            })
408    }
409
410    /// A decorative image is hidden from assistive technology; a described one is announced.
411    #[day_macros::test(day_core)]
412    fn image_a11y() -> Case {
413        Case::new()
414            .proves(kinds::IMAGE)
415            .page(|| {
416                image(RED_BLUE.to_vec())
417                    .a11y(|a| a.label("Red and blue"))
418                    .id(day_core::id!(image))
419                    .frame(40.0, 20.0)
420            })
421            .drive(|d: Drive| async move { d.a11y_audit(Some("image")).await })
422    }
423}