Skip to main content

alpha2_layout/layout/
resolve.rs

1//! Flexbox and grid resolution with taffy. This is the only file that names taffy.
2
3use super::{NodeRects, ResolvedLayout, wrap};
4use crate::PictureSize;
5use alpha2_eval::{EvaluatedLayout, EvaluatedNode, NodeContent, NodeLayout, Sides};
6use alpha2_model::{
7    AlignContent, AlignItems, Display, FlexDirection, FlexWrap, GridAutoFlow, GridEdge,
8    GridPlacement, JustifyContent, LayoutLength, Overflow, Position, RepeatCount, TrackBreadth,
9    TrackComponent, TrackList, TrackSize,
10};
11use alpha2_text::ShapedText;
12use std::sync::Arc;
13use taffy::{
14    AvailableSpace, Dimension, GridTemplateComponent, GridTemplateRepetition, LengthPercentage,
15    LengthPercentageAuto, MaxTrackSizingFunction, MinTrackSizingFunction, NodeId, Point, Rect,
16    RepetitionCount, Size, Style, TaffyTree, TrackSizingFunction,
17};
18
19/// What a leaf measures by.
20#[derive(Copy, Clone)]
21enum NodeContext {
22    /// The text node with this index among the shaped texts.
23    Text(usize),
24    /// A shape node, an empty node, or an empty text: no size of its own.
25    Other,
26}
27
28/// Lays `layout` out on a picture of `size` pixels. `shaped` holds each text node's shaped
29/// text in preorder, `None` for empty text.
30#[allow(clippy::cast_precision_loss)]
31#[must_use]
32pub fn resolve(
33    layout: &EvaluatedLayout,
34    size: PictureSize,
35    shaped: &[Option<Arc<ShapedText>>],
36) -> ResolvedLayout {
37    let (width, height) = (size.width() as f32, size.height() as f32);
38    let unit = width.min(height);
39    let mut tree = TaffyTree::<NodeContext>::new();
40    let mut ids = Vec::new();
41    let mut texts = 0;
42    let mut evaluated = Vec::new();
43    super::texts(&layout.root, &mut evaluated);
44    let root = build(
45        &mut tree,
46        &layout.root,
47        unit,
48        Some(Size { width, height }),
49        &mut ids,
50        &mut texts,
51    );
52    // A tree built from a valid layout always lays out; a failure leaves every rect empty.
53    let laid_out = tree
54        .compute_layout_with_measure(
55            root,
56            Size {
57                width: AvailableSpace::Definite(width),
58                height: AvailableSpace::Definite(height),
59            },
60            |inputs, _, context, style| match context {
61                Some(NodeContext::Text(index)) => {
62                    let text = shaped.get(*index).and_then(Option::as_deref);
63                    let node_text = evaluated.get(*index).copied().flatten();
64                    // The automatic height ends at the clamp point of a clamp by count.
65                    let limit = node_text
66                        .and_then(|text| text.line_clamp.as_ref())
67                        .and_then(|clamp| clamp.max_lines);
68                    let headroom = node_text.map_or(1.0, |text| text.advance_headroom);
69                    taffy::compute_leaf_layout(
70                        inputs,
71                        style,
72                        |_, _| 0.0,
73                        |known, available| {
74                            let Some(text) = text else {
75                                return Size::ZERO;
76                            };
77                            let (min, max) = (
78                                text.min_content_width() * headroom,
79                                text.max_content_width() * headroom,
80                            );
81                            let width = known.width.unwrap_or(match available.width {
82                                AvailableSpace::MinContent => min,
83                                AvailableSpace::MaxContent => max,
84                                AvailableSpace::Definite(space) => space.min(max).max(min),
85                            });
86                            let height = known.height.unwrap_or_else(|| {
87                                text.lines_within(
88                                    alpha2_text::wrap_width(wrap(width), headroom),
89                                    limit,
90                                )
91                                .lines
92                                .height
93                            });
94                            Size { width, height }
95                        },
96                    )
97                }
98                _ => taffy::compute_leaf_layout(
99                    inputs,
100                    style,
101                    |_, _| 0.0,
102                    |known, _| Size {
103                        width: known.width.unwrap_or(0.0),
104                        height: known.height.unwrap_or(0.0),
105                    },
106                ),
107            },
108        )
109        .is_ok();
110    let mut nodes = Vec::with_capacity(ids.len());
111    if laid_out {
112        collect(
113            &tree,
114            &layout.root,
115            &ids,
116            [0.0, 0.0],
117            &mut 0,
118            (shaped, unit),
119            &mut 0,
120            &mut nodes,
121        );
122    } else {
123        nodes.resize(ids.len(), NodeRects::default());
124    }
125    ResolvedLayout { nodes }
126}
127
128/// Adds `node` and its subtree to `tree`, children first; `ids` gets each node's id in
129/// preorder.
130fn build(
131    tree: &mut TaffyTree<NodeContext>,
132    node: &EvaluatedNode,
133    unit: f32,
134    root_size: Option<Size<f32>>,
135    ids: &mut Vec<NodeId>,
136    texts: &mut usize,
137) -> NodeId {
138    let style = taffy_style(&node.layout, unit, root_size);
139    let slot = ids.len();
140    ids.push(NodeId::from(0_u64));
141    let id = match &node.content {
142        NodeContent::Children(children) => {
143            let children = children
144                .iter()
145                .map(|child| build(tree, child, unit, None, ids, texts))
146                .collect::<Vec<_>>();
147            tree.new_with_children(style, &children)
148        }
149        NodeContent::Text(_) => {
150            let index = *texts;
151            *texts += 1;
152            tree.new_leaf_with_context(style, NodeContext::Text(index))
153        }
154        NodeContent::Empty | NodeContent::Shape(_) => {
155            tree.new_leaf_with_context(style, NodeContext::Other)
156        }
157    }
158    .expect("taffy adds nodes without failing");
159    ids[slot] = id;
160    id
161}
162
163fn length(value: f32, unit: f32) -> LengthPercentage {
164    LengthPercentage::length(value * unit)
165}
166
167// A plan holds no pixels (they became fractions); one left over would read as a fraction.
168
169fn length_auto(value: Option<LayoutLength>, unit: f32) -> LengthPercentageAuto {
170    match value {
171        None => LengthPercentageAuto::auto(),
172        Some(LayoutLength::Fraction(value) | LayoutLength::Px(value)) => {
173            LengthPercentageAuto::length(value * unit)
174        }
175        Some(LayoutLength::Percent(value)) => LengthPercentageAuto::percent(value / 100.0),
176    }
177}
178
179fn dimension(value: Option<LayoutLength>, unit: f32) -> Dimension {
180    match value {
181        None => Dimension::auto(),
182        Some(LayoutLength::Fraction(value) | LayoutLength::Px(value)) => {
183            Dimension::length(value * unit)
184        }
185        Some(LayoutLength::Percent(value)) => Dimension::percent(value / 100.0),
186    }
187}
188
189fn min_breadth(breadth: TrackBreadth, unit: f32) -> MinTrackSizingFunction {
190    match breadth {
191        TrackBreadth::Length(LayoutLength::Fraction(value) | LayoutLength::Px(value)) => {
192            MinTrackSizingFunction::length(value * unit)
193        }
194        TrackBreadth::Length(LayoutLength::Percent(value)) => {
195            MinTrackSizingFunction::percent(value / 100.0)
196        }
197        // A minimum is never fr: the parser refuses it, as CSS does.
198        TrackBreadth::Auto | TrackBreadth::Fr(_) => MinTrackSizingFunction::auto(),
199        TrackBreadth::MinContent => MinTrackSizingFunction::min_content(),
200        TrackBreadth::MaxContent => MinTrackSizingFunction::max_content(),
201    }
202}
203
204fn max_breadth(breadth: TrackBreadth, unit: f32) -> MaxTrackSizingFunction {
205    match breadth {
206        TrackBreadth::Length(LayoutLength::Fraction(value) | LayoutLength::Px(value)) => {
207            MaxTrackSizingFunction::length(value * unit)
208        }
209        TrackBreadth::Length(LayoutLength::Percent(value)) => {
210            MaxTrackSizingFunction::percent(value / 100.0)
211        }
212        TrackBreadth::Fr(share) => MaxTrackSizingFunction::fr(share),
213        TrackBreadth::Auto => MaxTrackSizingFunction::auto(),
214        TrackBreadth::MinContent => MaxTrackSizingFunction::min_content(),
215        TrackBreadth::MaxContent => MaxTrackSizingFunction::max_content(),
216    }
217}
218
219/// A track's sizing functions as CSS reads a single breadth: a length is fixed, `<n>fr` is
220/// `minmax(auto, <n>fr)`, and a keyword sizes by content.
221fn track(size: TrackSize, unit: f32) -> TrackSizingFunction {
222    let (min, max) = match size {
223        TrackSize::Breadth(TrackBreadth::Fr(share)) => (
224            MinTrackSizingFunction::auto(),
225            MaxTrackSizingFunction::fr(share),
226        ),
227        TrackSize::Breadth(breadth) => (min_breadth(breadth, unit), max_breadth(breadth, unit)),
228        TrackSize::MinMax(min, max) => (min_breadth(min, unit), max_breadth(max, unit)),
229        TrackSize::FitContent(limit) => (
230            MinTrackSizingFunction::auto(),
231            match limit {
232                LayoutLength::Fraction(value) | LayoutLength::Px(value) => {
233                    MaxTrackSizingFunction::fit_content_px(value * unit)
234                }
235                LayoutLength::Percent(value) => {
236                    MaxTrackSizingFunction::fit_content_percent(value / 100.0)
237                }
238            },
239        ),
240    };
241    TrackSizingFunction { min, max }
242}
243
244/// An explicit track list, `repeat()` kept for taffy to expand, without line names (the
245/// model refuses them).
246fn template<S: taffy::CheapCloneStr>(
247    tracks: Option<&TrackList>,
248    unit: f32,
249) -> Vec<GridTemplateComponent<S>> {
250    tracks.map_or_else(Vec::new, |tracks| {
251        tracks
252            .0
253            .iter()
254            .map(|component| match component {
255                TrackComponent::Single(size) => GridTemplateComponent::Single(track(*size, unit)),
256                TrackComponent::Repeat(count, sizes) => {
257                    GridTemplateComponent::Repeat(GridTemplateRepetition {
258                        count: match count {
259                            RepeatCount::Count(count) => RepetitionCount::Count(*count),
260                            RepeatCount::AutoFill => RepetitionCount::AutoFill,
261                            RepeatCount::AutoFit => RepetitionCount::AutoFit,
262                        },
263                        tracks: sizes.iter().map(|size| track(*size, unit)).collect(),
264                        line_names: Vec::new(),
265                    })
266                }
267            })
268            .collect()
269    })
270}
271
272/// Implicit track sizes: the model refuses `repeat()` in them.
273fn implicit(tracks: Option<&TrackList>, unit: f32) -> Vec<TrackSizingFunction> {
274    tracks.map_or_else(Vec::new, |tracks| {
275        tracks.sizes().map(|size| track(size, unit)).collect()
276    })
277}
278
279fn placement<S: taffy::CheapCloneStr>(
280    placement: GridPlacement,
281) -> taffy::Line<taffy::GridPlacement<S>> {
282    let edge = |edge: GridEdge| match edge {
283        GridEdge::Auto => taffy::GridPlacement::Auto,
284        GridEdge::Line(line) => taffy::style_helpers::line(line),
285        GridEdge::Span(count) => taffy::GridPlacement::Span(count),
286    };
287    taffy::Line {
288        start: edge(placement.start),
289        end: edge(placement.end),
290    }
291}
292
293const fn align(value: AlignItems) -> taffy::AlignItems {
294    match value {
295        AlignItems::Start => taffy::AlignItems::START,
296        AlignItems::Center => taffy::AlignItems::CENTER,
297        AlignItems::End => taffy::AlignItems::END,
298        AlignItems::Stretch => taffy::AlignItems::STRETCH,
299    }
300}
301
302const fn align_content(value: AlignContent) -> taffy::AlignContent {
303    match value {
304        AlignContent::Start => taffy::AlignContent::START,
305        AlignContent::Center => taffy::AlignContent::CENTER,
306        AlignContent::End => taffy::AlignContent::END,
307        AlignContent::SpaceBetween => taffy::AlignContent::SPACE_BETWEEN,
308        AlignContent::SpaceAround => taffy::AlignContent::SPACE_AROUND,
309        AlignContent::SpaceEvenly => taffy::AlignContent::SPACE_EVENLY,
310        AlignContent::Stretch => taffy::AlignContent::STRETCH,
311    }
312}
313
314/// The taffy style of one node, lengths scaled by `unit` pixels. The root takes the
315/// picture's size.
316fn taffy_style(node: &NodeLayout, unit: f32, root_size: Option<Size<f32>>) -> Style {
317    let insets = |insets: Sides| Rect {
318        left: length(insets.left, unit),
319        right: length(insets.right, unit),
320        top: length(insets.top, unit),
321        bottom: length(insets.bottom, unit),
322    };
323    let margin = Rect {
324        left: LengthPercentageAuto::length(node.margin.left * unit),
325        right: LengthPercentageAuto::length(node.margin.right * unit),
326        top: LengthPercentageAuto::length(node.margin.top * unit),
327        bottom: LengthPercentageAuto::length(node.margin.bottom * unit),
328    };
329    let border = length(node.border_width, unit);
330    let [left, top, right, bottom] = node.inset;
331    let overflow = match node.overflow {
332        Overflow::Visible => taffy::Overflow::Visible,
333        Overflow::Hidden => taffy::Overflow::Hidden,
334    };
335    Style {
336        display: match node.display {
337            Display::Flex => taffy::Display::Flex,
338            Display::Grid => taffy::Display::Grid,
339        },
340        box_sizing: taffy::BoxSizing::BorderBox,
341        direction: taffy::Direction::Ltr,
342        flex_direction: match node.flex_direction {
343            FlexDirection::Row => taffy::FlexDirection::Row,
344            FlexDirection::Column => taffy::FlexDirection::Column,
345            FlexDirection::RowReverse => taffy::FlexDirection::RowReverse,
346            FlexDirection::ColumnReverse => taffy::FlexDirection::ColumnReverse,
347        },
348        flex_wrap: match node.flex_wrap {
349            FlexWrap::NoWrap => taffy::FlexWrap::NoWrap,
350            FlexWrap::Wrap => taffy::FlexWrap::Wrap,
351        },
352        gap: Size {
353            width: length(node.column_gap, unit),
354            height: length(node.row_gap, unit),
355        },
356        justify_content: match node.justify_content {
357            JustifyContent::Start => taffy::JustifyContent::START,
358            JustifyContent::Center => taffy::JustifyContent::CENTER,
359            JustifyContent::End => taffy::JustifyContent::END,
360            JustifyContent::SpaceBetween => taffy::JustifyContent::SPACE_BETWEEN,
361            JustifyContent::SpaceAround => taffy::JustifyContent::SPACE_AROUND,
362            JustifyContent::SpaceEvenly => taffy::JustifyContent::SPACE_EVENLY,
363        },
364        align_items: align(node.align_items),
365        align_self: node.align_self.map(align),
366        align_content: align_content(node.align_content),
367        padding: insets(node.padding),
368        margin,
369        border: Rect {
370            left: border,
371            right: border,
372            top: border,
373            bottom: border,
374        },
375        size: root_size.map_or_else(
376            || Size {
377                width: dimension(node.width, unit),
378                height: dimension(node.height, unit),
379            },
380            |size| Size {
381                width: Dimension::length(size.width),
382                height: Dimension::length(size.height),
383            },
384        ),
385        min_size: Size {
386            width: length_auto(node.min_width, unit),
387            height: length_auto(node.min_height, unit),
388        },
389        max_size: Size {
390            width: length_auto(node.max_width, unit),
391            height: length_auto(node.max_height, unit),
392        },
393        aspect_ratio: node.aspect_ratio,
394        flex_grow: node.flex_grow,
395        flex_shrink: node.flex_shrink,
396        flex_basis: dimension(node.flex_basis, unit),
397        // Every box is positioned, so an absolute box's containing block is its parent.
398        position: match node.position {
399            Position::Relative => taffy::Position::Relative,
400            Position::Absolute => taffy::Position::Absolute,
401        },
402        inset: Rect {
403            left: length_auto(left, unit),
404            top: length_auto(top, unit),
405            right: length_auto(right, unit),
406            bottom: length_auto(bottom, unit),
407        },
408        overflow: Point {
409            x: overflow,
410            y: overflow,
411        },
412        scrollbar_width: 0.0,
413        ..grid_style(node, unit)
414    }
415}
416
417/// The grid container and grid item fields of one node's taffy style, lengths scaled by
418/// `unit` pixels.
419fn grid_style(node: &NodeLayout, unit: f32) -> Style {
420    Style {
421        justify_items: align(node.justify_items),
422        justify_self: node.justify_self.map(align),
423        grid_template_columns: template(node.grid_template_columns.as_ref(), unit),
424        grid_template_rows: template(node.grid_template_rows.as_ref(), unit),
425        grid_auto_columns: implicit(node.grid_auto_columns.as_ref(), unit),
426        grid_auto_rows: implicit(node.grid_auto_rows.as_ref(), unit),
427        grid_auto_flow: match node.grid_auto_flow {
428            GridAutoFlow::Row => taffy::GridAutoFlow::Row,
429            GridAutoFlow::Column => taffy::GridAutoFlow::Column,
430            GridAutoFlow::RowDense => taffy::GridAutoFlow::RowDense,
431            GridAutoFlow::ColumnDense => taffy::GridAutoFlow::ColumnDense,
432        },
433        grid_column: placement(node.grid_column),
434        grid_row: placement(node.grid_row),
435        ..Style::default()
436    }
437}
438
439/// Reads each node's rects in preorder as absolute whole-pixel boxes, summed from the
440/// rounded locations (taffy rounds by absolute position).
441#[allow(clippy::too_many_arguments)]
442fn collect(
443    tree: &TaffyTree<NodeContext>,
444    node: &EvaluatedNode,
445    ids: &[NodeId],
446    origin: [f32; 2],
447    index: &mut usize,
448    (shaped, unit): (&[Option<Arc<ShapedText>>], f32),
449    texts: &mut usize,
450    out: &mut Vec<NodeRects>,
451) {
452    let id = ids[*index];
453    *index += 1;
454    let rounded = tree.layout(id).expect("laid out");
455    let unrounded = tree.unrounded_layout(id);
456    let left = origin[0] + rounded.location.x;
457    let top = origin[1] + rounded.location.y;
458    let border = [
459        left,
460        top,
461        left + rounded.size.width,
462        top + rounded.size.height,
463    ];
464    let padding = [
465        border[0] + rounded.border.left,
466        border[1] + rounded.border.top,
467        border[2] - rounded.border.right,
468        border[3] - rounded.border.bottom,
469    ];
470    let content = [
471        padding[0] + rounded.padding.left,
472        padding[1] + rounded.padding.top,
473        padding[2] - rounded.padding.right,
474        padding[3] - rounded.padding.bottom,
475    ];
476    let text_width = (unrounded.size.width
477        - unrounded.border.left
478        - unrounded.border.right
479        - unrounded.padding.left
480        - unrounded.padding.right)
481        .max(0.0);
482    // Compare with the text's own unrounded height: taffy rounds edges by absolute position,
483    // so a whole-pixel box can be up to a pixel shorter than the height it was given.
484    let text_height = (unrounded.size.height
485        - unrounded.border.top
486        - unrounded.border.bottom
487        - unrounded.padding.top
488        - unrounded.padding.bottom)
489        .max(0.0);
490    let slot = out.len();
491    out.push(NodeRects {
492        border,
493        padding,
494        content,
495        text_width,
496        text_height,
497        ..NodeRects::default()
498    });
499    let mut overflow = false;
500    match &node.content {
501        NodeContent::Text(evaluated) => {
502            let text = shaped.get(*texts).and_then(Option::as_deref);
503            *texts += 1;
504            out[slot].font_size = evaluated.font_size;
505            out[slot].font_pixels = super::pixels(evaluated.font_size, unit);
506            let lines = text.map(|text| {
507                let boxed = super::node_lines(evaluated, text, text_width, text_height);
508                overflow = boxed.overflow;
509                out[slot].truncated = boxed.truncated;
510                boxed.lines
511            });
512            out[slot].line_count = Some(lines.map_or(0, |lines| lines.line_count));
513            out[slot].baselines = lines.map(|lines| {
514                [
515                    content[1] + lines.first_baseline,
516                    content[1] + lines.last_baseline,
517                ]
518            });
519        }
520        NodeContent::Children(children) => {
521            for child in children {
522                let at = out.len();
523                collect(
524                    tree,
525                    child,
526                    ids,
527                    [left, top],
528                    index,
529                    (shaped, unit),
530                    texts,
531                    out,
532                );
533                if child.layout.position == Position::Relative {
534                    let [l, t, r, b] = out[at].border;
535                    overflow |= l < padding[0] - 0.5
536                        || t < padding[1] - 0.5
537                        || r > padding[2] + 0.5
538                        || b > padding[3] + 0.5;
539                }
540            }
541        }
542        NodeContent::Empty | NodeContent::Shape(_) => {}
543    }
544    out[slot].overflow = overflow;
545}