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