Add inherent method constructors to style dimension types (#788)
1//! Style types for CSS Grid layout
2use super::{
3 AlignContent, AlignItems, AlignSelf, CompactLength, CoreStyle, Dimension, JustifyContent, LengthPercentage,
4 LengthPercentageAuto, Style,
5};
6use crate::compute::grid::{GridCoordinate, GridLine, OriginZeroLine};
7use crate::geometry::{AbsoluteAxis, AbstractAxis, Line, MinMax, Size};
8use crate::style_helpers::*;
9use crate::util::sys::GridTrackVec;
10use core::borrow::Borrow;
11use core::cmp::{max, min};
12use core::convert::Infallible;
13
14/// The set of styles required for a CSS Grid container
15pub trait GridContainerStyle: CoreStyle {
16 /// The type returned by grid_template_rows and grid_template_columns
17 type TemplateTrackList<'a>: Borrow<[TrackSizingFunction]>
18 where
19 Self: 'a;
20 /// The type returned by grid_auto_rows and grid_auto_columns
21 type AutoTrackList<'a>: Borrow<[NonRepeatedTrackSizingFunction]>
22 where
23 Self: 'a;
24
25 // FIXME: re-add default implemenations for grid_{template,auto}_{rows,columns} once the
26 // associated_type_defaults feature (https://github.com/rust-lang/rust/issues/29661) is stabilised.
27
28 /// Defines the track sizing functions (heights) of the grid rows
29 fn grid_template_rows(&self) -> Self::TemplateTrackList<'_>;
30 /// Defines the track sizing functions (widths) of the grid columns
31 fn grid_template_columns(&self) -> Self::TemplateTrackList<'_>;
32 /// Defines the size of implicitly created rows
33 fn grid_auto_rows(&self) -> Self::AutoTrackList<'_>;
34 /// Defined the size of implicitly created columns
35 fn grid_auto_columns(&self) -> Self::AutoTrackList<'_>;
36
37 /// Controls how items get placed into the grid for auto-placed items
38 #[inline(always)]
39 fn grid_auto_flow(&self) -> GridAutoFlow {
40 Style::DEFAULT.grid_auto_flow
41 }
42
43 /// How large should the gaps between items in a grid or flex container be?
44 #[inline(always)]
45 fn gap(&self) -> Size<LengthPercentage> {
46 Style::DEFAULT.gap
47 }
48
49 // Alignment properties
50
51 /// How should content contained within this item be aligned in the cross/block axis
52 #[inline(always)]
53 fn align_content(&self) -> Option<AlignContent> {
54 Style::DEFAULT.align_content
55 }
56 /// How should contained within this item be aligned in the main/inline axis
57 #[inline(always)]
58 fn justify_content(&self) -> Option<JustifyContent> {
59 Style::DEFAULT.justify_content
60 }
61 /// How this node's children aligned in the cross/block axis?
62 #[inline(always)]
63 fn align_items(&self) -> Option<AlignItems> {
64 Style::DEFAULT.align_items
65 }
66 /// How this node's children should be aligned in the inline axis
67 #[inline(always)]
68 fn justify_items(&self) -> Option<AlignItems> {
69 Style::DEFAULT.justify_items
70 }
71
72 /// Get a grid item's row or column placement depending on the axis passed
73 #[inline(always)]
74 fn grid_template_tracks(&self, axis: AbsoluteAxis) -> Self::TemplateTrackList<'_> {
75 match axis {
76 AbsoluteAxis::Horizontal => self.grid_template_columns(),
77 AbsoluteAxis::Vertical => self.grid_template_rows(),
78 }
79 }
80
81 /// Get a grid container's align-content or justify-content alignment depending on the axis passed
82 #[inline(always)]
83 fn grid_align_content(&self, axis: AbstractAxis) -> AlignContent {
84 match axis {
85 AbstractAxis::Inline => self.justify_content().unwrap_or(AlignContent::Stretch),
86 AbstractAxis::Block => self.align_content().unwrap_or(AlignContent::Stretch),
87 }
88 }
89}
90
91/// The set of styles required for a CSS Grid item (child of a CSS Grid container)
92pub trait GridItemStyle: CoreStyle {
93 /// Defines which row in the grid the item should start and end at
94 #[inline(always)]
95 fn grid_row(&self) -> Line<GridPlacement> {
96 Style::DEFAULT.grid_row
97 }
98 /// Defines which column in the grid the item should start and end at
99 #[inline(always)]
100 fn grid_column(&self) -> Line<GridPlacement> {
101 Style::DEFAULT.grid_column
102 }
103
104 /// How this node should be aligned in the cross/block axis
105 /// Falls back to the parents [`AlignItems`] if not set
106 #[inline(always)]
107 fn align_self(&self) -> Option<AlignSelf> {
108 Style::DEFAULT.align_self
109 }
110 /// How this node should be aligned in the inline axis
111 /// Falls back to the parents [`super::JustifyItems`] if not set
112 #[inline(always)]
113 fn justify_self(&self) -> Option<AlignSelf> {
114 Style::DEFAULT.justify_self
115 }
116
117 /// Get a grid item's row or column placement depending on the axis passed
118 #[inline(always)]
119 fn grid_placement(&self, axis: AbsoluteAxis) -> Line<GridPlacement> {
120 match axis {
121 AbsoluteAxis::Horizontal => self.grid_column(),
122 AbsoluteAxis::Vertical => self.grid_row(),
123 }
124 }
125}
126
127/// Controls whether grid items are placed row-wise or column-wise. And whether the sparse or dense packing algorithm is used.
128///
129/// The "dense" packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later. This may cause items to appear out-of-order, when doing so would fill in holes left by larger items.
130///
131/// Defaults to [`GridAutoFlow::Row`]
132///
133/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow)
134#[derive(Copy, Clone, PartialEq, Eq, Debug)]
135#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
136pub enum GridAutoFlow {
137 /// Items are placed by filling each row in turn, adding new rows as necessary
138 Row,
139 /// Items are placed by filling each column in turn, adding new columns as necessary.
140 Column,
141 /// Combines `Row` with the dense packing algorithm.
142 RowDense,
143 /// Combines `Column` with the dense packing algorithm.
144 ColumnDense,
145}
146
147impl Default for GridAutoFlow {
148 fn default() -> Self {
149 Self::Row
150 }
151}
152
153impl GridAutoFlow {
154 /// Whether grid auto placement uses the sparse placement algorithm or the dense placement algorithm
155 /// See: <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow#values>
156 pub fn is_dense(&self) -> bool {
157 match self {
158 Self::Row | Self::Column => false,
159 Self::RowDense | Self::ColumnDense => true,
160 }
161 }
162
163 /// Whether grid auto placement fills areas row-wise or column-wise
164 /// See: <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow#values>
165 pub fn primary_axis(&self) -> AbsoluteAxis {
166 match self {
167 Self::Row | Self::RowDense => AbsoluteAxis::Horizontal,
168 Self::Column | Self::ColumnDense => AbsoluteAxis::Vertical,
169 }
170 }
171}
172
173/// A grid line placement specification which is generic over the coordinate system that it uses to define
174/// grid line positions.
175///
176/// GenericGridPlacement<GridLine> is aliased as GridPlacement and is exposed to users of Taffy to define styles.
177/// GenericGridPlacement<OriginZeroLine> is aliased as OriginZeroGridPlacement and is used internally for placement computations.
178///
179/// See [`crate::compute::grid::type::coordinates`] for documentation on the different coordinate systems.
180#[derive(Copy, Clone, PartialEq, Eq, Debug)]
181#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
182pub enum GenericGridPlacement<LineType: GridCoordinate> {
183 /// Place item according to the auto-placement algorithm, and the parent's grid_auto_flow property
184 Auto,
185 /// Place item at specified line (column or row) index
186 Line(LineType),
187 /// Item should span specified number of tracks (columns or rows)
188 Span(u16),
189}
190
191/// A grid line placement using the normalized OriginZero coordinates to specify line positions.
192pub(crate) type OriginZeroGridPlacement = GenericGridPlacement<OriginZeroLine>;
193
194/// A grid line placement specification. Used for grid-[row/column]-[start/end]. Named tracks are not implemented.
195///
196/// Defaults to `GridPlacement::Auto`
197///
198/// [Specification](https://www.w3.org/TR/css3-grid-layout/#typedef-grid-row-start-grid-line)
199pub type GridPlacement = GenericGridPlacement<GridLine>;
200impl TaffyAuto for GridPlacement {
201 const AUTO: Self = Self::Auto;
202}
203impl TaffyGridLine for GridPlacement {
204 fn from_line_index(index: i16) -> Self {
205 GridPlacement::Line(GridLine::from(index))
206 }
207}
208impl TaffyGridLine for Line<GridPlacement> {
209 fn from_line_index(index: i16) -> Self {
210 Line { start: GridPlacement::from_line_index(index), end: GridPlacement::Auto }
211 }
212}
213impl TaffyGridSpan for GridPlacement {
214 fn from_span(span: u16) -> Self {
215 GridPlacement::Span(span)
216 }
217}
218impl TaffyGridSpan for Line<GridPlacement> {
219 fn from_span(span: u16) -> Self {
220 Line { start: GridPlacement::from_span(span), end: GridPlacement::Auto }
221 }
222}
223
224impl Default for GridPlacement {
225 fn default() -> Self {
226 Self::Auto
227 }
228}
229
230impl GridPlacement {
231 /// Apply a mapping function if the [`GridPlacement`] is a `Track`. Otherwise return `self` unmodified.
232 pub fn into_origin_zero_placement(self, explicit_track_count: u16) -> OriginZeroGridPlacement {
233 match self {
234 Self::Auto => OriginZeroGridPlacement::Auto,
235 Self::Span(span) => OriginZeroGridPlacement::Span(span),
236 // Grid line zero is an invalid index, so it gets treated as Auto
237 // See: https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row-start#values
238 Self::Line(line) => match line.as_i16() {
239 0 => OriginZeroGridPlacement::Auto,
240 _ => OriginZeroGridPlacement::Line(line.into_origin_zero_line(explicit_track_count)),
241 },
242 }
243 }
244}
245
246impl<T: GridCoordinate> Line<GenericGridPlacement<T>> {
247 /// Resolves the span for an indefinite placement (a placement that does not consist of two `Track`s).
248 /// Panics if called on a definite placement
249 pub fn indefinite_span(&self) -> u16 {
250 use GenericGridPlacement as GP;
251 match (self.start, self.end) {
252 (GP::Line(_), GP::Auto) => 1,
253 (GP::Auto, GP::Line(_)) => 1,
254 (GP::Auto, GP::Auto) => 1,
255 (GP::Line(_), GP::Span(span)) => span,
256 (GP::Span(span), GP::Line(_)) => span,
257 (GP::Span(span), GP::Auto) => span,
258 (GP::Auto, GP::Span(span)) => span,
259 (GP::Span(span), GP::Span(_)) => span,
260 (GP::Line(_), GP::Line(_)) => panic!("indefinite_span should only be called on indefinite grid tracks"),
261 }
262 }
263}
264
265impl Line<GridPlacement> {
266 #[inline]
267 /// Whether the track position is definite in this axis (or the item will need auto placement)
268 /// The track position is definite if least one of the start and end positions is a NON-ZERO track index
269 /// (0 is an invalid line in GridLine coordinates, and falls back to "auto" which is indefinite)
270 pub fn is_definite(&self) -> bool {
271 match (self.start, self.end) {
272 (GenericGridPlacement::Line(line), _) if line.as_i16() != 0 => true,
273 (_, GenericGridPlacement::Line(line)) if line.as_i16() != 0 => true,
274 _ => false,
275 }
276 }
277
278 /// Apply a mapping function if the [`GridPlacement`] is a `Track`. Otherwise return `self` unmodified.
279 pub fn into_origin_zero(&self, explicit_track_count: u16) -> Line<OriginZeroGridPlacement> {
280 Line {
281 start: self.start.into_origin_zero_placement(explicit_track_count),
282 end: self.end.into_origin_zero_placement(explicit_track_count),
283 }
284 }
285}
286
287impl Line<OriginZeroGridPlacement> {
288 #[inline]
289 /// Whether the track position is definite in this axis (or the item will need auto placement)
290 /// The track position is definite if least one of the start and end positions is a track index
291 pub fn is_definite(&self) -> bool {
292 matches!((self.start, self.end), (GenericGridPlacement::Line(_), _) | (_, GenericGridPlacement::Line(_)))
293 }
294
295 /// If at least one of the of the start and end positions is a track index then the other end can be resolved
296 /// into a track index purely based on the information contained with the placement specification
297 pub fn resolve_definite_grid_lines(&self) -> Line<OriginZeroLine> {
298 use OriginZeroGridPlacement as GP;
299 match (self.start, self.end) {
300 (GP::Line(line1), GP::Line(line2)) => {
301 if line1 == line2 {
302 Line { start: line1, end: line1 + 1 }
303 } else {
304 Line { start: min(line1, line2), end: max(line1, line2) }
305 }
306 }
307 (GP::Line(line), GP::Span(span)) => Line { start: line, end: line + span },
308 (GP::Line(line), GP::Auto) => Line { start: line, end: line + 1 },
309 (GP::Span(span), GP::Line(line)) => Line { start: line - span, end: line },
310 (GP::Auto, GP::Line(line)) => Line { start: line - 1, end: line },
311 _ => panic!("resolve_definite_grid_tracks should only be called on definite grid tracks"),
312 }
313 }
314
315 /// For absolutely positioned items:
316 /// - Tracks resolve to definite tracks
317 /// - For Spans:
318 /// - If the other position is a Track, they resolve to a definite track relative to the other track
319 /// - Else resolve to None
320 /// - Auto resolves to None
321 ///
322 /// When finally positioning the item, a value of None means that the item's grid area is bounded by the grid
323 /// container's border box on that side.
324 pub fn resolve_absolutely_positioned_grid_tracks(&self) -> Line<Option<OriginZeroLine>> {
325 use OriginZeroGridPlacement as GP;
326 match (self.start, self.end) {
327 (GP::Line(track1), GP::Line(track2)) => {
328 if track1 == track2 {
329 Line { start: Some(track1), end: Some(track1 + 1) }
330 } else {
331 Line { start: Some(min(track1, track2)), end: Some(max(track1, track2)) }
332 }
333 }
334 (GP::Line(track), GP::Span(span)) => Line { start: Some(track), end: Some(track + span) },
335 (GP::Line(track), GP::Auto) => Line { start: Some(track), end: None },
336 (GP::Span(span), GP::Line(track)) => Line { start: Some(track - span), end: Some(track) },
337 (GP::Auto, GP::Line(track)) => Line { start: None, end: Some(track) },
338 _ => Line { start: None, end: None },
339 }
340 }
341
342 /// If neither of the start and end positions is a track index then the other end can be resolved
343 /// into a track index if a definite start position is supplied externally
344 pub fn resolve_indefinite_grid_tracks(&self, start: OriginZeroLine) -> Line<OriginZeroLine> {
345 use OriginZeroGridPlacement as GP;
346 match (self.start, self.end) {
347 (GP::Auto, GP::Auto) => Line { start, end: start + 1 },
348 (GP::Span(span), GP::Auto) => Line { start, end: start + span },
349 (GP::Auto, GP::Span(span)) => Line { start, end: start + span },
350 (GP::Span(span), GP::Span(_)) => Line { start, end: start + span },
351 _ => panic!("resolve_indefinite_grid_tracks should only be called on indefinite grid tracks"),
352 }
353 }
354}
355
356/// Represents the start and end points of a GridItem within a given axis
357impl Default for Line<GridPlacement> {
358 fn default() -> Self {
359 Line { start: GridPlacement::Auto, end: GridPlacement::Auto }
360 }
361}
362
363/// Maximum track sizing function
364///
365/// Specifies the maximum size of a grid track. A grid track will automatically size between it's minimum and maximum size based
366/// on the size of it's contents, the amount of available space, and the sizing constraint the grid is being size under.
367/// See <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns>
368#[derive(Copy, Clone, PartialEq, Debug)]
369#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
370pub struct MaxTrackSizingFunction(pub(crate) CompactLength);
371impl TaffyZero for MaxTrackSizingFunction {
372 const ZERO: Self = Self(CompactLength::ZERO);
373}
374impl TaffyAuto for MaxTrackSizingFunction {
375 const AUTO: Self = Self(CompactLength::AUTO);
376}
377impl TaffyMinContent for MaxTrackSizingFunction {
378 const MIN_CONTENT: Self = Self(CompactLength::MIN_CONTENT);
379}
380impl TaffyMaxContent for MaxTrackSizingFunction {
381 const MAX_CONTENT: Self = Self(CompactLength::MAX_CONTENT);
382}
383impl FromLength for MaxTrackSizingFunction {
384 fn from_length<Input: Into<f32> + Copy>(value: Input) -> Self {
385 Self::length(value.into())
386 }
387}
388impl FromPercent for MaxTrackSizingFunction {
389 fn from_percent<Input: Into<f32> + Copy>(value: Input) -> Self {
390 Self::percent(value.into())
391 }
392}
393impl TaffyFitContent for MaxTrackSizingFunction {
394 fn fit_content(argument: LengthPercentage) -> Self {
395 Self(CompactLength::fit_content(argument))
396 }
397}
398impl FromFr for MaxTrackSizingFunction {
399 fn from_fr<Input: Into<f32> + Copy>(value: Input) -> Self {
400 Self::fr(value.into())
401 }
402}
403impl From<LengthPercentage> for MaxTrackSizingFunction {
404 fn from(input: LengthPercentage) -> Self {
405 Self(input.0)
406 }
407}
408impl From<LengthPercentageAuto> for MaxTrackSizingFunction {
409 fn from(input: LengthPercentageAuto) -> Self {
410 Self(input.0)
411 }
412}
413impl From<Dimension> for MaxTrackSizingFunction {
414 fn from(input: Dimension) -> Self {
415 Self(input.0)
416 }
417}
418impl From<MinTrackSizingFunction> for MaxTrackSizingFunction {
419 fn from(input: MinTrackSizingFunction) -> Self {
420 Self(input.0)
421 }
422}
423
424impl MaxTrackSizingFunction {
425 /// An absolute length in some abstract units. Users of Taffy may define what they correspond
426 /// to in their application (pixels, logical pixels, mm, etc) as they see fit.
427 #[inline(always)]
428 pub const fn length(val: f32) -> Self {
429 Self(CompactLength::length(val))
430 }
431
432 /// A percentage length relative to the size of the containing block.
433 ///
434 /// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
435 #[inline(always)]
436 pub const fn percent(val: f32) -> Self {
437 Self(CompactLength::percent(val))
438 }
439
440 /// The dimension should be automatically computed according to algorithm-specific rules
441 /// regarding the default size of boxes.
442 #[inline(always)]
443 pub const fn auto() -> Self {
444 Self(CompactLength::auto())
445 }
446
447 /// The size should be the "min-content" size.
448 /// This is the smallest size that can fit the item's contents with ALL soft line-wrapping opportunities taken
449 #[inline(always)]
450 pub const fn min_content() -> Self {
451 Self(CompactLength::min_content())
452 }
453
454 /// The size should be the "max-content" size.
455 /// This is the smallest size that can fit the item's contents with NO soft line-wrapping opportunities taken
456 #[inline(always)]
457 pub const fn max_content() -> Self {
458 Self(CompactLength::max_content())
459 }
460
461 /// The size should be computed according to the "fit content" formula:
462 /// `max(min_content, min(max_content, limit))`
463 /// where:
464 /// - `min_content` is the [min-content](Self::min_content) size
465 /// - `max_content` is the [max-content](Self::max_content) size
466 /// - `limit` is a LENGTH value passed to this function
467 ///
468 /// The effect of this is that the item takes the size of `limit` clamped
469 /// by the min-content and max-content sizes.
470 #[inline(always)]
471 pub const fn fit_content_px(limit: f32) -> Self {
472 Self(CompactLength::fit_content_px(limit))
473 }
474
475 /// The size should be computed according to the "fit content" formula:
476 /// `max(min_content, min(max_content, limit))`
477 /// where:
478 /// - `min_content` is the [min-content](Self::min_content) size
479 /// - `max_content` is the [max-content](Self::max_content) size
480 /// - `limit` is a PERCENTAGE value passed to this function
481 ///
482 /// The effect of this is that the item takes the size of `limit` clamped
483 /// by the min-content and max-content sizes.
484 #[inline(always)]
485 pub const fn fit_content_percent(limit: f32) -> Self {
486 Self(CompactLength::fit_content_percent(limit))
487 }
488
489 /// The dimension as a fraction of the total available grid space (`fr` units in CSS)
490 /// Specified value is the numerator of the fraction. Denominator is the sum of all fraction specified in that grid dimension
491 /// Spec: <https://www.w3.org/TR/css3-grid-layout/#fr-unit>
492 #[inline(always)]
493 pub const fn fr(val: f32) -> Self {
494 Self(CompactLength::fr(val))
495 }
496
497 /// A `calc()` value. The value passed here is treated as an opaque handle to
498 /// the actual calc representation and may be a pointer, index, etc.
499 ///
500 /// The low 3 bits are used as a tag value and will be returned as 0.
501 #[inline]
502 pub fn calc(ptr: *const ()) -> Self {
503 Self(CompactLength::calc(ptr))
504 }
505
506 /// Create a LengthPercentageAuto from a raw `CompactLength`.
507 /// # Safety
508 /// CompactLength must represent a valid variant for LengthPercentageAuto
509 #[allow(unsafe_code)]
510 pub unsafe fn from_raw(val: CompactLength) -> Self {
511 Self(val)
512 }
513
514 /// Get the underlying `CompactLength` representation of the value
515 pub fn into_raw(self) -> CompactLength {
516 self.0
517 }
518
519 /// Returns true if the max track sizing function is `MinContent`, `MaxContent`, `FitContent` or `Auto`, else false.
520 #[inline(always)]
521 pub fn is_intrinsic(&self) -> bool {
522 self.0.is_intrinsic()
523 }
524
525 /// Returns true if the max track sizing function is `MaxContent`, `FitContent` or `Auto` else false.
526 /// "In all cases, treat auto and fit-content() as max-content, except where specified otherwise for fit-content()."
527 /// See: <https://www.w3.org/TR/css-grid-1/#algo-terms>
528 #[inline(always)]
529 pub fn is_max_content_alike(&self) -> bool {
530 self.0.is_max_content_alike()
531 }
532
533 /// Returns true if the an Fr value, else false.
534 #[inline(always)]
535 pub fn is_fr(&self) -> bool {
536 self.0.is_fr()
537 }
538
539 /// Returns true if the is `Auto`, else false.
540 #[inline(always)]
541 pub fn is_auto(&self) -> bool {
542 self.0.is_auto()
543 }
544
545 /// Returns true if value is MinContent
546 #[inline(always)]
547 pub fn is_min_content(&self) -> bool {
548 self.0.is_min_content()
549 }
550
551 /// Returns true if value is MaxContent
552 #[inline(always)]
553 pub fn is_max_content(&self) -> bool {
554 self.0.is_max_content()
555 }
556
557 /// Returns true if value is FitContent(...)
558 #[inline(always)]
559 pub fn is_fit_content(&self) -> bool {
560 self.0.is_fit_content()
561 }
562
563 /// Returns true if value is MaxContent or FitContent(...)
564 #[inline(always)]
565 pub fn is_max_or_fit_content(&self) -> bool {
566 self.0.is_max_or_fit_content()
567 }
568
569 /// Returns whether the value can be resolved using `Self::definite_value`
570 #[inline(always)]
571 pub fn has_definite_value(self, parent_size: Option<f32>) -> bool {
572 match self.0.tag() {
573 CompactLength::LENGTH_TAG => true,
574 CompactLength::PERCENT_TAG => parent_size.is_some(),
575 _ if self.0.is_calc() => parent_size.is_some(),
576 _ => false,
577 }
578 }
579
580 /// Returns fixed point values directly. Attempts to resolve percentage values against
581 /// the passed available_space and returns if this results in a concrete value (which it
582 /// will if the available_space is `Some`). Otherwise returns None.
583 #[inline(always)]
584 pub fn definite_value(self, parent_size: Option<f32>, calc_resolver: impl Fn(u64, f32) -> f32) -> Option<f32> {
585 match self.0.tag() {
586 CompactLength::LENGTH_TAG => Some(self.0.value()),
587 CompactLength::PERCENT_TAG => parent_size.map(|size| self.0.value() * size),
588 _ if self.0.is_calc() => parent_size.map(|size| calc_resolver(self.0.calc_value(), size)),
589 _ => None,
590 }
591 }
592
593 /// Resolve the maximum size of the track as defined by either:
594 /// - A fixed track sizing function
595 /// - A percentage track sizing function (with definite available space)
596 /// - A fit-content sizing function with fixed argument
597 /// - A fit-content sizing function with percentage argument (with definite available space)
598 /// All other kinds of track sizing function return None.
599 #[inline(always)]
600 pub fn definite_limit(self, parent_size: Option<f32>, calc_resolver: impl Fn(u64, f32) -> f32) -> Option<f32> {
601 match self.0.tag() {
602 CompactLength::FIT_CONTENT_PX_TAG => Some(self.0.value()),
603 CompactLength::FIT_CONTENT_PERCENT_TAG => parent_size.map(|size| self.0.value() * size),
604 _ => self.definite_value(parent_size, calc_resolver),
605 }
606 }
607
608 /// Resolve percentage values against the passed parent_size, returning Some(value)
609 /// Non-percentage values always return None.
610 #[inline(always)]
611 pub fn resolved_percentage_size(self, parent_size: f32, calc_resolver: impl Fn(u64, f32) -> f32) -> Option<f32> {
612 self.0.resolved_percentage_size(parent_size, calc_resolver)
613 }
614
615 /// Whether the track sizing functions depends on the size of the parent node
616 #[inline(always)]
617 pub fn uses_percentage(self) -> bool {
618 self.0.uses_percentage()
619 }
620}
621
622/// Minimum track sizing function
623///
624/// Specifies the minimum size of a grid track. A grid track will automatically size between it's minimum and maximum size based
625/// on the size of it's contents, the amount of available space, and the sizing constraint the grid is being size under.
626/// See <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns>
627#[derive(Copy, Clone, PartialEq, Debug)]
628#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
629pub struct MinTrackSizingFunction(pub(crate) CompactLength);
630impl TaffyZero for MinTrackSizingFunction {
631 const ZERO: Self = Self(CompactLength::ZERO);
632}
633impl TaffyAuto for MinTrackSizingFunction {
634 const AUTO: Self = Self(CompactLength::AUTO);
635}
636impl TaffyMinContent for MinTrackSizingFunction {
637 const MIN_CONTENT: Self = Self(CompactLength::MIN_CONTENT);
638}
639impl TaffyMaxContent for MinTrackSizingFunction {
640 const MAX_CONTENT: Self = Self(CompactLength::MAX_CONTENT);
641}
642impl FromLength for MinTrackSizingFunction {
643 fn from_length<Input: Into<f32> + Copy>(value: Input) -> Self {
644 Self::length(value.into())
645 }
646}
647impl FromPercent for MinTrackSizingFunction {
648 fn from_percent<Input: Into<f32> + Copy>(value: Input) -> Self {
649 Self::percent(value.into())
650 }
651}
652impl From<LengthPercentage> for MinTrackSizingFunction {
653 fn from(input: LengthPercentage) -> Self {
654 Self(input.0)
655 }
656}
657impl From<LengthPercentageAuto> for MinTrackSizingFunction {
658 fn from(input: LengthPercentageAuto) -> Self {
659 Self(input.0)
660 }
661}
662impl From<Dimension> for MinTrackSizingFunction {
663 fn from(input: Dimension) -> Self {
664 Self(input.0)
665 }
666}
667
668impl MinTrackSizingFunction {
669 /// An absolute length in some abstract units. Users of Taffy may define what they correspond
670 /// to in their application (pixels, logical pixels, mm, etc) as they see fit.
671 #[inline(always)]
672 pub const fn length(val: f32) -> Self {
673 Self(CompactLength::length(val))
674 }
675
676 /// A percentage length relative to the size of the containing block.
677 ///
678 /// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
679 #[inline(always)]
680 pub const fn percent(val: f32) -> Self {
681 Self(CompactLength::percent(val))
682 }
683
684 /// The dimension should be automatically computed according to algorithm-specific rules
685 /// regarding the default size of boxes.
686 #[inline(always)]
687 pub const fn auto() -> Self {
688 Self(CompactLength::auto())
689 }
690
691 /// The size should be the "min-content" size.
692 /// This is the smallest size that can fit the item's contents with ALL soft line-wrapping opportunities taken
693 #[inline(always)]
694 pub const fn min_content() -> Self {
695 Self(CompactLength::min_content())
696 }
697
698 /// The size should be the "max-content" size.
699 /// This is the smallest size that can fit the item's contents with NO soft line-wrapping opportunities taken
700 #[inline(always)]
701 pub const fn max_content() -> Self {
702 Self(CompactLength::max_content())
703 }
704
705 /// A `calc()` value. The value passed here is treated as an opaque handle to
706 /// the actual calc representation and may be a pointer, index, etc.
707 ///
708 /// The low 3 bits are used as a tag value and will be returned as 0.
709 #[inline]
710 pub fn calc(ptr: *const ()) -> Self {
711 Self(CompactLength::calc(ptr))
712 }
713
714 /// Create a LengthPercentageAuto from a raw `CompactLength`.
715 /// # Safety
716 /// CompactLength must represent a valid variant for LengthPercentageAuto
717 #[allow(unsafe_code)]
718 pub unsafe fn from_raw(val: CompactLength) -> Self {
719 Self(val)
720 }
721
722 /// Get the underlying `CompactLength` representation of the value
723 pub fn into_raw(self) -> CompactLength {
724 self.0
725 }
726
727 /// Returns true if the min track sizing function is `MinContent`, `MaxContent` or `Auto`, else false.
728 #[inline(always)]
729 pub fn is_intrinsic(&self) -> bool {
730 self.0.is_intrinsic()
731 }
732
733 /// Returns true if the min track sizing function is `MinContent` or `MaxContent`, else false.
734 #[inline(always)]
735 pub fn is_min_or_max_content(&self) -> bool {
736 self.0.is_min_or_max_content()
737 }
738
739 /// Returns true if the value is an fr value
740 #[inline(always)]
741 pub fn is_fr(&self) -> bool {
742 self.0.is_fr()
743 }
744
745 /// Returns true if the is `Auto`, else false.
746 #[inline(always)]
747 pub fn is_auto(&self) -> bool {
748 self.0.is_auto()
749 }
750
751 /// Returns true if value is MinContent
752 #[inline(always)]
753 pub fn is_min_content(&self) -> bool {
754 self.0.is_min_content()
755 }
756
757 /// Returns true if value is MaxContent
758 #[inline(always)]
759 pub fn is_max_content(&self) -> bool {
760 self.0.is_max_content()
761 }
762
763 /// Returns fixed point values directly. Attempts to resolve percentage values against
764 /// the passed available_space and returns if this results in a concrete value (which it
765 /// will if the available_space is `Some`). Otherwise returns `None`.
766 #[inline(always)]
767 pub fn definite_value(self, parent_size: Option<f32>, calc_resolver: impl Fn(u64, f32) -> f32) -> Option<f32> {
768 match self.0.tag() {
769 CompactLength::LENGTH_TAG => Some(self.0.value()),
770 CompactLength::PERCENT_TAG => parent_size.map(|size| self.0.value() * size),
771 _ if self.0.is_calc() => parent_size.map(|size| calc_resolver(self.0.calc_value(), size)),
772 _ => None,
773 }
774 }
775
776 /// Resolve percentage values against the passed parent_size, returning Some(value)
777 /// Non-percentage values always return None.
778 #[inline(always)]
779 pub fn resolved_percentage_size(self, parent_size: f32, calc_resolver: impl Fn(u64, f32) -> f32) -> Option<f32> {
780 self.0.resolved_percentage_size(parent_size, calc_resolver)
781 }
782
783 /// Whether the track sizing functions depends on the size of the parent node
784 #[inline(always)]
785 pub fn uses_percentage(self) -> bool {
786 matches!(self.0.tag(), CompactLength::PERCENT_TAG) || self.0.is_calc()
787 }
788}
789
790/// The sizing function for a grid track (row/column)
791///
792/// May either be a MinMax variant which specifies separate values for the min-/max- track sizing functions
793/// or a scalar value which applies to both track sizing functions.
794pub type NonRepeatedTrackSizingFunction = MinMax<MinTrackSizingFunction, MaxTrackSizingFunction>;
795impl NonRepeatedTrackSizingFunction {
796 /// Extract the min track sizing function
797 pub fn min_sizing_function(&self) -> MinTrackSizingFunction {
798 self.min
799 }
800 /// Extract the max track sizing function
801 pub fn max_sizing_function(&self) -> MaxTrackSizingFunction {
802 self.max
803 }
804 /// Determine whether at least one of the components ("min" and "max") are fixed sizing function
805 pub fn has_fixed_component(&self) -> bool {
806 self.min.0.is_length_or_percentage() || self.max.0.is_length_or_percentage()
807 }
808}
809impl TaffyAuto for NonRepeatedTrackSizingFunction {
810 const AUTO: Self = Self { min: MinTrackSizingFunction::AUTO, max: MaxTrackSizingFunction::AUTO };
811}
812impl TaffyMinContent for NonRepeatedTrackSizingFunction {
813 const MIN_CONTENT: Self =
814 Self { min: MinTrackSizingFunction::MIN_CONTENT, max: MaxTrackSizingFunction::MIN_CONTENT };
815}
816impl TaffyMaxContent for NonRepeatedTrackSizingFunction {
817 const MAX_CONTENT: Self =
818 Self { min: MinTrackSizingFunction::MAX_CONTENT, max: MaxTrackSizingFunction::MAX_CONTENT };
819}
820impl TaffyFitContent for NonRepeatedTrackSizingFunction {
821 fn fit_content(argument: LengthPercentage) -> Self {
822 Self { min: MinTrackSizingFunction::AUTO, max: MaxTrackSizingFunction::fit_content(argument) }
823 }
824}
825impl TaffyZero for NonRepeatedTrackSizingFunction {
826 const ZERO: Self = Self { min: MinTrackSizingFunction::ZERO, max: MaxTrackSizingFunction::ZERO };
827}
828impl FromLength for NonRepeatedTrackSizingFunction {
829 fn from_length<Input: Into<f32> + Copy>(value: Input) -> Self {
830 Self { min: MinTrackSizingFunction::from_length(value), max: MaxTrackSizingFunction::from_length(value) }
831 }
832}
833impl FromPercent for NonRepeatedTrackSizingFunction {
834 fn from_percent<Input: Into<f32> + Copy>(percent: Input) -> Self {
835 Self { min: MinTrackSizingFunction::from_percent(percent), max: MaxTrackSizingFunction::from_percent(percent) }
836 }
837}
838impl FromFr for NonRepeatedTrackSizingFunction {
839 fn from_fr<Input: Into<f32> + Copy>(flex: Input) -> Self {
840 Self { min: MinTrackSizingFunction::AUTO, max: MaxTrackSizingFunction::from_fr(flex) }
841 }
842}
843impl From<LengthPercentage> for NonRepeatedTrackSizingFunction {
844 fn from(input: LengthPercentage) -> Self {
845 Self { min: input.into(), max: input.into() }
846 }
847}
848impl From<LengthPercentageAuto> for NonRepeatedTrackSizingFunction {
849 fn from(input: LengthPercentageAuto) -> Self {
850 Self { min: input.into(), max: input.into() }
851 }
852}
853impl From<Dimension> for NonRepeatedTrackSizingFunction {
854 fn from(input: Dimension) -> Self {
855 Self { min: input.into(), max: input.into() }
856 }
857}
858
859/// The first argument to a repeated track definition. This type represents the type of automatic repetition to perform.
860///
861/// See <https://www.w3.org/TR/css-grid-1/#auto-repeat> for an explanation of how auto-repeated track definitions work
862/// and the difference between AutoFit and AutoFill.
863#[derive(Clone, Copy, Debug, PartialEq, Eq)]
864#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
865pub enum GridTrackRepetition {
866 /// Auto-repeating tracks should be generated to fit the container
867 /// See: <https://developer.mozilla.org/en-US/docs/Web/CSS/repeat#auto-fill>
868 AutoFill,
869 /// Auto-repeating tracks should be generated to fit the container
870 /// See: <https://developer.mozilla.org/en-US/docs/Web/CSS/repeat#auto-fit>
871 AutoFit,
872 /// The specified tracks should be repeated exacts N times
873 Count(u16),
874}
875impl TryFrom<u16> for GridTrackRepetition {
876 type Error = Infallible;
877 fn try_from(value: u16) -> Result<Self, Infallible> {
878 Ok(Self::Count(value))
879 }
880}
881
882/// Error returned when trying to convert a string to a GridTrackRepetition and that string is not
883/// either "auto-fit" or "auto-fill"
884#[derive(Debug)]
885pub struct InvalidStringRepetitionValue;
886#[cfg(feature = "std")]
887impl std::error::Error for InvalidStringRepetitionValue {}
888impl core::fmt::Display for InvalidStringRepetitionValue {
889 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
890 f.write_str("&str can only be converted to GridTrackRepetition if it's value is 'auto-fit' or 'auto-fill'")
891 }
892}
893impl TryFrom<&str> for GridTrackRepetition {
894 type Error = InvalidStringRepetitionValue;
895 fn try_from(value: &str) -> Result<Self, InvalidStringRepetitionValue> {
896 match value {
897 "auto-fit" => Ok(Self::AutoFit),
898 "auto-fill" => Ok(Self::AutoFill),
899 _ => Err(InvalidStringRepetitionValue),
900 }
901 }
902}
903
904/// The sizing function for a grid track (row/column)
905/// See <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns>
906#[derive(Clone, PartialEq, Debug)]
907#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
908pub enum TrackSizingFunction {
909 /// A single non-repeated track
910 Single(NonRepeatedTrackSizingFunction),
911 /// Automatically generate grid tracks to fit the available space using the specified definite track lengths
912 /// Only valid if every track in template (not just the repetition) has a fixed size.
913 Repeat(GridTrackRepetition, GridTrackVec<NonRepeatedTrackSizingFunction>),
914}
915impl TrackSizingFunction {
916 /// Whether the track definition is a auto-repeated fragment
917 pub fn is_auto_repetition(&self) -> bool {
918 matches!(self, Self::Repeat(GridTrackRepetition::AutoFit | GridTrackRepetition::AutoFill, _))
919 }
920}
921impl TaffyAuto for TrackSizingFunction {
922 const AUTO: Self = Self::Single(NonRepeatedTrackSizingFunction::AUTO);
923}
924impl TaffyMinContent for TrackSizingFunction {
925 const MIN_CONTENT: Self = Self::Single(NonRepeatedTrackSizingFunction::MIN_CONTENT);
926}
927impl TaffyMaxContent for TrackSizingFunction {
928 const MAX_CONTENT: Self = Self::Single(NonRepeatedTrackSizingFunction::MAX_CONTENT);
929}
930impl TaffyFitContent for TrackSizingFunction {
931 fn fit_content(argument: LengthPercentage) -> Self {
932 Self::Single(NonRepeatedTrackSizingFunction::fit_content(argument))
933 }
934}
935impl TaffyZero for TrackSizingFunction {
936 const ZERO: Self = Self::Single(NonRepeatedTrackSizingFunction::ZERO);
937}
938impl FromLength for TrackSizingFunction {
939 fn from_length<Input: Into<f32> + Copy>(value: Input) -> Self {
940 Self::Single(NonRepeatedTrackSizingFunction::from_length(value))
941 }
942}
943impl FromPercent for TrackSizingFunction {
944 fn from_percent<Input: Into<f32> + Copy>(percent: Input) -> Self {
945 Self::Single(NonRepeatedTrackSizingFunction::from_percent(percent))
946 }
947}
948impl FromFr for TrackSizingFunction {
949 fn from_fr<Input: Into<f32> + Copy>(flex: Input) -> Self {
950 Self::Single(NonRepeatedTrackSizingFunction::from_fr(flex))
951 }
952}
953impl From<MinMax<MinTrackSizingFunction, MaxTrackSizingFunction>> for TrackSizingFunction {
954 fn from(input: MinMax<MinTrackSizingFunction, MaxTrackSizingFunction>) -> Self {
955 Self::Single(input)
956 }
957}