diff --git a/moli-css-parse/src/lib.rs b/moli-css-parse/src/lib.rs index 59e034a47f3..bbda4990d7f 100644 --- a/moli-css-parse/src/lib.rs +++ b/moli-css-parse/src/lib.rs @@ -10,6 +10,7 @@ mod font_palette; mod font_selection; mod math; mod media; +mod numeric_serialization; mod root_margin; mod stylesheet_imports; mod stylo_stylesheet; @@ -47,6 +48,9 @@ pub use media::{ evaluate_media_query_list, media_query_list_items, normalize_media_query_list, parse_media_query_list_with_context, screen_media_query_matches, }; +pub use numeric_serialization::{ + css_numeric_token_value, serialize_css_number, serialize_css_token, +}; pub use root_margin::{normalize_root_margin, root_margin_components}; pub use style::moli_declaration_block::{ CssDeclarationBlock, CssDeclarationEntry, CssMutationProjection, CssRemoveResult, CssSetResult, diff --git a/moli-css-parse/src/numeric_serialization.rs b/moli-css-parse/src/numeric_serialization.rs new file mode 100644 index 00000000000..555c8b67059 --- /dev/null +++ b/moli-css-parse/src/numeric_serialization.rs @@ -0,0 +1,268 @@ +//! Numeric serialization for Typed OM values and CSS token streams. +//! +//! A CSS numeric value uses CSSOM formatting; raw number/dimension tokens need +//! round-trippable double precision and must retain their lexical token type. + +use cssparser::{ToCss, Token, serialize_identifier}; +use std::fmt::{self, Write}; + +/// CSSOM's browser-compatible six-significant-digit numeric representation. +/// Rust's exponent formatter rounds ties to even, without first scaling the +/// double (which could overflow, underflow, or introduce another rounding). +/// Non-finite values use CSS math keywords; callers must put them in calc(). +pub fn serialize_css_number(value: f64) -> String { + if !value.is_finite() { + return if value.is_nan() { + "NaN" + } else if value.is_sign_negative() { + "-infinity" + } else { + "infinity" + } + .to_owned(); + } + if value == 0.0 { + return "0".to_owned(); + } + let rounded = format!("{value:.5e}"); + let (mantissa, exponent) = rounded.split_once('e').expect("exponent notation"); + let exponent: i32 = exponent.parse().expect("numeric exponent"); + if !(-4..6).contains(&exponent) { + return format!( + "{}e{exponent:+03}", + mantissa.trim_end_matches('0').trim_end_matches('.') + ); + } + let negative = mantissa.starts_with('-'); + let digits = mantissa.trim_start_matches('-').replace('.', ""); + let point = exponent + 1; + let mut output = if negative { + "-".to_owned() + } else { + String::new() + }; + if point <= 0 { + output.push_str("0."); + output.extend(std::iter::repeat_n('0', (-point) as usize)); + output.push_str(&digits); + } else { + let point = point as usize; + output.push_str(&digits[..point]); + if point < digits.len() { + output.push('.'); + output.push_str(&digits[point..]); + } + } + if output.contains('.') { + output.truncate(output.trim_end_matches('0').trim_end_matches('.').len()); + } + output +} + +// CSSParserToken in Chromium retains double precision but bounds the numeric +// range by f32::MAX. The source slice matters: cssparser's Token stores f32 +// values and saturates its integer field at i32 boundaries. +pub fn css_numeric_token_value(token: &Token<'_>, source: &str) -> Option { + let number = numeric_source(token, source)?.parse::().ok()?; + Some(number.clamp(-f64::from(f32::MAX), f64::from(f32::MAX))) +} + +fn numeric_source<'a>(token: &Token<'_>, source: &'a str) -> Option<&'a str> { + match token { + Token::Number { .. } => Some(source), + Token::Percentage { .. } => source.strip_suffix('%'), + Token::Dimension { .. } => { + // The tokenizer already validated the number. Find the boundary + // without consuming the e in a unit such as em; escaped units are + // handled by the original token rather than by slicing its name. + let bytes = source.as_bytes(); + let mut end = usize::from(matches!(bytes.first(), Some(b'+' | b'-'))); + while bytes.get(end).is_some_and(u8::is_ascii_digit) { + end += 1; + } + if bytes.get(end) == Some(&b'.') { + end += 1; + while bytes.get(end).is_some_and(u8::is_ascii_digit) { + end += 1; + } + } + if matches!(bytes.get(end), Some(b'e' | b'E')) { + let mut exponent = end + 1; + if matches!(bytes.get(exponent), Some(b'+' | b'-')) { + exponent += 1; + } + if bytes.get(exponent).is_some_and(u8::is_ascii_digit) { + end = exponent + 1; + while bytes.get(end).is_some_and(u8::is_ascii_digit) { + end += 1; + } + } + } + Some(&source[..end]) + } + _ => None, + } +} + +/// Serialize one tokenizer-produced token with its exact consumed source slice. +/// The caller owns token boundaries and insertion of any required separators. +pub fn serialize_css_token(token: &Token<'_>, source: &str, output: &mut String) -> fmt::Result { + let Some(value) = css_numeric_token_value(token, source) else { + return token.to_css(output); + }; + match token { + Token::Number { .. } => { + if !source.contains(['.', 'e', 'E']) { + // Match the browser's integer-token range, retaining values + // beyond i32 without silently making an integer token a float. + write!(output, "{}", value as i64)?; + } else { + let text = shortest_number(value); + output.push_str(&text); + if !text.contains(['.', 'e']) { + output.push_str(".0"); + } + } + } + Token::Percentage { .. } => { + output.push_str(&serialize_css_number(value)); + output.push('%'); + } + Token::Dimension { unit, .. } => { + output.push_str(&shortest_number(value)); + // A decoded unit such as e2 would turn 4e3e2 into a number token + // (4000e2). Escape its leading e so re-tokenizing preserves both + // the numeric value and the dimension type. + let bytes = unit.as_bytes(); + let ambiguous = matches!(bytes.first(), Some(b'e' | b'E')) + && (bytes.get(1).is_some_and(u8::is_ascii_digit) + || (matches!(bytes.get(1), Some(b'+' | b'-')) + && bytes.get(2).is_some_and(u8::is_ascii_digit))); + if ambiguous { + output.push_str(if bytes[0] == b'e' { "\\65 " } else { "\\45 " }); + cssparser::serialize_name(&unit[1..], output)?; + } else { + serialize_identifier(unit, output)?; + } + } + _ => unreachable!("numeric token projection"), + } + Ok(()) +} + +fn shortest_number(value: f64) -> String { + if value == 0.0 { + return "0".to_owned(); + } + let magnitude = value.abs(); + let plain = value.to_string(); + if (1e-6..1e21).contains(&magnitude) { + return plain; + } + let unsigned = plain.trim_start_matches('-'); + let point = unsigned.find('.').unwrap_or(unsigned.len()); + let digits = unsigned.replace('.', ""); + let significant = digits.trim_start_matches('0'); + let exponent = point as i32 - (digits.len() - significant.len()) as i32 - 1; + let significant = significant.trim_end_matches('0'); + let mut output = if value.is_sign_negative() { + "-".to_owned() + } else { + String::new() + }; + output.push_str(&significant[..1]); + if significant.len() > 1 { + output.push('.'); + output.push_str(&significant[1..]); + } + write!(&mut output, "e{exponent:+}").expect("String writes cannot fail"); + output +} + +#[cfg(test)] +mod tests { + use super::*; + use cssparser::Parser; + + fn serialize(source: &str) -> String { + let input = source; + let mut parser = Parser::new(input); + let token = parser.next().unwrap().clone(); + let mut result = String::new(); + serialize_css_token(&token, source, &mut result).unwrap(); + result + } + + #[test] + fn css_number_serialization_rounds_once_and_preserves_the_full_double_range() { + for (number, expected) in [ + (-0.0, "0"), + (0.031400000000000004, "0.0314"), + (1.234565, "1.23456"), + (-1.234565, "-1.23456"), + (999999.4, "999999"), + (999999.5, "1e+06"), + (0.0001, "0.0001"), + (0.00001, "1e-05"), + (f64::MAX, "1.79769e+308"), + (f64::from_bits(1), "4.94066e-324"), + (f64::INFINITY, "infinity"), + (f64::NEG_INFINITY, "-infinity"), + (f64::NAN, "NaN"), + ] { + assert_eq!(serialize_css_number(number), expected, "{number:?}"); + } + } + + #[test] + fn css_numeric_tokens_retain_precision_and_their_integer_or_number_type() { + for (source, expected) in [ + ("0.123456789123456789px", "0.12345678912345678px"), + ("0.123456789123456789", "0.12345678912345678"), + ("0.123456789123456789%", "0.123457%"), + ("+01.2300e+2px", "123px"), + ("+01.2300e+2", "123.0"), + ("-0", "0"), + ("-0.0", "0.0"), + ("-0px", "0px"), + ("+0.0%", "0%"), + ("2147483648", "2147483648"), + ("9223372036854775808", "9223372036854775807"), + ("1e100", "3.4028234663852886e+38"), + ("1e1000px", "3.4028234663852886e+38px"), + ("1e1000%", "3.40282e+38%"), + ("1e-999px", "0px"), + ("1e-7px", "1e-7px"), + ("1e-6px", "0.000001px"), + ("1e21px", "1e+21px"), + ("1em", "1em"), + ("1e2em", "100em"), + ("1p\\78", "1px"), + ] { + assert_eq!(serialize(source), expected, "{source}"); + } + } + + #[test] + fn dimension_serialization_does_not_turn_a_unit_into_an_exponent() { + for (source, unit, number) in [ + ("4e3e2", "e2", 4000.0), + ("4e3\\65 2", "e2", 4000.0), + ("1\\45 -2", "E-2", 1.0), + ("1e21e2", "e2", 1e21), + ("-2\\65 -foo", "e-foo", -2.0), + ] { + let text = serialize(source); + let input = &text; + let mut parser = Parser::new(input); + let token = parser.next().unwrap().clone(); + assert!( + matches!(&token, Token::Dimension { unit: parsed, .. } if parsed.as_ref() == unit), + "{source}: {text}" + ); + assert_eq!(css_numeric_token_value(&token, &text), Some(number)); + parser.expect_exhausted().unwrap(); + assert_eq!(serialize(&text), text, "serialization must be idempotent"); + } + } +} diff --git a/moli-css-parse/src/typed_om/tokens.rs b/moli-css-parse/src/typed_om/tokens.rs index 8002de946e8..cd89421913e 100644 --- a/moli-css-parse/src/typed_om/tokens.rs +++ b/moli-css-parse/src/typed_om/tokens.rs @@ -1,4 +1,4 @@ -use cssparser::{Parser, ToCss, Token, TokenSerializationType}; +use cssparser::{Parser, Token, TokenSerializationType}; use style::typed_om::{UnparsedSegment, UnparsedValue, VariableReferenceValue}; struct Frame { @@ -31,20 +31,21 @@ impl Frame { // Consume raw tokens without cssparser's component parser skipping nested // blocks; the input has already passed Stylo's declaration-value validation. -fn next<'a>(source: &mut &'a str) -> Option> { +fn next<'a>(source: &mut &'a str) -> Option<(Token<'a>, &'a str)> { let input = *source; let mut parser = Parser::new(input); let token = parser .next_including_whitespace_and_comments() .ok()? .clone(); - *source = &source[parser.position().byte_index()..]; - Some(token) + let (consumed, remaining) = source.split_at(parser.position().byte_index()); + *source = remaining; + Some((token, consumed)) } fn next_non_whitespace<'a>(source: &mut &'a str) -> Option> { loop { - let token = next(source)?; + let (token, _) = next(source)?; if !matches!(token, Token::WhiteSpace(_) | Token::Comment(_)) { return Some(token); } @@ -53,7 +54,7 @@ fn next_non_whitespace<'a>(source: &mut &'a str) -> Option> { pub(super) fn reify(mut source: &str) -> Option { let mut stack = vec![Frame::new(None)]; - while let Some(token) = next(&mut source) { + while let Some((token, consumed)) = next(&mut source) { let frame = stack.last_mut()?; if matches!(&token, Token::Function(name) if name.eq_ignore_ascii_case("var")) { frame.flush(); @@ -105,7 +106,7 @@ pub(super) fn reify(mut source: &str) -> Option { if frame.previous.needs_separator_when_before(kind) { frame.text.push_str("/**/"); } - token.to_css(&mut frame.text).ok()?; + crate::serialize_css_token(&token, consumed, &mut frame.text).ok()?; frame.previous = kind; } if stack.len() != 1 { diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/unparsed/serialization.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/unparsed/serialization.rs index 9b424590186..3df9726c286 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/unparsed/serialization.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/unparsed/serialization.rs @@ -1,5 +1,5 @@ use super::*; -use cssparser::{ToCss, TokenSerializationType, serialize_identifier}; +use cssparser::{TokenSerializationType, serialize_identifier}; struct Frame<'s> { owner: v8::Local<'s, v8::Object>, @@ -84,8 +84,7 @@ fn serialize_tokens(mut source: &str) -> String { if previous.needs_separator_when_before(next) { output.push_str("/**/"); } - token - .to_css(&mut output) + moli_css_parse::serialize_css_token(&token, &source[..consumed], &mut output) .expect("String writes cannot fail"); previous = next; } diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values.rs index aa5eef774d8..8a0953d6916 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values.rs @@ -2,10 +2,11 @@ use super::*; use style::typed_om::{NumericValue, TypedValue}; use moli_webapi::css_values::{ CssKeywordValueObjectDeclaration, CssUnitValueObjectDeclaration, opaque_style_value, + css_unit_value_number, css_unit_value_unit, }; pub(super) use moli_webapi::css_values::{ css_keyword_value_constructor_callback, css_unit_value_constructor_callback, - install_typed_value_template_bindings, style_value_from_text, + style_value_from_text, }; mod number; @@ -71,3 +72,68 @@ pub(super) fn from_parsed<'s>( .collect() } +#[derive(WebApiFunctionTemplate)] +#[webapi(interface = crate::web_api_interfaces::CSSStyleValue, enumerable)] +struct CssStyleValueSerializationDeclaration { + #[webapi(method = "toString", callback = css_style_value_to_string_callback, length = 0)] + to_string: (), +} + +pub(super) fn install_typed_value_template_bindings<'s>( + scope: &mut v8::PinScope<'s, '_, ()>, + template: v8::Local<'s, v8::FunctionTemplate>, + interface_name: &str, +) { + if interface_name == "CSSStyleValue" { + let prototype = template.prototype_template(scope); + CssStyleValueSerializationDeclaration::initialize_prototype_template(scope, prototype); + } else { + moli_webapi::css_values::install_typed_value_template_bindings( + scope, + template, + interface_name, + ); + } +} + +fn css_style_value_to_string_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if crate::web_api_interfaces::CSSUnparsedValue::is_instance(scope, args.this()) { + if let Some(text) = + super::unparsed::serialize(scope, args.this()).and_then(|text| v8_string(scope, &text)) + { + rv.set(text.into()); + } + return; + } + if let Some(unit) = css_unit_value_unit(scope, args.this()) { + let value = css_unit_value_number(scope, args.this()).unwrap_or(0.0); + let number = moli_css_parse::serialize_css_number(value); + let text = if !value.is_finite() { + // IDL constructors/setters require finite doubles; values reified + // from CSS math may nevertheless carry a non-finite result. + if unit == "number" { + format!("calc({number})") + } else { + format!( + "calc({number} * 1{})", + if unit == "percent" { "%" } else { &unit } + ) + } + } else { + match unit.as_str() { + "number" => number, + "percent" => format!("{number}%"), + _ => format!("{number}{unit}"), + } + }; + if let Some(text) = v8_string(scope, &text) { + rv.set(text.into()); + } + return; + } + moli_webapi::css_values::css_style_value_to_string_callback(scope, args, rv); +} diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values/number.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values/number.rs index 3905dd511dc..b3f2ccddaf7 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values/number.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/typed_om/values/number.rs @@ -12,52 +12,20 @@ pub(super) fn from_literal(source: &str, target_unit: &str) -> Option { let token = parser.next().ok()?.clone(); let text = parser.slice_from(start); parser.expect_exhausted().ok()?; - let number = match token { + let number = moli_css_parse::css_numeric_token_value(&token, text)?; + match token { Token::Number { .. } => { - let number = text.parse::().ok()?; if target_unit != "number" && number != 0.0 { return None; } - number + Some(number) } - Token::Percentage { .. } => { - let number = text.strip_suffix('%')?.parse::().ok()?; - match target_unit { - "%" | "percent" => number, - "number" => number * 0.01, - _ => return None, - } - } - Token::Dimension { unit, .. } if unit.eq_ignore_ascii_case(target_unit) => { - // The token is a validated CSS dimension. Locate its numeric part, - // allowing an exponent only when e/E is followed by signed digits - // (so 1em and 1e2em have distinct boundaries). Units may be escaped. - let bytes = text.as_bytes(); - let mut end = usize::from(matches!(bytes.first(), Some(b'+' | b'-'))); - while bytes.get(end).is_some_and(u8::is_ascii_digit) { - end += 1; - } - if bytes.get(end) == Some(&b'.') { - end += 1; - while bytes.get(end).is_some_and(u8::is_ascii_digit) { - end += 1; - } - } - if matches!(bytes.get(end), Some(b'e' | b'E')) { - let mut exponent = end + 1; - if matches!(bytes.get(exponent), Some(b'+' | b'-')) { - exponent += 1; - } - if bytes.get(exponent).is_some_and(u8::is_ascii_digit) { - end = exponent + 1; - while bytes.get(end).is_some_and(u8::is_ascii_digit) { - end += 1; - } - } - } - text[..end].parse::().ok()? - } - _ => return None, - }; - number.is_finite().then_some(number) + Token::Percentage { .. } => match target_unit { + "%" | "percent" => Some(number), + "number" => Some(number * 0.01), + _ => None, + }, + Token::Dimension { unit, .. } if unit.eq_ignore_ascii_case(target_unit) => Some(number), + _ => None, + } } diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs index 2d5e7728b30..41fb2511653 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs @@ -62,6 +62,7 @@ mod cross_document_and_animations; mod css_computed_background; mod css_computed_font; mod css_computed_map_enumeration; +mod css_numeric_serialization; mod css_style_value_parse; mod css_unparsed; mod css_variable_fonts; diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_serialization.js b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_serialization.js new file mode 100644 index 00000000000..ea8c572fd8c --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_serialization.js @@ -0,0 +1,78 @@ +(() => { + const equal = (actual, expected, label) => { + if (!Object.is(actual, expected)) throw new Error(`${label}: ${actual} !== ${expected}`); + }; + const throws = callback => { + try { callback(); } catch (error) { if (error instanceof TypeError) return; throw error; } + throw new Error('expected TypeError'); + }; + const cases = [ + [-0, '0'], [3.14, '3.14'], [.031400000000000004, '0.0314'], + [.12345678912345678, '0.123457'], [1.23456789, '1.23457'], + [123456.789, '123457'], [1234567.89, '1.23457e+06'], + [999999.5, '1e+06'], [999999.4, '999999'], [1e-4, '0.0001'], + [1e-5, '1e-05'], [1e-7, '1e-07'], [1e20, '1e+20'], [1e21, '1e+21'], + [1e100, '1e+100'], [Number.MAX_VALUE, '1.79769e+308'], + [Number.MIN_VALUE, '4.94066e-324'], [Number.MIN_VALUE * 2, '9.88131e-324'], + [Number.MAX_SAFE_INTEGER, '9.0072e+15'], [1.234565, '1.23456'], [-1.234565, '-1.23456'], + ]; + for (const [number, expected] of cases) { + for (const [unit, suffix] of [['number', ''], ['percent', '%'], ['px', 'px']]) { + const value = new CSSUnitValue(number, unit); + equal(String(value), expected + suffix, `format ${number}${unit}`); + equal(value.value, number, 'serialization does not round the stored double'); + value.value = number * -1; + equal(value.value, number * -1, 'setter retains the double'); + } + } + const parsed = CSSStyleValue.parse('opacity', '3.14%'); + equal(parsed.value, 3.14 * 0.01, 'parsed percentage double'); + equal(String(parsed), '0.0314', 'parsed percentage formatting'); + for (const source of ['1e100px', '1e1000px']) { + const value = CSSStyleValue.parse('width', source); + equal(value.value, 3.4028234663852886e38, 'CSS parser numeric range'); + equal(String(value), '3.40282e+38px', 'range-clamped value formatting'); + } + for (const [source, expected] of [ + ['0.123456789123456789px', '0.12345678912345678px'], + ['0.123456789123456789', '0.12345678912345678'], + ['0.123456789123456789%', '0.123457%'], + ['+01.2300e+2px', '123px'], ['+01.2300e+2', '123.0'], + ['1.0', '1.0'], ['-0', '0'], ['-0.0', '0.0'], ['-0px', '0px'], + ['+0.0%', '0%'], ['1e1000px', '3.4028234663852886e+38px'], + ['1e1000%', '3.40282e+38%'], ['1e-999px', '0px'], ['1e-7', '1e-7'], + ['1e+21px', '1e+21px'], ['1em', '1em'], ['1e2em', '100em'], + ['1p\\78', '1px'], ['2147483648', '2147483648'], + ['9223372036854775808', '9223372036854775807'], + ]) { + equal(String(new CSSUnparsedValue([source])), expected, 'constructed token ' + source); + const value = CSSStyleValue.parse('--raw', source); + equal(value[0], expected, 'reified token ' + source); + equal(String(value), expected, 'reified token serialization ' + source); + } + const reference = new CSSVariableReferenceValue('--x', new CSSUnparsedValue(['0.123456789123456789px'])); + equal(String(new CSSUnparsedValue([reference])), 'var(--x,0.12345678912345678px)', 'fallback precision'); + reference.fallback[0] = '0.234567890123456789px'; + equal(String(new CSSUnparsedValue([reference])), 'var(--x,0.2345678901234568px)', 'live fallback mutation'); + equal(String(new CSSUnparsedValue(['1.0', 'px'])), '1.0/**/px', 'number/identifier boundary'); + + const other = document.getElementById('child').contentWindow; + const foreign = new other.CSSUnitValue(.031400000000000004, 'number'); + equal(CSSStyleValue.prototype.toString.call(foreign), '0.0314', 'cross-realm native value'); + const value = new CSSUnitValue(1, 'px'); + for (const invalid of [NaN, Infinity, -Infinity]) { + throws(() => new CSSUnitValue(invalid, 'px')); + throws(() => { value.value = invalid; }); + equal(value.value, 1, 'invalid setter does not mutate'); + } + const precision = Number.prototype.toPrecision, numberString = Number.prototype.toString; + try { + Number.prototype.toPrecision = Number.prototype.toString = () => { throw new Error('author numeric formatting'); }; + equal(String(foreign), '0.0314', 'native formatter ignores author methods'); + equal(String(new CSSUnparsedValue(['0.123456789123456789px'])), '0.12345678912345678px', 'native token formatting'); + } finally { + Number.prototype.toPrecision = precision; + Number.prototype.toString = numberString; + } + return true; +})() diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_serialization.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_serialization.rs new file mode 100644 index 00000000000..4840aa03a28 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/css_numeric_serialization.rs @@ -0,0 +1,38 @@ +use super::*; + +#[test] +fn css_numeric_values_and_tokens_serialize_without_losing_double_precision() { + let mut vm = new_parsed_test_vm( + "https://css-numeric-serialization.test/", + "", + ); + assert_eq!( + vm.eval(include_str!("css_numeric_serialization.js")) + .unwrap(), + "true" + ); +} + +#[test] +fn css_unparsed_dimension_tokens_keep_their_type_and_value_when_reserialized() { + let mut vm = new_storage_test_vm("https://css-token-boundaries.test/"); + assert_eq!( + vm.eval( + r#"(() => { + for (const [source, expected] of [ + ['4e3e2', '4000\\65 2'], ['4e3\\65 2', '4000\\65 2'], + ['1\\45 -2', '1\\45 -2'], ['1e21e2', '1e+21\\65 2'], + ]) { + const parsed = CSSStyleValue.parse('--token', source); + if (parsed[0] !== expected || String(parsed) !== expected || + String(new CSSUnparsedValue([source])) !== expected || + String(CSSStyleValue.parse('--token', String(parsed))) !== expected) + throw new Error('dimension changed: ' + source + ' -> ' + String(parsed)); + } + return true; + })()"# + ) + .unwrap(), + "true" + ); +} diff --git a/moli-webapi/src/css_values.rs b/moli-webapi/src/css_values.rs index 8134e5925f5..672530122c3 100644 --- a/moli-webapi/src/css_values.rs +++ b/moli-webapi/src/css_values.rs @@ -84,7 +84,7 @@ struct CssUnitValuePrototypeDeclaration { #[derive(webidl::WebIdlArgs)] #[webidl(prefix = "CSSUnitValue")] struct CssUnitValueConstructorArgs { - #[webidl(required)] + #[webidl(required, converter = "double")] value: f64, #[webidl(required)] unit: String, @@ -261,19 +261,11 @@ fn normalize_unit_name(unit: &str) -> Option { VALID_UNIT_NAMES.contains(&unit.as_str()).then_some(unit) } -fn css_style_value_to_string_callback<'s>( +pub fn css_style_value_to_string_callback<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - if web_api_interfaces::CSSUnparsedValue::is_instance(scope, args.this()) { - if let Some(text) = - super::unparsed::serialize(scope, args.this()).and_then(|text| v8_string(scope, &text)) - { - rv.set(text.into()); - } - return; - } if let Some(unit) = css_unit_value_unit(scope, args.this()) { let value = css_unit_value_number(scope, args.this()).unwrap_or(0.0); let number = v8::Number::new(scope, value) @@ -406,7 +398,7 @@ fn css_unit_value_unit_getter_callback<'s>( } } -fn css_unit_value_number<'s>( +pub fn css_unit_value_number<'s>( scope: &mut v8::PinScope<'s, '_>, receiver: v8::Local<'s, v8::Object>, ) -> Option { @@ -423,7 +415,7 @@ fn css_keyword_value<'s>( .map(|value| value.to_rust_string_lossy(scope)) } -fn css_unit_value_unit<'s>( +pub fn css_unit_value_unit<'s>( scope: &mut v8::PinScope<'s, '_>, receiver: v8::Local<'s, v8::Object>, ) -> Option {