Skip to main content

taffy/style/
mod.rs

1//! A typed representation of [CSS style properties](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) in Rust. Used as input to layout computation.
2mod alignment;
3mod available_space;
4mod compact_length;
5mod dimension;
6
7#[cfg(feature = "block_layout")]
8mod block;
9#[cfg(feature = "flexbox")]
10mod flex;
11#[cfg(feature = "float_layout")]
12mod float;
13#[cfg(feature = "grid")]
14mod grid;
15
16pub use self::alignment::{
17    AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AlignmentSafety, JustifyContent,
18    JustifyItems, JustifySelf,
19};
20pub use self::available_space::AvailableSpace;
21pub use self::compact_length::CompactLength;
22pub use self::dimension::{
23    Dimension, ExpandedDimension, ExpandedLengthPercentage, ExpandedLengthPercentageAuto, LengthPercentage,
24    LengthPercentageAuto,
25};
26use crate::sys::DefaultCheapStr;
27
28#[cfg(feature = "block_layout")]
29pub use self::block::{BlockContainerStyle, BlockItemStyle, TextAlign};
30#[cfg(feature = "flexbox")]
31pub use self::flex::{FlexDirection, FlexWrap, FlexboxContainerStyle, FlexboxItemStyle};
32#[cfg(feature = "float_layout")]
33pub use self::float::{Clear, Float, FloatDirection};
34#[cfg(feature = "grid")]
35pub use self::grid::{
36    ExpandedMaxTrackSizingFunction, ExpandedMinTrackSizingFunction, GenericGridPlacement, GenericGridTemplateComponent,
37    GenericRepetition, GridAutoFlow, GridAutoTracks, GridContainerStyle, GridItemStyle, GridPlacement,
38    GridTemplateComponent, GridTemplateRepetition, GridTemplateTracks, MaxTrackSizingFunction, MinTrackSizingFunction,
39    RepetitionCount, TrackSizingFunction,
40};
41#[cfg(feature = "grid")]
42pub(crate) use self::grid::{GridAreaAxis, GridAreaEnd};
43#[cfg(feature = "grid")]
44pub use self::grid::{GridTemplateArea, GridTemplateAreas, NamedGridLine, TemplateLineNames};
45#[cfg(feature = "grid")]
46pub(crate) use self::grid::{NonNamedGridPlacement, OriginZeroGridPlacement};
47
48use crate::geometry::{Point, Rect, Size};
49use crate::style_helpers::TaffyAuto as _;
50use core::fmt::Debug;
51
52#[cfg(feature = "grid")]
53use crate::geometry::Line;
54#[cfg(feature = "serde")]
55use crate::style_helpers;
56#[cfg(feature = "grid")]
57use crate::util::sys::GridTrackVec;
58
59use crate::sys::String;
60
61/// Trait that represents a cheaply clonable string. If you're unsure what to use here
62/// consider `Arc<str>` or `string_cache::Atom`.
63pub trait CheapCloneStr:
64    AsRef<str> + for<'a> From<&'a str> + From<String> + PartialEq + Eq + Clone + Default + Debug + 'static
65{
66}
67impl<T> CheapCloneStr for T where
68    T: AsRef<str> + for<'a> From<&'a str> + From<String> + PartialEq + Eq + Clone + Default + Debug + 'static
69{
70}
71
72/// The core set of styles that are shared between all CSS layout nodes
73///
74/// Note that all methods come with a default implementation which simply returns the default value for that style property
75/// but this is a just a convenience to save on boilerplate for styles that your implementation doesn't support. You will need
76/// to override the default implementation for each style property that your style type actually supports.
77pub trait CoreStyle {
78    /// The type of custom identifiers used to identify named grid lines and areas
79    type CustomIdent: CheapCloneStr;
80
81    /// Which box generation mode should be used
82    #[inline(always)]
83    fn box_generation_mode(&self) -> BoxGenerationMode {
84        BoxGenerationMode::DEFAULT
85    }
86    /// Is block layout?
87    ///
88    /// This should only return `true` for `display: block`, and NOT for `display: flow-root`.
89    /// Flow-root boxes establish a new block formatting context and must not be treated as
90    /// being part of their parent's block formatting context (which is what this method controls).
91    #[inline(always)]
92    fn is_block(&self) -> bool {
93        false
94    }
95    /// Is it a compressible replaced element: a replaced element (image, video, canvas, ...) or a
96    /// form control with an intrinsic size (`input`, `select`, `textarea`, `meter`, ...)?
97    /// Such boxes resolve an `auto` width to their intrinsic size rather than being stretched by
98    /// block layout, and have a zero min-content contribution in grid layout.
99    /// <https://drafts.csswg.org/css-sizing-3/#compressible>
100    #[inline(always)]
101    fn is_compressible_replaced(&self) -> bool {
102        false
103    }
104    /// Is it a replaced element (image, video, canvas, ...)? Unlike other compressible replaced
105    /// elements (form controls), an `auto`-sized replaced element is not stretched between its
106    /// insets under `normal` alignment.
107    /// <https://html.spec.whatwg.org/multipage/rendering.html#replaced-elements>
108    #[inline(always)]
109    fn is_replaced(&self) -> bool {
110        false
111    }
112    /// Which box do size styles apply to
113    #[inline(always)]
114    fn box_sizing(&self) -> BoxSizing {
115        BoxSizing::BorderBox
116    }
117
118    /// The direction of text, table and grid columns, and horizontal overflow.
119    #[inline(always)]
120    fn direction(&self) -> Direction {
121        Direction::Ltr
122    }
123
124    // Overflow properties
125    /// How children overflowing their container should affect layout
126    #[inline(always)]
127    fn overflow(&self) -> Point<Overflow> {
128        Style::<Self::CustomIdent>::DEFAULT.overflow
129    }
130    /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
131    #[inline(always)]
132    fn scrollbar_width(&self) -> f32 {
133        0.0
134    }
135
136    // Position properties
137    /// What should the `position` value of this struct use as a base offset?
138    #[inline(always)]
139    fn position(&self) -> Position {
140        Style::<Self::CustomIdent>::DEFAULT.position
141    }
142    /// How should the position of this element be tweaked relative to the layout defined?
143    #[inline(always)]
144    fn inset(&self) -> Rect<LengthPercentageAuto> {
145        Style::<Self::CustomIdent>::DEFAULT.inset
146    }
147    /// Which out-of-flow (`absolute`/`fixed`) descendants this node establishes the containing block for.
148    ///
149    /// This is the single policy point for containing-block establishment: it decides both which
150    /// out-of-flow boxes a node claims and lays out, and (for grid containers) whether the static
151    /// position of an out-of-flow child is derived from its grid area.
152    ///
153    /// The default matches plain CSS positioning: a node is the containing block for `absolute` boxes
154    /// when its own `position` is not `static`, and never for `fixed` boxes (which are claimed by the
155    /// root). Implementations may override this so that other style properties (such as `transform`,
156    /// `filter` or `will-change` in a full CSS implementation) establish a containing block.
157    #[inline(always)]
158    fn is_containing_block(&self) -> ContainingBlockClaims {
159        ContainingBlockClaims { absolute: self.position().is_positioned(), fixed: false }
160    }
161
162    // Size properies
163    /// Sets the initial size of the item
164    #[inline(always)]
165    fn size(&self) -> Size<Dimension> {
166        Style::<Self::CustomIdent>::DEFAULT.size
167    }
168    /// Controls the minimum size of the item
169    #[inline(always)]
170    fn min_size(&self) -> Size<LengthPercentageAuto> {
171        Style::<Self::CustomIdent>::DEFAULT.min_size
172    }
173    /// Controls the maximum size of the item
174    #[inline(always)]
175    fn max_size(&self) -> Size<LengthPercentageAuto> {
176        Style::<Self::CustomIdent>::DEFAULT.max_size
177    }
178    /// Sets the preferred aspect ratio for the item
179    /// The ratio is calculated as width divided by height.
180    #[inline(always)]
181    fn aspect_ratio(&self) -> Option<f32> {
182        Style::<Self::CustomIdent>::DEFAULT.aspect_ratio
183    }
184
185    // Spacing Properties
186    /// How large should the margin be on each side?
187    #[inline(always)]
188    fn margin(&self) -> Rect<LengthPercentageAuto> {
189        Style::<Self::CustomIdent>::DEFAULT.margin
190    }
191    /// How large should the padding be on each side?
192    #[inline(always)]
193    fn padding(&self) -> Rect<LengthPercentage> {
194        Style::<Self::CustomIdent>::DEFAULT.padding
195    }
196    /// How large should the border be on each side?
197    #[inline(always)]
198    fn border(&self) -> Rect<LengthPercentage> {
199        Style::<Self::CustomIdent>::DEFAULT.border
200    }
201
202    /// The layout-affecting parts of the CSS `contain` property that apply to this node
203    #[inline(always)]
204    fn contain(&self) -> Contain {
205        Contain::NONE
206    }
207}
208
209/// The styles of an out-of-flow (`position: absolute` / `position: fixed`) box that are read by
210/// its containing block's out-of-flow positioning pass
211pub trait OofItemStyle: CoreStyle {
212    /// How the box is aligned in the block axis of its inset-modified containing block
213    /// (`align-self`). `None` corresponds to `normal`/`auto`.
214    #[inline(always)]
215    fn align_self(&self) -> Option<AlignSelf> {
216        None
217    }
218    /// How the box is aligned in the inline axis of its inset-modified containing block
219    /// (`justify-self`). `None` corresponds to `normal`/`auto`.
220    #[inline(always)]
221    fn justify_self(&self) -> Option<AlignSelf> {
222        None
223    }
224    /// Whether the box is a table wrapper box. A `normal` self-alignment does not stretch
225    /// tables to fill their inset-modified containing block.
226    #[inline(always)]
227    fn is_table(&self) -> bool {
228        false
229    }
230    /// Defines which row in the grid the box should start and end at, when the box's containing
231    /// block is a grid container
232    #[cfg(feature = "grid")]
233    #[inline(always)]
234    fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
235        Default::default()
236    }
237    /// Defines which column in the grid the box should start and end at, when the box's
238    /// containing block is a grid container
239    #[cfg(feature = "grid")]
240    #[inline(always)]
241    fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
242        Default::default()
243    }
244}
245
246/// Sets the layout used for the children of this node
247///
248/// The default values depends on on which feature flags are enabled. The order of precedence is: Flex, Grid, Block, None.
249#[derive(Copy, Clone, PartialEq, Eq, Debug)]
250#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
251pub enum Display {
252    /// The children will follow the block layout algorithm
253    #[cfg(feature = "block_layout")]
254    Block,
255    /// The children will follow the block layout algorithm and establish a new block formatting context
256    #[cfg(feature = "block_layout")]
257    FlowRoot,
258    /// The children will follow the flexbox layout algorithm
259    #[cfg(feature = "flexbox")]
260    Flex,
261    /// The children will follow the CSS Grid layout algorithm
262    #[cfg(feature = "grid")]
263    Grid,
264    /// The node is hidden, and it's children will also be hidden
265    None,
266}
267
268impl Display {
269    /// The default Display mode
270    #[cfg(feature = "flexbox")]
271    pub const DEFAULT: Display = Display::Flex;
272
273    /// The default Display mode
274    #[cfg(all(feature = "grid", not(feature = "flexbox")))]
275    pub const DEFAULT: Display = Display::Grid;
276
277    /// The default Display mode
278    #[cfg(all(feature = "block_layout", not(feature = "flexbox"), not(feature = "grid")))]
279    pub const DEFAULT: Display = Display::Block;
280
281    /// The default Display mode
282    #[cfg(all(not(feature = "flexbox"), not(feature = "grid"), not(feature = "block_layout")))]
283    pub const DEFAULT: Display = Display::None;
284}
285
286impl Default for Display {
287    fn default() -> Self {
288        Self::DEFAULT
289    }
290}
291
292#[cfg(feature = "parse")]
293crate::util::parse::impl_parse_for_keyword_enum!(Display,
294    "none" => None,
295    #[cfg(feature = "flexbox")]
296    "flex" => Flex,
297    #[cfg(feature = "grid")]
298    "grid" => Grid,
299    #[cfg(feature = "block_layout")]
300    "block" => Block,
301    #[cfg(feature = "block_layout")]
302    "flow-root" => FlowRoot,
303);
304
305impl core::fmt::Display for Display {
306    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
307        match self {
308            Display::None => write!(f, "NONE"),
309            #[cfg(feature = "block_layout")]
310            Display::Block => write!(f, "BLOCK"),
311            #[cfg(feature = "block_layout")]
312            Display::FlowRoot => write!(f, "FLOW-ROOT"),
313            #[cfg(feature = "flexbox")]
314            Display::Flex => write!(f, "FLEX"),
315            #[cfg(feature = "grid")]
316            Display::Grid => write!(f, "GRID"),
317        }
318    }
319}
320
321/// An abstracted version of the CSS `display` property where any value other than "none" is represented by "normal"
322/// See: <https://www.w3.org/TR/css-display-3/#box-generation>
323#[derive(Copy, Clone, PartialEq, Eq, Debug)]
324#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
325pub enum BoxGenerationMode {
326    /// The node generates a box in the regular way
327    Normal,
328    /// The node and it's descendants generate no boxes (they are hidden)
329    None,
330}
331
332impl BoxGenerationMode {
333    /// The default of BoxGenerationMode
334    pub const DEFAULT: BoxGenerationMode = BoxGenerationMode::Normal;
335}
336
337impl Default for BoxGenerationMode {
338    fn default() -> Self {
339        Self::DEFAULT
340    }
341}
342
343/// The positioning strategy for this item.
344///
345/// This controls both how the origin is determined for the [`Style::position`] field,
346/// and whether or not the item will be controlled by flexbox's layout algorithm.
347///
348/// WARNING: this enum follows the behavior of [CSS's `position` property](https://developer.mozilla.org/en-US/docs/Web/CSS/position),
349/// which can be unintuitive.
350///
351/// [`Position::Static`] is the default value, matching the default behavior in CSS.
352#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
353#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
354pub enum Position {
355    /// The item is laid out in normal flow. `inset` has no effect on statically positioned items,
356    /// and they do not act as a containing block for absolutely positioned descendants.
357    #[default]
358    Static,
359    /// The item is laid out in normal flow, then the `inset` offset is applied as a correction factor.
360    /// Offsets do not affect the position of any other items.
361    /// Relatively positioned items act as a containing block for absolutely positioned descendants.
362    Relative,
363    /// The item is taken out of normal flow and positioned relative to its closest positioned ancestor
364    /// (its containing block), if any. Otherwise, it is placed relative to the root.
365    /// No space is created for the item in the page layout, and its size will not be altered.
366    ///
367    /// WARNING: to opt-out of layouting entirely, you must use [`Display::None`] instead on your [`Style`] object.
368    Absolute,
369    /// The item is taken out of normal flow and positioned relative to the root (viewport),
370    /// unless an ancestor overrides containing-block behavior (e.g. via transforms in a full CSS implementation).
371    Fixed,
372    /// The item is laid out in normal flow exactly like a statically positioned item: `inset` is *not* applied
373    /// as an offset (in CSS, sticky insets are scroll thresholds, which Taffy has no knowledge of; applying the
374    /// sticky offset is the responsibility of the caller once it knows the scroll position).
375    /// Like `Relative`, a sticky item acts as a containing block for absolutely positioned descendants.
376    Sticky,
377}
378
379impl Position {
380    /// Returns true if this position takes the item out of normal flow (`Absolute` or `Fixed`)
381    #[inline(always)]
382    pub fn is_out_of_flow(self) -> bool {
383        matches!(self, Position::Absolute | Position::Fixed)
384    }
385
386    /// Returns true if this position causes the item to act as a containing block
387    /// for absolutely positioned descendants (any value other than `Static`)
388    #[inline(always)]
389    pub fn is_positioned(self) -> bool {
390        !matches!(self, Position::Static)
391    }
392}
393
394/// Which out-of-flow positions a node establishes a containing block for.
395///
396/// Returned by [`CoreStyle::is_containing_block`].
397#[derive(Debug, Copy, Clone, PartialEq, Eq)]
398pub struct ContainingBlockClaims {
399    /// Whether the node is the containing block for `position: absolute` boxes
400    pub absolute: bool,
401    /// Whether the node is the containing block for `position: fixed` boxes
402    pub fixed: bool,
403}
404
405impl ContainingBlockClaims {
406    /// Claims nothing
407    pub const NONE: Self = Self { absolute: false, fixed: false };
408    /// Claims every out-of-flow box (the initial containing block)
409    pub const ALL: Self = Self { absolute: true, fixed: true };
410
411    /// Whether the node is the containing block for a box with the given `position`
412    #[inline(always)]
413    pub fn for_position(self, position: Position) -> bool {
414        match position {
415            Position::Absolute => self.absolute,
416            Position::Fixed => self.fixed,
417            _ => false,
418        }
419    }
420}
421
422#[cfg(feature = "parse")]
423crate::util::parse::impl_parse_for_keyword_enum!(Position,
424    "static" => Static,
425    "relative" => Relative,
426    "absolute" => Absolute,
427    "fixed" => Fixed,
428    "sticky" => Sticky,
429);
430
431/// Specifies whether size styles for this node are assigned to the node's "content box" or "border box"
432///
433/// - The "content box" is the node's inner size excluding padding, border and margin
434/// - The "border box" is the node's outer size including padding and border (but still excluding margin)
435///
436/// This property modifies the application of the following styles:
437///
438///   - `size`
439///   - `min_size`
440///   - `max_size`
441///   - `flex_basis`
442///
443/// See <https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing>
444#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
445#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
446pub enum BoxSizing {
447    /// Size styles such size, min_size, max_size specify the box's "border box" (the size excluding margin but including padding/border)
448    #[default]
449    BorderBox,
450    /// Size styles such size, min_size, max_size specify the box's "content box" (the size excluding padding/border/margin)
451    ContentBox,
452}
453
454#[cfg(feature = "parse")]
455crate::util::parse::impl_parse_for_keyword_enum!(BoxSizing,
456    "border-box" => BorderBox,
457    "content-box" => ContentBox,
458);
459
460/// How children overflowing their container should affect layout
461///
462/// In CSS the primary effect of this property is to control whether contents of a parent container that overflow that container should
463/// be displayed anyway, be clipped, or trigger the container to become a scroll container. However it also has secondary effects on layout,
464/// the main ones being:
465///
466///   - The automatic minimum size Flexbox/CSS Grid items with non-`Visible` overflow is `0` rather than being content based
467///   - `Overflow::Scroll` nodes have space in the layout reserved for a scrollbar (width controlled by the `scrollbar_width` property)
468///
469/// In Taffy, we only implement the layout related secondary effects as we are not concerned with drawing/painting. The amount of space reserved for
470/// a scrollbar is controlled by the `scrollbar_width` property. If this is `0` then `Scroll` behaves identically to `Hidden`.
471///
472/// <https://developer.mozilla.org/en-US/docs/Web/CSS/overflow>
473#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
474#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
475pub enum Overflow {
476    /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
477    /// Content that overflows this node *should* contribute to the scroll region of its parent.
478    #[default]
479    Visible,
480    /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
481    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
482    Clip,
483    /// The automatic minimum size of this node as a flexbox/grid item should be `0`.
484    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
485    Hidden,
486    /// The automatic minimum size of this node as a flexbox/grid item should be `0`. Additionally, space should be reserved
487    /// for a scrollbar. The amount of space reserved is controlled by the `scrollbar_width` property.
488    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
489    Scroll,
490}
491
492impl Overflow {
493    /// Returns true for overflow modes that contain their contents (`Overflow::Hidden`, `Overflow::Scroll`, `Overflow::Auto`)
494    /// or else false for overflow modes that allow their contains to spill (`Overflow::Visible`).
495    #[inline(always)]
496    pub fn is_scroll_container(self) -> bool {
497        match self {
498            Self::Visible | Self::Clip => false,
499            Self::Hidden | Self::Scroll => true,
500        }
501    }
502
503    /// Returns `Some(0.0)` if the overflow mode would cause the automatic minimum size of a Flexbox or CSS Grid item
504    /// to be `0`. Else returns None.
505    #[inline(always)]
506    pub(crate) fn maybe_into_automatic_min_size(self) -> Option<f32> {
507        match self.is_scroll_container() {
508            true => Some(0.0),
509            false => None,
510        }
511    }
512}
513
514#[cfg(feature = "parse")]
515crate::util::parse::impl_parse_for_keyword_enum!(Overflow,
516    "visible" => Visible,
517    "hidden" => Hidden,
518    "clip" => Clip,
519    "scroll" => Scroll,
520);
521
522/// The layout-affecting parts of the CSS `contain` property.
523///
524/// Containment limits the ways in which a box's contents can affect layout outside of the box
525/// (and vice versa). Taffy implements the layout-relevant containment types:
526///
527///   - [`Contain::LAYOUT`]: the box establishes an independent formatting context, and is treated
528///     as having no baseline for baseline-alignment purposes (layout containment).
529///   - [`Contain::PAINT`]: the box establishes an independent formatting context. Paint
530///     containment's other effects (clipping, containing absolutely-positioned descendants,
531///     stacking context) are outside of Taffy's scope.
532///
533///   - [`Contain::INLINE_SIZE`] and [`Contain::BLOCK_SIZE`]: the box is sized as if it were empty
534///     on that axis (size containment), unless its own style or its parent fixes the size.
535///
536/// The `style` containment type has no effect on layout and is therefore not represented
537/// (it is accepted and ignored when parsing).
538///
539/// <https://developer.mozilla.org/en-US/docs/Web/CSS/contain>
540#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
541#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
542pub struct Contain(u8);
543
544impl Contain {
545    /// No containment (the default)
546    pub const NONE: Contain = Contain(0);
547    /// Layout containment: the box establishes an independent formatting context and is treated
548    /// as having no baseline for baseline-alignment purposes.
549    /// <https://drafts.csswg.org/css-contain-2/#containment-layout>
550    pub const LAYOUT: Contain = Contain(1 << 0);
551    /// Paint containment: the box establishes an independent formatting context. Its other
552    /// effects don't affect layout.
553    /// <https://drafts.csswg.org/css-contain-2/#containment-paint>
554    pub const PAINT: Contain = Contain(1 << 1);
555    /// The containment implied by `contain: content` (`layout paint`, ignoring style containment)
556    pub const CONTENT: Contain = Contain(Contain::LAYOUT.0 | Contain::PAINT.0);
557    /// Inline-size containment: the box's inline size is computed as if it had no content.
558    /// <https://drafts.csswg.org/css-contain-3/#containment-inline-size>
559    pub const INLINE_SIZE: Contain = Contain(1 << 2);
560    /// Size containment on the block axis; with [`Contain::INLINE_SIZE`] this is `contain: size`.
561    pub const BLOCK_SIZE: Contain = Contain(1 << 3);
562    /// `contain: size`
563    pub const SIZE: Contain = Contain(Contain::INLINE_SIZE.0 | Contain::BLOCK_SIZE.0);
564
565    /// The default containment (no containment)
566    pub const DEFAULT: Contain = Contain::NONE;
567
568    /// Returns whether `self` contains all of the containment types in `other`
569    #[inline(always)]
570    pub const fn contains(self, other: Contain) -> bool {
571        self.0 & other.0 == other.0
572    }
573
574    /// Returns whether `self` contains any of the containment types in `other`
575    #[inline(always)]
576    pub const fn intersects(self, other: Contain) -> bool {
577        self.0 & other.0 != 0
578    }
579
580    /// Returns the union of the containment types in `self` and `other`
581    #[inline(always)]
582    pub const fn union(self, other: Contain) -> Contain {
583        Contain(self.0 | other.0)
584    }
585
586    /// Whether this containment causes the box to establish an independent formatting context
587    /// (both layout and paint containment do)
588    #[inline(always)]
589    pub const fn establishes_independent_formatting_context(self) -> bool {
590        self.intersects(Contain::LAYOUT.union(Contain::PAINT))
591    }
592
593    /// Whether this containment suppresses the box's baseline for baseline-alignment purposes
594    /// (layout containment does, paint containment does not)
595    #[inline(always)]
596    pub const fn suppresses_baseline(self) -> bool {
597        self.contains(Contain::LAYOUT)
598    }
599
600    /// Whether this containment prevents the box's overflowing content from contributing to an
601    /// ancestor's scrollable overflow region (layout containment treats such overflow as ink
602    /// overflow; paint containment clips it)
603    #[inline(always)]
604    pub const fn contains_scrollable_overflow(self) -> bool {
605        self.intersects(Contain::LAYOUT.union(Contain::PAINT))
606    }
607}
608
609impl core::ops::BitOr for Contain {
610    type Output = Contain;
611    #[inline(always)]
612    fn bitor(self, rhs: Contain) -> Contain {
613        self.union(rhs)
614    }
615}
616
617impl core::ops::BitOrAssign for Contain {
618    #[inline(always)]
619    fn bitor_assign(&mut self, rhs: Contain) {
620        *self = self.union(rhs);
621    }
622}
623
624#[cfg(feature = "parse")]
625impl crate::util::parse::FromCss for Contain {
626    fn from_css<'i>(input: &mut crate::util::parse::Parser<'i, '_>) -> crate::util::parse::CssParseResult<'i, Self> {
627        /// Duplicate-detection bit for the ignored `style` keyword, which does not map to a
628        /// `Contain` flag
629        const STYLE_BIT: u8 = 1 << 6;
630
631        let mut flags = Contain::NONE;
632        let mut seen: u8 = 0;
633
634        loop {
635            let ident = input.expect_ident()?.clone();
636            let (flag, seen_bit) = cssparser::match_ignore_ascii_case! { &*ident,
637                // Single-keyword values (only valid on their own; `parse_entirely` in the
638                // `FromStr` impl rejects trailing keywords, and a leading keyword before them
639                // is rejected by the `seen != 0` check below)
640                "none" | "content" => {
641                    if seen != 0 || !input.is_exhausted() {
642                        return Err(input.new_unexpected_token_error(crate::util::parse::Token::Ident(ident)));
643                    }
644                    return Ok(cssparser::match_ignore_ascii_case! { &*ident,
645                        "content" => Contain::CONTENT,
646                        _ => Contain::NONE,
647                    });
648                },
649                "layout" => (Contain::LAYOUT, Contain::LAYOUT.0),
650                "paint" => (Contain::PAINT, Contain::PAINT.0),
651                "size" => (Contain::SIZE, Contain::SIZE.0),
652                "inline-size" => (Contain::INLINE_SIZE, Contain::SIZE.0),
653                // `style` containment has no layout effect: accept and ignore it so that real
654                // CSS values round-trip
655                "style" => (Contain::NONE, STYLE_BIT),
656                _ => {
657                    return Err(input.new_unexpected_token_error(crate::util::parse::Token::Ident(ident)));
658                }
659            };
660
661            // Reject duplicate keywords
662            if seen & seen_bit != 0 {
663                return Err(input.new_unexpected_token_error(crate::util::parse::Token::Ident(ident)));
664            }
665            seen |= seen_bit;
666            flags |= flag;
667
668            if input.is_exhausted() {
669                return Ok(flags);
670            }
671        }
672    }
673}
674#[cfg(feature = "parse")]
675crate::util::parse::from_str_from_css!(Contain);
676
677/// Sets the direction of text, table and grid columns, and horizontal overflow.
678/// <https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/direction>
679#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
680#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
681pub enum Direction {
682    #[default]
683    /// Left-to-right
684    Ltr,
685    /// Right-to-left
686    Rtl,
687}
688
689impl Direction {
690    /// Returns true if the direction is right-to-left
691    #[inline]
692    pub fn is_rtl(&self) -> bool {
693        matches!(self, Direction::Rtl)
694    }
695}
696
697#[cfg(feature = "parse")]
698crate::util::parse::impl_parse_for_keyword_enum!(Direction,
699    "ltr" => Ltr,
700    "rtl" => Rtl,
701);
702
703/// A typed representation of the CSS style information for a single node.
704///
705/// The most important idea in flexbox is the notion of a "main" and "cross" axis, which are always perpendicular to each other.
706/// The orientation of these axes are controlled via the [`FlexDirection`] field of this struct.
707///
708/// This struct follows the [CSS equivalent](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) directly;
709/// information about the behavior on the web should transfer directly.
710///
711/// Detailed information about the exact behavior of each of these fields
712/// can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS) by searching for the field name.
713/// The distinction between margin, padding and border is explained well in
714/// this [introduction to the box model](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model).
715///
716/// If the behavior does not match the flexbox layout algorithm on the web, please file a bug!
717#[derive(Clone, PartialEq, Debug)]
718#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
719#[cfg_attr(feature = "serde", serde(default))]
720pub struct Style<S: CheapCloneStr = DefaultCheapStr> {
721    /// This is a dummy field which is necessary to make Taffy compile with the `grid` feature disabled
722    /// It should always be set to `core::marker::PhantomData`.
723    pub dummy: core::marker::PhantomData<S>,
724    /// What layout strategy should be used?
725    pub display: Display,
726    /// Whether a child is display:table or not. This affects children of block layouts.
727    /// This should really be part of `Display`, but it is currently seperate because table layout isn't implemented
728    pub item_is_table: bool,
729    /// Is it a replaced element like an image or video? Implies `is_compressible_replaced`.
730    /// <https://html.spec.whatwg.org/multipage/rendering.html#replaced-elements>
731    pub item_is_replaced: bool,
732    /// Is it a compressible replaced element that is not a replaced element (a form control with
733    /// an intrinsic size)? <https://drafts.csswg.org/css-sizing-3/#compressible>
734    pub item_is_compressible_replaced: bool,
735    /// Should size styles apply to the content box or the border box of the node
736    pub box_sizing: BoxSizing,
737    /// Sets the direction of text, table and grid columns, and horizontal overflow.
738    pub direction: Direction,
739
740    // Overflow properties
741    /// How children overflowing their container should affect layout
742    pub overflow: Point<Overflow>,
743    /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
744    pub scrollbar_width: f32,
745    /// The layout-affecting parts of the CSS `contain` property
746    pub contain: Contain,
747
748    #[cfg(feature = "float_layout")]
749    /// Should the box be floated
750    pub float: Float,
751    #[cfg(feature = "float_layout")]
752    /// Should the box clear floats
753    pub clear: Clear,
754
755    // Position properties
756    /// What should the `position` value of this struct use as a base offset?
757    pub position: Position,
758    /// How should the position of this element be tweaked relative to the layout defined?
759    #[cfg_attr(feature = "serde", serde(default = "style_helpers::auto"))]
760    pub inset: Rect<LengthPercentageAuto>,
761
762    // Size properties
763    /// Sets the initial size of the item
764    #[cfg_attr(feature = "serde", serde(default = "style_helpers::auto"))]
765    pub size: Size<Dimension>,
766    /// Controls the minimum size of the item
767    #[cfg_attr(feature = "serde", serde(default = "style_helpers::auto"))]
768    pub min_size: Size<LengthPercentageAuto>,
769    /// Controls the maximum size of the item
770    #[cfg_attr(feature = "serde", serde(default = "style_helpers::auto"))]
771    pub max_size: Size<LengthPercentageAuto>,
772    /// Sets the preferred aspect ratio for the item
773    ///
774    /// The ratio is calculated as width divided by height.
775    pub aspect_ratio: Option<f32>,
776
777    // Spacing Properties
778    /// How large should the margin be on each side?
779    #[cfg_attr(feature = "serde", serde(default = "style_helpers::zero"))]
780    pub margin: Rect<LengthPercentageAuto>,
781    /// How large should the padding be on each side?
782    #[cfg_attr(feature = "serde", serde(default = "style_helpers::zero"))]
783    pub padding: Rect<LengthPercentage>,
784    /// How large should the border be on each side?
785    #[cfg_attr(feature = "serde", serde(default = "style_helpers::zero"))]
786    pub border: Rect<LengthPercentage>,
787
788    // Alignment properties
789    /// How this node's children aligned in the cross/block axis?
790    #[cfg(any(feature = "flexbox", feature = "grid"))]
791    pub align_items: AlignItems,
792    /// How this node should be aligned in the cross/block axis
793    /// Falls back to the parents [`AlignItems`] if not set
794    pub align_self: Option<AlignSelf>,
795    /// How this node's children should be aligned in the inline axis
796    #[cfg(any(feature = "grid", feature = "block_layout"))]
797    pub justify_items: AlignItems,
798    /// How this node should be aligned in the inline axis
799    /// Falls back to the parents [`JustifyItems`] if not set
800    pub justify_self: Option<AlignSelf>,
801    /// How should content contained within this item be aligned in the cross/block axis
802    #[cfg(any(feature = "flexbox", feature = "grid", feature = "block_layout"))]
803    pub align_content: AlignContent,
804    /// How should content contained within this item be aligned in the main/inline axis
805    #[cfg(any(feature = "flexbox", feature = "grid"))]
806    pub justify_content: JustifyContent,
807    /// How large should the gaps between items in a grid or flex container be?
808    #[cfg(any(feature = "flexbox", feature = "grid"))]
809    #[cfg_attr(feature = "serde", serde(default = "style_helpers::zero"))]
810    pub gap: Size<LengthPercentage>,
811
812    // Block container properties
813    /// How items elements should aligned in the inline axis
814    #[cfg(feature = "block_layout")]
815    pub text_align: TextAlign,
816
817    // Flexbox container properties
818    /// Which direction does the main axis flow in?
819    #[cfg(feature = "flexbox")]
820    pub flex_direction: FlexDirection,
821    /// Should elements wrap, or stay in a single line?
822    #[cfg(feature = "flexbox")]
823    pub flex_wrap: FlexWrap,
824    /// The minimum number of flex lines requested for a multi-line container. When items are
825    /// balanced ([`FlexWrap::Balance`] or [`FlexWrap::BalanceReverse`]) they are balanced into
826    /// at least this many lines. For any multi-line container, definite cross-axis available
827    /// space for measuring items is divided between this many lines.
828    ///
829    /// 1 is the default value, and this value must be at least 1.
830    #[cfg(feature = "flexbox_balance")]
831    pub flex_line_count: u16,
832
833    // Flexbox item properties
834    /// Sets the initial main axis size of the item
835    #[cfg(feature = "flexbox")]
836    pub flex_basis: Dimension,
837    /// The relative rate at which this item grows when it is expanding to fill space
838    ///
839    /// 0.0 is the default value, and this value must be positive.
840    #[cfg(feature = "flexbox")]
841    pub flex_grow: f32,
842    /// The relative rate at which this item shrinks when it is contracting to fit into space
843    ///
844    /// 1.0 is the default value, and this value must be positive.
845    #[cfg(feature = "flexbox")]
846    pub flex_shrink: f32,
847
848    // Grid container properies
849    /// Defines the track sizing functions (heights) of the grid rows
850    #[cfg(feature = "grid")]
851    pub grid_template_rows: GridTrackVec<GridTemplateComponent<S>>,
852    /// Defines the track sizing functions (widths) of the grid columns
853    #[cfg(feature = "grid")]
854    pub grid_template_columns: GridTrackVec<GridTemplateComponent<S>>,
855    /// Defines the size of implicitly created rows
856    #[cfg(feature = "grid")]
857    pub grid_auto_rows: GridTrackVec<TrackSizingFunction>,
858    /// Defined the size of implicitly created columns
859    #[cfg(feature = "grid")]
860    pub grid_auto_columns: GridTrackVec<TrackSizingFunction>,
861    /// Controls how items get placed into the grid for auto-placed items
862    #[cfg(feature = "grid")]
863    pub grid_auto_flow: GridAutoFlow,
864
865    // Grid container named properties
866    /// Defines the rectangular grid areas
867    #[cfg(feature = "grid")]
868    pub grid_template_areas: Option<GridTemplateAreas<S>>,
869    /// The named lines between the columns
870    #[cfg(feature = "grid")]
871    pub grid_template_column_names: GridTrackVec<GridTrackVec<S>>,
872    /// The named lines between the rows
873    #[cfg(feature = "grid")]
874    pub grid_template_row_names: GridTrackVec<GridTrackVec<S>>,
875
876    // Grid child properties
877    /// Defines which row in the grid the item should start and end at
878    #[cfg(feature = "grid")]
879    pub grid_row: Line<GridPlacement<S>>,
880    /// Defines which column in the grid the item should start and end at
881    #[cfg(feature = "grid")]
882    pub grid_column: Line<GridPlacement<S>>,
883}
884
885impl<S: CheapCloneStr> Style<S> {
886    /// The [`Default`] layout, in a form that can be used in const functions
887    pub const DEFAULT: Style<S> = Style {
888        dummy: core::marker::PhantomData,
889        display: Display::DEFAULT,
890        item_is_table: false,
891        item_is_replaced: false,
892        item_is_compressible_replaced: false,
893        box_sizing: BoxSizing::BorderBox,
894        direction: Direction::Ltr,
895        overflow: Point { x: Overflow::Visible, y: Overflow::Visible },
896        scrollbar_width: 0.0,
897        contain: Contain::NONE,
898        #[cfg(feature = "float_layout")]
899        float: Float::None,
900        #[cfg(feature = "float_layout")]
901        clear: Clear::None,
902        position: Position::Static,
903        inset: Rect::auto(),
904        margin: Rect::zero(),
905        padding: Rect::zero(),
906        border: Rect::zero(),
907        size: Size::auto(),
908        min_size: Size::auto(),
909        max_size: Size::auto(),
910        aspect_ratio: None,
911        #[cfg(any(feature = "flexbox", feature = "grid"))]
912        gap: Size::zero(),
913        // Alignment
914        #[cfg(any(feature = "flexbox", feature = "grid"))]
915        align_items: AlignItems::NORMAL,
916        align_self: None,
917        #[cfg(any(feature = "grid", feature = "block_layout"))]
918        justify_items: AlignItems::NORMAL,
919        justify_self: None,
920        #[cfg(any(feature = "flexbox", feature = "grid", feature = "block_layout"))]
921        align_content: AlignContent::NORMAL,
922        #[cfg(any(feature = "flexbox", feature = "grid"))]
923        justify_content: JustifyContent::NORMAL,
924        // Block
925        #[cfg(feature = "block_layout")]
926        text_align: TextAlign::Auto,
927        // Flexbox
928        #[cfg(feature = "flexbox")]
929        flex_direction: FlexDirection::Row,
930        #[cfg(feature = "flexbox")]
931        flex_wrap: FlexWrap::NoWrap,
932        #[cfg(feature = "flexbox_balance")]
933        flex_line_count: 1,
934        #[cfg(feature = "flexbox")]
935        flex_grow: 0.0,
936        #[cfg(feature = "flexbox")]
937        flex_shrink: 1.0,
938        #[cfg(feature = "flexbox")]
939        flex_basis: Dimension::AUTO,
940        // Grid
941        #[cfg(feature = "grid")]
942        grid_template_rows: GridTrackVec::new(),
943        #[cfg(feature = "grid")]
944        grid_template_columns: GridTrackVec::new(),
945        #[cfg(feature = "grid")]
946        grid_template_areas: None,
947        #[cfg(feature = "grid")]
948        grid_template_column_names: GridTrackVec::new(),
949        #[cfg(feature = "grid")]
950        grid_template_row_names: GridTrackVec::new(),
951        #[cfg(feature = "grid")]
952        grid_auto_rows: GridTrackVec::new(),
953        #[cfg(feature = "grid")]
954        grid_auto_columns: GridTrackVec::new(),
955        #[cfg(feature = "grid")]
956        grid_auto_flow: GridAutoFlow::Row,
957        #[cfg(feature = "grid")]
958        grid_row: Line { start: GridPlacement::<S>::Auto, end: GridPlacement::<S>::Auto },
959        #[cfg(feature = "grid")]
960        grid_column: Line { start: GridPlacement::<S>::Auto, end: GridPlacement::<S>::Auto },
961    };
962}
963
964impl<S: CheapCloneStr> Default for Style<S> {
965    fn default() -> Self {
966        Style::DEFAULT
967    }
968}
969
970impl<S: CheapCloneStr> CoreStyle for Style<S> {
971    type CustomIdent = S;
972
973    #[inline(always)]
974    fn box_generation_mode(&self) -> BoxGenerationMode {
975        match self.display {
976            Display::None => BoxGenerationMode::None,
977            _ => BoxGenerationMode::Normal,
978        }
979    }
980    #[inline(always)]
981    #[cfg(feature = "block_layout")]
982    fn is_block(&self) -> bool {
983        matches!(self.display, Display::Block)
984    }
985    #[inline(always)]
986    fn is_compressible_replaced(&self) -> bool {
987        self.item_is_replaced || self.item_is_compressible_replaced
988    }
989    #[inline(always)]
990    fn is_replaced(&self) -> bool {
991        self.item_is_replaced
992    }
993    #[inline(always)]
994    fn box_sizing(&self) -> BoxSizing {
995        self.box_sizing
996    }
997    #[inline(always)]
998    fn direction(&self) -> Direction {
999        self.direction
1000    }
1001    #[inline(always)]
1002    fn overflow(&self) -> Point<Overflow> {
1003        self.overflow
1004    }
1005    #[inline(always)]
1006    fn scrollbar_width(&self) -> f32 {
1007        self.scrollbar_width
1008    }
1009    #[inline(always)]
1010    fn position(&self) -> Position {
1011        self.position
1012    }
1013    #[inline(always)]
1014    fn inset(&self) -> Rect<LengthPercentageAuto> {
1015        self.inset
1016    }
1017    #[inline(always)]
1018    fn size(&self) -> Size<Dimension> {
1019        self.size
1020    }
1021    #[inline(always)]
1022    fn min_size(&self) -> Size<LengthPercentageAuto> {
1023        self.min_size
1024    }
1025    #[inline(always)]
1026    fn max_size(&self) -> Size<LengthPercentageAuto> {
1027        self.max_size
1028    }
1029    #[inline(always)]
1030    fn aspect_ratio(&self) -> Option<f32> {
1031        self.aspect_ratio
1032    }
1033    #[inline(always)]
1034    fn margin(&self) -> Rect<LengthPercentageAuto> {
1035        self.margin
1036    }
1037    #[inline(always)]
1038    fn padding(&self) -> Rect<LengthPercentage> {
1039        self.padding
1040    }
1041    #[inline(always)]
1042    fn border(&self) -> Rect<LengthPercentage> {
1043        self.border
1044    }
1045    #[inline(always)]
1046    fn contain(&self) -> Contain {
1047        self.contain
1048    }
1049}
1050
1051impl<S: CheapCloneStr> OofItemStyle for Style<S> {
1052    #[inline(always)]
1053    fn align_self(&self) -> Option<AlignSelf> {
1054        self.align_self
1055    }
1056    #[inline(always)]
1057    fn justify_self(&self) -> Option<AlignSelf> {
1058        self.justify_self
1059    }
1060    #[inline(always)]
1061    fn is_table(&self) -> bool {
1062        self.item_is_table
1063    }
1064    #[cfg(feature = "grid")]
1065    #[inline(always)]
1066    fn grid_row(&self) -> Line<GridPlacement<S>> {
1067        // TODO: Investigate eliminating clone
1068        self.grid_row.clone()
1069    }
1070    #[cfg(feature = "grid")]
1071    #[inline(always)]
1072    fn grid_column(&self) -> Line<GridPlacement<S>> {
1073        // TODO: Investigate eliminating clone
1074        self.grid_column.clone()
1075    }
1076}
1077
1078impl<T: CoreStyle> CoreStyle for &'_ T {
1079    type CustomIdent = T::CustomIdent;
1080
1081    #[inline(always)]
1082    fn box_generation_mode(&self) -> BoxGenerationMode {
1083        (*self).box_generation_mode()
1084    }
1085    #[inline(always)]
1086    fn is_block(&self) -> bool {
1087        (*self).is_block()
1088    }
1089    #[inline(always)]
1090    fn is_compressible_replaced(&self) -> bool {
1091        (*self).is_compressible_replaced()
1092    }
1093    #[inline(always)]
1094    fn is_replaced(&self) -> bool {
1095        (*self).is_replaced()
1096    }
1097    #[inline(always)]
1098    fn box_sizing(&self) -> BoxSizing {
1099        (*self).box_sizing()
1100    }
1101    #[inline(always)]
1102    fn direction(&self) -> Direction {
1103        (*self).direction()
1104    }
1105    #[inline(always)]
1106    fn overflow(&self) -> Point<Overflow> {
1107        (*self).overflow()
1108    }
1109    #[inline(always)]
1110    fn scrollbar_width(&self) -> f32 {
1111        (*self).scrollbar_width()
1112    }
1113    #[inline(always)]
1114    fn position(&self) -> Position {
1115        (*self).position()
1116    }
1117    #[inline(always)]
1118    fn inset(&self) -> Rect<LengthPercentageAuto> {
1119        (*self).inset()
1120    }
1121    #[inline(always)]
1122    fn is_containing_block(&self) -> ContainingBlockClaims {
1123        (*self).is_containing_block()
1124    }
1125    #[inline(always)]
1126    fn size(&self) -> Size<Dimension> {
1127        (*self).size()
1128    }
1129    #[inline(always)]
1130    fn min_size(&self) -> Size<LengthPercentageAuto> {
1131        (*self).min_size()
1132    }
1133    #[inline(always)]
1134    fn max_size(&self) -> Size<LengthPercentageAuto> {
1135        (*self).max_size()
1136    }
1137    #[inline(always)]
1138    fn aspect_ratio(&self) -> Option<f32> {
1139        (*self).aspect_ratio()
1140    }
1141    #[inline(always)]
1142    fn margin(&self) -> Rect<LengthPercentageAuto> {
1143        (*self).margin()
1144    }
1145    #[inline(always)]
1146    fn padding(&self) -> Rect<LengthPercentage> {
1147        (*self).padding()
1148    }
1149    #[inline(always)]
1150    fn border(&self) -> Rect<LengthPercentage> {
1151        (*self).border()
1152    }
1153    #[inline(always)]
1154    fn contain(&self) -> Contain {
1155        (*self).contain()
1156    }
1157}
1158
1159impl<T: OofItemStyle> OofItemStyle for &'_ T {
1160    #[inline(always)]
1161    fn align_self(&self) -> Option<AlignSelf> {
1162        (*self).align_self()
1163    }
1164    #[inline(always)]
1165    fn justify_self(&self) -> Option<AlignSelf> {
1166        (*self).justify_self()
1167    }
1168    #[inline(always)]
1169    fn is_table(&self) -> bool {
1170        (*self).is_table()
1171    }
1172    #[cfg(feature = "grid")]
1173    #[inline(always)]
1174    fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
1175        (*self).grid_row()
1176    }
1177    #[cfg(feature = "grid")]
1178    #[inline(always)]
1179    fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
1180        (*self).grid_column()
1181    }
1182}
1183
1184#[cfg(feature = "block_layout")]
1185impl<S: CheapCloneStr> BlockContainerStyle for Style<S> {
1186    #[inline(always)]
1187    fn text_align(&self) -> TextAlign {
1188        self.text_align
1189    }
1190
1191    #[inline(always)]
1192    fn align_content(&self) -> AlignContent {
1193        self.align_content
1194    }
1195
1196    #[inline(always)]
1197    fn justify_items(&self) -> AlignItems {
1198        self.justify_items
1199    }
1200}
1201
1202#[cfg(feature = "block_layout")]
1203impl<T: BlockContainerStyle> BlockContainerStyle for &'_ T {
1204    #[inline(always)]
1205    fn text_align(&self) -> TextAlign {
1206        (*self).text_align()
1207    }
1208
1209    #[inline(always)]
1210    fn align_content(&self) -> AlignContent {
1211        (*self).align_content()
1212    }
1213
1214    #[inline(always)]
1215    fn justify_items(&self) -> AlignItems {
1216        (*self).justify_items()
1217    }
1218}
1219
1220#[cfg(feature = "block_layout")]
1221impl<S: CheapCloneStr> BlockItemStyle for Style<S> {
1222    #[inline(always)]
1223    fn is_table(&self) -> bool {
1224        self.item_is_table
1225    }
1226
1227    #[inline(always)]
1228    fn align_self(&self) -> Option<AlignSelf> {
1229        self.align_self
1230    }
1231
1232    #[inline(always)]
1233    fn justify_self(&self) -> Option<AlignSelf> {
1234        self.justify_self
1235    }
1236
1237    #[inline(always)]
1238    fn align_content(&self) -> AlignContent {
1239        self.align_content
1240    }
1241
1242    #[cfg(feature = "float_layout")]
1243    #[inline(always)]
1244    fn float(&self) -> Float {
1245        self.float
1246    }
1247
1248    #[cfg(feature = "float_layout")]
1249    #[inline(always)]
1250    fn clear(&self) -> Clear {
1251        self.clear
1252    }
1253}
1254
1255#[cfg(feature = "block_layout")]
1256impl<T: BlockItemStyle> BlockItemStyle for &'_ T {
1257    #[inline(always)]
1258    fn is_table(&self) -> bool {
1259        (*self).is_table()
1260    }
1261
1262    #[inline(always)]
1263    fn align_self(&self) -> Option<AlignSelf> {
1264        (*self).align_self()
1265    }
1266
1267    #[inline(always)]
1268    fn justify_self(&self) -> Option<AlignSelf> {
1269        (*self).justify_self()
1270    }
1271
1272    #[inline(always)]
1273    fn align_content(&self) -> AlignContent {
1274        (*self).align_content()
1275    }
1276
1277    #[cfg(feature = "float_layout")]
1278    #[inline(always)]
1279    fn float(&self) -> Float {
1280        (*self).float()
1281    }
1282
1283    #[cfg(feature = "float_layout")]
1284    #[inline(always)]
1285    fn clear(&self) -> Clear {
1286        (*self).clear()
1287    }
1288}
1289
1290#[cfg(feature = "flexbox")]
1291impl<S: CheapCloneStr> FlexboxContainerStyle for Style<S> {
1292    #[inline(always)]
1293    fn flex_direction(&self) -> FlexDirection {
1294        self.flex_direction
1295    }
1296    #[inline(always)]
1297    fn flex_wrap(&self) -> FlexWrap {
1298        self.flex_wrap
1299    }
1300    #[cfg(feature = "flexbox_balance")]
1301    #[inline(always)]
1302    fn flex_line_count(&self) -> u16 {
1303        self.flex_line_count
1304    }
1305    #[inline(always)]
1306    fn gap(&self) -> Size<LengthPercentage> {
1307        self.gap
1308    }
1309    #[inline(always)]
1310    fn align_content(&self) -> AlignContent {
1311        self.align_content
1312    }
1313    #[inline(always)]
1314    fn align_items(&self) -> AlignItems {
1315        self.align_items
1316    }
1317    #[inline(always)]
1318    fn justify_content(&self) -> JustifyContent {
1319        self.justify_content
1320    }
1321}
1322
1323#[cfg(feature = "flexbox")]
1324impl<T: FlexboxContainerStyle> FlexboxContainerStyle for &'_ T {
1325    #[inline(always)]
1326    fn flex_direction(&self) -> FlexDirection {
1327        (*self).flex_direction()
1328    }
1329    #[inline(always)]
1330    fn flex_wrap(&self) -> FlexWrap {
1331        (*self).flex_wrap()
1332    }
1333    #[cfg(feature = "flexbox_balance")]
1334    #[inline(always)]
1335    fn flex_line_count(&self) -> u16 {
1336        (*self).flex_line_count()
1337    }
1338    #[inline(always)]
1339    fn gap(&self) -> Size<LengthPercentage> {
1340        (*self).gap()
1341    }
1342    #[inline(always)]
1343    fn align_content(&self) -> AlignContent {
1344        (*self).align_content()
1345    }
1346    #[inline(always)]
1347    fn align_items(&self) -> AlignItems {
1348        (*self).align_items()
1349    }
1350    #[inline(always)]
1351    fn justify_content(&self) -> JustifyContent {
1352        (*self).justify_content()
1353    }
1354}
1355
1356#[cfg(feature = "flexbox")]
1357impl<S: CheapCloneStr> FlexboxItemStyle for Style<S> {
1358    #[inline(always)]
1359    fn flex_basis(&self) -> Dimension {
1360        self.flex_basis
1361    }
1362    #[inline(always)]
1363    fn flex_grow(&self) -> f32 {
1364        self.flex_grow
1365    }
1366    #[inline(always)]
1367    fn flex_shrink(&self) -> f32 {
1368        self.flex_shrink
1369    }
1370    #[inline(always)]
1371    fn align_self(&self) -> Option<AlignSelf> {
1372        self.align_self
1373    }
1374}
1375
1376#[cfg(feature = "flexbox")]
1377impl<T: FlexboxItemStyle> FlexboxItemStyle for &'_ T {
1378    #[inline(always)]
1379    fn flex_basis(&self) -> Dimension {
1380        (*self).flex_basis()
1381    }
1382    #[inline(always)]
1383    fn flex_grow(&self) -> f32 {
1384        (*self).flex_grow()
1385    }
1386    #[inline(always)]
1387    fn flex_shrink(&self) -> f32 {
1388        (*self).flex_shrink()
1389    }
1390    #[inline(always)]
1391    fn align_self(&self) -> Option<AlignSelf> {
1392        (*self).align_self()
1393    }
1394}
1395
1396#[cfg(feature = "grid")]
1397impl<S: CheapCloneStr> GridContainerStyle for Style<S> {
1398    type Repetition<'a>
1399        = &'a GridTemplateRepetition<S>
1400    where
1401        Self: 'a;
1402
1403    type TemplateTrackList<'a>
1404        = core::iter::Map<
1405        core::slice::Iter<'a, GridTemplateComponent<S>>,
1406        fn(&'a GridTemplateComponent<S>) -> GenericGridTemplateComponent<S, &'a GridTemplateRepetition<S>>,
1407    >
1408    where
1409        Self: 'a;
1410
1411    type AutoTrackList<'a>
1412        = core::iter::Copied<core::slice::Iter<'a, TrackSizingFunction>>
1413    where
1414        Self: 'a;
1415
1416    #[cfg(feature = "grid")]
1417    type TemplateLineNames<'a>
1418        = core::iter::Map<core::slice::Iter<'a, GridTrackVec<S>>, fn(&GridTrackVec<S>) -> core::slice::Iter<'_, S>>
1419    where
1420        Self: 'a;
1421    #[cfg(feature = "grid")]
1422    type GridTemplateAreas<'a>
1423        = core::iter::Cloned<core::slice::Iter<'a, GridTemplateArea<S>>>
1424    where
1425        Self: 'a;
1426
1427    #[inline(always)]
1428    fn grid_template_rows(&self) -> Option<Self::TemplateTrackList<'_>> {
1429        Some(self.grid_template_rows.iter().map(|c| c.as_component_ref()))
1430    }
1431    #[inline(always)]
1432    fn grid_template_columns(&self) -> Option<Self::TemplateTrackList<'_>> {
1433        Some(self.grid_template_columns.iter().map(|c| c.as_component_ref()))
1434    }
1435    #[inline(always)]
1436    fn grid_auto_rows(&self) -> Self::AutoTrackList<'_> {
1437        self.grid_auto_rows.iter().copied()
1438    }
1439    #[inline(always)]
1440    fn grid_auto_columns(&self) -> Self::AutoTrackList<'_> {
1441        self.grid_auto_columns.iter().copied()
1442    }
1443    #[inline(always)]
1444    fn grid_auto_flow(&self) -> GridAutoFlow {
1445        self.grid_auto_flow
1446    }
1447    #[inline(always)]
1448    fn gap(&self) -> Size<LengthPercentage> {
1449        self.gap
1450    }
1451    #[inline(always)]
1452    fn align_content(&self) -> AlignContent {
1453        self.align_content
1454    }
1455    #[inline(always)]
1456    fn justify_content(&self) -> JustifyContent {
1457        self.justify_content
1458    }
1459    #[inline(always)]
1460    fn align_items(&self) -> AlignItems {
1461        self.align_items
1462    }
1463    #[inline(always)]
1464    fn justify_items(&self) -> AlignItems {
1465        self.justify_items
1466    }
1467
1468    #[inline(always)]
1469    #[cfg(feature = "grid")]
1470    fn grid_template_areas(&self) -> Option<Self::GridTemplateAreas<'_>> {
1471        self.grid_template_areas.as_ref().map(|template| template.areas.iter().cloned())
1472    }
1473    #[inline(always)]
1474    #[cfg(feature = "grid")]
1475    fn grid_template_area_row_count(&self) -> u16 {
1476        self.grid_template_areas.as_ref().map(|template| template.row_count).unwrap_or(0)
1477    }
1478    #[inline(always)]
1479    #[cfg(feature = "grid")]
1480    fn grid_template_area_column_count(&self) -> u16 {
1481        self.grid_template_areas.as_ref().map(|template| template.column_count).unwrap_or(0)
1482    }
1483
1484    #[inline(always)]
1485    #[cfg(feature = "grid")]
1486    fn grid_template_column_names(&self) -> Option<Self::TemplateLineNames<'_>> {
1487        Some(self.grid_template_column_names.iter().map(|names| names.iter()))
1488    }
1489
1490    #[inline(always)]
1491    #[cfg(feature = "grid")]
1492    fn grid_template_row_names(&self) -> Option<Self::TemplateLineNames<'_>> {
1493        Some(self.grid_template_row_names.iter().map(|names| names.iter()))
1494    }
1495}
1496
1497#[cfg(feature = "grid")]
1498impl<T: GridContainerStyle> GridContainerStyle for &'_ T {
1499    type Repetition<'a>
1500        = T::Repetition<'a>
1501    where
1502        Self: 'a;
1503
1504    type TemplateTrackList<'a>
1505        = T::TemplateTrackList<'a>
1506    where
1507        Self: 'a;
1508
1509    type AutoTrackList<'a>
1510        = T::AutoTrackList<'a>
1511    where
1512        Self: 'a;
1513
1514    /// The type returned by grid_template_row_names and grid_template_column_names
1515    #[cfg(feature = "grid")]
1516    type TemplateLineNames<'a>
1517        = T::TemplateLineNames<'a>
1518    where
1519        Self: 'a;
1520    #[cfg(feature = "grid")]
1521    type GridTemplateAreas<'a>
1522        = T::GridTemplateAreas<'a>
1523    where
1524        Self: 'a;
1525
1526    #[inline(always)]
1527    fn grid_template_rows(&self) -> Option<Self::TemplateTrackList<'_>> {
1528        (*self).grid_template_rows()
1529    }
1530    #[inline(always)]
1531    fn grid_template_columns(&self) -> Option<Self::TemplateTrackList<'_>> {
1532        (*self).grid_template_columns()
1533    }
1534    #[inline(always)]
1535    fn grid_auto_rows(&self) -> Self::AutoTrackList<'_> {
1536        (*self).grid_auto_rows()
1537    }
1538    #[inline(always)]
1539    fn grid_auto_columns(&self) -> Self::AutoTrackList<'_> {
1540        (*self).grid_auto_columns()
1541    }
1542    #[cfg(feature = "grid")]
1543    #[inline(always)]
1544    fn grid_template_areas(&self) -> Option<Self::GridTemplateAreas<'_>> {
1545        (*self).grid_template_areas()
1546    }
1547    #[inline(always)]
1548    fn grid_template_area_row_count(&self) -> u16 {
1549        (*self).grid_template_area_row_count()
1550    }
1551    #[inline(always)]
1552    fn grid_template_area_column_count(&self) -> u16 {
1553        (*self).grid_template_area_column_count()
1554    }
1555    #[cfg(feature = "grid")]
1556    #[inline(always)]
1557    fn grid_template_column_names(&self) -> Option<Self::TemplateLineNames<'_>> {
1558        (*self).grid_template_column_names()
1559    }
1560    #[cfg(feature = "grid")]
1561    #[inline(always)]
1562    fn grid_template_row_names(&self) -> Option<Self::TemplateLineNames<'_>> {
1563        (*self).grid_template_row_names()
1564    }
1565    #[inline(always)]
1566    fn grid_auto_flow(&self) -> GridAutoFlow {
1567        (*self).grid_auto_flow()
1568    }
1569    #[inline(always)]
1570    fn gap(&self) -> Size<LengthPercentage> {
1571        (*self).gap()
1572    }
1573    #[inline(always)]
1574    fn align_content(&self) -> AlignContent {
1575        (*self).align_content()
1576    }
1577    #[inline(always)]
1578    fn justify_content(&self) -> JustifyContent {
1579        (*self).justify_content()
1580    }
1581    #[inline(always)]
1582    fn align_items(&self) -> AlignItems {
1583        (*self).align_items()
1584    }
1585    #[inline(always)]
1586    fn justify_items(&self) -> AlignItems {
1587        (*self).justify_items()
1588    }
1589}
1590
1591#[cfg(feature = "grid")]
1592impl<S: CheapCloneStr> GridItemStyle for Style<S> {
1593    #[inline(always)]
1594    fn grid_row(&self) -> Line<GridPlacement<S>> {
1595        // TODO: Investigate eliminating clone
1596        self.grid_row.clone()
1597    }
1598    #[inline(always)]
1599    fn grid_column(&self) -> Line<GridPlacement<S>> {
1600        // TODO: Investigate eliminating clone
1601        self.grid_column.clone()
1602    }
1603    #[inline(always)]
1604    fn align_self(&self) -> Option<AlignSelf> {
1605        self.align_self
1606    }
1607    #[inline(always)]
1608    fn justify_self(&self) -> Option<AlignSelf> {
1609        self.justify_self
1610    }
1611}
1612
1613#[cfg(feature = "grid")]
1614impl<T: GridItemStyle> GridItemStyle for &'_ T {
1615    #[inline(always)]
1616    fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
1617        (*self).grid_row()
1618    }
1619    #[inline(always)]
1620    fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
1621        (*self).grid_column()
1622    }
1623    #[inline(always)]
1624    fn align_self(&self) -> Option<AlignSelf> {
1625        (*self).align_self()
1626    }
1627    #[inline(always)]
1628    fn justify_self(&self) -> Option<AlignSelf> {
1629        (*self).justify_self()
1630    }
1631}
1632
1633#[cfg(test)]
1634mod tests {
1635    use std::sync::Arc;
1636
1637    use super::Style;
1638    use crate::sys::DefaultCheapStr;
1639    use crate::{geometry::*, style_helpers::TaffyAuto as _};
1640
1641    #[test]
1642    fn defaults_match() {
1643        #[cfg(feature = "grid")]
1644        use super::GridPlacement;
1645
1646        let old_defaults: Style<DefaultCheapStr> = Style {
1647            dummy: core::marker::PhantomData,
1648            display: Default::default(),
1649            item_is_table: false,
1650            item_is_replaced: false,
1651            item_is_compressible_replaced: false,
1652            box_sizing: Default::default(),
1653            #[cfg(feature = "float_layout")]
1654            float: Default::default(),
1655            #[cfg(feature = "float_layout")]
1656            clear: Default::default(),
1657            direction: Default::default(),
1658            overflow: Default::default(),
1659            scrollbar_width: 0.0,
1660            contain: Default::default(),
1661            position: Default::default(),
1662            #[cfg(feature = "flexbox")]
1663            flex_direction: Default::default(),
1664            #[cfg(feature = "flexbox")]
1665            flex_wrap: Default::default(),
1666            #[cfg(feature = "flexbox_balance")]
1667            flex_line_count: 1,
1668            #[cfg(any(feature = "flexbox", feature = "grid"))]
1669            align_items: Default::default(),
1670            align_self: Default::default(),
1671            #[cfg(any(feature = "grid", feature = "block_layout"))]
1672            justify_items: Default::default(),
1673            justify_self: Default::default(),
1674            #[cfg(any(feature = "flexbox", feature = "grid", feature = "block_layout"))]
1675            align_content: Default::default(),
1676            #[cfg(any(feature = "flexbox", feature = "grid"))]
1677            justify_content: Default::default(),
1678            inset: Rect::auto(),
1679            margin: Rect::zero(),
1680            padding: Rect::zero(),
1681            border: Rect::zero(),
1682            gap: Size::zero(),
1683            #[cfg(feature = "block_layout")]
1684            text_align: Default::default(),
1685            #[cfg(feature = "flexbox")]
1686            flex_grow: 0.0,
1687            #[cfg(feature = "flexbox")]
1688            flex_shrink: 1.0,
1689            #[cfg(feature = "flexbox")]
1690            flex_basis: super::Dimension::AUTO,
1691            size: Size::auto(),
1692            min_size: Size::auto(),
1693            max_size: Size::auto(),
1694            aspect_ratio: Default::default(),
1695            #[cfg(feature = "grid")]
1696            grid_template_rows: Default::default(),
1697            #[cfg(feature = "grid")]
1698            grid_template_columns: Default::default(),
1699            #[cfg(feature = "grid")]
1700            grid_template_row_names: Default::default(),
1701            #[cfg(feature = "grid")]
1702            grid_template_column_names: Default::default(),
1703            #[cfg(feature = "grid")]
1704            grid_template_areas: Default::default(),
1705            #[cfg(feature = "grid")]
1706            grid_auto_rows: Default::default(),
1707            #[cfg(feature = "grid")]
1708            grid_auto_columns: Default::default(),
1709            #[cfg(feature = "grid")]
1710            grid_auto_flow: Default::default(),
1711            #[cfg(feature = "grid")]
1712            grid_row: Line { start: GridPlacement::Auto, end: GridPlacement::Auto },
1713            #[cfg(feature = "grid")]
1714            grid_column: Line { start: GridPlacement::Auto, end: GridPlacement::Auto },
1715        };
1716
1717        assert_eq!(Style::DEFAULT, Style::<DefaultCheapStr>::default());
1718        assert_eq!(Style::DEFAULT, old_defaults);
1719    }
1720
1721    #[test]
1722    #[cfg(feature = "parse")]
1723    fn parse_contain() {
1724        use super::Contain;
1725
1726        fn parse(input: &str) -> Contain {
1727            input.parse().unwrap()
1728        }
1729
1730        assert_eq!(parse("none"), Contain::NONE);
1731        assert_eq!(parse("content"), Contain::LAYOUT | Contain::PAINT);
1732        assert_eq!(parse("layout"), Contain::LAYOUT);
1733        assert_eq!(parse("style"), Contain::NONE);
1734        assert_eq!(parse("paint"), Contain::PAINT);
1735        assert_eq!(parse("layout paint"), Contain::LAYOUT | Contain::PAINT);
1736        assert_eq!(parse("paint layout"), Contain::LAYOUT | Contain::PAINT);
1737        assert_eq!(parse("layout paint style"), Contain::LAYOUT | Contain::PAINT);
1738        assert_eq!(parse("Paint LAYOUT"), Contain::LAYOUT | Contain::PAINT);
1739        assert!("paint paint".parse::<Contain>().is_err());
1740
1741        assert!("".parse::<Contain>().is_err());
1742        assert!("banana".parse::<Contain>().is_err());
1743        assert!("layout layout".parse::<Contain>().is_err());
1744        assert!("none layout".parse::<Contain>().is_err());
1745        assert!("layout none".parse::<Contain>().is_err());
1746        assert!("content layout".parse::<Contain>().is_err());
1747        assert!("layout content".parse::<Contain>().is_err());
1748    }
1749
1750    // NOTE: Please feel free the update the sizes in this test as required. This test is here to prevent unintentional size changes
1751    // and to serve as accurate up-to-date documentation on the sizes.
1752    #[test]
1753    fn style_sizes() {
1754        use super::*;
1755        type S = crate::sys::DefaultCheapStr;
1756
1757        fn assert_type_size<T>(expected_size: usize) {
1758            let name = ::core::any::type_name::<T>();
1759            let name = name.replace("taffy::geometry::", "");
1760            let name = name.replace("taffy::style::dimension::", "");
1761            let name = name.replace("taffy::style::alignment::", "");
1762            let name = name.replace("taffy::style::flex::", "");
1763            let name = name.replace("taffy::style::grid::", "");
1764
1765            assert_eq!(
1766                ::core::mem::size_of::<T>(),
1767                expected_size,
1768                "Expected {} for be {} byte(s) but it was {} byte(s)",
1769                name,
1770                expected_size,
1771                ::core::mem::size_of::<T>(),
1772            );
1773        }
1774
1775        // Display and Position
1776        assert_type_size::<Display>(1);
1777        assert_type_size::<BoxSizing>(1);
1778        assert_type_size::<Position>(1);
1779        assert_type_size::<Overflow>(1);
1780
1781        // Dimensions and aggregations of Dimensions
1782        assert_type_size::<f32>(4);
1783        assert_type_size::<LengthPercentage>(8);
1784        assert_type_size::<LengthPercentageAuto>(8);
1785        assert_type_size::<Dimension>(8);
1786        assert_type_size::<Size<LengthPercentage>>(16);
1787        assert_type_size::<Size<LengthPercentageAuto>>(16);
1788        assert_type_size::<Size<Dimension>>(16);
1789        assert_type_size::<Rect<LengthPercentage>>(32);
1790        assert_type_size::<Rect<LengthPercentageAuto>>(32);
1791        assert_type_size::<Rect<Dimension>>(32);
1792
1793        // Alignment — `AlignContent` and `AlignItems` are structs of two `#[repr(u8)]` enums
1794        // (position keyword + safety modifier). Niche-packing in the safety byte (only 2 of
1795        // 256 values used) lets `Option<_>` stay the same size as the bare struct.
1796        assert_type_size::<AlignContentKeyword>(1);
1797        assert_type_size::<AlignItemsKeyword>(1);
1798        assert_type_size::<AlignmentSafety>(1);
1799        assert_type_size::<AlignContent>(2);
1800        assert_type_size::<AlignItems>(2);
1801        assert_type_size::<Option<AlignItems>>(2);
1802
1803        // Flexbox Container
1804        assert_type_size::<FlexDirection>(1);
1805        assert_type_size::<FlexWrap>(1);
1806
1807        // CSS Grid Container
1808        assert_type_size::<GridAutoFlow>(1);
1809        assert_type_size::<MinTrackSizingFunction>(8);
1810        assert_type_size::<MaxTrackSizingFunction>(8);
1811        assert_type_size::<TrackSizingFunction>(16);
1812        assert_type_size::<Vec<TrackSizingFunction>>(24);
1813        assert_type_size::<Vec<GridTemplateComponent<S>>>(24);
1814
1815        // String-type dependent (String)
1816        assert_type_size::<GridTemplateComponent<String>>(56);
1817        assert_type_size::<GridPlacement<String>>(32);
1818        assert_type_size::<Line<GridPlacement<String>>>(64);
1819        assert_type_size::<Style<String>>(560);
1820
1821        // String-type dependent (Arc<str>)
1822        assert_type_size::<GridTemplateComponent<Arc<str>>>(56);
1823        assert_type_size::<GridPlacement<Arc<str>>>(24);
1824        assert_type_size::<Line<GridPlacement<Arc<str>>>>(48);
1825        assert_type_size::<Style<Arc<str>>>(528);
1826    }
1827}