The headless browser for AI agents and web scraping
fix(js): give HTMLSlotElement its own class and expose assignedNodes/assignedElements
michabbb88d2174eaf65
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 8a77042b..86011b75 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -6453,6 +6453,12 @@ function _elementClassFor(nid) {}if (tag === "FORM" && globalThis.HTMLFormElement) return globalThis.HTMLFormElement;if (tag === "TEXTAREA" && globalThis.HTMLTextAreaElement) return globalThis.HTMLTextAreaElement;+ // Only HTML slots take part in slot assignment; a foreign-namespace "SLOT"+ // (createElementNS + cloneNode lands here) stays a plain Element.+ if (tag === "SLOT" && globalThis.HTMLSlotElement+ && _domParse("namespace_uri", nid) === "http://www.w3.org/1999/xhtml") {+ return globalThis.HTMLSlotElement;+ }if (tag === "IMG") return HTMLImageElement;if (tag === "CANVAS" && globalThis.HTMLCanvasElement) return globalThis.HTMLCanvasElement;if (tag === "AUDIO") return HTMLAudioElement;@@ -6473,6 +6479,7 @@ function _elementClassForKnownName(namespace, qualifiedName) {const tag = localName.toUpperCase();if (tag === "FORM" && globalThis.HTMLFormElement) return globalThis.HTMLFormElement;if (tag === "TEXTAREA" && globalThis.HTMLTextAreaElement) return globalThis.HTMLTextAreaElement;+ if (tag === "SLOT" && globalThis.HTMLSlotElement) return globalThis.HTMLSlotElement;if (tag === "IMG") return HTMLImageElement;if (tag === "CANVAS" && globalThis.HTMLCanvasElement) return globalThis.HTMLCanvasElement;if (tag === "AUDIO") return HTMLAudioElement;@@ -11655,7 +11662,54 @@ globalThis.HTMLLIElement = Element;globalThis.HTMLPreElement = Element;globalThis.HTMLHeadingElement = Element;globalThis.HTMLTemplateElement = Element;-globalThis.HTMLSlotElement = Element;+// <slot> needs its own brand: with `HTMLSlotElement = Element` every element+// was an instance, but assignedElements() did not exist, so the common+// `el instanceof HTMLSlotElement && el.assignedElements()` guard (Swiper's+// getChildren helper, seen on idealo's search result slider) threw a+// TypeError on a plain <div>.+//+// Direct assignment comes from the native DomTree::assigned_nodes (the same+// named-slot algorithm the renderer uses: only HTML slots inside a shadow+// tree, first same-name slot in tree order wins, elements match on their+// `slot` attribute, text nodes go to the default slot). `flatten` walks+// nested slots with a work list and falls back to a slot's own slottable+// children. Limits: manual slot assignment (`slotAssignment: "manual"`,+// `slot.assign()`) assigns nothing (fallback only); no `slotchange` events.+function _slotDirectAssigned(slot) {+ const ids = _domParse("assigned_nodes", slot._nid);+ if (ids === null || ids === undefined) return null; // not an HTML slot in a shadow tree+ const root = slot.getRootNode();+ if (root instanceof ShadowRoot && root.slotAssignment === 'manual') return [];+ return ids.map(_wrap).filter(Boolean);+}+function _slotFallbackChildren(slot) {+ const out = [];+ for (let child = slot.firstChild; child; child = child.nextSibling) {+ if (child.nodeType === 1 || child.nodeType === 3) out.push(child);+ }+ return out;+}+function _slotAssignedNodes(slot, flatten) {+ const assigned = _slotDirectAssigned(slot);+ if (assigned === null) return [];+ if (!flatten) return assigned;+ const out = [];+ const work = (assigned.length ? assigned : _slotFallbackChildren(slot)).reverse();+ while (work.length) {+ const node = work.pop();+ const nested = node.nodeType === 1 ? _slotDirectAssigned(node) : null;+ if (nested === null) { out.push(node); continue; }+ const inner = nested.length ? nested : _slotFallbackChildren(node);+ for (let i = inner.length - 1; i >= 0; i--) work.push(inner[i]);+ }+ return out;+}+globalThis.HTMLSlotElement = class HTMLSlotElement extends Element {+ get name() { return this.getAttribute('name') || ''; }+ set name(v) { this.setAttribute('name', String(v)); }+ assignedNodes(options) { return _slotAssignedNodes(this, !!(options && options.flatten)); }+ assignedElements(options) { return this.assignedNodes(options).filter(n => n.nodeType === 1); }+};globalThis.HTMLOptionElement = Element;globalThis.HTMLDataListElement = Element;globalThis.HTMLFieldSetElement = Element;diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex da58ec50..57311b11 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -1587,6 +1587,20 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->.collect();serde_json::to_string(&ids).unwrap_or("[]".into())}+ // Nodes directly assigned to an HTML <slot> (named slot assignment; the+ // first same-name slot in the shadow tree wins). `null` when the node is+ // not an HTML slot inside a shadow tree, so JS can tell "no slot" from+ // "slot without assignments" and fall back to the slot's own children.+ "assigned_nodes" => {+ let nid = arg1.parse::<u32>().unwrap_or(0);+ match dom.assigned_nodes(NodeId::new(nid)) {+ Some(ids) => {+ let ids: Vec<i32> = ids.iter().map(|id| id.index() as i32).collect();+ serde_json::to_string(&ids).unwrap_or("[]".into())+ }+ None => "null".into(),+ }+ }"tag_name" => {let nid = arg1.parse::<u32>().unwrap_or(0);let name = domdiff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 1211d43e..7f7f6a0e 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -5299,6 +5299,140 @@ mod tests {assert_eq!(result, serde_json::json!([true, true, true, 1, "ready"]));}+ #[test]+ fn slot_element_has_own_brand_and_named_assignment() {+ // Regression for the idealo search result slider: Swiper's getChildren+ // helper guards with `instanceof HTMLSlotElement` before calling+ // assignedElements(). With `HTMLSlotElement = Element` the guard matched+ // a plain <div> and the missing method threw a TypeError.+ let mut rt = setup_runtime(+ r#"<html><body><div id="plain"><i></i></div><slot id="light"><i></i></slot></body></html>"#,+ );+ let result = rt+ .evaluate(+ r##"+ const tags = nodes => nodes.map(n => n.nodeType === 3 ? "#text" : n.tagName).join(",");+ const children = el => {+ const out = [...el.children];+ if (window.HTMLSlotElement && el instanceof HTMLSlotElement) {+ out.push(...el.assignedElements());+ }+ return out;+ };+ const plain = document.getElementById("plain");+ const light = document.getElementById("light");+ const created = document.createElement("slot");++ const host = document.createElement("x-host");+ document.body.appendChild(host);+ host.innerHTML = '<b slot="title">T</b>text<span>S</span><em slot="missing">M</em>';+ const root = host.attachShadow({ mode: "open" });+ root.innerHTML = '<slot name="title"></slot><div><slot></slot></div>'+ + '<slot name="title"></slot><slot name="empty"><u>fallback</u></slot>';+ const title = root.childNodes[0];+ const dflt = root.childNodes[1].firstChild;+ const dupe = root.childNodes[2];+ const empty = root.childNodes[3];++ const outer = document.createElement("x-outer");+ document.body.appendChild(outer);+ outer.innerHTML = "<p>deep</p>";+ const outerRoot = outer.attachShadow({ mode: "open" });+ outerRoot.innerHTML = "<x-inner><slot></slot></x-inner>";+ const inner = outerRoot.firstChild;+ const innerRoot = inner.attachShadow({ mode: "open" });+ innerRoot.innerHTML = '<slot name="unused"></slot><slot></slot>';+ const innerDefault = innerRoot.childNodes[1];++ created.name = "n1";++ // Later same-name slot: no direct assignment, but its own+ // fallback children with flatten (comments are not slottable).+ const dupHost = document.createElement("x-dup");+ document.body.appendChild(dupHost);+ dupHost.innerHTML = '<b slot="title">T</b>';+ const dupRoot = dupHost.attachShadow({ mode: "open" });+ dupRoot.innerHTML = '<slot name="title"></slot><slot name="title"><i>fb</i>text<!--c--></slot>';+ const dupSlot = dupRoot.childNodes[1];++ // Manual slot assignment is not implemented: nothing assigned, fallback only.+ const manHost = document.createElement("x-man");+ document.body.appendChild(manHost);+ manHost.innerHTML = "<b>light</b>";+ const manRoot = manHost.attachShadow({ mode: "open", slotAssignment: "manual" });+ manRoot.innerHTML = "<slot><u>fb</u></slot>";+ const manSlot = manRoot.firstChild;++ // Foreign-namespace "SLOT" (also via cloneNode) is no HTML slot+ // and must not steal the assignment of a following real slot.+ const foreign = document.createElementNS("urn:example", "SLOT");+ const foreignClone = foreign.cloneNode();+ const fHost = document.createElement("x-foreign");+ document.body.appendChild(fHost);+ fHost.innerHTML = "<b>light</b>";+ const fRoot = fHost.attachShadow({ mode: "open" });+ fRoot.appendChild(foreignClone);+ const realSlot = document.createElement("slot");+ fRoot.appendChild(realSlot);++ // Deep shadow tree: assignment must not depend on JS recursion depth.+ const deepHost = document.createElement("x-deep");+ document.body.appendChild(deepHost);+ deepHost.innerHTML = "<b>deep-light</b>";+ const deepRoot = deepHost.attachShadow({ mode: "open" });+ let cursor = deepRoot;+ for (let i = 0; i < 20000; i++) {+ const div = document.createElement("div");+ cursor.appendChild(div);+ cursor = div;+ }+ const deepSlot = document.createElement("slot");+ cursor.appendChild(deepSlot);++ return [+ plain instanceof HTMLSlotElement,+ light instanceof HTMLSlotElement,+ created instanceof HTMLSlotElement,+ light instanceof HTMLElement && light instanceof Element,+ typeof plain.assignedElements,+ light.assignedNodes().length + light.assignedElements().length+ + light.assignedNodes({ flatten: true }).length,+ children(plain).length,+ children(light).length,+ created.name + "|" + created.getAttribute("name") + "|" + title.name + "|" + dflt.name,+ tags(title.assignedElements()),+ tags(dflt.assignedNodes()),+ tags(dflt.assignedElements()),+ dupe.assignedNodes().length,+ empty.assignedNodes().length,+ tags(empty.assignedNodes({ flatten: true })),+ tags(innerDefault.assignedNodes()),+ tags(innerDefault.assignedNodes({ flatten: true })),+ tags(children(dflt)),+ dupSlot.assignedNodes().length,+ tags(dupSlot.assignedNodes({ flatten: true })),+ tags(dupSlot.assignedElements({ flatten: true })),+ manSlot.assignedNodes().length,+ tags(manSlot.assignedNodes({ flatten: true })),+ foreign instanceof HTMLSlotElement,+ foreignClone instanceof HTMLSlotElement,+ typeof foreignClone.assignedNodes,+ tags(realSlot.assignedNodes()),+ tags(deepSlot.assignedNodes()),+ ];+ "##,+ )+ .unwrap();+ assert_eq!(+ result,+ serde_json::json!([+ false, true, true, true, "undefined", 0, 1, 1,+ "n1|n1|title|", "B", "#text,SPAN", "SPAN", 0, 0, "U", "SLOT", "P", "SPAN",+ 0, "I,#text", "I", 0, "U", false, false, "undefined", "B", "B"+ ])+ );+ }+#[test]fn shadow_root_children_expose_parent_siblings_and_composed_root() {let mut rt = setup_runtime("<html><body></body></html>");