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