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(main) = self.main_axis(node.id) {
492                    // `size` is the box's own size at the basis, not what the flex line makes of
493                    // it: a container laid out again at last frame's size would shrink it.
494                    let sized = [&node.width, &node.height][main].iter().any(Option::is_some);
495                    if let Some(basis) = node.flex_basis {
496                        probe.flex_basis = basis_dimension(basis.basis);
497                    } else if sized {
498                        probe.flex_basis = taffy::style::Dimension::auto();
499                    }
500                    if node.flex_basis.is_some() || sized {
501                        probe.flex_grow = 0.;
502                        probe.flex_shrink = 0.;
503                    }
504                }
505                if probe != requested {
506                    self.taffy.set_style(node.id.0, probe).expect(EXPECT_MESSAGE);
507                }
508                requested
509            })
510            .collect()
511    }
512
513    /// The second pass's styles: each `calc-size()` as the length its function gives for the
514    /// measured basis, in the box-sizing box.
515    fn resolve_calc_sizes(
516        &mut self,
517        nodes: &[CalcSizeNode],
518        requested: Vec<taffy::style::Style>,
519        rem_size: Pixels,
520        scale_factor: f32,
521    ) {
522        for (node, mut style) in nodes.iter().zip(requested) {
523            let layout = *self.taffy.layout(node.id.0).expect(EXPECT_MESSAGE);
524            let content_box = style.box_sizing == taffy::style::BoxSizing::ContentBox;
525            let inner = |outer: f32, a: f32, b: f32, c: f32, d: f32| {
526                if content_box {
527                    (outer - a - b - c - d).max(0.)
528                } else {
529                    outer
530                }
531            };
532            let measured = [
533                inner(
534                    layout.size.width,
535                    layout.padding.left,
536                    layout.padding.right,
537                    layout.border.left,
538                    layout.border.right,
539                ),
540                inner(
541                    layout.size.height,
542                    layout.padding.top,
543                    layout.padding.bottom,
544                    layout.border.top,
545                    layout.border.bottom,
546                ),
547            ];
548            let resolve = |c: &crate::VnCalcSize, axis: usize| {
549                calc_size_value(c, measured[axis] / scale_factor, rem_size, scale_factor)
550            };
551            let dimension = |v: Result<*const (), f32>| match v {
552                Ok(handle) => taffy::style::Dimension::calc(handle),
553                Err(length) => taffy::style::Dimension::length(length),
554            };
555            let bound = |v: Result<*const (), f32>| match v {
556                Ok(handle) => taffy::style::LengthPercentageAuto::calc(handle),
557                Err(length) => taffy::style::LengthPercentageAuto::length(length),
558            };
559            for axis in 0..2 {
560                let [size, min, max] = if axis == 0 { node.width } else { node.height };
561                let (s, lo, hi) = if axis == 0 {
562                    (
563                        &mut style.size.width,
564                        &mut style.min_size.width,
565                        &mut style.max_size.width,
566                    )
567                } else {
568                    (
569                        &mut style.size.height,
570                        &mut style.min_size.height,
571                        &mut style.max_size.height,
572                    )
573                };
574                if let Some(c) = size {
575                    *s = dimension(resolve(&c, axis));
576                }
577                if let Some(c) = min {
578                    *lo = bound(resolve(&c, axis));
579                }
580                if let Some(c) = max {
581                    *hi = bound(resolve(&c, axis));
582                }
583            }
584            if let (Some(c), Some(axis)) = (node.flex_basis, self.main_axis(node.id)) {
585                style.flex_basis = dimension(resolve(&c, axis));
586            }
587            if self.taffy.style(node.id.0).expect(EXPECT_MESSAGE) != &style {
588                self.taffy.set_style(node.id.0, style).expect(EXPECT_MESSAGE);
589            }
590        }
591    }
592
593    /// The flex container's main axis for `id`, 0 for rows and 1 for columns.
594    fn main_axis(&self, id: LayoutId) -> Option<usize> {
595        let parent = self.taffy.parent(id.0)?;
596        let style = self.taffy.style(parent).ok()?;
597        use taffy::style::FlexDirection as F;
598        (style.display == taffy::style::Display::Flex).then(|| match style.flex_direction {
599            F::Row | F::RowReverse => 0,
600            F::Column | F::ColumnReverse => 1,
601        })
602    }
603
604    // Pixel snapping
605    //
606    // Painting primitives at non-integer pixel coordinates produces blurry
607    // output. Pixel snapping converts layout coordinates into integer
608    // device-pixel coordinates so painted edges land exactly on physical
609    // pixel boundaries.
610    //
611    // Non-integer coordinates can arise for several reasons, including:
612    //   - flex distribution, percentages, centering, and text measurement
613    //     can produce fractional element sizes and positions;
614    //   - at fractional scale factors (for example 125% or 150%), integer
615    //     logical-pixel values can map to non-integer device-pixel values.
616    //
617    // We pixel-snap by rounding in device-pixel space, after multiplying
618    // by `scale_factor`, so that snapping targets physical pixels. Bounds
619    // are divided by `scale_factor` before being returned to GPUI.
620    //
621    // Midpoints are rounded toward zero. This is a stylistic choice: a
622    // 1-logical-pixel line at 150% scale should render as 1 dp rather than
623    // 2 dp.
624    //
625    // Pixel snapping is done in two phases:
626    //
627    //  1. Pre-layout metric snapping. Before Taffy computes layout, all
628    //     authored absolute lengths are rounded in `to_taffy`. This
629    //     includes borders, padding, gaps, and explicit sizes.
630    //     Custom-measured leaf nodes have their measured sizes rounded up
631    //     to integer device-pixel lengths.
632    //
633    //  2. Post-layout edge snapping. After Taffy resolves the tree, layout
634    //     relationships such as flex shares, grid tracks, percentages, and
635    //     centering can produce new fractional edge positions. Boxes now
636    //     have edges in absolute coordinates, and snapping must decide
637    //     where those edges land on the device-pixel grid.
638    //
639    // Ideally, post-layout snapping would satisfy:
640    //
641    //  - Edge closure. Two raw layout edges at the same absolute position
642    //    should snap to the same pixel column.
643    //  - Translation stability. A component's internal geometry should not
644    //    change when it moves to a new absolute position.
645    //
646    // These goals are in tension because rounding is not associative.
647    // The simple local schemes make different tradeoffs:
648    //
649    //  - Absolute edge rounding gives each window coordinate one answer,
650    //    so coincident edges always close globally. But a span's snapped
651    //    length is `round(far) - round(near)`, which may change by 1 dp
652    //    as its absolute origin moves.
653    //
654    //  - Parent-relative edge rounding rounds each child inside its
655    //    parent's coordinate space. This guarantees translation stability,
656    //    but a shared edge reached through different parents can
657    //    accumulate different rounding, causing non-closure between
658    //    cousins.
659    //
660    //  - Length rounding rounds each width, height, and thickness
661    //    independently and then places boxes from those rounded lengths.
662    //    Sizes stay stable under translation, but neighboring boxes derive
663    //    their shared boundary from different sources, so closure is not
664    //    guaranteed.
665    //
666    // We apply absolute edge rounding for each element's outer box in
667    // post-layout rounding to preserve closure. Border and padding widths
668    // are not touched by post-layout rounding; they keep their pre-layout
669    // rounded value so that they remain stable under translation.
670    //
671    // This gives both closure and translation stability in the case that
672    // all local metrics are integer device-pixel lengths. Pre-layout
673    // rounding covers that in most cases. The exception is metrics
674    // resolved by layout relationships, such as percentages. Outer box
675    // edges will still close globally, and painted border widths are still
676    // snapped independently, but the raw content-box origin can carry a
677    // 1dp residual into descendants.
678
679    /// vue-native fork: whether the node is out of flow (`position:
680    /// absolute`), which a scroll container measures without its padding.
681    pub fn is_absolute(&self, id: LayoutId) -> bool {
682        self.taffy
683            .style(id.0)
684            .is_ok_and(|style| style.position == taffy::style::Position::Absolute)
685    }
686
687    pub fn layout_bounds(&mut self, id: LayoutId, scale_factor: f32) -> Bounds<Pixels> {
688        if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
689            return layout;
690        }
691
692        let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
693        let layout_location = layout.location;
694        let layout_size = layout.size;
695        let parent = self.taffy.parent(id.0);
696
697        let absolute_outer_origin = match parent {
698            Some(parent_id) => {
699                let parent_id = LayoutId::from(parent_id);
700                self.layout_bounds(parent_id, scale_factor);
701                let parent_origin = *self
702                    .absolute_outer_origins
703                    .get(&parent_id)
704                    .expect("parent absolute outer origin should be cached");
705                parent_origin + Point::from(layout_location)
706            }
707            None => Point::from(layout_location),
708        };
709        self.absolute_outer_origins
710            .insert(id, absolute_outer_origin);
711
712        let absolute_far = absolute_outer_origin + Point::from(Size::from(layout_size));
713        let snapped_bounds = Bounds::from_corners(
714            absolute_outer_origin.map(round_half_toward_zero),
715            absolute_far.map(round_half_toward_zero),
716        );
717
718        let bounds = (snapped_bounds / scale_factor).map(Pixels);
719        self.absolute_layout_bounds.insert(id, bounds);
720        bounds
721    }
722}
723
724/// A unique identifier for a layout node, generated when requesting a layout from Taffy
725#[derive(Copy, Clone, Eq, PartialEq, Debug)]
726#[repr(transparent)]
727pub struct LayoutId(NodeId);
728
729impl LayoutId {
730    fn to_taffy_slice(node_ids: &[Self]) -> &[taffy::NodeId] {
731        // SAFETY: LayoutId is repr(transparent) to taffy::tree::NodeId.
732        unsafe { std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(node_ids) }
733    }
734}
735
736impl std::hash::Hash for LayoutId {
737    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
738        u64::from(self.0).hash(state);
739    }
740}
741
742impl From<NodeId> for LayoutId {
743    fn from(node_id: NodeId) -> Self {
744        Self(node_id)
745    }
746}
747
748impl From<LayoutId> for NodeId {
749    fn from(layout_id: LayoutId) -> NodeId {
750        layout_id.0
751    }
752}
753
754fn snap_measured_size_to_device_pixels(size: Size<Pixels>, scale_factor: f32) -> Size<f32> {
755    size.map(|d| ceil_to_device_pixel(d.0.max(0.0), scale_factor))
756}
757
758fn border_widths_to_taffy(
759    widths: &Edges<AbsoluteLength>,
760    rem_size: Pixels,
761    scale_factor: f32,
762) -> TaffyRect<taffy::style::LengthPercentage> {
763    let snap = |w: &AbsoluteLength| {
764        taffy::style::LengthPercentage::length(round_stroke_to_device_pixel(
765            w.to_pixels(rem_size).0,
766            scale_factor,
767        ))
768    };
769    TaffyRect {
770        top: snap(&widths.top),
771        right: snap(&widths.right),
772        bottom: snap(&widths.bottom),
773        left: snap(&widths.left),
774    }
775}
776
777trait ToTaffy<Output> {
778    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> Output;
779}
780
781impl ToTaffy<taffy::style::Style> for Style {
782    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style {
783        use taffy::style_helpers::{fr, length, minmax, repeat};
784
785        fn to_grid_line(
786            placement: &Range<crate::GridPlacement>,
787        ) -> taffy::Line<taffy::GridPlacement> {
788            taffy::Line {
789                start: placement.start.into(),
790                end: placement.end.into(),
791            }
792        }
793
794        fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
795            unit: &Option<GridTemplate>,
796        ) -> Vec<taffy::GridTemplateComponent<T>> {
797            unit.map(|template| {
798                match template.min_size {
799                    // grid-template-*: repeat(<number>, minmax(0, 1fr));
800                    crate::GridTemplateMinSize::Zero => {
801                        vec![repeat(
802                            template.repeat,
803                            vec![minmax(length(0.0_f32), fr(1.0_f32))],
804                        )]
805                    }
806                    // grid-template-*: repeat(<number>, minmax(min-content, 1fr));
807                    crate::GridTemplateMinSize::MinContent => {
808                        vec![repeat(
809                            template.repeat,
810                            vec![minmax(min_content(), fr(1.0_f32))],
811                        )]
812                    }
813                    // grid-template-*: repeat(<number>, minmax(0, max-content))
814                    crate::GridTemplateMinSize::MaxContent => {
815                        vec![repeat(
816                            template.repeat,
817                            vec![minmax(length(0.0_f32), max_content())],
818                        )]
819                    }
820                }
821            })
822            .unwrap_or_default()
823        }
824
825        // An ARBITRARY track list (`1fr auto`, `minmax(0,1fr) 200px`), which
826        // `to_grid_repeat`'s one-shape `repeat()` cannot express. Each track is
827        // already in `minmax()` normal form, so this is a straight translation.
828        fn to_track_size_min(size: crate::GridTrackSize) -> taffy::MinTrackSizingFunction {
829            use crate::GridTrackSize as G;
830            use taffy::MinTrackSizingFunction as M;
831            match size {
832                G::Auto => M::auto(),
833                G::MinContent => M::min_content(),
834                G::MaxContent => M::max_content(),
835                G::Px(v) => M::length(v),
836                G::Percent(v) => M::percent(v),
837                // `<flex>` is not a valid track MINIMUM in CSS; it computes to
838                // `auto` there, so it does here.
839                G::Fr(_) => M::auto(),
840            }
841        }
842        fn to_track_size_max(size: crate::GridTrackSize) -> taffy::MaxTrackSizingFunction {
843            use crate::GridTrackSize as G;
844            use taffy::MaxTrackSizingFunction as M;
845            match size {
846                G::Auto => M::auto(),
847                G::MinContent => M::min_content(),
848                G::MaxContent => M::max_content(),
849                G::Px(v) => M::length(v),
850                G::Percent(v) => M::percent(v),
851                G::Fr(v) => M::fr(v),
852            }
853        }
854        fn to_grid_tracks<T: taffy::style::CheapCloneStr>(
855            tracks: &Option<Vec<crate::GridTrack>>,
856            auto: Option<crate::GridAutoRepeat>,
857        ) -> Option<Vec<taffy::GridTemplateComponent<T>>> {
858            let track =
859                |t: &crate::GridTrack| minmax(to_track_size_min(t.min), to_track_size_max(t.max));
860            tracks.as_ref().map(|list| {
861                // vue-native fork: one `repeat(auto-fill | auto-fit, …)` run,
862                // which taffy expands against the container at layout time.
863                let run = auto
864                    .map(|a| a.start as usize..(a.start as usize + a.len as usize))
865                    .filter(|run| !run.is_empty() && run.end <= list.len());
866                let mut out = Vec::with_capacity(list.len());
867                for (index, t) in list.iter().enumerate() {
868                    match (&run, auto) {
869                        (Some(run), Some(a)) if run.contains(&index) => {
870                            if index == run.start {
871                                let count = if a.fit {
872                                    taffy::RepetitionCount::AutoFit
873                                } else {
874                                    taffy::RepetitionCount::AutoFill
875                                };
876                                out.push(repeat(
877                                    count,
878                                    list[run.clone()].iter().map(track).collect(),
879                                ));
880                            }
881                        }
882                        _ => out.push(taffy::GridTemplateComponent::Single(track(t))),
883                    }
884                }
885                out
886            })
887        }
888
889        taffy::style::Style {
890            display: self.display.into(),
891            overflow: self.overflow.into(),
892            scrollbar_width: self.scrollbar_width.to_taffy(rem_size, scale_factor),
893            position: self.position.into(),
894            inset: self.inset.to_taffy(rem_size, scale_factor),
895            size: self.size.to_taffy(rem_size, scale_factor),
896            min_size: self.min_size.to_taffy(rem_size, scale_factor),
897            max_size: self.max_size.to_taffy(rem_size, scale_factor),
898            aspect_ratio: self
899                .aspect_ratio
900                .map(f32::abs)
901                .filter(|ratio| ratio.is_finite() && *ratio > 0.0),
902            margin: self.margin.to_taffy(rem_size, scale_factor),
903            padding: self.padding.to_taffy(rem_size, scale_factor),
904            border: border_widths_to_taffy(&self.border_widths, rem_size, scale_factor),
905            align_items: self.align_items.map(Into::into).unwrap_or_default(),
906            align_self: self.align_self.map(|x| x.into()),
907            align_content: self.align_content.map(Into::into).unwrap_or_default(),
908            justify_content: self.justify_content.map(Into::into).unwrap_or_default(),
909            gap: self.gap.to_taffy(rem_size, scale_factor),
910            flex_direction: self.flex_direction.into(),
911            flex_wrap: self.flex_wrap.into(),
912            flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor),
913            flex_grow: self.flex_grow,
914            flex_shrink: self.flex_shrink,
915            // An explicit track list wins over the `repeat(N, …)` shorthand.
916            grid_template_rows: to_grid_tracks(&self.vn_grid_rows, self.vn_grid_rows_auto)
917                .unwrap_or_else(|| to_grid_repeat(&self.grid_rows)),
918            grid_template_columns: to_grid_tracks(&self.vn_grid_cols, self.vn_grid_cols_auto)
919                .unwrap_or_else(|| to_grid_repeat(&self.grid_cols)),
920            grid_auto_columns: self.vn_grid_auto_cols.as_ref().map(|tracks| tracks.iter()
921                .map(|track| minmax(to_track_size_min(track.min), to_track_size_max(track.max)))
922                .collect()).unwrap_or_default(),
923            grid_auto_rows: self.vn_grid_auto_rows.as_ref().map(|tracks| tracks.iter()
924                .map(|track| minmax(to_track_size_min(track.min), to_track_size_max(track.max)))
925                .collect()).unwrap_or_default(),
926            grid_auto_flow: match self.vn_grid_auto_flow.unwrap_or_default() {
927                crate::GridAutoFlow::Row => taffy::GridAutoFlow::Row,
928                crate::GridAutoFlow::Column => taffy::GridAutoFlow::Column,
929                crate::GridAutoFlow::RowDense => taffy::GridAutoFlow::RowDense,
930                crate::GridAutoFlow::ColumnDense => taffy::GridAutoFlow::ColumnDense,
931            },
932            justify_items: self.vn_justify_items.map(Into::into).unwrap_or_default(),
933            justify_self: self.vn_justify_self.map(|x| x.into()),
934            grid_row: self
935                .grid_location
936                .as_ref()
937                .map(|location| to_grid_line(&location.row))
938                .unwrap_or_default(),
939            grid_column: self
940                .grid_location
941                .as_ref()
942                .map(|location| to_grid_line(&location.column))
943                .unwrap_or_default(),
944            contain: {
945                let mut contain = taffy::Contain::NONE;
946                if self.vn_contain_size & Style::CONTAIN_INLINE_SIZE != 0 {
947                    contain |= taffy::Contain::INLINE_SIZE;
948                }
949                if self.vn_contain_size & Style::CONTAIN_BLOCK_SIZE != 0 {
950                    contain |= taffy::Contain::BLOCK_SIZE;
951                }
952                contain
953            },
954            ..Default::default()
955        }
956    }
957}
958
959impl ToTaffy<f32> for AbsoluteLength {
960    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> f32 {
961        round_to_device_pixel(self.to_pixels(rem_size).0, scale_factor)
962    }
963}
964
965impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
966    fn to_taffy(
967        &self,
968        rem_size: Pixels,
969        scale_factor: f32,
970    ) -> taffy::prelude::LengthPercentageAuto {
971        match self {
972            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
973            Length::Auto | Length::VnCalcSize(_) => taffy::prelude::LengthPercentageAuto::auto(),
974        }
975    }
976}
977
978impl ToTaffy<taffy::style::Dimension> for Length {
979    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::prelude::Dimension {
980        match self {
981            Length::Definite(length) => length.to_taffy(rem_size, scale_factor),
982            Length::Auto => taffy::prelude::Dimension::auto(),
983            Length::VnCalcSize(c) => basis_dimension(c.basis),
984        }
985    }
986}
987
988/// vue-native fork: a node whose sizing properties hold a `calc-size()` other than its basis
989/// alone, which [`TaffyLayoutEngine::compute_layout`] lays out twice. Per axis: size, min, max.
990struct CalcSizeNode {
991    id: LayoutId,
992    width: [Option<crate::VnCalcSize>; 3],
993    height: [Option<crate::VnCalcSize>; 3],
994    flex_basis: Option<crate::VnCalcSize>,
995}
996
997impl CalcSizeNode {
998    fn of(id: LayoutId, style: &Style) -> Option<Self> {
999        let calc = |l: &Length| match l {
1000            Length::VnCalcSize(c) if !c.is_basis() => Some(*c),
1001            _ => None,
1002        };
1003        let node = CalcSizeNode {
1004            id,
1005            width: [
1006                calc(&style.size.width),
1007                calc(&style.min_size.width),
1008                calc(&style.max_size.width),
1009            ],
1010            height: [
1011                calc(&style.size.height),
1012                calc(&style.min_size.height),
1013                calc(&style.max_size.height),
1014            ],
1015            flex_basis: calc(&style.flex_basis),
1016        };
1017        (node.width.iter().chain(&node.height).any(Option::is_some) || node.flex_basis.is_some())
1018            .then_some(node)
1019    }
1020}
1021
1022/// `size * scale + offset` with `size` the measured basis in logical pixels, as [`calc_handle`]
1023/// returns it: a percentage in the offset still resolves against the containing block.
1024fn calc_size_value(
1025    c: &crate::VnCalcSize,
1026    size: f32,
1027    rem_size: Pixels,
1028    scale_factor: f32,
1029) -> Result<*const (), f32> {
1030    let scaled = c.scale * size;
1031    let (fraction, pixels) = match c.offset {
1032        DefiniteLength::Absolute(a) => (0., scaled + a.to_pixels(rem_size).0),
1033        DefiniteLength::Fraction(f) => (f, scaled),
1034        DefiniteLength::Calc { fraction, pixels } => (fraction, scaled + pixels.0),
1035    };
1036    if fraction == 0. {
1037        return Err(round_to_device_pixel(pixels.max(0.), scale_factor));
1038    }
1039    calc_handle(fraction, Pixels(pixels), scale_factor)
1040}
1041
1042/// vue-native fork: the keyword a `calc-size()` is measured from; also its whole layout when it
1043/// is the identity (`calc-size(auto, size)`).
1044fn basis_dimension(basis: crate::VnSizeBasis) -> taffy::style::Dimension {
1045    use crate::VnSizeBasis as B;
1046    use taffy::style::Dimension as D;
1047    match basis {
1048        B::Auto => D::auto(),
1049        B::MinContent => D::min_content(),
1050        B::MaxContent => D::max_content(),
1051        B::FitContent => D::fit_content(),
1052        B::Content => D::content(),
1053    }
1054}
1055
1056impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
1057    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
1058        match self {
1059            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1060            DefiniteLength::Fraction(fraction) => {
1061                taffy::style::LengthPercentage::percent(*fraction)
1062            }
1063            DefiniteLength::Calc { fraction, pixels } => {
1064                match calc_handle(*fraction, *pixels, scale_factor) {
1065                    Ok(handle) => taffy::style::LengthPercentage::calc(handle),
1066                    Err(pixels) => taffy::style::LengthPercentage::length(pixels),
1067                }
1068            }
1069        }
1070    }
1071}
1072
1073impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
1074    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
1075        match self {
1076            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1077            DefiniteLength::Fraction(fraction) => {
1078                taffy::style::LengthPercentageAuto::percent(*fraction)
1079            }
1080            DefiniteLength::Calc { fraction, pixels } => {
1081                match calc_handle(*fraction, *pixels, scale_factor) {
1082                    Ok(handle) => taffy::style::LengthPercentageAuto::calc(handle),
1083                    Err(pixels) => taffy::style::LengthPercentageAuto::length(pixels),
1084                }
1085            }
1086        }
1087    }
1088}
1089
1090impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
1091    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
1092        match self {
1093            DefiniteLength::Absolute(length) => length.to_taffy(rem_size, scale_factor),
1094            DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
1095            DefiniteLength::Calc { fraction, pixels } => {
1096                match calc_handle(*fraction, *pixels, scale_factor) {
1097                    Ok(handle) => taffy::style::Dimension::calc(handle),
1098                    Err(pixels) => taffy::style::Dimension::length(pixels),
1099                }
1100            }
1101        }
1102    }
1103}
1104
1105/// vue-native fork: the taffy `calc()` handle for [`DefiniteLength::Calc`].
1106///
1107/// taffy treats a calc value as an opaque, 8-byte-aligned handle and asks its
1108/// tree to resolve it against the percentage basis (`resolve_calc_value`). A
1109/// pointer to a heap node would need an owner and a lifetime; the linear form
1110/// `fraction * basis + pixels` fits in the handle itself, so it is packed
1111/// there: the length's `f32` bits in the high half, the fraction's in the low
1112/// half with its three lowest mantissa bits cleared for taffy's tag (a relative
1113/// error under 2^-20). vue-native's vendored taffy (`vendor/taffy`, patched
1114/// into the vue-native workspace) decodes exactly this in
1115/// `TaffyView::resolve_calc_value`; the two halves are a contract. Upstream
1116/// taffy resolves every calc to zero, which is what this degrades to in a
1117/// build against it (only vue-native ever writes a `Calc`).
1118///
1119/// `Err(pixels)` when there is nothing to pack: a zero fraction is a plain
1120/// length, and taffy reserves the all-zero handle. On a 32-bit target the
1121/// handle has no room for two `f32`s, so the percentage half is dropped there.
1122fn calc_handle(fraction: f32, pixels: Pixels, scale_factor: f32) -> Result<*const (), f32> {
1123    let length = round_to_device_pixel(pixels.0, scale_factor);
1124    if fraction == 0. {
1125        return Err(length);
1126    }
1127    #[cfg(target_pointer_width = "64")]
1128    {
1129        let bits = ((length.to_bits() as u64) << 32) | (fraction.to_bits() & !0b111) as u64;
1130        if bits == 0 {
1131            return Err(length);
1132        }
1133        Ok(bits as usize as *const ())
1134    }
1135    #[cfg(not(target_pointer_width = "64"))]
1136    {
1137        Err(length)
1138    }
1139}
1140
1141/// vue-native fork: the inverse of [`calc_handle`], for the leaves taffy 0.15
1142/// lays out through `compute_leaf_layout` with a caller-supplied resolver. It
1143/// must decode exactly what the vendored taffy's
1144/// `TaffyView::resolve_calc_value` does for every other node.
1145#[inline(always)]
1146fn resolve_calc_handle(val: *const (), basis: f32) -> f32 {
1147    #[cfg(target_pointer_width = "64")]
1148    {
1149        let bits = val as usize as u64;
1150        let length = f32::from_bits((bits >> 32) as u32);
1151        let fraction = f32::from_bits(bits as u32 & !0b111);
1152        fraction * basis + length
1153    }
1154    #[cfg(not(target_pointer_width = "64"))]
1155    {
1156        let _ = (val, basis);
1157        0.0
1158    }
1159}
1160
1161impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
1162    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentage {
1163        taffy::style::LengthPercentage::length(self.to_taffy(rem_size, scale_factor))
1164    }
1165}
1166
1167impl ToTaffy<taffy::style::LengthPercentageAuto> for AbsoluteLength {
1168    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::LengthPercentageAuto {
1169        taffy::style::LengthPercentageAuto::length(self.to_taffy(rem_size, scale_factor))
1170    }
1171}
1172
1173impl ToTaffy<taffy::style::Dimension> for AbsoluteLength {
1174    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Dimension {
1175        taffy::style::Dimension::length(self.to_taffy(rem_size, scale_factor))
1176    }
1177}
1178
1179impl<T, T2> From<TaffyPoint<T>> for Point<T2>
1180where
1181    T: Into<T2>,
1182    T2: Clone + Debug + Default + PartialEq,
1183{
1184    fn from(point: TaffyPoint<T>) -> Point<T2> {
1185        Point {
1186            x: point.x.into(),
1187            y: point.y.into(),
1188        }
1189    }
1190}
1191
1192impl<T, T2> From<Point<T>> for TaffyPoint<T2>
1193where
1194    T: Into<T2> + Clone + Debug + Default + PartialEq,
1195{
1196    fn from(val: Point<T>) -> Self {
1197        TaffyPoint {
1198            x: val.x.into(),
1199            y: val.y.into(),
1200        }
1201    }
1202}
1203
1204impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
1205where
1206    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
1207{
1208    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffySize<U> {
1209        TaffySize {
1210            width: self.width.to_taffy(rem_size, scale_factor),
1211            height: self.height.to_taffy(rem_size, scale_factor),
1212        }
1213    }
1214}
1215
1216impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
1217where
1218    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
1219{
1220    fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> TaffyRect<U> {
1221        TaffyRect {
1222            top: self.top.to_taffy(rem_size, scale_factor),
1223            right: self.right.to_taffy(rem_size, scale_factor),
1224            bottom: self.bottom.to_taffy(rem_size, scale_factor),
1225            left: self.left.to_taffy(rem_size, scale_factor),
1226        }
1227    }
1228}
1229
1230impl<T, U> From<TaffySize<T>> for Size<U>
1231where
1232    T: Into<U>,
1233    U: Clone + Debug + Default + PartialEq,
1234{
1235    fn from(taffy_size: TaffySize<T>) -> Self {
1236        Size {
1237            width: taffy_size.width.into(),
1238            height: taffy_size.height.into(),
1239        }
1240    }
1241}
1242
1243impl<T, U> From<Size<T>> for TaffySize<U>
1244where
1245    T: Into<U> + Clone + Debug + Default + PartialEq,
1246{
1247    fn from(size: Size<T>) -> Self {
1248        TaffySize {
1249            width: size.width.into(),
1250            height: size.height.into(),
1251        }
1252    }
1253}
1254
1255/// The space available for an element to be laid out in
1256#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
1257pub enum AvailableSpace {
1258    /// The amount of space available is the specified number of pixels
1259    Definite(Pixels),
1260    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
1261    #[default]
1262    MinContent,
1263    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
1264    MaxContent,
1265}
1266
1267impl AvailableSpace {
1268    /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
1269    ///
1270    /// This function is useful when you want to create a `Size` with the minimum content constraints
1271    /// for both dimensions.
1272    ///
1273    /// # Examples
1274    ///
1275    /// ```
1276    /// use gpui::AvailableSpace;
1277    /// let min_content_size = AvailableSpace::min_size();
1278    /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
1279    /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
1280    /// ```
1281    pub const fn min_size() -> Size<Self> {
1282        Size {
1283            width: Self::MinContent,
1284            height: Self::MinContent,
1285        }
1286    }
1287}
1288
1289impl From<AvailableSpace> for TaffyAvailableSpace {
1290    fn from(space: AvailableSpace) -> TaffyAvailableSpace {
1291        match space {
1292            AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
1293            AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
1294            AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
1295        }
1296    }
1297}
1298
1299impl From<TaffyAvailableSpace> for AvailableSpace {
1300    fn from(space: TaffyAvailableSpace) -> AvailableSpace {
1301        match space {
1302            TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
1303            TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
1304            TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
1305        }
1306    }
1307}
1308
1309impl From<Pixels> for AvailableSpace {
1310    fn from(pixels: Pixels) -> Self {
1311        AvailableSpace::Definite(pixels)
1312    }
1313}
1314
1315impl From<Size<Pixels>> for Size<AvailableSpace> {
1316    fn from(size: Size<Pixels>) -> Self {
1317        Size {
1318            width: AvailableSpace::Definite(size.width),
1319            height: AvailableSpace::Definite(size.height),
1320        }
1321    }
1322}
1323
1324#[cfg(test)]
1325mod tests {
1326    use super::*;
1327
1328    #[test]
1329    fn flex_and_grid_lay_their_children_out_in_order_modified_document_order() {
1330        let mut engine = TaffyLayoutEngine::new();
1331        let leaf = |engine: &mut TaffyLayoutEngine, order: i32| {
1332            let style = Style { vn_order: order, ..Default::default() };
1333            engine.request_layout(style, Pixels(16.0), 1.0, &[])
1334        };
1335        let kids = [leaf(&mut engine, 2), leaf(&mut engine, -1), leaf(&mut engine, 0), leaf(&mut engine, 2)];
1336        let laid_out = |engine: &mut TaffyLayoutEngine, display: Display| {
1337            let style = Style { display, ..Default::default() };
1338            let root = engine.request_layout(style, Pixels(16.0), 1.0, &kids);
1339            engine.taffy.child_ids(root.into()).map(LayoutId::from).collect::<Vec<_>>()
1340        };
1341        let modified = vec![kids[1], kids[2], kids[0], kids[3]];
1342        assert_eq!(laid_out(&mut engine, Display::Flex), modified);
1343        assert_eq!(laid_out(&mut engine, Display::Grid), modified);
1344        assert_eq!(laid_out(&mut engine, Display::Block), kids.to_vec());
1345        engine.clear();
1346        let fresh = [leaf(&mut engine, 0), leaf(&mut engine, 0)];
1347        let root = engine.request_layout(Style { display: Display::Flex, ..Default::default() }, Pixels(16.0), 1.0, &fresh);
1348        assert!(engine.taffy.child_ids(root.into()).map(LayoutId::from).eq(fresh));
1349    }
1350
1351    #[test]
1352    fn implicit_fractional_columns_share_the_container_width() {
1353        let mut tree = TaffyTree::<()>::new();
1354        let children: Vec<_> = (0..3).map(|_| tree.new_leaf(Default::default()).unwrap()).collect();
1355        let style = Style {
1356            display: crate::Display::Grid,
1357            size: Size {
1358                width: Length::Definite(Pixels(300.0).into()),
1359                height: Length::Definite(Pixels(40.0).into()),
1360            },
1361            vn_grid_auto_flow: Some(crate::GridAutoFlow::Column),
1362            vn_grid_auto_cols: Some(vec![crate::GridTrack::fr(1.0)]),
1363            ..Default::default()
1364        };
1365        let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1366        tree.compute_layout(root, TaffySize {
1367            width: TaffyAvailableSpace::Definite(300.0), height: TaffyAvailableSpace::Definite(40.0),
1368        }).unwrap();
1369        for (index, child) in children.into_iter().enumerate() {
1370            let layout = tree.layout(child).unwrap();
1371            assert_eq!(layout.size.width, 100.0);
1372            assert_eq!(layout.location.x, index as f32 * 100.0);
1373        }
1374    }
1375
1376    #[test]
1377    fn implicit_row_patterns_repeat_in_layout() {
1378        use crate::GridTrackSize as Track;
1379        let mut tree = TaffyTree::<()>::new();
1380        let children: Vec<_> = (0..5).map(|_| tree.new_leaf(Default::default()).unwrap()).collect();
1381        let style = Style {
1382            display: crate::Display::Grid,
1383            vn_grid_cols: Some(vec![crate::GridTrack::fixed(Track::Px(100.0))]),
1384            vn_grid_auto_rows: Some(vec![crate::GridTrack::fixed(Track::Px(20.0)), crate::GridTrack::fixed(Track::Px(35.0))]),
1385            ..Default::default()
1386        };
1387        let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1388        tree.compute_layout(root, TaffySize {
1389            width: TaffyAvailableSpace::MaxContent, height: TaffyAvailableSpace::MaxContent,
1390        }).unwrap();
1391        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) {
1392            let layout = tree.layout(child).unwrap();
1393            assert_eq!(layout.size.height, height);
1394            assert_eq!(layout.location.y, top);
1395        }
1396    }
1397
1398    #[test]
1399    fn implicit_auto_reset_replaces_a_fixed_row_pattern() {
1400        use crate::{GridTrack, GridTrackSize, Refineable, StyleRefinement};
1401        let mut style = Style {
1402            display: crate::Display::Grid,
1403            vn_grid_cols: Some(vec![GridTrack::fixed(GridTrackSize::Px(100.0))]),
1404            vn_grid_auto_rows: Some(vec![GridTrack::fixed(GridTrackSize::Px(50.0))]),
1405            ..Default::default()
1406        };
1407        style.refine(&StyleRefinement { vn_grid_auto_rows: Some(Vec::new()), ..Default::default() });
1408        let mut tree = TaffyTree::<()>::new();
1409        let children: Vec<_> = [17.0, 29.0].into_iter().map(|height| {
1410            let mut leaf_style = taffy::style::Style::default();
1411            leaf_style.size.height = taffy::style::Dimension::length(height);
1412            tree.new_leaf(leaf_style).unwrap()
1413        }).collect();
1414        let root = tree.new_with_children(style.to_taffy(Pixels(16.0), 1.0), &children).unwrap();
1415        tree.compute_layout(root, TaffySize {
1416            width: TaffyAvailableSpace::MaxContent, height: TaffyAvailableSpace::MaxContent,
1417        }).unwrap();
1418        assert_eq!(tree.layout(children[1]).unwrap().location.y, 17.0);
1419        assert_eq!(tree.layout(root).unwrap().size.height, 46.0);
1420    }
1421
1422    #[test]
1423    fn border_widths_to_taffy_use_stroke_snapping() {
1424        let border_widths = Edges {
1425            top: Pixels(0.0).into(),
1426            right: Pixels(0.4).into(),
1427            bottom: Pixels(0.5).into(),
1428            left: Pixels(1.6).into(),
1429        };
1430        let taffy_border = border_widths_to_taffy(&border_widths, Pixels(16.0), 1.0);
1431
1432        assert_eq!(
1433            taffy_border.top,
1434            taffy::style::LengthPercentage::length(0.0)
1435        );
1436        assert_eq!(
1437            taffy_border.right,
1438            taffy::style::LengthPercentage::length(1.0)
1439        );
1440        assert_eq!(
1441            taffy_border.bottom,
1442            taffy::style::LengthPercentage::length(1.0)
1443        );
1444        assert_eq!(
1445            taffy_border.left,
1446            taffy::style::LengthPercentage::length(2.0)
1447        );
1448    }
1449}