taffy/compute/common/
alignment.rs

1//! Generic CSS alignment code that is shared between both the Flexbox and CSS Grid algorithms.
2use crate::style::AlignContent;
3
4/// Generic alignment function that is used:
5///   - For both align-content and justify-content alignment
6///   - For both the Flexbox and CSS Grid algorithms
7/// CSS Grid does not apply gaps as part of alignment, so the gap parameter should
8/// always be set to zero for CSS Grid.
9pub(crate) fn compute_alignment_offset(
10    free_space: f32,
11    num_items: usize,
12    gap: f32,
13    alignment_mode: AlignContent,
14    layout_is_flex_reversed: bool,
15    is_first: bool,
16) -> f32 {
17    if is_first {
18        match alignment_mode {
19            AlignContent::Start => 0.0,
20            AlignContent::FlexStart => {
21                if layout_is_flex_reversed {
22                    free_space
23                } else {
24                    0.0
25                }
26            }
27            AlignContent::End => free_space,
28            AlignContent::FlexEnd => {
29                if layout_is_flex_reversed {
30                    0.0
31                } else {
32                    free_space
33                }
34            }
35            AlignContent::Center => free_space / 2.0,
36            AlignContent::Stretch => 0.0,
37            AlignContent::SpaceBetween => 0.0,
38            AlignContent::SpaceAround => {
39                if free_space >= 0.0 {
40                    (free_space / num_items as f32) / 2.0
41                } else {
42                    free_space / 2.0
43                }
44            }
45            AlignContent::SpaceEvenly => {
46                if free_space >= 0.0 {
47                    free_space / (num_items + 1) as f32
48                } else {
49                    free_space / 2.0
50                }
51            }
52        }
53    } else {
54        let free_space = free_space.max(0.0);
55        gap + match alignment_mode {
56            AlignContent::Start => 0.0,
57            AlignContent::FlexStart => 0.0,
58            AlignContent::End => 0.0,
59            AlignContent::FlexEnd => 0.0,
60            AlignContent::Center => 0.0,
61            AlignContent::Stretch => 0.0,
62            AlignContent::SpaceBetween => free_space / (num_items - 1) as f32,
63            AlignContent::SpaceAround => free_space / num_items as f32,
64            AlignContent::SpaceEvenly => free_space / (num_items + 1) as f32,
65        }
66    }
67}