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.
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}
691
692impl From<LayoutIssue> for GeneratorIssue {
693    fn from(issue: LayoutIssue) -> Self {
694        Self::Layout(issue)
695    }
696}
697
698impl From<ValueIssue> for GeneratorIssue {
699    fn from(issue: ValueIssue) -> Self {
700        Self::Layout(issue.into())
701    }
702}
703
704/// What the whole tree has used up of its limits so far.
705#[derive(Default)]
706struct Counts {
707    nodes: usize,
708    texts: usize,
709    isolated: usize,
710    shape_items: usize,
711}
712
713type LayoutChecked = Result<(), GeneratorIssue>;
714
715/// What a node is checked against: the picture's shorter side in canvas pixels, when known,
716/// its parent's `display`, and the family and weight it inherits.
717#[derive(Copy, Clone)]
718struct Context<'a> {
719    shorter_side: Option<f32>,
720    parent: Option<Display>,
721    family: Option<&'a str>,
722    weight: u16,
723}
724
725/// Checks a layout tree: limits, structure, value ranges, and keyframe kind agreement. Shape
726/// nodes' items are checked as a shapes generator's, counted together. With the canvas
727/// (`(width, height)`), pixel font sizes are checked against the layout limit.
728///
729/// # Errors
730/// Returns the first problem in preorder.
731pub(crate) fn validate_layout(root: &LayoutNode, canvas: Option<(u32, u32)>) -> LayoutChecked {
732    let mut counts = Counts::default();
733    if root.has_item_field() {
734        return Err(LayoutIssue::new("root", LayoutProblem::RootItemField).into());
735    }
736    #[allow(clippy::cast_precision_loss)]
737    let shorter_side = canvas.map(|(width, height)| width.min(height) as f32);
738    let context = Context {
739        shorter_side,
740        parent: None,
741        family: None,
742        weight: crate::TextStyle::default().font_weight,
743    };
744    validate_node(root, "root", 1, context, &mut counts)
745}
746
747fn validate_node<'a>(
748    node: &'a LayoutNode,
749    at: &str,
750    depth: usize,
751    context: Context<'a>,
752    counts: &mut Counts,
753) -> LayoutChecked {
754    let issue = |problem| Err(LayoutIssue::new(at, problem).into());
755    counts.nodes += 1;
756    if counts.nodes > MAX_LAYOUT_NODES {
757        return issue(LayoutProblem::TooManyNodes);
758    }
759    if depth > MAX_LAYOUT_DEPTH {
760        return issue(LayoutProblem::TooDeep);
761    }
762    let contents = usize::from(!node.children.is_empty())
763        + usize::from(node.text.is_some())
764        + usize::from(node.shape.is_some());
765    if contents > 1 {
766        return issue(LayoutProblem::MixedContent);
767    }
768    let leaf = node.text.is_some() || node.shape.is_some();
769    if leaf && node.display.is_some() {
770        return issue(LayoutProblem::DisplayOnLeaf);
771    }
772    if leaf && node.has_container_field() {
773        return issue(LayoutProblem::ContainerFieldOnLeaf);
774    }
775    let display = node.display.unwrap_or_default();
776    let mismatch = match display {
777        Display::Flex => node
778            .grid_container_field()
779            .map(LayoutProblem::GridFieldOnFlex),
780        Display::Grid => node
781            .flex_container_field()
782            .map(LayoutProblem::FlexFieldOnGrid),
783    };
784    if let Some(problem) = mismatch {
785        return issue(problem);
786    }
787    let item_mismatch = match context.parent {
788        Some(Display::Flex) => node
789            .grid_item_field()
790            .map(LayoutProblem::GridItemFieldInFlex),
791        Some(Display::Grid) => node
792            .flex_item_field()
793            .map(LayoutProblem::FlexItemFieldInGrid),
794        None => None,
795    };
796    if let Some(problem) = item_mismatch {
797        return issue(problem);
798    }
799    if node.text.is_some() {
800        counts.texts += 1;
801        if counts.texts > MAX_LAYOUT_TEXTS {
802            return issue(LayoutProblem::TooManyTexts);
803        }
804    }
805    if node.is_isolated() {
806        counts.isolated += 1;
807        if counts.isolated > MAX_LAYOUT_ISOLATED {
808            return issue(LayoutProblem::TooManyIsolated);
809        }
810    }
811    validate_fields(node, at)?;
812    validate_grid(node, at)?;
813    validate_style(node, at, context.shorter_side)?;
814    let family = node.font_family.as_deref().or(context.family);
815    let weight = node.font_weight.unwrap_or(context.weight);
816    if let Some(text) = &node.text {
817        let base = crate::text_animation::FontSelection {
818            family,
819            weight,
820            style: crate::FontStyle::Normal,
821        };
822        validate_text(text, &format!("{at}.text"), base)?;
823    }
824    if let Some(shape) = &node.shape {
825        crate::shapes::validate_items(
826            &shape.items,
827            &format!("{at}.shape.items"),
828            1,
829            &mut counts.shape_items,
830        )
831        .map_err(GeneratorIssue::Shape)?;
832    }
833    let inner = Context {
834        shorter_side: context.shorter_side,
835        parent: Some(display),
836        family,
837        weight,
838    };
839    for (index, child) in node.children.iter().enumerate() {
840        validate_node(
841            child,
842            &format!("{at}.children[{index}]"),
843            depth + 1,
844            inner,
845            counts,
846        )?;
847    }
848    Ok(())
849}
850
851fn optional<T, E>(value: Option<&T>, check: impl FnOnce(&T) -> Result<(), E>) -> LayoutChecked
852where
853    GeneratorIssue: From<E>,
854{
855    Ok(value.map_or(Ok(()), check)?)
856}
857
858fn flex_factor(value: f32) -> bool {
859    (0.0..=MAX_FLEX_FACTOR).contains(&value)
860}
861
862fn validate_fields(node: &LayoutNode, at: &str) -> LayoutChecked {
863    let field = |name: &str| format!("{at}.{name}");
864    for (name, gap) in [
865        ("gap", &node.gap),
866        ("row_gap", &node.row_gap),
867        ("column_gap", &node.column_gap),
868    ] {
869        optional(gap.as_ref(), |gap| size(gap, &field(name), non_negative))?;
870    }
871    optional(node.padding.as_ref(), |padding| {
872        insets(padding, &field("padding"), non_negative)
873    })?;
874    optional(node.background.as_ref(), |paint| {
875        validate_paint(paint, &field("background"))
876    })?;
877    if let Some(border) = &node.border {
878        size(&border.width, &field("border.width"), non_negative)?;
879        validate_paint(&border.paint, &field("border.paint"))?;
880    }
881    optional(node.border_radius.as_ref(), |radius| {
882        size(radius, &field("border_radius"), non_negative)
883    })?;
884    for (name, size) in [
885        ("width", &node.width),
886        ("height", &node.height),
887        ("min_width", &node.min_width),
888        ("min_height", &node.min_height),
889        ("max_width", &node.max_width),
890        ("max_height", &node.max_height),
891    ] {
892        optional(size.as_ref(), |size| {
893            length(size, &field(name), non_negative)
894        })?;
895    }
896    if node
897        .aspect_ratio
898        .is_some_and(|ratio| !ASPECT_RATIO_RANGE.contains(&ratio))
899    {
900        return Err(ValueIssue::new(field("aspect_ratio"), ValueProblem::OutOfRange).into());
901    }
902    optional(node.margin.as_ref(), |margin| {
903        insets(margin, &field("margin"), any)
904    })?;
905    optional(node.flex_grow.as_ref(), |grow| {
906        scalar(grow, &field("flex_grow"), flex_factor)
907    })?;
908    optional(node.flex_shrink.as_ref(), |shrink| {
909        scalar(shrink, &field("flex_shrink"), flex_factor)
910    })?;
911    optional(node.flex_basis.as_ref(), |basis| {
912        length(basis, &field("flex_basis"), non_negative)
913    })?;
914    if let Some(inset) = &node.inset {
915        for (name, side) in inset.sides() {
916            optional(side, |side| {
917                length(side, &field(&format!("inset.{name}")), any)
918            })?;
919        }
920    }
921    optional(node.opacity.as_ref(), |opacity| {
922        scalar(opacity, &field("opacity"), unit)
923    })?;
924    optional(node.translate.as_ref(), |translate| {
925        animated(translate, &field("translate"), |offset| {
926            offset.x.in_bounds() && offset.y.in_bounds()
927        })
928    })?;
929    optional(node.scale.as_ref(), |scale| {
930        vec2(scale, &field("scale"), |_| true)
931    })?;
932    optional(node.rotation_degrees.as_ref(), |rotation| {
933        scalar(rotation, &field("rotation_degrees"), any)
934    })
935}
936
937/// The grid fields: track counts and sizes, and placement lines.
938fn validate_grid(node: &LayoutNode, at: &str) -> LayoutChecked {
939    let issue = |name: &str, problem| Err(LayoutIssue::new(format!("{at}.{name}"), problem).into());
940    for (name, tracks, explicit) in [
941        ("grid_template_columns", &node.grid_template_columns, true),
942        ("grid_template_rows", &node.grid_template_rows, true),
943        ("grid_auto_columns", &node.grid_auto_columns, false),
944        ("grid_auto_rows", &node.grid_auto_rows, false),
945    ] {
946        let Some(tracks) = tracks else { continue };
947        if let Some(problem) = track_problem(tracks, explicit) {
948            return issue(name, problem);
949        }
950    }
951    for (name, placement) in [
952        ("grid_column", node.grid_column),
953        ("grid_row", node.grid_row),
954    ] {
955        let in_range = |edge: GridEdge| match edge {
956            GridEdge::Auto => true,
957            GridEdge::Line(line) => line != 0 && (-MAX_GRID_LINE..=MAX_GRID_LINE).contains(&line),
958            GridEdge::Span(count) => (1..=64).contains(&count),
959        };
960        if placement.is_some_and(|placement| !placement.edges().into_iter().all(in_range)) {
961            return issue(name, LayoutProblem::GridLineOutOfRange);
962        }
963    }
964    Ok(())
965}
966
967fn track_problem(tracks: &TrackList, explicit: bool) -> Option<LayoutProblem> {
968    let lengths_valid = tracks
969        .lengths()
970        .all(|length| length.in_bounds() && length.value() >= 0.0);
971    let shares_valid = tracks
972        .shares()
973        .all(|share| share.is_finite() && share > 0.0);
974    if !(lengths_valid && shares_valid) {
975        return Some(LayoutProblem::OutOfRange);
976    }
977    let repeats = tracks.0.iter().filter_map(|component| match component {
978        TrackComponent::Repeat(count, _) => Some(*count),
979        TrackComponent::Single(_) => None,
980    });
981    if !explicit && repeats.clone().next().is_some() {
982        return Some(LayoutProblem::RepeatInAutoTracks);
983    }
984    if repeats
985        .clone()
986        .any(|count| matches!(count, RepeatCount::Count(count) if !(1..=64).contains(&count)))
987    {
988        return Some(LayoutProblem::RepeatCount);
989    }
990    if tracks.track_count() > MAX_GRID_TRACKS {
991        return Some(LayoutProblem::TooManyTracks);
992    }
993    let automatic = repeats
994        .filter(|count| !matches!(count, RepeatCount::Count(_)))
995        .count();
996    if automatic > 1
997        || (automatic == 1
998            && !tracks
999                .sizes()
1000                .all(crate::layout_values::TrackSize::is_fixed))
1001    {
1002        return Some(LayoutProblem::AutoRepeatNeedsFixedTracks);
1003    }
1004    None
1005}
1006
1007/// The inherited text style a node writes, where it writes it.
1008fn validate_style(node: &LayoutNode, at: &str, shorter_side: Option<f32>) -> LayoutChecked {
1009    let out_of_range = |name: &str| {
1010        Err(LayoutIssue::new(format!("{at}.{name}"), LayoutProblem::OutOfRange).into())
1011    };
1012    if node
1013        .font_family
1014        .as_ref()
1015        .is_some_and(|family| family.is_empty() || family.len() > MAX_FONT_FAMILY_BYTES)
1016    {
1017        return out_of_range("font_family");
1018    }
1019    optional(node.font_size.as_ref(), |font_size| {
1020        animated(font_size, &format!("{at}.font_size"), |value| {
1021            // Pixels compare with the limit on a known canvas only.
1022            let fraction = match (*value, shorter_side) {
1023                (LayoutSize::Px(_), None) => 0.0,
1024                (value, Some(side)) => value.fraction(side),
1025                (value, None) => value.value(),
1026            };
1027            value.value().is_finite() && value.value() > 0.0 && fraction <= MAX_LAYOUT_FONT_SIZE
1028        })
1029    })?;
1030    if node.fill.as_ref().is_some_and(|fill| !fill.is_valid()) {
1031        return out_of_range("fill");
1032    }
1033    if node
1034        .line_height
1035        .is_some_and(|height| !LINE_HEIGHT_RANGE.contains(&height))
1036    {
1037        return out_of_range("line_height");
1038    }
1039    if node
1040        .letter_spacing
1041        .is_some_and(|spacing| !LETTER_SPACING_RANGE.contains(&spacing))
1042    {
1043        return out_of_range("letter_spacing");
1044    }
1045    if node
1046        .font_weight
1047        .is_some_and(|weight| !FONT_WEIGHT_RANGE.contains(&weight))
1048    {
1049        return out_of_range("font_weight");
1050    }
1051    if node
1052        .strokes
1053        .as_deref()
1054        .is_some_and(|strokes| !crate::text::valid_strokes(strokes))
1055    {
1056        return out_of_range("strokes");
1057    }
1058    if node
1059        .shadows
1060        .as_deref()
1061        .is_some_and(|shadows| !crate::text::valid_shadows(shadows))
1062    {
1063        return out_of_range("shadows");
1064    }
1065    if !crate::text_animation::valid_animators(&node.text_animators, true) {
1066        return out_of_range("text_animators");
1067    }
1068    if !node
1069        .text_animator_pivot
1070        .is_none_or(crate::text::valid_animator_pivot)
1071    {
1072        return out_of_range("text_animator_pivot");
1073    }
1074    if let Some(fit) = &node.font_size_fit {
1075        let font_size = |value: LayoutSize| {
1076            // Pixels compare with the limit on a known canvas only.
1077            let fraction = match (value, shorter_side) {
1078                (LayoutSize::Px(_), None) => 0.0,
1079                (value, Some(side)) => value.fraction(side),
1080                (value, None) => value.value(),
1081            };
1082            value.value().is_finite() && value.value() > 0.0 && fraction <= MAX_LAYOUT_FONT_SIZE
1083        };
1084        let ordered = match (fit.min, fit.max, shorter_side) {
1085            (min, Some(max), Some(side)) => min.fraction(side) <= max.fraction(side),
1086            (LayoutSize::Fraction(min), Some(LayoutSize::Fraction(max)), None)
1087            | (LayoutSize::Px(min), Some(LayoutSize::Px(max)), None) => min <= max,
1088            _ => true,
1089        };
1090        if !font_size(fit.min) || !fit.max.is_none_or(font_size) || !ordered {
1091            return out_of_range("font_size_fit");
1092        }
1093    }
1094    if node
1095        .line_clamp
1096        .as_ref()
1097        .is_some_and(|clamp| !clamp.is_valid())
1098    {
1099        return out_of_range("line_clamp");
1100    }
1101    Ok(())
1102}
1103
1104fn insets(animation: &Animated<Insets>, at: &str, check: fn(f32) -> bool) -> Checked {
1105    animated(animation, at, |value| {
1106        value
1107            .sides()
1108            .iter()
1109            .all(|side| side.in_bounds() && check(side.value()))
1110    })
1111}
1112
1113fn size(animation: &Animated<LayoutSize>, at: &str, check: fn(f32) -> bool) -> Checked {
1114    animated(animation, at, |value| {
1115        value.in_bounds() && check(value.value())
1116    })
1117}
1118
1119/// A length's values, and that its keyframes share a kind: a percent, or a length (a
1120/// fraction or pixels).
1121fn length(
1122    animation: &Animated<LayoutLength>,
1123    at: &str,
1124    check: fn(f32) -> bool,
1125) -> Result<(), GeneratorIssue> {
1126    animated(animation, at, |value| {
1127        value.in_bounds() && check(value.value())
1128    })?;
1129    if let Animated::Keyframes { keyframes } = animation {
1130        let kind = keyframes[0].value.is_percent();
1131        if keyframes.iter().any(|key| key.value.is_percent() != kind) {
1132            return Err(LayoutIssue::new(at, LayoutProblem::LengthKeyframesDiffer).into());
1133        }
1134    }
1135    Ok(())
1136}
1137
1138fn validate_text(
1139    content: &Animated<crate::TextContent>,
1140    at: &str,
1141    base: crate::text_animation::FontSelection<'_>,
1142) -> LayoutChecked {
1143    animated(content, at, |_| true)?;
1144    if let Animated::Keyframes { keyframes } = content
1145        && keyframes
1146            .iter()
1147            .any(|key| key.interpolation != Interpolation::Hold)
1148    {
1149        return Err(LayoutIssue::new(at, LayoutProblem::TextKeyframesInterpolate).into());
1150    }
1151    let not_static = |content: &crate::TextContent| {
1152        content.runs().iter().any(|run| {
1153            !run.class.is_empty()
1154                || run.time.is_some()
1155                || run.style.as_ref().is_some_and(|style| !style.is_static())
1156        })
1157    };
1158    let runs_static = match content {
1159        Animated::Constant { value } => !not_static(value),
1160        Animated::Keyframes { keyframes } => !keyframes.iter().any(|key| not_static(&key.value)),
1161        Animated::Data(_) => true,
1162    };
1163    if !runs_static {
1164        return Err(LayoutIssue::new(at, LayoutProblem::TextRunNotStatic).into());
1165    }
1166    animated(content, at, |content| {
1167        content.len() <= MAX_TEXT_CONTENT_BYTES
1168            && content.runs().iter().all(|run| !run.text.is_empty())
1169            && content.invalid_run_style(base).is_none()
1170    })?;
1171    Ok(())
1172}
1173
1174impl LayoutNode {
1175    /// Whether any container field is present.
1176    fn has_container_field(&self) -> bool {
1177        self.flex_container_field().is_some()
1178            || self.grid_container_field().is_some()
1179            || self.gap.is_some()
1180            || self.row_gap.is_some()
1181            || self.column_gap.is_some()
1182            || self.justify_content.is_some()
1183            || self.align_items.is_some()
1184            || self.align_content.is_some()
1185    }
1186
1187    /// The first flex container field present.
1188    fn flex_container_field(&self) -> Option<&'static str> {
1189        [
1190            ("flex_direction", self.flex_direction.is_some()),
1191            ("flex_wrap", self.flex_wrap.is_some()),
1192        ]
1193        .into_iter()
1194        .find_map(|(name, present)| present.then_some(name))
1195    }
1196
1197    /// The first grid container field present.
1198    fn grid_container_field(&self) -> Option<&'static str> {
1199        [
1200            (
1201                "grid_template_columns",
1202                self.grid_template_columns.is_some(),
1203            ),
1204            ("grid_template_rows", self.grid_template_rows.is_some()),
1205            ("grid_auto_columns", self.grid_auto_columns.is_some()),
1206            ("grid_auto_rows", self.grid_auto_rows.is_some()),
1207            ("grid_auto_flow", self.grid_auto_flow.is_some()),
1208            ("justify_items", self.justify_items.is_some()),
1209        ]
1210        .into_iter()
1211        .find_map(|(name, present)| present.then_some(name))
1212    }
1213
1214    /// The first flex item field present.
1215    fn flex_item_field(&self) -> Option<&'static str> {
1216        [
1217            ("flex_grow", self.flex_grow.is_some()),
1218            ("flex_shrink", self.flex_shrink.is_some()),
1219            ("flex_basis", self.flex_basis.is_some()),
1220        ]
1221        .into_iter()
1222        .find_map(|(name, present)| present.then_some(name))
1223    }
1224
1225    /// The first grid item field present.
1226    fn grid_item_field(&self) -> Option<&'static str> {
1227        [
1228            ("grid_column", self.grid_column.is_some()),
1229            ("grid_row", self.grid_row.is_some()),
1230            ("justify_self", self.justify_self.is_some()),
1231        ]
1232        .into_iter()
1233        .find_map(|(name, present)| present.then_some(name))
1234    }
1235
1236    /// Whether any field the root may not have is present.
1237    fn has_item_field(&self) -> bool {
1238        self.width.is_some()
1239            || self.height.is_some()
1240            || self.min_width.is_some()
1241            || self.min_height.is_some()
1242            || self.max_width.is_some()
1243            || self.max_height.is_some()
1244            || self.aspect_ratio.is_some()
1245            || self.margin.is_some()
1246            || self.flex_item_field().is_some()
1247            || self.grid_item_field().is_some()
1248            || self.align_self.is_some()
1249            || self.position.is_some()
1250            || self.inset.is_some()
1251    }
1252
1253    /// Whether the node has a visual field: opacity, translate, scale, or rotation.
1254    #[must_use]
1255    pub const fn has_visual(&self) -> bool {
1256        self.opacity.is_some()
1257            || self.translate.is_some()
1258            || self.scale.is_some()
1259            || self.rotation_degrees.is_some()
1260    }
1261
1262    /// Whether the node is drawn into its own composite (a visual field or hidden overflow).
1263    /// Presence decides, not values.
1264    #[must_use]
1265    pub const fn is_isolated(&self) -> bool {
1266        self.has_visual() || matches!(self.overflow, Some(Overflow::Hidden))
1267    }
1268
1269    /// Whether the node, its subtree, or a shape in it changes over time.
1270    #[must_use]
1271    pub fn is_animated(&self) -> bool {
1272        let inset = self.inset.as_ref().is_some_and(|inset| {
1273            inset
1274                .sides()
1275                .into_iter()
1276                .any(|(_, value)| keyed_option(value))
1277        });
1278        let shape = self
1279            .shape
1280            .as_ref()
1281            .is_some_and(|shape| shape.items.iter().any(ShapeItem::is_animated));
1282        let border = self
1283            .border
1284            .as_ref()
1285            .is_some_and(|border| keyed(&border.width) || keyed(&border.paint));
1286        [
1287            &self.gap,
1288            &self.row_gap,
1289            &self.column_gap,
1290            &self.border_radius,
1291            &self.font_size,
1292        ]
1293        .into_iter()
1294        .any(|value| keyed_option(value.as_ref()))
1295            || keyed_option(self.padding.as_ref())
1296            || keyed_option(self.background.as_ref())
1297            || border
1298            || [
1299                &self.width,
1300                &self.height,
1301                &self.min_width,
1302                &self.min_height,
1303                &self.max_width,
1304                &self.max_height,
1305                &self.flex_basis,
1306            ]
1307            .into_iter()
1308            .any(|value| keyed_option(value.as_ref()))
1309            || keyed_option(self.margin.as_ref())
1310            || keyed_option(self.flex_grow.as_ref())
1311            || keyed_option(self.flex_shrink.as_ref())
1312            || inset
1313            || keyed_option(self.opacity.as_ref())
1314            || keyed_option(self.translate.as_ref())
1315            || keyed_option(self.scale.as_ref())
1316            || keyed_option(self.rotation_degrees.as_ref())
1317            || keyed_option(self.text.as_ref())
1318            || shape
1319            || crate::text_animation::animators_have_keyframes(&self.text_animators)
1320            || self.children.iter().any(Self::is_animated)
1321    }
1322
1323    /// Every node of the tree in preorder, with its path from the root.
1324    pub fn walk(&self, mut visit: impl FnMut(&str, &Self)) {
1325        fn go(node: &LayoutNode, at: &str, visit: &mut impl FnMut(&str, &LayoutNode)) {
1326            visit(at, node);
1327            for (index, child) in node.children.iter().enumerate() {
1328                go(child, &format!("{at}.children[{index}]"), visit);
1329            }
1330        }
1331        go(self, "root", &mut visit);
1332    }
1333
1334    /// Calls `visit` with each keyframed value of the tree, by path (`root.children[0].opacity`,
1335    /// `root.shape.items[0].transform.scale`), and its times, in document order.
1336    pub(crate) fn for_each_keyed(
1337        &self,
1338        at: &str,
1339        visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
1340    ) {
1341        let field = |name: &str| format!("{at}.{name}");
1342        if let Some(text) = &self.text {
1343            visit_keyed(&field("text"), text, visit);
1344        }
1345        if let Some(shape) = &self.shape {
1346            crate::shapes::for_each_keyed_item(&shape.items, &field("shape.items"), visit);
1347        }
1348        crate::text_animation::for_each_keyed_animator(
1349            &self.text_animators,
1350            &field("text_animators"),
1351            visit,
1352        );
1353        for (name, value) in [
1354            ("gap", &self.gap),
1355            ("row_gap", &self.row_gap),
1356            ("column_gap", &self.column_gap),
1357            ("border_radius", &self.border_radius),
1358            ("font_size", &self.font_size),
1359        ] {
1360            visit_option(&field(name), value.as_ref(), visit);
1361        }
1362        visit_option(&field("padding"), self.padding.as_ref(), visit);
1363        visit_option(&field("background"), self.background.as_ref(), visit);
1364        if let Some(border) = &self.border {
1365            visit_keyed(&field("border.width"), &border.width, visit);
1366            visit_keyed(&field("border.paint"), &border.paint, visit);
1367        }
1368        for (name, value) in [
1369            ("width", &self.width),
1370            ("height", &self.height),
1371            ("min_width", &self.min_width),
1372            ("min_height", &self.min_height),
1373            ("max_width", &self.max_width),
1374            ("max_height", &self.max_height),
1375            ("flex_basis", &self.flex_basis),
1376        ] {
1377            visit_option(&field(name), value.as_ref(), visit);
1378        }
1379        visit_option(&field("margin"), self.margin.as_ref(), visit);
1380        visit_option(&field("flex_grow"), self.flex_grow.as_ref(), visit);
1381        visit_option(&field("flex_shrink"), self.flex_shrink.as_ref(), visit);
1382        if let Some(inset) = &self.inset {
1383            for (side, value) in inset.sides() {
1384                visit_option(&field(&format!("inset.{side}")), value, visit);
1385            }
1386        }
1387        visit_option(&field("opacity"), self.opacity.as_ref(), visit);
1388        visit_option(&field("translate"), self.translate.as_ref(), visit);
1389        visit_option(&field("scale"), self.scale.as_ref(), visit);
1390        visit_option(
1391            &field("rotation_degrees"),
1392            self.rotation_degrees.as_ref(),
1393            visit,
1394        );
1395        for (index, child) in self.children.iter().enumerate() {
1396            child.for_each_keyed(&format!("{at}.children[{index}]"), visit);
1397        }
1398    }
1399
1400    /// The tree with every pixel length converted to a fraction of a picture `shorter_side`
1401    /// pixels on its shorter side, so pixels and fractions interpolate as one kind.
1402    #[must_use]
1403    pub fn without_px(&self, shorter_side: f32) -> Self {
1404        let mut node = self.clone();
1405        node.convert_px(shorter_side);
1406        node
1407    }
1408
1409    fn convert_px(&mut self, shorter_side: f32) {
1410        let size = |value: &mut Option<Animated<LayoutSize>>| {
1411            if let Some(value) = value {
1412                *value = value.map(|size| size.without_px(shorter_side));
1413            }
1414        };
1415        let length = |value: &mut Option<Animated<LayoutLength>>| {
1416            if let Some(value) = value {
1417                *value = value.map(|length| length.without_px(shorter_side));
1418            }
1419        };
1420        let insets = |value: &mut Option<Animated<Insets>>| {
1421            if let Some(value) = value {
1422                *value = value.map(|insets| insets.without_px(shorter_side));
1423            }
1424        };
1425        let tracks = |value: &mut Option<TrackList>| {
1426            if let Some(tracks) = value {
1427                *tracks = tracks.without_px(shorter_side);
1428            }
1429        };
1430        tracks(&mut self.grid_template_columns);
1431        tracks(&mut self.grid_template_rows);
1432        tracks(&mut self.grid_auto_columns);
1433        tracks(&mut self.grid_auto_rows);
1434        for value in [
1435            &mut self.gap,
1436            &mut self.row_gap,
1437            &mut self.column_gap,
1438            &mut self.border_radius,
1439            &mut self.font_size,
1440        ] {
1441            size(value);
1442        }
1443        if let Some(fit) = &mut self.font_size_fit {
1444            fit.min = fit.min.without_px(shorter_side);
1445            fit.max = fit.max.map(|max| max.without_px(shorter_side));
1446        }
1447        insets(&mut self.padding);
1448        insets(&mut self.margin);
1449        if let Some(border) = &mut self.border {
1450            border.width = border.width.map(|width| width.without_px(shorter_side));
1451        }
1452        for value in [
1453            &mut self.width,
1454            &mut self.height,
1455            &mut self.min_width,
1456            &mut self.min_height,
1457            &mut self.max_width,
1458            &mut self.max_height,
1459            &mut self.flex_basis,
1460        ] {
1461            length(value);
1462        }
1463        if let Some(inset) = &mut self.inset {
1464            for side in [
1465                &mut inset.left,
1466                &mut inset.top,
1467                &mut inset.right,
1468                &mut inset.bottom,
1469            ] {
1470                length(side);
1471            }
1472        }
1473        if let Some(translate) = &mut self.translate {
1474            *translate = translate.map(|offset| offset.without_px(shorter_side));
1475        }
1476        for child in &mut self.children {
1477            child.convert_px(shorter_side);
1478        }
1479    }
1480}
1481
1482fn visit_option<T: crate::animation::Placed>(
1483    at: &str,
1484    animation: Option<&Animated<T>>,
1485    visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
1486) {
1487    if let Some(animation) = animation {
1488        visit_keyed(at, animation, visit);
1489    }
1490}
1491
1492const fn keyed<T>(animation: &Animated<T>) -> bool {
1493    matches!(animation, Animated::Keyframes { .. })
1494}
1495
1496const fn keyed_option<T>(animation: Option<&Animated<T>>) -> bool {
1497    matches!(animation, Some(Animated::Keyframes { .. }))
1498}