tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 707HTML 660Markdown 12TOML 62344 Definiciones

⎇ 7b6efafe42c49ebdf1d84a7afe8ff4e62fda94ed src/compute/grid/alignment.rs Rust · 291 líneas · 11.8 KB Historia Quién tocó qué crudo

Convert algorithms to traitified styles 7b6efafe4 · Nico Burns ·

1//! Alignment of tracks and final positioning of items
2use super::types::GridTrack;
3use crate::compute::common::alignment::{apply_alignment_fallback, compute_alignment_offset};
4use crate::geometry::{InBothAbsAxis, Line, Point, Rect, Size};
5use crate::style::{AlignContent, AlignItems, AlignSelf, AvailableSpace, CoreStyle, GridItemStyle, Overflow, Position};
6use crate::tree::{Layout, LayoutPartialTreeExt, NodeId, SizingMode};
7use crate::util::sys::f32_max;
8use crate::util::{MaybeMath, MaybeResolve, ResolveOrZero};
9
10#[cfg(feature = "content_size")]
11use crate::compute::common::content_size::compute_content_size_contribution;
12use crate::LayoutGridContainer;
13
14/// Align the grid tracks within the grid according to the align-content (rows) or
15/// justify-content (columns) property. This only does anything if the size of the
16/// grid is not equal to the size of the grid container in the axis being aligned.
17pub(super) fn align_tracks(
18    grid_container_content_box_size: f32,
19    padding: Line<f32>,
20    border: Line<f32>,
21    tracks: &mut [GridTrack],
22    track_alignment_style: AlignContent,
23) {
24    let used_size: f32 = tracks.iter().map(|track| track.base_size).sum();
25    let free_space = grid_container_content_box_size - used_size;
26    let origin = padding.start + border.start;
27
28    // Count the number of non-collapsed tracks (not counting gutters)
29    let num_tracks = tracks.iter().skip(1).step_by(2).filter(|track| !track.is_collapsed).count();
30
31    // Grid layout treats gaps as full tracks rather than applying them at alignment so we
32    // simply pass zero here. Grid layout is never reversed.
33    let gap = 0.0;
34    let layout_is_reversed = false;
35    let is_safe = false; // TODO: Implement safe alignment
36    let track_alignment = apply_alignment_fallback(free_space, num_tracks, track_alignment_style, is_safe);
37
38    // Compute offsets
39    let mut total_offset = origin;
40    tracks.iter_mut().enumerate().for_each(|(i, track)| {
41        // Odd tracks are gutters (but slices are zero-indexed, so odd tracks have even indices)
42        let is_gutter = i % 2 == 0;
43
44        // The first non-gutter track is index 1
45        let is_first = i == 1;
46
47        let offset = if is_gutter {
48            0.0
49        } else {
50            compute_alignment_offset(free_space, num_tracks, gap, track_alignment, layout_is_reversed, is_first)
51        };
52
53        track.offset = total_offset + offset;
54        total_offset = total_offset + offset + track.base_size;
55    });
56}
57
58/// Align and size a grid item into it's final position
59pub(super) fn align_and_position_item(
60    tree: &mut impl LayoutGridContainer,
61    node: NodeId,
62    order: u32,
63    grid_area: Rect<f32>,
64    container_alignment_styles: InBothAbsAxis<Option<AlignItems>>,
65    baseline_shim: f32,
66) -> (Size<f32>, f32, f32) {
67    let grid_area_size = Size { width: grid_area.right - grid_area.left, height: grid_area.bottom - grid_area.top };
68
69    let style = tree.get_grid_child_style(node);
70
71    let overflow = style.overflow();
72    let scrollbar_width = style.scrollbar_width();
73    let aspect_ratio = style.aspect_ratio();
74    let justify_self = style.justify_self();
75    let align_self = style.align_self();
76
77    let position = style.position();
78    let inset_horizontal =
79        style.inset().horizontal_components().map(|size| size.resolve_to_option(grid_area_size.width));
80    let inset_vertical = style.inset().vertical_components().map(|size| size.resolve_to_option(grid_area_size.height));
81    let padding = style.padding().map(|p| p.resolve_or_zero(Some(grid_area_size.width)));
82    let border = style.border().map(|p| p.resolve_or_zero(Some(grid_area_size.width)));
83    let padding_border_size = (padding + border).sum_axes();
84    let inherent_size = style.size().maybe_resolve(grid_area_size).maybe_apply_aspect_ratio(aspect_ratio);
85    let min_size = style
86        .min_size()
87        .maybe_resolve(grid_area_size)
88        .or(padding_border_size.map(Some))
89        .maybe_max(padding_border_size)
90        .maybe_apply_aspect_ratio(aspect_ratio);
91    let max_size = style.max_size().maybe_resolve(grid_area_size).maybe_apply_aspect_ratio(aspect_ratio);
92
93    // Resolve default alignment styles if they are set on neither the parent or the node itself
94    // Note: if the child has a preferred aspect ratio but neither width or height are set, then the width is stretched
95    // and the then height is calculated from the width according the aspect ratio
96    // See: https://www.w3.org/TR/css-grid-1/#grid-item-sizing
97    let alignment_styles = InBothAbsAxis {
98        horizontal: justify_self.or(container_alignment_styles.horizontal).unwrap_or_else(|| {
99            if inherent_size.width.is_some() {
100                AlignSelf::Start
101            } else {
102                AlignSelf::Stretch
103            }
104        }),
105        vertical: align_self.or(container_alignment_styles.vertical).unwrap_or_else(|| {
106            if inherent_size.height.is_some() || aspect_ratio.is_some() {
107                AlignSelf::Start
108            } else {
109                AlignSelf::Stretch
110            }
111        }),
112    };
113
114    // Note: This is not a bug. It is part of the CSS spec that both horizontal and vertical margins
115    // resolve against the WIDTH of the grid area.
116    let margin = style.margin().map(|margin| margin.resolve_to_option(grid_area_size.width));
117
118    let grid_area_minus_item_margins_size = Size {
119        width: grid_area_size.width.maybe_sub(margin.left).maybe_sub(margin.right),
120        height: grid_area_size.height.maybe_sub(margin.top).maybe_sub(margin.bottom) - baseline_shim,
121    };
122
123    // If node is absolutely positioned and width is not set explicitly, then deduce it
124    // from left, right and container_content_box if both are set.
125    let width = inherent_size.width.or_else(|| {
126        // Apply width derived from both the left and right properties of an absolutely
127        // positioned element being set
128        if position == Position::Absolute {
129            if let (Some(left), Some(right)) = (inset_horizontal.start, inset_horizontal.end) {
130                return Some(f32_max(grid_area_minus_item_margins_size.width - left - right, 0.0));
131            }
132        }
133
134        // Apply width based on stretch alignment if:
135        //  - Alignment style is "stretch"
136        //  - The node is not absolutely positioned
137        //  - The node does not have auto margins in this axis.
138        if margin.left.is_some()
139            && margin.right.is_some()
140            && alignment_styles.horizontal == AlignSelf::Stretch
141            && position != Position::Absolute
142        {
143            return Some(grid_area_minus_item_margins_size.width);
144        }
145
146        None
147    });
148
149    // Reapply aspect ratio after stretch and absolute position width adjustments
150    let Size { width, height } = Size { width, height: inherent_size.height }.maybe_apply_aspect_ratio(aspect_ratio);
151
152    let height = height.or_else(|| {
153        if position == Position::Absolute {
154            if let (Some(top), Some(bottom)) = (inset_vertical.start, inset_vertical.end) {
155                return Some(f32_max(grid_area_minus_item_margins_size.height - top - bottom, 0.0));
156            }
157        }
158
159        // Apply height based on stretch alignment if:
160        //  - Alignment style is "stretch"
161        //  - The node is not absolutely positioned
162        //  - The node does not have auto margins in this axis.
163        if margin.top.is_some()
164            && margin.bottom.is_some()
165            && alignment_styles.vertical == AlignSelf::Stretch
166            && position != Position::Absolute
167        {
168            return Some(grid_area_minus_item_margins_size.height);
169        }
170
171        None
172    });
173    // Reapply aspect ratio after stretch and absolute position height adjustments
174    let Size { width, height } = Size { width, height }.maybe_apply_aspect_ratio(aspect_ratio);
175
176    // Clamp size by min and max width/height
177    let Size { width, height } = Size { width, height }.maybe_clamp(min_size, max_size);
178
179    // Layout node
180    drop(style);
181    let layout_output = tree.perform_child_layout(
182        node,
183        Size { width, height },
184        grid_area_size.map(Option::Some),
185        grid_area_minus_item_margins_size.map(AvailableSpace::Definite),
186        SizingMode::InherentSize,
187        Line::FALSE,
188    );
189
190    // Resolve final size
191    let Size { width, height } = Size { width, height }.unwrap_or(layout_output.size).maybe_clamp(min_size, max_size);
192
193    let x = align_item_within_area(
194        Line { start: grid_area.left, end: grid_area.right },
195        justify_self.unwrap_or(alignment_styles.horizontal),
196        width,
197        position,
198        inset_horizontal,
199        margin.horizontal_components(),
200        0.0,
201    );
202    let y = align_item_within_area(
203        Line { start: grid_area.top, end: grid_area.bottom },
204        align_self.unwrap_or(alignment_styles.vertical),
205        height,
206        position,
207        inset_vertical,
208        margin.vertical_components(),
209        baseline_shim,
210    );
211
212    let scrollbar_size = Size {
213        width: if overflow.y == Overflow::Scroll { scrollbar_width } else { 0.0 },
214        height: if overflow.x == Overflow::Scroll { scrollbar_width } else { 0.0 },
215    };
216
217    tree.set_unrounded_layout(
218        node,
219        &Layout {
220            order,
221            location: Point { x, y },
222            size: Size { width, height },
223            #[cfg(feature = "content_size")]
224            content_size: layout_output.content_size,
225            scrollbar_size,
226            padding,
227            border,
228        },
229    );
230
231    #[cfg(feature = "content_size")]
232    let contribution =
233        compute_content_size_contribution(Point { x, y }, Size { width, height }, layout_output.content_size, overflow);
234    #[cfg(not(feature = "content_size"))]
235    let contribution = Size::ZERO;
236
237    (contribution, y, height)
238}
239
240/// Align and size a grid item along a single axis
241pub(super) fn align_item_within_area(
242    grid_area: Line<f32>,
243    alignment_style: AlignSelf,
244    resolved_size: f32,
245    position: Position,
246    inset: Line<Option<f32>>,
247    margin: Line<Option<f32>>,
248    baseline_shim: f32,
249) -> f32 {
250    // Calculate grid area dimension in the axis
251    let non_auto_margin = Line { start: margin.start.unwrap_or(0.0) + baseline_shim, end: margin.end.unwrap_or(0.0) };
252    let grid_area_size = f32_max(grid_area.end - grid_area.start, 0.0);
253    let free_space = f32_max(grid_area_size - resolved_size - non_auto_margin.sum(), 0.0);
254
255    // Expand auto margins to fill available space
256    let auto_margin_count = margin.start.is_none() as u8 + margin.end.is_none() as u8;
257    let auto_margin_size = if auto_margin_count > 0 { free_space / auto_margin_count as f32 } else { 0.0 };
258    let resolved_margin = Line {
259        start: margin.start.unwrap_or(auto_margin_size) + baseline_shim,
260        end: margin.end.unwrap_or(auto_margin_size),
261    };
262
263    // Compute offset in the axis
264    let alignment_based_offset = match alignment_style {
265        AlignSelf::Start | AlignSelf::FlexStart => resolved_margin.start,
266        AlignSelf::End | AlignSelf::FlexEnd => grid_area_size - resolved_size - resolved_margin.end,
267        AlignSelf::Center => (grid_area_size - resolved_size + resolved_margin.start - resolved_margin.end) / 2.0,
268        // TODO: Add support for baseline alignment. For now we treat it as "start".
269        AlignSelf::Baseline => resolved_margin.start,
270        AlignSelf::Stretch => resolved_margin.start,
271    };
272
273    let offset_within_area = if position == Position::Absolute {
274        if let Some(start) = inset.start {
275            start + non_auto_margin.start
276        } else if let Some(end) = inset.end {
277            grid_area_size - end - resolved_size - non_auto_margin.end
278        } else {
279            alignment_based_offset
280        }
281    } else {
282        alignment_based_offset
283    };
284
285    let mut start = grid_area.start + offset_within_area;
286    if position == Position::Relative {
287        start += inset.start.or(inset.end.map(|pos| -pos)).unwrap_or(0.0);
288    }
289
290    start
291}