use crate::style::{
StyleError,
component::Component,
declaration::{self, Specified},
grammar::{Keyword, Label, NODES, Node, Production, Property},
wide_keywords::WideKeyword,
};
use std::sync::Arc;
type Longhands = Vec<(Property, Specified)>;
const TOP: usize = 0;
const RIGHT: usize = 1;
const BOTTOM: usize = 2;
const LEFT: usize = 3;
const BORDER_PARTS: usize = 3;
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 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::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 => radius(&value),
P::Border => border(&value, &[TOP, RIGHT, BOTTOM, LEFT])
.into_iter()
.chain(BORDER_IMAGE.map(|property| (property, initial())))
.collect(),
P::BorderImage => border_image(&value),
P::Columns => columns(&value),
P::BorderTop => border(&value, &[TOP]),
P::BorderRight => border(&value, &[RIGHT]),
P::BorderBottom => border(&value, &[BOTTOM]),
P::BorderLeft => border(&value, &[LEFT]),
P::Overflow => pair(&value, [P::OverflowX, P::OverflowY]),
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 if value.keyword() == Some(Keyword::Normal) => {
declaration::wide(P::FontVariant, WideKeyword::Initial)
}
P::FontVariant if crate::style::font_values::is_small_caps(&value) => {
let mut values = declaration::wide(P::FontVariant, WideKeyword::Initial);
values
.iter_mut()
.find(|(property, _)| *property == P::FontVariantCaps)
.expect("font-variant metadata contains caps")
.1 = longhand(P::FontVariantCaps, &Component::Keyword(Keyword::SmallCaps));
values
}
P::FontSynthesis => font_synthesis(&value)?,
P::Background => background(&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),
_ => {
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())))
}
fn edges(value: &Component, sides: [Property; 4]) -> Longhands {
let items = value.items();
let index = |side: usize| match (items.len(), side) {
(1, _) => 0,
(2 | 3, LEFT) => 1,
(2, BOTTOM) => 0,
_ => side,
};
sides
.iter()
.enumerate()
.map(|(side, property)| (*property, longhand(*property, &items[index(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 radius(value: &Component) -> Longhands {
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), &[][..]],
};
let corner = |values: &[Component], index: usize| match (values.len(), index) {
(1, _) => 0,
(2 | 3, 3) => 1,
(2, 2) => 0,
_ => index,
};
[
Property::BorderTopLeftRadius,
Property::BorderTopRightRadius,
Property::BorderBottomRightRadius,
Property::BorderBottomLeftRadius,
]
.iter()
.enumerate()
.map(|(index, property)| {
let mut radii = vec![horizontal[corner(horizontal, index)].clone()];
if !vertical.is_empty() {
radii.push(vertical[corner(vertical, index)].clone());
}
(*property, longhand(*property, &Component::Group(radii)))
})
.collect()
}
fn border(value: &Component, sides: &[usize]) -> Longhands {
const PARTS: [[Property; BORDER_PARTS]; 4] = [
[
Property::BorderTopWidth,
Property::BorderTopStyle,
Property::BorderTopColor,
],
[
Property::BorderRightWidth,
Property::BorderRightStyle,
Property::BorderRightColor,
],
[
Property::BorderBottomWidth,
Property::BorderBottomStyle,
Property::BorderBottomColor,
],
[
Property::BorderLeftWidth,
Property::BorderLeftStyle,
Property::BorderLeftColor,
],
];
sides
.iter()
.flat_map(|side| {
PARTS[*side].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 {
BORDER_IMAGE
.iter()
.map(|property| {
let found = (0..BORDER_IMAGE_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 alias(value: &Component, property: Property) -> Longhands {
vec![(property, longhand(property, value))]
}
fn background(value: &Component) -> Longhands {
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::BackgroundPosition, &layers, &position),
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));
longhands
}
fn layered(
property: Property,
layers: &[&Component],
item: &dyn Fn(&Component) -> Option<Component>,
) -> (Property, Specified) {
let items: Vec<Option<Component>> = layers.iter().map(|layer| item(layer)).collect();
if items.iter().all(Option::is_none) {
return (property, initial());
}
let fallback = declaration::initial(property)
.and_then(|initial| initial.items().first())
.cloned();
let items = items
.into_iter()
.map(|item| item.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)
}