1use serde::de::{self, Deserializer, MapAccess, Visitor};
14use serde::ser::{SerializeStruct, Serializer};
15use serde::{Deserialize, Serialize};
16use std::fmt::{self, Write as _};
17
18pub(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
32pub const MAX_LAYOUT_FRACTION: f32 = 1_024.0;
34#[allow(clippy::cast_precision_loss)]
36pub const MAX_LAYOUT_PX: f32 = 1_024.0 * crate::MAX_CANVAS_DIMENSION as f32;
37pub 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#[derive(Copy, Clone, Debug, PartialEq)]
50pub enum LayoutLength {
51 Fraction(f32),
53 Px(f32),
56 Percent(f32),
58}
59
60impl Default for LayoutLength {
61 fn default() -> Self {
62 Self::Fraction(0.0)
63 }
64}
65
66impl LayoutLength {
67 #[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 #[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 #[must_use]
89 pub const fn is_percent(self) -> bool {
90 matches!(self, Self::Percent(_))
91 }
92
93 #[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 #[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#[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#[derive(Copy, Clone, Debug, PartialEq)]
148pub enum LayoutSize {
149 Fraction(f32),
151 Px(f32),
153}
154
155impl Default for LayoutSize {
156 fn default() -> Self {
157 Self::Fraction(0.0)
158 }
159}
160
161impl LayoutSize {
162 #[must_use]
164 pub const fn value(self) -> f32 {
165 match self {
166 Self::Fraction(value) | Self::Px(value) => value,
167 }
168 }
169
170 #[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 #[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 #[must_use]
193 pub fn fraction(self, shorter_side: f32) -> f32 {
194 self.without_px(shorter_side).value()
195 }
196
197 #[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 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
252struct 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#[derive(Copy, Clone, Debug, Default, PartialEq)]
329pub struct Insets {
330 pub top: LayoutSize,
332 pub right: LayoutSize,
334 pub bottom: LayoutSize,
336 pub left: LayoutSize,
338}
339
340impl Insets {
341 #[must_use]
343 pub const fn sides(self) -> [LayoutSize; 4] {
344 [self.top, self.right, self.bottom, self.left]
345 }
346
347 #[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 #[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
378fn 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#[derive(Copy, Clone, Debug, Default, PartialEq)]
463pub struct LayoutOffset {
464 pub x: LayoutSize,
466 pub y: LayoutSize,
468}
469
470impl LayoutOffset {
471 #[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#[derive(Copy, Clone, Debug, PartialEq)]
539pub enum TrackBreadth {
540 Length(LayoutLength),
542 Fr(f32),
544 Auto,
546 MinContent,
548 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#[derive(Copy, Clone, Debug, PartialEq)]
599pub enum TrackSize {
600 Breadth(TrackBreadth),
603 MinMax(TrackBreadth, TrackBreadth),
605 FitContent(LayoutLength),
607}
608
609impl TrackSize {
610 #[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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
668pub enum RepeatCount {
669 Count(u16),
671 AutoFill,
673 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#[derive(Clone, Debug, PartialEq)]
689pub enum TrackComponent {
690 Single(TrackSize),
692 Repeat(RepeatCount, Vec<TrackSize>),
694}
695
696#[derive(Clone, Debug, Default, PartialEq)]
699pub struct TrackList(pub Vec<TrackComponent>);
700
701impl TrackList {
702 #[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 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 pub fn lengths(&self) -> impl Iterator<Item = LayoutLength> + '_ {
728 self.sizes().flat_map(TrackSize::lengths)
729 }
730
731 pub fn shares(&self) -> impl Iterator<Item = f32> + '_ {
733 self.sizes().filter_map(TrackSize::fr)
734 }
735
736 #[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
797fn 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 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 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 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 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#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
963pub enum GridEdge {
964 #[default]
966 Auto,
967 Line(i16),
969 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#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1029pub struct GridPlacement {
1030 pub start: GridEdge,
1032 pub end: GridEdge,
1034}
1035
1036impl GridPlacement {
1037 #[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 #[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 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;