Replace Number type with a simpler Option<f32> (#144)
1//! A representation of [CSS layout properties](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) in Rust, used for flexbox layout
2
3use crate::geometry::{Rect, Size};
4
5/// How [`Nodes`](crate::node::Node) are aligned relative to the cross axis
6///
7/// The default behavior is [`AlignItems::Stretch`].
8///
9/// [Specification](https://www.w3.org/TR/css-flexbox-1/#align-items-property)
10#[derive(Copy, Clone, PartialEq, Eq, Debug)]
11#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12pub enum AlignItems {
13 /// Items are packed toward the start of the cross axis
14 FlexStart,
15 /// Items are packed toward the end of the cross axis
16 FlexEnd,
17 /// Items are packed along the center of the cross axis
18 Center,
19 /// Items are aligned such as their baselines align
20 Baseline,
21 /// Stretch to fill the container
22 Stretch,
23}
24
25impl Default for AlignItems {
26 fn default() -> Self {
27 Self::Stretch
28 }
29}
30
31/// Overrides the inherited [`AlignItems`] behavior for this node.
32///
33/// The behavior of any child nodes will be controlled by this node's [`AlignItems`] value.
34///
35/// The default behavior is [`AlignSelf::Auto`].
36///
37/// [Specification](https://www.w3.org/TR/css-flexbox-1/#align-items-property)
38#[derive(Copy, Clone, PartialEq, Eq, Debug)]
39#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
40pub enum AlignSelf {
41 /// Inherits the [`AlignItems`] behavior of the parent
42 Auto,
43 /// Items are packed toward the start of the cross axis
44 FlexStart,
45 /// Items are packed toward the end of the cross axis
46 FlexEnd,
47 /// Items are packed along the center of the cross axis
48 Center,
49 /// Items are aligned such as their baselines align
50 Baseline,
51 /// Distribute items evenly, but stretch them to fill the container
52 Stretch,
53}
54
55impl Default for AlignSelf {
56 fn default() -> Self {
57 Self::Auto
58 }
59}
60
61/// Sets the distribution of space between and around content items along the cross-axis
62///
63/// The default value is [`AlignContent::Stretch`].
64///
65/// [Specification](https://www.w3.org/TR/css-flexbox-1/#align-content-property)
66#[derive(Copy, Clone, PartialEq, Eq, Debug)]
67#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
68pub enum AlignContent {
69 /// Items are packed toward the start of the cross axis
70 FlexStart,
71 /// Items are packed toward the end of the cross axis
72 FlexEnd,
73 /// Items are packed along the center of the cross axis
74 Center,
75 /// Distribute items evenly, but stretch them to fill the container
76 Stretch,
77 /// Distribute items evenly, such that the first and last item are aligned with the edges
78 SpaceBetween,
79 /// Distribute items evenly,
80 /// such that the space between items is the same as the space between the first and last item and the edges
81 SpaceAround,
82}
83
84impl Default for AlignContent {
85 fn default() -> Self {
86 Self::Stretch
87 }
88}
89
90/// Sets the layout used for the children of this node
91///
92/// [`Display::Flex`] is the default value.
93#[derive(Copy, Clone, PartialEq, Eq, Debug)]
94#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
95pub enum Display {
96 /// The children will follow the flexbox layout algorithm
97 Flex,
98 /// The children will not be laid out, and will follow absolute positioning
99 None,
100}
101
102impl Default for Display {
103 fn default() -> Self {
104 Self::Flex
105 }
106}
107
108/// The direction of the flexbox layout main axis.
109///
110/// There are always two perpendicular layout axes: main (or primary) and cross (or secondary).
111/// Adding items will cause them to be positioned adjacent to each other along the main axis.
112/// By varying this value throughout your tree, you can create complex axis-aligned layouts.
113///
114/// Items are always aligned relative to the cross axis, and justified relative to the main axis.
115///
116/// The default behavior is [`FlexDirection::Row`].
117///
118/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-direction-property)
119#[derive(Copy, Clone, PartialEq, Eq, Debug)]
120#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
121pub enum FlexDirection {
122 /// Defines +x as the main axis
123 ///
124 /// Items will be added from left to right in a row.
125 Row,
126 /// Defines +y as the main axis
127 ///
128 /// Items will be added from top to bottom in a column.
129 Column,
130 /// Defines -x as the main axis
131 ///
132 /// Items will be added from right to left in a row.
133 RowReverse,
134 /// Defines -y as the main axis
135 ///
136 /// Items will be added from bottom to top in a column.
137 ColumnReverse,
138}
139
140impl Default for FlexDirection {
141 fn default() -> Self {
142 Self::Row
143 }
144}
145
146impl FlexDirection {
147 #[inline]
148 /// Is the direction [`FlexDirection::Row`] or [`FlexDirection::RowReverse`]?
149 pub(crate) fn is_row(self) -> bool {
150 matches!(self, Self::Row | Self::RowReverse)
151 }
152
153 #[inline]
154 /// Is the direction [`FlexDirection::Column`] or [`FlexDirection::ColumnReverse`]?
155 pub(crate) fn is_column(self) -> bool {
156 matches!(self, Self::Column | Self::ColumnReverse)
157 }
158
159 #[inline]
160 /// Is the direction [`FlexDirection::RowReverse`] or [`FlexDirection::ColumnReverse`]?
161 pub(crate) fn is_reverse(self) -> bool {
162 matches!(self, Self::RowReverse | Self::ColumnReverse)
163 }
164}
165
166/// Sets the distribution of space between and around content items along the main-axis
167///
168/// The default value is [`JustifyContent::FlexStart`].
169///
170/// [Specification](https://www.w3.org/TR/css-flexbox-1/#justify-content-property)
171#[derive(Copy, Clone, PartialEq, Eq, Debug)]
172#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
173pub enum JustifyContent {
174 /// Items are packed toward the start of the main axis
175 FlexStart,
176 /// Items are packed toward the end of the main axis
177 FlexEnd,
178 /// Items are packed along the center of the main axis
179 Center,
180 /// Distribute items evenly, such that the first and last item are aligned with the edges
181 SpaceBetween,
182 /// Distribute items evenly,
183 /// such that the space between items is twice same as the space between the first and last item and the edges
184 SpaceAround,
185 /// Distribute items evenly,
186 /// such that the space between items is the same as the space between the first and last item and the edges
187 SpaceEvenly,
188}
189
190impl Default for JustifyContent {
191 fn default() -> Self {
192 Self::FlexStart
193 }
194}
195
196/// The positioning strategy for this item.
197///
198/// This controls both how the origin is determined for the [`Style::position`] field,
199/// and whether or not the item will be controlled by flexbox's layout algorithm.
200///
201/// WARNING: this enum follows the behavior of [CSS's `position` property](https://developer.mozilla.org/en-US/docs/Web/CSS/position),
202/// which can be unintuitive.
203///
204/// [`PositionType::Relative`] is the default value, in contrast to the default behavior in CSS.
205#[derive(Copy, Clone, PartialEq, Eq, Debug)]
206#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
207pub enum PositionType {
208 /// The offset is computed relative to the final position given by the layout algorithm.
209 /// Offsets do not affect the position of any other items; they are effectively a correction factor applied at the end.
210 Relative,
211 /// The offset is computed relative to this item's closest positioned ancestor, if any.
212 /// Otherwise, it is placed relative to the origin.
213 /// No space is created for the item in the page layout, and its size will not be altered.
214 ///
215 /// WARNING: to opt-out of layouting entirely, you must use [`Display::None`] instead on your [`Style`] object.
216 Absolute,
217}
218
219impl Default for PositionType {
220 fn default() -> Self {
221 Self::Relative
222 }
223}
224
225/// Controls whether flex items are forced onto one line or can wrap onto multiple lines.
226///
227/// Defaults to [`FlexWrap::NoWrap`]
228///
229/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-wrap-property)
230#[derive(Copy, Clone, PartialEq, Eq, Debug)]
231#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
232pub enum FlexWrap {
233 /// Items will not wrap and stay on a single line
234 NoWrap,
235 /// Items will wrap according to this item's [`FlexDirection`]
236 Wrap,
237 /// Items will wrap in the oppposite direction to this item's [`FlexDirection`]
238 WrapReverse,
239}
240
241impl Default for FlexWrap {
242 fn default() -> Self {
243 Self::NoWrap
244 }
245}
246
247/// A unit of linear measurement
248///
249/// This is commonly combined with [`Rect`], [`Point`](crate::geometry::Point) and [`Size<T>`].
250/// The default value is [`Dimension::Undefined`].
251#[derive(Copy, Clone, PartialEq, Debug)]
252#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
253pub enum Dimension {
254 /// The dimension is not given
255 Undefined,
256 /// The dimension should be automatically computed
257 Auto,
258 /// The dimension is stored in [points](https://en.wikipedia.org/wiki/Point_(typography))
259 ///
260 /// Each point is about 0.353 mm in size.
261 Points(f32),
262 /// The dimension is stored in percentage relative to the parent item.
263 Percent(f32),
264}
265
266impl Default for Dimension {
267 fn default() -> Self {
268 Self::Undefined
269 }
270}
271
272impl Dimension {
273 /// Converts the given [`Dimension`] into a concrete value of points
274 pub(crate) fn resolve(self, parent_dim: Option<f32>) -> Option<f32> {
275 match self {
276 Dimension::Points(points) => Some(points),
277 // parent_dim * percent
278 Dimension::Percent(percent) => parent_dim.map(|dim| dim * percent),
279 _ => None,
280 }
281 }
282
283 /// Is this value defined?
284 pub(crate) fn is_defined(self) -> bool {
285 matches!(self, Dimension::Points(_) | Dimension::Percent(_))
286 }
287}
288
289impl Default for Rect<Dimension> {
290 fn default() -> Self {
291 Self { start: Default::default(), end: Default::default(), top: Default::default(), bottom: Default::default() }
292 }
293}
294
295impl Default for Size<Dimension> {
296 fn default() -> Self {
297 Self { width: Dimension::Auto, height: Dimension::Auto }
298 }
299}
300
301/// The flexbox layout information for a single [`Node`](crate::node::Node).
302///
303/// The most important idea in flexbox is the notion of a "main" and "cross" axis, which are always perpendicular to each other.
304/// The orientation of these axes are controlled via the [`FlexDirection`] field of this struct.
305///
306/// This struct follows the [CSS equivalent](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) directly;
307/// information about the behavior on the web should transfer directly.
308///
309/// Detailed information about the exact behavior of each of these fields
310/// can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS) by searching for the field name.
311/// The distinction between margin, padding and border is explained well in
312/// this [introduction to the box model](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model).
313///
314/// If the behavior does not match the flexbox layout algorithm on the web, please file a bug!
315#[derive(Copy, Clone, PartialEq, Debug)]
316#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
317#[cfg_attr(feature = "serde", serde(default))]
318pub struct FlexboxLayout {
319 /// What layout strategy should be used?
320 pub display: Display,
321 /// What should the `position` value of this struct use as a base offset?
322 pub position_type: PositionType,
323 /// Which direction does the main axis flow in?
324 pub flex_direction: FlexDirection,
325 /// Should elements wrap, or stay in a single line?
326 pub flex_wrap: FlexWrap,
327 /// How should items be aligned relative to the cross axis?
328 pub align_items: AlignItems,
329 /// Should this item violate the cross axis alignment specified by its parent's [`AlignItems`]?
330 pub align_self: AlignSelf,
331 /// How should content contained within this item be aligned relative to the cross axis?
332 pub align_content: AlignContent,
333 /// How should items be aligned relative to the main axis?
334 pub justify_content: JustifyContent,
335 /// How should the position of this element be tweaked relative to the layout defined?
336 pub position: Rect<Dimension>,
337 /// How large should the margin be on each side?
338 pub margin: Rect<Dimension>,
339 /// How large should the padding be on each side?
340 pub padding: Rect<Dimension>,
341 /// How large should the border be on each side?
342 pub border: Rect<Dimension>,
343 /// The relative rate at which this item grows when it is expanding to fill space
344 ///
345 /// 0.0 is the default value, and this value must be positive.
346 pub flex_grow: f32,
347 /// The relative rate at which this item shrinks when it is contracting to fit into space
348 ///
349 /// 1.0 is the default value, and this value must be positive.
350 pub flex_shrink: f32,
351 /// Sets the initial main axis size of the item
352 pub flex_basis: Dimension,
353 /// Sets the initial size of the item
354 // TODO: why does this exist as distinct from flex_basis? How do they interact?
355 pub size: Size<Dimension>,
356 /// Controls the minimum size of the item
357 pub min_size: Size<Dimension>,
358 /// Controls the maximum size of the item
359 pub max_size: Size<Dimension>,
360 /// Sets the preferred aspect ratio for the item
361 ///
362 /// The ratio is calculated as width divided by height.
363 pub aspect_ratio: Option<f32>,
364}
365
366impl Default for FlexboxLayout {
367 fn default() -> Self {
368 Self {
369 display: Default::default(),
370 position_type: Default::default(),
371 flex_direction: Default::default(),
372 flex_wrap: Default::default(),
373 align_items: Default::default(),
374 align_self: Default::default(),
375 align_content: Default::default(),
376 justify_content: Default::default(),
377 position: Default::default(),
378 margin: Default::default(),
379 padding: Default::default(),
380 border: Default::default(),
381 flex_grow: 0.0,
382 flex_shrink: 1.0,
383 flex_basis: Dimension::Auto,
384 size: Default::default(),
385 min_size: Default::default(),
386 max_size: Default::default(),
387 aspect_ratio: Default::default(),
388 }
389 }
390}
391
392impl FlexboxLayout {
393 /// If the `direction` is row-oriented, the min width. Otherwise the min height
394 pub(crate) fn min_main_size(&self, direction: FlexDirection) -> Dimension {
395 if direction.is_row() {
396 self.min_size.width
397 } else {
398 self.min_size.height
399 }
400 }
401
402 /// If the `direction` is row-oriented, the max width. Otherwise the max height
403 pub(crate) fn max_main_size(&self, direction: FlexDirection) -> Dimension {
404 if direction.is_row() {
405 self.max_size.width
406 } else {
407 self.max_size.height
408 }
409 }
410
411 /// If the `direction` is row-oriented, the margin start. Otherwise the margin top
412 pub(crate) fn main_margin_start(&self, direction: FlexDirection) -> Dimension {
413 if direction.is_row() {
414 self.margin.start
415 } else {
416 self.margin.top
417 }
418 }
419
420 /// If the `direction` is row-oriented, the margin end. Otherwise the margin bottom
421 pub(crate) fn main_margin_end(&self, direction: FlexDirection) -> Dimension {
422 if direction.is_row() {
423 self.margin.end
424 } else {
425 self.margin.bottom
426 }
427 }
428
429 /// If the `direction` is row-oriented, the height. Otherwise the width
430 pub(crate) fn cross_size(&self, direction: FlexDirection) -> Dimension {
431 if direction.is_row() {
432 self.size.height
433 } else {
434 self.size.width
435 }
436 }
437
438 /// If the `direction` is row-oriented, the min height. Otherwise the min width
439 pub(crate) fn min_cross_size(&self, direction: FlexDirection) -> Dimension {
440 if direction.is_row() {
441 self.min_size.height
442 } else {
443 self.min_size.width
444 }
445 }
446
447 /// If the `direction` is row-oriented, the max height. Otherwise the max width
448 pub(crate) fn max_cross_size(&self, direction: FlexDirection) -> Dimension {
449 if direction.is_row() {
450 self.max_size.height
451 } else {
452 self.max_size.width
453 }
454 }
455
456 /// If the `direction` is row-oriented, the margin top. Otherwise the margin start
457 pub(crate) fn cross_margin_start(&self, direction: FlexDirection) -> Dimension {
458 if direction.is_row() {
459 self.margin.top
460 } else {
461 self.margin.start
462 }
463 }
464
465 /// If the `direction` is row-oriented, the margin bottom. Otherwise the margin end
466 pub(crate) fn cross_margin_end(&self, direction: FlexDirection) -> Dimension {
467 if direction.is_row() {
468 self.margin.bottom
469 } else {
470 self.margin.end
471 }
472 }
473
474 /// Computes the final alignment of this item based on the parent's [`AlignItems`] and this item's [`AlignSelf`]
475 pub(crate) fn align_self(&self, parent: &FlexboxLayout) -> AlignSelf {
476 if self.align_self == AlignSelf::Auto {
477 match parent.align_items {
478 AlignItems::FlexStart => AlignSelf::FlexStart,
479 AlignItems::FlexEnd => AlignSelf::FlexEnd,
480 AlignItems::Center => AlignSelf::Center,
481 AlignItems::Baseline => AlignSelf::Baseline,
482 AlignItems::Stretch => AlignSelf::Stretch,
483 }
484 } else {
485 self.align_self
486 }
487 }
488}