use crate::style::{
StyleError,
component::Component,
declaration::{self, Specified},
grammar::{Keyword, Label, NODES, Node, Production, Property},
logical::{BOTTOM, LEFT},
wide_keywords::WideKeyword,
};
use std::sync::Arc;
type Longhands = Vec<(Property, Specified)>;
type BorderSide = [Property; 3];
const BORDER_TOP: BorderSide = [
Property::BorderTopWidth,
Property::BorderTopStyle,
Property::BorderTopColor,
];
const BORDER_RIGHT: BorderSide = [
Property::BorderRightWidth,
Property::BorderRightStyle,
Property::BorderRightColor,
];
const BORDER_BOTTOM: BorderSide = [
Property::BorderBottomWidth,
Property::BorderBottomStyle,
Property::BorderBottomColor,
];
const BORDER_LEFT: BorderSide = [
Property::BorderLeftWidth,
Property::BorderLeftStyle,
Property::BorderLeftColor,
];
const BORDER_BLOCK_START: BorderSide = [
Property::BorderBlockStartWidth,
Property::BorderBlockStartStyle,
Property::BorderBlockStartColor,
];
const BORDER_BLOCK_END: BorderSide = [
Property::BorderBlockEndWidth,
Property::BorderBlockEndStyle,
Property::BorderBlockEndColor,
];
const BORDER_INLINE_START: BorderSide = [
Property::BorderInlineStartWidth,
Property::BorderInlineStartStyle,
Property::BorderInlineStartColor,
];
const BORDER_INLINE_END: BorderSide = [
Property::BorderInlineEndWidth,
Property::BorderInlineEndStyle,
Property::BorderInlineEndColor,
];
const BORDER_IMAGE: [Property; 5] = [
Property::BorderImageSource,
Property::BorderImageSlice,
Property::BorderImageWidth,
Property::BorderImageOutset,
Property::BorderImageRepeat,
];
const BORDER_IMAGE_SLOTS: usize = 3;
const LAYER_IMAGE: usize = 0;
const LAYER_POSITION: usize = 1;
const LAYER_REPEAT: usize = 2;
const LAYER_ATTACHMENT: usize = 3;
const LAYER_ORIGIN: usize = 4;
const LAYER_CLIP: usize = 5;
const LAYER_COLOR: usize = 6;
const FLEX_OMITTED_FACTOR: &str = "1";
const FLEX_OMITTED_BASIS: &str = "0%";
const FLEX_NONE: [&str; 3] = ["0", "0", "auto"];
const ROW_FLOW: &str = "row";
const COLUMN_FLOW: &str = "column";
const DENSE: &str = "dense";
const TRANSITION: [Property; 5] = [
Property::TransitionProperty,
Property::TransitionDuration,
Property::TransitionTimingFunction,
Property::TransitionDelay,
Property::TransitionBehavior,
];
const ANIMATION: [Property; 9] = [
Property::AnimationDuration,
Property::AnimationTimingFunction,
Property::AnimationDelay,
Property::AnimationIterationCount,
Property::AnimationDirection,
Property::AnimationFillMode,
Property::AnimationPlayState,
Property::AnimationName,
Property::AnimationTimeline,
];
const ANIMATION_RESET: [Property; 2] = [Property::AnimationRangeStart, Property::AnimationRangeEnd];
const NAMED_RANGE_END: f32 = 1.0;
const WHITE_SPACE_KEYWORDS: [(Keyword, &str, &str); 4] = [
(Keyword::Normal, "collapse", "wrap"),
(Keyword::Pre, "preserve", "nowrap"),
(Keyword::PreWrap, "preserve", "wrap"),
(Keyword::PreLine, "preserve-breaks", "wrap"),
];
const CLAMP_DISCARD: &str = "discard";
const CLAMP_WEBKIT_DISCARD: &str = "-webkit-discard";
const CLAMP_ELLIPSIS: &str = "auto";
const ORIENT_ROW: &str = "row";
const ORIENT_COLUMN: &str = "column";
const MARKERS: [Property; 3] = [
Property::MarkerStart,
Property::MarkerMid,
Property::MarkerEnd,
];
const SYNTHESIS_ON: &str = "auto";
const SYNTHESIS_OFF: &str = "none";
pub(crate) fn expand(shorthand: Property, value: Component) -> Result<Longhands, StyleError> {
use Property as P;
Ok(match shorthand {
P::Size => pair(&value, [P::Width, P::Height]),
P::MinSize => pair(&value, [P::MinWidth, P::MinHeight]),
P::MaxSize => pair(&value, [P::MaxWidth, P::MaxHeight]),
P::TextAlign => text_align(&value),
P::BoxShadow => box_shadow(&value),
P::Margin => edges(
&value,
[P::MarginTop, P::MarginRight, P::MarginBottom, P::MarginLeft],
),
P::Padding => edges(
&value,
[
P::PaddingTop,
P::PaddingRight,
P::PaddingBottom,
P::PaddingLeft,
],
),
P::Inset => edges(&value, [P::Top, P::Right, P::Bottom, P::Left]),
P::BorderWidth => edges(
&value,
[
P::BorderTopWidth,
P::BorderRightWidth,
P::BorderBottomWidth,
P::BorderLeftWidth,
],
),
P::BorderStyle => edges(
&value,
[
P::BorderTopStyle,
P::BorderRightStyle,
P::BorderBottomStyle,
P::BorderLeftStyle,
],
),
P::BorderColor => edges(
&value,
[
P::BorderTopColor,
P::BorderRightColor,
P::BorderBottomColor,
P::BorderLeftColor,
],
),
P::BorderRadius
| P::BorderTopRadius
| P::BorderRightRadius
| P::BorderBottomRadius
| P::BorderLeftRadius
| P::BorderBlockStartRadius
| P::BorderBlockEndRadius
| P::BorderInlineStartRadius
| P::BorderInlineEndRadius => radius(&value, shorthand.longhands()),
P::Border => border(
&value,
&[BORDER_TOP, BORDER_RIGHT, BORDER_BOTTOM, BORDER_LEFT],
)
.into_iter()
.chain(BORDER_IMAGE.map(|property| (property, initial())))
.collect(),
P::BorderImage => border_image(&value),
P::Columns => columns(&value),
P::BorderTop => border(&value, &[BORDER_TOP]),
P::BorderRight => border(&value, &[BORDER_RIGHT]),
P::BorderBottom => border(&value, &[BORDER_BOTTOM]),
P::BorderLeft => border(&value, &[BORDER_LEFT]),
P::MarginBlock => pair(&value, [P::MarginBlockStart, P::MarginBlockEnd]),
P::MarginInline => pair(&value, [P::MarginInlineStart, P::MarginInlineEnd]),
P::PaddingBlock => pair(&value, [P::PaddingBlockStart, P::PaddingBlockEnd]),
P::PaddingInline => pair(&value, [P::PaddingInlineStart, P::PaddingInlineEnd]),
P::InsetBlock => pair(&value, [P::InsetBlockStart, P::InsetBlockEnd]),
P::InsetInline => pair(&value, [P::InsetInlineStart, P::InsetInlineEnd]),
P::BorderBlockWidth => pair(&value, [P::BorderBlockStartWidth, P::BorderBlockEndWidth]),
P::BorderInlineWidth => pair(&value, [P::BorderInlineStartWidth, P::BorderInlineEndWidth]),
P::BorderBlockStyle => pair(&value, [P::BorderBlockStartStyle, P::BorderBlockEndStyle]),
P::BorderInlineStyle => pair(&value, [P::BorderInlineStartStyle, P::BorderInlineEndStyle]),
P::BorderBlockColor => pair(&value, [P::BorderBlockStartColor, P::BorderBlockEndColor]),
P::BorderInlineColor => pair(&value, [P::BorderInlineStartColor, P::BorderInlineEndColor]),
P::BorderBlockStart => border(&value, &[BORDER_BLOCK_START]),
P::BorderBlockEnd => border(&value, &[BORDER_BLOCK_END]),
P::BorderInlineStart => border(&value, &[BORDER_INLINE_START]),
P::BorderInlineEnd => border(&value, &[BORDER_INLINE_END]),
P::BorderBlock => border(&value, &[BORDER_BLOCK_START, BORDER_BLOCK_END]),
P::BorderInline => border(&value, &[BORDER_INLINE_START, BORDER_INLINE_END]),
P::Overflow => pair(&value, [P::OverflowX, P::OverflowY]),
P::OverflowClipMargin | P::OverflowClipMarginInline | P::OverflowClipMarginBlock => {
shorthand
.longhands()
.iter()
.map(|&property| (property, longhand(property, &value)))
.collect()
}
P::Gap | P::GridGap => pair(&value, [P::RowGap, P::ColumnGap]),
P::GridRowGap => alias(&value, P::RowGap),
P::GridColumnGap => alias(&value, P::ColumnGap),
P::GridRow => grid_lines(&value, [P::GridRowStart, P::GridRowEnd]),
P::GridColumn => grid_lines(&value, [P::GridColumnStart, P::GridColumnEnd]),
P::GridArea => grid_area(&value),
P::GridTemplate => grid_template(&value),
P::Grid => grid(&value)?,
P::PlaceContent => pair(&value, [P::AlignContent, P::JustifyContent]),
P::PlaceItems => pair(&value, [P::AlignItems, P::JustifyItems]),
P::PlaceSelf => pair(&value, [P::AlignSelf, P::JustifySelf]),
P::Flex => flex(&value)?,
P::Font => crate::style::font_values::expand_font(&value)?,
P::FontStretch => alias(value.unwrap(), P::FontWidth),
P::FontVariant => crate::style::font_values::expand_variant(&value)?,
P::FontSynthesis => font_synthesis(&value)?,
P::Background => background(&value)?,
P::Mask => mask(&value),
P::MaskBorder => sliced_image(&value, &MASK_BORDER, MASK_BORDER_SLOTS),
P::BackgroundPosition => background_position(&value)?,
P::PageBreakBefore => legacy_break(&value, P::BreakBefore)?,
P::PageBreakAfter => legacy_break(&value, P::BreakAfter)?,
P::PageBreakInside => legacy_break(&value, P::BreakInside)?,
P::WordWrap => alias(&value, P::OverflowWrap),
P::ColorAdjust => alias(&value, P::PrintColorAdjust),
P::DashWebkitAppearance => alias(&value, P::Appearance),
P::Marker => MARKERS
.into_iter()
.map(|marker| (marker, longhand(marker, &value)))
.collect(),
P::WhiteSpace => white_space(&value)?,
P::TextWrap => slotted(&value, &[P::TextWrapMode, P::TextWrapStyle]),
P::LineClamp => line_clamp(&value, false)?,
P::DashWebkitLineClamp => line_clamp(&value, true)?,
P::DashWebkitBoxOrient => box_orient(&value)?,
P::TextBox => text_box(&value)?,
P::TextSpacing => text_spacing(&value)?,
P::DashWebkitTextStroke => slots(
&value,
&[P::DashWebkitTextStrokeWidth, P::DashWebkitTextStrokeColor],
),
P::Transition => slotted_list(&value, &TRANSITION),
P::Animation => slotted_list(&value, &ANIMATION)
.into_iter()
.chain(ANIMATION_RESET.map(|property| (property, initial())))
.collect(),
P::ScrollTimeline => scroll_timeline(&value),
P::ViewTimeline => view_timeline(&value),
P::AnimationRange => animation_range(&value),
P::ScrollMargin => edges(
&value,
[
P::ScrollMarginTop,
P::ScrollMarginRight,
P::ScrollMarginBottom,
P::ScrollMarginLeft,
],
),
P::ScrollPadding => edges(
&value,
[
P::ScrollPaddingTop,
P::ScrollPaddingRight,
P::ScrollPaddingBottom,
P::ScrollPaddingLeft,
],
),
P::OverscrollBehavior => pair(&value, [P::OverscrollBehaviorX, P::OverscrollBehaviorY]),
P::ScrollMarginBlock => pair(&value, [P::ScrollMarginBlockStart, P::ScrollMarginBlockEnd]),
P::ScrollMarginInline => pair(
&value,
[P::ScrollMarginInlineStart, P::ScrollMarginInlineEnd],
),
P::ScrollPaddingBlock => pair(
&value,
[P::ScrollPaddingBlockStart, P::ScrollPaddingBlockEnd],
),
P::ScrollPaddingInline => pair(
&value,
[P::ScrollPaddingInlineStart, P::ScrollPaddingInlineEnd],
),
P::PositionTry => [P::PositionTryOrder, P::PositionTryFallbacks]
.into_iter()
.map(|property| {
(
property,
value
.find(Label::Property(property))
.map_or_else(initial, |value| longhand(property, value)),
)
})
.collect(),
P::InterestDelay => pair(&value, [P::InterestDelayStart, P::InterestDelayEnd]),
P::Container => {
let names = value
.find(Label::Property(P::ContainerName))
.ok_or_else(|| StyleError::Invalid(format!("container without names: {value}")))?;
vec![
(P::ContainerName, longhand(P::ContainerName, names)),
(
P::ContainerType,
value
.find(Label::Property(P::ContainerType))
.map_or_else(initial, |kind| longhand(P::ContainerType, kind)),
),
]
}
P::ContainIntrinsicSize => {
let items = value.items();
let height = items.get(1).unwrap_or(&items[0]);
vec![
(
P::ContainIntrinsicWidth,
longhand(P::ContainIntrinsicWidth, &items[0]),
),
(
P::ContainIntrinsicHeight,
longhand(P::ContainIntrinsicHeight, height),
),
]
}
_ => {
if let Some(longhands) = unordered_references(shorthand, &value)? {
longhands
} else {
let value = Arc::new(value);
declaration::longhands(shorthand)
.map(|longhand| (longhand, Specified::Unexpanded(shorthand, value.clone())))
.collect()
}
}
})
}
pub(super) fn longhand(longhand: Property, component: &Component) -> Specified {
let inner = match component {
Component::Reference(Label::Property(_), inner) => inner.as_ref().clone(),
other => other.clone(),
};
Specified::Value(Arc::new(Component::Reference(
Label::Property(longhand),
Box::new(inner),
)))
}
fn initial() -> Specified {
Specified::Wide(WideKeyword::Initial)
}
fn literal(property: Property, source: &str) -> Result<Specified, StyleError> {
declaration::value(property, source, &mut 0)?
.map(|value| Specified::Value(Arc::new(value)))
.ok_or_else(|| StyleError::Invalid(format!("{source} is not a {}", property.name())))
}
pub(super) fn edge_value(count: usize, side: usize) -> usize {
match (count, side) {
(1, _) => 0,
(2 | 3, LEFT) => 1,
(2, BOTTOM) => 0,
_ => side,
}
}
fn edges(value: &Component, sides: [Property; 4]) -> Longhands {
let items = value.items();
sides
.iter()
.enumerate()
.map(|(side, property)| {
(
*property,
longhand(*property, &items[edge_value(items.len(), side)]),
)
})
.collect()
}
fn pair(value: &Component, properties: [Property; 2]) -> Longhands {
let items: Vec<&Component> = match value.unwrap() {
Component::Group(items) => items
.iter()
.flat_map(|item| match item {
Component::Group(nested) => nested.iter().collect(),
single => vec![single],
})
.collect(),
single => vec![single],
};
let first = items[0];
let second = items.get(1).copied().unwrap_or(first);
vec![
(properties[0], longhand(properties[0], first)),
(properties[1], longhand(properties[1], second)),
]
}
fn text_align(value: &Component) -> Longhands {
let justify = Component::Keyword(Keyword::Justify);
let auto = Component::Keyword(Keyword::Auto);
let (all, last) = match value.keyword() {
Some(Keyword::JustifyAll) => (&justify, &justify),
Some(Keyword::MatchParent) => (value, value),
_ => (value, &auto),
};
vec![
(
Property::TextAlignAll,
longhand(Property::TextAlignAll, all),
),
(
Property::TextAlignLast,
longhand(Property::TextAlignLast, last),
),
]
}
pub(super) fn corner_values(value: &Component) -> [Component; 4] {
let [horizontal, vertical] = match value.unwrap() {
Component::Group(parts) => [
parts[0].items(),
parts[1]
.items()
.first()
.and_then(|slash| slash.items().get(1))
.map_or(&[][..], Component::items),
],
single => [std::slice::from_ref(single), &[][..]],
};
std::array::from_fn(|corner| {
let mut radii = vec![horizontal[edge_value(horizontal.len(), corner)].clone()];
if !vertical.is_empty() {
radii.push(vertical[edge_value(vertical.len(), corner)].clone());
}
Component::Group(radii)
})
}
fn radius(value: &Component, properties: &[Property]) -> Longhands {
properties
.iter()
.copied()
.zip(corner_values(value))
.map(|(property, radii)| (property, longhand(property, &radii)))
.collect()
}
fn border(value: &Component, sides: &[BorderSide]) -> Longhands {
sides.iter().flat_map(|side| slots(value, side)).collect()
}
fn slots(value: &Component, properties: &[Property]) -> Longhands {
properties
.iter()
.enumerate()
.map(|(part, property)| {
let specified = value
.slot(part)
.map_or_else(initial, |slot| longhand(*property, slot));
(*property, specified)
})
.collect()
}
fn border_image(value: &Component) -> Longhands {
sliced_image(value, &BORDER_IMAGE, BORDER_IMAGE_SLOTS)
}
fn sliced_image(value: &Component, properties: &[Property], slots: usize) -> Longhands {
properties
.iter()
.map(|property| {
let found = (0..slots)
.filter_map(|slot| value.slot(slot))
.find_map(|slot| slot.find(Label::Property(*property)));
(
*property,
found.map_or_else(initial, |component| longhand(*property, component)),
)
})
.collect()
}
fn columns(value: &Component) -> Longhands {
[
Property::ColumnWidth,
Property::ColumnCount,
Property::ColumnHeight,
]
.iter()
.map(|property| {
(
*property,
value
.find(Label::Property(*property))
.map_or_else(initial, |component| longhand(*property, component)),
)
})
.collect()
}
fn flex(value: &Component) -> Result<Longhands, StyleError> {
let properties = [
Property::FlexGrow,
Property::FlexShrink,
Property::FlexBasis,
];
if value.keyword() == Some(Keyword::None) {
return properties
.iter()
.zip(FLEX_NONE)
.map(|(property, source)| Ok((*property, literal(*property, source)?)))
.collect();
}
let factors = value.slot(0);
let grow = factors.and_then(|factors| factors.find(Label::Property(Property::FlexGrow)));
let shrink = factors.and_then(|factors| factors.find(Label::Property(Property::FlexShrink)));
let basis = value.slot(1);
let resolve = |property: Property, found: Option<&Component>, omitted: &str| {
found.map_or_else(
|| literal(property, omitted),
|component| Ok(longhand(property, component)),
)
};
Ok(vec![
(
Property::FlexGrow,
resolve(Property::FlexGrow, grow, FLEX_OMITTED_FACTOR)?,
),
(
Property::FlexShrink,
resolve(Property::FlexShrink, shrink, FLEX_OMITTED_FACTOR)?,
),
(
Property::FlexBasis,
resolve(Property::FlexBasis, basis, FLEX_OMITTED_BASIS)?,
),
])
}
fn font_synthesis(value: &Component) -> Result<Longhands, StyleError> {
[
Property::FontSynthesisWeight,
Property::FontSynthesisStyle,
Property::FontSynthesisSmallCaps,
Property::FontSynthesisPosition,
]
.iter()
.enumerate()
.map(|(index, property)| {
let allowed = value.slot(index).is_some();
Ok((
*property,
literal(
*property,
if allowed { SYNTHESIS_ON } else { SYNTHESIS_OFF },
)?,
))
})
.collect()
}
fn legacy_break(value: &Component, property: Property) -> Result<Longhands, StyleError> {
let keyword = match value.keyword() {
Some(Keyword::Always) => Keyword::Page,
Some(keyword) => keyword,
None => return Err(StyleError::Invalid(format!("legacy break {value}"))),
};
Ok(vec![(property, literal(property, keyword.name())?)])
}
fn white_space(value: &Component) -> Result<Longhands, StyleError> {
if let Some(keyword) = value.keyword()
&& let Some((_, collapse, wrap)) = WHITE_SPACE_KEYWORDS
.iter()
.find(|(candidate, ..)| *candidate == keyword)
{
return Ok(vec![
(
Property::WhiteSpaceCollapse,
literal(Property::WhiteSpaceCollapse, collapse)?,
),
(
Property::TextWrapMode,
literal(Property::TextWrapMode, wrap)?,
),
]);
}
Ok(slotted(
value,
&[Property::WhiteSpaceCollapse, Property::TextWrapMode],
))
}
fn slotted(value: &Component, properties: &[Property]) -> Longhands {
properties
.iter()
.enumerate()
.map(|(slot, &property)| {
let specified = value
.slot(slot)
.map_or_else(initial, |slot| longhand(property, slot));
(property, specified)
})
.collect()
}
fn line_clamp(value: &Component, legacy: bool) -> Result<Longhands, StyleError> {
let ellipsis = match value.find(Label::Property(Property::BlockEllipsis)) {
Some(ellipsis) => longhand(Property::BlockEllipsis, ellipsis),
None if legacy || value.keyword() != Some(Keyword::None) => {
literal(Property::BlockEllipsis, CLAMP_ELLIPSIS)?
}
None => initial(),
};
let (lines, continuation) = if value.keyword() == Some(Keyword::None) {
(initial(), initial())
} else {
(
longhand(Property::MaxLines, &value.items()[0]),
literal(
Property::Continue,
if legacy {
CLAMP_WEBKIT_DISCARD
} else {
CLAMP_DISCARD
},
)?,
)
};
Ok(vec![
(Property::MaxLines, lines),
(Property::BlockEllipsis, ellipsis),
(Property::Continue, continuation),
])
}
fn box_orient(value: &Component) -> Result<Longhands, StyleError> {
let direction = match value.keyword() {
Some(Keyword::Horizontal | Keyword::InlineAxis) => ORIENT_ROW,
Some(Keyword::Vertical | Keyword::BlockAxis) => ORIENT_COLUMN,
_ => return Err(StyleError::Invalid(format!("box orientation {value}"))),
};
Ok(vec![(
Property::FlexDirection,
literal(Property::FlexDirection, direction)?,
)])
}
fn text_box(value: &Component) -> Result<Longhands, StyleError> {
const TRIM_SLOT: usize = 0;
const EDGE_SLOT: usize = 1;
const OMITTED_TRIM: &str = "trim-both";
if value.keyword() == Some(Keyword::Normal) {
return Ok(vec![
(Property::TextBoxTrim, initial()),
(Property::TextBoxEdge, initial()),
]);
}
Ok(vec![
(
Property::TextBoxTrim,
match value.slot(TRIM_SLOT) {
Some(trim) => longhand(Property::TextBoxTrim, trim),
None => literal(Property::TextBoxTrim, OMITTED_TRIM)?,
},
),
(
Property::TextBoxEdge,
value
.slot(EDGE_SLOT)
.map_or_else(initial, |edge| longhand(Property::TextBoxEdge, edge)),
),
])
}
fn text_spacing(value: &Component) -> Result<Longhands, StyleError> {
const TRIM_SLOT: usize = 0;
const AUTOSPACE_SLOT: usize = 1;
const TRIM_OFF: &str = "space-all";
const AUTOSPACE_OFF: &str = "no-autospace";
const AUTO: &str = "auto";
let both = |trim: &str, autospace: &str| -> Result<Longhands, StyleError> {
Ok(vec![
(
Property::TextSpacingTrim,
literal(Property::TextSpacingTrim, trim)?,
),
(
Property::TextAutospace,
literal(Property::TextAutospace, autospace)?,
),
])
};
match value.keyword() {
Some(Keyword::None) => return both(TRIM_OFF, AUTOSPACE_OFF),
Some(Keyword::Auto) => return both(AUTO, AUTO),
_ => {}
}
Ok(vec![
(
Property::TextSpacingTrim,
value
.slot(TRIM_SLOT)
.map_or_else(initial, |trim| longhand(Property::TextSpacingTrim, trim)),
),
(
Property::TextAutospace,
value
.slot(AUTOSPACE_SLOT)
.map_or_else(initial, |autospace| {
longhand(Property::TextAutospace, autospace)
}),
),
])
}
fn alias(value: &Component, property: Property) -> Longhands {
vec![(property, longhand(property, value))]
}
fn box_shadow(value: &Component) -> Longhands {
const COLOR_SLOT: usize = 0;
const GEOMETRY_SLOT: usize = 1;
const POSITION_SLOT: usize = 2;
let items: Vec<_> = value.items().iter().collect();
fn geometry(item: &Component) -> Option<&[Component]> {
item.slot(GEOMETRY_SLOT).map(Component::items)
}
fn blur_spread(item: &Component) -> Option<&[Component]> {
geometry(item)?
.get(1)?
.items()
.first()
.map(Component::items)
}
vec![
coordinated(Property::BoxShadowColor, &items, &|item| {
item.slot(COLOR_SLOT)
.and_then(|color| color.items().first())
.cloned()
.or_else(|| {
(geometry(item)?.first()?.keyword() == Some(Keyword::None))
.then_some(Component::Color(crate::paint::AbsoluteColor::TRANSPARENT))
})
}),
coordinated(Property::BoxShadowOffset, &items, &|item| {
geometry(item)?.first().cloned()
}),
coordinated(Property::BoxShadowBlur, &items, &|item| {
blur_spread(item)?.first().cloned()
}),
coordinated(Property::BoxShadowSpread, &items, &|item| {
blur_spread(item)?.get(1)?.items().first().cloned()
}),
coordinated(Property::BoxShadowPosition, &items, &|item| {
item.slot(POSITION_SLOT)?.items().first().cloned()
}),
]
}
fn slotted_list(value: &Component, properties: &[Property]) -> Longhands {
let items: Vec<&Component> = value.items().iter().collect();
properties
.iter()
.enumerate()
.map(|(index, property)| coordinated(*property, &items, &|item| item.slot(index).cloned()))
.collect()
}
fn optional(item: &Component) -> Option<&Component> {
item.items().get(1).and_then(|part| part.items().first())
}
fn scroll_timeline(value: &Component) -> Longhands {
let items: Vec<&Component> = value.items().iter().collect();
vec![
coordinated(Property::ScrollTimelineName, &items, &|item| {
item.items().first().cloned()
}),
coordinated(Property::ScrollTimelineAxis, &items, &|item| {
optional(item).cloned()
}),
]
}
fn view_timeline(value: &Component) -> Longhands {
let items: Vec<&Component> = value.items().iter().collect();
let part = |index: usize| move |item: &Component| optional(item)?.slot(index).cloned();
vec![
coordinated(Property::ViewTimelineName, &items, &|item| {
item.items().first().cloned()
}),
coordinated(Property::ViewTimelineAxis, &items, &part(0)),
coordinated(Property::ViewTimelineInset, &items, &part(1)),
]
}
fn animation_range(value: &Component) -> Longhands {
let items: Vec<&Component> = value.items().iter().collect();
let end = |item: &Component| {
optional(item).cloned().or_else(|| {
let name = item
.items()
.first()?
.find(Label::Production(Production::TimelineRangeName))?;
Some(Component::Group(vec![
Component::Reference(
Label::Production(Production::TimelineRangeName),
Box::new(name.clone()),
),
Component::Group(vec![Component::Percentage(NAMED_RANGE_END)]),
]))
})
};
vec![
coordinated(Property::AnimationRangeStart, &items, &|item| {
item.items().first().cloned()
}),
coordinated(Property::AnimationRangeEnd, &items, &end),
]
}
fn background(value: &Component) -> Result<Longhands, StyleError> {
let mut layers = Vec::new();
value.unwrap().references(
&[
Label::Production(Production::BgLayer),
Label::Production(Production::FinalBgLayer),
],
&mut layers,
);
let layers: Vec<&Component> = layers.into_iter().map(|(_, layer)| layer).collect();
let position = |layer: &Component| {
layer
.slot(LAYER_POSITION)
.and_then(|slot| slot.find(Label::Production(Production::BgPosition)))
.map(|found| {
Component::Reference(
Label::Production(Production::BgPosition),
Box::new(found.clone()),
)
})
};
let size = |layer: &Component| {
layer
.slot(LAYER_POSITION)
.and_then(|slot| slot.find(Label::Production(Production::BgSize)))
.map(|found| {
Component::Reference(
Label::Production(Production::BgSize),
Box::new(found.clone()),
)
})
};
let slot = |index: usize| move |layer: &Component| layer.slot(index).cloned();
let clip = |layer: &Component| {
layer
.slot(LAYER_CLIP)
.or_else(|| layer.slot(LAYER_ORIGIN))
.map(|visual_box| {
Component::Reference(
Label::Production(Production::BgClip),
Box::new(visual_box.clone()),
)
})
};
let mut longhands = vec![
layered(Property::BackgroundImage, &layers, &slot(LAYER_IMAGE)),
layered(Property::BackgroundSize, &layers, &size),
layered(Property::BackgroundRepeat, &layers, &slot(LAYER_REPEAT)),
layered(
Property::BackgroundAttachment,
&layers,
&slot(LAYER_ATTACHMENT),
),
layered(Property::BackgroundOrigin, &layers, &slot(LAYER_ORIGIN)),
layered(Property::BackgroundClip, &layers, &clip),
];
let color = layers
.last()
.and_then(|layer| layer.slot(LAYER_COLOR))
.map_or_else(initial, |color| longhand(Property::BackgroundColor, color));
longhands.push((Property::BackgroundColor, color));
let positions: Vec<Option<Component>> = layers.iter().map(|layer| position(layer)).collect();
longhands.extend(axis_lists(
&positions.iter().map(Option::as_ref).collect::<Vec<_>>(),
)?);
Ok(longhands)
}
const MASK_REFERENCE: usize = 0;
const MASK_POSITION: usize = 1;
const MASK_REPEAT: usize = 2;
const MASK_ORIGIN: usize = 3;
const MASK_CLIP: usize = 4;
const MASK_COMPOSITE: usize = 5;
const MASK_MODE: usize = 6;
const MASK_BORDER_SLOTS: usize = 4;
const MASK_BORDER: [Property; 6] = [
Property::MaskBorderSource,
Property::MaskBorderSlice,
Property::MaskBorderWidth,
Property::MaskBorderOutset,
Property::MaskBorderRepeat,
Property::MaskBorderMode,
];
fn mask(value: &Component) -> Longhands {
let mut layers = Vec::new();
value
.unwrap()
.references(&[Label::Production(Production::MaskLayer)], &mut layers);
let layers: Vec<&Component> = layers.into_iter().map(|(_, layer)| layer).collect();
let slot = |index: usize| move |layer: &Component| layer.slot(index).cloned();
let found = |production: Production| {
move |layer: &Component| {
layer
.slot(MASK_POSITION)
.and_then(|slot| slot.find(Label::Production(production)))
.map(|found| {
Component::Reference(Label::Production(production), Box::new(found.clone()))
})
}
};
let clip = |layer: &Component| {
layer
.slot(MASK_CLIP)
.or_else(|| layer.slot(MASK_ORIGIN))
.cloned()
};
[
layered(Property::MaskImage, &layers, &slot(MASK_REFERENCE)),
layered(
Property::MaskPosition,
&layers,
&found(Production::Position),
),
layered(Property::MaskSize, &layers, &found(Production::BgSize)),
layered(Property::MaskRepeat, &layers, &slot(MASK_REPEAT)),
layered(Property::MaskOrigin, &layers, &slot(MASK_ORIGIN)),
layered(Property::MaskClip, &layers, &clip),
layered(Property::MaskComposite, &layers, &slot(MASK_COMPOSITE)),
layered(Property::MaskMode, &layers, &slot(MASK_MODE)),
]
.into_iter()
.chain(MASK_BORDER.map(|property| (property, initial())))
.collect()
}
fn background_position(value: &Component) -> Result<Longhands, StyleError> {
axis_lists(&value.items().iter().map(Some).collect::<Vec<_>>())
}
fn axis_lists(positions: &[Option<&Component>]) -> Result<Longhands, StyleError> {
let axes = [Property::BackgroundPositionX, Property::BackgroundPositionY];
if positions.iter().all(Option::is_none) {
return Ok(axes.map(|axis| (axis, initial())).into());
}
let initial_item = |axis: Property| {
declaration::initial(axis)
.and_then(|initial| initial.items().first())
.cloned()
.ok_or_else(|| StyleError::Invalid(format!("{} has no initial item", axis.name())))
};
let mut lists = [Vec::new(), Vec::new()];
for position in positions {
let items = match position {
Some(position) => crate::style::background_values::position_axes(position)?
.map(|part| part.cloned().unwrap_or(Component::Keyword(Keyword::Center))),
None => [initial_item(axes[0])?, initial_item(axes[1])?],
};
for (list, item) in lists.iter_mut().zip(items) {
list.push(item);
}
}
Ok(axes
.into_iter()
.zip(lists)
.map(|(axis, items)| (axis, longhand(axis, &Component::Group(items))))
.collect())
}
fn layered(
property: Property,
layers: &[&Component],
item: &dyn Fn(&Component) -> Option<Component>,
) -> (Property, Specified) {
if layers.iter().all(|layer| item(layer).is_none()) {
return (property, initial());
}
coordinated(property, layers, item)
}
fn coordinated(
property: Property,
entries: &[&Component],
item: &dyn Fn(&Component) -> Option<Component>,
) -> (Property, Specified) {
let fallback = declaration::initial(property)
.and_then(|initial| initial.items().first())
.cloned();
let items = entries
.iter()
.map(|entry| item(entry).or_else(|| fallback.clone()))
.collect::<Option<Vec<_>>>();
match items {
Some(items) => (property, longhand(property, &Component::Group(items))),
None => (property, initial()),
}
}
fn unordered_references(
shorthand: Property,
value: &Component,
) -> Result<Option<Longhands>, StyleError> {
let Node::Reference(_, target) = NODES[usize::from(shorthand.data().root)] else {
return Ok(None);
};
let (Node::AnyOf(alternatives) | Node::AllOf(alternatives)) = &NODES[usize::from(target)]
else {
return Ok(None);
};
let direct = shorthand.longhands();
let Some(properties) = alternatives
.iter()
.map(|alternative| match NODES[usize::from(*alternative)] {
Node::Reference(Label::Property(property), _) if direct.contains(&property) => {
Some(property)
}
_ => None,
})
.collect::<Option<Vec<_>>>()
else {
return Ok(None);
};
if direct.iter().any(|longhand| !properties.contains(longhand)) {
return Ok(None);
}
let mut longhands = Longhands::new();
for (index, property) in properties.into_iter().enumerate() {
match value.slot(index) {
Some(slot) if !property.longhands().is_empty() => {
longhands.extend(expand(property, slot.clone())?);
}
Some(slot) => longhands.push((property, longhand(property, slot))),
None => longhands.extend(declaration::longhands(property).map(|l| (l, initial()))),
}
}
Ok(Some(longhands))
}
fn bare_name(line: &Component) -> bool {
matches!(line.unwrap(), Component::Ident(_))
}
fn grid_lines(value: &Component, properties: [Property; 2]) -> Longhands {
grid_placement(value, &properties, &[None, Some(0)])
}
fn grid_area(value: &Component) -> Longhands {
grid_placement(
value,
&[
Property::GridRowStart,
Property::GridColumnStart,
Property::GridRowEnd,
Property::GridColumnEnd,
],
&[None, Some(0), Some(0), Some(1)],
)
}
fn grid_placement(
value: &Component,
properties: &[Property],
sources: &[Option<usize>],
) -> Longhands {
let mut lines = Vec::new();
value.references(&[Label::Production(Production::GridLine)], &mut lines);
let mut resolved: Vec<Option<&Component>> = Vec::with_capacity(properties.len());
for (index, source) in sources.iter().enumerate() {
let line = lines.get(index).map(|(_, line)| *line).or_else(|| {
source
.and_then(|source| resolved[source])
.filter(|line| bare_name(line))
});
resolved.push(line);
}
properties
.iter()
.zip(resolved)
.map(|(property, line)| {
(
*property,
line.map_or_else(initial, |line| longhand(*property, line)),
)
})
.collect()
}
fn auto_track() -> Component {
Component::Reference(
Label::Production(Production::TrackSize),
Box::new(Component::Reference(
Label::Production(Production::TrackBreadth),
Box::new(Component::Keyword(Keyword::Auto)),
)),
)
}
fn grid_template(value: &Component) -> Longhands {
let properties = [
Property::GridTemplateRows,
Property::GridTemplateColumns,
Property::GridTemplateAreas,
];
if value.keyword() == Some(Keyword::None) {
return properties
.iter()
.map(|property| (*property, initial()))
.collect();
}
if let Some(rows) = value.find(Label::Property(Property::GridTemplateRows)) {
let columns = value.find(Label::Property(Property::GridTemplateColumns));
return vec![
(properties[0], longhand(properties[0], rows)),
(
properties[1],
columns.map_or_else(initial, |columns| longhand(properties[1], columns)),
),
(properties[2], initial()),
];
}
let parts = value.items();
let rows = parts.first().map_or(&[][..], Component::items);
let mut tracks = Vec::new();
let mut strings = Vec::new();
for row in rows {
let [before, string, size, after] = row.items() else {
continue;
};
tracks.extend(before.items().iter().cloned());
strings.push(string.clone());
tracks.push(size.items().first().cloned().unwrap_or_else(auto_track));
tracks.extend(after.items().iter().cloned());
}
let columns = parts
.get(1)
.and_then(|tail| tail.find(Label::Production(Production::ExplicitTrackList)));
vec![
(
properties[0],
longhand(properties[0], &Component::Group(tracks)),
),
(
properties[1],
columns.map_or_else(initial, |columns| longhand(properties[1], columns)),
),
(
properties[2],
longhand(properties[2], &Component::Group(strings)),
),
]
}
fn grid(value: &Component) -> Result<Longhands, StyleError> {
let template = match value {
Component::Reference(Label::Property(Property::Grid), inner) => inner.as_ref(),
other => other,
};
let mut implicit = vec![
(Property::GridAutoRows, initial()),
(Property::GridAutoColumns, initial()),
(Property::GridAutoFlow, initial()),
];
if matches!(
template,
Component::Reference(Label::Property(Property::GridTemplate), _)
) {
let mut longhands = grid_template(template);
longhands.append(&mut implicit);
return Ok(longhands);
}
let mut keywords = Vec::new();
value.keywords(&mut keywords);
let dense = keywords.contains(&Keyword::Dense);
let rows = value.find(Label::Property(Property::GridTemplateRows));
let (template, auto, flow) = match rows {
Some(rows) => (
(Property::GridTemplateRows, rows),
Property::GridAutoColumns,
COLUMN_FLOW,
),
None => (
(
Property::GridTemplateColumns,
value
.find(Label::Property(Property::GridTemplateColumns))
.ok_or_else(|| StyleError::Invalid(format!("grid: {value}")))?,
),
Property::GridAutoRows,
ROW_FLOW,
),
};
let flow = if dense {
format!("{flow} {DENSE}")
} else {
flow.to_owned()
};
let mut longhands = vec![
(Property::GridTemplateRows, initial()),
(Property::GridTemplateColumns, initial()),
(Property::GridTemplateAreas, initial()),
(Property::GridAutoRows, initial()),
(Property::GridAutoColumns, initial()),
(
Property::GridAutoFlow,
literal(Property::GridAutoFlow, &flow)?,
),
];
for (property, specified) in &mut longhands {
if *property == template.0 {
*specified = longhand(*property, template.1);
} else if *property == auto
&& let Some(sizes) = value.find(Label::Property(auto))
{
*specified = longhand(*property, sizes);
}
}
Ok(longhands)
}