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