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