Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(cssom): accept counters in content alternative text

ldm0a54ba82a7ac6
diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/parse.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/parse.rs
index 93a527b6e..321151a38 100644
--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/parse.rs
+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/parse.rs
@@ -2346,6 +2346,9 @@ fn parse_pdb_supplemental_entries(
value: &str,
priority: bool,
) -> Option<ParsedStylePropertyEntries> {
+ if let Some(entries) = parse_content_alt_counter_supplemental_entries(name, value, priority) {
+ return Some(entries);
+ }
if let Some(entries) = parse_preferred_pdb_supplemental_entries(name, value, priority) {
return Some(entries);
}
@@ -2370,6 +2373,140 @@ fn parse_pdb_supplemental_entries(
parse_transition_numeric_property_entries(name, value, priority)
}
+fn parse_content_alt_counter_supplemental_entries(
+ name: &str,
+ value: &str,
+ priority: bool,
+) -> Option<ParsedStylePropertyEntries> {
+ if name != "content" {
+ return None;
+ }
+ let (content, alt) = split_content_alt_text(value)?;
+ if !content_alt_text_contains_only_strings_attrs_and_counters(alt)? {
+ return None;
+ }
+
+ // Stylo already owns the grammar on both sides of the slash. Its current
+ // content parser only has one narrower restriction: counter() and
+ // counters() are rejected after the alt marker. Validate the main list
+ // with an ordinary string alt, then validate the alt list as an ordinary
+ // content list. This keeps images and quote keywords out of alt text while
+ // retaining Stylo's counter argument and counter-style validation.
+ stylo_pdb_single_property_value(name, &format!("{content} / \"\""), priority)?;
+ let content = stylo_pdb_single_property_value(name, content, priority)?;
+ let alt = stylo_pdb_single_property_value(name, alt, priority)?;
+ Some(ParsedStylePropertyEntries {
+ entries: vec![StyleEntry {
+ name: name.to_owned(),
+ value: format!("{content} / {alt}"),
+ priority,
+ }],
+ affected_names: vec![name.to_owned()],
+ })
+}
+
+fn stylo_pdb_single_property_value(name: &str, value: &str, priority: bool) -> Option<String> {
+ let parsed = stylo_pdb_entries_for_property(name, value, priority)?;
+ let [entry] = parsed.entries.as_slice() else {
+ return None;
+ };
+ (entry.name == name && entry.priority == priority).then(|| entry.value.clone())
+}
+
+fn split_content_alt_text(value: &str) -> Option<(&str, &str)> {
+ let mut parser_input = cssparser::ParserInput::new(value);
+ let mut input = cssparser::Parser::new(&mut parser_input);
+ let value_start = input.position();
+ let mut slash = None;
+
+ loop {
+ let token_start = input.position();
+ let Ok(token) = input.next_including_whitespace_and_comments().cloned() else {
+ break;
+ };
+ let token_end = input.position();
+ match token {
+ cssparser::Token::Delim('/') => {
+ if slash.replace((token_start, token_end)).is_some() {
+ return None;
+ }
+ }
+ token if content_component_starts_nested_block(&token) => {
+ let nested: Result<(), cssparser::ParseError<'_, ()>> =
+ input.parse_nested_block(|input| {
+ consume_nested_content_components(input)
+ .ok_or_else(|| input.new_custom_error::<(), ()>(()))
+ });
+ nested.ok()?;
+ }
+ _ => {}
+ }
+ }
+ if !input.is_exhausted() {
+ return None;
+ }
+
+ let value_end = input.position();
+ let (slash_start, slash_end) = slash?;
+ let content = input.slice(value_start..slash_start).trim();
+ let alt = input.slice(slash_end..value_end).trim();
+ (!content.is_empty() && !alt.is_empty()).then_some((content, alt))
+}
+
+fn content_alt_text_contains_only_strings_attrs_and_counters(value: &str) -> Option<bool> {
+ let mut parser_input = cssparser::ParserInput::new(value);
+ let mut input = cssparser::Parser::new(&mut parser_input);
+ let mut has_counter = false;
+
+ while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {
+ match token {
+ cssparser::Token::WhiteSpace(_)
+ | cssparser::Token::Comment(_)
+ | cssparser::Token::QuotedString(_) => {}
+ cssparser::Token::Function(name)
+ if name.eq_ignore_ascii_case("attr")
+ || name.eq_ignore_ascii_case("counter")
+ || name.eq_ignore_ascii_case("counters") =>
+ {
+ has_counter |=
+ name.eq_ignore_ascii_case("counter") || name.eq_ignore_ascii_case("counters");
+ let nested: Result<(), cssparser::ParseError<'_, ()>> =
+ input.parse_nested_block(|input| {
+ consume_nested_content_components(input)
+ .ok_or_else(|| input.new_custom_error::<(), ()>(()))
+ });
+ nested.ok()?;
+ }
+ _ => return None,
+ }
+ }
+ input.is_exhausted().then_some(has_counter)
+}
+
+fn content_component_starts_nested_block(token: &cssparser::Token<'_>) -> bool {
+ matches!(
+ token,
+ cssparser::Token::Function(_)
+ | cssparser::Token::ParenthesisBlock
+ | cssparser::Token::SquareBracketBlock
+ | cssparser::Token::CurlyBracketBlock
+ )
+}
+
+fn consume_nested_content_components(input: &mut cssparser::Parser<'_, '_>) -> Option<()> {
+ while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {
+ if content_component_starts_nested_block(&token) {
+ let nested: Result<(), cssparser::ParseError<'_, ()>> =
+ input.parse_nested_block(|input| {
+ consume_nested_content_components(input)
+ .ok_or_else(|| input.new_custom_error::<(), ()>(()))
+ });
+ nested.ok()?;
+ }
+ }
+ input.is_exhausted().then_some(())
+}
+
fn parse_text_decoration_line_supplemental_entries(
name: &str,
value: &str,
@@ -7364,4 +7501,66 @@ mod tests {
"linear(0 0%, 1.3 11.111111%, 1 22.222222%, 0.92 33.333333%, 1 44.444444%, 0.99 55.555556%, 1 66.666667%, 1.004 77.777778%, 0.998 88.888889%, 1 100%, 1 100%)"
);
}
+
+ #[test]
+ fn content_alt_counters_use_validated_supplemental_entries() {
+ for (input, expected) in [
+ ("\"\" / counter(cnt)", "\"\" / counter(cnt)"),
+ (
+ "\"regular text\" / \"alt text 1\" counter(cnt) \"alt text 2\"",
+ "\"regular text\" / \"alt text 1\" counter(cnt) \"alt text 2\"",
+ ),
+ (
+ "\"regular text\" / counter(cnt) \"alt text\"",
+ "\"regular text\" / counter(cnt) \"alt text\"",
+ ),
+ (
+ "\"regular text\" / counters(chapter, \".\", DECIMAL)",
+ "\"regular text\" / counters(chapter, \".\")",
+ ),
+ (
+ "\"main / label\" / /* alt */ counter(cnt)",
+ "\"main / label\" / counter(cnt)",
+ ),
+ ] {
+ let parsed = parse_style_property_entries_for_cssom_write("content", input, true, None)
+ .unwrap_or_else(|| panic!("content: {input} should parse"));
+ assert_eq!(parsed.entries.len(), 1, "content: {input}");
+ assert_eq!(parsed.entries[0].name, "content", "content: {input}");
+ assert_eq!(parsed.entries[0].value, expected, "content: {input}");
+ assert!(parsed.entries[0].priority, "content: {input}");
+ assert_eq!(parsed.affected_names, vec!["content".to_owned()]);
+ assert!(style_entry_is_pdb_safe(&parsed.entries[0]));
+ assert!(
+ style_entry_is_pdb_supplemental_side_entry(&parsed.entries[0]),
+ "content: {input} should use side storage until Stylo parses alt counters"
+ );
+ }
+
+ for invalid in [
+ "none / counter(cnt)",
+ "\"\" / counter()",
+ "\"\" / url(alt.svg) counter(cnt)",
+ "\"\" / open-quote counter(cnt)",
+ "\"\" / counter(cnt) / \"extra\"",
+ "\"\" / counter(cnt) }",
+ ] {
+ assert!(
+ parse_style_property_entries_for_cssom_write("content", invalid, false, None)
+ .is_none(),
+ "content: {invalid} should remain invalid"
+ );
+ }
+
+ let ordinary = parse_style_property_entries_for_cssom_write(
+ "content",
+ "\"regular text\" / \"alt text\"",
+ false,
+ None,
+ )
+ .expect("ordinary string alt text should remain Stylo-backed");
+ assert!(!style_entry_is_pdb_supplemental_side_entry(
+ &ordinary.entries[0]
+ ));
+ }
}
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom.rs
index 5c996fc9f..3f8cec4aa 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom.rs
@@ -13070,6 +13070,66 @@ fn css_style_declaration_parses_content_and_bookmark_properties() {
);
}
+#[test]
+fn css_style_declaration_accepts_counters_in_content_alt_text() {
+ let mut vm = new_storage_test_vm("https://css-style-content-alt-counter.test/");
+
+ let result = vm
+ .eval(
+ r#"
+(() => {
+ const live = document.createElement('div').style;
+ const values = [
+ `"" / counter(cnt)`,
+ `"regular text" / "alt text 1" counter(cnt) "alt text 2"`,
+ `"regular text" / counter(cnt) "alt text"`,
+ `"regular text" / counters(chapter, ".", DECIMAL)`
+ ];
+ const serialized = values.map(value => {
+ live.content = value;
+ const read = live.getPropertyValue('content');
+ live.content = read;
+ return live.getPropertyValue('content');
+ });
+ live.content = `"regular text" / counter()`;
+ const afterInvalid = live.getPropertyValue('content');
+
+ live.cssText = `color: red; content: "" / counter(css-text)`;
+ const cssTextContent = live.getPropertyValue('content');
+ const cssTextColor = live.getPropertyValue('color');
+
+ const sheet = new CSSStyleSheet();
+ sheet.insertRule('div {}');
+ const rule = sheet.cssRules[0].style;
+ rule.setProperty('content', `"rule" / counter(rule-counter) "alt"`, 'important');
+ const ruleValue = rule.getPropertyValue('content');
+ const rulePriority = rule.getPropertyPriority('content');
+ rule.setProperty('content', `"rule" / url(alt.svg) counter(rule-counter)`);
+ const ruleAfterInvalid = rule.getPropertyValue('content');
+
+ return [
+ CSS.supports('content', `"" / counter(cnt)`),
+ CSS.supports('content', `"" / counters(cnt, ".")`),
+ CSS.supports('content', `"" / counter()`),
+ serialized.join('~'),
+ afterInvalid,
+ cssTextContent,
+ cssTextColor,
+ ruleValue,
+ rulePriority,
+ ruleAfterInvalid
+ ].join('|');
+})()
+"#,
+ )
+ .expect("content alt counter CSSOM should evaluate");
+
+ assert_eq!(
+ result,
+ "true|true|false|\"\" / counter(cnt)~\"regular text\" / \"alt text 1\" counter(cnt) \"alt text 2\"~\"regular text\" / counter(cnt) \"alt text\"~\"regular text\" / counters(chapter, \".\")|\"regular text\" / counters(chapter, \".\")|\"\" / counter(css-text)|red|\"rule\" / counter(rule-counter) \"alt\"|important|\"rule\" / counter(rule-counter) \"alt\""
+ );
+}
+
#[test]
fn css_style_declaration_supports_will_change() {
let mut vm = new_storage_test_vm("https://css-style-will-change.test/");