From 3fc3c436585de1e700456f29faaf9bde4e5556ef Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sat, 26 Sep 2026 06:17:45 +0800 Subject: [PATCH] fix(focus): align native focusability across element namespaces --- moli-renderer-v8/src/native_bridge/element.rs | 8 +- .../native_bridge/element/base_prototypes.rs | 18 +++ .../src/native_bridge/element/focus.rs | 112 +++++++++++++----- .../src/script_vm/tests/dom_elements/focus.rs | 58 +++++++++ .../tests/fixtures/element-focusability.js | 111 +++++++++++++++++ .../tests/fixtures/foreign-focus-receivers.js | 61 ++++++++++ 6 files changed, 339 insertions(+), 29 deletions(-) create mode 100644 moli-renderer-v8/tests/fixtures/element-focusability.js create mode 100644 moli-renderer-v8/tests/fixtures/foreign-focus-receivers.js diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rs index f7998653b45..05fb54ce903 100644 --- a/moli-renderer-v8/src/native_bridge/element.rs +++ b/moli-renderer-v8/src/native_bridge/element.rs @@ -1520,9 +1520,15 @@ pub(crate) fn install_element_template_bindings<'s>( HtmlElementPopoverPrototypeDeclaration, HtmlElementGeometryPrototypeDeclaration, ), - "SVGElement" | "MathMLElement" => install!( + "SVGElement" => install!( ElementStylePrototypeDeclaration, HtmlOrForeignElementPrototypeDeclaration, + SvgElementFocusPrototypeDeclaration, + ), + "MathMLElement" => install!( + ElementStylePrototypeDeclaration, + HtmlOrForeignElementPrototypeDeclaration, + MathMlElementFocusPrototypeDeclaration, ), _ => {} } diff --git a/moli-renderer-v8/src/native_bridge/element/base_prototypes.rs b/moli-renderer-v8/src/native_bridge/element/base_prototypes.rs index 1f4539318ef..663f62f08a7 100644 --- a/moli-renderer-v8/src/native_bridge/element/base_prototypes.rs +++ b/moli-renderer-v8/src/native_bridge/element/base_prototypes.rs @@ -969,6 +969,24 @@ pub(super) struct HtmlElementActionPrototypeDeclaration { scroll_into_view_if_needed: (), } +#[derive(WebApiFunctionTemplate)] +#[webapi(interface = web_api_interfaces::SVGElement, receiver)] +struct SvgElementFocusPrototypeDeclaration { + #[webapi(method, length = 0, enumerable, callback = node_focus_callback)] + focus: (), + #[webapi(method, length = 0, enumerable, callback = node_blur_callback)] + blur: (), +} + +#[derive(WebApiFunctionTemplate)] +#[webapi(interface = web_api_interfaces::MathMLElement, receiver)] +struct MathMlElementFocusPrototypeDeclaration { + #[webapi(method, length = 0, enumerable, callback = node_focus_callback)] + focus: (), + #[webapi(method, length = 0, enumerable, callback = node_blur_callback)] + blur: (), +} + #[derive(WebApiFunctionTemplate)] #[webapi(name = "HTMLOrForeignElement")] pub(super) struct HtmlOrForeignElementPrototypeDeclaration { diff --git a/moli-renderer-v8/src/native_bridge/element/focus.rs b/moli-renderer-v8/src/native_bridge/element/focus.rs index 128dcd66284..56ed43ffb9b 100644 --- a/moli-renderer-v8/src/native_bridge/element/focus.rs +++ b/moli-renderer-v8/src/native_bridge/element/focus.rs @@ -1,5 +1,4 @@ -use super::global_attributes::parse_tab_index_attribute; -use crate::dom::native::Node; +use crate::dom::native::{Element, Node}; use super::super::{ JsContextHost, PendingWindowMessageEndpoint, document, node::node_runtime_and_handle_from_args, @@ -9,6 +8,7 @@ use super::forms::{ text_control_value, }; use super::geometry::{read_element_metrics, scroll_node_into_view_if_needed}; +use super::global_attributes::parse_tab_index_attribute; use super::styles::{StyleMode, style_property_value}; use super::{ construct_click_event, construct_focus_event, construct_interest_event, @@ -80,10 +80,7 @@ fn html_area_has_associated_image_map(runtime: &JsContextHost, handle: DomHandle let Some(area) = dom.node(handle).and_then(Node::as_element) else { return false; }; - if area.namespace() != document::XHTML_NS - || area.local_name() != "area" - || !area.has_attribute("href") - { + if !area.is_html_element("area") { return false; } @@ -141,17 +138,82 @@ pub(super) fn is_focusable(runtime: &JsContextHost, handle: DomHandle) -> bool { { return false; } - if element.namespace() == document::XHTML_NS && element.local_name() == "area" { - return html_area_has_associated_image_map(runtime, handle); + if element.is_html_element("area") && !html_area_has_associated_image_map(runtime, handle) { + return false; } - matches!( - element.local_name(), - "input" | "button" | "select" | "textarea" | "a" | "iframe" | "frame" | "dialog" - ) || element.has_attribute("tabindex") - || contenteditable_editing_host(runtime, handle) == Some(handle) + if element.is_html_element("input") + && element + .attribute("type") + .is_some_and(|value| value.eq_ignore_ascii_case("hidden")) + { + return false; + } + element + .attribute("tabindex") + .and_then(parse_tab_index_attribute) + .is_some() + || has_default_focus_behavior(runtime, handle) || element_is_scrollable(runtime, handle) } +fn has_default_focus_behavior(runtime: &JsContextHost, handle: DomHandle) -> bool { + let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else { + return false; + }; + let native_focus_behavior = match (element.namespace(), element.local_name()) { + (document::XHTML_NS, "a" | "area") | (document::MATHML_NS, "a") => { + element.has_attribute("href") + } + (document::SVG_NS, "a") => { + element.has_attribute("href") + || element.has_attribute_ns("http://www.w3.org/1999/xlink", "href") + } + ( + document::XHTML_NS, + "input" | "button" | "select" | "textarea" | "iframe" | "frame" | "object" | "dialog", + ) => true, + (document::XHTML_NS, "audio" | "video") => element.has_attribute("controls"), + (document::XHTML_NS, "summary") => { + runtime + .dom_host() + .parent_node(handle) + .is_some_and(|parent| { + super::details_dialog::main_summary_child(runtime, parent) == Some(handle) + }) + } + _ => false, + }; + native_focus_behavior + || (element.namespace() == document::XHTML_NS + && contenteditable_editing_host(runtime, handle) == Some(handle)) +} + +fn svg_element_is_non_renderable(element: &Element) -> bool { + // Only directly renderable SVG elements can receive focus. Definitions, + // effects, animation and unknown elements cannot opt in with display or + // tabindex. Source elements are not shadow-tree instances. + element.namespace() == document::SVG_NS + && !matches!( + element.local_name(), + "a" | "circle" + | "ellipse" + | "foreignObject" + | "g" + | "image" + | "line" + | "path" + | "polygon" + | "polyline" + | "rect" + | "svg" + | "switch" + | "text" + | "textPath" + | "tspan" + | "use" + ) +} + fn element_focus_is_suppressed(runtime: &JsContextHost, handle: DomHandle) -> bool { let visibility = style_property_value(runtime, handle, StyleMode::Computed, "visibility"); if matches!( @@ -169,6 +231,7 @@ fn element_focus_is_suppressed(runtime: &JsContextHost, handle: DomHandle) -> bo .and_then(Node::as_element) && (element.has_attribute("inert") || element.has_attribute("hidden") + || svg_element_is_non_renderable(element) || computed_display(runtime, candidate) == "none") { return true; @@ -1510,16 +1573,10 @@ fn is_interactive_sequential_focusable_descendant( runtime: &JsContextHost, handle: DomHandle, ) -> bool { - let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else { - return false; - }; - if is_disabled_form_control(runtime, handle) { + if !is_focusable(runtime, handle) { return false; } - let is_interactive_element = matches!( - element.local_name(), - "a" | "button" | "input" | "select" | "textarea" - ); + let is_interactive_element = has_default_focus_behavior(runtime, handle); let has_non_negative_tab_index = element_attribute(runtime, handle, "tabindex") .and_then(|value| parse_tab_index_attribute(&value)) .is_some_and(|value| value >= 0); @@ -1537,13 +1594,12 @@ fn default_sequential_tab_index(runtime: &JsContextHost, handle: DomHandle) -> i let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else { return -1; }; - if element.namespace() != "http://www.w3.org/1999/xhtml" { - return -1; - } - match element.local_name() { - "a" | "button" | "input" | "select" | "textarea" => 0, - _ if element_is_scrollable(runtime, handle) => 0, - _ => -1, + if (has_default_focus_behavior(runtime, handle) && !element.is_html_element("dialog")) + || element_is_scrollable(runtime, handle) + { + 0 + } else { + -1 } } diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/focus.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/focus.rs index 30e5da34227..08ebdd552c9 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_elements/focus.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/focus.rs @@ -1,5 +1,63 @@ use super::*; +#[test] +fn element_focusability_uses_parsed_tabindex_and_native_defaults() { + let mut vm = new_storage_test_vm("https://focusability.test/"); + assert_eq!( + vm.eval(include_str!( + "../../../../tests/fixtures/element-focusability.js" + )) + .expect("element focusability should be observable"), + "" + ); +} + +#[test] +fn foreign_element_focus_methods_validate_native_receivers_before_options() { + let mut vm = new_storage_test_vm("https://foreign-focus-receivers.test/"); + assert_eq!( + vm.eval(include_str!( + "../../../../tests/fixtures/foreign-focus-receivers.js" + )) + .expect("foreign focus methods should validate receivers"), + "" + ); +} + +#[test] +fn tab_navigation_uses_native_defaults_and_shared_integer_parsing() { + let mut vm = new_streamed_parser_test_vm( + "https://focusability-navigation.test/", + r##" + +
+
+
+ + + +"##, + ); + assert_eq!( + vm.eval(r#" +(() => { + const ids = ['start', 'link', 'summary', 'editing', 'svg-link', 'rect', 'math-link', 'row', 'end']; + const failures = []; + for (const reverse of [false, true]) { + const order = reverse ? ids.slice().reverse() : ids; + document.getElementById(order[0]).focus(); + for (const id of order.slice(1)) { + __moliDispatchTrustedKey('keydown', 'Tab', 'Tab', false, false, false, reverse); + if (document.activeElement.id !== id) failures.push(`${reverse}: ${document.activeElement.id} != ${id}`); + } + } + return failures.join(','); +})() +"#).expect("Tab navigation should share programmatic focus eligibility"), + "" + ); +} + #[test] fn post_parse_autofocus_uses_connection_order_after_reinsert() { let mut vm = new_storage_test_vm("https://autofocus-reinsert.test/"); diff --git a/moli-renderer-v8/tests/fixtures/element-focusability.js b/moli-renderer-v8/tests/fixtures/element-focusability.js new file mode 100644 index 00000000000..74690557f4c --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/element-focusability.js @@ -0,0 +1,111 @@ +(() => { + const root = document.documentElement || document.appendChild(document.createElement('html')); + const body = document.body || root.appendChild(document.createElement('body')); + const reset = body.appendChild(document.createElement('input')); + const failures = []; + const svgNS = 'http://www.w3.org/2000/svg'; + const mathNS = 'http://www.w3.org/1998/Math/MathML'; + function check(condition, description) { + if (!condition) failures.push(description); + } + function checkFocus(element, expected, description) { + reset.focus(); + element.focus({preventScroll: true}); + check((document.activeElement === element) === expected, description); + } + const tokens = [ + [null, -1, false], ['', -1, false], ['invalid', -1, false], + ['\u00a00', -1, false], ['\u000b0', -1, false], ['+ 1', -1, false], + ['2147483648', -1, false], ['-2147483649', -1, false], + ['99999999999999999999999', -1, false], + ['0', 0, true], ['-1', -1, true], ['+1tail', 1, true], + [' \t\n\r\f0tail', 0, true], + ['2147483647', 2147483647, true], ['-2147483648', -2147483648, true] + ]; + for (const [namespace, containerTag, tag] of [ + ['http://www.w3.org/1999/xhtml', 'div', 'div'], + [svgNS, 'svg', 'rect'], [mathNS, 'math', 'mrow'] + ]) { + const container = body.appendChild(document.createElementNS(namespace, containerTag)); + const element = container.appendChild(document.createElementNS(namespace, tag)); + for (const [value, tabIndex, focusable] of tokens) { + if (value === null) element.removeAttribute('tabindex'); + else element.setAttribute('tabindex', value); + check(element.tabIndex === tabIndex, `${tag} tabIndex ${JSON.stringify(value)}`); + checkFocus(element, focusable, `${tag} focus ${JSON.stringify(value)}`); + } + element.tabIndex = 0; + const events = []; + reset.focus(); + for (const type of ['focus', 'focusin', 'blur', 'focusout']) { + element.addEventListener(type, () => events.push(type)); + } + element.focus(); + check(element.matches(':focus'), `${tag} :focus after focus`); + element.blur(); + check(document.activeElement === body && !element.matches(':focus'), `${tag} blur`); + check(events.join(',') === 'focus,focusin,blur,focusout', `${tag} events: ${events}`); + container.remove(); + } + + const samples = body.appendChild(document.createElement('div')); + samples.innerHTML = ` + + + + + + + +
+
+ + + + `; + for (const id of ['link', 'button', 'object', 'audio', 'video', 'first-summary', 'editing', 'editing-nonlink', 'area', 'svg-link', 'math-link']) { + checkFocus(samples.querySelector(`#${id}`), true, `${id} default focus`); + } + for (const id of ['nonlink', 'hidden', 'disabled', 'audio-no-controls', 'video-no-controls', 'outside-summary', 'second-summary', 'unreferenced', 'svg-nonlink', 'math-nonlink']) { + checkFocus(samples.querySelector(`#${id}`), false, `${id} no default focus`); + } + check(samples.querySelector('#nonlink').tabIndex === 0, 'nonlink reflection is separate from focusability'); + for (const id of ['audio', 'video']) { + const media = samples.querySelector(`#${id}`); + media.removeAttribute('controls'); + checkFocus(media, false, `${id} controls removal`); + } + const first = samples.querySelector('#first-summary'); + const second = samples.querySelector('#second-summary'); + first.parentNode.insertBefore(second, first); + checkFocus(first, false, 'summary losing first position'); + checkFocus(second, true, 'summary gaining first position'); + const svgLink = samples.querySelector('#svg-link'); + svgLink.removeAttribute('href'); + svgLink.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#'); + checkFocus(svgLink, true, 'SVG xlink:href focus'); + samples.remove(); + + const svg = body.appendChild(document.createElementNS(svgNS, 'svg')); + for (const tag of ['clipPath', 'defs', 'desc', 'linearGradient', 'marker', 'mask', 'metadata', 'pattern', 'radialGradient', 'script', 'style', 'title', 'symbol', 'filter', 'stop', 'feGaussianBlur', 'animate', 'animateMotion', 'set', 'view', 'unknown', 'mesh']) { + const container = svg.appendChild(document.createElementNS(svgNS, tag)); + container.setAttribute('tabindex', '0'); + container.style.display = 'block'; + checkFocus(container, false, `${tag} is never directly rendered`); + const child = container.appendChild(document.createElementNS(svgNS, 'rect')); + child.setAttribute('tabindex', '0'); + checkFocus(child, false, `${tag} excludes SVG descendants`); + const foreign = container.appendChild(document.createElementNS(svgNS, 'foreignObject')); + const input = foreign.appendChild(document.createElement('input')); + checkFocus(input, false, `${tag} excludes HTML descendants`); + container.remove(); + } + const rect = svg.appendChild(document.createElementNS(svgNS, 'rect')); + rect.tabIndex = 0; + checkFocus(rect, true, 'renderable SVG descendant'); + const fakeInput = svg.appendChild(document.createElementNS(svgNS, 'input')); + checkFocus(fakeInput, false, 'foreign input does not inherit HTML focus behavior'); + svg.remove(); + reset.remove(); + return failures; +})() diff --git a/moli-renderer-v8/tests/fixtures/foreign-focus-receivers.js b/moli-renderer-v8/tests/fixtures/foreign-focus-receivers.js new file mode 100644 index 00000000000..8117600f7fa --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/foreign-focus-receivers.js @@ -0,0 +1,61 @@ +(() => { + const failures = []; + const namespaces = ['http://www.w3.org/1999/xhtml', 'http://www.w3.org/2000/svg', 'http://www.w3.org/1998/Math/MathML']; + const tags = ['div', 'rect', 'mrow']; + const names = ['HTMLElement', 'SVGElement', 'MathMLElement']; + const root = document.documentElement || document.appendChild(document.createElement('html')); + const body = document.body || root.appendChild(document.createElement('body')); + const frame = body.appendChild(document.createElement('iframe')); + const child = frame.contentWindow; + let reads = 0; + let traps = 0; + const options = {get preventScroll() { reads++; return true; }}; + for (const realm of [window, child]) { + for (let owner = 0; owner < names.length; ++owner) { + const proto = realm[names[owner]].prototype; + const real = document.createElementNS(namespaces[owner], tags[owner]); + const revoked = Proxy.revocable(real, {}); + revoked.revoke(); + const receivers = [null, {}, proto, Object.create(proto), Object.create(real), + new Proxy(real, {get() { traps++; throw new Error('proxy trap'); }}), revoked.proxy]; + for (let other = 0; other < names.length; ++other) { + if (other !== owner) receivers.push(document.createElementNS(namespaces[other], tags[other])); + } + for (const name of ['focus', 'blur']) { + const descriptor = Object.getOwnPropertyDescriptor(proto, name); + if (!descriptor || typeof descriptor.value !== 'function') { + failures.push(`${names[owner]}.${name} missing`); + continue; + } + const method = descriptor.value; + if (method.length !== 0 || !descriptor.enumerable || !descriptor.writable || !descriptor.configurable) { + failures.push(`${names[owner]}.${name} descriptor`); + } + for (const receiver of receivers) { + const before = reads; + try { Reflect.apply(method, receiver, [options]); failures.push(`${names[owner]}.${name} accepted invalid receiver`); } + catch (error) { + if (!(error instanceof realm.TypeError)) failures.push(`${names[owner]}.${name} wrong error realm`); + } + if (reads !== before) failures.push(`${names[owner]}.${name} converted before receiver check`); + } + for (const documentInRealm of [document, child.document]) { + const valid = documentInRealm.createElementNS(namespaces[owner], tags[owner]); + Object.setPrototypeOf(valid, null); + const before = reads; + try { Reflect.apply(method, valid, [options]); } + catch (error) { failures.push(`${names[owner]}.${name} rejected genuine object: ${error.name}`); } + if (reads !== before + (name === 'focus' ? 1 : 0)) failures.push(`${names[owner]}.${name} options reads`); + } + if (name === 'focus') { + const sentinel = {}; + try { method.call(real, {get preventScroll() { throw sentinel; }}); failures.push('swallowed options exception'); } + catch (error) { if (error !== sentinel) failures.push('replaced options exception'); } + } + } + } + } + if (traps !== 0) failures.push(`receiver validation invoked ${traps} proxy traps`); + frame.remove(); + return failures; +})()