1use crate::animation::visit_keyed;
13use crate::checks::{
14 Checked, ValueIssue, ValueProblem, animated, any, non_negative, scalar, unit, validate_paint,
15 vec2,
16};
17use crate::layout_values::{
18 GridEdge, GridPlacement, Insets, LayoutLength, LayoutOffset, LayoutSize, RepeatCount,
19 TrackComponent, TrackList,
20};
21use crate::{
22 Animated, FONT_WEIGHT_RANGE, Interpolation, LETTER_SPACING_RANGE, LINE_HEIGHT_RANGE,
23 MAX_FONT_FAMILY_BYTES, MAX_TEXT_CONTENT_BYTES, Paint, Rgba, ShapeIssue, ShapeItem, TextAlign,
24 TextShadow, TextStroke, Vec2,
25};
26use serde::{Deserialize, Serialize};
27use std::fmt;
28
29pub const MAX_LAYOUT_NODES: usize = 256;
31pub const MAX_LAYOUT_DEPTH: usize = 16;
33pub const MAX_LAYOUT_TEXTS: usize = 64;
35pub const MAX_LAYOUT_ISOLATED: usize = 16;
37pub const MAX_LAYOUT_FONT_SIZE: f32 = 1.0;
39pub const MAX_FLEX_FACTOR: f32 = 1e6;
41pub const ASPECT_RATIO_RANGE: std::ops::RangeInclusive<f32> = 1e-4..=1e4;
43pub const MAX_GRID_TRACKS: usize = 64;
45const MAX_GRID_LINE: i16 = 65;
47
48pub const LAYOUT_TEXT_DEFAULTS: LayoutTextStyle = LayoutTextStyle {
50 font_family: None,
51 font_size: 0.05,
52 fill: Paint::Solid {
53 color: Rgba::new(1.0, 1.0, 1.0, 1.0),
54 },
55 line_height: 1.2,
56 letter_spacing: 0.0,
57 font_weight: 400,
58 text_align: TextAlign::Start,
59 strokes: Vec::new(),
60 shadows: Vec::new(),
61};
62
63#[derive(Clone, Debug, PartialEq)]
65pub struct LayoutTextStyle {
66 pub font_family: Option<String>,
68 pub font_size: f32,
70 pub fill: Paint,
72 pub line_height: f32,
74 pub letter_spacing: f32,
76 pub font_weight: u16,
78 pub text_align: TextAlign,
80 pub strokes: Vec<TextStroke>,
82 pub shadows: Vec<TextShadow>,
85}
86
87#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
94#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
95#[serde(deny_unknown_fields)]
96pub struct LayoutNode {
97 #[serde(default, skip_serializing_if = "Vec::is_empty")]
99 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_LAYOUT_NODES }>")]
100 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_LAYOUT_NODES)))]
101 pub children: Vec<LayoutNode>,
102 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub text: Option<Animated<String>>,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub shape: Option<LayoutShape>,
111
112 #[serde(default, skip_serializing_if = "Option::is_none")]
115 pub display: Option<Display>,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub flex_direction: Option<FlexDirection>,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub flex_wrap: Option<FlexWrap>,
122 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub grid_template_columns: Option<TrackList>,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub grid_template_rows: Option<TrackList>,
129 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub grid_auto_columns: Option<TrackList>,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub grid_auto_rows: Option<TrackList>,
135 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub grid_auto_flow: Option<GridAutoFlow>,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub gap: Option<Animated<LayoutSize>>,
141 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub row_gap: Option<Animated<LayoutSize>>,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub column_gap: Option<Animated<LayoutSize>>,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub justify_content: Option<JustifyContent>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub align_items: Option<AlignItems>,
154 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub align_content: Option<AlignContent>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub justify_items: Option<AlignItems>,
161
162 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub padding: Option<Animated<Insets>>,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
169 pub background: Option<Animated<Paint>>,
170 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub border: Option<LayoutBorder>,
173 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub border_radius: Option<Animated<LayoutSize>>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub overflow: Option<Overflow>,
180
181 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub width: Option<Animated<LayoutLength>>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub height: Option<Animated<LayoutLength>>,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub min_width: Option<Animated<LayoutLength>>,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
192 pub min_height: Option<Animated<LayoutLength>>,
193 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub max_width: Option<Animated<LayoutLength>>,
196 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub max_height: Option<Animated<LayoutLength>>,
199 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub aspect_ratio: Option<f32>,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub margin: Option<Animated<Insets>>,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
208 pub flex_grow: Option<Animated<f32>>,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub flex_shrink: Option<Animated<f32>>,
213 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub flex_basis: Option<Animated<LayoutLength>>,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
219 pub align_self: Option<AlignItems>,
220 #[serde(default, skip_serializing_if = "Option::is_none")]
223 pub justify_self: Option<AlignItems>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub grid_column: Option<GridPlacement>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
230 pub grid_row: Option<GridPlacement>,
231 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub position: Option<Position>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub inset: Option<LayoutInset>,
237
238 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub font_family: Option<String>,
242 #[serde(default, skip_serializing_if = "Option::is_none")]
245 pub font_size: Option<Animated<LayoutSize>>,
246 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub fill: Option<Paint>,
249 #[serde(default, skip_serializing_if = "Option::is_none")]
252 pub line_height: Option<f32>,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
256 pub letter_spacing: Option<f32>,
257 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub font_weight: Option<u16>,
261 #[serde(default, skip_serializing_if = "Option::is_none")]
263 pub text_align: Option<TextAlign>,
264 #[serde(default, skip_serializing_if = "Option::is_none")]
267 #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_TEXT_STROKES }>")]
268 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_STROKES)))]
269 pub strokes: Option<Vec<TextStroke>>,
270 #[serde(default, skip_serializing_if = "Option::is_none")]
273 #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_TEXT_SHADOWS }>")]
274 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_SHADOWS)))]
275 pub shadows: Option<Vec<TextShadow>>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
280 pub font_size_fit: Option<LayoutFontSizeFit>,
281 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub line_clamp: Option<crate::LineClamp>,
286 #[serde(default, skip_serializing_if = "Vec::is_empty")]
290 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_ANIMATORS }>")]
291 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_ANIMATORS)))]
292 pub text_animators: Vec<crate::TextAnimator>,
293
294 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub opacity: Option<Animated<f32>>,
297 #[serde(default, skip_serializing_if = "Option::is_none")]
300 pub translate: Option<Animated<LayoutOffset>>,
301 #[serde(default, skip_serializing_if = "Option::is_none")]
303 pub scale: Option<Animated<Vec2>>,
304 #[serde(default, skip_serializing_if = "Option::is_none")]
307 pub rotation_degrees: Option<Animated<f32>>,
308}
309
310#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
313#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
314#[serde(deny_unknown_fields)]
315pub struct LayoutFontSizeFit {
316 pub min: LayoutSize,
318 #[serde(default, skip_serializing_if = "Option::is_none")]
320 pub max: Option<LayoutSize>,
321}
322
323#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
326#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
327#[serde(deny_unknown_fields)]
328pub struct LayoutShape {
329 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_SHAPE_ITEMS }>")]
331 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_SHAPE_ITEMS)))]
332 pub items: Vec<ShapeItem>,
333}
334
335#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
337#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
338#[serde(deny_unknown_fields)]
339pub struct LayoutBorder {
340 pub width: Animated<LayoutSize>,
342 pub paint: Animated<Paint>,
344}
345
346#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
349#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
350#[serde(deny_unknown_fields)]
351pub struct LayoutInset {
352 #[serde(default, skip_serializing_if = "Option::is_none")]
354 pub left: Option<Animated<LayoutLength>>,
355 #[serde(default, skip_serializing_if = "Option::is_none")]
357 pub top: Option<Animated<LayoutLength>>,
358 #[serde(default, skip_serializing_if = "Option::is_none")]
360 pub right: Option<Animated<LayoutLength>>,
361 #[serde(default, skip_serializing_if = "Option::is_none")]
363 pub bottom: Option<Animated<LayoutLength>>,
364}
365
366impl LayoutInset {
367 fn sides(&self) -> [(&'static str, Option<&Animated<LayoutLength>>); 4] {
368 [
369 ("left", self.left.as_ref()),
370 ("top", self.top.as_ref()),
371 ("right", self.right.as_ref()),
372 ("bottom", self.bottom.as_ref()),
373 ]
374 }
375}
376
377#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
379#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
380#[serde(rename_all = "snake_case")]
381pub enum Display {
382 #[default]
384 Flex,
385 Grid,
387}
388
389#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
391#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
392#[serde(rename_all = "snake_case")]
393pub enum FlexDirection {
394 #[default]
396 Row,
397 Column,
399 RowReverse,
401 ColumnReverse,
403}
404
405#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
407#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
408pub enum FlexWrap {
409 #[default]
411 #[serde(rename = "nowrap")]
412 NoWrap,
413 #[serde(rename = "wrap")]
415 Wrap,
416}
417
418#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
420#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
421#[serde(rename_all = "snake_case")]
422pub enum GridAutoFlow {
423 #[default]
425 Row,
426 Column,
428 RowDense,
430 ColumnDense,
432}
433
434#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
436#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
437#[serde(rename_all = "snake_case")]
438pub enum JustifyContent {
439 #[default]
441 Start,
442 Center,
444 End,
446 SpaceBetween,
448 SpaceAround,
450 SpaceEvenly,
452}
453
454#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
456#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
457#[serde(rename_all = "snake_case")]
458pub enum AlignContent {
459 Start,
461 Center,
463 End,
465 SpaceBetween,
467 SpaceAround,
469 SpaceEvenly,
471 #[default]
473 Stretch,
474}
475
476#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
478#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
479#[serde(rename_all = "snake_case")]
480pub enum AlignItems {
481 Start,
483 Center,
485 End,
487 #[default]
489 Stretch,
490}
491
492#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
494#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
495#[serde(rename_all = "snake_case")]
496pub enum Position {
497 #[default]
499 Relative,
500 Absolute,
502}
503
504#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
506#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
507#[serde(rename_all = "snake_case")]
508pub enum Overflow {
509 #[default]
511 Visible,
512 Hidden,
514}
515
516#[derive(Copy, Clone, Debug, Eq, PartialEq)]
518#[non_exhaustive]
519pub enum LayoutProblem {
520 TooManyNodes,
522 TooDeep,
524 TooManyTexts,
526 TooManyIsolated,
528 MixedContent,
530 DisplayOnLeaf,
532 ContainerFieldOnLeaf,
534 RootItemField,
536 GridFieldOnFlex(&'static str),
538 FlexFieldOnGrid(&'static str),
540 FlexItemFieldInGrid(&'static str),
542 GridItemFieldInFlex(&'static str),
544 TooManyTracks,
546 RepeatCount,
548 RepeatInAutoTracks,
550 AutoRepeatNeedsFixedTracks,
552 GridLineOutOfRange,
554 InvalidKeyframes,
556 OutOfRange,
558 LengthKeyframesDiffer,
560 PaintKeyframesDiffer,
562 TextKeyframesInterpolate,
564}
565
566impl fmt::Display for LayoutProblem {
567 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
568 match self {
569 Self::GridFieldOnFlex(field) => {
570 return write!(
571 formatter,
572 "sets {field}, a grid container field, without display grid"
573 );
574 }
575 Self::FlexFieldOnGrid(field) => {
576 return write!(
577 formatter,
578 "sets {field}, a flex container field, on a grid container"
579 );
580 }
581 Self::FlexItemFieldInGrid(field) => {
582 return write!(
583 formatter,
584 "sets {field}, a flex item field, in a grid container"
585 );
586 }
587 Self::GridItemFieldInFlex(field) => {
588 return write!(
589 formatter,
590 "sets {field}, a grid item field, in a flex container"
591 );
592 }
593 _ => {}
594 }
595 formatter.write_str(match self {
596 Self::TooManyNodes => "has more nodes than a layout may hold",
597 Self::TooDeep => "nests nodes too deeply",
598 Self::TooManyTexts => "has more text nodes than a layout may hold",
599 Self::TooManyIsolated => {
600 "has more nodes with opacity, transforms, or hidden overflow than a layout may hold"
601 }
602 Self::MixedContent => "has more than one of children, text, and shape",
603 Self::DisplayOnLeaf => "sets display on a node with text or shape content",
604 Self::ContainerFieldOnLeaf => {
605 "sets a container field on a node with text or shape content"
606 }
607 Self::RootItemField => "sets a size, margin, position, or item field on the root",
608 Self::TooManyTracks => "has more than 64 tracks",
609 Self::RepeatCount => "repeats tracks a number of times outside 1 to 64",
610 Self::RepeatInAutoTracks => "uses repeat() in implicit track sizes",
611 Self::AutoRepeatNeedsFixedTracks => {
612 "repeats auto-fill or auto-fit beside another, or with a track without a fixed size"
613 }
614 Self::GridLineOutOfRange => {
615 "names a grid line outside -65 to 65 or line 0, or a span outside 1 to 64"
616 }
617 Self::InvalidKeyframes => "has invalid keyframes",
618 Self::OutOfRange => "has a value out of range",
619 Self::LengthKeyframesDiffer => "has size keyframes that differ in kind",
620 Self::PaintKeyframesDiffer => "has paint keyframes that differ in kind or stops",
621 Self::TextKeyframesInterpolate => "has text keyframes that do not hold",
622 Self::GridFieldOnFlex(_)
623 | Self::FlexFieldOnGrid(_)
624 | Self::FlexItemFieldInGrid(_)
625 | Self::GridItemFieldInFlex(_) => unreachable!("written above"),
626 })
627 }
628}
629
630#[derive(Clone, Debug, Eq, PartialEq)]
632pub struct LayoutIssue {
633 pub at: String,
635 pub problem: LayoutProblem,
637}
638
639impl LayoutIssue {
640 fn new(at: impl Into<String>, problem: LayoutProblem) -> Self {
641 Self {
642 at: at.into(),
643 problem,
644 }
645 }
646}
647
648impl From<ValueIssue> for LayoutIssue {
649 fn from(issue: ValueIssue) -> Self {
650 Self::new(
651 issue.at,
652 match issue.problem {
653 ValueProblem::InvalidKeyframes => LayoutProblem::InvalidKeyframes,
654 ValueProblem::OutOfRange => LayoutProblem::OutOfRange,
655 ValueProblem::PaintKeyframesDiffer => LayoutProblem::PaintKeyframesDiffer,
656 },
657 )
658 }
659}
660
661#[derive(Clone, Debug, Eq, PartialEq)]
663pub enum GeneratorIssue {
664 Invalid,
666 Shape(ShapeIssue),
669 Layout(LayoutIssue),
671}
672
673impl From<LayoutIssue> for GeneratorIssue {
674 fn from(issue: LayoutIssue) -> Self {
675 Self::Layout(issue)
676 }
677}
678
679impl From<ValueIssue> for GeneratorIssue {
680 fn from(issue: ValueIssue) -> Self {
681 Self::Layout(issue.into())
682 }
683}
684
685#[derive(Default)]
687struct Counts {
688 nodes: usize,
689 texts: usize,
690 isolated: usize,
691 shape_items: usize,
692}
693
694type LayoutChecked = Result<(), GeneratorIssue>;
695
696#[derive(Copy, Clone)]
699struct Context {
700 shorter_side: Option<f32>,
701 parent: Option<Display>,
702}
703
704pub(crate) fn validate_layout(root: &LayoutNode, canvas: Option<(u32, u32)>) -> LayoutChecked {
711 let mut counts = Counts::default();
712 if root.has_item_field() {
713 return Err(LayoutIssue::new("root", LayoutProblem::RootItemField).into());
714 }
715 #[allow(clippy::cast_precision_loss)]
716 let shorter_side = canvas.map(|(width, height)| width.min(height) as f32);
717 let context = Context {
718 shorter_side,
719 parent: None,
720 };
721 validate_node(root, "root", 1, context, &mut counts)
722}
723
724fn validate_node(
725 node: &LayoutNode,
726 at: &str,
727 depth: usize,
728 context: Context,
729 counts: &mut Counts,
730) -> LayoutChecked {
731 let issue = |problem| Err(LayoutIssue::new(at, problem).into());
732 counts.nodes += 1;
733 if counts.nodes > MAX_LAYOUT_NODES {
734 return issue(LayoutProblem::TooManyNodes);
735 }
736 if depth > MAX_LAYOUT_DEPTH {
737 return issue(LayoutProblem::TooDeep);
738 }
739 let contents = usize::from(!node.children.is_empty())
740 + usize::from(node.text.is_some())
741 + usize::from(node.shape.is_some());
742 if contents > 1 {
743 return issue(LayoutProblem::MixedContent);
744 }
745 let leaf = node.text.is_some() || node.shape.is_some();
746 if leaf && node.display.is_some() {
747 return issue(LayoutProblem::DisplayOnLeaf);
748 }
749 if leaf && node.has_container_field() {
750 return issue(LayoutProblem::ContainerFieldOnLeaf);
751 }
752 let display = node.display.unwrap_or_default();
753 let mismatch = match display {
754 Display::Flex => node
755 .grid_container_field()
756 .map(LayoutProblem::GridFieldOnFlex),
757 Display::Grid => node
758 .flex_container_field()
759 .map(LayoutProblem::FlexFieldOnGrid),
760 };
761 if let Some(problem) = mismatch {
762 return issue(problem);
763 }
764 let item_mismatch = match context.parent {
765 Some(Display::Flex) => node
766 .grid_item_field()
767 .map(LayoutProblem::GridItemFieldInFlex),
768 Some(Display::Grid) => node
769 .flex_item_field()
770 .map(LayoutProblem::FlexItemFieldInGrid),
771 None => None,
772 };
773 if let Some(problem) = item_mismatch {
774 return issue(problem);
775 }
776 if node.text.is_some() {
777 counts.texts += 1;
778 if counts.texts > MAX_LAYOUT_TEXTS {
779 return issue(LayoutProblem::TooManyTexts);
780 }
781 }
782 if node.is_isolated() {
783 counts.isolated += 1;
784 if counts.isolated > MAX_LAYOUT_ISOLATED {
785 return issue(LayoutProblem::TooManyIsolated);
786 }
787 }
788 validate_fields(node, at)?;
789 validate_grid(node, at)?;
790 validate_style(node, at, context.shorter_side)?;
791 if let Some(text) = &node.text {
792 validate_text(text, &format!("{at}.text"))?;
793 }
794 if let Some(shape) = &node.shape {
795 crate::shapes::validate_items(
796 &shape.items,
797 &format!("{at}.shape.items"),
798 1,
799 &mut counts.shape_items,
800 )
801 .map_err(GeneratorIssue::Shape)?;
802 }
803 let inner = Context {
804 shorter_side: context.shorter_side,
805 parent: Some(display),
806 };
807 for (index, child) in node.children.iter().enumerate() {
808 validate_node(
809 child,
810 &format!("{at}.children[{index}]"),
811 depth + 1,
812 inner,
813 counts,
814 )?;
815 }
816 Ok(())
817}
818
819fn optional<T, E>(value: Option<&T>, check: impl FnOnce(&T) -> Result<(), E>) -> LayoutChecked
820where
821 GeneratorIssue: From<E>,
822{
823 Ok(value.map_or(Ok(()), check)?)
824}
825
826fn flex_factor(value: f32) -> bool {
827 (0.0..=MAX_FLEX_FACTOR).contains(&value)
828}
829
830fn validate_fields(node: &LayoutNode, at: &str) -> LayoutChecked {
831 let field = |name: &str| format!("{at}.{name}");
832 for (name, gap) in [
833 ("gap", &node.gap),
834 ("row_gap", &node.row_gap),
835 ("column_gap", &node.column_gap),
836 ] {
837 optional(gap.as_ref(), |gap| size(gap, &field(name), non_negative))?;
838 }
839 optional(node.padding.as_ref(), |padding| {
840 insets(padding, &field("padding"), non_negative)
841 })?;
842 optional(node.background.as_ref(), |paint| {
843 validate_paint(paint, &field("background"))
844 })?;
845 if let Some(border) = &node.border {
846 size(&border.width, &field("border.width"), non_negative)?;
847 validate_paint(&border.paint, &field("border.paint"))?;
848 }
849 optional(node.border_radius.as_ref(), |radius| {
850 size(radius, &field("border_radius"), non_negative)
851 })?;
852 for (name, size) in [
853 ("width", &node.width),
854 ("height", &node.height),
855 ("min_width", &node.min_width),
856 ("min_height", &node.min_height),
857 ("max_width", &node.max_width),
858 ("max_height", &node.max_height),
859 ] {
860 optional(size.as_ref(), |size| {
861 length(size, &field(name), non_negative)
862 })?;
863 }
864 if node
865 .aspect_ratio
866 .is_some_and(|ratio| !ASPECT_RATIO_RANGE.contains(&ratio))
867 {
868 return Err(ValueIssue::new(field("aspect_ratio"), ValueProblem::OutOfRange).into());
869 }
870 optional(node.margin.as_ref(), |margin| {
871 insets(margin, &field("margin"), any)
872 })?;
873 optional(node.flex_grow.as_ref(), |grow| {
874 scalar(grow, &field("flex_grow"), flex_factor)
875 })?;
876 optional(node.flex_shrink.as_ref(), |shrink| {
877 scalar(shrink, &field("flex_shrink"), flex_factor)
878 })?;
879 optional(node.flex_basis.as_ref(), |basis| {
880 length(basis, &field("flex_basis"), non_negative)
881 })?;
882 if let Some(inset) = &node.inset {
883 for (name, side) in inset.sides() {
884 optional(side, |side| {
885 length(side, &field(&format!("inset.{name}")), any)
886 })?;
887 }
888 }
889 optional(node.opacity.as_ref(), |opacity| {
890 scalar(opacity, &field("opacity"), unit)
891 })?;
892 optional(node.translate.as_ref(), |translate| {
893 animated(translate, &field("translate"), |offset| {
894 offset.x.in_bounds() && offset.y.in_bounds()
895 })
896 })?;
897 optional(node.scale.as_ref(), |scale| {
898 vec2(scale, &field("scale"), |_| true)
899 })?;
900 optional(node.rotation_degrees.as_ref(), |rotation| {
901 scalar(rotation, &field("rotation_degrees"), any)
902 })
903}
904
905fn validate_grid(node: &LayoutNode, at: &str) -> LayoutChecked {
907 let issue = |name: &str, problem| Err(LayoutIssue::new(format!("{at}.{name}"), problem).into());
908 for (name, tracks, explicit) in [
909 ("grid_template_columns", &node.grid_template_columns, true),
910 ("grid_template_rows", &node.grid_template_rows, true),
911 ("grid_auto_columns", &node.grid_auto_columns, false),
912 ("grid_auto_rows", &node.grid_auto_rows, false),
913 ] {
914 let Some(tracks) = tracks else { continue };
915 if let Some(problem) = track_problem(tracks, explicit) {
916 return issue(name, problem);
917 }
918 }
919 for (name, placement) in [
920 ("grid_column", node.grid_column),
921 ("grid_row", node.grid_row),
922 ] {
923 let in_range = |edge: GridEdge| match edge {
924 GridEdge::Auto => true,
925 GridEdge::Line(line) => line != 0 && (-MAX_GRID_LINE..=MAX_GRID_LINE).contains(&line),
926 GridEdge::Span(count) => (1..=64).contains(&count),
927 };
928 if placement.is_some_and(|placement| !placement.edges().into_iter().all(in_range)) {
929 return issue(name, LayoutProblem::GridLineOutOfRange);
930 }
931 }
932 Ok(())
933}
934
935fn track_problem(tracks: &TrackList, explicit: bool) -> Option<LayoutProblem> {
936 let lengths_valid = tracks
937 .lengths()
938 .all(|length| length.in_bounds() && length.value() >= 0.0);
939 let shares_valid = tracks
940 .shares()
941 .all(|share| share.is_finite() && share > 0.0);
942 if !(lengths_valid && shares_valid) {
943 return Some(LayoutProblem::OutOfRange);
944 }
945 let repeats = tracks.0.iter().filter_map(|component| match component {
946 TrackComponent::Repeat(count, _) => Some(*count),
947 TrackComponent::Single(_) => None,
948 });
949 if !explicit && repeats.clone().next().is_some() {
950 return Some(LayoutProblem::RepeatInAutoTracks);
951 }
952 if repeats
953 .clone()
954 .any(|count| matches!(count, RepeatCount::Count(count) if !(1..=64).contains(&count)))
955 {
956 return Some(LayoutProblem::RepeatCount);
957 }
958 if tracks.track_count() > MAX_GRID_TRACKS {
959 return Some(LayoutProblem::TooManyTracks);
960 }
961 let automatic = repeats
962 .filter(|count| !matches!(count, RepeatCount::Count(_)))
963 .count();
964 if automatic > 1
965 || (automatic == 1
966 && !tracks
967 .sizes()
968 .all(crate::layout_values::TrackSize::is_fixed))
969 {
970 return Some(LayoutProblem::AutoRepeatNeedsFixedTracks);
971 }
972 None
973}
974
975fn validate_style(node: &LayoutNode, at: &str, shorter_side: Option<f32>) -> LayoutChecked {
977 let out_of_range = |name: &str| {
978 Err(LayoutIssue::new(format!("{at}.{name}"), LayoutProblem::OutOfRange).into())
979 };
980 if node
981 .font_family
982 .as_ref()
983 .is_some_and(|family| family.is_empty() || family.len() > MAX_FONT_FAMILY_BYTES)
984 {
985 return out_of_range("font_family");
986 }
987 optional(node.font_size.as_ref(), |font_size| {
988 animated(font_size, &format!("{at}.font_size"), |value| {
989 let fraction = match (*value, shorter_side) {
991 (LayoutSize::Px(_), None) => 0.0,
992 (value, Some(side)) => value.fraction(side),
993 (value, None) => value.value(),
994 };
995 value.value().is_finite() && value.value() > 0.0 && fraction <= MAX_LAYOUT_FONT_SIZE
996 })
997 })?;
998 if node.fill.as_ref().is_some_and(|fill| !fill.is_valid()) {
999 return out_of_range("fill");
1000 }
1001 if node
1002 .line_height
1003 .is_some_and(|height| !LINE_HEIGHT_RANGE.contains(&height))
1004 {
1005 return out_of_range("line_height");
1006 }
1007 if node
1008 .letter_spacing
1009 .is_some_and(|spacing| !LETTER_SPACING_RANGE.contains(&spacing))
1010 {
1011 return out_of_range("letter_spacing");
1012 }
1013 if node
1014 .font_weight
1015 .is_some_and(|weight| !FONT_WEIGHT_RANGE.contains(&weight))
1016 {
1017 return out_of_range("font_weight");
1018 }
1019 if node
1020 .strokes
1021 .as_deref()
1022 .is_some_and(|strokes| !crate::text::valid_strokes(strokes))
1023 {
1024 return out_of_range("strokes");
1025 }
1026 if node
1027 .shadows
1028 .as_deref()
1029 .is_some_and(|shadows| !crate::text::valid_shadows(shadows))
1030 {
1031 return out_of_range("shadows");
1032 }
1033 if !crate::text_animation::valid_animators(&node.text_animators, true) {
1034 return out_of_range("text_animators");
1035 }
1036 if let Some(fit) = &node.font_size_fit {
1037 let font_size = |value: LayoutSize| {
1038 let fraction = match (value, shorter_side) {
1040 (LayoutSize::Px(_), None) => 0.0,
1041 (value, Some(side)) => value.fraction(side),
1042 (value, None) => value.value(),
1043 };
1044 value.value().is_finite() && value.value() > 0.0 && fraction <= MAX_LAYOUT_FONT_SIZE
1045 };
1046 let ordered = match (fit.min, fit.max, shorter_side) {
1047 (min, Some(max), Some(side)) => min.fraction(side) <= max.fraction(side),
1048 (LayoutSize::Fraction(min), Some(LayoutSize::Fraction(max)), None)
1049 | (LayoutSize::Px(min), Some(LayoutSize::Px(max)), None) => min <= max,
1050 _ => true,
1051 };
1052 if !font_size(fit.min) || !fit.max.is_none_or(font_size) || !ordered {
1053 return out_of_range("font_size_fit");
1054 }
1055 }
1056 if node
1057 .line_clamp
1058 .as_ref()
1059 .is_some_and(|clamp| !clamp.is_valid())
1060 {
1061 return out_of_range("line_clamp");
1062 }
1063 Ok(())
1064}
1065
1066fn insets(animation: &Animated<Insets>, at: &str, check: fn(f32) -> bool) -> Checked {
1067 animated(animation, at, |value| {
1068 value
1069 .sides()
1070 .iter()
1071 .all(|side| side.in_bounds() && check(side.value()))
1072 })
1073}
1074
1075fn size(animation: &Animated<LayoutSize>, at: &str, check: fn(f32) -> bool) -> Checked {
1076 animated(animation, at, |value| {
1077 value.in_bounds() && check(value.value())
1078 })
1079}
1080
1081fn length(
1084 animation: &Animated<LayoutLength>,
1085 at: &str,
1086 check: fn(f32) -> bool,
1087) -> Result<(), GeneratorIssue> {
1088 animated(animation, at, |value| {
1089 value.in_bounds() && check(value.value())
1090 })?;
1091 if let Animated::Keyframes { keyframes } = animation {
1092 let kind = keyframes[0].value.is_percent();
1093 if keyframes.iter().any(|key| key.value.is_percent() != kind) {
1094 return Err(LayoutIssue::new(at, LayoutProblem::LengthKeyframesDiffer).into());
1095 }
1096 }
1097 Ok(())
1098}
1099
1100fn validate_text(content: &Animated<String>, at: &str) -> LayoutChecked {
1101 animated(content, at, |_| true)?;
1102 if let Animated::Keyframes { keyframes } = content
1103 && keyframes
1104 .iter()
1105 .any(|key| key.interpolation != Interpolation::Hold)
1106 {
1107 return Err(LayoutIssue::new(at, LayoutProblem::TextKeyframesInterpolate).into());
1108 }
1109 animated(content, at, |content| {
1110 content.len() <= MAX_TEXT_CONTENT_BYTES
1111 })?;
1112 Ok(())
1113}
1114
1115impl LayoutNode {
1116 fn has_container_field(&self) -> bool {
1118 self.flex_container_field().is_some()
1119 || self.grid_container_field().is_some()
1120 || self.gap.is_some()
1121 || self.row_gap.is_some()
1122 || self.column_gap.is_some()
1123 || self.justify_content.is_some()
1124 || self.align_items.is_some()
1125 || self.align_content.is_some()
1126 }
1127
1128 fn flex_container_field(&self) -> Option<&'static str> {
1130 [
1131 ("flex_direction", self.flex_direction.is_some()),
1132 ("flex_wrap", self.flex_wrap.is_some()),
1133 ]
1134 .into_iter()
1135 .find_map(|(name, present)| present.then_some(name))
1136 }
1137
1138 fn grid_container_field(&self) -> Option<&'static str> {
1140 [
1141 (
1142 "grid_template_columns",
1143 self.grid_template_columns.is_some(),
1144 ),
1145 ("grid_template_rows", self.grid_template_rows.is_some()),
1146 ("grid_auto_columns", self.grid_auto_columns.is_some()),
1147 ("grid_auto_rows", self.grid_auto_rows.is_some()),
1148 ("grid_auto_flow", self.grid_auto_flow.is_some()),
1149 ("justify_items", self.justify_items.is_some()),
1150 ]
1151 .into_iter()
1152 .find_map(|(name, present)| present.then_some(name))
1153 }
1154
1155 fn flex_item_field(&self) -> Option<&'static str> {
1157 [
1158 ("flex_grow", self.flex_grow.is_some()),
1159 ("flex_shrink", self.flex_shrink.is_some()),
1160 ("flex_basis", self.flex_basis.is_some()),
1161 ]
1162 .into_iter()
1163 .find_map(|(name, present)| present.then_some(name))
1164 }
1165
1166 fn grid_item_field(&self) -> Option<&'static str> {
1168 [
1169 ("grid_column", self.grid_column.is_some()),
1170 ("grid_row", self.grid_row.is_some()),
1171 ("justify_self", self.justify_self.is_some()),
1172 ]
1173 .into_iter()
1174 .find_map(|(name, present)| present.then_some(name))
1175 }
1176
1177 fn has_item_field(&self) -> bool {
1179 self.width.is_some()
1180 || self.height.is_some()
1181 || self.min_width.is_some()
1182 || self.min_height.is_some()
1183 || self.max_width.is_some()
1184 || self.max_height.is_some()
1185 || self.aspect_ratio.is_some()
1186 || self.margin.is_some()
1187 || self.flex_item_field().is_some()
1188 || self.grid_item_field().is_some()
1189 || self.align_self.is_some()
1190 || self.position.is_some()
1191 || self.inset.is_some()
1192 }
1193
1194 #[must_use]
1196 pub const fn has_visual(&self) -> bool {
1197 self.opacity.is_some()
1198 || self.translate.is_some()
1199 || self.scale.is_some()
1200 || self.rotation_degrees.is_some()
1201 }
1202
1203 #[must_use]
1206 pub const fn is_isolated(&self) -> bool {
1207 self.has_visual() || matches!(self.overflow, Some(Overflow::Hidden))
1208 }
1209
1210 #[must_use]
1212 pub fn is_animated(&self) -> bool {
1213 let inset = self.inset.as_ref().is_some_and(|inset| {
1214 inset
1215 .sides()
1216 .into_iter()
1217 .any(|(_, value)| keyed_option(value))
1218 });
1219 let shape = self
1220 .shape
1221 .as_ref()
1222 .is_some_and(|shape| shape.items.iter().any(ShapeItem::is_animated));
1223 let border = self
1224 .border
1225 .as_ref()
1226 .is_some_and(|border| keyed(&border.width) || keyed(&border.paint));
1227 [
1228 &self.gap,
1229 &self.row_gap,
1230 &self.column_gap,
1231 &self.border_radius,
1232 &self.font_size,
1233 ]
1234 .into_iter()
1235 .any(|value| keyed_option(value.as_ref()))
1236 || keyed_option(self.padding.as_ref())
1237 || keyed_option(self.background.as_ref())
1238 || border
1239 || [
1240 &self.width,
1241 &self.height,
1242 &self.min_width,
1243 &self.min_height,
1244 &self.max_width,
1245 &self.max_height,
1246 &self.flex_basis,
1247 ]
1248 .into_iter()
1249 .any(|value| keyed_option(value.as_ref()))
1250 || keyed_option(self.margin.as_ref())
1251 || keyed_option(self.flex_grow.as_ref())
1252 || keyed_option(self.flex_shrink.as_ref())
1253 || inset
1254 || keyed_option(self.opacity.as_ref())
1255 || keyed_option(self.translate.as_ref())
1256 || keyed_option(self.scale.as_ref())
1257 || keyed_option(self.rotation_degrees.as_ref())
1258 || keyed_option(self.text.as_ref())
1259 || shape
1260 || crate::text_animation::animators_have_keyframes(&self.text_animators)
1261 || self.children.iter().any(Self::is_animated)
1262 }
1263
1264 pub fn walk(&self, mut visit: impl FnMut(&str, &Self)) {
1266 fn go(node: &LayoutNode, at: &str, visit: &mut impl FnMut(&str, &LayoutNode)) {
1267 visit(at, node);
1268 for (index, child) in node.children.iter().enumerate() {
1269 go(child, &format!("{at}.children[{index}]"), visit);
1270 }
1271 }
1272 go(self, "root", &mut visit);
1273 }
1274
1275 pub(crate) fn for_each_keyed(
1278 &self,
1279 at: &str,
1280 visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
1281 ) {
1282 let field = |name: &str| format!("{at}.{name}");
1283 if let Some(text) = &self.text {
1284 visit_keyed(&field("text"), text, visit);
1285 }
1286 if let Some(shape) = &self.shape {
1287 crate::shapes::for_each_keyed_item(&shape.items, &field("shape.items"), visit);
1288 }
1289 crate::text_animation::for_each_keyed_animator(
1290 &self.text_animators,
1291 &field("text_animators"),
1292 visit,
1293 );
1294 for (name, value) in [
1295 ("gap", &self.gap),
1296 ("row_gap", &self.row_gap),
1297 ("column_gap", &self.column_gap),
1298 ("border_radius", &self.border_radius),
1299 ("font_size", &self.font_size),
1300 ] {
1301 visit_option(&field(name), value.as_ref(), visit);
1302 }
1303 visit_option(&field("padding"), self.padding.as_ref(), visit);
1304 visit_option(&field("background"), self.background.as_ref(), visit);
1305 if let Some(border) = &self.border {
1306 visit_keyed(&field("border.width"), &border.width, visit);
1307 visit_keyed(&field("border.paint"), &border.paint, visit);
1308 }
1309 for (name, value) in [
1310 ("width", &self.width),
1311 ("height", &self.height),
1312 ("min_width", &self.min_width),
1313 ("min_height", &self.min_height),
1314 ("max_width", &self.max_width),
1315 ("max_height", &self.max_height),
1316 ("flex_basis", &self.flex_basis),
1317 ] {
1318 visit_option(&field(name), value.as_ref(), visit);
1319 }
1320 visit_option(&field("margin"), self.margin.as_ref(), visit);
1321 visit_option(&field("flex_grow"), self.flex_grow.as_ref(), visit);
1322 visit_option(&field("flex_shrink"), self.flex_shrink.as_ref(), visit);
1323 if let Some(inset) = &self.inset {
1324 for (side, value) in inset.sides() {
1325 visit_option(&field(&format!("inset.{side}")), value, visit);
1326 }
1327 }
1328 visit_option(&field("opacity"), self.opacity.as_ref(), visit);
1329 visit_option(&field("translate"), self.translate.as_ref(), visit);
1330 visit_option(&field("scale"), self.scale.as_ref(), visit);
1331 visit_option(
1332 &field("rotation_degrees"),
1333 self.rotation_degrees.as_ref(),
1334 visit,
1335 );
1336 for (index, child) in self.children.iter().enumerate() {
1337 child.for_each_keyed(&format!("{at}.children[{index}]"), visit);
1338 }
1339 }
1340
1341 #[must_use]
1344 pub fn without_px(&self, shorter_side: f32) -> Self {
1345 let mut node = self.clone();
1346 node.convert_px(shorter_side);
1347 node
1348 }
1349
1350 fn convert_px(&mut self, shorter_side: f32) {
1351 let size = |value: &mut Option<Animated<LayoutSize>>| {
1352 if let Some(value) = value {
1353 *value = value.map(|size| size.without_px(shorter_side));
1354 }
1355 };
1356 let length = |value: &mut Option<Animated<LayoutLength>>| {
1357 if let Some(value) = value {
1358 *value = value.map(|length| length.without_px(shorter_side));
1359 }
1360 };
1361 let insets = |value: &mut Option<Animated<Insets>>| {
1362 if let Some(value) = value {
1363 *value = value.map(|insets| insets.without_px(shorter_side));
1364 }
1365 };
1366 let tracks = |value: &mut Option<TrackList>| {
1367 if let Some(tracks) = value {
1368 *tracks = tracks.without_px(shorter_side);
1369 }
1370 };
1371 tracks(&mut self.grid_template_columns);
1372 tracks(&mut self.grid_template_rows);
1373 tracks(&mut self.grid_auto_columns);
1374 tracks(&mut self.grid_auto_rows);
1375 for value in [
1376 &mut self.gap,
1377 &mut self.row_gap,
1378 &mut self.column_gap,
1379 &mut self.border_radius,
1380 &mut self.font_size,
1381 ] {
1382 size(value);
1383 }
1384 if let Some(fit) = &mut self.font_size_fit {
1385 fit.min = fit.min.without_px(shorter_side);
1386 fit.max = fit.max.map(|max| max.without_px(shorter_side));
1387 }
1388 insets(&mut self.padding);
1389 insets(&mut self.margin);
1390 if let Some(border) = &mut self.border {
1391 border.width = border.width.map(|width| width.without_px(shorter_side));
1392 }
1393 for value in [
1394 &mut self.width,
1395 &mut self.height,
1396 &mut self.min_width,
1397 &mut self.min_height,
1398 &mut self.max_width,
1399 &mut self.max_height,
1400 &mut self.flex_basis,
1401 ] {
1402 length(value);
1403 }
1404 if let Some(inset) = &mut self.inset {
1405 for side in [
1406 &mut inset.left,
1407 &mut inset.top,
1408 &mut inset.right,
1409 &mut inset.bottom,
1410 ] {
1411 length(side);
1412 }
1413 }
1414 if let Some(translate) = &mut self.translate {
1415 *translate = translate.map(|offset| offset.without_px(shorter_side));
1416 }
1417 for child in &mut self.children {
1418 child.convert_px(shorter_side);
1419 }
1420 }
1421}
1422
1423fn visit_option<T: crate::animation::Placed>(
1424 at: &str,
1425 animation: Option<&Animated<T>>,
1426 visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
1427) {
1428 if let Some(animation) = animation {
1429 visit_keyed(at, animation, visit);
1430 }
1431}
1432
1433const fn keyed<T>(animation: &Animated<T>) -> bool {
1434 matches!(animation, Animated::Keyframes { .. })
1435}
1436
1437const fn keyed_option<T>(animation: Option<&Animated<T>>) -> bool {
1438 matches!(animation, Some(Animated::Keyframes { .. }))
1439}