Truly independent web browser
LibWeb: Preserve token contents when trimming unresolved values
Callum Law198c017b6d59
diff --git a/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs b/Libraries/LibWeb/Rust/src/css/css_tokenizer.rsindex f86221cb3aa..0419de4a3e4 100644--- a/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs+++ b/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs@@ -11,6 +11,8 @@ use std::ops::Range;use std::ptr;use std::sync::Arc;+use crate::css::serialize::trim_ascii_whitespace_start;+const REPLACEMENT_CHARACTER: u32 = 0xFFFD;const TOKENIZER_EOF: u32 = u32::MAX;@@ -911,6 +913,63 @@ whereTokenizer::new(filtered_input.as_input()).tokenize(callback);}+pub(crate) fn trim_component_value_boundary_whitespace(source: &[u16]) -> &[u16] {+ let source = trim_ascii_whitespace_start(source);+ let is_ascii_whitespace = |unit: &u16| matches!(*unit, 0x09 | 0x0a | 0x0c | 0x0d | 0x20);+ if !source.last().is_some_and(is_ascii_whitespace) {+ return source;+ }++ let mut source_end = source.len();+ let code_points = filter_code_points(source.into());+ let input = code_points.as_input();+ let mut tokenizer = Tokenizer::new(input);+ let mut expected_closings = SmallVec::<[CssTokenType; 8]>::new();+ let mut trailing_whitespace_length = 0;+ let mut follows_backslash = false;++ loop {+ let token = tokenizer.next_token();+ let token_type = token.as_syntax_ffi().token_type;+ match token_type {+ CssTokenType::EndOfFile => break,+ CssTokenType::Function | CssTokenType::OpenParen => expected_closings.push(CssTokenType::CloseParen),+ CssTokenType::OpenSquare => expected_closings.push(CssTokenType::CloseSquare),+ CssTokenType::OpenCurly => expected_closings.push(CssTokenType::CloseCurly),+ token_type if expected_closings.last() == Some(&token_type) => {+ expected_closings.pop();+ }+ _ => {}+ }+ // Comments are emitted as whitespace tokens whose source starts with '/'.+ if token_type == CssTokenType::Whitespace+ && is_whitespace(u32::from(input.code_unit_at(token.original_source_range.start)))+ {+ trailing_whitespace_length += token.original_source_range.len();+ } else {+ trailing_whitespace_length = 0;+ follows_backslash = matches!(token.token_type, TokenType::Delim { value } if value == u32::from(b'\\'));+ }+ }++ // Whitespace inside an unclosed function or block belongs to that component value.+ if !expected_closings.is_empty() {+ return &source[..source_end];+ }++ // Token source lengths count CRLF as a single code point after input preprocessing.+ for _ in 0..trailing_whitespace_length {+ let is_crlf = source[..source_end].ends_with(&[0x0d, 0x0a]);+ source_end -= if is_crlf { 2 } else { 1 };+ }++ if follows_backslash {+ // Preserve the newline required to serialize a U+005C delimiter.+ source_end += 1;+ }+ &source[..source_end]+}+struct Tokenizer<'a> {input: TokenizerInput<'a>,index: usize,diff --git a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rsindex f1331fbad7b..3f6f7e71e8c 100644--- a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs@@ -16,6 +16,7 @@ use crate::css::css_pixels::CssPixels;use crate::css::css_string::{CssString, CssStringList};use crate::css::css_tokenizer::{CssNumberType, ParserTokenKind, TokenizerInput, tokenize_for_parser, tokenize_for_parser_without_source,+ trim_component_value_boundary_whitespace,};use crate::css::display::FfiDisplay;use crate::css::ffi_support::FfiUtf16View;@@ -5801,26 +5802,12 @@ fn parse_animation_transition_shorthand(ParseOutcome::Parsed(shared_style_value(shorthand_value(property, sub_properties, output)))}-fn trim_ascii_whitespace(code_units: &[u16]) -> &[u16] {- let is_ascii_whitespace = |unit: &u16| matches!(*unit, 0x09 | 0x0a | 0x0c | 0x0d | 0x20);- let start = code_units- .iter()- .position(|unit| !is_ascii_whitespace(unit))- .unwrap_or(code_units.len());- let end = code_units- .iter()- .rposition(|unit| !is_ascii_whitespace(unit))- .map_or(start, |position| position + 1);- &code_units[start..end]-}-pub(crate) fn unresolved_value_from_string(unresolved_source: &[u16],presence: SubstitutionFunctionsPresence,) -> StyleValueData {- let source_text = trim_ascii_whitespace(unresolved_source);- let values = consume_a_counted_list_of_component_values(tokenize_for_parser(source_text)).unwrap_or_default();- unresolved_value(source_text, &[], values, presence)+ let values = consume_a_counted_list_of_component_values(tokenize_for_parser(unresolved_source)).unwrap_or_default();+ unresolved_value(unresolved_source, &[], values, presence)}pub(crate) fn unresolved_value(@@ -5829,7 +5816,7 @@ pub(crate) fn unresolved_value(values: impl Into<ComponentValueList>,presence: SubstitutionFunctionsPresence,) -> StyleValueData {- let source_text = trim_ascii_whitespace(unresolved_source);+ let source_text = trim_component_value_boundary_whitespace(unresolved_source);let components = RetainedComponentValueList::from_values(values);if presence.attr {crate::css::parser::arbitrary_substitution::note_attr_names_read_by(components.as_slice());diff --git a/Libraries/LibWeb/Rust/src/css/serialize.rs b/Libraries/LibWeb/Rust/src/css/serialize.rsindex 7a7ce930f57..6618b7357b4 100644--- a/Libraries/LibWeb/Rust/src/css/serialize.rs+++ b/Libraries/LibWeb/Rust/src/css/serialize.rs@@ -330,15 +330,6 @@ pub(crate) fn original_component_values_source(Some(source)}-pub(crate) fn trim_ascii_whitespace(value: &[u16]) -> &[u16] {- let value = trim_ascii_whitespace_start(value);- let end = value- .iter()- .rposition(|unit| !matches!(*unit, 0x09 | 0x0a | 0x0c | 0x0d | 0x20))- .map_or(0, |position| position + 1);- &value[..end]-}-pub(crate) fn trim_ascii_whitespace_start(value: &[u16]) -> &[u16] {let start = value.iter()diff --git a/Libraries/LibWeb/Rust/src/css/style_value.rs b/Libraries/LibWeb/Rust/src/css/style_value.rsindex 2466f116a66..afc05e94872 100644--- a/Libraries/LibWeb/Rust/src/css/style_value.rs+++ b/Libraries/LibWeb/Rust/src/css/style_value.rs@@ -15,13 +15,14 @@ use crate::css::ffi_support::OwnedArc;use std::ffi::c_void;use std::sync::Arc;-use crate::css::css_tokenizer::{ParserSource, ParserTokenKind, SourcePosition, TokenizerInput};+use crate::css::css_tokenizer::{+ ParserSource, ParserTokenKind, SourcePosition, TokenizerInput, trim_component_value_boundary_whitespace,+};use crate::css::parser::component_value::{ComponentKind, ComponentSerializationMode, ComponentValue, ComponentValueList, ComponentValueSlice,};use crate::css::serialize::{- original_component_values_source, serialize_component_values_to_utf16, trim_ascii_whitespace,- trim_ascii_whitespace_start,+ original_component_values_source, serialize_component_values_to_utf16, trim_ascii_whitespace_start,};pub(crate) use crate::css::css_string::{CssString, CssStringList};@@ -3363,7 +3364,7 @@ pub unsafe extern "C" fn rust_style_value_create_unresolved_from_source(_ => unreachable!("unknown unresolved source text mode"),};let source_text = if source_text_mode == 0 {- trim_ascii_whitespace(&source_text)+ trim_component_value_boundary_whitespace(&source_text)} else if source_text_mode == 1 {trim_ascii_whitespace_start(&source_text)} else {diff --git a/Tests/LibWeb/Text/expected/css/custom-property-token-whitespace.txt b/Tests/LibWeb/Text/expected/css/custom-property-token-whitespace.txtnew file mode 100644index 00000000000..70305322efd--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/custom-property-token-whitespace.txt@@ -0,0 +1,10 @@+escaped space: ["a\\ ","a\\ "]+escaped space roundtrip: ["a\\ ","a\\ "]+delimiter newline: ["a\\\n","fallback"]+delimiter newline roundtrip: ["a\\\n","fallback"]+delimiter CR: ["a\\\r","fallback"]+delimiter CR roundtrip: ["a\\\r","fallback"]+EOF string: ["\"a ","\"a \""]+EOF string roundtrip: ["\"a ","\"a \""]+EOF function: "f(a "+EOF URL: "url(a\\ "diff --git a/Tests/LibWeb/Text/input/css/custom-property-token-whitespace.html b/Tests/LibWeb/Text/input/css/custom-property-token-whitespace.htmlnew file mode 100644index 00000000000..8e5004e7bf5--- /dev/null+++ b/Tests/LibWeb/Text/input/css/custom-property-token-whitespace.html@@ -0,0 +1,37 @@+<!doctype html>+<div id="target"></div>+<script src="../include.js"></script>+<script>+ test(() => {+ for (const [name, syntax, initialValue] of [+ ["--identifier", "<custom-ident>", "fallback"],+ ["--string", "<string>", '"fallback"'],+ ]) {+ CSS.registerProperty({ name, syntax, inherits: false, initialValue });+ }++ for (const [label, name, source] of [+ ["escaped space", "--identifier", " \r\n\ta\\ \r\n\t "],+ ["delimiter newline", "--identifier", "a" + String.fromCharCode(92, 10) + " "],+ ["delimiter CR", "--identifier", "a" + String.fromCharCode(92, 13) + " "],+ ["EOF string", "--string", ' \t"a '],+ ]) {+ target.style.setProperty(name, source);+ const values = () => JSON.stringify([+ target.style.getPropertyValue(name),+ getComputedStyle(target).getPropertyValue(name),+ ]);+ println(`${label}: ${values()}`);+ target.style.setProperty(name, target.style.getPropertyValue(name));+ println(`${label} roundtrip: ${values()}`);+ }++ for (const [label, source] of [+ ["EOF function", " f(a "],+ ["EOF URL", " url(a\\ "],+ ]) {+ target.style.setProperty("--raw", source);+ println(`${label}: ${JSON.stringify(target.style.getPropertyValue("--raw"))}`);+ }+ });+</script>