use crate::style::{
BoxSizing, CalculatedSize, LengthPercentage, Size, StyleError, box_values::unsupported,
component::Component, grammar::Keyword, units::Relative,
};
use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)]
pub(crate) struct AspectRatio {
pub auto: bool,
pub ratio: Option<f32>,
}
impl Default for AspectRatio {
fn default() -> Self {
Self {
auto: true,
ratio: None,
}
}
}
impl AspectRatio {
pub(super) fn from_component(
value: &Component,
relative: &Relative<'_>,
) -> Result<Self, StyleError> {
if value.keyword() == Some(Keyword::Auto) {
return Ok(Self::default());
}
let ratio = value
.slot(1)
.map(|ratio| {
let mut numbers = Vec::new();
ratio_numbers(ratio, &mut numbers);
let [width, height] = match numbers.as_slice() {
[width] => [*width, &Component::Number(1.0)],
[width, height] => [*width, *height],
_ => return Err(unsupported(ratio)),
};
Ok([
crate::style::values::number(width, relative)?,
crate::style::values::number(height, relative)?,
])
})
.transpose()?;
let ratio = ratio
.filter(|numbers| numbers.iter().all(|n| n.is_finite() && *n > 0.0))
.map(|[width, height]| width / height);
Ok(Self {
auto: value.slot(0).is_some(),
ratio,
})
}
pub(crate) fn preferred(self, natural: Option<f32>) -> Option<(f32, bool)> {
match (self.auto, self.ratio) {
(_, None) => natural.map(|ratio| (ratio, false)),
(false, Some(ratio)) => Some((ratio, true)),
(true, Some(ratio)) => Some((natural.unwrap_or(ratio), false)),
}
}
}
fn ratio_numbers<'a>(value: &'a Component, output: &mut Vec<&'a Component>) {
match value.unwrap() {
Component::Group(items) => items.iter().for_each(|item| ratio_numbers(item, output)),
Component::Delim(_) => {}
number => output.push(number),
}
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct IntrinsicWidths {
pub min: f32,
pub max: f32,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub(crate) enum IntrinsicSizing {
MinContent,
MaxContent,
FitContent,
FitContentLimit(LengthPercentage),
Stretch,
}
impl IntrinsicSizing {
pub(crate) fn resolve(
&self,
widths: IntrinsicWidths,
available: Option<f32>,
basis: Option<f32>,
sizing_edges: f32,
) -> f32 {
let fit = |space: Option<f32>| widths.max.min(widths.min.max(space.unwrap_or(widths.max)));
match self {
Self::MinContent => widths.min,
Self::MaxContent => widths.max,
Self::FitContent => fit(available),
Self::FitContentLimit(limit) => fit(Size::Value(limit.clone())
.resolve_definite(basis)
.map(|limit| (limit - sizing_edges).max(0.0))
.or(available)),
Self::Stretch => available.unwrap_or(widths.max),
}
}
}
#[derive(Debug)]
struct Resolution {
basis: Option<f32>,
sizing_edges: f32,
automatic: [Option<Arc<CalculatedSize>>; 2],
}
#[derive(Clone, Debug)]
pub(crate) struct SharedResolution(Arc<Resolution>);
impl PartialEq for SharedResolution {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for SharedResolution {}
impl std::hash::Hash for SharedResolution {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.0).hash(state);
}
}
#[derive(Clone, Default)]
pub(crate) struct SizeConstraints {
pub specified: Option<f32>,
pub minimum: f32,
pub maximum: Option<f32>,
resolution: Option<SharedResolution>,
}
#[derive(Clone, Hash, PartialEq, Eq)]
pub(crate) struct ConstraintsKey {
specified: Option<u32>,
minimum: u32,
maximum: Option<u32>,
resolution: Option<SharedResolution>,
}
impl ConstraintsKey {
pub(crate) fn constraints(&self) -> SizeConstraints {
SizeConstraints {
specified: self.specified.map(f32::from_bits),
minimum: f32::from_bits(self.minimum),
maximum: self.maximum.map(f32::from_bits),
resolution: self.resolution.clone(),
}
}
}
impl SizeConstraints {
pub(crate) fn fixed(specified: Option<f32>, minimum: f32, maximum: Option<f32>) -> Self {
Self {
specified,
minimum,
maximum,
resolution: None,
}
}
pub(crate) fn key(&self) -> ConstraintsKey {
ConstraintsKey {
specified: self.specified.map(f32::to_bits),
minimum: self.minimum.to_bits(),
maximum: self.maximum.map(f32::to_bits),
resolution: self.resolution.clone(),
}
}
fn resolution(&self) -> Option<&Resolution> {
self.resolution.as_ref().map(|shared| &*shared.0)
}
fn basis(&self) -> Option<f32> {
self.resolution().and_then(|resolution| resolution.basis)
}
pub(crate) fn sizing_edges(&self) -> f32 {
self.resolution()
.map_or(0.0, |resolution| resolution.sizing_edges)
}
fn calculate(&self, calculated: &CalculatedSize, value: f32) -> f32 {
let edges = self.sizing_edges();
(calculated.resolve(value + edges, self.basis()) - edges).max(0.0)
}
fn automatic(&self, index: usize, value: f32) -> f32 {
match self
.resolution()
.and_then(|resolution| resolution.automatic[index].as_deref())
{
Some(calculated) => self.calculate(calculated, value),
None => value,
}
}
pub(crate) fn preferred(&self, automatic: f32) -> f32 {
self.specified
.unwrap_or_else(|| self.automatic(0, automatic))
}
pub(crate) fn adjust(&self, size: &Size, value: f32) -> f32 {
match size {
Size::Calculated(calculated) => self.calculate(calculated, value),
_ => value,
}
}
pub(crate) fn calculates_automatic(&self) -> bool {
self.specified.is_none()
&& self
.resolution()
.is_some_and(|resolution| resolution.automatic[0].is_some())
}
pub(crate) fn automatic_minimum(&self, automatic: f32) -> f32 {
self.automatic(1, automatic)
}
#[must_use]
pub(crate) fn with_intrinsic(
mut self,
sizes: [&Size; 3],
widths: IntrinsicWidths,
available: Option<f32>,
) -> Self {
for (index, size) in sizes.into_iter().enumerate() {
if let Some(keyword) = size.intrinsic() {
let value = keyword
.resolve(widths, available, self.basis(), self.sizing_edges())
.max(0.0);
let value = self.adjust(size, value);
match index {
0 => self.specified = Some(value),
1 => self.minimum = value,
_ => self.maximum = Some(value),
}
}
}
self
}
#[must_use]
pub(crate) fn with_stretch(self, sizes: [&Size; 3], available: Option<f32>) -> Self {
let stretched = sizes.map(|size| size.intrinsic() == Some(&IntrinsicSizing::Stretch));
match available {
Some(available) if stretched.contains(&true) => self.with_intrinsic(
sizes.map(|size| {
if size.intrinsic() == Some(&IntrinsicSizing::Stretch) {
size
} else {
&Size::Auto
}
}),
IntrinsicWidths {
min: available,
max: available,
},
Some(available),
),
_ => self,
}
}
pub(crate) fn new(
sizes: [&Size; 3],
basis: Option<f32>,
sizing: BoxSizing,
edges: f32,
) -> Self {
let sizing_edges = if sizing == BoxSizing::BorderBox {
edges
} else {
0.0
};
let [specified, minimum, maximum] = sizes.map(|size| {
size.resolve_definite(basis)
.map(|value| (value - sizing_edges).max(0.0))
});
let automatic = |size: &Size, value: Option<f32>| match size {
Size::Calculated(calculated) if value.is_none() => Some(calculated.clone()),
_ => None,
};
let resolved = sizes.iter().any(|size| {
matches!(
size,
Size::Calculated(_) | Size::Intrinsic(IntrinsicSizing::FitContentLimit(_))
)
});
let mut constraints = Self {
specified,
minimum: 0.0,
maximum,
resolution: resolved.then(|| {
SharedResolution(Arc::new(Resolution {
basis,
sizing_edges,
automatic: [automatic(sizes[0], specified), automatic(sizes[1], minimum)],
}))
}),
};
constraints.minimum = minimum.unwrap_or_else(|| constraints.automatic_minimum(0.0));
constraints
}
pub(crate) fn constrain(&self, value: f32) -> f32 {
self.maximum
.map_or(value, |maximum| value.min(maximum))
.max(self.minimum)
}
}
pub(super) fn valid(property: crate::style::grammar::Property, value: &Component) -> bool {
use crate::style::grammar::Property as P;
!matches!(
property,
P::MaxWidth | P::MaxHeight | P::MaxInlineSize | P::MaxBlockSize | P::MaxSize
) || !has_auto_basis(value)
}
fn has_auto_basis(value: &Component) -> bool {
match value {
Component::Function(Keyword::CalcSize, Some(arguments)) => match &**arguments {
Component::Tokens(arguments) => {
let mut input = cssparser::ParserInput::new(arguments);
auto_basis(&mut cssparser::Parser::new(&mut input))
}
_ => false,
},
Component::Reference(_, inner) | Component::Block(_, inner) => has_auto_basis(inner),
Component::Group(items) => items.iter().any(has_auto_basis),
Component::Slots(slots) => slots.iter().flatten().any(has_auto_basis),
_ => false,
}
}
fn auto_basis(input: &mut cssparser::Parser<'_, '_>) -> bool {
match input.next() {
Ok(cssparser::Token::Ident(name)) => Keyword::from_ident(name) == Some(Keyword::Auto),
Ok(cssparser::Token::Function(name))
if Keyword::from_ident(name) == Some(Keyword::CalcSize) =>
{
input
.parse_nested_block(|nested| {
Ok::<_, cssparser::ParseError<'_, ()>>(auto_basis(nested))
})
.unwrap_or(false)
}
_ => false,
}
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub(crate) enum Overconstraint {
AdjustEndMargin,
ResizeContaining,
}
#[derive(Clone, Copy)]
pub(crate) struct UsedAxis {
pub size: f32,
pub margins: [f32; 2],
pub containing: f32,
}
impl SizeConstraints {
pub(crate) fn normal_flow(
&self,
containing: f32,
edges: f32,
margins: [Option<f32>; 2],
used_size: Option<f32>,
reverse: bool,
overconstraint: Overconstraint,
) -> UsedAxis {
let [start, end] = margins;
let natural = used_size.unwrap_or_else(|| {
self.preferred(
(containing - edges - start.unwrap_or(0.0) - end.unwrap_or(0.0)).max(0.0),
)
});
let size = used_size.unwrap_or_else(|| self.constrain(natural));
let specified = used_size.is_some() || self.specified.is_some() || size != natural;
let remainder = containing - edges - size - start.unwrap_or(0.0) - end.unwrap_or(0.0);
let mut used = [start.unwrap_or(0.0), end.unwrap_or(0.0)];
let adjustable = usize::from(!reverse);
let mut resize = false;
if specified && remainder >= 0.0 {
match (start, end) {
(None, None) => used = [remainder / margins.len() as f32; 2],
(None, Some(_)) => used[0] = remainder,
(Some(_), None) => used[1] = remainder,
(Some(_), Some(_)) => resize = true,
}
} else {
resize = true;
}
let containing = if resize && overconstraint == Overconstraint::ResizeContaining {
if specified || remainder < 0.0 {
size + edges + used[0] + used[1]
} else {
containing
}
} else {
if resize {
used[adjustable] += remainder;
}
containing
};
UsedAxis {
size,
margins: used,
containing,
}
}
}