Skip to main content

mitsuami_core/
style.rs

1//! Layout style: the CSS flexbox / grid property set, in abstract units.
2
3use taffy::style_helpers::{TaffyGridLine, TaffyGridSpan};
4
5use crate::units::{Length, ResolveContext, Resolved};
6
7#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8pub enum Display {
9    #[default]
10    Flex,
11    Grid,
12    Block,
13    /// Not laid out and not visible.
14    None,
15}
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
18pub enum FlexDirection {
19    Row,
20    /// The default, as in React Native: app UIs stack vertically far more often.
21    #[default]
22    Column,
23    RowReverse,
24    ColumnReverse,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum Align {
29    Start,
30    End,
31    Center,
32    Stretch,
33    Baseline,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum Justify {
38    Start,
39    End,
40    Center,
41    Stretch,
42    SpaceBetween,
43    SpaceAround,
44    SpaceEvenly,
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub enum Position {
49    #[default]
50    Relative,
51    Absolute,
52}
53
54/// Layout direction. Styles use logical edges (`start` / `end`), so the same
55/// style works for left-to-right and right-to-left locales.
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
57pub enum TextDirection {
58    #[default]
59    Inherit,
60    Ltr,
61    Rtl,
62}
63
64/// Four edges in logical order: inline start/end, block top/bottom.
65#[derive(Clone, Copy, Debug, Default, PartialEq)]
66pub struct Edges {
67    pub start: Length,
68    pub end: Length,
69    pub top: Length,
70    pub bottom: Length,
71}
72
73impl Edges {
74    pub fn all(v: Length) -> Edges {
75        Edges { start: v, end: v, top: v, bottom: v }
76    }
77
78    pub fn zero() -> Edges {
79        Edges::all(Length::Px(0.0))
80    }
81}
82
83/// Where an item sits on one grid axis.
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub struct GridPlacement {
86    /// 1-based line to start at; negative counts from the end. `None` = auto-placed.
87    pub start: Option<i16>,
88    /// Number of tracks to span.
89    pub span: Option<u16>,
90}
91
92impl GridPlacement {
93    pub fn at(line: i16) -> GridPlacement {
94        GridPlacement { start: Some(line), span: None }
95    }
96
97    pub fn span(tracks: u16) -> GridPlacement {
98        GridPlacement { start: None, span: Some(tracks) }
99    }
100
101    pub fn at_span(line: i16, tracks: u16) -> GridPlacement {
102        GridPlacement { start: Some(line), span: Some(tracks) }
103    }
104}
105
106/// A grid track size: a length (`Fr` allowed), or a `minmax` pair.
107#[derive(Clone, Copy, Debug, PartialEq)]
108pub enum Track {
109    Size(Length),
110    MinMax(Length, Length),
111    MinContent,
112    MaxContent,
113}
114
115impl From<Length> for Track {
116    fn from(l: Length) -> Track {
117        Track::Size(l)
118    }
119}
120
121/// `repeat(3, 1.fr())`
122pub fn repeat(count: usize, track: impl Into<Track>) -> Vec<Track> {
123    vec![track.into(); count]
124}
125
126#[derive(Clone, Debug, PartialEq)]
127pub struct Style {
128    pub display: Display,
129    /// Hidden nodes act like `display: none` but keep their `display`.
130    pub hidden: bool,
131    pub position: Position,
132    pub direction: TextDirection,
133    /// Content may overflow along these axes and is scrolled natively.
134    /// Set by `ScrollView`; also lets it shrink below its content size.
135    pub scroll_x: bool,
136    pub scroll_y: bool,
137    pub inset: Edges,
138
139    pub width: Length,
140    pub height: Length,
141    pub min_width: Length,
142    pub min_height: Length,
143    pub max_width: Length,
144    pub max_height: Length,
145    pub aspect_ratio: Option<f32>,
146
147    pub margin: Edges,
148    pub padding: Edges,
149
150    pub flex_direction: FlexDirection,
151    pub flex_wrap: bool,
152    pub flex_grow: f32,
153    pub flex_shrink: f32,
154    pub flex_basis: Length,
155
156    pub align_items: Option<Align>,
157    pub align_self: Option<Align>,
158    /// Alignment inside a grid cell along the inline axis.
159    pub justify_self: Option<Align>,
160    pub align_content: Option<Justify>,
161    pub justify_content: Option<Justify>,
162    pub row_gap: Length,
163    pub column_gap: Length,
164
165    pub grid_template_columns: Vec<Track>,
166    pub grid_template_rows: Vec<Track>,
167    pub grid_column: GridPlacement,
168    pub grid_row: GridPlacement,
169}
170
171impl Default for Style {
172    fn default() -> Style {
173        Style {
174            display: Display::Flex,
175            hidden: false,
176            position: Position::Relative,
177            direction: TextDirection::Inherit,
178            scroll_x: false,
179            scroll_y: false,
180            inset: Edges::default(),
181            width: Length::Auto,
182            height: Length::Auto,
183            min_width: Length::Auto,
184            min_height: Length::Auto,
185            max_width: Length::Auto,
186            max_height: Length::Auto,
187            aspect_ratio: None,
188            margin: Edges::zero(),
189            padding: Edges::zero(),
190            flex_direction: FlexDirection::Column,
191            flex_wrap: false,
192            flex_grow: 0.0,
193            flex_shrink: 1.0,
194            flex_basis: Length::Auto,
195            align_items: None,
196            align_self: None,
197            justify_self: None,
198            align_content: None,
199            justify_content: None,
200            row_gap: Length::Px(0.0),
201            column_gap: Length::Px(0.0),
202            grid_template_columns: Vec::new(),
203            grid_template_rows: Vec::new(),
204            grid_column: GridPlacement::default(),
205            grid_row: GridPlacement::default(),
206        }
207    }
208}
209
210// ------------------------------------------------------------------ to Taffy
211
212fn dimension(l: Length, cx: &ResolveContext<'_>) -> taffy::Dimension {
213    match l.resolve(cx) {
214        Resolved::Length(v) => taffy::Dimension::length(v),
215        Resolved::Percent(v) => taffy::Dimension::percent(v),
216        Resolved::Fr(_) | Resolved::Auto => taffy::Dimension::auto(),
217    }
218}
219
220fn lpa(l: Length, cx: &ResolveContext<'_>) -> taffy::LengthPercentageAuto {
221    match l.resolve(cx) {
222        Resolved::Length(v) => taffy::LengthPercentageAuto::length(v),
223        Resolved::Percent(v) => taffy::LengthPercentageAuto::percent(v),
224        Resolved::Fr(_) | Resolved::Auto => taffy::LengthPercentageAuto::auto(),
225    }
226}
227
228fn lp(l: Length, cx: &ResolveContext<'_>) -> taffy::LengthPercentage {
229    match l.resolve(cx) {
230        Resolved::Length(v) => taffy::LengthPercentage::length(v),
231        Resolved::Percent(v) => taffy::LengthPercentage::percent(v),
232        Resolved::Fr(_) | Resolved::Auto => taffy::LengthPercentage::length(0.0),
233    }
234}
235
236fn min_track(l: Length, cx: &ResolveContext<'_>) -> taffy::MinTrackSizingFunction {
237    match l.resolve(cx) {
238        Resolved::Length(v) => taffy::MinTrackSizingFunction::length(v),
239        Resolved::Percent(v) => taffy::MinTrackSizingFunction::percent(v),
240        Resolved::Fr(_) | Resolved::Auto => taffy::MinTrackSizingFunction::auto(),
241    }
242}
243
244fn max_track(l: Length, cx: &ResolveContext<'_>) -> taffy::MaxTrackSizingFunction {
245    match l.resolve(cx) {
246        Resolved::Length(v) => taffy::MaxTrackSizingFunction::length(v),
247        Resolved::Percent(v) => taffy::MaxTrackSizingFunction::percent(v),
248        Resolved::Fr(v) => taffy::MaxTrackSizingFunction::fr(v),
249        Resolved::Auto => taffy::MaxTrackSizingFunction::auto(),
250    }
251}
252
253fn track(t: Track, cx: &ResolveContext<'_>) -> taffy::TrackSizingFunction {
254    match t {
255        // `1fr` in CSS is `minmax(auto, 1fr)`.
256        Track::Size(l) => taffy::MinMax { min: min_track(l, cx), max: max_track(l, cx) },
257        Track::MinMax(min, max) => taffy::MinMax { min: min_track(min, cx), max: max_track(max, cx) },
258        Track::MinContent => taffy::MinMax {
259            min: taffy::MinTrackSizingFunction::min_content(),
260            max: taffy::MaxTrackSizingFunction::min_content(),
261        },
262        Track::MaxContent => taffy::MinMax {
263            min: taffy::MinTrackSizingFunction::max_content(),
264            max: taffy::MaxTrackSizingFunction::max_content(),
265        },
266    }
267}
268
269fn placement(p: GridPlacement) -> taffy::Line<taffy::GridPlacement> {
270    let start = match p.start {
271        Some(line) => taffy::GridPlacement::from_line_index(line),
272        None => taffy::GridPlacement::Auto,
273    };
274    let end = match p.span {
275        Some(n) => taffy::GridPlacement::from_span(n),
276        None => taffy::GridPlacement::Auto,
277    };
278    taffy::Line { start, end }
279}
280
281fn align_items(a: Align) -> taffy::AlignItems {
282    match a {
283        Align::Start => taffy::AlignItems::START,
284        Align::End => taffy::AlignItems::END,
285        Align::Center => taffy::AlignItems::CENTER,
286        Align::Stretch => taffy::AlignItems::STRETCH,
287        Align::Baseline => taffy::AlignItems::BASELINE,
288    }
289}
290
291fn justify(j: Justify) -> taffy::JustifyContent {
292    match j {
293        Justify::Start => taffy::JustifyContent::START,
294        Justify::End => taffy::JustifyContent::END,
295        Justify::Center => taffy::JustifyContent::CENTER,
296        Justify::Stretch => taffy::JustifyContent::STRETCH,
297        Justify::SpaceBetween => taffy::JustifyContent::SPACE_BETWEEN,
298        Justify::SpaceAround => taffy::JustifyContent::SPACE_AROUND,
299        Justify::SpaceEvenly => taffy::JustifyContent::SPACE_EVENLY,
300    }
301}
302
303impl Style {
304    /// Resolves units and maps logical edges for the given direction.
305    pub(crate) fn to_taffy(&self, cx: &ResolveContext<'_>, rtl: bool) -> taffy::Style {
306        let edges_lpa = |e: &Edges| {
307            let (left, right) = if rtl { (e.end, e.start) } else { (e.start, e.end) };
308            taffy::Rect { left: lpa(left, cx), right: lpa(right, cx), top: lpa(e.top, cx), bottom: lpa(e.bottom, cx) }
309        };
310        let edges_lp = |e: &Edges| {
311            let (left, right) = if rtl { (e.end, e.start) } else { (e.start, e.end) };
312            taffy::Rect { left: lp(left, cx), right: lp(right, cx), top: lp(e.top, cx), bottom: lp(e.bottom, cx) }
313        };
314        taffy::Style {
315            display: match if self.hidden { Display::None } else { self.display } {
316                Display::Flex => taffy::Display::Flex,
317                Display::Grid => taffy::Display::Grid,
318                Display::Block => taffy::Display::Block,
319                Display::None => taffy::Display::None,
320            },
321            direction: if rtl { taffy::Direction::Rtl } else { taffy::Direction::Ltr },
322            position: match self.position {
323                Position::Relative => taffy::Position::Relative,
324                Position::Absolute => taffy::Position::Absolute,
325            },
326            inset: edges_lpa(&self.inset),
327            overflow: taffy::Point {
328                x: if self.scroll_x { taffy::Overflow::Scroll } else { taffy::Overflow::Visible },
329                y: if self.scroll_y { taffy::Overflow::Scroll } else { taffy::Overflow::Visible },
330            },
331            scrollbar_width: 0.0,
332            size: taffy::Size { width: dimension(self.width, cx), height: dimension(self.height, cx) },
333            min_size: taffy::Size { width: lpa(self.min_width, cx), height: lpa(self.min_height, cx) },
334            max_size: taffy::Size { width: lpa(self.max_width, cx), height: lpa(self.max_height, cx) },
335            aspect_ratio: self.aspect_ratio,
336            margin: edges_lpa(&self.margin),
337            padding: edges_lp(&self.padding),
338            flex_direction: match self.flex_direction {
339                FlexDirection::Row => taffy::FlexDirection::Row,
340                FlexDirection::Column => taffy::FlexDirection::Column,
341                FlexDirection::RowReverse => taffy::FlexDirection::RowReverse,
342                FlexDirection::ColumnReverse => taffy::FlexDirection::ColumnReverse,
343            },
344            flex_wrap: if self.flex_wrap { taffy::FlexWrap::Wrap } else { taffy::FlexWrap::NoWrap },
345            flex_grow: self.flex_grow,
346            flex_shrink: self.flex_shrink,
347            flex_basis: dimension(self.flex_basis, cx),
348            align_items: self.align_items.map(align_items),
349            align_self: self.align_self.map(align_items),
350            justify_self: self.justify_self.map(align_items),
351            align_content: self.align_content.map(justify),
352            justify_content: self.justify_content.map(justify),
353            gap: taffy::Size { width: lp(self.column_gap, cx), height: lp(self.row_gap, cx) },
354            grid_template_columns: self
355                .grid_template_columns
356                .iter()
357                .map(|t| taffy::GridTemplateComponent::Single(track(*t, cx)))
358                .collect(),
359            grid_template_rows: self
360                .grid_template_rows
361                .iter()
362                .map(|t| taffy::GridTemplateComponent::Single(track(*t, cx)))
363                .collect(),
364            grid_column: placement(self.grid_column),
365            grid_row: placement(self.grid_row),
366            ..taffy::Style::default()
367        }
368    }
369}
370
371impl Style {
372    /// Takes no space and is not shown.
373    pub fn is_hidden(&self) -> bool {
374        self.hidden || self.display == Display::None
375    }
376}
377
378macro_rules! static_value {
379    ($($t:ty),*) => {$(
380        impl mitsuami_reactive::IntoValue<$t> for $t {
381            fn into_value(self) -> mitsuami_reactive::Value<$t> {
382                mitsuami_reactive::Value::Static(self)
383            }
384        }
385    )*};
386}
387
388static_value!(Display, FlexDirection, Align, Justify, Position, TextDirection, GridPlacement);