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::Ink>,
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 /// Recolor the image to `color`, keeping only its alpha: every pixel becomes `color` at
168 /// the opacity the image had there (docs/images.md "Tinting"). What turns a white-on-clear
169 /// logo or a scanned signature into the theme's ink; on a photo with no transparency it is
170 /// a flat block of color.
171 pub fn tint(mut self, color: impl Into<day_spec::Ink>) -> Self {
172 self.tint = Some(color.into());
173 self
174 }
175 /// The tint to realize with; later changes go through `ImagePatch::Tint` (docs/vectors.md).
176 pub(crate) fn initial_tint(mut self, tint: Option<day_spec::Ink>) -> Self {
177 self.tint = tint;
178 self
179 }
180}
181
182impl Piece for Image {
183 fn build(self, cx: &mut BuildCx) -> day_core::RNode {
184 let source = self.source;
185 let seed = source.get_untracked();
186 let props = ImageProps {
187 source: seed.clone(),
188 decorative: self.decorative,
189 content_mode: self.content_mode,
190 aspect_ratio: self.aspect_ratio,
191 tint: self.tint,
192 template: self.template,
193 };
194 let node = match self.aspect_ratio {
195 Some(ratio) => cx.native(
196 kinds::IMAGE,
197 &props,
198 std::rc::Rc::new(AspectRatioLayout {
199 ratio: std::cell::Cell::new(ratio),
200 }),
201 Flex::default(),
202 day_core::Boundary::No,
203 ),
204 None => cx.leaf(kinds::IMAGE, &props, Flex::default()),
205 };
206 // A constant source reads the same value forever, so this seeds once and never patches;
207 // a signal or closure replaces the pixels in the view that is already on screen rather
208 // than realizing a second one, which would flash (docs/images.md).
209 day_reactive::bind_seeded(
210 seed,
211 move || source.get(),
212 move |s: &day_spec::ImageSource| {
213 day_core::with_tree(|t| {
214 t.patch(node, Box::new(ImagePatch::Source(s.clone())), true);
215 });
216 },
217 );
218 node
219 }
220}
221
222// ---------------------------------------------------------------------------
223// Vector (docs/vectors.md): a bundled vector glyph from `resource/vectors/`.
224// ---------------------------------------------------------------------------
225
226/// A bundled vector glyph, resolved by name through whatever form the backend loads natively
227/// (§18.3: a `VectorDrawable` on Android, a catalog entry on Apple, an SVG on the web, a
228/// build-rasterized PNG where the toolkit has no vector path). Distinct from [`image()`] on
229/// purpose: only a typed [`VectorName`](day_spec::VectorName) is accepted, and the modifiers
230/// are the vector-appropriate ones: [`tint`](Vector::tint) recolors a monochrome glyph where
231/// the backend can (template rendering on Apple, drawable tint on Android, pixel recolor on
232/// GTK; backends without a tint path draw the authored colors).
233#[must_use]
234pub struct Vector {
235 source: crate::Reactive<day_spec::VectorName>,
236 tint: Option<crate::Reactive<day_spec::Ink>>,
237 weight: VectorWeight,
238 decorative: bool,
239 template: bool,
240}
241
242/// A vector glyph's stroke weight (docs/vectors.md). Template-form sources (SF template SVGs,
243/// `.symbolset` bundles) carry true per-weight art; plain SVGs alias every weight to the same
244/// glyph, so `.weight(…)` degrades to Regular rather than to a missing asset.
245#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
246pub enum VectorWeight {
247 Light,
248 #[default]
249 Regular,
250 Bold,
251}
252
253pub fn vector<M>(name: impl crate::IntoReactive<day_spec::VectorName, M>) -> Vector {
254 Vector {
255 source: name.into_reactive(),
256 tint: None,
257 weight: VectorWeight::Regular,
258 decorative: false,
259 template: false,
260 }
261}
262
263#[day_macros::builder(VectorBuilder)]
264impl Vector {
265 /// Recolor the glyph (monochrome art) where the backend supports tinting.
266 ///
267 /// Takes a plain [`Color`](day_spec::Color) or anything reactive: a signal or closure repaints
268 /// the realized glyph through [`ImagePatch::Tint`](day_spec::props::ImagePatch) instead of
269 /// rebuilding it, so a glyph that follows the selection or the theme keeps its native view.
270 pub fn tint<M>(mut self, color: impl crate::IntoReactive<day_spec::Ink, M>) -> Self {
271 self.tint = Some(color.into_reactive());
272 self
273 }
274 /// Select the glyph's weight (template-form sources render true weights; plain SVGs
275 /// degrade to Regular; see [`VectorWeight`]).
276 pub fn weight(mut self, w: VectorWeight) -> Self {
277 self.weight = w;
278 self
279 }
280 /// Mark the glyph decorative (hidden from accessibility).
281 pub fn decorative(mut self) -> Self {
282 self.decorative = true;
283 self
284 }
285 /// Draw the glyph as a template (docs/vectors.md "Template"): untinted, it takes the
286 /// foreground of the surface it sits on and follows the theme, instead of its authored
287 /// colors. A `.tint(…)` still wins while it is set.
288 pub fn template(mut self) -> Self {
289 self.template = true;
290 self
291 }
292}
293
294impl Piece for Vector {
295 fn build(self, cx: &mut BuildCx) -> day_core::RNode {
296 // Weight variants stage under suffixed resolution names (docs/vectors.md).
297 let weight = self.weight;
298 let resolved = move |name: day_spec::VectorName| {
299 let name = name.as_str();
300 day_spec::ImageSource::Named(match weight {
301 VectorWeight::Regular => name.to_owned(),
302 VectorWeight::Light => format!("{name}__light"),
303 VectorWeight::Bold => format!("{name}__bold"),
304 })
305 };
306 let source = self.source;
307 let source_seed = resolved(source.get_untracked());
308 let tint = self.tint;
309 let seed = tint.as_ref().map(super::canvas::Reactive::get_untracked);
310 let props = ImageProps {
311 source: source_seed.clone(),
312 decorative: self.decorative,
313 content_mode: ContentMode::Fit,
314 aspect_ratio: None,
315 tint: seed,
316 template: self.template,
317 };
318 let node = cx.leaf(kinds::IMAGE, &props, Flex::default());
319 // A reactive name swaps the glyph in the view already on screen, keeping its template
320 // and tint (a recycled row's icon following its row), as `image` does.
321 if let crate::Reactive::Dyn(_) = source {
322 day_reactive::bind_seeded(
323 source_seed,
324 move || resolved(source.get()),
325 move |s: &day_spec::ImageSource| {
326 day_core::with_tree(|t| {
327 t.patch(node, Box::new(ImagePatch::Source(s.clone())), true);
328 });
329 },
330 );
331 }
332 // A constant tint reads the same value forever, so this seeds once and never patches; a
333 // signal or closure re-runs and repaints the realized glyph.
334 if let Some(tint) = tint
335 && let Some(seed) = seed
336 {
337 day_reactive::bind_seeded(
338 seed,
339 move || tint.get(),
340 move |c: &day_spec::Ink| {
341 day_core::with_tree(|t| {
342 t.patch(
343 node,
344 Box::new(day_spec::props::ImagePatch::Tint(Some(*c))),
345 false,
346 );
347 });
348 },
349 );
350 }
351 node
352 }
353}
354
355// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
356
357// ---------------------------------------------------------------------------
358// Conformance cases (docs/testing.md)
359// ---------------------------------------------------------------------------
360
361/// The image piece's `#[day::test]` cases, next to its constructor.
362#[cfg(feature = "conformance")]
363pub(crate) mod conformance {
364 use day_core::conformance::{Case, Drive};
365 use day_spec::{Cap, kinds};
366
367 use crate::*;
368
369 /// A 4×2 PNG: the left half red, the right half blue. Encoded once by hand (zlib level 9),
370 /// so the case needs no image resource and every toolkit decodes the same bytes.
371 pub(crate) const RED_BLUE: [u8; 76] = [
372 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,
373 0x52, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02, 0x08, 0x02, 0x00, 0x00, 0x00, 0xf0,
374 0xca, 0xea, 0x34, 0x00, 0x00, 0x00, 0x13, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0xf8,
375 0xcf, 0xc0, 0x00, 0x44, 0x60, 0xe2, 0x3f, 0x03, 0x32, 0x07, 0x00, 0x67, 0xb2, 0x07, 0xf9,
376 0xf7, 0x92, 0x56, 0x82, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60,
377 0x82,
378 ];
379
380 /// Encoded bytes decode natively and draw at the frame Day gives them, each half its color.
381 #[day_macros::test(day_core)]
382 fn image_bytes() -> Case {
383 Case::new()
384 .proves(kinds::IMAGE)
385 .proves_cap(Cap::ImageDecode)
386 .proves_modifier("frame")
387 .page(|| {
388 image(RED_BLUE.to_vec())
389 .stretch()
390 .id(day_core::id!(image))
391 .frame(120.0, 60.0)
392 })
393 .shot("default")
394 .drive(|d: Drive| async move {
395 d.assert_size("image", 120.0, 60.0).await?;
396 d.sample_pixel("image", 0.2, 0.5, "#ff0000").await?;
397 d.sample_pixel("image", 0.8, 0.5, "#0000ff").await
398 })
399 }
400
401 /// A tinted raster image draws in the tint, not in its own colors.
402 #[day_macros::test(day_core)]
403 fn image_tint_recolors_raster() -> Case {
404 Case::new()
405 .proves(kinds::IMAGE)
406 .requires(Cap::ImageDecode)
407 .requires(Cap::Snapshot)
408 .page(|| {
409 image(RED_BLUE.to_vec())
410 .stretch()
411 .tint(day_spec::Color::rgb(0.0, 1.0, 0.0))
412 .id(day_core::id!(image))
413 .frame(120.0, 60.0)
414 })
415 .drive(|d: Drive| async move {
416 d.sample_pixel("image", 0.2, 0.5, "#00ff00").await?;
417 d.sample_pixel("image", 0.8, 0.5, "#00ff00").await
418 })
419 }
420
421 /// Fit keeps the image's 2:1 shape inside a square frame: the middle row still shows both
422 /// halves, in order.
423 #[day_macros::test(day_core)]
424 fn image_fit() -> Case {
425 Case::new()
426 .proves(kinds::IMAGE)
427 .page(|| {
428 image(RED_BLUE.to_vec())
429 .fit()
430 .id(day_core::id!(image))
431 .frame(100.0, 100.0)
432 })
433 .drive(|d: Drive| async move {
434 d.assert_size("image", 100.0, 100.0).await?;
435 d.sample_pixel("image", 0.25, 0.5, "#ff0000").await?;
436 d.sample_pixel("image", 0.75, 0.5, "#0000ff").await
437 })
438 }
439
440 /// A decorative image is hidden from assistive technology; a described one is announced.
441 #[day_macros::test(day_core)]
442 fn image_a11y() -> Case {
443 Case::new()
444 .proves(kinds::IMAGE)
445 .page(|| {
446 image(RED_BLUE.to_vec())
447 .a11y(|a| a.label("Red and blue"))
448 .id(day_core::id!(image))
449 .frame(40.0, 20.0)
450 })
451 .drive(|d: Drive| async move { d.a11y_audit(Some("image")).await })
452 }
453}