meo_canvas/unit.rs
1//! The values a style is written in: lengths, edges, corners and colours.
2//!
3//! Free functions rather than methods, because a length is written before there
4//! is anything to call a method on: `padding(all(px(24.0)))` reads as the CSS
5//! it came from, where `Length::points(24.0).all()` reads as arithmetic.
6//!
7//! Every function here is `const`, which is what lets a whole style be one:
8//!
9//! ```
10//! use meo_canvas::{Style, all, hex_rgb, px};
11//!
12//! const CARD: Style = Style::new().padding(all(px(24.0))).gap(px(16.0));
13//! ```
14//!
15//! The exception is [`hex`], which parses a string and so cannot be.
16//! [`hex_rgb`] is its `const` form, taking the same digits as a number.
17
18use meo_canvas_scene::{
19 Corners, Sides,
20 style::{
21 Dimension, Length,
22 layout::TrackSize,
23 paint::{Color, ColorValue},
24 },
25};
26
27/// A length in logical pixels.
28///
29/// The unit everything else is expressed against, and the one a bare number
30/// means everywhere in the scene.
31///
32/// ```
33/// use meo_canvas::{Style, px};
34///
35/// const GUTTER: Style = Style::new().gap(px(16.0));
36/// ```
37#[must_use]
38pub const fn px(points: f32) -> Length {
39 Length::Points(points)
40}
41
42/// A percentage of whatever the property resolves against.
43///
44/// Written as the number a stylesheet writes: `pct(50.0)` is `50%`, not `0.5`.
45/// The scene stores the fraction, and converting here rather than at the call
46/// site is what keeps `50` from meaning `5000%` on the way in. A caller who
47/// already holds a fraction wants [`fraction`], which says why.
48///
49/// ```
50/// use meo_canvas::{Style, pct};
51///
52/// const HALF: Style = Style::new().width(pct(50.0));
53/// ```
54#[must_use]
55pub const fn pct(percent: f32) -> Length {
56 Length::Percent(percent / 100.0)
57}
58
59/// A fraction of whatever the property resolves against, narrowed **once**.
60///
61/// `fraction(0.5)` is `50%`, where [`pct`] spells the same length `pct(50.0)`.
62/// Both exist because a caller either holds a percentage or holds a fraction,
63/// and **the conversion between them is not free**.
64///
65/// # Why a caller holding a fraction must not reach for `pct`
66///
67/// `pct(f * 100.0)` multiplies in `f64`, narrows at the argument and divides
68/// again in `f32` — **two roundings of one number**, and the second moves the
69/// last bit: `1 - 1/3` arrives as `0.666_666_75` by that route and
70/// `0.666_666_69` by every other, the JavaScript surface's included. No render
71/// can see a sixth of a hundred-millionth of a box; a byte comparison can.
72///
73/// ```
74/// use meo_canvas::{Style, Styled, fraction};
75///
76/// // A third of the way down, narrowed at the boundary and nowhere else.
77/// let placed = Style::new().height(fraction(1.0 / 3.0));
78/// ```
79#[must_use]
80pub const fn fraction(of_the_box: f64) -> Length {
81 #[expect(
82 clippy::cast_possible_truncation,
83 reason = "the single narrowing this exists to perform"
84 )]
85 Length::Percent(of_the_box as f32)
86}
87
88/// A share of a grid's leftover space, as CSS's `fr`.
89///
90/// Only a grid track takes one, so this returns a [`TrackSize`] rather than a
91/// [`Length`] — `fr` is meaningless as a width.
92#[must_use]
93pub const fn fr(share: f32) -> TrackSize {
94 TrackSize::Fraction(share)
95}
96
97/// A fixed or proportional grid track.
98///
99/// A track takes a [`TrackSize`] and a length is not one, so this is the
100/// widening. `fr` and `auto` build a `TrackSize` directly, because neither is
101/// expressible as a length.
102#[must_use]
103pub const fn track(length: Length) -> TrackSize {
104 match length {
105 Length::Points(points) => TrackSize::Points(points),
106 Length::Percent(fraction) => TrackSize::Percent(fraction),
107 }
108}
109
110/// A track sized to its content.
111#[must_use]
112pub const fn auto() -> TrackSize {
113 TrackSize::Auto
114}
115
116/// One value on every edge, as CSS's one-value shorthand.
117#[must_use]
118pub const fn all<T: Copy>(value: T) -> Sides<T> {
119 Sides {
120 top: value,
121 right: value,
122 bottom: value,
123 left: value,
124 }
125}
126
127/// Vertical and horizontal, as CSS's two-value shorthand.
128///
129/// `xy(a, b)` is CSS's `margin: a b` — the first is top and bottom, the second
130/// left and right. The argument order is the shorthand's, not `(x, y)`, because
131/// that is what a caller copying `padding: 8px 16px` writes.
132#[must_use]
133pub const fn xy<T: Copy>(vertical: T, horizontal: T) -> Sides<T> {
134 Sides {
135 top: vertical,
136 right: horizontal,
137 bottom: vertical,
138 left: horizontal,
139 }
140}
141
142/// Each edge named, in CSS's clockwise order.
143#[must_use]
144pub const fn sides<T>(top: T, right: T, bottom: T, left: T) -> Sides<T> {
145 Sides {
146 top,
147 right,
148 bottom,
149 left,
150 }
151}
152
153/// One edge, with the rest at zero.
154///
155/// ```
156/// use meo_canvas::{Style, px, top};
157///
158/// const HEADER: Style = Style::new().padding(top(px(12.0)));
159/// ```
160#[must_use]
161pub const fn top<T: DefaultZero>(value: T) -> Sides<T> {
162 let zero = T::ZERO;
163 sides(value, zero, zero, zero)
164}
165
166/// The right edge alone. See [`top`].
167#[must_use]
168pub const fn right<T: DefaultZero>(value: T) -> Sides<T> {
169 let zero = T::ZERO;
170 sides(zero, value, zero, zero)
171}
172
173/// The bottom edge alone. See [`top`].
174#[must_use]
175pub const fn bottom<T: DefaultZero>(value: T) -> Sides<T> {
176 let zero = T::ZERO;
177 sides(zero, zero, value, zero)
178}
179
180/// The left edge alone. See [`top`].
181#[must_use]
182pub const fn left<T: DefaultZero>(value: T) -> Sides<T> {
183 let zero = T::ZERO;
184 sides(zero, zero, zero, value)
185}
186
187/// The value an unnamed edge of a per-edge shorthand takes.
188///
189/// A trait with an associated constant rather than [`Default`], because
190/// `Default::default()` cannot be called from a `const fn` and these shorthands
191/// are `const` so that a whole [`crate::Style`] can be.
192pub trait DefaultZero: Copy {
193 /// The zero of this type.
194 const ZERO: Self;
195}
196
197impl DefaultZero for f32 {
198 const ZERO: Self = 0.0;
199}
200
201impl DefaultZero for Length {
202 const ZERO: Self = Self::Points(0.0);
203}
204
205impl DefaultZero for Dimension {
206 const ZERO: Self = Self::Points(0.0);
207}
208
209/// An edge nobody named is not pinned at all, rather than pinned to zero.
210///
211/// `inset` is the one per-edge property whose edges are optional, and the
212/// difference matters: an offset of zero pins that edge to the container's,
213/// where absence leaves it to the flow. Without this, [`left`] and its siblings
214/// cannot express an inset at all — which is the property they are most often
215/// reached for.
216impl<T: Copy> DefaultZero for Option<T> {
217 const ZERO: Self = None;
218}
219
220/// The same value on every corner.
221#[must_use]
222pub const fn corners_all(border_radius: f32) -> Corners<f32> {
223 Corners {
224 top_left: border_radius,
225 top_right: border_radius,
226 bottom_right: border_radius,
227 bottom_left: border_radius,
228 }
229}
230
231/// Each corner named, clockwise from the top left.
232#[must_use]
233pub const fn corners(
234 top_left: f32,
235 top_right: f32,
236 bottom_right: f32,
237 bottom_left: f32,
238) -> Corners<f32> {
239 Corners {
240 top_left,
241 top_right,
242 bottom_right,
243 bottom_left,
244 }
245}
246
247/// An opaque colour from packed `0xRRGGBB`.
248///
249/// The `const` form of [`hex`]. A string cannot be parsed in a `const fn`, so a
250/// style that has to be a `const` writes its colours as numbers:
251///
252/// ```
253/// use meo_canvas::{ColorValue, Style, hex_rgb};
254///
255/// const PANEL: Style =
256/// Style::new().background_color(ColorValue::Rgba(hex_rgb(0x10_10_14)));
257/// ```
258#[must_use]
259pub const fn hex_rgb(packed: u32) -> Color {
260 Color::rgb(
261 ((packed >> 16) & 0xff) as u8,
262 ((packed >> 8) & 0xff) as u8,
263 (packed & 0xff) as u8,
264 )
265}
266
267/// A colour from packed `0xRRGGBBAA`.
268#[must_use]
269pub const fn hex_rgba(packed: u32) -> Color {
270 Color::rgba(
271 ((packed >> 24) & 0xff) as u8,
272 ((packed >> 16) & 0xff) as u8,
273 ((packed >> 8) & 0xff) as u8,
274 (packed & 0xff) as u8,
275 )
276}
277
278/// A colour from a CSS hex string.
279///
280/// Takes `#rgb`, `#rgba`, `#rrggbb` and `#rrggbbaa`, with or without the hash,
281/// which is what a caller copying a value out of a design tool has in hand.
282/// Anything else is [`Color::BLACK`] — a style is not a place to return a
283/// `Result`, and a colour that silently failed to parse is visible immediately.
284///
285/// Not `const`: parsing a `&str` needs iteration a `const fn` cannot do. Use
286/// [`hex_rgb`] where the style must be a `const`.
287///
288/// ```
289/// use meo_canvas::{hex, scene::Color};
290///
291/// assert_eq!(hex("#101014"), Color::rgb(0x10, 0x10, 0x14));
292/// assert_eq!(hex("f0c"), Color::rgb(0xff, 0x00, 0xcc));
293/// assert_eq!(hex("#80808080").a, 0x80);
294/// ```
295#[must_use]
296pub fn hex(value: &str) -> Color {
297 parse_hex(value).unwrap_or(Color::BLACK)
298}
299
300/// [`hex`]'s parse, separated so `?` has an `Option` to return into.
301fn parse_hex(value: &str) -> Option<Color> {
302 let digits = value.strip_prefix('#').unwrap_or(value).as_bytes();
303
304 let nibble = |index: usize| -> Option<u8> {
305 let digit = char::from(*digits.get(index)?).to_digit(16)?;
306 u8::try_from(digit).ok()
307 };
308 // The short forms repeat each digit, so `f` is `ff` -- CSS's rule, and the
309 // reason `#f0c` and `#ff00cc` are the same colour.
310 let doubled = |index: usize| nibble(index).map(|digit| digit * 17);
311 let pair = |index: usize| Some(nibble(index)? * 16 + nibble(index + 1)?);
312
313 match digits.len() {
314 3 => Some(Color::rgb(doubled(0)?, doubled(1)?, doubled(2)?)),
315 4 => Some(Color::rgba(
316 doubled(0)?,
317 doubled(1)?,
318 doubled(2)?,
319 doubled(3)?,
320 )),
321 6 => Some(Color::rgb(pair(0)?, pair(2)?, pair(4)?)),
322 8 => Some(Color::rgba(pair(0)?, pair(2)?, pair(4)?, pair(6)?)),
323 _ => None,
324 }
325}
326
327/// A colour from channels and an alpha fraction.
328///
329/// Alpha is `0.0` to `1.0`, as CSS writes it, rather than the byte the scene
330/// stores.
331#[must_use]
332pub fn rgba(red: u8, green: u8, blue: u8, alpha: f32) -> Color {
333 // Rounded rather than truncated: `0.5` is 128 as a browser reports it, and
334 // truncation would make every fraction one step too transparent.
335 let alpha = (alpha.clamp(0.0, 1.0) * 255.0).round();
336 Color::rgba(red, green, blue, alpha as u8)
337}
338
339/// An opaque colour from channels.
340#[must_use]
341pub const fn rgb(red: u8, green: u8, blue: u8) -> Color {
342 Color::rgb(red, green, blue)
343}
344
345/// `auto` for a width or height: the [`Dimension`] no [`Length`] can spell,
346/// since a length is always a measure.
347#[must_use]
348pub const fn size_auto() -> Dimension {
349 Dimension::Auto
350}
351
352/// What a per-edge setter accepts: one value, or the four named.
353///
354/// CSS's shorthand, as a trait. `padding(px(24.0))` is every edge and
355/// `padding(sides(...))` is each of them, which is the same choice CSS gives
356/// and the same one the JavaScript surface gives through a union type.
357///
358/// The node setters take this; [`Style`](crate::Style)'s take a
359/// [`Sides`] directly, because they are `const fn` and a trait method cannot
360/// be. So `const CARD: Style = Style::new().padding(all(px(24.0)))` spells the
361/// shorthand out, and a node written in a chain does not have to.
362pub trait IntoSides<T> {
363 /// The four edges this names.
364 fn into_sides(self) -> Sides<T>;
365}
366
367impl<T: Copy> IntoSides<T> for Sides<T> {
368 fn into_sides(self) -> Self {
369 self
370 }
371}
372
373impl IntoSides<Self> for Length {
374 fn into_sides(self) -> Sides<Self> {
375 Sides::all(self)
376 }
377}
378
379impl IntoSides<Self> for Dimension {
380 fn into_sides(self) -> Sides<Self> {
381 Sides::all(self)
382 }
383}
384
385/// A length is a dimension, so a length reaches a property that takes one.
386///
387/// `margin` is the property this exists for: it takes a [`Dimension`] because
388/// `auto` is CSS's free-space-absorbing margin, and without this a caller with
389/// a `px` in hand cannot write one at all — [`px`] answers a [`Length`] and
390/// there is no widening spelling of it.
391impl IntoSides<Dimension> for Length {
392 fn into_sides(self) -> Sides<Dimension> {
393 Sides::all(widen(self))
394 }
395}
396
397impl IntoSides<Dimension> for Sides<Length> {
398 fn into_sides(self) -> Sides<Dimension> {
399 Sides {
400 top: widen(self.top),
401 right: widen(self.right),
402 bottom: widen(self.bottom),
403 left: widen(self.left),
404 }
405 }
406}
407
408/// A [`Length`] as the [`Dimension`] a sizing property takes.
409///
410/// Sizes admit `auto` and lengths do not, so every length is a dimension and
411/// the widening is total.
412const fn widen(length: Length) -> Dimension {
413 match length {
414 Length::Points(points) => Dimension::Points(points),
415 Length::Percent(fraction) => Dimension::Percent(fraction),
416 }
417}
418
419impl IntoSides<Self> for f32 {
420 fn into_sides(self) -> Sides<Self> {
421 Sides::all(self)
422 }
423}
424
425/// Per-edge colours written as [`Color`]s reach a border colour, which takes
426/// [`ColorValue`]s so that an edge can be `currentColor`.
427impl IntoSides<Option<ColorValue>> for Sides<Option<Color>> {
428 fn into_sides(self) -> Sides<Option<ColorValue>> {
429 let value = |edge: Option<Color>| edge.map(ColorValue::Rgba);
430 Sides {
431 top: value(self.top),
432 right: value(self.right),
433 bottom: value(self.bottom),
434 left: value(self.left),
435 }
436 }
437}
438
439impl IntoSides<Option<Self>> for Length {
440 fn into_sides(self) -> Sides<Option<Self>> {
441 Sides::all(Some(self))
442 }
443}
444
445impl IntoSides<Option<Self>> for Color {
446 fn into_sides(self) -> Sides<Option<Self>> {
447 Sides::all(Some(self))
448 }
449}
450
451/// What a per-corner setter accepts: one radius, or the four named.
452pub trait IntoCorners<T> {
453 /// The four corners this names.
454 fn into_corners(self) -> Corners<T>;
455}
456
457impl<T: Copy> IntoCorners<T> for Corners<T> {
458 fn into_corners(self) -> Self {
459 self
460 }
461}
462
463impl IntoCorners<Self> for f32 {
464 fn into_corners(self) -> Corners<Self> {
465 Corners::all(self)
466 }
467}
468
469#[cfg(test)]
470mod tests {
471 use meo_canvas_scene::style::{
472 Dimension, Length, layout::TrackSize, paint::Color,
473 };
474
475 use super::{
476 all, bottom, corners, corners_all, fr, hex, hex_rgb, hex_rgba, left,
477 pct, px, rgb, rgba, right, sides, size_auto, top, track, xy,
478 };
479
480 #[test]
481 fn a_percentage_is_written_as_a_stylesheet_writes_it() {
482 // `pct(50.0)` is `50%`. The scene stores the fraction, and converting
483 // here is what keeps `50` from meaning 5000%.
484 assert_eq!(pct(50.0), Length::Percent(0.5));
485 assert_eq!(pct(100.0), Length::Percent(1.0));
486 assert_eq!(px(16.0), Length::Points(16.0));
487 }
488
489 #[test]
490 fn the_edge_shorthands_follow_css() {
491 assert_eq!(all(px(4.0)), sides(px(4.0), px(4.0), px(4.0), px(4.0)));
492 // CSS's two-value form is vertical then horizontal, not (x, y).
493 assert_eq!(
494 xy(px(8.0), px(16.0)),
495 sides(px(8.0), px(16.0), px(8.0), px(16.0))
496 );
497 }
498
499 #[test]
500 fn a_single_edge_leaves_the_others_at_zero() {
501 let zero = Length::Points(0.0);
502 assert_eq!(top(px(4.0)), sides(px(4.0), zero, zero, zero));
503 assert_eq!(right(px(4.0)), sides(zero, px(4.0), zero, zero));
504 assert_eq!(bottom(px(4.0)), sides(zero, zero, px(4.0), zero));
505 assert_eq!(left(px(4.0)), sides(zero, zero, zero, px(4.0)));
506 }
507
508 #[test]
509 fn tracks_carry_the_unit_a_grid_takes() {
510 assert_eq!(track(px(240.0)), TrackSize::Points(240.0));
511 assert_eq!(track(pct(50.0)), TrackSize::Percent(0.5));
512 assert_eq!(fr(1.0), TrackSize::Fraction(1.0));
513 assert_eq!(super::auto(), TrackSize::Auto);
514 assert_eq!(size_auto(), Dimension::Auto);
515 }
516
517 #[test]
518 fn corner_shorthands_set_what_they_name() {
519 let even = corners_all(8.0);
520 assert_eq!(even.top_left.to_bits(), 8.0_f32.to_bits());
521 assert_eq!(even.bottom_right.to_bits(), 8.0_f32.to_bits());
522
523 let mixed = corners(1.0, 2.0, 3.0, 4.0);
524 assert_eq!(mixed.top_left.to_bits(), 1.0_f32.to_bits());
525 assert_eq!(mixed.top_right.to_bits(), 2.0_f32.to_bits());
526 assert_eq!(mixed.bottom_right.to_bits(), 3.0_f32.to_bits());
527 assert_eq!(mixed.bottom_left.to_bits(), 4.0_f32.to_bits());
528 }
529
530 #[test]
531 fn every_css_hex_form_parses() {
532 // The short forms repeat each digit, which is CSS's rule and the reason
533 // `#f0c` and `#ff00cc` are the same colour.
534 assert_eq!(hex("#f0c"), Color::rgb(0xff, 0x00, 0xcc));
535 assert_eq!(hex("f0c"), Color::rgb(0xff, 0x00, 0xcc));
536 assert_eq!(hex("#101014"), Color::rgb(0x10, 0x10, 0x14));
537 assert_eq!(hex("#f0c8"), Color::rgba(0xff, 0x00, 0xcc, 0x88));
538 assert_eq!(hex("#80808080"), Color::rgba(0x80, 0x80, 0x80, 0x80));
539 }
540
541 #[test]
542 fn a_hex_that_does_not_parse_is_black_rather_than_a_panic() {
543 // A style is not a place to return a `Result`, and a colour that failed
544 // to parse is visible the moment the picture is looked at.
545 for bad in ["", "#", "#12", "#12345", "zzz", "#gggggg"] {
546 assert_eq!(hex(bad), Color::BLACK, "{bad:?} should read as black");
547 }
548 }
549
550 #[test]
551 fn the_packed_forms_match_the_string_ones() {
552 assert_eq!(hex_rgb(0x10_10_14), hex("#101014"));
553 assert_eq!(hex_rgba(0x80_80_80_80), hex("#80808080"));
554 assert_eq!(rgb(1, 2, 3), Color::rgb(1, 2, 3));
555 }
556
557 #[test]
558 fn an_alpha_fraction_rounds_the_way_a_browser_reports_it() {
559 // Rounded, not truncated: `0.5` is 128, and truncation would make every
560 // fraction one step too transparent.
561 assert_eq!(rgba(0, 0, 0, 0.5).a, 128);
562 assert_eq!(rgba(0, 0, 0, 1.0).a, 255);
563 assert_eq!(rgba(0, 0, 0, 0.0).a, 0);
564 // Out of range is clamped rather than wrapped.
565 assert_eq!(rgba(0, 0, 0, 2.0).a, 255);
566 assert_eq!(rgba(0, 0, 0, -1.0).a, 0);
567 }
568}