Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(svg): resolve detached font lengths with initial style

ldm0f70ebff0a1a3
diff --git a/moli-renderer-v8/src/context_bootstrap/svg_runtime/builders.rs b/moli-renderer-v8/src/context_bootstrap/svg_runtime/builders.rs
index 567b4191c..169af290b 100644
--- a/moli-renderer-v8/src/context_bootstrap/svg_runtime/builders.rs
+++ b/moli-renderer-v8/src/context_bootstrap/svg_runtime/builders.rs
@@ -3908,6 +3908,15 @@ fn resolve_svg_length_without_context(value: f64, unit: SvgLengthUnit) -> Option
if let Some(value) = resolve_svg_absolute_length(value, unit) {
return Some(value);
}
+ if matches!(unit, SvgLengthUnit::Ems | SvgLengthUnit::Exs) {
+ // SVGLength without an associated element uses the initial font size,
+ // independently of the element on which createSVGLength was called.
+ let context = moli_css_parse::CssNumericContext {
+ font_size_px: Some(crate::style_engine::initial_font_size_px()),
+ ..Default::default()
+ };
+ return resolve_svg_length_in_context(value, unit, 100.0, context);
+ }
matches!(unit, SvgLengthUnit::Percentage).then_some(value)
}
@@ -3935,6 +3944,18 @@ fn resolve_svg_length_user_value_for_unit<'s>(
100.0
};
let context = svg_length_numeric_context(runtime, handle, unit, connected);
+ resolve_svg_length_in_context(value, unit, basis, context)
+}
+
+fn resolve_svg_length_in_context(
+ value: f64,
+ unit: SvgLengthUnit,
+ basis: f64,
+ context: moli_css_parse::CssNumericContext,
+) -> Option<f64> {
+ if let Some(value) = resolve_svg_absolute_length(value, unit) {
+ return Some(value);
+ }
match unit {
SvgLengthUnit::Percentage => Some(value * basis / 100.0),
SvgLengthUnit::Ems => context.font_size_px.map(|basis| value * basis),
diff --git a/moli-renderer-v8/src/context_bootstrap/svg_runtime/callbacks.rs b/moli-renderer-v8/src/context_bootstrap/svg_runtime/callbacks.rs
index a51f6924f..2b57da172 100644
--- a/moli-renderer-v8/src/context_bootstrap/svg_runtime/callbacks.rs
+++ b/moli-renderer-v8/src/context_bootstrap/svg_runtime/callbacks.rs
@@ -3325,9 +3325,7 @@ pub(super) fn svg_svg_element_create_length_callback<'s>(
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
if require_svg_svg_element_receiver(scope, args.this(), "createSVGLength") {
- let length = build_svg_length(scope, 0.0);
- set_svg_length_owner_attribute(scope, length, args.this(), "");
- rv.set(length.into());
+ rv.set(build_svg_length(scope, 0.0).into());
}
}
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index 96fdaed66..00e4e198f 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -2161,6 +2161,7 @@ mod performance_observer_contract;
mod performance_receiver_consolidation;
mod svg_animation_interfaces;
mod svg_computed_path_precision;
+mod svg_detached_lengths;
mod svg_transform_sync_consolidation;
mod audio_event_interfaces;
diff --git a/moli-renderer-v8/src/script_vm/tests/svg_detached_lengths.js b/moli-renderer-v8/src/script_vm/tests/svg_detached_lengths.js
new file mode 100644
index 000000000..e35c9db11
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/svg_detached_lengths.js
@@ -0,0 +1,128 @@
+(() => {
+ const checks = [], ns = 'http://www.w3.org/2000/svg';
+ const check = (name, fn) => {
+ try { checks.push({name, passed: fn() === true}); }
+ catch (error) { checks.push({name, passed: false, error: String(error)}); }
+ };
+ const near = (actual, expected) => Math.abs(actual - expected) < 1e-5;
+ const realms = [window, document.querySelector('iframe').contentWindow];
+ for (const [ownerIndex, owner] of realms.entries()) {
+ const initial = owner.document.createElement('span');
+ initial.style.fontSize = 'initial';
+ owner.document.body.appendChild(initial);
+ const initialFont = parseFloat(owner.getComputedStyle(initial).fontSize);
+ initial.remove();
+ const docs = [owner.document,
+ owner.document.implementation.createHTMLDocument(''),
+ owner.document.implementation.createDocument(ns, 'svg'),
+ new owner.DOMParser().parseFromString('<svg xmlns="' + ns + '"/>', 'image/svg+xml')];
+ for (const [docIndex, doc] of docs.entries()) {
+ const factory = doc.createElementNS(ns, 'svg');
+ factory.style.fontSize = '48px';
+ (doc.body || doc.documentElement).appendChild(factory);
+ for (const [calleeIndex, callee] of realms.entries()) {
+ const prefix = `detached-length/${ownerIndex}/${docIndex}/${calleeIndex}`;
+ const proto = callee.SVGLength.prototype;
+ const value = Object.getOwnPropertyDescriptor(proto, 'value');
+ const specified = Object.getOwnPropertyDescriptor(proto, 'valueInSpecifiedUnits');
+ const string = Object.getOwnPropertyDescriptor(proto, 'valueAsString');
+ const convert = proto.convertToSpecifiedUnits, assign = proto.newValueSpecifiedUnits;
+ check(prefix + '/initial-font', () => initialFont > 0 && Number.isFinite(initialFont));
+ for (const [suffix, unit, basis] of [['em', proto.SVG_LENGTHTYPE_EMS, initialFont],
+ ['ex', proto.SVG_LENGTHTYPE_EXS, initialFont / 2]]) {
+ const length = factory.createSVGLength();
+ check(prefix + '/' + suffix + '/parse', () => {
+ string.set.call(length, '2' + suffix);
+ return length.unitType === unit && specified.get.call(length) === 2;
+ });
+ check(prefix + '/' + suffix + '/value', () => near(value.get.call(length), 2 * basis));
+ check(prefix + '/' + suffix + '/specified-setter', () => {
+ specified.set.call(length, 4.25);
+ return near(value.get.call(length), 4.25 * basis) && length.valueAsString === '4.25' + suffix;
+ });
+ check(prefix + '/' + suffix + '/absolute-setter', () => {
+ value.set.call(length, 3 * basis);
+ return length.unitType === unit && near(specified.get.call(length), 3) && near(length.value, 3 * basis);
+ });
+ check(prefix + '/' + suffix + '/assign', () => {
+ assign.call(length, unit, -1.5);
+ return near(length.value, -1.5 * basis) && length.valueInSpecifiedUnits === -1.5;
+ });
+ check(prefix + '/' + suffix + '/convert-px', () => {
+ convert.call(length, proto.SVG_LENGTHTYPE_PX);
+ return length.unitType === proto.SVG_LENGTHTYPE_PX && near(length.valueInSpecifiedUnits, -1.5 * basis);
+ });
+ check(prefix + '/' + suffix + '/convert-back', () => {
+ convert.call(length, unit);
+ return length.unitType === unit && near(length.valueInSpecifiedUnits, -1.5) && near(length.value, -1.5 * basis);
+ });
+ check(prefix + '/' + suffix + '/factory-font-mutation', () => {
+ factory.style.fontSize = '96px';
+ const result = near(length.value, -1.5 * basis);
+ factory.style.fontSize = '48px';
+ return result;
+ });
+ check(prefix + '/' + suffix + '/factory-removal', () => {
+ factory.remove();
+ const result = near(length.value, -1.5 * basis);
+ (doc.body || doc.documentElement).appendChild(factory);
+ return result;
+ });
+ const fromPx = factory.createSVGLength();
+ fromPx.valueAsString = '2px';
+ check(prefix + '/' + suffix + '/from-px', () => {
+ convert.call(fromPx, unit);
+ return fromPx.unitType === unit && near(fromPx.valueInSpecifiedUnits, 2 / basis) && near(fromPx.value, 2);
+ });
+ check(prefix + '/' + suffix + '/round-trip', () => {
+ convert.call(fromPx, proto.SVG_LENGTHTYPE_NUMBER);
+ return fromPx.unitType === proto.SVG_LENGTHTYPE_NUMBER && near(fromPx.valueInSpecifiedUnits, 2) && near(fromPx.value, 2);
+ });
+ }
+ const percent = factory.createSVGLength();
+ check(prefix + '/percent-basis', () => {
+ percent.valueAsString = '25%';
+ convert.call(percent, proto.SVG_LENGTHTYPE_EMS);
+ return near(percent.value, 25) && near(percent.valueInSpecifiedUnits, 25 / initialFont);
+ });
+ const real = factory.createSVGLength();
+ let proxyTraps = 0;
+ const revoked = callee.Proxy.revocable(real, {}); revoked.revoke();
+ const invalid = [{}, Object.create(proto), Object.create(real),
+ new callee.Proxy(real, {get() { proxyTraps++; throw 'unexpected proxy get'; }}), revoked.proxy];
+ for (const [index, receiver] of invalid.entries()) {
+ check(prefix + '/brand/' + index, () => {
+ let conversions = 0, error;
+ try { convert.call(receiver, {valueOf() { conversions++; return proto.SVG_LENGTHTYPE_EMS; }}); }
+ catch (caught) { error = caught; }
+ return error instanceof callee.TypeError && conversions === 0 && proxyTraps === 0;
+ });
+ }
+ if (docIndex === 0) {
+ const text = doc.createElementNS(ns, 'text');
+ text.style.fontSize = '40px'; text.setAttribute('x', '2em'); factory.appendChild(text);
+ const list = text.x.baseVal, item = list.getItem(0);
+ check(prefix + '/list/attached-font', () => near(value.get.call(item), 80));
+ check(prefix + '/list/remove-rebases', () => list.removeItem(0) === item && near(value.get.call(item), 2 * initialFont));
+ check(prefix + '/list/detached-mutation', () => {
+ specified.set.call(item, 6);
+ return near(value.get.call(item), 6 * initialFont) && text.getAttribute('x') === '';
+ });
+ check(prefix + '/list/reattach-rebases', () => {
+ text.style.fontSize = '20px';
+ return list.appendItem(item) === item && near(value.get.call(item), 120) && text.getAttribute('x') === '6em';
+ });
+ check(prefix + '/list/clear-rebases', () => {
+ list.clear(); return near(value.get.call(item), 6 * initialFont) && text.getAttribute('x') === '';
+ });
+ text.remove();
+ }
+ }
+ factory.remove();
+ }
+ }
+ globalThis.__svgDetachedLengthResults = {complete: true, total: checks.length,
+ passed: checks.filter(row => row.passed).length, checks};
+ globalThis.__uiEventResults = globalThis.__svgDetachedLengthResults;
+ return true;
+})()
diff --git a/moli-renderer-v8/src/script_vm/tests/svg_detached_lengths.rs b/moli-renderer-v8/src/script_vm/tests/svg_detached_lengths.rs
new file mode 100644
index 000000000..b27fa8922
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/svg_detached_lengths.rs
@@ -0,0 +1,20 @@
+use super::*;
+
+#[test]
+fn svg_detached_font_lengths_rebase_with_list_ownership() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://svg-detached-lengths.test/");
+ vm.eval("document.body.innerHTML = '<iframe></iframe>'")
+ .unwrap();
+ vm.eval(include_str!("svg_detached_lengths.js")).unwrap();
+ assert_eq!(
+ vm.eval("__svgDetachedLengthResults.complete").unwrap(),
+ "true"
+ );
+ assert_eq!(vm.eval("__svgDetachedLengthResults.total").unwrap(), "484");
+ assert_eq!(
+ vm.eval("JSON.stringify(__svgDetachedLengthResults.checks.filter(row => !row.passed).slice(0, 8))")
+ .unwrap(),
+ "[]"
+ );
+ assert_eq!(vm.eval("__svgDetachedLengthResults.passed").unwrap(), "484");
+}
diff --git a/moli-renderer-v8/src/style_engine/mod.rs b/moli-renderer-v8/src/style_engine/mod.rs
index 3ab9ff00b..36ac463d0 100644
--- a/moli-renderer-v8/src/style_engine/mod.rs
+++ b/moli-renderer-v8/src/style_engine/mod.rs
@@ -50,7 +50,7 @@ mod request;
mod retained;
pub(crate) use stylesheet::{
NativeStylesheetFontFaceProjection, NativeStylesheetFontFaceRuleProjection,
- StylesheetFontFaceProjection, StylesheetFontFaceRuleProjection,
+ StylesheetFontFaceProjection, StylesheetFontFaceRuleProjection, initial_font_size_px,
native_font_face_projection_for_stylesheet, native_font_face_rules_for_stylesheet,
};
#[cfg(test)]
diff --git a/moli-renderer-v8/src/style_engine/stylesheet.rs b/moli-renderer-v8/src/style_engine/stylesheet.rs
index aa403d188..016a4d006 100644
--- a/moli-renderer-v8/src/style_engine/stylesheet.rs
+++ b/moli-renderer-v8/src/style_engine/stylesheet.rs
@@ -373,6 +373,15 @@ pub(super) fn new_stylist_with_viewport(
)
}
+pub(crate) fn initial_font_size_px() -> f64 {
+ f64::from(
+ Font::initial_values()
+ .clone_font_size()
+ .computed_size()
+ .px(),
+ )
+}
+
pub(super) fn new_style_device_with_viewport(
viewport: StyleViewport,
environment: StyloStyleEnvironment,