Skip to main content

alpha2_model/
layout_values.rs

1//! The CSS value forms a layout reads: lengths, the four-side shorthand, grid track lists and
2//! grid lines.
3//!
4//! A JSON number is a fraction of the picture's shorter side. A string is CSS: `"12px"` is
5//! project canvas pixels, `"50%"` a percent of the parent's content box where allowed.
6//! Keywords inside these strings use CSS spelling (`min-content`, `auto-fill`); elsewhere
7//! layout keywords are `snake_case`. Whitespace is ASCII spaces. Unparsable strings are
8//! refused with the offending token and, where likely, the intended spelling.
9//!
10//! Each form serializes canonically (a number, `"<n>px"`, `"<n>%"`, the sides object, a track
11//! list as CSS) and round-trips.
12
13use serde::de::{self, Deserializer, MapAccess, Visitor};
14use serde::ser::{SerializeStruct, Serializer};
15use serde::{Deserialize, Serialize};
16use std::fmt::{self, Write as _};
17
18/// A CSS number without an exponent, `-?(\d+\.?\d*|\.\d+)`, finite. Read through 64 bits as
19/// a JSON number is, so `"0.1px"` holds the same `f32` as `0.1`.
20pub(crate) fn parse_number(text: &str) -> Option<f32> {
21    let digits = text.strip_prefix('-').unwrap_or(text);
22    let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
23    let all_digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
24    if !(all_digits(whole) && all_digits(fraction)) || (whole.is_empty() && fraction.is_empty()) {
25        return None;
26    }
27    #[allow(clippy::cast_possible_truncation)]
28    let value = text.parse::<f64>().ok()? as f32;
29    value.is_finite().then_some(value)
30}
31
32/// Largest magnitude of a layout length written as a fraction of the picture's shorter side.
33pub const MAX_LAYOUT_FRACTION: f32 = 1_024.0;
34/// Largest magnitude of a layout length in canvas pixels: 1,024 times the largest canvas side.
35#[allow(clippy::cast_precision_loss)]
36pub const MAX_LAYOUT_PX: f32 = 1_024.0 * crate::MAX_CANVAS_DIMENSION as f32;
37/// Largest magnitude of a layout length written as a percent.
38pub const MAX_LAYOUT_PERCENT: f32 = 100_000.0;
39
40fn tokens(text: &str) -> impl Iterator<Item = &str> {
41    text.split(' ').filter(|token| !token.is_empty())
42}
43
44fn write_length(out: &mut impl fmt::Write, value: f32, unit: &str) -> fmt::Result {
45    write!(out, "{value}{unit}")
46}
47
48/// A layout length that may be a percent: a size or an inset side.
49#[derive(Copy, Clone, Debug, PartialEq)]
50pub enum LayoutLength {
51    /// A fraction of the layout picture's shorter side, written as a number.
52    Fraction(f32),
53    /// Pixels of the project canvas, written `"<n>px"`. A plan converts it to a fraction of the
54    /// canvas's shorter side.
55    Px(f32),
56    /// Percent (0 to 100) of the parent's content box along the field's axis, written `"<n>%"`.
57    Percent(f32),
58}
59
60impl Default for LayoutLength {
61    fn default() -> Self {
62        Self::Fraction(0.0)
63    }
64}
65
66impl LayoutLength {
67    /// The number, whatever its unit.
68    #[must_use]
69    pub const fn value(self) -> f32 {
70        match self {
71            Self::Fraction(value) | Self::Px(value) | Self::Percent(value) => value,
72        }
73    }
74
75    /// Whether the number is finite and within its unit's bound: [`MAX_LAYOUT_FRACTION`],
76    /// [`MAX_LAYOUT_PX`] or [`MAX_LAYOUT_PERCENT`].
77    #[must_use]
78    pub fn in_bounds(self) -> bool {
79        let bound = match self {
80            Self::Fraction(_) => MAX_LAYOUT_FRACTION,
81            Self::Px(_) => MAX_LAYOUT_PX,
82            Self::Percent(_) => MAX_LAYOUT_PERCENT,
83        };
84        self.value().abs() <= bound
85    }
86
87    /// Whether it is a percent.
88    #[must_use]
89    pub const fn is_percent(self) -> bool {
90        matches!(self, Self::Percent(_))
91    }
92
93    /// The same length with pixels converted to a fraction of a picture `shorter_side` pixels on
94    /// its shorter side.
95    #[must_use]
96    pub fn without_px(self, shorter_side: f32) -> Self {
97        match self {
98            Self::Px(value) => Self::Fraction(px_fraction(value, shorter_side)),
99            other => other,
100        }
101    }
102
103    /// The same kind of length with `value`.
104    #[must_use]
105    pub const fn with_value(self, value: f32) -> Self {
106        match self {
107            Self::Fraction(_) => Self::Fraction(value),
108            Self::Px(_) => Self::Px(value),
109            Self::Percent(_) => Self::Percent(value),
110        }
111    }
112
113    fn parse(text: &str) -> Result<Self, String> {
114        let size = |value: LayoutSize| match value {
115            LayoutSize::Fraction(value) => Self::Fraction(value),
116            LayoutSize::Px(value) => Self::Px(value),
117        };
118        match text.trim_matches(' ').strip_suffix('%') {
119            Some(number) => parse_number(number)
120                .map(Self::Percent)
121                .ok_or_else(|| invalid_length(text, true)),
122            None => LayoutSize::parse_token(text.trim_matches(' '), true)
123                .map(size)
124                .map_err(|_| invalid_length(text, true)),
125        }
126    }
127}
128
129/// `n` canvas pixels as a fraction of a shorter side of `shorter_side` pixels.
130#[allow(clippy::cast_possible_truncation)]
131fn px_fraction(value: f32, shorter_side: f32) -> f32 {
132    (f64::from(value) / f64::from(shorter_side)) as f32
133}
134
135impl fmt::Display for LayoutLength {
136    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137        match *self {
138            Self::Fraction(value) => write!(formatter, "{value}"),
139            Self::Px(value) => write_length(formatter, value, "px"),
140            Self::Percent(value) => write_length(formatter, value, "%"),
141        }
142    }
143}
144
145/// A layout length that may not be a percent: a gap, radius, border width, font size,
146/// padding or margin side, or translation.
147#[derive(Copy, Clone, Debug, PartialEq)]
148pub enum LayoutSize {
149    /// A fraction of the layout picture's shorter side, written as a number.
150    Fraction(f32),
151    /// Pixels of the project canvas, written `"<n>px"`.
152    Px(f32),
153}
154
155impl Default for LayoutSize {
156    fn default() -> Self {
157        Self::Fraction(0.0)
158    }
159}
160
161impl LayoutSize {
162    /// The number, whatever its unit.
163    #[must_use]
164    pub const fn value(self) -> f32 {
165        match self {
166            Self::Fraction(value) | Self::Px(value) => value,
167        }
168    }
169
170    /// Whether the number is finite and within its unit's bound: [`MAX_LAYOUT_FRACTION`] or
171    /// [`MAX_LAYOUT_PX`].
172    #[must_use]
173    pub fn in_bounds(self) -> bool {
174        let bound = match self {
175            Self::Fraction(_) => MAX_LAYOUT_FRACTION,
176            Self::Px(_) => MAX_LAYOUT_PX,
177        };
178        self.value().abs() <= bound
179    }
180
181    /// The same size with pixels converted to a fraction of a picture `shorter_side` pixels on
182    /// its shorter side.
183    #[must_use]
184    pub fn without_px(self, shorter_side: f32) -> Self {
185        match self {
186            Self::Px(value) => Self::Fraction(px_fraction(value, shorter_side)),
187            other @ Self::Fraction(_) => other,
188        }
189    }
190
191    /// Its fraction of a picture `shorter_side` pixels on its shorter side.
192    #[must_use]
193    pub fn fraction(self, shorter_side: f32) -> f32 {
194        self.without_px(shorter_side).value()
195    }
196
197    /// The same kind of size with `value`.
198    #[must_use]
199    pub const fn with_value(self, value: f32) -> Self {
200        match self {
201            Self::Fraction(_) => Self::Fraction(value),
202            Self::Px(_) => Self::Px(value),
203        }
204    }
205
206    /// One token: a number or `<n>px`. `percent` says whether the field takes a percent, for the
207    /// error message.
208    fn parse_token(token: &str, percent: bool) -> Result<Self, String> {
209        if let Some(number) = token.strip_suffix("px") {
210            return parse_number(number)
211                .map(Self::Px)
212                .ok_or_else(|| invalid_length(token, percent));
213        }
214        if !percent && token.ends_with('%') && parse_number(&token[..token.len() - 1]).is_some() {
215            return Err(format!("percent is not allowed here: \"{token}\""));
216        }
217        parse_number(token)
218            .map(Self::Fraction)
219            .ok_or_else(|| invalid_length(token, percent))
220    }
221
222    fn parse(text: &str) -> Result<Self, String> {
223        Self::parse_token(text.trim_matches(' '), false)
224    }
225}
226
227impl fmt::Display for LayoutSize {
228    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
229        match *self {
230            Self::Fraction(value) => write!(formatter, "{value}"),
231            Self::Px(value) => write_length(formatter, value, "px"),
232        }
233    }
234}
235
236fn invalid_length(token: &str, percent: bool) -> String {
237    let hint = if token.contains(' ') {
238        format!(" (write {})", token.replace(' ', ""))
239    } else if token.ends_with("em") {
240        " (em and rem are not supported: write px or a number)".to_owned()
241    } else {
242        String::new()
243    };
244    let forms = if percent {
245        "a number, \"<n>px\", or \"<n>%\""
246    } else {
247        "a number or \"<n>px\""
248    };
249    format!("invalid length \"{token}\"{hint}: write {forms}")
250}
251
252/// A visitor for a value written as a number or a string.
253struct NumberOrString<T> {
254    expecting: &'static str,
255    number: fn(f32) -> T,
256    string: fn(&str) -> Result<T, String>,
257}
258
259impl<T> Visitor<'_> for NumberOrString<T> {
260    type Value = T;
261
262    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
263        formatter.write_str(self.expecting)
264    }
265
266    #[allow(clippy::cast_possible_truncation)]
267    fn visit_f64<E: de::Error>(self, value: f64) -> Result<T, E> {
268        Ok((self.number)(value as f32))
269    }
270
271    #[allow(clippy::cast_precision_loss)]
272    fn visit_u64<E: de::Error>(self, value: u64) -> Result<T, E> {
273        Ok((self.number)(value as f32))
274    }
275
276    #[allow(clippy::cast_precision_loss)]
277    fn visit_i64<E: de::Error>(self, value: i64) -> Result<T, E> {
278        Ok((self.number)(value as f32))
279    }
280
281    fn visit_str<E: de::Error>(self, value: &str) -> Result<T, E> {
282        (self.string)(value).map_err(E::custom)
283    }
284}
285
286impl<'de> Deserialize<'de> for LayoutLength {
287    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
288        deserializer.deserialize_any(NumberOrString {
289            expecting: "a length: a number, \"<n>px\", or \"<n>%\"",
290            number: Self::Fraction,
291            string: Self::parse,
292        })
293    }
294}
295
296impl Serialize for LayoutLength {
297    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
298        match self {
299            Self::Fraction(value) => serializer.serialize_f32(*value),
300            other => serializer.collect_str(other),
301        }
302    }
303}
304
305impl<'de> Deserialize<'de> for LayoutSize {
306    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
307        deserializer.deserialize_any(NumberOrString {
308            expecting: "a length: a number or \"<n>px\"",
309            number: Self::Fraction,
310            string: Self::parse,
311        })
312    }
313}
314
315impl Serialize for LayoutSize {
316    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
317        match self {
318            Self::Fraction(value) => serializer.serialize_f32(*value),
319            other @ Self::Px(_) => serializer.collect_str(other),
320        }
321    }
322}
323
324/// A length on each side of a box (padding or margin). Missing sides are 0.
325///
326/// Written as one length, as the CSS shorthand (`"8px 16px"`: one to four lengths, top first,
327/// clockwise, missing ones repeating the opposite side), or as the sides object.
328#[derive(Copy, Clone, Debug, Default, PartialEq)]
329pub struct Insets {
330    /// Top side.
331    pub top: LayoutSize,
332    /// Right side.
333    pub right: LayoutSize,
334    /// Bottom side.
335    pub bottom: LayoutSize,
336    /// Left side.
337    pub left: LayoutSize,
338}
339
340impl Insets {
341    /// The sides, top first, clockwise.
342    #[must_use]
343    pub const fn sides(self) -> [LayoutSize; 4] {
344        [self.top, self.right, self.bottom, self.left]
345    }
346
347    /// Insets from sides, top first, clockwise.
348    #[must_use]
349    pub const fn from_sides([top, right, bottom, left]: [LayoutSize; 4]) -> Self {
350        Self {
351            top,
352            right,
353            bottom,
354            left,
355        }
356    }
357
358    /// The same insets with pixels converted to fractions.
359    #[must_use]
360    pub fn without_px(self, shorter_side: f32) -> Self {
361        Self::from_sides(self.sides().map(|side| side.without_px(shorter_side)))
362    }
363
364    fn parse(text: &str) -> Result<Self, String> {
365        let sides = tokens(text)
366            .map(|token| LayoutSize::parse_token(token, false))
367            .collect::<Result<Vec<_>, _>>()?;
368        let [top, right, bottom, left] = shorthand(&sides)?;
369        Ok(Self {
370            top,
371            right,
372            bottom,
373            left,
374        })
375    }
376}
377
378/// The four sides of a CSS shorthand of one to four values.
379fn shorthand<T: Copy>(values: &[T]) -> Result<[T; 4], String> {
380    match *values {
381        [all] => Ok([all; 4]),
382        [vertical, horizontal] => Ok([vertical, horizontal, vertical, horizontal]),
383        [top, horizontal, bottom] => Ok([top, horizontal, bottom, horizontal]),
384        [top, right, bottom, left] => Ok([top, right, bottom, left]),
385        _ => Err(format!("expected 1 to 4 lengths, got {}", values.len())),
386    }
387}
388
389#[derive(Deserialize)]
390#[serde(deny_unknown_fields)]
391struct InsetsObject {
392    #[serde(default)]
393    top: LayoutSize,
394    #[serde(default)]
395    right: LayoutSize,
396    #[serde(default)]
397    bottom: LayoutSize,
398    #[serde(default)]
399    left: LayoutSize,
400}
401
402struct InsetsVisitor;
403
404impl<'de> Visitor<'de> for InsetsVisitor {
405    type Value = Insets;
406
407    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
408        formatter.write_str("insets: a length, one to four lengths, or the sides object")
409    }
410
411    #[allow(clippy::cast_possible_truncation)]
412    fn visit_f64<E: de::Error>(self, value: f64) -> Result<Insets, E> {
413        Ok(Insets::from_sides([LayoutSize::Fraction(value as f32); 4]))
414    }
415
416    #[allow(clippy::cast_precision_loss)]
417    fn visit_u64<E: de::Error>(self, value: u64) -> Result<Insets, E> {
418        Ok(Insets::from_sides([LayoutSize::Fraction(value as f32); 4]))
419    }
420
421    #[allow(clippy::cast_precision_loss)]
422    fn visit_i64<E: de::Error>(self, value: i64) -> Result<Insets, E> {
423        Ok(Insets::from_sides([LayoutSize::Fraction(value as f32); 4]))
424    }
425
426    fn visit_str<E: de::Error>(self, value: &str) -> Result<Insets, E> {
427        Insets::parse(value).map_err(E::custom)
428    }
429
430    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Insets, A::Error> {
431        let sides = InsetsObject::deserialize(de::value::MapAccessDeserializer::new(map))?;
432        Ok(Insets {
433            top: sides.top,
434            right: sides.right,
435            bottom: sides.bottom,
436            left: sides.left,
437        })
438    }
439}
440
441impl<'de> Deserialize<'de> for Insets {
442    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
443        deserializer.deserialize_any(InsetsVisitor)
444    }
445}
446
447impl Serialize for Insets {
448    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
449        let mut sides = serializer.serialize_struct("Insets", 4)?;
450        sides.serialize_field("top", &self.top)?;
451        sides.serialize_field("right", &self.right)?;
452        sides.serialize_field("bottom", &self.bottom)?;
453        sides.serialize_field("left", &self.left)?;
454        sides.end()
455    }
456}
457
458/// A box's offset after layout: `x` right, `y` down.
459///
460/// Written as the object, or as the CSS `translate` value: one or two lengths, `y` 0 when
461/// missing.
462#[derive(Copy, Clone, Debug, Default, PartialEq)]
463pub struct LayoutOffset {
464    /// Rightward.
465    pub x: LayoutSize,
466    /// Downward.
467    pub y: LayoutSize,
468}
469
470impl LayoutOffset {
471    /// The same offset with pixels converted to fractions.
472    #[must_use]
473    pub fn without_px(self, shorter_side: f32) -> Self {
474        Self {
475            x: self.x.without_px(shorter_side),
476            y: self.y.without_px(shorter_side),
477        }
478    }
479
480    fn parse(text: &str) -> Result<Self, String> {
481        let values = tokens(text)
482            .map(|token| LayoutSize::parse_token(token, false))
483            .collect::<Result<Vec<_>, _>>()?;
484        match *values {
485            [x] => Ok(Self {
486                x,
487                y: LayoutSize::default(),
488            }),
489            [x, y] => Ok(Self { x, y }),
490            _ => Err(format!("expected 1 or 2 lengths, got {}", values.len())),
491        }
492    }
493}
494
495#[derive(Deserialize)]
496#[serde(deny_unknown_fields)]
497struct OffsetObject {
498    x: LayoutSize,
499    y: LayoutSize,
500}
501
502struct OffsetVisitor;
503
504impl<'de> Visitor<'de> for OffsetVisitor {
505    type Value = LayoutOffset;
506
507    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
508        formatter.write_str("an offset: one or two lengths, or {x, y}")
509    }
510
511    fn visit_str<E: de::Error>(self, value: &str) -> Result<LayoutOffset, E> {
512        LayoutOffset::parse(value).map_err(E::custom)
513    }
514
515    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<LayoutOffset, A::Error> {
516        let OffsetObject { x, y } =
517            OffsetObject::deserialize(de::value::MapAccessDeserializer::new(map))?;
518        Ok(LayoutOffset { x, y })
519    }
520}
521
522impl<'de> Deserialize<'de> for LayoutOffset {
523    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
524        deserializer.deserialize_any(OffsetVisitor)
525    }
526}
527
528impl Serialize for LayoutOffset {
529    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
530        let mut offset = serializer.serialize_struct("LayoutOffset", 2)?;
531        offset.serialize_field("x", &self.x)?;
532        offset.serialize_field("y", &self.y)?;
533        offset.end()
534    }
535}
536
537/// One side of `minmax()`: how large a grid track may be at least or at most.
538#[derive(Copy, Clone, Debug, PartialEq)]
539pub enum TrackBreadth {
540    /// A length or a percent of the grid's content box.
541    Length(LayoutLength),
542    /// A share of the free space, `<n>fr`; only as the largest size.
543    Fr(f32),
544    /// `auto`.
545    Auto,
546    /// `min-content`.
547    MinContent,
548    /// `max-content`.
549    MaxContent,
550}
551
552impl TrackBreadth {
553    const fn is_fixed(self) -> bool {
554        matches!(self, Self::Length(_))
555    }
556
557    fn without_px(self, shorter_side: f32) -> Self {
558        match self {
559            Self::Length(length) => Self::Length(length.without_px(shorter_side)),
560            other => other,
561        }
562    }
563
564    fn parse(token: &str, max: bool) -> Result<Self, String> {
565        match token {
566            "auto" => Ok(Self::Auto),
567            "min-content" => Ok(Self::MinContent),
568            "max-content" => Ok(Self::MaxContent),
569            _ => {
570                if let Some(share) = token.strip_suffix("fr").and_then(parse_number) {
571                    return if max {
572                        Ok(Self::Fr(share))
573                    } else {
574                        Err(format!("a minimum size cannot be fr: \"{token}\""))
575                    };
576                }
577                LayoutLength::parse(token)
578                    .map(Self::Length)
579                    .map_err(|_| unknown_track(token))
580            }
581        }
582    }
583}
584
585impl fmt::Display for TrackBreadth {
586    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
587        match self {
588            Self::Length(length) => write!(formatter, "{length}"),
589            Self::Fr(share) => write_length(formatter, *share, "fr"),
590            Self::Auto => formatter.write_str("auto"),
591            Self::MinContent => formatter.write_str("min-content"),
592            Self::MaxContent => formatter.write_str("max-content"),
593        }
594    }
595}
596
597/// The size of one grid track.
598#[derive(Copy, Clone, Debug, PartialEq)]
599pub enum TrackSize {
600    /// One breadth, as CSS reads it: a length is fixed, `<n>fr` is `minmax(auto, <n>fr)`, a
601    /// keyword sizes by content.
602    Breadth(TrackBreadth),
603    /// `minmax(min, max)`.
604    MinMax(TrackBreadth, TrackBreadth),
605    /// `fit-content(limit)`.
606    FitContent(LayoutLength),
607}
608
609impl TrackSize {
610    /// Whether it is a CSS fixed size, as `auto-fill` and `auto-fit` need: a length, or
611    /// `minmax()` with a length on one side and no flexible or content minimum.
612    #[must_use]
613    pub const fn is_fixed(self) -> bool {
614        match self {
615            Self::Breadth(breadth) => breadth.is_fixed(),
616            Self::MinMax(min, max) => {
617                min.is_fixed() || (max.is_fixed() && !matches!(min, TrackBreadth::Fr(_)))
618            }
619            Self::FitContent(_) => false,
620        }
621    }
622
623    fn without_px(self, shorter_side: f32) -> Self {
624        match self {
625            Self::Breadth(breadth) => Self::Breadth(breadth.without_px(shorter_side)),
626            Self::MinMax(min, max) => {
627                Self::MinMax(min.without_px(shorter_side), max.without_px(shorter_side))
628            }
629            Self::FitContent(limit) => Self::FitContent(limit.without_px(shorter_side)),
630        }
631    }
632
633    fn lengths(self) -> impl Iterator<Item = LayoutLength> {
634        let breadth = |breadth: TrackBreadth| match breadth {
635            TrackBreadth::Length(length) => Some(length),
636            _ => None,
637        };
638        let (first, second) = match self {
639            Self::Breadth(single) => (breadth(single), None),
640            Self::MinMax(min, max) => (breadth(min), breadth(max)),
641            Self::FitContent(limit) => (Some(limit), None),
642        };
643        first.into_iter().chain(second)
644    }
645
646    fn fr(self) -> Option<f32> {
647        match self {
648            Self::Breadth(TrackBreadth::Fr(share)) | Self::MinMax(_, TrackBreadth::Fr(share)) => {
649                Some(share)
650            }
651            _ => None,
652        }
653    }
654}
655
656impl fmt::Display for TrackSize {
657    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
658        match self {
659            Self::Breadth(breadth) => write!(formatter, "{breadth}"),
660            Self::MinMax(min, max) => write!(formatter, "minmax({min}, {max})"),
661            Self::FitContent(limit) => write!(formatter, "fit-content({limit})"),
662        }
663    }
664}
665
666/// How often `repeat()` repeats its tracks.
667#[derive(Copy, Clone, Debug, Eq, PartialEq)]
668pub enum RepeatCount {
669    /// That many times.
670    Count(u16),
671    /// `auto-fill`: as many as fit.
672    AutoFill,
673    /// `auto-fit`: as many as fit, empty ones collapsed.
674    AutoFit,
675}
676
677impl fmt::Display for RepeatCount {
678    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
679        match self {
680            Self::Count(count) => write!(formatter, "{count}"),
681            Self::AutoFill => formatter.write_str("auto-fill"),
682            Self::AutoFit => formatter.write_str("auto-fit"),
683        }
684    }
685}
686
687/// One entry of a track list: a track, or `repeat()` of some.
688#[derive(Clone, Debug, PartialEq)]
689pub enum TrackComponent {
690    /// One track.
691    Single(TrackSize),
692    /// `repeat(count, tracks)`.
693    Repeat(RepeatCount, Vec<TrackSize>),
694}
695
696/// A grid track list as CSS writes it: `"1fr 2fr 120px"`, `"repeat(3, minmax(100px, 1fr))"`,
697/// `"repeat(auto-fill, 160px)"`. Named lines are not supported.
698#[derive(Clone, Debug, Default, PartialEq)]
699pub struct TrackList(pub Vec<TrackComponent>);
700
701impl TrackList {
702    /// The explicit track count, with each repeat count applied (an automatic repeat counts
703    /// once).
704    #[must_use]
705    pub fn track_count(&self) -> usize {
706        self.0
707            .iter()
708            .map(|component| match component {
709                TrackComponent::Single(_) => 1,
710                TrackComponent::Repeat(RepeatCount::Count(count), tracks) => {
711                    usize::from(*count) * tracks.len()
712                }
713                TrackComponent::Repeat(_, tracks) => tracks.len(),
714            })
715            .sum()
716    }
717
718    /// Every track size, once each, repeats included once.
719    pub fn sizes(&self) -> impl Iterator<Item = TrackSize> + '_ {
720        self.0.iter().flat_map(|component| match component {
721            TrackComponent::Single(size) => std::slice::from_ref(size).iter().copied(),
722            TrackComponent::Repeat(_, tracks) => tracks.iter().copied(),
723        })
724    }
725
726    /// Every length in it, for range checks.
727    pub fn lengths(&self) -> impl Iterator<Item = LayoutLength> + '_ {
728        self.sizes().flat_map(TrackSize::lengths)
729    }
730
731    /// Every `fr` share in it.
732    pub fn shares(&self) -> impl Iterator<Item = f32> + '_ {
733        self.sizes().filter_map(TrackSize::fr)
734    }
735
736    /// The same list with pixels converted to fractions.
737    #[must_use]
738    pub fn without_px(&self, shorter_side: f32) -> Self {
739        Self(
740            self.0
741                .iter()
742                .map(|component| match component {
743                    TrackComponent::Single(size) => {
744                        TrackComponent::Single(size.without_px(shorter_side))
745                    }
746                    TrackComponent::Repeat(count, tracks) => TrackComponent::Repeat(
747                        *count,
748                        tracks
749                            .iter()
750                            .map(|size| size.without_px(shorter_side))
751                            .collect(),
752                    ),
753                })
754                .collect(),
755        )
756    }
757
758    fn parse(text: &str) -> Result<Self, String> {
759        let mut parser = TrackParser { text, at: 0 };
760        let mut components = Vec::new();
761        while parser.skip_spaces() {
762            if parser.rest().starts_with("repeat(") {
763                parser.at += "repeat(".len();
764                components.push(parser.repeat()?);
765            } else {
766                components.push(TrackComponent::Single(parser.track()?));
767            }
768        }
769        if components.is_empty() {
770            return Err("expected at least one track".to_owned());
771        }
772        Ok(Self(components))
773    }
774}
775
776impl fmt::Display for TrackList {
777    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
778        for (index, component) in self.0.iter().enumerate() {
779            if index > 0 {
780                formatter.write_char(' ')?;
781            }
782            match component {
783                TrackComponent::Single(size) => write!(formatter, "{size}")?,
784                TrackComponent::Repeat(count, tracks) => {
785                    write!(formatter, "repeat({count},")?;
786                    for size in tracks {
787                        write!(formatter, " {size}")?;
788                    }
789                    formatter.write_char(')')?;
790                }
791            }
792        }
793        Ok(())
794    }
795}
796
797/// The message for a track that is not one, with the spelling likely meant.
798fn unknown_track(token: &str) -> String {
799    let hint = match token {
800        "min_content" => Some("min-content".to_owned()),
801        "max_content" => Some("max-content".to_owned()),
802        "auto_fill" => Some("auto-fill".to_owned()),
803        "auto_fit" => Some("auto-fit".to_owned()),
804        _ if token.starts_with('[') => {
805            return format!("named grid lines are not supported: \"{token}\"");
806        }
807        _ if token.contains(' ') => Some(token.replace(' ', "")),
808        _ => None,
809    };
810    match hint {
811        Some(hint) => format!("unknown track \"{token}\" (write {hint})"),
812        None => format!("unknown track \"{token}\""),
813    }
814}
815
816struct TrackParser<'a> {
817    text: &'a str,
818    at: usize,
819}
820
821impl<'a> TrackParser<'a> {
822    fn rest(&self) -> &'a str {
823        &self.text[self.at..]
824    }
825
826    /// Skips spaces; whether anything is left.
827    fn skip_spaces(&mut self) -> bool {
828        while self.rest().starts_with(' ') {
829            self.at += 1;
830        }
831        !self.rest().is_empty()
832    }
833
834    /// The next token: up to a space, a comma or a parenthesis.
835    fn token(&mut self) -> &'a str {
836        let rest = &self.text[self.at..];
837        let end = rest.find([' ', ',', '(', ')']).unwrap_or(rest.len());
838        self.at += end;
839        &rest[..end]
840    }
841
842    /// `expected` after optional spaces.
843    fn expect(&mut self, expected: char) -> Result<(), String> {
844        self.skip_spaces();
845        if self.rest().starts_with(expected) {
846            self.at += 1;
847            Ok(())
848        } else {
849            Err(format!("expected \"{expected}\" in \"{}\"", self.text))
850        }
851    }
852
853    fn track(&mut self) -> Result<TrackSize, String> {
854        let start = self.at;
855        let token = self.token();
856        match token {
857            "minmax" | "fit-content" if self.rest().starts_with('(') => {
858                self.at += 1;
859                if token == "fit-content" {
860                    let limit = self.breadth(false)?;
861                    self.expect(')')?;
862                    return match limit {
863                        TrackBreadth::Length(limit) => Ok(TrackSize::FitContent(limit)),
864                        _ => Err(format!(
865                            "fit-content takes a length: \"{}\"",
866                            &self.text[start..self.at]
867                        )),
868                    };
869                }
870                let min = self.breadth(false)?;
871                self.expect(',')?;
872                let max = self.breadth(true)?;
873                self.expect(')')?;
874                Ok(TrackSize::MinMax(min, max))
875            }
876            "" => Err(format!("expected a track in \"{}\"", self.text)),
877            "fit_content" | "min_max" => Err(format!(
878                "unknown track \"{token}\" (write {})",
879                token.replace('_', "-").replace("min-max", "minmax")
880            )),
881            _ => {
882                // A unit standing apart from its number: "1 fr".
883                let after = self.at;
884                if parse_number(token).is_some() && self.skip_spaces() {
885                    let mark = self.at;
886                    let unit = self.token();
887                    if matches!(unit, "fr" | "px" | "%") {
888                        return Err(unknown_track(&self.text[start..self.at]));
889                    }
890                    self.at = mark;
891                }
892                self.at = after;
893                TrackBreadth::parse(token, true).map(TrackSize::Breadth)
894            }
895        }
896    }
897
898    fn breadth(&mut self, max: bool) -> Result<TrackBreadth, String> {
899        self.skip_spaces();
900        let token = self.token();
901        if token.is_empty() {
902            return Err(format!("expected a track size in \"{}\"", self.text));
903        }
904        TrackBreadth::parse(token, max)
905    }
906
907    fn repeat(&mut self) -> Result<TrackComponent, String> {
908        self.skip_spaces();
909        let token = self.token();
910        let count = match token {
911            "auto-fill" => RepeatCount::AutoFill,
912            "auto-fit" => RepeatCount::AutoFit,
913            "auto_fill" | "auto_fit" => {
914                return Err(format!(
915                    "unknown repeat count \"{token}\" (write {})",
916                    token.replace('_', "-")
917                ));
918            }
919            _ => token
920                .parse::<u16>()
921                .ok()
922                .filter(|_| token.bytes().all(|byte| byte.is_ascii_digit()))
923                .map(RepeatCount::Count)
924                .ok_or_else(|| format!("unknown repeat count \"{token}\""))?,
925        };
926        self.expect(',')?;
927        let mut tracks = Vec::new();
928        loop {
929            if !self.skip_spaces() {
930                return Err(format!("expected \")\" in \"{}\"", self.text));
931            }
932            if self.rest().starts_with(')') {
933                self.at += 1;
934                break;
935            }
936            if self.rest().starts_with("repeat(") {
937                return Err("repeat() cannot hold repeat()".to_owned());
938            }
939            tracks.push(self.track()?);
940        }
941        if tracks.is_empty() {
942            return Err("repeat() needs at least one track".to_owned());
943        }
944        Ok(TrackComponent::Repeat(count, tracks))
945    }
946}
947
948impl<'de> Deserialize<'de> for TrackList {
949    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
950        let text = String::deserialize(deserializer)?;
951        Self::parse(&text).map_err(de::Error::custom)
952    }
953}
954
955impl Serialize for TrackList {
956    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
957        serializer.collect_str(self)
958    }
959}
960
961/// One edge of a grid item's placement.
962#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
963pub enum GridEdge {
964    /// Placed automatically.
965    #[default]
966    Auto,
967    /// At a line: 1 is the first, -1 the last explicit line.
968    Line(i16),
969    /// So many tracks from the other edge.
970    Span(u16),
971}
972
973impl GridEdge {
974    fn parse(text: &str) -> Result<Self, String> {
975        let words = tokens(text).collect::<Vec<_>>();
976        let integer = |word: &str| {
977            let digits = word.strip_prefix('-').unwrap_or(word);
978            (!digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()))
979                .then(|| word.parse::<i16>().ok())
980                .flatten()
981        };
982        match *words {
983            ["auto"] => Ok(Self::Auto),
984            ["span", count] => integer(count)
985                .and_then(|count| u16::try_from(count).ok())
986                .map(Self::Span)
987                .ok_or_else(|| invalid_line(text)),
988            [line] => integer(line)
989                .map(Self::Line)
990                .ok_or_else(|| invalid_line(text)),
991            _ => Err(invalid_line(text)),
992        }
993    }
994}
995
996fn invalid_line(text: &str) -> String {
997    let text = text.trim_matches(' ');
998    let named = text
999        .split([' ', '/'])
1000        .filter(|word| !word.is_empty())
1001        .any(|word| {
1002            word != "span"
1003                && word != "auto"
1004                && word
1005                    .bytes()
1006                    .next()
1007                    .is_some_and(|byte| byte.is_ascii_alphabetic())
1008        });
1009    if named {
1010        format!("named grid lines are not supported: \"{text}\"")
1011    } else {
1012        format!("invalid grid line \"{text}\": write a line number, \"span <n>\", or \"auto\"")
1013    }
1014}
1015
1016impl fmt::Display for GridEdge {
1017    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1018        match self {
1019            Self::Auto => formatter.write_str("auto"),
1020            Self::Line(line) => write!(formatter, "{line}"),
1021            Self::Span(count) => write!(formatter, "span {count}"),
1022        }
1023    }
1024}
1025
1026/// Where a grid item lies on one axis, as CSS `grid_column` writes it: `2`, `"1 / 3"`,
1027/// `"span 2"`, `"2 / span 3"`, `"auto"`. A missing end is `auto`.
1028#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1029pub struct GridPlacement {
1030    /// The start edge.
1031    pub start: GridEdge,
1032    /// The end edge.
1033    pub end: GridEdge,
1034}
1035
1036impl GridPlacement {
1037    /// Every edge of it.
1038    #[must_use]
1039    pub const fn edges(self) -> [GridEdge; 2] {
1040        [self.start, self.end]
1041    }
1042
1043    fn parse(text: &str) -> Result<Self, String> {
1044        let (start, end) = match text.split_once('/') {
1045            Some((start, end)) => (start, Some(end)),
1046            None => (text, None),
1047        };
1048        if end.is_some_and(|end| end.contains('/')) {
1049            return Err(invalid_line(text));
1050        }
1051        let edge = |text| GridEdge::parse(text).map_err(|_| invalid_line(text));
1052        Ok(Self {
1053            start: edge(start)?,
1054            end: end.map_or(Ok(GridEdge::Auto), edge)?,
1055        })
1056    }
1057}
1058
1059impl fmt::Display for GridPlacement {
1060    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1061        match self.end {
1062            GridEdge::Auto => write!(formatter, "{}", self.start),
1063            end => write!(formatter, "{} / {end}", self.start),
1064        }
1065    }
1066}
1067
1068struct PlacementVisitor;
1069
1070impl Visitor<'_> for PlacementVisitor {
1071    type Value = GridPlacement;
1072
1073    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1074        formatter.write_str("a grid line: a line number, \"1 / 3\", \"span 2\", or \"auto\"")
1075    }
1076
1077    fn visit_u64<E: de::Error>(self, value: u64) -> Result<GridPlacement, E> {
1078        i16::try_from(value)
1079            .map(|line| GridPlacement {
1080                start: GridEdge::Line(line),
1081                end: GridEdge::Auto,
1082            })
1083            .map_err(|_| E::custom(invalid_line(&value.to_string())))
1084    }
1085
1086    fn visit_i64<E: de::Error>(self, value: i64) -> Result<GridPlacement, E> {
1087        i16::try_from(value)
1088            .map(|line| GridPlacement {
1089                start: GridEdge::Line(line),
1090                end: GridEdge::Auto,
1091            })
1092            .map_err(|_| E::custom(invalid_line(&value.to_string())))
1093    }
1094
1095    /// A JSON number with a fraction is a line when it is whole, as in JavaScript.
1096    #[allow(clippy::cast_possible_truncation)]
1097    fn visit_f64<E: de::Error>(self, value: f64) -> Result<GridPlacement, E> {
1098        if value.fract() == 0.0 && (f64::from(i16::MIN)..=f64::from(i16::MAX)).contains(&value) {
1099            return Ok(GridPlacement {
1100                start: GridEdge::Line(value as i16),
1101                end: GridEdge::Auto,
1102            });
1103        }
1104        Err(E::custom(invalid_line(&value.to_string())))
1105    }
1106
1107    fn visit_str<E: de::Error>(self, value: &str) -> Result<GridPlacement, E> {
1108        GridPlacement::parse(value).map_err(E::custom)
1109    }
1110}
1111
1112impl<'de> Deserialize<'de> for GridPlacement {
1113    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1114        deserializer.deserialize_any(PlacementVisitor)
1115    }
1116}
1117
1118impl Serialize for GridPlacement {
1119    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1120        match (self.start, self.end) {
1121            (GridEdge::Line(line), GridEdge::Auto) => serializer.serialize_i16(line),
1122            _ => serializer.collect_str(self),
1123        }
1124    }
1125}
1126
1127#[cfg(feature = "schema")]
1128mod schema {
1129    //! The schema of each form. String grammar is the parser's; patterns state it where a
1130    //! regular expression can.
1131
1132    use super::{GridPlacement, Insets, LayoutLength, LayoutOffset, LayoutSize, TrackList};
1133    use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
1134    use std::borrow::Cow;
1135
1136    const NUMBER: &str = r"-?(\d+\.?\d*|\.\d+)";
1137
1138    fn size_pattern() -> String {
1139        format!("^ *{NUMBER}(px)? *$")
1140    }
1141
1142    fn length_pattern() -> String {
1143        format!("^ *{NUMBER}(px|%)? *$")
1144    }
1145
1146    fn sides_pattern() -> String {
1147        format!("^ *{NUMBER}(px)?( +{NUMBER}(px)?){{0,3}} *$")
1148    }
1149
1150    impl JsonSchema for LayoutLength {
1151        fn schema_name() -> Cow<'static, str> {
1152            "LayoutLength".into()
1153        }
1154
1155        fn json_schema(_: &mut SchemaGenerator) -> Schema {
1156            json_schema!({
1157                "description": "A length: a number is a fraction of the layout picture's shorter side, \"<n>px\" pixels of the project canvas, \"<n>%\" a percent of the parent's content box along the field's axis.",
1158                "anyOf": [
1159                    { "type": "number", "format": "float" },
1160                    { "type": "string", "pattern": length_pattern() },
1161                ],
1162            })
1163        }
1164    }
1165
1166    impl JsonSchema for LayoutSize {
1167        fn schema_name() -> Cow<'static, str> {
1168            "LayoutSize".into()
1169        }
1170
1171        fn json_schema(_: &mut SchemaGenerator) -> Schema {
1172            json_schema!({
1173                "description": "A length that may not be a percent: a number is a fraction of the layout picture's shorter side, \"<n>px\" pixels of the project canvas.",
1174                "anyOf": [
1175                    { "type": "number", "format": "float" },
1176                    { "type": "string", "pattern": size_pattern() },
1177                ],
1178            })
1179        }
1180    }
1181
1182    impl JsonSchema for Insets {
1183        fn schema_name() -> Cow<'static, str> {
1184            "Insets".into()
1185        }
1186
1187        fn json_schema(generator: &mut SchemaGenerator) -> Schema {
1188            let side = generator.subschema_for::<LayoutSize>();
1189            json_schema!({
1190                "description": "A length on each side of a box: one length for every side, the CSS shorthand of one to four lengths (\"8px 16px\": top first, clockwise), or the sides object, missing sides 0.",
1191                "anyOf": [
1192                    { "type": "number", "format": "float" },
1193                    { "type": "string", "pattern": sides_pattern() },
1194                    {
1195                        "type": "object",
1196                        "properties": {
1197                            "top": side,
1198                            "right": side,
1199                            "bottom": side,
1200                            "left": side,
1201                        },
1202                        "additionalProperties": false,
1203                    },
1204                ],
1205            })
1206        }
1207    }
1208
1209    impl JsonSchema for LayoutOffset {
1210        fn schema_name() -> Cow<'static, str> {
1211            "LayoutOffset".into()
1212        }
1213
1214        fn json_schema(generator: &mut SchemaGenerator) -> Schema {
1215            let side = generator.subschema_for::<LayoutSize>();
1216            json_schema!({
1217                "description": "An offset, x right and y down: one or two lengths as CSS translate writes them (y 0 when missing), or {x, y}.",
1218                "anyOf": [
1219                    {
1220                        "type": "string",
1221                        "pattern": format!("^ *{NUMBER}(px)?( +{NUMBER}(px)?)? *$"),
1222                    },
1223                    {
1224                        "type": "object",
1225                        "properties": { "x": side, "y": side },
1226                        "required": ["x", "y"],
1227                        "additionalProperties": false,
1228                    },
1229                ],
1230            })
1231        }
1232    }
1233
1234    impl JsonSchema for TrackList {
1235        fn schema_name() -> Cow<'static, str> {
1236            "TrackList".into()
1237        }
1238
1239        fn json_schema(_: &mut SchemaGenerator) -> Schema {
1240            json_schema!({
1241                "description": "A grid track list as CSS writes it: \"1fr 2fr 120px\", \"repeat(3, minmax(100px, 1fr))\", \"repeat(auto-fill, 160px)\", \"auto min-content max-content\", \"fit-content(200px)\". A bare number is a fraction of the picture's shorter side. Named lines are not supported.",
1242                "type": "string",
1243            })
1244        }
1245    }
1246
1247    impl JsonSchema for GridPlacement {
1248        fn schema_name() -> Cow<'static, str> {
1249            "GridPlacement".into()
1250        }
1251
1252        fn json_schema(_: &mut SchemaGenerator) -> Schema {
1253            json_schema!({
1254                "description": "Where a grid item lies on one axis, as CSS writes it: 2, \"1 / 3\", \"span 2\", \"2 / span 3\", \"auto\". Lines count from 1, or from -1 at the end.",
1255                "anyOf": [
1256                    { "type": "integer", "minimum": -32768, "maximum": 32767 },
1257                    { "type": "string" },
1258                ],
1259            })
1260        }
1261    }
1262}
1263
1264#[cfg(test)]
1265#[path = "layout_values_tests.rs"]
1266mod tests;