Skip to main content

devpage_design/render/
layout.rs

1//! Layout: the scene as a taffy tree — flexbox restricted to Figma's auto
2//! layout, no-layout frames hugging their children — and every node's box.
3
4use crate::scene::{self, Align, ImageFiles, Layout, Node, Scene, Size as DSize};
5use crate::tree::{Order, OrderKey};
6
7use super::*;
8
9mod run;
10pub(super) use run::*;
11impl Renderer {
12    /// Lays the scene out: every node's box, in tree order — as a drawing
13    /// lays it out, runs and all.
14    pub fn layout(&mut self, scene: &Scene) -> Vec<Frame> {
15        self.register(&scene.fonts);
16        let mut l = Laid::build(self, scene);
17        l.settle_top(self);
18        l.frames(self, &scene.root).into_values().collect()
19    }
20
21    /// Lays out `tree` from `root` in the room `available` gives it, each leaf
22    /// measured by what it is ([`Leaf`]).
23    pub(super) fn compute(
24        &mut self,
25        runs: &mut Runs,
26        tree: &mut TaffyTree<Option<Leaf>>,
27        root: NodeId,
28        available: Size<AvailableSpace>,
29    ) {
30        tree.compute_layout_with_measure(root, available, |input, _id, ctx, style| {
31            let known = input.known_dimensions;
32            let fixed = |d: Dimension| (!d.is_auto()).then(|| d.value());
33            let known = Size {
34                width: known.width.or(fixed(style.size.width)),
35                height: known.height.or(fixed(style.size.height)),
36            };
37            let size = match ctx {
38                Some(Some(Leaf::Intrinsic(w, h))) => {
39                    // A vector or an image hugging keeps its own aspect.
40                    let (w, h) = (*w, *h);
41                    match (known.width, known.height) {
42                        (Some(kw), None) => Size {
43                            width: kw,
44                            height: kw * h / w,
45                        },
46                        (None, Some(kh)) => Size {
47                            width: kh * w / h,
48                            height: kh,
49                        },
50                        (kw, kh) => Size {
51                            width: kw.unwrap_or(w),
52                            height: kh.unwrap_or(h),
53                        },
54                    }
55                }
56                Some(Some(Leaf::Run(id))) => {
57                    // A size the run's own style gives is never less than
58                    // its padding, as taffy floors a box's own size; a size
59                    // its parent gives — a stretch — is taken as it is.
60                    let [t, r, b, l] = runs.get(*id).padding;
61                    let own = Size {
62                        width: fixed(style.size.width).map(|v| v.max(l + r)),
63                        height: fixed(style.size.height).map(|v| v.max(t + b)),
64                    };
65                    let known = Size {
66                        width: input.known_dimensions.width.or(own.width),
67                        height: input.known_dimensions.height.or(own.height),
68                    };
69                    return taffy::LayoutOutput::from_outer_size(self.measure_run(
70                        runs,
71                        *id,
72                        known,
73                        input.available_space,
74                    ));
75                }
76                Some(Some(Leaf::Text(text, wraps))) => {
77                    let width = known.width.or(match input.available_space.width {
78                        AvailableSpace::Definite(w) if *wraps => Some(w),
79                        _ => None,
80                    });
81                    let layout = self.text_layout(text, width);
82                    Size {
83                        width: known.width.unwrap_or(layout.width().ceil()),
84                        height: known.height.unwrap_or(layout.height()),
85                    }
86                }
87                _ => Size {
88                    width: known.width.unwrap_or(0.0),
89                    height: known.height.unwrap_or(0.0),
90                },
91            };
92            taffy::LayoutOutput::from_outer_size(size)
93        })
94        .expect("layout");
95    }
96}
97
98impl Renderer {
99    /// Lays a tree out from `root` in `available`, hugging no-layout frames
100    /// to their children.
101    pub(super) fn settle_in(
102        &mut self,
103        runs: &mut Runs,
104        tree: &mut TaffyTree<Option<Leaf>>,
105        root: NodeId,
106        available: Size<AvailableSpace>,
107        hugs: &[(NodeId, bool, bool)],
108    ) {
109        // To the fixed point: each pass settles at least one more level of
110        // hugging frames, and a run sized against the room a hugging frame
111        // gives it can take another; bounded, so it always ends.
112        for _ in 0..256 {
113            self.compute(runs, tree, root, available);
114            let mut changed = false;
115            for &(id, w, h) in hugs {
116                let (mut ew, mut eh) = (0.0f32, 0.0f32);
117                for child in tree.children(id).expect("children") {
118                    let l = tree.unrounded_layout(child);
119                    ew = ew.max(l.location.x + l.size.width);
120                    eh = eh.max(l.location.y + l.size.height);
121                }
122                let mut style = tree.style(id).expect("style").clone();
123                let mut ch = false;
124                let mut set = |d: &mut Dimension, v: f32| {
125                    if *d != Dimension::length(v) {
126                        *d = Dimension::length(v);
127                        ch = true;
128                    }
129                };
130                if w {
131                    set(&mut style.size.width, ew);
132                }
133                if h {
134                    set(&mut style.size.height, eh);
135                }
136                if ch {
137                    tree.set_style(id, style).expect("style");
138                    changed = true;
139                }
140            }
141            if !changed {
142                break;
143            }
144        }
145    }
146}
147
148/// The node at `order` under `root`; panics when there is none.
149pub(super) fn find_node<'a>(root: &'a Node, order: &[OrderKey]) -> &'a Node {
150    let mut at = root;
151    for k in order {
152        at = at.children.get(k).expect("a node there");
153    }
154    at
155}
156
157/// Removes `id` and everything under it from the layout tree.
158pub(super) fn remove_subtree(tree: &mut TaffyTree<Option<Leaf>>, id: NodeId) {
159    for child in tree.children(id).unwrap_or_default() {
160        remove_subtree(tree, child);
161    }
162    let _ = tree.remove(id);
163}
164
165/// What a leaf of the layout tree measures by: a text, or a vector's or an
166/// image's own size.
167pub(super) enum Leaf {
168    /// A text, and whether it wraps at its width.
169    Text(Box<scene::TextStyle>, bool),
170    /// A vector or an image: its own width and height, whose aspect it keeps
171    /// when it hugs.
172    Intrinsic(f32, f32),
173    /// A run, laid out by its own tree: [`Renderer::measure_run`].
174    Run(u32),
175    /// A run's `"fill"` child as the run's flex tree sees it: measured by
176    /// laying the child out in its own container.
177    Proxy(OrderKey),
178}
179
180/// A scene's layout kept in pieces: the drawing's own layout tree, a tree
181/// for each run's children, and where each node is in them.
182pub(super) struct Laid {
183    /// The drawing's own layout tree, laid out unrounded.
184    pub(super) top: TaffyTree<Option<Leaf>>,
185    /// The scene root's node in `top`.
186    pub(super) root: NodeId,
187    /// Each run's layout, with its tree for its children.
188    pub(super) runs: Runs,
189    /// Each node's tree and layout node, by its order.
190    pub(super) nodes: BTreeMap<Order, (Owner, NodeId)>,
191    /// Each run's layout, by its node's order.
192    pub(super) run_of: BTreeMap<Order, u32>,
193    /// Whether each node's size can depend on the room it is given, and how
194    /// many of its children's can: counted, so an edit settles it along its
195    /// path alone.
196    pub(super) sens: BTreeMap<Order, Sens>,
197}
198
199/// Whether a node's size can depend on the room it is laid out in, along
200/// each axis, and how many of its children's sizes can along each.
201#[derive(Clone, Copy, Debug, Default)]
202pub(super) struct Sens {
203    /// Whether its width or its height depends on its room.
204    pub(super) me: bool,
205    /// Whether its width depends on its room; `me` is this or `h`.
206    pub(super) w: bool,
207    /// Whether its height depends on its room.
208    pub(super) h: bool,
209    /// How many of its children's widths do.
210    pub(super) kids_w: usize,
211    /// How many of its children's heights do.
212    pub(super) kids_h: usize,
213}
214
215/// Whether `node`'s width and height depend on its room, given how many of
216/// its children's do: a size it fixes doesn't, whatever is in it; `"fill"`
217/// does; a size that hugs does only through a child's that does. A text
218/// wraps at a width it is given — fixed or `"fill"` — and hugs its words
219/// otherwise, so a text's own room reaches it only through `"fill"`.
220fn room(node: &Node, kids_w: usize, kids_h: usize) -> (bool, bool) {
221    let along = |s: DSize, kids: usize| match s {
222        DSize::Px(_) => false,
223        DSize::Fill => true,
224        DSize::Hug => kids > 0,
225    };
226    (along(node.width, kids_w), along(node.height, kids_h))
227}
228
229impl Laid {
230    /// The room-dependence of `node`, at `order`, and everything under it:
231    /// whether its width and its height depend on its room.
232    pub(super) fn sens_build(&mut self, node: &Node, order: Order) -> (bool, bool) {
233        let (mut kids_w, mut kids_h) = (0, 0);
234        for (k, c) in node.children.entries() {
235            let mut o = order.clone();
236            o.push(k.clone());
237            let (w, h) = self.sens_build(c, o);
238            kids_w += w as usize;
239            kids_h += h as usize;
240        }
241        let (w, h) = room(node, kids_w, kids_h);
242        self.sens.insert(
243            order,
244            Sens {
245                me: w || h,
246                w,
247                h,
248                kids_w,
249                kids_h,
250            },
251        );
252        (w, h)
253    }
254
255    /// Whether the node at `order` can depend on its room.
256    pub(super) fn sensitive(&self, order: &Order) -> bool {
257        self.sens.get(order).is_some_and(|s| s.me)
258    }
259
260    /// The node at `order` changed, or a child of it came or went, changing
261    /// how many of its children depend on their room along each axis by
262    /// `kids`: its room-dependence settled again, and its parents' while it
263    /// changes — a run told its child is laid out another way.
264    pub(super) fn sens_settle(&mut self, root: &Node, order: &Order, kids: (isize, isize)) {
265        let mut at = order.clone();
266        let mut delta = kids;
267        loop {
268            let node = find_node(root, &at);
269            let s = self.sens.entry(at.clone()).or_default();
270            s.kids_w = (s.kids_w as isize + delta.0).max(0) as usize;
271            s.kids_h = (s.kids_h as isize + delta.1).max(0) as usize;
272            let (was_w, was_h, was) = (s.w, s.h, s.me);
273            let (w, h) = room(node, s.kids_w, s.kids_h);
274            (s.w, s.h, s.me) = (w, h, w || h);
275            if at.is_empty() {
276                return;
277            }
278            let parent = at[..at.len() - 1].to_vec();
279            if was != s.me
280                && let Some(&rid) = self.run_of.get(&parent)
281            {
282                let now = s.me;
283                let k = at.last().expect("a key").clone();
284                let run = self.runs.get_mut(rid);
285                let stretch = run.children.get(&k).is_some_and(|c| c.stretch);
286                run.classify(&k, stretch, now);
287            }
288            if (was_w, was_h) == (w, h) {
289                return;
290            }
291            delta = (w as isize - was_w as isize, h as isize - was_h as isize);
292            at = parent;
293        }
294    }
295
296    /// The subtree at `order` gone: its records dropped, and its parent's
297    /// counts with it.
298    pub(super) fn sens_drop(&mut self, root: &Node, order: &Order) {
299        let (w, h) = self.sens.get(order).map_or((false, false), |s| (s.w, s.h));
300        let under: Vec<Order> = self
301            .sens
302            .range(order.clone()..)
303            .take_while(|(o, _)| o.starts_with(order))
304            .map(|(o, _)| o.clone())
305            .collect();
306        for o in under {
307            self.sens.remove(&o);
308        }
309        if (w || h) && !order.is_empty() {
310            let parent = order[..order.len() - 1].to_vec();
311            if self.sens.contains_key(&parent) {
312                self.sens_settle(root, &parent, (-(w as isize), -(h as isize)));
313            }
314        }
315    }
316}
317
318use std::collections::BTreeMap;
319
320impl Laid {
321    /// The layout trees of a scene, not yet laid out.
322    pub(super) fn build(_r: &mut Renderer, scene: &Scene) -> Laid {
323        let mut top = TaffyTree::new();
324        // Only the boxes read are rounded, by `placed`, as taffy would round
325        // them all.
326        top.disable_rounding();
327        let mut l = Laid {
328            top: TaffyTree::new(),
329            root: NodeId::from(0u64),
330            runs: Runs::default(),
331            nodes: BTreeMap::new(),
332            run_of: BTreeMap::new(),
333            sens: BTreeMap::new(),
334        };
335        l.sens_build(&scene.root, Vec::new());
336        let root = l.build_node(
337            &mut top,
338            Owner::Top,
339            None,
340            &scene.root,
341            None,
342            &scene.images,
343            Vec::new(),
344        );
345        l.top = top;
346        l.root = root;
347        l
348    }
349
350    /// The layout tree `owner` names.
351    pub(super) fn tree(&self, owner: Owner) -> &TaffyTree<Option<Leaf>> {
352        match owner {
353            Owner::Top => &self.top,
354            Owner::Run(id) => &self.runs.get(id).tree,
355        }
356    }
357
358    /// The layout tree `owner` names, to change.
359    pub(super) fn tree_mut(&mut self, owner: Owner) -> &mut TaffyTree<Option<Leaf>> {
360        match owner {
361            Owner::Top => &mut self.top,
362            Owner::Run(id) => &mut self.runs.get_mut(id).tree,
363        }
364    }
365
366    /// The layout tree of `node` — at `order`, in `tree`, which is `owner`'s
367    /// and, in a run's tree, inside that run's child `inside` — and
368    /// everything under it.
369    #[allow(clippy::too_many_arguments)]
370    pub(super) fn build_node(
371        &mut self,
372        tree: &mut TaffyTree<Option<Leaf>>,
373        owner: Owner,
374        inside: Option<OrderKey>,
375        node: &Node,
376        parent: Option<&Node>,
377        images: &ImageFiles,
378        order: Order,
379    ) -> NodeId {
380        let style = style_of(node, parent);
381        if let Some(leaf) = leaf_of(node, images) {
382            let id = tree.new_leaf_with_context(style, Some(leaf)).expect("leaf");
383            self.nodes.insert(order, (owner, id));
384            return id;
385        }
386        if is_run(node) {
387            let rid = self.runs.reserve();
388            // Its padding stays in its style: what a box is given is never
389            // less than its padding, and taffy floors it there — but a frame
390            // with no layout sizes itself, as taffy sizes such a frame.
391            let leaf = tree
392                .new_leaf_with_context(style, Some(Leaf::Run(rid)))
393                .expect("leaf");
394            let mut run = RunLayout::new(node, order.clone(), owner, leaf, inside);
395            run.hug = hugs_by_extent(node, parent).unwrap_or((false, false));
396            for (k, c) in node.children.entries() {
397                self.add_child(&mut run, rid, k, c, node, images, &order);
398            }
399            self.runs.put(rid, run);
400            self.run_of.insert(order.clone(), rid);
401            self.nodes.insert(order, (owner, leaf));
402            return leaf;
403        }
404        // A frame with no children: a box of its own size.
405        let id = tree.new_leaf(style).expect("leaf");
406        self.nodes.insert(order, (owner, id));
407        id
408    }
409
410    /// Builds `child`, at key `k` under the run `node` — `run`, in slot
411    /// `rid`, at `order` — into the run's tree as a child of it.
412    #[allow(clippy::too_many_arguments)]
413    pub(super) fn add_child(
414        &mut self,
415        run: &mut RunLayout,
416        rid: u32,
417        k: &OrderKey,
418        child: &Node,
419        node: &Node,
420        images: &ImageFiles,
421        order: &Order,
422    ) {
423        let mut o = order.clone();
424        o.push(k.clone());
425        let mut tree = std::mem::replace(&mut run.tree, TaffyTree::new());
426        let id = self.build_node(
427            &mut tree,
428            Owner::Run(rid),
429            Some(k.clone()),
430            child,
431            Some(node),
432            images,
433            o,
434        );
435        run.tree = tree;
436        let (along, across) = if run.row {
437            (child.width, child.height)
438        } else {
439            (child.height, child.width)
440        };
441        let mut o = order.clone();
442        o.push(k.clone());
443        let sens = self.sensitive(&o);
444        run.add(k.clone(), id, across == DSize::Fill, sens);
445        if along == DSize::Fill {
446            run.add_fill(k.clone(), style_of(child, Some(node)));
447        }
448    }
449
450    /// Lays the drawing's own tree out, and every run in it that changed.
451    pub(super) fn settle_top(&mut self, r: &mut Renderer) {
452        let root = self.root;
453        r.settle_in(&mut self.runs, &mut self.top, root, Size::MAX_CONTENT, &[]);
454    }
455
456    /// Where the run at `order` places each child: the run's laid-out sizes
457    /// for its final breadth, where the first child starts along it, and
458    /// how far apart its children are — its gap, and the free room
459    /// `"space-between"` spreads between them.
460    pub(super) fn run_places(
461        &self,
462        rid: u32,
463        size: Size<f32>,
464    ) -> Option<(&RunLayout, &Asked, f32, f64)> {
465        let run = self.runs.get(rid);
466        let (pa0, pa1) = run.padding_along();
467        let (pc0, pc1) = run.padding_across();
468        let (along, across) = if run.row {
469            (size.width, size.height)
470        } else {
471            (size.height, size.width)
472        };
473        let line = (across - pc0 - pc1).max(0.0);
474        let asked = run.placed(line)?;
475        let free = along - pa0 - pa1 - run.length(asked) as f32;
476        let n = run.children.len();
477        let spread = if run.justify == Align::SpaceBetween && free > 1e-3 && n > 1 {
478            free as f64 / (n - 1) as f64
479        } else {
480            0.0
481        };
482        Some((run, asked, pa0 + run.lead(free), run.gap as f64 + spread))
483    }
484
485    /// Every node's box, by order, in the design's coordinates.
486    pub(super) fn frames(&mut self, r: &mut Renderer, root: &Node) -> BTreeMap<Order, Frame> {
487        let mut out = BTreeMap::new();
488        let top = self.root;
489        self.frames_of(
490            r,
491            root,
492            Vec::new(),
493            Owner::Top,
494            top,
495            Place::default(),
496            true,
497            &mut out,
498        );
499        out
500    }
501
502    /// Puts the box of `node`, at `order` and laid out as `id` in `owner`'s
503    /// tree, into `out`, placed from `parent`, then its children's, a run's at
504    /// its places.
505    #[allow(clippy::too_many_arguments)]
506    fn frames_of(
507        &mut self,
508        r: &mut Renderer,
509        node: &Node,
510        order: Order,
511        owner: Owner,
512        id: NodeId,
513        parent: Place,
514        root: bool,
515        out: &mut BTreeMap<Order, Frame>,
516    ) {
517        let tree = self.tree(owner);
518        let (frame, place) = placed(tree, id, parent, root);
519        out.insert(order.clone(), frame);
520        if let Some(&rid) = self.run_of.get(&order)
521            && self.runs.get(rid).free
522        {
523            // Each child at its own place in the frame, measured from it.
524            for (k, c) in node.children.entries() {
525                r.relay_free(&mut self.runs, rid, k);
526                let node_id = self.runs.get(rid).children[k].node;
527                let mut o = order.clone();
528                o.push(k.clone());
529                self.frames_of(r, c, o, Owner::Run(rid), node_id, place, false, out);
530            }
531            return;
532        }
533        if let Some(&rid) = self.run_of.get(&order) {
534            let size = tree.unrounded_layout(id).size;
535            let mut before = 0.0f64;
536            for (k, c) in node.children.entries() {
537                let Some((run, asked, lead, step)) = self.run_places(rid, size) else {
538                    return;
539                };
540                let line = asked.line;
541                let Some(s) = run.size_of(asked, k) else {
542                    continue;
543                };
544                let (pc0, _) = run.padding_across();
545                let stretch = run.children[k].stretch;
546                let across = pc0 + run.across(line, &s, stretch);
547                let item = child_place(place, run.row, lead as f64 + before, across as f64);
548                let node_id = run.children[k].node;
549                r.relay(&mut self.runs, rid, k, line);
550                let mut o = order.clone();
551                o.push(k.clone());
552                self.frames_of(r, c, o, Owner::Run(rid), node_id, item, false, out);
553                before += s.along as f64 + step;
554            }
555            return;
556        }
557        let kids = tree.children(id).unwrap_or_default();
558        for ((k, c), &child) in node.children.entries().zip(&kids) {
559            let mut o = order.clone();
560            o.push(k.clone());
561            self.frames_of(r, c, o, owner, child, place, false, out);
562        }
563    }
564}
565
566/// The place a run's child is laid out from: `along` and `across` from the
567/// run's node's unrounded top-left, rounded as taffy rounds a box in the
568/// flow — measured from the run's node — so that the child, at the origin of
569/// its own one-item tree, gets exactly the box taffy would give it.
570pub(super) fn child_place(run: Place, row: bool, along: f64, across: f64) -> Place {
571    // In single precision, as taffy places a box and its rounding pass
572    // rounds it: the child's place within the run, then the run's.
573    let (along, across) = (along as f32, across as f32);
574    let (dx, dy) = if row {
575        (along, across)
576    } else {
577        (across, along)
578    };
579    let raw = (run.raw.0 + dx, run.raw.1 + dy);
580    let at = (
581        run.at.0 + snap(raw.0) - snap(run.raw.0),
582        run.at.1 + snap(raw.1) - snap(run.raw.1),
583    );
584    Place { at, raw }
585}
586
587/// The layout tree of `node` and everything under it as one taffy tree,
588/// no run laid out by its own: what taffy alone makes of a scene, for the
589/// tests to hold the drawing's layout to.
590#[cfg(test)]
591pub(super) fn build_plain(
592    tree: &mut TaffyTree<Option<Leaf>>,
593    node: &Node,
594    parent: Option<&Node>,
595    hugs: &mut Vec<(NodeId, bool, bool)>,
596    images: &ImageFiles,
597) -> NodeId {
598    let style = style_of(node, parent);
599    if let Some(leaf) = leaf_of(node, images) {
600        return tree.new_leaf_with_context(style, Some(leaf)).expect("leaf");
601    }
602    let children: Vec<NodeId> = node
603        .children
604        .iter()
605        .map(|c| build_plain(tree, c, Some(node), hugs, images))
606        .collect();
607    let id = tree.new_with_children(style, &children).expect("node");
608    if let Some((w, h)) = hugs_by_extent(node, parent) {
609        hugs.push((id, w, h));
610    }
611    id
612}
613
614/// Whether `node`, laid out in a plain taffy tree, hugs its children's
615/// extent — a frame with no layout — and along which axes.
616pub(super) fn hugs_by_extent(node: &Node, parent: Option<&Node>) -> Option<(bool, bool)> {
617    if leafy(node) {
618        return None;
619    }
620    // A root has no parent space to fill: on its own, `"fill"` hugs.
621    let hugs_by = |s: DSize| s == DSize::Hug || (parent.is_none() && s == DSize::Fill);
622    let (w, h) = (hugs_by(node.width), hugs_by(node.height));
623    (node.layout == Layout::None && !node.children.is_empty() && (w || h)).then_some((w, h))
624}
625
626/// Whether `node` is a leaf of the layout tree: a text, a vector or an image.
627pub(super) fn leafy(node: &Node) -> bool {
628    node.text.is_some() || node.vector.is_some() || node.image.is_some()
629}
630
631/// What a leaf of the layout tree measures by, for a node that is one.
632pub(super) fn leaf_of(node: &Node, images: &ImageFiles) -> Option<Leaf> {
633    if let Some(text) = &node.text {
634        let wraps = !matches!(node.width, DSize::Hug);
635        return Some(Leaf::Text(Box::new(text.clone()), wraps));
636    }
637    let intrinsic = match (&node.vector, &node.image) {
638        (Some(v), _) => Some((v.view_box[2], v.view_box[3])),
639        (_, Some(i)) => images.get(&i.id).map(|f| (f.width as f32, f.height as f32)),
640        _ => None,
641    };
642    intrinsic.map(|(w, h)| Leaf::Intrinsic(w, h))
643}
644
645/// A node's flexbox style, which its parent's layout decides part of.
646pub(super) fn style_of(node: &Node, parent: Option<&Node>) -> Style {
647    let mut style = Style::default();
648    let dir = parent.map(|p| p.layout);
649    let dim = |s: DSize| match s {
650        DSize::Px(v) => Dimension::length(v),
651        _ => Dimension::auto(),
652    };
653    style.size = Size {
654        width: dim(node.width),
655        height: dim(node.height),
656    };
657    let (main, cross) = match dir {
658        Some(Layout::Row) => (node.width, node.height),
659        Some(Layout::Column) => (node.height, node.width),
660        _ => (DSize::Hug, DSize::Hug),
661    };
662    if main == DSize::Fill {
663        style.flex_grow = 1.0;
664        style.flex_basis = Dimension::length(0.0);
665    }
666    if cross == DSize::Fill {
667        style.align_self = Some(AlignSelf::STRETCH);
668    }
669    // Every frame is the containing block of the boxes placed absolutely in
670    // it, as in Figma: a child at `x` and `y` is placed, sized and rounded
671    // against its own parent, never a farther ancestor.
672    style.position = Position::Relative;
673    if dir == Some(Layout::None) {
674        style.position = Position::Absolute;
675        style.inset = taffy::Rect {
676            left: LengthPercentageAuto::length(node.x),
677            top: LengthPercentageAuto::length(node.y),
678            right: LengthPercentageAuto::auto(),
679            bottom: LengthPercentageAuto::auto(),
680        };
681    }
682    style.flex_shrink = 0.0;
683    // A frame with no layout is never smaller than its padding, along
684    // either axis — as every other box is, and as taffy floors a leaf.
685    if node.layout == Layout::None && !leafy(node) {
686        let [t, r, b, l] = node.padding;
687        style.min_size = Size {
688            width: LengthPercentageAuto::length(l + r),
689            height: LengthPercentageAuto::length(t + b),
690        };
691    }
692    match node.layout {
693        Layout::Row => style.flex_direction = FlexDirection::Row,
694        Layout::Column => style.flex_direction = FlexDirection::Column,
695        Layout::None => {}
696    }
697    style.gap = Size {
698        width: LengthPercentage::length(node.gap),
699        height: LengthPercentage::length(node.gap),
700    };
701    let [t, r, b, l] = node.padding;
702    style.padding = taffy::Rect {
703        top: LengthPercentage::length(t),
704        right: LengthPercentage::length(r),
705        bottom: LengthPercentage::length(b),
706        left: LengthPercentage::length(l),
707    };
708    style.align_items = match node.align {
709        Align::Center => AlignItems::CENTER,
710        Align::End => AlignItems::FLEX_END,
711        _ => AlignItems::FLEX_START,
712    };
713    style.justify_content = match node.justify {
714        Align::Center => JustifyContent::CENTER,
715        Align::End => JustifyContent::FLEX_END,
716        Align::SpaceBetween => JustifyContent::SPACE_BETWEEN,
717        Align::Start => JustifyContent::FLEX_START,
718    };
719    style
720}
721
722#[cfg(test)]
723mod tests;
724
725/// Rounds to the nearest whole pixel, a half up, as taffy rounds.
726pub(super) fn snap(v: f32) -> f32 {
727    (v + 0.5).floor()
728}
729
730/// Where a node's parent is, for placing the node: the parent's box's
731/// top-left in whole pixels, and its unrounded one, which taffy's rounding
732/// pass measures the node from — every frame is the containing block of the
733/// boxes placed absolutely in it, so a box is always measured from its
734/// parent.
735#[derive(Clone, Copy, Debug, Default)]
736pub(super) struct Place {
737    /// The parent's top-left in whole pixels.
738    pub(super) at: (f32, f32),
739    /// The parent's unrounded top-left, which the node is measured from.
740    pub(super) raw: (f32, f32),
741}
742
743/// A node's box in whole pixels, in the design's coordinates, and the place
744/// its children are measured from — given its parent's. The tree is laid
745/// out unrounded, and only the boxes read are rounded, exactly as taffy's
746/// own pass rounds every box: each edge at its unrounded place measured from
747/// its parent — so the boxes are the very ones a tree rounded whole has.
748pub(super) fn placed(
749    tree: &TaffyTree<Option<Leaf>>,
750    id: NodeId,
751    parent: Place,
752    _root: bool,
753) -> (Frame, Place) {
754    let l = tree.unrounded_layout(id);
755    let base = parent.raw;
756    let (x, y) = (base.0 + l.location.x, base.1 + l.location.y);
757    let frame = Frame {
758        x: parent.at.0 + snap(x) - snap(base.0),
759        y: parent.at.1 + snap(y) - snap(base.1),
760        width: snap(x + l.size.width) - snap(x),
761        height: snap(y + l.size.height) - snap(y),
762    };
763    let place = Place {
764        at: (frame.x, frame.y),
765        raw: (x, y),
766    };
767    (frame, place)
768}