fix(css): reify generated images and image lists

This commit is contained in:
ldm0
2026-11-20 22:47:45 +08:00
parent 343258d5a9
commit e7ea5a4aa4
8 changed files with 385 additions and 33 deletions
+4 -1
View File
@@ -98,7 +98,10 @@ pub use typed_declaration::{
CssDeclarationBlock, CssDeclaredMathNode, CssDeclaredNumericValue, CssDeclaredNumericValues,
CssDeclaredUnitValue, CssMathOperator, parse_declaration_block,
};
pub use typed_om::{ParsedTypedStyleValue, parse_typed_style_value, reify_unparsed_style_value};
pub use typed_om::{
ParsedTypedStyleValue, TypedImageValue, TypedStyleValueList, computed_typed_style_value_list,
parse_typed_style_value, reify_unparsed_style_value,
};
pub use util::{
camel_case_style_property_name, camel_to_kebab, canonical_style_property_identifier,
canonical_style_property_name, decapitalize_ascii_head, escape_top_level_semicolons,
+54 -9
View File
@@ -13,13 +13,50 @@ use style::{
};
use style_traits::ParsingMode;
mod images;
mod tokens;
pub use images::{TypedImageValue, computed_typed_style_value_list};
/// Stylo's general projection plus image ASTs which its pinned ToTyped
/// implementation does not yet cover (gradients, image-set and mixed lists).
pub enum TypedStyleValueList {
Native(TypedValueList),
Images(Vec<TypedImageValue>),
}
impl TypedStyleValueList {
pub fn native(&self) -> Option<&TypedValueList> {
match self {
Self::Native(values) => Some(values),
Self::Images(_) => None,
}
}
pub fn len(&self) -> usize {
match self {
Self::Native(values) => values.values.len(),
Self::Images(values) => values.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn is_single_image(&self) -> bool {
match self {
Self::Native(values) => matches!(values.values.as_slice(), [TypedValue::Image(_)]),
Self::Images(values) => matches!(values.as_slice(), [TypedImageValue::Image(_)]),
}
}
}
pub struct ParsedTypedStyleValue {
/// CSSOM serialization of the validated declaration (including shorthands).
pub css_text: String,
/// None denotes a property-associated value without a specialized projection.
pub values: Option<TypedValueList>,
pub values: Option<TypedStyleValueList>,
}
/// Parse exactly one value, never a declaration list or an !important suffix.
@@ -83,6 +120,10 @@ pub fn parse_typed_style_value(
} else {
block.property_value_to_typed_value_list(&id).ok()?
};
let values = values.map(TypedStyleValueList::Native).or_else(|| {
let (declaration, _) = block.get(id.as_shorthand().err()?)?;
images::from_declaration(declaration).map(TypedStyleValueList::Images)
});
Some(ParsedTypedStyleValue {
css_text: serialized,
values,
@@ -125,6 +166,13 @@ mod tests {
use super::*;
use style::typed_om::{NumericValue, UnparsedSegment};
fn native_values(parsed: ParsedTypedStyleValue) -> TypedValueList {
match parsed.values.expect("typed values") {
TypedStyleValueList::Native(values) => values,
TypedStyleValueList::Images(_) => panic!("unexpected image projection"),
}
}
#[test]
fn all_reifies_keywords_without_retyping_ordinary_shorthands() {
for property in ["all", "width", "color", "animation-name"] {
@@ -132,9 +180,7 @@ mod tests {
let source = format!("/**/{} /**/", keyword.to_ascii_uppercase());
let parsed = parse_typed_style_value(property, &source, None)
.unwrap_or_else(|| panic!("{property}: {source}"));
let values = parsed
.values
.unwrap_or_else(|| panic!("{property}: opaque"));
let values = native_values(parsed);
assert_eq!(values.values.len(), 1, "{property}: {keyword}");
assert!(
matches!(&values.values[0], TypedValue::Keyword(value) if value.0 == keyword),
@@ -144,7 +190,7 @@ mod tests {
}
let parsed = parse_typed_style_value("all", r"\69 nherit", None).unwrap();
assert!(matches!(
&parsed.values.unwrap().values[0], TypedValue::Keyword(value) if value.0 == "inherit"
&native_values(parsed).values[0], TypedValue::Keyword(value) if value.0 == "inherit"
));
for (property, source) in [
("margin", "initial 1px"),
@@ -176,7 +222,7 @@ mod tests {
] {
let parsed = parse_typed_style_value(property, source, None).unwrap();
assert!(matches!(
&parsed.values.unwrap().values[0],
&native_values(parsed).values[0],
TypedValue::Unparsed(_)
));
}
@@ -200,7 +246,7 @@ mod tests {
);
}
let parsed = parse_typed_style_value("width", "0", None).unwrap();
let TypedValue::Numeric(NumericValue::Unit(value)) = &parsed.values.unwrap().values[0]
let TypedValue::Numeric(NumericValue::Unit(value)) = &native_values(parsed).values[0]
else {
panic!("length zero must remain a dimension");
};
@@ -211,7 +257,6 @@ mod tests {
.unwrap()
.values
.unwrap()
.values
.len(),
2
);
@@ -234,7 +279,7 @@ mod tests {
let parsed =
parse_typed_style_value("margin", "calc(1px + var(--x, env(foo, var(--y,))))", None)
.unwrap();
let TypedValue::Unparsed(parts) = &parsed.values.unwrap().values[0] else {
let TypedValue::Unparsed(parts) = &native_values(parsed).values[0] else {
panic!("unparsed shorthand");
};
assert!(matches!(&parts[0], UnparsedSegment::String(text) if text == "calc(1px + "));
+124
View File
@@ -0,0 +1,124 @@
use super::TypedStyleValueList;
use style::{
properties::{ComputedValues, LonghandId, PropertyDeclaration},
values::specified::Image,
};
use style_traits::ToCss;
/// A single native <image> iteration, including the distinct `none` keyword.
/// CSSImageValue is opaque: preserve the native AST's serialization without
/// interpreting function names or splitting commas inside image functions.
pub enum TypedImageValue {
None,
Image(String),
}
fn reify(image: &Image) -> TypedImageValue {
match image {
Image::None => TypedImageValue::None,
_ => TypedImageValue::Image(image.to_css_string()),
}
}
pub(super) fn from_declaration(declaration: &PropertyDeclaration) -> Option<Vec<TypedImageValue>> {
match declaration {
PropertyDeclaration::BackgroundImage(images) => Some(images.0.iter().map(reify).collect()),
PropertyDeclaration::MaskImage(images) => Some(images.0.iter().map(reify).collect()),
PropertyDeclaration::BorderImageSource(image)
| PropertyDeclaration::ListStyleImage(image) => Some(vec![reify(image)]),
_ => None,
}
}
pub fn computed_typed_style_value_list(
computed: &ComputedValues,
id: LonghandId,
) -> Option<TypedStyleValueList> {
if let Some(values) = computed.property_value_to_typed_value_list(id) {
return Some(TypedStyleValueList::Native(values));
}
match id {
LonghandId::BackgroundImage
| LonghandId::MaskImage
| LonghandId::BorderImageSource
| LonghandId::ListStyleImage => {
// Keep computed colors (including symbolic currentcolor), lengths
// and absolute URLs. This converts
// the computed AST directly; it does not parse CSSOM used values.
let declaration = computed.computed_or_resolved_declaration(id, None);
from_declaration(&declaration).map(TypedStyleValueList::Images)
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parse_typed_style_value;
use style::typed_om::TypedValue;
#[test]
fn native_image_iterations_preserve_nested_functions_none_and_urls() {
let source = r#"linear-gradient(red, blue), none, image-set(url("a,b.png") 1x, radial-gradient(red, blue) 2x), url("end.png")"#;
// mask-image requires browser prefs and is covered by the V8 fixture.
let property = "background-image";
let parsed = parse_typed_style_value(property, source, None)
.unwrap_or_else(|| panic!("valid {property}: {source}"));
let Some(TypedStyleValueList::Images(images)) = parsed.values else {
panic!("native image projection: {property}");
};
assert_eq!(images.len(), 4);
assert!(matches!(images[1], TypedImageValue::None));
let texts: Vec<_> = images
.iter()
.map(|value| match value {
TypedImageValue::None => "none",
TypedImageValue::Image(text) => text,
})
.collect();
assert_eq!(texts.join(", "), parsed.css_text);
assert!(texts[2].contains("a,b.png"));
assert!(texts[2].contains("radial-gradient("));
}
#[test]
fn image_projection_keeps_property_grammar_and_unparsed_boundaries() {
for property in [
"background-image",
"border-image-source",
"list-style-image",
] {
let parsed =
parse_typed_style_value(property, r"\6c inear-gradient(red, blue)", None).unwrap();
assert!(parsed.values.unwrap().is_single_image());
}
for property in ["background", "border-image"] {
let parsed =
parse_typed_style_value(property, "linear-gradient(red, blue)", None).unwrap();
assert!(parsed.values.is_none(), "{property} must remain opaque");
}
for (property, source) in [
("background-image", "linear-gradient(var(--x), blue)"),
("--image", "linear-gradient(red, blue)"),
] {
let parsed = parse_typed_style_value(property, source, None).unwrap();
let values = parsed.values.unwrap();
assert!(matches!(
values.native().unwrap().values.as_slice(),
[TypedValue::Unparsed(_)]
));
}
for (property, source) in [
("width", "linear-gradient(red, blue)"),
("border-image-source", "linear-gradient(red, blue), none"),
("background-image", "linear-gradient()"),
("background-image", "image-set(url(a) -1x)"),
] {
assert!(
parse_typed_style_value(property, source, None).is_none(),
"invalid {property}: {source}"
);
}
}
}
@@ -281,21 +281,26 @@ fn typed_value_count(parsed: &moli_css_parse::ParsedTypedStyleValue) -> usize {
parsed
.values
.as_ref()
.map_or(0, |values| values.values.len())
.map_or(0, moli_css_parse::TypedStyleValueList::len)
}
fn is_unparsed(parsed: &moli_css_parse::ParsedTypedStyleValue) -> bool {
parsed.values.as_ref().is_some_and(|list| {
list.values
.iter()
.any(|v| matches!(v, TypedValue::Unparsed(_)))
})
parsed
.values
.as_ref()
.and_then(moli_css_parse::TypedStyleValueList::native)
.is_some_and(|list| {
list.values
.iter()
.any(|v| matches!(v, TypedValue::Unparsed(_)))
})
}
fn is_numeric(parsed: &moli_css_parse::ParsedTypedStyleValue) -> bool {
parsed
.values
.as_ref()
.and_then(moli_css_parse::TypedStyleValueList::native)
.is_some_and(|list| matches!(list.values.as_slice(), [TypedValue::Numeric(_)]))
}
@@ -342,9 +347,7 @@ fn coerce_values<'s>(
&& !parsed
.as_ref()
.and_then(|v| v.values.as_ref())
.is_some_and(|v| {
v.values.len() == 1 && matches!(&v.values[0], TypedValue::Image(_))
})
.is_some_and(moli_css_parse::TypedStyleValueList::is_single_image)
{
return Err(CoercionError::Invalid);
}
@@ -391,6 +394,7 @@ fn coerce_values<'s>(
)
.and_then(|v| v.values)
.ok_or(CoercionError::Invalid)?;
let probe = probe.native().ok_or(CoercionError::Invalid)?;
if probe.values.len() != 1
|| !matches!(&probe.values[0], TypedValue::Numeric(NumericValue::Unit(value))
if values::native_unit_name(value.unit_str()) == unit
@@ -425,6 +429,7 @@ fn coerce_values<'s>(
&& !parsed
.as_ref()
.and_then(|v| v.values.as_ref())
.and_then(moli_css_parse::TypedStyleValueList::native)
.is_some_and(|v| {
v.values.len() == 1 && matches!(&v.values[0], TypedValue::Keyword(_))
})
@@ -460,7 +465,7 @@ fn coerce_values<'s>(
let doubled = format!("{text}, {text}");
let repeated = moli_css_parse::parse_typed_style_value(property, &doubled, base_url)
.and_then(|v| v.values)
.is_some_and(|v| v.values.len() >= 2);
.is_some_and(|v| v.len() >= 2);
if !repeated {
return Err(CoercionError::Invalid);
}
@@ -1,5 +1,7 @@
use super::*;
use moli_css_parse::CssDeclaredNumericValue;
use crate::web_api_interfaces;
use moli_css_parse::{CssDeclaredNumericValue, TypedImageValue, TypedStyleValueList};
use style::typed_om::{NumericValue, TypedValue};
use moli_webapi::css_values::{
CssKeywordValueObjectDeclaration, CssUnitValueObjectDeclaration, css_keyword_value, image_value,
};
@@ -8,7 +10,6 @@ pub(super) use moli_webapi::css_values::{
css_unit_value_constructor_callback, css_unit_value_number, css_unit_value_unit, keyword_value,
normalize_unit_name, opaque_style_value, style_value_from_text, unit_value,
};
use style::typed_om::{NumericValue, TypedValue};
mod number;
@@ -19,9 +20,13 @@ pub(super) fn from_parsed<'s>(
parsed: moli_css_parse::ParsedTypedStyleValue,
typed_values: Option<&[Option<CssDeclaredNumericValue>]>,
) -> Vec<v8::Local<'s, v8::Object>> {
let Some(typed) = parsed.values.filter(|list| !list.values.is_empty()) else {
let Some(typed) = parsed.values.filter(|list| !list.is_empty()) else {
return vec![opaque_style_value(scope, property, &parsed.css_text)];
};
let typed = match typed {
TypedStyleValueList::Native(typed) => typed,
TypedStyleValueList::Images(images) => return image_values(scope, images),
};
// Stylo determines whether this property is list-valued. Only subdivide
// its serialization when that projection has multiple items; a shorthand
// or unsupported property can contain commas without becoming a list.
@@ -151,14 +156,34 @@ pub(super) fn serialize<'s>(
moli_webapi::css_values::style_value_text(scope, value)
}
fn image_values<'s>(
scope: &mut v8::PinScope<'s, '_>,
images: Vec<TypedImageValue>,
) -> Vec<v8::Local<'s, v8::Object>> {
images
.into_iter()
.map(|value| match value {
TypedImageValue::None => CssKeywordValueObjectDeclaration::new("none".into())
.bind(scope)
.expect("CSSKeywordValue declaration should bind"),
TypedImageValue::Image(text) => image_value(scope, &text),
})
.collect()
}
pub(super) fn from_computed<'s>(
scope: &mut v8::PinScope<'s, '_>,
property: &str,
parsed: moli_css_parse::ParsedTypedStyleValue,
) -> Vec<v8::Local<'s, v8::Object>> {
let Some(typed) = parsed.values.filter(|list| !list.values.is_empty()) else {
let Some(typed) = parsed.values.filter(|list| !list.is_empty()) else {
return vec![opaque_style_value(scope, property, &parsed.css_text)];
};
let typed = match typed {
TypedStyleValueList::Native(typed) => typed,
TypedStyleValueList::Images(images) => return image_values(scope, images),
};
let texts = if typed.values.len() == 1 {
vec![parsed.css_text.clone()]
} else {
@@ -377,7 +377,9 @@ pub(crate) fn computed_typed_style_value_from_object<'s>(
let declaration = computed.computed_or_resolved_declaration(longhand, Some(&mut context));
let mut css_text = String::new();
declaration.to_css(&mut css_text).ok()?;
let values = declaration.to_typed_value_list();
let values = declaration
.to_typed_value_list()
.map(moli_css_parse::TypedStyleValueList::Native);
return Some(moli_css_parse::ParsedTypedStyleValue { css_text, values });
}
if let PropertyId::Custom(name) = &id
@@ -398,16 +400,18 @@ pub(crate) fn computed_typed_style_value_from_object<'s>(
return None;
}
let values = if property.starts_with("--") {
Some(style::typed_om::TypedValueList {
values: [style::typed_om::TypedValue::Unparsed(
moli_css_parse::reify_unparsed_style_value(&css_text, None)?,
)]
.into_iter()
.collect(),
})
Some(moli_css_parse::TypedStyleValueList::Native(
style::typed_om::TypedValueList {
values: [style::typed_om::TypedValue::Unparsed(
moli_css_parse::reify_unparsed_style_value(&css_text, None)?,
)]
.into_iter()
.collect(),
},
))
} else {
id.longhand_id()
.and_then(|id| computed.property_value_to_typed_value_list(id))
.and_then(|id| moli_css_parse::computed_typed_style_value_list(&computed, id))
};
Some(moli_css_parse::ParsedTypedStyleValue { css_text, values })
}
@@ -0,0 +1,134 @@
(() => {
const check = (ok, label) => { if (!ok) throw new Error(label); };
const throws = (realm, run, label) => {
let error;
try { run(); } catch (caught) { error = caught; }
check(error instanceof realm.TypeError, label);
};
const sources = [
'linear-gradient(to right, red, blue)',
'radial-gradient(circle at 25% 75%, red, blue)',
'conic-gradient(from 45deg, red, blue)',
'repeating-linear-gradient(red 0px, blue 10px)',
'repeating-radial-gradient(red 0px, blue 10px)',
'repeating-conic-gradient(red 0deg, blue 30deg)',
'image-set(url("/one.png") 1x, linear-gradient(red, blue) 2x)',
'image-set("data:image/svg+xml,<svg/>" 1x type("image/svg+xml"), url("/two.png") 2x)',
String.raw`\6c inear-gradient(/**/red, blue)`,
'linear-gradient(red)',
];
const child = document.querySelector('iframe').contentWindow;
for (const realm of [window, child]) {
const element = realm.document.createElement('div');
realm.document.body.append(element);
const map = element.attributeStyleMap;
const stringify = realm.CSSStyleValue.prototype.toString;
const properties = ['background-image', 'mask-image', 'border-image-source', 'list-style-image'];
for (const source of sources) {
const value = realm.CSSStyleValue.parse('background-image', source);
check(value instanceof realm.CSSImageValue, 'generated image type: ' + source);
check(Object.getPrototypeOf(value) === realm.CSSImageValue.prototype, 'native image prototype');
for (const property of properties) {
element.style.setProperty(property, source);
const text = element.style.getPropertyValue(property);
check(text !== '', 'native parser accepts image');
check(stringify.call(value) === text, 'native specified serialization');
map.set(property, value);
check(map.get(property) instanceof realm.CSSImageValue, 'cross-property image write');
check(String(map.get(property)) === text, 'declared image serialization');
const computed = element.computedStyleMap().get(property);
check(computed instanceof realm.CSSImageValue, 'computed image type');
check(String(computed) === realm.getComputedStyle(element).getPropertyValue(property), 'computed image serialization');
}
}
const parts = [sources[0], 'none', sources[6], 'url("/last.png")', sources[1]];
const list = realm.CSSStyleValue.parseAll('background-image', parts.join(', '));
const verifyList = (items, label) => {
check(items.length === parts.length, label + ': cardinality');
items.forEach((value, i) => check(i === 1
? value instanceof realm.CSSKeywordValue && value.value === 'none'
: value instanceof realm.CSSImageValue, label + ': iteration ' + i));
};
verifyList(list, 'parseAll');
check(String(realm.CSSStyleValue.parse('background-image', parts.join(', '))) === String(list[0]), 'parse returns first iteration');
for (const property of ['background-image', 'mask-image']) {
map.set(property, ...list);
verifyList(map.getAll(property), 'typed set');
check(map.getAll(property).map(String).join(', ') === element.style.getPropertyValue(property), 'declared list order');
const computed = element.computedStyleMap().getAll(property);
verifyList(computed, 'computed list');
check(computed.map(String).join(', ') === realm.getComputedStyle(element).getPropertyValue(property), 'computed list order');
map.set(property, list[0]);
map.append(property, ...list.slice(1));
verifyList(map.getAll(property), 'append');
const before = element.style.getPropertyValue(property);
throws(realm, () => map.set(property, list[0], realm.CSS.px(4)), 'invalid typed list');
throws(realm, () => map.append(property, 'linear-gradient()'), 'invalid appended image');
check(element.style.getPropertyValue(property) === before, 'failed writes are atomic');
}
for (const property of ['border-image-source', 'list-style-image']) {
throws(realm, () => map.set(property, ...list), 'single-valued property rejects list');
throws(realm, () => map.append(property, list[0]), 'single-valued property rejects append');
}
for (const property of ['background', 'width', '--image']) {
throws(realm, () => map.set(property, list[0]), 'image rejects incompatible property');
}
for (const source of ['linear-gradient()', 'image-set(url(a) -1x)', 'linear-gradient(red, blue); color: red']) {
throws(realm, () => realm.CSSStyleValue.parse('background-image', source), 'image grammar remains authoritative');
}
check(realm.CSSStyleValue.parse('background', sources[0]).constructor === realm.CSSStyleValue, 'shorthand remains property-associated');
check(realm.CSSStyleValue.parse('background-image', 'linear-gradient(var(--color), blue)') instanceof realm.CSSUnparsedValue, 'unresolved variables retain tokens');
element.style.color = 'rgb(10, 20, 30)';
element.style.fontSize = '10px';
element.style.setProperty('--image', 'linear-gradient(currentcolor 1em, blue 50%)');
element.style.backgroundImage = 'var(--image)';
check(map.get('background-image') instanceof realm.CSSUnparsedValue, 'declared variable remains unparsed');
const snapshot = element.computedStyleMap().get('background-image');
const previous = String(snapshot);
check(snapshot instanceof realm.CSSImageValue && previous.includes('10px'), 'computed image resolves relative lengths');
// Typed OM exposes computed values. CSS Color 4 keeps currentcolor
// symbolic until used-value time, unlike getComputedStyle's resolution.
check(previous === 'linear-gradient(currentcolor 10px, rgb(0, 0, 255) 50%)', 'computed variable image retains currentcolor');
const receiver = realm.document.createElement('div');
receiver.style.color = 'rgb(40, 50, 60)';
realm.document.body.append(receiver);
receiver.attributeStyleMap.set('background-image', snapshot);
check(String(receiver.attributeStyleMap.get('background-image')) === previous, 'computed image transfers its symbolic color');
check(realm.getComputedStyle(receiver).backgroundImage === 'linear-gradient(rgb(40, 50, 60) 10px, rgb(0, 0, 255) 50%)', 'transferred image resolves against receiver color');
receiver.remove();
element.style.fontSize = '20px';
check(String(element.computedStyleMap().get('background-image')).includes('20px'), 'computed image invalidates after style change');
check(String(snapshot) === previous, 'image is an immutable snapshot');
const value = list[0], text = String(value);
Object.defineProperty(value, 'toString', {value() { throw new Error('author stringifier'); }});
Object.defineProperty(value, Symbol.toPrimitive, {value() { throw new Error('author conversion'); }});
Object.setPrototypeOf(value, null);
map.set('list-style-image', value);
check(String(map.get('list-style-image')) === text, 'native identity and serialization survive author changes');
const sheet = new realm.CSSStyleSheet();
sheet.replaceSync('div { background-image: ' + parts.join(', ') + '; }');
const rule = sheet.cssRules[0];
verifyList(rule.styleMap.getAll('background-image'), 'rule map');
rule.styleMap.set('mask-image', ...list);
verifyList(rule.styleMap.getAll('mask-image'), 'rule typed write');
const retained = rule.styleMap.get('background-image');
sheet.deleteRule(0);
check(String(retained) === text, 'native image outlives removed rule');
const detached = realm.document.implementation.createHTMLDocument('').createElement('div');
detached.style.backgroundImage = parts.join(', ');
verifyList(detached.attributeStyleMap.getAll('background-image'), 'windowless image list');
element.remove();
}
const value = child.CSSStyleValue.parse('background-image', sources[6]);
const element = child.document.createElement('div');
child.document.body.append(element);
StylePropertyMap.prototype.set.call(element.attributeStyleMap, 'list-style-image', value);
const read = StylePropertyMapReadOnly.prototype.get.call(element.attributeStyleMap, 'list-style-image');
check(read instanceof child.CSSImageValue && !(read instanceof CSSImageValue), 'cross-realm map uses owner realm');
check(CSSStyleValue.prototype.toString.call(value) === String(read), 'cross-realm genuine image receiver');
element.remove();
return true;
})()
@@ -1,5 +1,17 @@
use super::*;
#[test]
fn css_generated_images_reify_native_lists_computed_values_and_typed_writes() {
let mut vm = new_parsed_test_vm(
"https://css-generated-images.test/",
"<!doctype html><body><iframe id=child></iframe>",
);
assert_eq!(
vm.eval(include_str!("css_generated_images.js")).unwrap(),
"true"
);
}
#[test]
fn css_image_values_reify_native_urls_and_preserve_brands_realms_and_writes() {
let mut vm = new_parsed_test_vm(