Skip to main content

gpui/
taffy.rs

1mod layout_bounds;
2mod retained;
3pub use retained::VnRetainedLayoutStats;
4
5use layout_bounds::LayoutIdMap;
6
7use crate::{
8    AbsoluteLength, App, Bounds, DefiniteLength, Display, Edges, GridTemplate, Length, Pixels,
9    Point, Size, Style, Window, size,
10    util::{
11        ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel,
12        round_to_device_pixel,
13    },
14};
15use collections::{FxHashMap, FxHashSet};
16use std::{fmt::Debug, ops::Range};
17use taffy::{
18    TaffyTree, TraversePartialTree as _,
19    geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
20    prelude::{max_content, min_content},
21    style::AvailableSpace as TaffyAvailableSpace,
22    tree::NodeId,
23};
24
25#[cfg(feature = "stacker")]
26type StackSafe<T> = stacksafe::StackSafe<T>;
27#[cfg(not(feature = "stacker"))]
28type StackSafe<T> = T;
29
30type MeasureFn =
31    dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>;
32type NodeMeasureFn = StackSafe<Box<MeasureFn>>;
33
34struct NodeContext {
35    measure: NodeMeasureFn,
36}
37pub struct TaffyLayoutEngine {
38    taffy: TaffyTree<NodeContext>,
39    absolute_layout_bounds: LayoutIdMap<Bounds<Pixels>>,
40    /// Unrounded absolute border-box top-left per-node coordinate in device pixels.
41    absolute_outer_origins: LayoutIdMap<Point<f32>>,
42    retention: retained::Retention,
43    computed_layouts: FxHashSet<LayoutId>,
44    layout_bounds_scratch_space: Vec<LayoutId>,
45    /// This frame's nonzero `vn_order`s, by node.
46    orders: FxHashMap<LayoutId, i32>,
47    calc_sizes: Vec<CalcSizeNode>,
48}
49
50const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
51
52impl TaffyLayoutEngine {
53    pub fn new() -> Self {
54        let mut taffy = TaffyTree::new();
55        taffy.disable_rounding();
56        TaffyLayoutEngine {
57            taffy,
58            absolute_layout_bounds: LayoutIdMap::default(),
59            absolute_outer_origins: LayoutIdMap::default(),
60            retention: retained::Retention::default(),
61            computed_layouts: FxHashSet::default(),
62            layout_bounds_scratch_space: Vec::new(),
63            orders: FxHashMap::default(),
64            calc_sizes: Vec::new(),
65        }
66    }
67
68    pub fn clear(&mut self) {
69        if self.retention.enabled {
70            retained::finish_frame(self);
71        } else {
72            self.taffy.clear();
73        }
74        self.absolute_layout_bounds.clear();
75        self.absolute_outer_origins.clear();
76        self.computed_layouts.clear();
77        self.orders.clear();
78        self.calc_sizes.clear();
79    }
80
81    pub(crate) fn retention_enabled(&self) -> bool {
82        self.retention.enabled
83    }
84
85    pub(crate) fn enable_retention(&mut self) {
86        if !self.retention.enabled {
87            assert_eq!(
88                self.taffy.total_node_count(),
89                0,
90                "enable retained layout before the first layout request"
91            );
92            self.retention.enabled = true;
93        }
94    }
95
96    pub(crate) fn profile_retention(&mut self, enabled: bool) {
97        self.retention.stats = enabled.then(Default::default);
98    }
99
100    pub(crate) fn take_retention_stats(&mut self) -> Option<VnRetainedLayoutStats> {
101        self.retention.stats.as_mut().map(std::mem::take)
102    }
103
104    pub fn request_layout(
105        &mut self,
106        style: Style,
107        rem_size: Pixels,
108        scale_factor: f32,
109        children: &[LayoutId],
110    ) -> LayoutId {
111        self.request_layout_in_scope(None, style, rem_size, scale_factor, children)
112    }
113
114    pub(crate) fn request_layout_in_scope(
115        &mut self,
116        scope: Option<crate::GlobalElementId>,
117        style: Style,
118        rem_size: Pixels,
119        scale_factor: f32,
120        children: &[LayoutId],
121    ) -> LayoutId {
122        let taffy_style = style.to_taffy(rem_size, scale_factor);
123        let reordered = self.order_modified(&style, children);
124        let children = reordered.as_deref().unwrap_or(children);
125        let id = if self.retention.enabled {
126            retained::request_layout(self, scope, taffy_style, children)
127        } else if children.is_empty() {
128            self.taffy
129                .new_leaf(taffy_style)
130                .expect(EXPECT_MESSAGE)
131                .into()
132        } else {
133            self.taffy
134                // This is safe because LayoutId is repr(transparent) to taffy::tree::NodeId.
135                .new_with_children(taffy_style, LayoutId::to_taffy_slice(children))
136                .expect(EXPECT_MESSAGE)
137                .into()
138        };
139        self.note_order(id, &style);
140        id
141    }
142
143    fn note_order(&mut self, id: LayoutId, style: &Style) {
144        if style.vn_order != 0 {
145            self.orders.insert(id, style.vn_order);
146        }
147        if let Some(node) = CalcSizeNode::of(id, style) {
148            self.calc_sizes.push(node);
149        }
150    }
151
152    /// CSS's order-modified document order for a flex or grid container's children; `None` when
153    /// it is document order.
154    fn order_modified(&self, style: &Style, children: &[LayoutId]) -> Option<Vec<LayoutId>> {
155        if self.orders.is_empty() || !matches!(style.display, Display::Flex | Display::Grid) {
156            return None;
157        }
158        let order = |id: &LayoutId| self.orders.get(id).copied().unwrap_or(0);
159        if children.windows(2).all(|w| order(&w[0]) <= order(&w[1])) {
160            return None;
161        }
162        let mut sorted = children.to_vec();
163        sorted.sort_by_key(order);
164        Some(sorted)
165    }
166
167    pub fn request_measured_layout(
168        &mut self,
169        style: Style,
170        rem_size: Pixels,
171        scale_factor: f32,
172        measure: impl FnMut(
173            Size<Option<Pixels>>,
174            Size<AvailableSpace>,
175            &mut Window,
176            &mut App,
177        ) -> Size<Pixels>
178        + 'static,
179    ) -> LayoutId {
180        self.request_measured_layout_in_scope(None, style, rem_size, scale_factor, measure)
181    }
182
183    pub(crate) fn request_measured_layout_in_scope(
184        &mut self,
185        scope: Option<crate::GlobalElementId>,
186        style: Style,
187        rem_size: Pixels,
188        scale_factor: f32,
189        measure: impl FnMut(
190            Size<Option<Pixels>>,
191            Size<AvailableSpace>,
192            &mut Window,
193            &mut App,
194        ) -> Size<Pixels>
195        + 'static,
196    ) -> LayoutId {
197        let taffy_style = style.to_taffy(rem_size, scale_factor);
198        let id = if self.retention.enabled {
199            retained::request_measured_layout(self, scope, taffy_style, measure)
200        } else {
201            let measure = Box::new(measure) as Box<MeasureFn>;
202            #[cfg(feature = "stacker")]
203            let measure = StackSafe::new(measure);
204
205            self.taffy
206                .new_leaf_with_context(taffy_style, NodeContext { measure })
207                .expect(EXPECT_MESSAGE)
208                .into()
209        };
210        self.note_order(id, &style);
211        id
212    }
213
214    /// Treats any `auto` dimension of the given node's style as filling `size`.
215    ///
216    /// This is applied to window roots before layout so they behave like the
217    /// root element on the web, which stretches to fill the initial containing
218    /// block (the viewport) unless given an explicit size. Explicitly styled
219    /// dimensions are preserved.
220    pub fn stretch_auto_size_to_fill(
221        &mut self,
222        id: LayoutId,
223        size: Size<Pixels>,
224        scale_factor: f32,
225    ) {
226        if self.retention.enabled {
227            retained::stretch(self, id, size, scale_factor);
228            return;
229        }
230        let style = self.taffy.style(id.0).expect(EXPECT_MESSAGE);
231        let stretch_width = style.size.width.is_auto();
232        let stretch_height = style.size.height.is_auto();
233        if !stretch_width && !stretch_height {
234            return;
235        }
236        let mut style = style.clone();
237        if stretch_width {
238            style.size.width =
239                taffy::style::Dimension::length(round_to_device_pixel(size.width.0, scale_factor));
240        }
241        if stretch_height {
242            style.size.height =
243                taffy::style::Dimension::length(round_to_device_pixel(size.height.0, scale_factor));
244        }
245        self.taffy.set_style(id.0, style).expect(EXPECT_MESSAGE);
246    }
247
248    // Used to understand performance
249    #[allow(dead_code)]
250    fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
251        let mut count = 0;
252
253        for child in self.taffy.children(parent.0)? {
254            // Count this child.
255            count += 1;
256
257            // Count all of this child's children.
258            count += self.count_all_children(LayoutId(child))?
259        }
260
261        Ok(count)
262    }
263
264    // Used to understand performance
265    #[allow(dead_code)]
266    fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
267        println!(
268            "{parent:?} at depth {depth} has {} children",
269            self.taffy.child_count(parent.0)
270        );
271
272        let mut max_child_depth = 0;
273
274        for child in self.taffy.children(parent.0)? {
275            max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
276        }
277
278        Ok(depth + 1 + max_child_depth)
279    }
280
281    // Used to understand performance
282    #[allow(dead_code)]
283    fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
284        let mut edges = Vec::new();
285
286        for child in self.taffy.children(parent.0)? {
287            edges.push((parent, LayoutId(child)));
288
289            edges.extend(self.get_edges(LayoutId(child))?);
290        }
291
292        Ok(edges)
293    }
294
295    /// vue-native fork: `id` is laid out as a root, so it has no parent.
296    ///
297    /// A retained node keeps the Taffy parent it had last frame until that
298    /// parent is requested again with other children, or freed, and an
299    /// unrequested one is only freed when the frame ends. A node that was a
300    /// child and is a root this frame would be placed at the stale parent's
301    /// origin by [`Self::layout_bounds`].
302    pub(crate) fn detach_root(&mut self, id: LayoutId) {
303        if let Some(parent) = self.taffy.parent(id.0) {
304            self.taffy.remove_child(parent, id.0).expect(EXPECT_MESSAGE);
305        }
306    }
307
308    #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
309    pub fn compute_layout(
310        &mut self,
311        id: LayoutId,
312        available_space: Size<AvailableSpace>,
313        window: &mut Window,
314        cx: &mut App,
315    ) {
316        // Leaving this here until we have a better instrumentation approach.
317        // println!("Laying out {} children", self.count_all_children(id)?);
318        // println!("Max layout depth: {}", self.max_depth(0, id)?);
319
320        // Output the edges (branches) of the tree in Mermaid format for visualization.
321        // println!("Edges:");
322        // for (a, b) in self.get_edges(id)? {
323        //     println!("N{} --> N{}", u64::from(a), u64::from(b));
324        // }
325        //
326
327        if self.retention.enabled {
328            self.detach_root(id);
329        }
330
331        if !self.computed_layouts.insert(id) {
332            let stack = &mut self.layout_bounds_scratch_space;
333            stack.push(id);
334            while let Some(id) = stack.pop() {
335                self.absolute_layout_bounds.remove(&id);
336                self.absolute_outer_origins.remove(&id);
337                stack.extend(
338                    self.taffy
339                        .children(id.into())
340                        .expect(EXPECT_MESSAGE)
341                        .into_iter()
342                        .map(LayoutId::from),
343                );
344            }
345        }
346
347        let scale_factor = window.scale_factor();
348
349        let transform = |v: AvailableSpace| match v {
350            AvailableSpace::Definite(pixels) => {
351                AvailableSpace::Definite(Pixels(pixels.0 * scale_factor))
352            }
353            AvailableSpace::MinContent => AvailableSpace::MinContent,
354            AvailableSpace::MaxContent => AvailableSpace::MaxContent,
355        };
356        let available_space = size(
357            transform(available_space.width),
358            transform(available_space.height),
359        );
360
361        if self.retention.enabled {
362            retained::prepare_compute(self, scale_factor);
363            retained::replay(self, window, cx);
364        }
365        let calc_sizes = self.take_calc_sizes(id);
366        if !calc_sizes.is_empty() {
367            let requested = self.probe_calc_sizes(&calc_sizes);
368            self.run_taffy(id, available_space, scale_factor, window, cx);
369            let rem_size = window.rem_size();
370            self.resolve_calc_sizes(&calc_sizes, requested, rem_size, scale_factor);
371        }
372        self.run_taffy(id, available_space, scale_factor, window, cx);
373        if self.retention.enabled {
374            retained::settle(self, window, cx);
375        }
376    }
377
378    fn run_taffy(
379        &mut self,
380        id: LayoutId,
381        available_space: Size<AvailableSpace>,
382        scale_factor: f32,
383        window: &mut Window,
384        cx: &mut App,
385    ) {
386        let retention = &mut self.retention;
387        self.taffy
388            .compute_layout_with_measure(
389                id.into(),
390                available_space.into(),
391                |input, id, node_context, style| {
392                    taffy::compute_leaf_layout(
393                        input,
394                        style,
395                        // vue-native fork: a leaf's padding, border and size
396                        // can be a `DefiniteLength::Calc` too (taffy 0.15 asks
397                        // the caller to resolve them here, not the tree).
398                        resolve_calc_handle,
399                        |known_dimensions, available_space| {
400                            let Some(node_context) = node_context else {
401                                return taffy::geometry::Size::default();
402                            };
403
404                            let known_dimensions = Size {
405                                width: known_dimensions.width.map(|e| Pixels(e / scale_factor)),
406                                height: known_dimensions.height.map(|e| Pixels(e / scale_factor)),
407                            };
408
409                            let available_space: Size<AvailableSpace> = available_space.into();
410                            let untransform = |ev: AvailableSpace| match ev {
411                                AvailableSpace::Definite(pixels) => {
412                                    AvailableSpace::Definite(Pixels(pixels.0 / scale_factor))
413                                }
414                                AvailableSpace::MinContent => AvailableSpace::MinContent,
415                                AvailableSpace::MaxContent => AvailableSpace::MaxContent,
416                            };
417                            let available_space = size(
418                                untransform(available_space.width),
419                                untransform(available_space.height),
420                            );
421
422                            if retention.enabled {
423                                retained::note_measure(
424                                    retention,
425                                    id,
426                                    known_dimensions,
427                                    available_space,
428                                );
429                            }
430                            let measured_size: Size<Pixels> = (node_context.measure)(
431                                known_dimensions,
432                                available_space,
433                                window,
434                                cx,
435                            );
436                            snap_measured_size_to_device_pixels(measured_size, scale_factor).into()
437                        },
438                    )
439                },
440            )
441            .expect(EXPECT_MESSAGE);
442    }
443
444    /// vue-native fork: the `calc-size()` nodes under `root`; the others wait for their own root.
445    fn take_calc_sizes(&mut self, root: LayoutId) -> Vec<CalcSizeNode> {
446        if self.calc_sizes.is_empty() {
447            return Vec::new();
448        }
449        let taffy = &self.taffy;
450        let under = |mut node: NodeId| loop {
451            if node == root.0 {
452                return true;
453            }
454            match taffy.parent(node) {
455                Some(parent) => node = parent,
456                None => return false,
457            }
458        };
459        let (mine, rest) = std::mem::take(&mut self.calc_sizes)
460            .into_iter()
461            .partition(|n| under(n.id.0));
462        self.calc_sizes = rest;
463        mine
464    }
465
466    /// The first pass lays each `calc-size()` axis out at its basis keyword, unclamped and (for a
467    /// flex basis) unflexed, so the box's size there is the basis's `size`. Returns the styles
468    /// as requested.
469    fn probe_calc_sizes(&mut self, nodes: &[CalcSizeNode]) -> Vec<taffy::style::Style> {
470        nodes
471            .iter()
472            .map(|node| {
473                let requested = self.taffy.style(node.id.0).expect(EXPECT_MESSAGE).clone();
474                let mut probe = requested.clone();
475                for (axis, props) in [(0, &node.width), (1, &node.height)] {
476                    let Some(first) = props.iter().flatten().next() else {
477                        continue;
478                    };
479                    let size = basis_dimension(first.basis);
480                    let none = taffy::style::LengthPercentageAuto::auto();
481                    if axis == 0 {
482                        probe.size.width = size;
483                        probe.min_size.width = none;
484                        probe.max_size.width = none;
485                    } else {
486                        probe.size.height = size;
487                        probe.min_size.height = none;
488                        probe.max_size.height = none;
489                    }
490                }
491                if let (Some(basis), Some(_)) = (node.flex_basis, self.main_axis(node.id)) {
492                    probe.flex_basis = basis_dimension(basis.basis);
493                    probe.flex_grow = 0.;
494                    probe.flex_shrink = 0.;
495                }
496                if probe != requested {
497                    self.taffy.set_style(node.id.0, probe).expect(EXPECT_MESSAGE);
498                }
499                requested
500            })
501            .collect()
502    }
503
504    /// The second pass's styles: each `calc-size()` as the length its function gives for the
505    /// measured basis, in the box-sizing box.
506    fn resolve_calc_sizes(
507        &mut self,
508        nodes: &[CalcSizeNode],
509        requested: Vec<taffy::style::Style>,
510        rem_size: Pixels,
511        scale_factor: f32,
512    ) {
513        for (node, mut style) in nodes.iter().zip(requested) {
514            let layout = *self.taffy.layout(node.id.0).expect(EXPECT_MESSAGE);
515            let content_box = style.box_sizing == taffy::style::BoxSizing::ContentBox;
516            let inner = |outer: f32, a: f32, b: f32, c: f32, d: f32| {
517                if content_box {
518                    (outer - a - b - c - d).max(0.)
519                } else {
520                    outer
521                }
522            };
523            let measured = [
524                inner(
525                    layout.size.width,
526                    layout.padding.left,
527                    layout.padding.right,
528                    layout.border.left,
529                    layout.border.right,
530                ),
531                inner(
532                    layout.size.height,
533                    layout.padding.top,
534                    layout.padding.bottom,
535                    layout.border.top,
536                    layout.border.bottom,
537                ),
538            ];
539            let resolve = |c: &crate::VnCalcSize, axis: usize| {
540                calc_size_value(c, measured[axis] / scale_factor, rem_size, scale_factor)
541            };
542            let dimension = |v: Result<*const (), f32>| match v {
543                Ok(handle) => taffy::style::Dimension::calc(handle),
544                Err(length) => taffy::style::Dimension::length(length),
545            };
546            let bound = |v: Result<*const (), f32>| match v {
547                Ok(handle) => taffy::style::LengthPercentageAuto::calc(handle),
548                Err(length) => taffy::style::LengthPercentageAuto::length(length),
549            };
550            for axis in 0..2 {
551                let [size, min, max] = if axis == 0 { node.width } else { node.height };
552                let (s, lo, hi) = if axis == 0 {
553                    (
554                        &mut style.size.width,
555                        &mut style.min_size.width,
556                        &mut style.max_size.width,
557                    )
558                } else {
559                    (
560                        &mut style.size.height,
561                        &mut style.min_size.height,
562                        &mut style.max_size.height,
563                    )
564                };
565                if let Some(c) = size {
566                    *s = dimension(resolve(&c, axis));
567                }
568                if let Some(c) = min {
569                    *lo = bound(resolve(&c, axis));
570                }
571                if let Some(c) = max {
572                    *hi = bound(resolve(&c, axis));
573                }
574            }
575            if let (Some(c), Some(axis)) = (node.flex_basis, self.main_axis(node.id)) {
576                style.flex_basis = dimension(resolve(&c, axis));
577            }
578            if self.taffy.style(node.id.0).expect(EXPECT_MESSAGE) != &style {
579                self.taffy.set_style(node.id.0, style).expect(EXPECT_MESSAGE);
580            }
581        }
582    }
583
584    /// The flex container's main axis for `id`, 0 for rows and 1 for columns.
585    fn main_axis(&self, id: LayoutId) -> Option<usize> {
586        let parent = self.taffy.parent(id.0)?;
587        let style = self.taffy.style(parent).ok()?;
588        use taffy::style::FlexDirection as F;
589        (style.display == taffy::style::Display::Flex).then(|| match style.flex_direction {
590            F::Row | F::RowReverse => 0,
591            F::Column | F::ColumnReverse => 1,
592        })
593    }
594
595    // Pixel snapping
596    //
597    // Painting primitives at non-integer pixel coordinates produces blurry
598    // output. Pixel snapping converts layout coordinates into integer
599    // device-pixel coordinates so painted edges land exactly on physical
600    // pixel boundaries.
601    //
602    // Non-integer coordinates can arise for several reasons, including:
603    //   - flex distribution, percentages, centering, and text measurement
604    //     can produce fractional element sizes and positions;
605    //   - at fractional scale factors (for example 125% or 150%), integer
606    //     logical-pixel values can map to non-integer device-pixel values.
607    //
608    // We pixel-snap by rounding in device-pixel space, after multiplying
609    // by `scale_factor`, so that snapping targets physical pixels. Bounds
610    // are divided by `scale_factor` before being returned to GPUI.
611    //
612    // Midpoints are rounded toward zero. This is a stylistic choice: a
613    // 1-logical-pixel line at 150% scale should render as 1 dp rather than
614    // 2 dp.
615    //
616    // Pixel snapping is done in two phases:
617    //
618    //  1. Pre-layout metric snapping. Before Taffy computes layout, all
619    //     authored absolute lengths are rounded in `to_taffy`. This
620    //     includes borders, padding, gaps, and explicit sizes.
621    //     Custom-measured leaf nodes have their measured sizes rounded up
622    //     to integer device-pixel lengths.
623    //
624    //  2. Post-layout edge snapping. After Taffy resolves the tree, layout
625    //     relationships such as flex shares, grid tracks, percentages, and
626    //     centering can produce new fractional edge positions. Boxes now
627    //     have edges in absolute coordinates, and snapping must decide
628    //     where those edges land on the device-pixel grid.
629    //
630    // Ideally, post-layout snapping would satisfy:
631    //
632    //  - Edge closure. Two raw layout edges at the same absolute position
633    //    should snap to the same pixel column.
634    //  - Translation stability. A component's internal geometry should not
635    //    change when it moves to a new absolute position.
636    //
637    // These goals are in tension because rounding is not associative.
638    // The simple local schemes make different tradeoffs:
639    //
640    //  - Absolute edge rounding gives each window coordinate one answer,
641    //    so coincident edges always close globally. But a span's snapped
642    //    length is `round(far) - round(near)`, which may change by 1 dp
643    //    as its absolute origin moves.
644    //
645    //  - Parent-relative edge rounding rounds each child inside its
646    //    parent's coordinate space. This guarantees translation stability,
647    //    but a shared edge reached through different parents can
648    //    accumulate different rounding, causing non-closure between
649    //    cousins.
650    //
651    //  - Length rounding rounds each width, height, and thickness
652    //    independently and then places boxes from those rounded lengths.
653    //    Sizes stay stable under translation, but neighboring boxes derive
654    //    their shared boundary from different sources, so closure is not
655    //    guaranteed.
656    //
657    // We apply absolute edge rounding for each element's outer box in
658    // post-layout rounding to preserve closure. Border and padding widths
659    // are not touched by post-layout rounding; they keep their pre-layout
660    // rounded value so that they remain stable under translation.
661    //
662    // This gives both closure and translation stability in the case that
663    // all local metrics are integer device-pixel lengths. Pre-layout
664    // rounding covers that in most cases. The exception is metrics
665    // resolved by layout relationships, such as percentages. Outer box
666    // edges will still close globally, and painted border widths are still
667    // snapped independently, but the raw content-box origin can carry a
668    // 1dp residual into descendants.
669
670    /// vue-native fork: whether the node is out of flow (`position:
671    /// absolute`), which a scroll container measures without its padding.
672    pub fn is_absolute(&self, id: LayoutId) -> bool {
673        self.taffy
674            .style(id.0)
675            .is_ok_and(|style| style.position == taffy::style::Position::Absolute)
676    }
677
678    pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
679        if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
680            return layout;
681        }
682
683        let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
684        let layout_location = layout.location;
685        let layout_size = layout.size;
686        let parent = self.taffy.parent(id.0);
687
688        let absolute_outer_origin = match parent {
689            Some(parent_id) => {
690                let parent_id = LayoutId::from(parent_id);
691                self.layout_bounds(parent_id, scale_factor);
692                let parent_origin = *self
693                    .absolute_outer_origins
694                    .get(&parent_id)
695                    .expect("parent absolute outer origin should be cached");
696                parent_origin + Point::from(layout_location)
697            }
698            None => Point::from(layout_location),
699        };
700        self.absolute_outer_origins
701            .insert(id, absolute_outer_origin);
702
703        let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
704        let snapped_bounds = Bounds::from_corners(
705            absolute_outer_origin.map(round_half_toward_zero),
706            absolute_far.map(round_half_toward_zero),
707        );
708
709        let bounds = (snapped_bounds / scale_factor).map(Pixels);
710        self.absolute_layout_bounds.insert(id, bounds);
711        bounds
712    }
713}
714
715/// A unique identifier for a layout node, generated when requesting a layout from Taffy
716#[derive(Copy, Clone, Eq, PartialEq, Debug)]
717#[repr(transparent)]
718pub struct LayoutId(NodeId);
719
720impl LayoutId {
721    fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
722        // SAFETY: LayoutId is repr(transparent) to taffy::tree::NodeId.
723        unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
724    }
725}
726
727impl std::hash::Hash for LayoutId {
728    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
729        u64::from(self.0).hash(state);
730    }
731}
732
733impl From<NodeId> for LayoutId {
734    fn from(node_id: NodeId) -> Self {
735        Self(node_id)
736    }
737}
738
739impl From<LayoutId> for NodeId {
740    fn from(layout_id: LayoutId) -> NodeId {
741        layout_id.0
742    }
743}
744
745fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
746    size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
747}
748
749fn border_widths_to_taffy(
750    widths: &Edges<AbsoluteLength>,
751    rem_size: Pixels,
752    scale_factor: f32,
753) -> TaffyRect<taffy::style::LengthPercentage> {
754    let snap = |w: &AbsoluteLength| {
755        taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
756            w.to_pixels(rem_size).0,
757            scale_factor,
758        ))
759    };
760    TaffyRect {
761        top: snap(&widths.top),
762        right: snap(&widths.right),
763        bottom: snap(&widths.bottom),
764        left: snap(&widths.left),
765    }
766}
767
768trait ToTaffy<Output> {
769    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
770}
771
772impl ToTaffy<taffy::style::Style> for Style {
773    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
774        use taffy::style_helpers::{fr, length, minmax, repeat};
775
776        fn to_grid_line(
777            placement: &Range<crate::GridPlacement>,
778        ) -> taffy::Line<taffy::GridPlacement> {
779            taffy::Line {
780                start: placement.start.into(),
781                end: placement.end.into(),
782            }
783        }
784
785        fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
786            unit: &Option<GridTemplate>,
787        ) -> Vec<taffy::GridTemplateComponent<T>> {
788            unit.map(|template| {
789                match template.min_size {
790                    // grid-template-*: repeat(<number>, minmax(0, 1fr));
791                    crate::GridTemplateMinSize::Zero => {
792                        vec![repeat(
793                            template.repeat,
794                            vec![minmax(length(0.0_f32), fr(1.0_f32))],
795                        )]
796                    }
797                    // grid-template-*: repeat(<number>, minmax(min-content, 1fr));
798                    crate::GridTemplateMinSize::MinContent => {
799                        vec![repeat(
800                            template.repeat,
801                            vec![minmax(min_content(), fr(1.0_f32))],
802                        )]
803                    }
804                    // grid-template-*: repeat(<number>, minmax(0, max-content))
805                    crate::GridTemplateMinSize::MaxContent => {
806                        vec![repeat(
807                            template.repeat,
808                            vec![minmax(length(0.0_f32), max_content())],
809                        )]
810                    }
811                }
812            })
813            .unwrap_or_default()
814        }
815
816        // An ARBITRARY track list (`1fr auto`, `minmax(0,1fr) 200px`), which
817        // `to_grid_repeat`'s one-shape `repeat()` cannot express. Each track is
818        // already in `minmax()` normal form, so this is a straight translation.
819        fn to_track_size_min(size: crate::GridTrackSize) -> taffy::MinTrackSizingFunction {
820            use crate::GridTrackSize as G;
821            use taffy::MinTrackSizingFunction as M;
822            match size {
823                G::Auto => M::auto(),
824                G::MinContent => M::min_content(),
825                G::MaxContent => M::max_content(),
826                G::Px(v) => M::length(v),
827                G::Percent(v) => M::percent(v),
828                // `<flex>` is not a valid track MINIMUM in CSS; it computes to
829                // `auto` there, so it does here.
830                G::Fr(_) => M::auto(),
831            }
832        }
833        fn to_track_size_max(size: crate::GridTrackSize) -> taffy::MaxTrackSizingFunction {
834            use crate::GridTrackSize as G;
835            use taffy::MaxTrackSizingFunction as M;
836            match size {
837                G::Auto => M::auto(),
838                G::MinContent => M::min_content(),
839                G::MaxContent => M::max_content(),
840                G::Px(v) => M::length(v),
841                G::Percent(v) => M::percent(v),
842                G::Fr(v) => M::fr(v),
843            }
844        }
845        fn to_grid_tracks<T: taffy::style::CheapCloneStr>(
846            tracks: &Option<Vec<crate::GridTrack>>,
847            auto: Option<crate::GridAutoRepeat>,
848        ) -> Option<Vec<taffy::GridTemplateComponent<T>>> {
849            let track =
850                |t: &crate::GridTrack| minmax(to_track_size_min(t.min), to_track_size_max(t.max));
851            tracks.as_ref().map(|list| {
852                // vue-native fork: one `repeat(auto-fill | auto-fit, …)` run,
853                // which taffy expands against the container at layout time.
854                let run = auto
855                    .map(|a| a.start as usize..(a.start as usize + a.len as usize))
856                    .filter(|run| !run.is_empty() && run.end <= list.len());
857                let mut out = Vec::with_capacity(list.len());
858                for (index, t) in list.iter().enumerate() {
859                    match (&run, auto) {
860                        (Some(run), Some(a)) if run.contains(&index) => {
861                            if index == run.start {
862                                let count = if a.fit {
863                                    taffy::RepetitionCount::AutoFit
864                                } else {
865                                    taffy::RepetitionCount::AutoFill
866                                };
867                                out.push(repeat(
868                                    count,
869                                    list[run.clone()].iter().map(track).collect(),
870                                ));
871                            }
872                        }
873                        _ => out.push(taffy::GridTemplateComponent::Single(track(t))),
874                    }
875                }
876                out
877            })
878        }
879
880        taffy::style::Style {
881            display: self.display.into(),
882            overflow: self.overflow.into(),
883            scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
884            position: self.position.into(),
885            inset: self.inset.to_taffy(rem_size, scale_factor),
886            size: self.size.to_taffy(rem_size, scale_factor),
887            min_size: self.min_size.to_taffy(rem_size, scale_factor),
888            max_size: self.max_size.to_taffy(rem_size, scale_factor),
889            aspect_ratio: self
890                .aspect_ratio
891                .map(f32::abs)
892                .filter(|ratio| ratio.is_finite() && *ratio > 0.0),
893            margin: self.margin.to_taffy(rem_size, scale_factor),
894            padding: self.padding.to_taffy(rem_size, scale_factor),
895            border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
896            align_items: self.align_items.map(Into::into).unwrap_or_default(),
897            align_self: self.align_self.map(|x| x.into()),
898            align_content: self.align_content.map(Into::into).unwrap_or_default(),
899            justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
900            gap: self.gap.to_taffy(rem_size, scale_factor),
901            flex_direction: self.flex_direction.into(),
902            flex_wrap: self.flex_wrap.into(),
903            flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
904            flex_grow: self.flex_grow,
905            flex_shrink: self.flex_shrink,
906            // An explicit track list wins over the `repeat(N, …)` shorthand.
907            grid_template_rows: to_grid_tracks(&self.vn_grid_rows, self.vn_grid_rows_auto)
908                .unwrap_or_else(|| to_grid_repeat(&self.grid_rows)),
909            grid_template_columns: to_grid_tracks(&self.vn_grid_cols, self.vn_grid_cols_auto)
910                .unwrap_or_else(|| to_grid_repeat(&self.grid_cols)),
911            grid_auto_columns: self.vn_grid_auto_cols.as_ref().map(|tracks| tracks.iter()
912                .map(|track| minmax(to_track_size_min(track.min), to_track_size_max(track.max)))
913                .collect()).unwrap_or_default(),
914            grid_auto_rows: self.vn_grid_auto_rows.as_ref().map(|tracks| tracks.iter()
915                .map(|track| minmax(to_track_size_min(track.min), to_track_size_max(track.max)))
916                .collect()).unwrap_or_default(),
917            grid_auto_flow: match self.vn_grid_auto_flow.unwrap_or_default() {
918                crate::GridAutoFlow::Row => taffy::GridAutoFlow::Row,
919                crate::GridAutoFlow::Column => taffy::GridAutoFlow::Column,
920                crate::GridAutoFlow::RowDense => taffy::GridAutoFlow::RowDense,
921                crate::GridAutoFlow::ColumnDense => taffy::GridAutoFlow::ColumnDense,
922            },
923            justify_items: self.vn_justify_items.map(Into::into).unwrap_or_default(),
924            justify_self: self.vn_justify_self.map(|x| x.into()),
925            grid_row: self
926                .grid_location
927                .as_ref()
928                .map(|location| to_grid_line(&location.row))
929                .unwrap_or_default(),
930            grid_column: self
931                .grid_location
932                .as_ref()
933                .map(|location| to_grid_line(&location.column))
934                .unwrap_or_default(),
935            contain: {
936                let mut contain = taffy::Contain::NONE;
937                if self.vn_contain_size & Style::CONTAIN_INLINE_SIZE != 0 {
938                    contain |= taffy::Contain::INLINE_SIZE;
939                }
940                if self.vn_contain_size & Style::CONTAIN_BLOCK_SIZE != 0 {
941                    contain |= taffy::Contain::BLOCK_SIZE;
942                }
943                contain
944            },
945            ..Default::default()
946        }
947    }
948}
949
950impl ToTaffy<f32> for AbsoluteLength {
951    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
952        round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
953    }
954}
955
956impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
957    fn to_taffy(
958        &self,
959        rem_size: Pixels,
960        scale_factor: f32,
961    ) -> taffy::prelude::LengthPercentageAuto {
962        match self {
963            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
964            Length::Auto | Length::VnCalcSize(_) => taffy::prelude::LengthPercentageAuto::auto(),
965        }
966    }
967}
968
969impl ToTaffy<taffy::style::Dimension> for Length {
970    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
971        match self {
972            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
973            Length::Auto => taffy::prelude::Dimension::auto(),
974            Length::VnCalcSize(c) => basis_dimension(c.basis),
975        }
976    }
977}
978
979/// vue-native fork: a node whose sizing properties hold a `calc-size()` other than its basis
980/// alone, which [`TaffyLayoutEngine::compute_layout`] lays out twice. Per axis: size, min, max.
981struct CalcSizeNode {
982    id: LayoutId,
983    width: [Option<crate::VnCalcSize>; 3],
984    height: [Option<crate::VnCalcSize>; 3],
985    flex_basis: Option<crate::VnCalcSize>,
986}
987
988impl CalcSizeNode {
989    fn of(id: LayoutId, style: &Style) -> Option<Self> {
990        let calc = |l: &Length| match l {
991            Length::VnCalcSize(c) if !c.is_basis() => Some(*c),
992            _ => None,
993        };
994        let node = CalcSizeNode {
995            id,
996            width: [
997                calc(&style.size.width),
998                calc(&style.min_size.width),
999                calc(&style.max_size.width),
1000            ],
1001            height: [
1002                calc(&style.size.height),
1003                calc(&style.min_size.height),
1004                calc(&style.max_size.height),
1005            ],
1006            flex_basis: calc(&style.flex_basis),
1007        };
1008        (node.width.iter().chain(&node.height).any(Option::is_some) || node.flex_basis.is_some())
1009            .then_some(node)
1010    }
1011}
1012
1013/// `size * scale + offset` with `size` the measured basis in logical pixels, as [`calc_handle`]
1014/// returns it: a percentage in the offset still resolves against the containing block.
1015fn calc_size_value(
1016    c: &crate::VnCalcSize,
1017    size: f32,
1018    rem_size: Pixels,
1019    scale_factor: f32,
1020) -> Result<*const (), f32> {
1021    let scaled = c.scale * size;
1022    let (fraction, pixels) = match c.offset {
1023        DefiniteLength::Absolute(a) => (0., scaled + a.to_pixels(rem_size).0),
1024        DefiniteLength::Fraction(f) => (f, scaled),
1025        DefiniteLength::Calc { fraction, pixels } => (fraction, scaled + pixels.0),
1026    };
1027    if fraction == 0. {
1028        return Err(round_to_device_pixel(pixels.max(0.), scale_factor));
1029    }
1030    calc_handle(fraction, Pixels(pixels), scale_factor)
1031}
1032
1033/// vue-native fork: the keyword a `calc-size()` is measured from; also its whole layout when it
1034/// is the identity (`calc-size(auto, size)`).
1035fn basis_dimension(basis: crate::VnSizeBasis) -> taffy::style::Dimension {
1036    use crate::VnSizeBasis as B;
1037    use taffy::style::Dimension as D;
1038    match basis {
1039        B::Auto => D::auto(),
1040        B::MinContent => D::min_content(),
1041        B::MaxContent => D::max_content(),
1042        B::FitContent => D::fit_content(),
1043        B::Content => D::content(),
1044    }
1045}
1046
1047impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
1048    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
1049        match self {
1050            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1051            DefiniteLength::Fraction(fraction) => {
1052                taffy::style::LengthPercentage::percent(*fraction)
1053            }
1054            DefiniteLength::Calc { fraction, pixels } => {
1055                match calc_handle(*fraction, *pixels, scale_factor) {
1056                    Ok(handle) => taffy::style::LengthPercentage::calc(handle),
1057                    Err(pixels) => taffy::style::LengthPercentage::length(pixels),
1058                }
1059            }
1060        }
1061    }
1062}
1063
1064impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
1065    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
1066        match self {
1067            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1068            DefiniteLength::Fraction(fraction) => {
1069                taffy::style::LengthPercentageAuto::percent(*fraction)
1070            }
1071            DefiniteLength::Calc { fraction, pixels } => {
1072                match calc_handle(*fraction, *pixels, scale_factor) {
1073                    Ok(handle) => taffy::style::LengthPercentageAuto::calc(handle),
1074                    Err(pixels) => taffy::style::LengthPercentageAuto::length(pixels),
1075                }
1076            }
1077        }
1078    }
1079}
1080
1081impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
1082    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
1083        match self {
1084            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1085            DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
1086            DefiniteLength::Calc { fraction, pixels } => {
1087                match calc_handle(*fraction, *pixels, scale_factor) {
1088                    Ok(handle) => taffy::style::Dimension::calc(handle),
1089                    Err(pixels) => taffy::style::Dimension::length(pixels),
1090                }
1091            }
1092        }
1093    }
1094}
1095
1096/// vue-native fork: the taffy `calc()` handle for [`DefiniteLength::Calc`].
1097///
1098/// taffy treats a calc value as an opaque, 8-byte-aligned handle and asks its
1099/// tree to resolve it against the percentage basis (`resolve_calc_value`). A
1100/// pointer to a heap node would need an owner and a lifetime; the linear form
1101/// `fraction * basis + pixels` fits in the handle itself, so it is packed
1102/// there: the length's `f32` bits in the high half, the fraction's in the low
1103/// half with its three lowest mantissa bits cleared for taffy's tag (a relative
1104/// error under 2^-20). vue-native's vendored taffy (`vendor/taffy`, patched
1105/// into the vue-native workspace) decodes exactly this in
1106/// `TaffyView::resolve_calc_value`; the two halves are a contract. Upstream
1107/// taffy resolves every calc to zero, which is what this degrades to in a
1108/// build against it (only vue-native ever writes a `Calc`).
1109///
1110/// `Err(pixels)` when there is nothing to pack: a zero fraction is a plain
1111/// length, and taffy reserves the all-zero handle. On a 32-bit target the
1112/// handle has no room for two `f32`s, so the percentage half is dropped there.
1113fn calc_handle(fraction: f32, pixels: Pixels, scale_factor: f32) -> Result<*const (), f32> {
1114    let length = round_to_device_pixel(pixels.0, scale_factor);
1115    if fraction == 0. {
1116        return Err(length);
1117    }
1118    #[cfg(target_pointer_width = "64")]
1119    {
1120        let bits = ((length.to_bits() as u64) << 32) | (fraction.to_bits() & !0b111) as u64;
1121        if bits == 0 {
1122            return Err(length);
1123        }
1124        Ok(bits as usize as *const ())
1125    }
1126    #[cfg(not(target_pointer_width = "64"))]
1127    {
1128        Err(length)
1129    }
1130}
1131
1132/// vue-native fork: the inverse of [`calc_handle`], for the leaves taffy 0.15
1133/// lays out through `compute_leaf_layout` with a caller-supplied resolver. It
1134/// must decode exactly what the vendored taffy's
1135/// `TaffyView::resolve_calc_value` does for every other node.
1136#[inline(always)]
1137fn resolve_calc_handle(val: *const (), basis: f32) -> f32 {
1138    #[cfg(target_pointer_width = "64")]
1139    {
1140        let bits = val as usize as u64;
1141        let length = f32::from_bits((bits >> 32) as u32);
1142        let fraction = f32::from_bits(bits as u32 & !0b111);
1143        fraction * basis + length
1144    }
1145    #[cfg(not(target_pointer_width = "64"))]
1146    {
1147        let _ = (val, basis);
1148        0.0
1149    }
1150}
1151
1152impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
1153    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
1154        taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
1155    }
1156}
1157
1158impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
1159    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
1160        taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
1161    }
1162}
1163
1164impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
1165    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
1166        taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
1167    }
1168}
1169
1170impl<T, T2> From<TaffyPoint<T>> for Point<T2>
1171where
1172    T: Into<T2>,
1173    T2: Clone + Debug + Default + PartialEq,
1174{
1175    fn from(point: TaffyPoint<T>) -> Point<T2> {
1176        Point {
1177            x: point.x.into(),
1178            y: point.y.into(),
1179        }
1180    }
1181}
1182
1183impl<T, T2> From<Point<T>> for TaffyPoint<T2>
1184where
1185    T: Into<T2> + Clone + Debug + Default + PartialEq,
1186{
1187    fn from(val: Point<T>) -> Self {
1188        TaffyPoint {
1189            x: val.x.into(),
1190            y: val.y.into(),
1191        }
1192    }
1193}
1194
1195impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
1196where
1197    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
1198{
1199    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
1200        TaffySize {
1201            width: self.width.to_taffy(rem_size, scale_factor),
1202            height: self.height.to_taffy(rem_size, scale_factor),
1203        }
1204    }
1205}
1206
1207impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
1208where
1209    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
1210{
1211    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
1212        TaffyRect {
1213            top: self.top.to_taffy(rem_size, scale_factor),
1214            right: self.right.to_taffy(rem_size, scale_factor),
1215            bottom: self.bottom.to_taffy(rem_size, scale_factor),
1216            left: self.left.to_taffy(rem_size, scale_factor),
1217        }
1218    }
1219}
1220
1221impl<T, U> From<TaffySize<T>> for Size<U>
1222where
1223    T: Into<U>,
1224    U: Clone + Debug + Default + PartialEq,
1225{
1226    fn from(taffy_size: TaffySize<T>) -> Self {
1227        Size {
1228            width: taffy_size.width.into(),
1229            height: taffy_size.height.into(),
1230        }
1231    }
1232}
1233
1234impl<T, U> From<Size<T>> for TaffySize<U>
1235where
1236    T: Into<U> + Clone + Debug + Default + PartialEq,
1237{
1238    fn from(size: Size<T>) -> Self {
1239        TaffySize {
1240            width: size.width.into(),
1241            height: size.height.into(),
1242        }
1243    }
1244}
1245
1246/// The space available for an element to be laid out in
1247#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
1248pub enum AvailableSpace {
1249    /// The amount of space available is the specified number of pixels
1250    Definite(Pixels),
1251    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
1252    #[default]
1253    MinContent,
1254    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
1255    MaxContent,
1256}
1257
1258impl AvailableSpace {
1259    /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
1260    ///
1261    /// This function is useful when you want to create a `Size` with the minimum content constraints
1262    /// for both dimensions.
1263    ///
1264    /// # Examples
1265    ///
1266    /// ```
1267    /// use gpui::AvailableSpace;
1268    /// let min_content_size = AvailableSpace::min_size();
1269    /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
1270    /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
1271    /// ```
1272    pub const fn min_size() -> Size<Self> {
1273        Size {
1274            width: Self::MinContent,
1275            height: Self::MinContent,
1276        }
1277    }
1278}
1279
1280impl From<AvailableSpace> for TaffyAvailableSpace {
1281    fn from(space: AvailableSpace) -> TaffyAvailableSpace {
1282        match space {
1283            AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
1284            AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
1285            AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
1286        }
1287    }
1288}
1289
1290impl From<TaffyAvailableSpace> for AvailableSpace {
1291    fn from(space: TaffyAvailableSpace) -> AvailableSpace {
1292        match space {
1293            TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
1294            TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
1295            TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
1296        }
1297    }
1298}
1299
1300impl From<Pixels> for AvailableSpace {
1301    fn from(pixels: Pixels) -> Self {
1302        AvailableSpace::Definite(pixels)
1303    }
1304}
1305
1306impl From<Size<Pixels>> for Size<AvailableSpace> {
1307    fn from(size: Size<Pixels>) -> Self {
1308        Size {
1309            width: AvailableSpace::Definite(size.width),
1310            height: AvailableSpace::Definite(size.height),
1311        }
1312    }
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318
1319    #[test]
1320    fn flex_and_grid_lay_their_children_out_in_order_modified_document_order() {
1321        let mut engine = TaffyLayoutEngine::new();
1322        let leaf = |engine: &mut TaffyLayoutEngine, order: i32| {
1323            let style = Style { vn_order: order, ..Default::default() };
1324            engine.request_layout(style, Pixels(16.0), 1.0, &[])
1325        };
1326        let kids = [leaf(&mut engine, 2), leaf(&mut engine, -1), leaf(&mut engine, 0), leaf(&mut engine, 2)];
1327        let laid_out = |engine: &mut TaffyLayoutEngine, display: Display| {
1328            let style = Style { display, ..Default::default() };
1329            let root = engine.request_layout(style, Pixels(16.0), 1.0, &kids);
1330            engine.taffy.child_ids(root.into()).map(LayoutId::from).collect::<Vec<_>>()
1331        };
1332        let modified = vec![kids[1], kids[2], kids[0], kids[3]];
1333        assert_eq!(laid_out(&mut engine, Display::Flex), modified);
1334        assert_eq!(laid_out(&mut engine, Display::Grid), modified);
1335        assert_eq!(laid_out(&mut engine, Display::Block), kids.to_vec());
1336        engine.clear();
1337        let fresh = [leaf(&mut engine, 0), leaf(&mut engine, 0)];
1338        let root = engine.request_layout(Style { display: Display::Flex, ..Default::default() }, Pixels(16.0), 1.0, &fresh);
1339        assert!(engine.taffy.child_ids(root.into()).map(LayoutId::from).eq(fresh));
1340    }
1341
1342    #[test]
1343    fn implicit_fractional_columns_share_the_container_width() {
1344        let mut tree = TaffyTree::<()>::new();
1345        let children: Vec<_> = (0..3).map(|_| tree.new_leaf(Default::default()).unwrap()).collect();
1346        let style = Style {
1347            display: crate::Display::Grid,
1348            size: Size {
1349                width: Length::Definite(Pixels(300.0).into()),
1350                height: Length::Definite(Pixels(40.0).into()),
1351            },
1352            vn_grid_auto_flow: Some(crate::GridAutoFlow::Column),
1353            vn_grid_auto_cols: Some(vec![crate::GridTrack::fr(1.0)]),
1354            ..Default::default()
1355        };
1356        let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1357        tree.compute_layout(root, TaffySize {
1358            width: TaffyAvailableSpace::Definite(300.0), height: TaffyAvailableSpace::Definite(40.0),
1359        }).unwrap();
1360        for (index, child) in children.into_iter().enumerate() {
1361            let layout = tree.layout(child).unwrap();
1362            assert_eq!(layout.size.width, 100.0);
1363            assert_eq!(layout.location.x, index as f32 * 100.0);
1364        }
1365    }
1366
1367    #[test]
1368    fn implicit_row_patterns_repeat_in_layout() {
1369        use crate::GridTrackSize as Track;
1370        let mut tree = TaffyTree::<()>::new();
1371        let children: Vec<_> = (0..5).map(|_| tree.new_leaf(Default::default()).unwrap()).collect();
1372        let style = Style {
1373            display: crate::Display::Grid,
1374            vn_grid_cols: Some(vec![crate::GridTrack::fixed(Track::Px(100.0))]),
1375            vn_grid_auto_rows: Some(vec![crate::GridTrack::fixed(Track::Px(20.0)), crate::GridTrack::fixed(Track::Px(35.0))]),
1376            ..Default::default()
1377        };
1378        let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1379        tree.compute_layout(root, TaffySize {
1380            width: TaffyAvailableSpace::MaxContent, height: TaffyAvailableSpace::MaxContent,
1381        }).unwrap();
1382        for ((height, top), child) in [(20.0, 0.0), (35.0, 20.0), (20.0, 55.0), (35.0, 75.0), (20.0, 110.0)].into_iter().zip(children) {
1383            let layout = tree.layout(child).unwrap();
1384            assert_eq!(layout.size.height, height);
1385            assert_eq!(layout.location.y, top);
1386        }
1387    }
1388
1389    #[test]
1390    fn implicit_auto_reset_replaces_a_fixed_row_pattern() {
1391        use crate::{GridTrack, GridTrackSize, Refineable, StyleRefinement};
1392        let mut style = Style {
1393            display: crate::Display::Grid,
1394            vn_grid_cols: Some(vec![GridTrack::fixed(GridTrackSize::Px(100.0))]),
1395            vn_grid_auto_rows: Some(vec![GridTrack::fixed(GridTrackSize::Px(50.0))]),
1396            ..Default::default()
1397        };
1398        style.refine(&StyleRefinement { vn_grid_auto_rows: Some(Vec::new()), ..Default::default() });
1399        let mut tree = TaffyTree::<()>::new();
1400        let children: Vec<_> = [17.0, 29.0].into_iter().map(|height| {
1401            let mut leaf_style = taffy::style::Style::default();
1402            leaf_style.size.height = taffy::style::Dimension::length(height);
1403            tree.new_leaf(leaf_style).unwrap()
1404        }).collect();
1405        let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1406        tree.compute_layout(root, TaffySize {
1407            width: TaffyAvailableSpace::MaxContent, height: TaffyAvailableSpace::MaxContent,
1408        }).unwrap();
1409        assert_eq!(tree.layout(children[1]).unwrap().location.y, 17.0);
1410        assert_eq!(tree.layout(root).unwrap().size.height, 46.0);
1411    }
1412
1413    #[test]
1414    fn border_widths_to_taffy_use_stroke_snapping() {
1415        let border_widths = Edges {
1416            top: Pixels(0.0).into(),
1417            right: Pixels(0.4).into(),
1418            bottom: Pixels(0.5).into(),
1419            left: Pixels(1.6).into(),
1420        };
1421        let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
1422
1423        assert_eq!(
1424            taffy_border.top,
1425            taffy::style::LengthPercentage::length(0.0)
1426        );
1427        assert_eq!(
1428            taffy_border.right,
1429            taffy::style::LengthPercentage::length(1.0)
1430        );
1431        assert_eq!(
1432            taffy_border.bottom,
1433            taffy::style::LengthPercentage::length(1.0)
1434        );
1435        assert_eq!(
1436            taffy_border.left,
1437            taffy::style::LengthPercentage::length(2.0)
1438        );
1439    }
1440}