Skip to main content

alpha2_model/
layout.rs

1//! The box tree of a layout generator: boxes laid out by CSS flexbox or grid around their
2//! text and shapes.
3//!
4//! Field names are CSS property names and keyword values CSS keywords, both in `snake_case`.
5//! A length is a number (a fraction of the picture's shorter side), `"<n>px"` (project canvas
6//! pixels), or, for sizes and insets, `"<n>%"` of the parent's content box (see
7//! [`crate::layout_values`]). Boxes are `border-box`. Text style fields (`font_family`,
8//! `font_size`, `fill`, `font_weight`, `line_height`, `letter_spacing`, `text_align`,
9//! `strokes`, `shadows`) may be set on any box and inherit as in CSS. `font_size_fit`,
10//! `line_clamp` and `text_animators` apply to the box's own text only.
11
12use 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
29/// Most nodes in one layout tree, the root included.
30pub const MAX_LAYOUT_NODES: usize = 256;
31/// Deepest nesting of one layout tree; the root is depth 1.
32pub const MAX_LAYOUT_DEPTH: usize = 16;
33/// Most nodes with text in one layout tree.
34pub const MAX_LAYOUT_TEXTS: usize = 64;
35/// Most isolated nodes (with a visual field or hidden overflow) in one layout tree.
36pub const MAX_LAYOUT_ISOLATED: usize = 16;
37/// Largest font size of a layout's text, as a fraction of the picture's shorter side.
38pub const MAX_LAYOUT_FONT_SIZE: f32 = 1.0;
39/// Largest flex grow or shrink factor.
40pub const MAX_FLEX_FACTOR: f32 = 1e6;
41/// The range of a layout box's `aspect_ratio`.
42pub const ASPECT_RATIO_RANGE: std::ops::RangeInclusive<f32> = 1e-4..=1e4;
43/// Most explicit tracks on one axis of a grid, `repeat()` counts expanded.
44pub const MAX_GRID_TRACKS: usize = 64;
45/// The farthest grid line a placement names, from either end.
46const MAX_GRID_LINE: i16 = 65;
47
48/// The initial text style: what the root inherits.
49pub 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/// A box's text style once inherited. Lengths are fractions of the picture's shorter side.
64#[derive(Clone, Debug, PartialEq)]
65pub struct LayoutTextStyle {
66    /// The family the text draws in, as a text style's `font_family`.
67    pub font_family: Option<String>,
68    /// Font size as a fraction of the picture's shorter side.
69    pub font_size: f32,
70    /// What paints the glyphs, a gradient in the text's layout box.
71    pub fill: Paint,
72    /// Baseline-to-baseline distance in font sizes.
73    pub line_height: f32,
74    /// Space after each character, a fraction of the font size.
75    pub letter_spacing: f32,
76    /// The weight its faces are matched by.
77    pub font_weight: u16,
78    /// How lines align within the content width.
79    pub text_align: TextAlign,
80    /// Bands around the glyphs, innermost first; widths are fractions of the font size.
81    pub strokes: Vec<TextStroke>,
82    /// Shadows of the glyphs and strokes, the first on top; lengths are fractions of the font
83    /// size.
84    pub shadows: Vec<TextShadow>,
85}
86
87/// One box of a layout tree.
88///
89/// A box lays its children out by flexbox (the default) or grid. It is a container with
90/// children, a leaf with text or shape content, and empty otherwise (a spacer or decoration).
91/// Each box draws background, then border, then content. Boxes draw in document order;
92/// reversed directions and grid placement move them but do not change paint order.
93#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
94#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
95#[serde(deny_unknown_fields)]
96pub struct LayoutNode {
97    /// Boxes laid out in this one, in document (and paint) order. Not with `text` or `shape`.
98    #[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    /// The box's text, a string or runs, wrapped at its content width in the inherited style;
103    /// `\n` starts a line. At most [`MAX_TEXT_CONTENT_BYTES`] bytes per value; may be empty.
104    /// Keyframes all `hold`. A run takes a `style` with a constant `font_scale` only: no
105    /// `class`, `time` or keyframes. Not with `children` or `shape`.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub text: Option<Animated<crate::TextContent>>,
108    /// Shapes drawn on a picture the size of the box's content box. Not with `children` or
109    /// `text`.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub shape: Option<LayoutShape>,
112
113    /// How the box lays its children out. Default `flex`. Like every container field, not on a
114    /// box with text or shape content.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub display: Option<Display>,
117    /// The main axis of a flex container's children. Default `row`.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub flex_direction: Option<FlexDirection>,
120    /// Whether a flex container's children wrap onto more lines. Default `nowrap`.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub flex_wrap: Option<FlexWrap>,
123    /// A grid's explicit columns, as CSS writes them (`"1fr 2fr"`,
124    /// `"repeat(3, minmax(100px, 1fr))"`). Default none.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub grid_template_columns: Option<TrackList>,
127    /// A grid's explicit rows. Default none.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub grid_template_rows: Option<TrackList>,
130    /// The size of a grid's implicit columns. Default `auto`.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub grid_auto_columns: Option<TrackList>,
133    /// The size of a grid's implicit rows. Default `auto`.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub grid_auto_rows: Option<TrackList>,
136    /// How a grid places items without a placement. Default `row`.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub grid_auto_flow: Option<GridAutoFlow>,
139    /// Space between children, on both axes. At least 0; default 0.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub gap: Option<Animated<LayoutSize>>,
142    /// Space between rows (or lines of a wrapping row flex container), in place of `gap`. At
143    /// least 0.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub row_gap: Option<Animated<LayoutSize>>,
146    /// Space between columns, in place of `gap`. At least 0.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub column_gap: Option<Animated<LayoutSize>>,
149    /// Where children lie along the main (for a grid, inline) axis. Default `start`.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub justify_content: Option<JustifyContent>,
152    /// Where children lie across the main axis, or in their grid areas' rows. Default `stretch`.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub align_items: Option<AlignItems>,
155    /// Where lines of a wrapping flex container, or a grid's rows, lie across the container.
156    /// Default `stretch`.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub align_content: Option<AlignContent>,
159    /// Where a grid's children lie in their grid areas' columns. Default `stretch`.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub justify_items: Option<AlignItems>,
162
163    /// Space inside the border: a length, the CSS shorthand (`"8px 16px"`), or the sides object.
164    /// Sides at least 0; default 0.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub padding: Option<Animated<Insets>>,
167    /// What covers the border box, rounded by `border_radius`. Positions are normalized to the
168    /// border box.
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub background: Option<Animated<Paint>>,
171    /// A border inside the border box.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub border: Option<LayoutBorder>,
174    /// The corner radius of the border box. At least 0; default 0. Capped at half the box's
175    /// shorter side.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub border_radius: Option<Animated<LayoutSize>>,
178    /// Whether content past the padding box is drawn. Default `visible`.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub overflow: Option<Overflow>,
181
182    /// Border-box width. `None` is auto. Like every item field, not on the root.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub width: Option<Animated<LayoutLength>>,
185    /// Border-box height. `None` is auto.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub height: Option<Animated<LayoutLength>>,
188    /// Smallest width. `None` is auto, the CSS automatic minimum size.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub min_width: Option<Animated<LayoutLength>>,
191    /// Smallest height. `None` is auto.
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub min_height: Option<Animated<LayoutLength>>,
194    /// Largest width. `None` is none.
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub max_width: Option<Animated<LayoutLength>>,
197    /// Largest height. `None` is none.
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub max_height: Option<Animated<LayoutLength>>,
200    /// Width over height. Positive.
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub aspect_ratio: Option<f32>,
203    /// Space outside the border, written as `padding` is. Sides may be negative; no `auto`.
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub margin: Option<Animated<Insets>>,
206    /// How much of a flex container's free space the box takes. At least 0; default 0. Like
207    /// every flex item field, not in a grid.
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub flex_grow: Option<Animated<f32>>,
210    /// How much the box gives up when a flex container's space runs short. At least 0; default
211    /// 1.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub flex_shrink: Option<Animated<f32>>,
214    /// The main size before growing and shrinking. `None` is auto.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub flex_basis: Option<Animated<LayoutLength>>,
217    /// Where the box lies across its flex container's main axis, or in its grid area's row.
218    /// `None` follows the parent's `align_items`.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub align_self: Option<AlignItems>,
221    /// Where the box lies in its grid area's column. `None` follows the parent's
222    /// `justify_items`. Like every grid item field, not in a flex container.
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub justify_self: Option<AlignItems>,
225    /// The box's columns in its grid, as CSS writes them (`2`, `"1 / 3"`, `"span 2"`). Default
226    /// `auto`.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub grid_column: Option<GridPlacement>,
229    /// The box's rows in its grid. Default `auto`.
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub grid_row: Option<GridPlacement>,
232    /// Whether the box is in its parent's flow. Default `relative`.
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub position: Option<Position>,
235    /// Where an `absolute` box lies in its parent's padding box.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub inset: Option<LayoutInset>,
238
239    /// The family the box's text draws in, as a text style's `font_family`. Inherited; the
240    /// root's is the host's first font.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub font_family: Option<String>,
243    /// Font size: positive, at most [`MAX_LAYOUT_FONT_SIZE`] of the picture's shorter side.
244    /// Inherited; the root's is 0.05.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub font_size: Option<Animated<LayoutSize>>,
247    /// What paints the text's glyphs, as a text style's `fill`. Inherited; the root's is white.
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub fill: Option<Paint>,
250    /// Baseline-to-baseline distance in font sizes, in `[0.5, 3]`, as a text style's
251    /// `line_height`. Inherited; the root's is 1.2.
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub line_height: Option<f32>,
254    /// Space after each character, as a fraction of the font size, in `[-0.5, 1]`, as a text
255    /// style's `letter_spacing`. Not animated. Inherited; the root's is 0.
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub letter_spacing: Option<f32>,
258    /// The weight in `[1, 1000]` used to match the family's faces, as a text style's
259    /// `font_weight`. Not animated. Inherited; the root's is 400.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub font_weight: Option<u16>,
262    /// How lines align within the content width. Inherited; the root's is `start`.
263    #[serde(default, skip_serializing_if = "Option::is_none")]
264    pub text_align: Option<TextAlign>,
265    /// Bands around the glyphs, as a text style's `strokes`. Inherited as a whole list; the root
266    /// has none.
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_TEXT_STROKES }>")]
269    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_STROKES)))]
270    pub strokes: Option<Vec<TextStroke>>,
271    /// Shadows of the glyphs and strokes, as a text style's `shadows`. Inherited as a whole list
272    /// (as CSS `text-shadow`); the root has none.
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_TEXT_SHADOWS }>")]
275    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_SHADOWS)))]
276    pub shadows: Option<Vec<TextShadow>>,
277    /// The range the font size of the box's own text is fitted in so the text fits its content
278    /// box, as a text style's `font_size_fit`. The box is laid out at `font_size` first, and
279    /// the fit never changes its size. Not inherited.
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub font_size_fit: Option<LayoutFontSizeFit>,
282    /// Where the lines of the box's own text are cut and what ends the cut line, as CSS
283    /// `line-clamp` and a text style's `line_clamp`. The clamp point is also at the content
284    /// box's height. The box's automatic height ends at the clamp point. Not inherited.
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub line_clamp: Option<crate::LineClamp>,
287    /// Per-character motion of the box's own text, Range selectors only (layout text has no
288    /// runs). At most [`crate::MAX_TEXT_ANIMATORS`], keyed in picture time. Not inherited. They
289    /// never change layout, except that one whose advance follows its scale makes the text wrap,
290    /// and measure as wide, with room for its largest scale.
291    #[serde(default, skip_serializing_if = "Vec::is_empty")]
292    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_ANIMATORS }>")]
293    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_ANIMATORS)))]
294    pub text_animators: Vec<crate::TextAnimator>,
295    /// The units whose characters `text_animators` scale and turn about one pivot, as a text
296    /// style's `animator_grouping`. Not inherited.
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub text_animator_grouping: Option<crate::AnimatorGrouping>,
299    /// Where in each group's box its pivot lies, as a text style's `animator_pivot`. Not
300    /// inherited.
301    #[serde(default, skip_serializing_if = "Option::is_none")]
302    pub text_animator_pivot: Option<crate::Vec2>,
303
304    /// Opacity of the box and everything in it as one group, in `0..=1`. Applied after layout.
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub opacity: Option<Animated<f32>>,
307    /// Offset of the box and everything in it after layout: the object, or one or two lengths as
308    /// CSS `translate` writes them.
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub translate: Option<Animated<LayoutOffset>>,
311    /// Per-axis scale of the box and everything in it about its border-box centre, after layout.
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub scale: Option<Animated<Vec2>>,
314    /// Clockwise rotation of the box and everything in it about its border-box centre, in
315    /// degrees, after layout.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub rotation_degrees: Option<Animated<f32>>,
318}
319
320/// The font sizes a layout text is fitted between, as a text style's
321/// [`crate::FontSizeFit`], in layout sizes. A `min` above `max` wins.
322#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
323#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
324#[serde(deny_unknown_fields)]
325pub struct LayoutFontSizeFit {
326    /// Smallest font size, positive and at most [`MAX_LAYOUT_FONT_SIZE`] of the shorter side.
327    pub min: LayoutSize,
328    /// Largest font size, with the same limits. `None` is `font_size`, so the text only shrinks.
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub max: Option<LayoutSize>,
331}
332
333/// A box's shapes, drawn as a shapes generator draws its items on a picture the size of the
334/// box's content box. A shape box has no size of its own.
335#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
336#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
337#[serde(deny_unknown_fields)]
338pub struct LayoutShape {
339    /// The content tree, front first.
340    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_SHAPE_ITEMS }>")]
341    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_SHAPE_ITEMS)))]
342    pub items: Vec<ShapeItem>,
343}
344
345/// A border inside the border box, as wide on every side.
346#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
347#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
348#[serde(deny_unknown_fields)]
349pub struct LayoutBorder {
350    /// Width. At least 0.
351    pub width: Animated<LayoutSize>,
352    /// What covers the border. Positions are normalized to the border box.
353    pub paint: Animated<Paint>,
354}
355
356/// Where an absolute box lies in its parent's padding box. A missing side is auto; with
357/// neither `left` nor `right`, the box keeps its flow position on that axis.
358#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
359#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
360#[serde(deny_unknown_fields)]
361pub struct LayoutInset {
362    /// Distance from the parent's left padding edge.
363    #[serde(default, skip_serializing_if = "Option::is_none")]
364    pub left: Option<Animated<LayoutLength>>,
365    /// Distance from the parent's top padding edge.
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub top: Option<Animated<LayoutLength>>,
368    /// Distance from the parent's right padding edge.
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub right: Option<Animated<LayoutLength>>,
371    /// Distance from the parent's bottom padding edge.
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub bottom: Option<Animated<LayoutLength>>,
374}
375
376impl LayoutInset {
377    fn sides(&self) -> [(&'static str, Option<&Animated<LayoutLength>>); 4] {
378        [
379            ("left", self.left.as_ref()),
380            ("top", self.top.as_ref()),
381            ("right", self.right.as_ref()),
382            ("bottom", self.bottom.as_ref()),
383        ]
384    }
385}
386
387/// How a box lays its children out.
388#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
389#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
390#[serde(rename_all = "snake_case")]
391pub enum Display {
392    /// CSS flexbox.
393    #[default]
394    Flex,
395    /// CSS grid.
396    Grid,
397}
398
399/// The main axis of a flex container.
400#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
401#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
402#[serde(rename_all = "snake_case")]
403pub enum FlexDirection {
404    /// Left to right.
405    #[default]
406    Row,
407    /// Top to bottom.
408    Column,
409    /// Right to left.
410    RowReverse,
411    /// Bottom to top.
412    ColumnReverse,
413}
414
415/// Whether a flex container's children wrap.
416#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
417#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
418pub enum FlexWrap {
419    /// One line.
420    #[default]
421    #[serde(rename = "nowrap")]
422    NoWrap,
423    /// As many lines as the children need.
424    #[serde(rename = "wrap")]
425    Wrap,
426}
427
428/// How a grid places items that have no placement of their own.
429#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
430#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
431#[serde(rename_all = "snake_case")]
432pub enum GridAutoFlow {
433    /// Filling each row, adding rows.
434    #[default]
435    Row,
436    /// Filling each column, adding columns.
437    Column,
438    /// As `row`, filling earlier holes.
439    RowDense,
440    /// As `column`, filling earlier holes.
441    ColumnDense,
442}
443
444/// Where children lie along a container's main axis, or a grid's columns in it.
445#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
446#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
447#[serde(rename_all = "snake_case")]
448pub enum JustifyContent {
449    /// Packed at the start.
450    #[default]
451    Start,
452    /// Packed in the middle.
453    Center,
454    /// Packed at the end.
455    End,
456    /// The first at the start, the last at the end, equal space between.
457    SpaceBetween,
458    /// Equal space around each.
459    SpaceAround,
460    /// Equal space between each and at both ends.
461    SpaceEvenly,
462}
463
464/// Where the lines of a wrapping flex container, or a grid's rows, lie across the container.
465#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
466#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
467#[serde(rename_all = "snake_case")]
468pub enum AlignContent {
469    /// Packed at the start.
470    Start,
471    /// Packed in the middle.
472    Center,
473    /// Packed at the end.
474    End,
475    /// The first at the start, the last at the end, equal space between.
476    SpaceBetween,
477    /// Equal space around each.
478    SpaceAround,
479    /// Equal space between each and at both ends.
480    SpaceEvenly,
481    /// Grown to fill the container.
482    #[default]
483    Stretch,
484}
485
486/// Where children lie across a flex container's main axis, or in their grid areas.
487#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
488#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
489#[serde(rename_all = "snake_case")]
490pub enum AlignItems {
491    /// At the start.
492    Start,
493    /// In the middle.
494    Center,
495    /// At the end.
496    End,
497    /// Across the whole line or area.
498    #[default]
499    Stretch,
500}
501
502/// Whether a box is in its parent's flow.
503#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
504#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
505#[serde(rename_all = "snake_case")]
506pub enum Position {
507    /// In the flow.
508    #[default]
509    Relative,
510    /// Out of the flow, placed by `inset`.
511    Absolute,
512}
513
514/// Whether content past a box's padding box is drawn.
515#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
516#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
517#[serde(rename_all = "snake_case")]
518pub enum Overflow {
519    /// Drawn.
520    #[default]
521    Visible,
522    /// Clipped to the padding box.
523    Hidden,
524}
525
526/// Why a layout tree is invalid.
527#[derive(Copy, Clone, Debug, Eq, PartialEq)]
528#[non_exhaustive]
529pub enum LayoutProblem {
530    /// More than [`MAX_LAYOUT_NODES`] nodes.
531    TooManyNodes,
532    /// Nodes nested deeper than [`MAX_LAYOUT_DEPTH`].
533    TooDeep,
534    /// More than [`MAX_LAYOUT_TEXTS`] nodes with text.
535    TooManyTexts,
536    /// More than [`MAX_LAYOUT_ISOLATED`] nodes with a visual field or hidden overflow.
537    TooManyIsolated,
538    /// A node with more than one of children, text, and shape.
539    MixedContent,
540    /// `display` on a node with text or shape content.
541    DisplayOnLeaf,
542    /// A container field on a node with text or shape content.
543    ContainerFieldOnLeaf,
544    /// A size, margin, position, or item field on the root.
545    RootItemField,
546    /// A grid container field (named) on a flex container.
547    GridFieldOnFlex(&'static str),
548    /// A flex container field (named) on a grid container.
549    FlexFieldOnGrid(&'static str),
550    /// A flex item field (named) on a grid's child.
551    FlexItemFieldInGrid(&'static str),
552    /// A grid item field (named) on a flex container's child.
553    GridItemFieldInFlex(&'static str),
554    /// More than [`MAX_GRID_TRACKS`] explicit tracks on one axis.
555    TooManyTracks,
556    /// A `repeat()` count outside 1 to 64.
557    RepeatCount,
558    /// `repeat()` in implicit track sizes.
559    RepeatInAutoTracks,
560    /// An `auto-fill` or `auto-fit` repeat beside another, or with a track without a fixed size.
561    AutoRepeatNeedsFixedTracks,
562    /// A grid line outside -65 to 65, line 0, or a span outside 1 to 64.
563    GridLineOutOfRange,
564    /// Keyframes that are empty, out of order, or have an unusable curve.
565    InvalidKeyframes,
566    /// A value that is not finite or outside its range.
567    OutOfRange,
568    /// Size keyframes that mix a percent with a length.
569    LengthKeyframesDiffer,
570    /// Paint keyframes that differ in kind, stop count, or spread.
571    PaintKeyframesDiffer,
572    /// A text keyframe whose interpolation is not `hold`.
573    TextKeyframesInterpolate,
574    /// A text run with a class, a time or a keyframed font scale.
575    TextRunNotStatic,
576}
577
578impl fmt::Display for LayoutProblem {
579    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
580        match self {
581            Self::GridFieldOnFlex(field) => {
582                return write!(
583                    formatter,
584                    "sets {field}, a grid container field, without display grid"
585                );
586            }
587            Self::FlexFieldOnGrid(field) => {
588                return write!(
589                    formatter,
590                    "sets {field}, a flex container field, on a grid container"
591                );
592            }
593            Self::FlexItemFieldInGrid(field) => {
594                return write!(
595                    formatter,
596                    "sets {field}, a flex item field, in a grid container"
597                );
598            }
599            Self::GridItemFieldInFlex(field) => {
600                return write!(
601                    formatter,
602                    "sets {field}, a grid item field, in a flex container"
603                );
604            }
605            _ => {}
606        }
607        formatter.write_str(match self {
608            Self::TooManyNodes => "has more nodes than a layout may hold",
609            Self::TooDeep => "nests nodes too deeply",
610            Self::TooManyTexts => "has more text nodes than a layout may hold",
611            Self::TooManyIsolated => {
612                "has more nodes with opacity, transforms, or hidden overflow than a layout may hold"
613            }
614            Self::MixedContent => "has more than one of children, text, and shape",
615            Self::DisplayOnLeaf => "sets display on a node with text or shape content",
616            Self::ContainerFieldOnLeaf => {
617                "sets a container field on a node with text or shape content"
618            }
619            Self::RootItemField => "sets a size, margin, position, or item field on the root",
620            Self::TooManyTracks => "has more than 64 tracks",
621            Self::RepeatCount => "repeats tracks a number of times outside 1 to 64",
622            Self::RepeatInAutoTracks => "uses repeat() in implicit track sizes",
623            Self::AutoRepeatNeedsFixedTracks => {
624                "repeats auto-fill or auto-fit beside another, or with a track without a fixed size"
625            }
626            Self::GridLineOutOfRange => {
627                "names a grid line outside -65 to 65 or line 0, or a span outside 1 to 64"
628            }
629            Self::InvalidKeyframes => "has invalid keyframes",
630            Self::OutOfRange => "has a value out of range",
631            Self::LengthKeyframesDiffer => "has size keyframes that differ in kind",
632            Self::PaintKeyframesDiffer => "has paint keyframes that differ in kind or stops",
633            Self::TextKeyframesInterpolate => "has text keyframes that do not hold",
634            Self::TextRunNotStatic => "has a run with a class, a time or a keyframed font scale",
635            Self::GridFieldOnFlex(_)
636            | Self::FlexFieldOnGrid(_)
637            | Self::FlexItemFieldInGrid(_)
638            | Self::GridItemFieldInFlex(_) => unreachable!("written above"),
639        })
640    }
641}
642
643/// Where in a layout tree a problem lies, and what it is.
644#[derive(Clone, Debug, Eq, PartialEq)]
645pub struct LayoutIssue {
646    /// The field's path from the root, like `root.children[2].padding`.
647    pub at: String,
648    /// What is wrong there.
649    pub problem: LayoutProblem,
650}
651
652impl LayoutIssue {
653    fn new(at: impl Into<String>, problem: LayoutProblem) -> Self {
654        Self {
655            at: at.into(),
656            problem,
657        }
658    }
659}
660
661impl From<ValueIssue> for LayoutIssue {
662    fn from(issue: ValueIssue) -> Self {
663        Self::new(
664            issue.at,
665            match issue.problem {
666                ValueProblem::InvalidKeyframes => LayoutProblem::InvalidKeyframes,
667                ValueProblem::OutOfRange => LayoutProblem::OutOfRange,
668                ValueProblem::PaintKeyframesDiffer => LayoutProblem::PaintKeyframesDiffer,
669            },
670        )
671    }
672}
673
674/// Why a generator is invalid.
675#[derive(Clone, Debug, Eq, PartialEq)]
676pub enum GeneratorIssue {
677    /// A fill's or a text's field is out of range, or an effect is malformed.
678    Invalid,
679    /// A text generator's run `run` has a style out of range, or draws past
680    /// [`crate::MAX_TEXT_FONT_SELECTIONS`] font selections.
681    TextRun {
682        /// The run's position among the text's runs.
683        run: usize,
684    },
685    /// A problem in a shapes generator's content tree, or in a layout's shape node (its path
686    /// from the layout's root).
687    Shape(ShapeIssue),
688    /// A problem in a layout tree.
689    Layout(LayoutIssue),
690    /// An effect generator that does not match its built-in definition.
691    Effect {
692        /// The effect id.
693        id: String,
694        /// How it fails its definition.
695        problem: crate::EffectProblem,
696    },
697}
698
699impl From<LayoutIssue> for GeneratorIssue {
700    fn from(issue: LayoutIssue) -> Self {
701        Self::Layout(issue)
702    }
703}
704
705impl From<ValueIssue> for GeneratorIssue {
706    fn from(issue: ValueIssue) -> Self {
707        Self::Layout(issue.into())
708    }
709}
710
711/// What the whole tree has used up of its limits so far.
712#[derive(Default)]
713struct Counts {
714    nodes: usize,
715    texts: usize,
716    isolated: usize,
717    shape_items: usize,
718}
719
720type LayoutChecked = Result<(), GeneratorIssue>;
721
722/// What a node is checked against: the picture's shorter side in canvas pixels, when known,
723/// its parent's `display`, and the family and weight it inherits.
724#[derive(Copy, Clone)]
725struct Context<'a> {
726    shorter_side: Option<f32>,
727    parent: Option<Display>,
728    family: Option<&'a str>,
729    weight: u16,
730}
731
732/// Checks a layout tree: limits, structure, value ranges, and keyframe kind agreement. Shape
733/// nodes' items are checked as a shapes generator's, counted together. With the canvas
734/// (`(width, height)`), pixel font sizes are checked against the layout limit.
735///
736/// # Errors
737/// Returns the first problem in preorder.
738pub(crate) fn validate_layout(root: &LayoutNode, canvas: Option<(u32, u32)>) -> LayoutChecked {
739    let mut counts = Counts::default();
740    if root.has_item_field() {
741        return Err(LayoutIssue::new("root", LayoutProblem::RootItemField).into());
742    }
743    #[allow(clippy::cast_precision_loss)]
744    let shorter_side = canvas.map(|(width, height)| width.min(height) as f32);
745    let context = Context {
746        shorter_side,
747        parent: None,
748        family: None,
749        weight: crate::TextStyle::default().font_weight,
750    };
751    validate_node(root, "root", 1, context, &mut counts)
752}
753
754fn validate_node<'a>(
755    node: &'a LayoutNode,
756    at: &str,
757    depth: usize,
758    context: Context<'a>,
759    counts: &mut Counts,
760) -> LayoutChecked {
761    let issue = |problem| Err(LayoutIssue::new(at, problem).into());
762    counts.nodes += 1;
763    if counts.nodes > MAX_LAYOUT_NODES {
764        return issue(LayoutProblem::TooManyNodes);
765    }
766    if depth > MAX_LAYOUT_DEPTH {
767        return issue(LayoutProblem::TooDeep);
768    }
769    let contents = usize::from(!node.children.is_empty())
770        + usize::from(node.text.is_some())
771        + usize::from(node.shape.is_some());
772    if contents > 1 {
773        return issue(LayoutProblem::MixedContent);
774    }
775    let leaf = node.text.is_some() || node.shape.is_some();
776    if leaf && node.display.is_some() {
777        return issue(LayoutProblem::DisplayOnLeaf);
778    }
779    if leaf && node.has_container_field() {
780        return issue(LayoutProblem::ContainerFieldOnLeaf);
781    }
782    let display = node.display.unwrap_or_default();
783    let mismatch = match display {
784        Display::Flex => node
785            .grid_container_field()
786            .map(LayoutProblem::GridFieldOnFlex),
787        Display::Grid => node
788            .flex_container_field()
789            .map(LayoutProblem::FlexFieldOnGrid),
790    };
791    if let Some(problem) = mismatch {
792        return issue(problem);
793    }
794    let item_mismatch = match context.parent {
795        Some(Display::Flex) => node
796            .grid_item_field()
797            .map(LayoutProblem::GridItemFieldInFlex),
798        Some(Display::Grid) => node
799            .flex_item_field()
800            .map(LayoutProblem::FlexItemFieldInGrid),
801        None => None,
802    };
803    if let Some(problem) = item_mismatch {
804        return issue(problem);
805    }
806    if node.text.is_some() {
807        counts.texts += 1;
808        if counts.texts > MAX_LAYOUT_TEXTS {
809            return issue(LayoutProblem::TooManyTexts);
810        }
811    }
812    if node.is_isolated() {
813        counts.isolated += 1;
814        if counts.isolated > MAX_LAYOUT_ISOLATED {
815            return issue(LayoutProblem::TooManyIsolated);
816        }
817    }
818    validate_fields(node, at)?;
819    validate_grid(node, at)?;
820    validate_style(node, at, context.shorter_side)?;
821    let family = node.font_family.as_deref().or(context.family);
822    let weight = node.font_weight.unwrap_or(context.weight);
823    if let Some(text) = &node.text {
824        let base = crate::text_animation::FontSelection {
825            family,
826            weight,
827            style: crate::FontStyle::Normal,
828        };
829        validate_text(text, &format!("{at}.text"), base)?;
830    }
831    if let Some(shape) = &node.shape {
832        crate::shapes::validate_items(
833            &shape.items,
834            &format!("{at}.shape.items"),
835            1,
836            &mut counts.shape_items,
837        )
838        .map_err(GeneratorIssue::Shape)?;
839    }
840    let inner = Context {
841        shorter_side: context.shorter_side,
842        parent: Some(display),
843        family,
844        weight,
845    };
846    for (index, child) in node.children.iter().enumerate() {
847        validate_node(
848            child,
849            &format!("{at}.children[{index}]"),
850            depth + 1,
851            inner,
852            counts,
853        )?;
854    }
855    Ok(())
856}
857
858fn optional<T, E>(value: Option<&T>, check: impl FnOnce(&T) -> Result<(), E>) -> LayoutChecked
859where
860    GeneratorIssue: From<E>,
861{
862    Ok(value.map_or(Ok(()), check)?)
863}
864
865fn flex_factor(value: f32) -> bool {
866    (0.0..=MAX_FLEX_FACTOR).contains(&value)
867}
868
869fn validate_fields(node: &LayoutNode, at: &str) -> LayoutChecked {
870    let field = |name: &str| format!("{at}.{name}");
871    for (name, gap) in [
872        ("gap", &node.gap),
873        ("row_gap", &node.row_gap),
874        ("column_gap", &node.column_gap),
875    ] {
876        optional(gap.as_ref(), |gap| size(gap, &field(name), non_negative))?;
877    }
878    optional(node.padding.as_ref(), |padding| {
879        insets(padding, &field("padding"), non_negative)
880    })?;
881    optional(node.background.as_ref(), |paint| {
882        validate_paint(paint, &field("background"))
883    })?;
884    if let Some(border) = &node.border {
885        size(&border.width, &field("border.width"), non_negative)?;
886        validate_paint(&border.paint, &field("border.paint"))?;
887    }
888    optional(node.border_radius.as_ref(), |radius| {
889        size(radius, &field("border_radius"), non_negative)
890    })?;
891    for (name, size) in [
892        ("width", &node.width),
893        ("height", &node.height),
894        ("min_width", &node.min_width),
895        ("min_height", &node.min_height),
896        ("max_width", &node.max_width),
897        ("max_height", &node.max_height),
898    ] {
899        optional(size.as_ref(), |size| {
900            length(size, &field(name), non_negative)
901        })?;
902    }
903    if node
904        .aspect_ratio
905        .is_some_and(|ratio| !ASPECT_RATIO_RANGE.contains(&ratio))
906    {
907        return Err(ValueIssue::new(field("aspect_ratio"), ValueProblem::OutOfRange).into());
908    }
909    optional(node.margin.as_ref(), |margin| {
910        insets(margin, &field("margin"), any)
911    })?;
912    optional(node.flex_grow.as_ref(), |grow| {
913        scalar(grow, &field("flex_grow"), flex_factor)
914    })?;
915    optional(node.flex_shrink.as_ref(), |shrink| {
916        scalar(shrink, &field("flex_shrink"), flex_factor)
917    })?;
918    optional(node.flex_basis.as_ref(), |basis| {
919        length(basis, &field("flex_basis"), non_negative)
920    })?;
921    if let Some(inset) = &node.inset {
922        for (name, side) in inset.sides() {
923            optional(side, |side| {
924                length(side, &field(&format!("inset.{name}")), any)
925            })?;
926        }
927    }
928    optional(node.opacity.as_ref(), |opacity| {
929        scalar(opacity, &field("opacity"), unit)
930    })?;
931    optional(node.translate.as_ref(), |translate| {
932        animated(translate, &field("translate"), |offset| {
933            offset.x.in_bounds() && offset.y.in_bounds()
934        })
935    })?;
936    optional(node.scale.as_ref(), |scale| {
937        vec2(scale, &field("scale"), |_| true)
938    })?;
939    optional(node.rotation_degrees.as_ref(), |rotation| {
940        scalar(rotation, &field("rotation_degrees"), any)
941    })
942}
943
944/// The grid fields: track counts and sizes, and placement lines.
945fn validate_grid(node: &LayoutNode, at: &str) -> LayoutChecked {
946    let issue = |name: &str, problem| Err(LayoutIssue::new(format!("{at}.{name}"), problem).into());
947    for (name, tracks, explicit) in [
948        ("grid_template_columns", &node.grid_template_columns, true),
949        ("grid_template_rows", &node.grid_template_rows, true),
950        ("grid_auto_columns", &node.grid_auto_columns, false),
951        ("grid_auto_rows", &node.grid_auto_rows, false),
952    ] {
953        let Some(tracks) = tracks else { continue };
954        if let Some(problem) = track_problem(tracks, explicit) {
955            return issue(name, problem);
956        }
957    }
958    for (name, placement) in [
959        ("grid_column", node.grid_column),
960        ("grid_row", node.grid_row),
961    ] {
962        let in_range = |edge: GridEdge| match edge {
963            GridEdge::Auto => true,
964            GridEdge::Line(line) => line != 0 && (-MAX_GRID_LINE..=MAX_GRID_LINE).contains(&line),
965            GridEdge::Span(count) => (1..=64).contains(&count),
966        };
967        if placement.is_some_and(|placement| !placement.edges().into_iter().all(in_range)) {
968            return issue(name, LayoutProblem::GridLineOutOfRange);
969        }
970    }
971    Ok(())
972}
973
974fn track_problem(tracks: &TrackList, explicit: bool) -> Option<LayoutProblem> {
975    let lengths_valid = tracks
976        .lengths()
977        .all(|length| length.in_bounds() && length.value() >= 0.0);
978    let shares_valid = tracks
979        .shares()
980        .all(|share| share.is_finite() && share > 0.0);
981    if !(lengths_valid && shares_valid) {
982        return Some(LayoutProblem::OutOfRange);
983    }
984    let repeats = tracks.0.iter().filter_map(|component| match component {
985        TrackComponent::Repeat(count, _) => Some(*count),
986        TrackComponent::Single(_) => None,
987    });
988    if !explicit && repeats.clone().next().is_some() {
989        return Some(LayoutProblem::RepeatInAutoTracks);
990    }
991    if repeats
992        .clone()
993        .any(|count| matches!(count, RepeatCount::Count(count) if !(1..=64).contains(&count)))
994    {
995        return Some(LayoutProblem::RepeatCount);
996    }
997    if tracks.track_count() > MAX_GRID_TRACKS {
998        return Some(LayoutProblem::TooManyTracks);
999    }
1000    let automatic = repeats
1001        .filter(|count| !matches!(count, RepeatCount::Count(_)))
1002        .count();
1003    if automatic > 1
1004        || (automatic == 1
1005            && !tracks
1006                .sizes()
1007                .all(crate::layout_values::TrackSize::is_fixed))
1008    {
1009        return Some(LayoutProblem::AutoRepeatNeedsFixedTracks);
1010    }
1011    None
1012}
1013
1014/// The inherited text style a node writes, where it writes it.
1015fn validate_style(node: &LayoutNode, at: &str, shorter_side: Option<f32>) -> LayoutChecked {
1016    let out_of_range = |name: &str| {
1017        Err(LayoutIssue::new(format!("{at}.{name}"), LayoutProblem::OutOfRange).into())
1018    };
1019    if node
1020        .font_family
1021        .as_ref()
1022        .is_some_and(|family| family.is_empty() || family.len() > MAX_FONT_FAMILY_BYTES)
1023    {
1024        return out_of_range("font_family");
1025    }
1026    optional(node.font_size.as_ref(), |font_size| {
1027        animated(font_size, &format!("{at}.font_size"), |value| {
1028            // Pixels compare with the limit on a known canvas only.
1029            let fraction = match (*value, shorter_side) {
1030                (LayoutSize::Px(_), None) => 0.0,
1031                (value, Some(side)) => value.fraction(side),
1032                (value, None) => value.value(),
1033            };
1034            value.value().is_finite() && value.value() > 0.0 && fraction <= MAX_LAYOUT_FONT_SIZE
1035        })
1036    })?;
1037    if node.fill.as_ref().is_some_and(|fill| !fill.is_valid()) {
1038        return out_of_range("fill");
1039    }
1040    if node
1041        .line_height
1042        .is_some_and(|height| !LINE_HEIGHT_RANGE.contains(&height))
1043    {
1044        return out_of_range("line_height");
1045    }
1046    if node
1047        .letter_spacing
1048        .is_some_and(|spacing| !LETTER_SPACING_RANGE.contains(&spacing))
1049    {
1050        return out_of_range("letter_spacing");
1051    }
1052    if node
1053        .font_weight
1054        .is_some_and(|weight| !FONT_WEIGHT_RANGE.contains(&weight))
1055    {
1056        return out_of_range("font_weight");
1057    }
1058    if node
1059        .strokes
1060        .as_deref()
1061        .is_some_and(|strokes| !crate::text::valid_strokes(strokes))
1062    {
1063        return out_of_range("strokes");
1064    }
1065    if node
1066        .shadows
1067        .as_deref()
1068        .is_some_and(|shadows| !crate::text::valid_shadows(shadows))
1069    {
1070        return out_of_range("shadows");
1071    }
1072    if !crate::text_animation::valid_animators(&node.text_animators, true) {
1073        return out_of_range("text_animators");
1074    }
1075    if !node
1076        .text_animator_pivot
1077        .is_none_or(crate::text::valid_animator_pivot)
1078    {
1079        return out_of_range("text_animator_pivot");
1080    }
1081    if let Some(fit) = &node.font_size_fit {
1082        let font_size = |value: LayoutSize| {
1083            // Pixels compare with the limit on a known canvas only.
1084            let fraction = match (value, shorter_side) {
1085                (LayoutSize::Px(_), None) => 0.0,
1086                (value, Some(side)) => value.fraction(side),
1087                (value, None) => value.value(),
1088            };
1089            value.value().is_finite() && value.value() > 0.0 && fraction <= MAX_LAYOUT_FONT_SIZE
1090        };
1091        let ordered = match (fit.min, fit.max, shorter_side) {
1092            (min, Some(max), Some(side)) => min.fraction(side) <= max.fraction(side),
1093            (LayoutSize::Fraction(min), Some(LayoutSize::Fraction(max)), None)
1094            | (LayoutSize::Px(min), Some(LayoutSize::Px(max)), None) => min <= max,
1095            _ => true,
1096        };
1097        if !font_size(fit.min) || !fit.max.is_none_or(font_size) || !ordered {
1098            return out_of_range("font_size_fit");
1099        }
1100    }
1101    if node
1102        .line_clamp
1103        .as_ref()
1104        .is_some_and(|clamp| !clamp.is_valid())
1105    {
1106        return out_of_range("line_clamp");
1107    }
1108    Ok(())
1109}
1110
1111fn insets(animation: &Animated<Insets>, at: &str, check: fn(f32) -> bool) -> Checked {
1112    animated(animation, at, |value| {
1113        value
1114            .sides()
1115            .iter()
1116            .all(|side| side.in_bounds() && check(side.value()))
1117    })
1118}
1119
1120fn size(animation: &Animated<LayoutSize>, at: &str, check: fn(f32) -> bool) -> Checked {
1121    animated(animation, at, |value| {
1122        value.in_bounds() && check(value.value())
1123    })
1124}
1125
1126/// A length's values, and that its keyframes share a kind: a percent, or a length (a
1127/// fraction or pixels).
1128fn length(
1129    animation: &Animated<LayoutLength>,
1130    at: &str,
1131    check: fn(f32) -> bool,
1132) -> Result<(), GeneratorIssue> {
1133    animated(animation, at, |value| {
1134        value.in_bounds() && check(value.value())
1135    })?;
1136    if let Animated::Keyframes { keyframes, .. } = animation {
1137        let kind = keyframes[0].value.is_percent();
1138        if keyframes.iter().any(|key| key.value.is_percent() != kind) {
1139            return Err(LayoutIssue::new(at, LayoutProblem::LengthKeyframesDiffer).into());
1140        }
1141    }
1142    Ok(())
1143}
1144
1145fn validate_text(
1146    content: &Animated<crate::TextContent>,
1147    at: &str,
1148    base: crate::text_animation::FontSelection<'_>,
1149) -> LayoutChecked {
1150    animated(content, at, |_| true)?;
1151    if let Animated::Keyframes { keyframes, .. } = content
1152        && keyframes
1153            .iter()
1154            .any(|key| key.interpolation != Interpolation::Hold)
1155    {
1156        return Err(LayoutIssue::new(at, LayoutProblem::TextKeyframesInterpolate).into());
1157    }
1158    let not_static = |content: &crate::TextContent| {
1159        content.runs().iter().any(|run| {
1160            !run.class.is_empty()
1161                || run.time.is_some()
1162                || run.style.as_ref().is_some_and(|style| !style.is_static())
1163        })
1164    };
1165    let runs_static = match content {
1166        Animated::Constant { value } => !not_static(value),
1167        Animated::Keyframes { keyframes, .. } => {
1168            !keyframes.iter().any(|key| not_static(&key.value))
1169        }
1170        Animated::Data(_) | Animated::Split { .. } => true,
1171    };
1172    if !runs_static {
1173        return Err(LayoutIssue::new(at, LayoutProblem::TextRunNotStatic).into());
1174    }
1175    animated(content, at, |content| {
1176        content.len() <= MAX_TEXT_CONTENT_BYTES
1177            && content.runs().iter().all(|run| !run.text.is_empty())
1178            && content.invalid_run_style(base).is_none()
1179    })?;
1180    Ok(())
1181}
1182
1183impl LayoutNode {
1184    /// Whether any container field is present.
1185    fn has_container_field(&self) -> bool {
1186        self.flex_container_field().is_some()
1187            || self.grid_container_field().is_some()
1188            || self.gap.is_some()
1189            || self.row_gap.is_some()
1190            || self.column_gap.is_some()
1191            || self.justify_content.is_some()
1192            || self.align_items.is_some()
1193            || self.align_content.is_some()
1194    }
1195
1196    /// The first flex container field present.
1197    fn flex_container_field(&self) -> Option<&'static str> {
1198        [
1199            ("flex_direction", self.flex_direction.is_some()),
1200            ("flex_wrap", self.flex_wrap.is_some()),
1201        ]
1202        .into_iter()
1203        .find_map(|(name, present)| present.then_some(name))
1204    }
1205
1206    /// The first grid container field present.
1207    fn grid_container_field(&self) -> Option<&'static str> {
1208        [
1209            (
1210                "grid_template_columns",
1211                self.grid_template_columns.is_some(),
1212            ),
1213            ("grid_template_rows", self.grid_template_rows.is_some()),
1214            ("grid_auto_columns", self.grid_auto_columns.is_some()),
1215            ("grid_auto_rows", self.grid_auto_rows.is_some()),
1216            ("grid_auto_flow", self.grid_auto_flow.is_some()),
1217            ("justify_items", self.justify_items.is_some()),
1218        ]
1219        .into_iter()
1220        .find_map(|(name, present)| present.then_some(name))
1221    }
1222
1223    /// The first flex item field present.
1224    fn flex_item_field(&self) -> Option<&'static str> {
1225        [
1226            ("flex_grow", self.flex_grow.is_some()),
1227            ("flex_shrink", self.flex_shrink.is_some()),
1228            ("flex_basis", self.flex_basis.is_some()),
1229        ]
1230        .into_iter()
1231        .find_map(|(name, present)| present.then_some(name))
1232    }
1233
1234    /// The first grid item field present.
1235    fn grid_item_field(&self) -> Option<&'static str> {
1236        [
1237            ("grid_column", self.grid_column.is_some()),
1238            ("grid_row", self.grid_row.is_some()),
1239            ("justify_self", self.justify_self.is_some()),
1240        ]
1241        .into_iter()
1242        .find_map(|(name, present)| present.then_some(name))
1243    }
1244
1245    /// Whether any field the root may not have is present.
1246    fn has_item_field(&self) -> bool {
1247        self.width.is_some()
1248            || self.height.is_some()
1249            || self.min_width.is_some()
1250            || self.min_height.is_some()
1251            || self.max_width.is_some()
1252            || self.max_height.is_some()
1253            || self.aspect_ratio.is_some()
1254            || self.margin.is_some()
1255            || self.flex_item_field().is_some()
1256            || self.grid_item_field().is_some()
1257            || self.align_self.is_some()
1258            || self.position.is_some()
1259            || self.inset.is_some()
1260    }
1261
1262    /// Whether the node has a visual field: opacity, translate, scale, or rotation.
1263    #[must_use]
1264    pub const fn has_visual(&self) -> bool {
1265        self.opacity.is_some()
1266            || self.translate.is_some()
1267            || self.scale.is_some()
1268            || self.rotation_degrees.is_some()
1269    }
1270
1271    /// Whether the node is drawn into its own composite (a visual field or hidden overflow).
1272    /// Presence decides, not values.
1273    #[must_use]
1274    pub const fn is_isolated(&self) -> bool {
1275        self.has_visual() || matches!(self.overflow, Some(Overflow::Hidden))
1276    }
1277
1278    /// Whether the node, its subtree, or a shape in it changes over time.
1279    #[must_use]
1280    pub fn is_animated(&self) -> bool {
1281        let inset = self.inset.as_ref().is_some_and(|inset| {
1282            inset
1283                .sides()
1284                .into_iter()
1285                .any(|(_, value)| keyed_option(value))
1286        });
1287        let shape = self
1288            .shape
1289            .as_ref()
1290            .is_some_and(|shape| shape.items.iter().any(ShapeItem::is_animated));
1291        let border = self
1292            .border
1293            .as_ref()
1294            .is_some_and(|border| keyed(&border.width) || keyed(&border.paint));
1295        [
1296            &self.gap,
1297            &self.row_gap,
1298            &self.column_gap,
1299            &self.border_radius,
1300            &self.font_size,
1301        ]
1302        .into_iter()
1303        .any(|value| keyed_option(value.as_ref()))
1304            || keyed_option(self.padding.as_ref())
1305            || keyed_option(self.background.as_ref())
1306            || border
1307            || [
1308                &self.width,
1309                &self.height,
1310                &self.min_width,
1311                &self.min_height,
1312                &self.max_width,
1313                &self.max_height,
1314                &self.flex_basis,
1315            ]
1316            .into_iter()
1317            .any(|value| keyed_option(value.as_ref()))
1318            || keyed_option(self.margin.as_ref())
1319            || keyed_option(self.flex_grow.as_ref())
1320            || keyed_option(self.flex_shrink.as_ref())
1321            || inset
1322            || keyed_option(self.opacity.as_ref())
1323            || keyed_option(self.translate.as_ref())
1324            || keyed_option(self.scale.as_ref())
1325            || keyed_option(self.rotation_degrees.as_ref())
1326            || keyed_option(self.text.as_ref())
1327            || shape
1328            || crate::text_animation::animators_have_keyframes(&self.text_animators)
1329            || self.children.iter().any(Self::is_animated)
1330    }
1331
1332    /// Every node of the tree in preorder, with its path from the root.
1333    pub fn walk(&self, mut visit: impl FnMut(&str, &Self)) {
1334        fn go(node: &LayoutNode, at: &str, visit: &mut impl FnMut(&str, &LayoutNode)) {
1335            visit(at, node);
1336            for (index, child) in node.children.iter().enumerate() {
1337                go(child, &format!("{at}.children[{index}]"), visit);
1338            }
1339        }
1340        go(self, "root", &mut visit);
1341    }
1342
1343    /// Calls `visit` with each keyframed value of the tree, by path (`root.children[0].opacity`,
1344    /// `root.shape.items[0].transform.scale`), and its times, in document order.
1345    pub(crate) fn for_each_keyed(
1346        &self,
1347        at: &str,
1348        visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
1349    ) {
1350        let field = |name: &str| format!("{at}.{name}");
1351        if let Some(text) = &self.text {
1352            visit_keyed(&field("text"), text, visit);
1353        }
1354        if let Some(shape) = &self.shape {
1355            crate::shapes::for_each_keyed_item(&shape.items, &field("shape.items"), visit);
1356        }
1357        crate::text_animation::for_each_keyed_animator(
1358            &self.text_animators,
1359            &field("text_animators"),
1360            visit,
1361        );
1362        for (name, value) in [
1363            ("gap", &self.gap),
1364            ("row_gap", &self.row_gap),
1365            ("column_gap", &self.column_gap),
1366            ("border_radius", &self.border_radius),
1367            ("font_size", &self.font_size),
1368        ] {
1369            visit_option(&field(name), value.as_ref(), visit);
1370        }
1371        visit_option(&field("padding"), self.padding.as_ref(), visit);
1372        visit_option(&field("background"), self.background.as_ref(), visit);
1373        if let Some(border) = &self.border {
1374            visit_keyed(&field("border.width"), &border.width, visit);
1375            visit_keyed(&field("border.paint"), &border.paint, visit);
1376        }
1377        for (name, value) in [
1378            ("width", &self.width),
1379            ("height", &self.height),
1380            ("min_width", &self.min_width),
1381            ("min_height", &self.min_height),
1382            ("max_width", &self.max_width),
1383            ("max_height", &self.max_height),
1384            ("flex_basis", &self.flex_basis),
1385        ] {
1386            visit_option(&field(name), value.as_ref(), visit);
1387        }
1388        visit_option(&field("margin"), self.margin.as_ref(), visit);
1389        visit_option(&field("flex_grow"), self.flex_grow.as_ref(), visit);
1390        visit_option(&field("flex_shrink"), self.flex_shrink.as_ref(), visit);
1391        if let Some(inset) = &self.inset {
1392            for (side, value) in inset.sides() {
1393                visit_option(&field(&format!("inset.{side}")), value, visit);
1394            }
1395        }
1396        visit_option(&field("opacity"), self.opacity.as_ref(), visit);
1397        visit_option(&field("translate"), self.translate.as_ref(), visit);
1398        visit_option(&field("scale"), self.scale.as_ref(), visit);
1399        visit_option(
1400            &field("rotation_degrees"),
1401            self.rotation_degrees.as_ref(),
1402            visit,
1403        );
1404        for (index, child) in self.children.iter().enumerate() {
1405            child.for_each_keyed(&format!("{at}.children[{index}]"), visit);
1406        }
1407    }
1408
1409    /// The tree with every pixel length converted to a fraction of a picture `shorter_side`
1410    /// pixels on its shorter side, so pixels and fractions interpolate as one kind.
1411    #[must_use]
1412    pub fn without_px(&self, shorter_side: f32) -> Self {
1413        let mut node = self.clone();
1414        node.convert_px(shorter_side);
1415        node
1416    }
1417
1418    fn convert_px(&mut self, shorter_side: f32) {
1419        let size = |value: &mut Option<Animated<LayoutSize>>| {
1420            if let Some(value) = value {
1421                *value = value.map(|size| size.without_px(shorter_side));
1422            }
1423        };
1424        let length = |value: &mut Option<Animated<LayoutLength>>| {
1425            if let Some(value) = value {
1426                *value = value.map(|length| length.without_px(shorter_side));
1427            }
1428        };
1429        let insets = |value: &mut Option<Animated<Insets>>| {
1430            if let Some(value) = value {
1431                *value = value.map(|insets| insets.without_px(shorter_side));
1432            }
1433        };
1434        let tracks = |value: &mut Option<TrackList>| {
1435            if let Some(tracks) = value {
1436                *tracks = tracks.without_px(shorter_side);
1437            }
1438        };
1439        tracks(&mut self.grid_template_columns);
1440        tracks(&mut self.grid_template_rows);
1441        tracks(&mut self.grid_auto_columns);
1442        tracks(&mut self.grid_auto_rows);
1443        for value in [
1444            &mut self.gap,
1445            &mut self.row_gap,
1446            &mut self.column_gap,
1447            &mut self.border_radius,
1448            &mut self.font_size,
1449        ] {
1450            size(value);
1451        }
1452        if let Some(fit) = &mut self.font_size_fit {
1453            fit.min = fit.min.without_px(shorter_side);
1454            fit.max = fit.max.map(|max| max.without_px(shorter_side));
1455        }
1456        insets(&mut self.padding);
1457        insets(&mut self.margin);
1458        if let Some(border) = &mut self.border {
1459            border.width = border.width.map(|width| width.without_px(shorter_side));
1460        }
1461        for value in [
1462            &mut self.width,
1463            &mut self.height,
1464            &mut self.min_width,
1465            &mut self.min_height,
1466            &mut self.max_width,
1467            &mut self.max_height,
1468            &mut self.flex_basis,
1469        ] {
1470            length(value);
1471        }
1472        if let Some(inset) = &mut self.inset {
1473            for side in [
1474                &mut inset.left,
1475                &mut inset.top,
1476                &mut inset.right,
1477                &mut inset.bottom,
1478            ] {
1479                length(side);
1480            }
1481        }
1482        if let Some(translate) = &mut self.translate {
1483            *translate = translate.map(|offset| offset.without_px(shorter_side));
1484        }
1485        for child in &mut self.children {
1486            child.convert_px(shorter_side);
1487        }
1488    }
1489}
1490
1491fn visit_option<T: crate::animation::Placed>(
1492    at: &str,
1493    animation: Option<&Animated<T>>,
1494    visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
1495) {
1496    if let Some(animation) = animation {
1497        visit_keyed(at, animation, visit);
1498    }
1499}
1500
1501const fn keyed<T>(animation: &Animated<T>) -> bool {
1502    matches!(
1503        animation,
1504        Animated::Keyframes { .. } | Animated::Split { .. }
1505    )
1506}
1507
1508const fn keyed_option<T>(animation: Option<&Animated<T>>) -> bool {
1509    matches!(
1510        animation,
1511        Some(Animated::Keyframes { .. } | Animated::Split { .. })
1512    )
1513}