fix(css): reify all declarations as native keyword values

Project the native CSSWideKeyword for all into CSSKeywordValue while
preserving property-specific shorthand and unparsed-value behavior.
Cover parse/parseAll, declaration snapshots, realms, native-slot writes,
property-independent keyword reuse and invalid-write atomicity.
This commit is contained in:
ldm0
2026-11-20 22:47:45 +08:00
parent 46c156b276
commit 55feaa3d21
3 changed files with 189 additions and 3 deletions
+75 -3
View File
@@ -5,11 +5,11 @@ use style::{
context::QuirksMode,
custom_properties::SpecifiedValue,
properties::{
Importance, PropertyDeclaration, PropertyDeclarationBlock, PropertyId,
SourcePropertyDeclaration, parse_one_declaration_into,
CSSWideKeyword, Importance, PropertyDeclaration, PropertyDeclarationBlock, PropertyId,
ShorthandId, SourcePropertyDeclaration, parse_one_declaration_into,
},
stylesheets::{CssRuleType, CssRuleTypes, Origin, UrlExtraData},
typed_om::{TypedValue, TypedValueList, UnparsedValue},
typed_om::{ToTyped, TypedValue, TypedValueList, UnparsedValue},
};
use style_traits::ParsingMode;
@@ -73,6 +73,13 @@ pub fn parse_typed_style_value(
.into_iter()
.collect(),
})
} else if matches!(id.as_shorthand(), Ok(ShorthandId::All))
&& let Some(keyword) = css_wide_keyword(&block)
{
// Typed OM explicitly reifies `all` as an identifier. Other
// shorthands keep their property-specific projection. Read the
// parsed keyword instead of guessing from serialized longhands.
keyword.to_typed_value_list()
} else {
block.property_value_to_typed_value_list(&id).ok()?
};
@@ -82,6 +89,14 @@ pub fn parse_typed_style_value(
})
}
fn css_wide_keyword(block: &PropertyDeclarationBlock) -> Option<CSSWideKeyword> {
let mut declarations = block.declaration_importance_iter();
let keyword = declarations.next()?.0.get_css_wide_keyword()?;
declarations
.all(|(declaration, _)| declaration.get_css_wide_keyword() == Some(keyword))
.then_some(keyword)
}
/// Preserve var() references in raw tokens, including inside other functions.
/// Stylo validates and recovers the token stream first. The token projection is
/// iterative and leaves env()/attr() as raw syntax instead of treating them as
@@ -110,6 +125,63 @@ mod tests {
use super::*;
use style::typed_om::{NumericValue, UnparsedSegment};
#[test]
fn all_reifies_keywords_without_retyping_ordinary_shorthands() {
for property in ["all", "width", "color", "animation-name"] {
for keyword in ["initial", "inherit", "unset", "revert", "revert-layer"] {
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"));
assert_eq!(values.values.len(), 1, "{property}: {keyword}");
assert!(
matches!(&values.values[0], TypedValue::Keyword(value) if value.0 == keyword),
"{property}: {keyword}"
);
}
}
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"
));
for (property, source) in [
("margin", "initial 1px"),
("margin", "initial, inherit"),
("all", "auto"),
("unknown-property", "initial"),
] {
assert!(parse_typed_style_value(property, source, None).is_none());
}
for (property, source) in [
("margin", "initial"),
("background", "inherit"),
("border", "revert-layer"),
("margin", "auto"),
("background", "none"),
("font", "medium serif"),
] {
assert!(
parse_typed_style_value(property, source, None)
.unwrap()
.values
.is_none()
);
}
for (property, source) in [
("all", "var(--x, initial)"),
("margin", "var(--x, initial)"),
("--x", "initial"),
] {
let parsed = parse_typed_style_value(property, source, None).unwrap();
assert!(matches!(
&parsed.values.unwrap().values[0],
TypedValue::Unparsed(_)
));
}
}
#[test]
fn typed_property_parsing_uses_grammar_and_property_types() {
for (name, value) in [
@@ -0,0 +1,102 @@
(() => {
'use strict';
const check = (ok, label) => { if (!ok) throw new Error(label); };
const equal = (actual, expected, label) => check(Object.is(actual, expected), label);
const raises = (callback, Type = TypeError) => {
try { callback(); } catch (error) { check(error instanceof Type, 'exception realm'); return; }
throw new Error('missing exception');
};
const keyword = (value, expected, realm = globalThis) => {
equal(Object.getPrototypeOf(value), realm.CSSKeywordValue.prototype, 'keyword realm');
equal(value.value, expected, 'keyword value');
equal(String(value), expected, 'keyword serialization');
};
const other = document.getElementById('child').contentWindow;
const keywords = ['initial', 'inherit', 'unset', 'revert', 'revert-layer'];
for (const realm of [globalThis, other]) {
const parse = realm.CSSStyleValue.parse;
for (const value of keywords) {
keyword(parse('AlL', `/**/${value.toUpperCase()} /**/`), value, realm);
const list = realm.CSSStyleValue.parseAll('all', value);
equal(Object.getPrototypeOf(list), realm.Array.prototype, 'parseAll realm');
equal(list.length, 1, 'all is single-valued');
keyword(list[0], value, realm);
for (const property of ['margin', 'background', 'border', 'font']) {
equal(Object.getPrototypeOf(parse(property, value)), realm.CSSStyleValue.prototype,
'ordinary shorthand remains property-associated');
}
equal(Object.getPrototypeOf(parse('--x', value)), realm.CSSUnparsedValue.prototype,
'unregistered custom property remains unparsed');
}
for (const source of ['auto', 'initial inherit', 'initial, inherit', 'initial; color:red']) {
raises(() => parse('all', source), realm.TypeError);
}
const unparsed = parse('all', 'var(--x, inherit)');
check(unparsed instanceof realm.CSSUnparsedValue, 'variable reference stays unparsed');
equal(unparsed[0].variable, '--x', 'native variable reference');
const Constructor = realm.CSSKeywordValue;
realm.CSSKeywordValue = () => { throw new Error('author constructor'); };
try {
equal(Object.getPrototypeOf(parse('all', 'inherit')), Constructor.prototype, 'intrinsic allocation');
} finally { realm.CSSKeywordValue = Constructor; }
}
const elements = [
document.createElement('div'),
document.createElementNS('http://www.w3.org/2000/svg', 'g'),
document.createElementNS('http://www.w3.org/1998/Math/MathML', 'mi'),
document.implementation.createHTMLDocument('').createElement('select'),
];
const sheet = new CSSStyleSheet(); sheet.replaceSync('div {}');
const foreign = other.document.createElement('div');
const foreignSheet = new other.CSSStyleSheet(); foreignSheet.replaceSync('div {}');
const surfaces = [
...elements.map(element => [element.style, element.attributeStyleMap, globalThis]),
[sheet.cssRules[0].style, sheet.cssRules[0].styleMap, globalThis],
[foreign.style, foreign.attributeStyleMap, other],
[foreignSheet.cssRules[0].style, foreignSheet.cssRules[0].styleMap, other],
];
for (const [style, map, realm] of surfaces) {
for (const value of keywords) {
style.cssText = '';
style.setProperty('all', value, 'important');
const snapshot = StylePropertyMapReadOnly.prototype.get.call(map, 'all');
keyword(snapshot, value, realm);
equal(map.getAll('all').length, 1, 'one all value');
keyword(map.getAll('all')[0], value, realm);
snapshot.value = 'changed';
keyword(map.get('all'), value, realm);
const input = other.CSSStyleValue.parse('all', value);
input.toString = () => { throw new Error('author stringifier'); };
Object.defineProperty(input, 'value', {get() { throw new Error('author value getter'); }});
StylePropertyMap.prototype.set.call(map, 'all', input);
keyword(map.get('all'), value, realm);
equal(style.getPropertyPriority('all'), '', 'typed write removes priority');
const before = style.cssText;
raises(() => map.set('all', CSS.px(1)), realm.TypeError);
raises(() => map.set('all', 'initial', 'inherit'), realm.TypeError);
raises(() => map.append('all', 'initial'), realm.TypeError);
equal(style.cssText, before, 'invalid all write stays atomic');
map.clear();
StylePropertyMap.prototype.set.call(map, 'color', input);
keyword(map.get('color'), value, realm);
style.cssText = 'all: inherit';
keyword(map.get('all'), 'inherit', realm);
style.removeProperty('all');
equal(map.getAll('all').length, 0, 'removed all declaration');
}
}
const element = elements[0];
const map = element.attributeStyleMap;
document.body.append(element);
element.setAttribute('style', 'all: initial');
keyword(map.get('all'), 'initial');
const observer = new MutationObserver(() => {});
observer.observe(element, {attributes: true, attributeOldValue: true});
map.set('all', CSSStyleValue.parse('all', 'inherit'));
const records = observer.takeRecords(); observer.disconnect();
equal(records.length, 1, 'one style mutation');
equal(records[0].oldValue, 'all: initial', 'mutation old value');
keyword(map.get('all'), 'inherit');
element.remove();
return true;
})()
@@ -1,5 +1,17 @@
use super::*;
#[test]
fn css_all_keywords_preserve_native_realms_and_property_independent_values() {
let mut vm = new_parsed_test_vm(
"https://css-all-keywords.test/",
"<!doctype html><body><iframe id=child></iframe>",
);
assert_eq!(
vm.eval(include_str!("css_all_keywords.js")).unwrap(),
"true"
);
}
#[test]
fn css_style_value_parse_reifies_declared_math_with_native_brands_and_realms() {
let mut vm = new_parsed_test_vm(