Skip to content

Lightpanda: the headless browser designed for AI and automation

mem: Switch Node's _type to a bare tag

Karl Seguin7db42891a7f4
diff --git a/src/browser/Factory.zig b/src/browser/Factory.zig
index b400aff4d..151cab9d7 100644
--- a/src/browser/Factory.zig
+++ b/src/browser/Factory.zig
@@ -97,7 +97,7 @@ pub fn uiEvent(_: *const Factory, arena: *lp.Arena, typ: String, child: anytype)
// Special case: Event has a _type_string field, so we need manual setup
const event_ptr = chain.get(0);
event_ptr.* = try eventInit(arena, typ, chain.get(1));
- chain.setMiddle(1, UIEvent.Type);
+ chain.setMiddle(1);
chain.setLeaf(2, child);
return chain.get(2);
@@ -111,7 +111,7 @@ pub fn mouseEvent(_: *const Factory, arena: *lp.Arena, typ: String, mouse: Mouse
// Special case: Event has a _type_string field, so we need manual setup
const event_ptr = chain.get(0);
event_ptr.* = try eventInit(arena, typ, chain.get(1));
- chain.setMiddle(1, UIEvent.Type);
+ chain.setMiddle(1);
// Set MouseEvent with all its fields
const mouse_ptr = chain.get(2);
@@ -178,31 +178,20 @@ fn PrototypeChain(comptime types: []const type) type {
ptr.* = value;
}
- fn setRoot(self: *const Self, comptime T: type) void {
+ fn setRoot(self: *const Self) void {
const ptr = self.get(0);
- ptr.* = .{ ._type = unionInit(T, self.get(1)) };
+ ptr.* = .{ ._type = typeInit(types[0], self.get(1)) };
}
- fn setMiddle(self: *const Self, comptime index: usize, comptime T: type) void {
+ fn setMiddle(self: *const Self, comptime index: usize) void {
assert(index >= 1);
assert(index < types.len);
const ptr = self.get(index);
ptr.* = if (comptime @hasField(types[index], "_proto"))
- .{ ._proto = undefined, ._type = unionInit(T, self.get(index + 1)) }
+ .{ ._proto = undefined, ._type = typeInit(types[index], self.get(index + 1)) }
else
- .{ ._type = unionInit(T, self.get(index + 1)) };
- setProto(ptr, self.get(index - 1));
- }
-
- fn setMiddleWithValue(self: *const Self, comptime index: usize, comptime T: type, value: anytype) void {
- assert(index >= 1);
-
- const ptr = self.get(index);
- ptr.* = if (comptime @hasField(types[index], "_proto"))
- .{ ._proto = undefined, ._type = unionInit(T, value) }
- else
- .{ ._type = unionInit(T, value) };
+ .{ ._type = typeInit(types[index], self.get(index + 1)) };
setProto(ptr, self.get(index - 1));
}
@@ -221,12 +210,10 @@ fn AutoPrototypeChain(comptime types: []const type) type {
fn create(allocator: std.mem.Allocator, leaf_value: anytype) !*@TypeOf(leaf_value) {
const chain = try PrototypeChain(types).allocate(allocator);
- const RootType = types[0];
- chain.setRoot(RootType.Type);
+ chain.setRoot();
inline for (1..types.len - 1) |i| {
- const MiddleType = types[i];
- chain.setMiddle(i, MiddleType.Type);
+ chain.setMiddle(i);
}
chain.setLeaf(types.len - 1, leaf_value);
@@ -327,8 +314,8 @@ pub fn cdataNode(self: *Factory, cd: Node.CData, leaf: anytype) !*Node.CData {
comptime assert(types[0] == EventTarget and types[1] == Node and types[2] == Node.CData);
const chain = try PrototypeChain(types).allocate(self._slab.allocator());
- chain.setRoot(EventTarget.Type);
- chain.setMiddle(1, Node.Type);
+ chain.setRoot();
+ chain.setMiddle(1);
const cd_ptr = chain.get(2);
cd_ptr.* = cd;
@@ -480,7 +467,7 @@ pub fn svgElement(self: *Factory, tag_name: []const u8, child: anytype) !*@TypeO
const types = comptime svgPrototypeTypes(@TypeOf(child));
const chain = try PrototypeChain(types).allocate(self._slab.allocator());
- chain.setRoot(EventTarget.Type);
+ chain.setRoot();
inline for (1..types.len - 1) |i| {
const T = types[i];
if (T == Element.Svg) {
@@ -491,7 +478,7 @@ pub fn svgElement(self: *Factory, tag_name: []const u8, child: anytype) !*@TypeO
};
setProto(svg_ptr, chain.get(i - 1));
} else {
- chain.setMiddle(i, T.Type);
+ chain.setMiddle(i);
}
}
chain.setLeaf(types.len - 1, child);
@@ -598,6 +585,25 @@ fn unionInit(comptime T: type, value: anytype) T {
return @unionInit(T, field_name, value);
}
+// Initializes Parent._type for the chain member laid out after Parent. For a
+// tagged-union _type the member's pointer is the payload; for a bare-tag _type
+// (e.g. Node, CData) the member is reached by arithmetic and only its tag is
+// stored.
+fn typeInit(comptime Parent: type, value: anytype) Parent.Type {
+ if (comptime @typeInfo(Parent.Type) == .@"enum") {
+ return comptime subtypeTag(Parent, reflect.Struct(@TypeOf(value)));
+ }
+ return unionInit(Parent.Type, value);
+}
+
+fn subtypeTag(comptime Parent: type, comptime V: type) Parent.Type {
+ for (@typeInfo(Parent.Type).@"enum".fields) |f| {
+ const tag: Parent.Type = @enumFromInt(f.value);
+ if (Parent.Subtype(tag) == V) return tag;
+ }
+ @compileError(@typeName(V) ++ " is not a subtype of " ++ @typeName(Parent));
+}
+
// There can be friction between comptime and runtime. Comptime has to
// account for all possible types, even if some runtime flow makes certain
// cases impossible. At runtime, we always call `unionFieldName` with the
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zig
index 542f9a4cf..54b347326 100644
--- a/src/browser/Frame.zig
+++ b/src/browser/Frame.zig
@@ -2001,9 +2001,10 @@ fn getElementIdMap(frame: *Frame, node: *Node) ElementIdMaps {
const parent = current._parent orelse {
if (current._type == .document) {
+ const doc = current.subtype(Document);
return .{
- .lookup = &current._type.document._elements_by_id,
- .removed_ids = &current._type.document._removed_ids,
+ .lookup = &doc._elements_by_id,
+ .removed_ids = &doc._removed_ids,
};
}
// Detached nodes should not have IDs registered
@@ -2054,7 +2055,7 @@ pub fn getElementByIdFromNode(self: *Frame, node: *Node, id: []const u8) ?*Eleme
// shadow DOM. Walk to the root once and consult the matching map.
const root = node.getRootNode(.{});
if (root._type == .document) {
- return root._type.document.getElementById(id, self);
+ return root.subtype(Document).getElementById(id, self);
}
if (root.is(ShadowRoot)) |shadow_root| {
return shadow_root.getElementById(id, self);
diff --git a/src/browser/dump.zig b/src/browser/dump.zig
index 9d5247745..c2db77472 100644
--- a/src/browser/dump.zig
+++ b/src/browser/dump.zig
@@ -79,7 +79,8 @@ pub fn deep(node: *Node, opts: Opts, writer: *std.Io.Writer, frame: *Frame) erro
fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Writer, frame: *Frame) error{WriteFailed}!void {
switch (node._type) {
- .cdata => |cd| {
+ .cdata => {
+ const cd = node.subtype(Node.CData);
if (node.is(Node.CData.Comment)) |_| {
try writer.writeAll("<!--");
try writer.writeAll(cd.getData().str());
@@ -98,7 +99,8 @@ fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Wri
}
}
},
- .element => |el| {
+ .element => {
+ const el = node.subtype(Node.Element);
if (shouldStripElement(el, opts, frame)) {
return;
}
@@ -164,7 +166,8 @@ fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Wri
}
},
.document => try children(node, opts, writer, frame),
- .document_type => |dt| {
+ .document_type => {
+ const dt = node.subtype(Node.DocumentType);
try writer.writeAll("<!DOCTYPE ");
try writer.writeAll(dt.getName());
@@ -207,7 +210,7 @@ pub fn toJSON(node: *Node, writer: *std.json.Stringify) !void {
try writer.beginObject();
try writer.objectField("type");
- switch (node.type) {
+ switch (node._type) {
.cdata => {
try writer.write("cdata");
},
@@ -217,7 +220,8 @@ pub fn toJSON(node: *Node, writer: *std.json.Stringify) !void {
.document_type => {
try writer.write("document_type");
},
- .element => |*el| {
+ .element => {
+ const el = node.subtype(Node.Element);
try writer.write("element");
try writer.objectField("tag");
try writer.write(el.tagName());
diff --git a/src/browser/js/Caller.zig b/src/browser/js/Caller.zig
index 9a993051a..8a1636f28 100644
--- a/src/browser/js/Caller.zig
+++ b/src/browser/js/Caller.zig
@@ -530,7 +530,7 @@ fn errorLocal(comptime T: type, local: *const Local, info: anytype) Local {
const node = protoNode(T, instance);
const doc: *Document = node.ownerDocument(frame) orelse switch (node._type) {
- .document => |d| d,
+ .document => node.subtype(Document),
else => return local.*,
};
const doc_frame = doc._frame orelse return local.*;
diff --git a/src/browser/markdown.zig b/src/browser/markdown.zig
index 86cdd45f4..3606a4d6a 100644
--- a/src/browser/markdown.zig
+++ b/src/browser/markdown.zig
@@ -206,12 +206,12 @@ const Context = struct {
.document, .document_fragment => {
try self.renderChildren(node);
},
- .element => |el| {
- try self.renderElement(el);
+ .element => {
+ try self.renderElement(node.subtype(Node.Element));
},
- .cdata => |cd| {
+ .cdata => {
if (node.is(Node.CData.Text)) |_| {
- var text = cd.getData().str();
+ var text = node.subtype(Node.CData).getData().str();
if (self.state.pre_node) |pre| {
if (node.parentNode() == pre and node.nextSibling() == null) {
text = std.mem.trimEnd(u8, text, " \t\r\n");
diff --git a/src/browser/webapi/CData.zig b/src/browser/webapi/CData.zig
index ea160045c..674472142 100644
--- a/src/browser/webapi/CData.zig
+++ b/src/browser/webapi/CData.zig
@@ -69,7 +69,8 @@ fn tagOf(comptime T: type) Type {
@compileError(@typeName(T) ++ " is not a CData subtype");
}
-pub fn subtype(self: *CData, comptime T: type) *T {
+// Takes a const cdata but returns a mutable subtype; see Node.subtype.
+pub fn subtype(self: *const CData, comptime T: type) *T {
const offset = comptime Factory.chainOffsetOf(T, T) - Factory.chainOffsetOf(T, CData);
const sub: *T = @ptrFromInt(@intFromPtr(self) + offset);
if (comptime lp.IS_DEBUG) {
@@ -327,7 +328,7 @@ pub fn format(self: *const CData, writer: *std.Io.Writer) !void {
.text => writer.print("<text>{f}</text>", .{self._data}),
.comment => writer.print("<!-- {f} -->", .{self._data}),
.cdata_section => writer.print("<![CDATA[{f}]]>", .{self._data}),
- .processing_instruction => writer.print("<?{s} {f}?>", .{ @constCast(self).subtype(ProcessingInstruction)._target, self._data }),
+ .processing_instruction => writer.print("<?{s} {f}?>", .{ self.subtype(ProcessingInstruction)._target, self._data }),
};
}
@@ -342,8 +343,8 @@ pub fn isEqualNode(self: *const CData, other: *const CData) bool {
if (self._type == .processing_instruction) {
@branchHint(.unlikely);
- const self_target = @constCast(self).subtype(ProcessingInstruction)._target;
- const other_target = @constCast(other).subtype(ProcessingInstruction)._target;
+ const self_target = self.subtype(ProcessingInstruction)._target;
+ const other_target = other.subtype(ProcessingInstruction)._target;
if (std.mem.eql(u8, self_target, other_target) == false) {
return false;
}
diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zig
index b3084f635..78e2a3f83 100644
--- a/src/browser/webapi/Document.zig
+++ b/src/browser/webapi/Document.zig
@@ -1298,7 +1298,7 @@ fn validateDocumentNodes(self: *Document, nodes: []const Node.NodeOrText, compti
}
has_doctype = true;
},
- .cdata => |cd| switch (cd._type) {
+ .cdata => switch (frag_child.subtype(Node.CData)._type) {
.comment, .processing_instruction => {}, // Allowed
.text, .cdata_section => return error.HierarchyError, // Not allowed in Document
},
@@ -1324,7 +1324,7 @@ fn validateDocumentNodes(self: *Document, nodes: []const Node.NodeOrText, compti
}
has_doctype = true;
},
- .cdata => |cd| switch (cd._type) {
+ .cdata => switch (child.subtype(Node.CData)._type) {
.comment, .processing_instruction => {}, // Allowed
.text, .cdata_section => return error.HierarchyError, // Not allowed in Document
},
diff --git a/src/browser/webapi/Event.zig b/src/browser/webapi/Event.zig
index 13aa08661..6076e91c8 100644
--- a/src/browser/webapi/Event.zig
+++ b/src/browser/webapi/Event.zig
@@ -349,8 +349,9 @@ pub fn composedPath(self: *Event, exec: *Execution) ![]const *EventTarget {
// Check if this node is a shadow root
if (n._type == .document_fragment) {
- if (n._type.document_fragment._type == .shadow_root) {
- const shadow = n._type.document_fragment._type.shadow_root;
+ const df = n.subtype(Node.DocumentFragment);
+ if (df._type == .shadow_root) {
+ const shadow = df._type.shadow_root;
if (!self._composed and n == target_root) {
stopped_at_shadow_boundary = true;
diff --git a/src/browser/webapi/IntersectionObserver.zig b/src/browser/webapi/IntersectionObserver.zig
index de6e7c624..37fe27b22 100644
--- a/src/browser/webapi/IntersectionObserver.zig
+++ b/src/browser/webapi/IntersectionObserver.zig
@@ -83,7 +83,7 @@ pub fn init(callback: js.Function.Global, options: ?ObserverInit, frame: *Frame)
const root: ?*Element = blk: {
const root_opt = opts.root orelse break :blk null;
switch (root_opt._type) {
- .element => |el| break :blk el,
+ .element => break :blk root_opt.subtype(Element),
.document => {
// not strictly correct, `null` means the viewport, not the
// entire document, but since we don't render anything, this
diff --git a/src/browser/webapi/Node.zig b/src/browser/webapi/Node.zig
index 4d41b2550..cb6f038d7 100644
--- a/src/browser/webapi/Node.zig
+++ b/src/browser/webapi/Node.zig
@@ -23,7 +23,6 @@ const js = @import("../js/js.zig");
const Frame = @import("../Frame.zig");
const URL = @import("../URL.zig");
const Factory = @import("../Factory.zig");
-const reflect = @import("../reflect.zig");
const EventTarget = @import("EventTarget.zig");
const collections = @import("collections.zig");
@@ -60,15 +59,38 @@ _proto_canary: if (lp.IS_DEBUG) *EventTarget else void = undefined,
// Lookup for nodes that have a different owner document than frame.document
pub const OwnerDocumentLookup = std.AutoHashMapUnmanaged(*Node, *Document);
-pub const Type = union(enum) {
- cdata: *CData,
- element: *Element,
- document: *Document,
- document_type: *DocumentType,
- attribute: *Element.Attribute,
- document_fragment: *DocumentFragment,
+pub const Type = enum(u8) {
+ cdata,
+ element,
+ document,
+ document_type,
+ attribute,
+ document_fragment,
};
+pub fn Subtype(comptime tag: Type) type {
+ return switch (tag) {
+ .cdata => CData,
+ .element => Element,
+ .document => Document,
+ .document_type => DocumentType,
+ .attribute => Element.Attribute,
+ .document_fragment => DocumentFragment,
+ };
+}
+
+pub fn subtype(self: *const Node, comptime T: type) *T {
+ const offset = comptime Factory.chainOffsetOf(T, T) - Factory.chainOffsetOf(T, Node);
+ const sub: *T = @ptrFromInt(@intFromPtr(self) + offset);
+ if (comptime lp.IS_DEBUG) {
+ // This pointer dance only works because the factory allocates the chain
+ // in a contiguous block of memory. In debug, we assert this holds via
+ // the _proto_canary back pointer.
+ std.debug.assert(Factory.protoOf(sub) == self);
+ }
+ return sub;
+}
+
pub fn asEventTarget(self: *Node) *EventTarget {
return Factory.protoOf(self);
}
@@ -83,7 +105,8 @@ pub fn as(self: *Node, comptime T: type) *T {
pub fn is(self: *Node, comptime T: type) ?*T {
const type_name = @typeName(T);
switch (self._type) {
- .element => |el| {
+ .element => {
+ const el = self.subtype(Element);
if (T == Element) {
return el;
}
@@ -91,7 +114,8 @@ pub fn is(self: *Node, comptime T: type) ?*T {
return el.is(T);
}
},
- .cdata => |cd| {
+ .cdata => {
+ const cd = self.subtype(CData);
if (T == CData) {
return cd;
}
@@ -99,12 +123,13 @@ pub fn is(self: *Node, comptime T: type) ?*T {
return cd.is(T);
}
},
- .attribute => |attr| {
+ .attribute => {
if (T == Element.Attribute) {
- return attr;
+ return self.subtype(Element.Attribute);
}
},
- .document => |doc| {
+ .document => {
+ const doc = self.subtype(Document);
if (T == Document) {
return doc;
}
@@ -112,12 +137,13 @@ pub fn is(self: *Node, comptime T: type) ?*T {
return doc.is(T);
}
},
- .document_type => |dt| {
+ .document_type => {
if (T == DocumentType) {
- return dt;
+ return self.subtype(DocumentType);
}
},
- .document_fragment => |doc| {
+ .document_fragment => {
+ const doc = self.subtype(DocumentFragment);
if (T == DocumentFragment) {
return doc;
}
@@ -259,7 +285,8 @@ fn ensurePreInsertValidity(parent: *Node, node: *Node, child: ?*Node, comptime m
switch (node._type) {
.document, .attribute => return error.HierarchyError,
- .cdata => |cd| {
+ .cdata => {
+ const cd = node.subtype(CData);
if ((cd._type == .text or cd._type == .cdata_section) and parent._type == .document) {
// A Text node (CDATASection included) cannot be a child of a
// document.
@@ -285,7 +312,8 @@ fn ensurePreInsertValidity(parent: *Node, node: *Node, child: ?*Node, comptime m
while (it.next()) |frag_child| {
switch (frag_child._type) {
.element => element_count += 1,
- .cdata => |cd| {
+ .cdata => {
+ const cd = frag_child.subtype(CData);
// A Text node (CDATASection included) cannot be a
// child of a document.
if (cd._type == .text or cd._type == .cdata_section) {
@@ -413,10 +441,10 @@ pub fn getTextContent(self: *Node, writer: *std.Io.Writer) error{WriteFailed}!vo
try child.getTextContent(writer);
}
},
- .cdata => |c| try writer.writeAll(c._data.str()),
+ .cdata => try writer.writeAll(self.subtype(CData)._data.str()),
.document => {},
.document_type => {},
- .attribute => |attr| try writer.writeAll(attr._value.str()),
+ .attribute => try writer.writeAll(self.subtype(Element.Attribute)._value.str()),
}
}
@@ -456,39 +484,47 @@ pub fn childTextContentLen(self: *Node) usize {
pub fn setTextContent(self: *Node, data: []const u8, frame: *Frame) !void {
switch (self._type) {
- .element => |el| {
+ .element => {
+ const el = self.subtype(Element);
if (data.len == 0) {
return el.replaceChildren(&.{}, frame);
}
return el.replaceChildren(&.{.{ .text = data }}, frame);
},
// Per spec, setting textContent on CharacterData runs replaceData(0, length, value)
- .cdata => |c| try c.replaceData(0, c.getLength(), data, frame),
+ .cdata => {
+ const c = self.subtype(CData);
+ try c.replaceData(0, c.getLength(), data, frame);
+ },
.document => {},
.document_type => {},
- .document_fragment => |frag| {
+ .document_fragment => {
+ const frag = self.subtype(DocumentFragment);
if (data.len == 0) {
return frag.replaceChildren(&.{}, frame);
}
return frag.replaceChildren(&.{.{ .text = data }}, frame);
},
- .attribute => |attr| return attr.setValue(.wrap(data), frame),
+ .attribute => return self.subtype(Element.Attribute).setValue(.wrap(data), frame),
}
}
pub fn getNodeName(self: *const Node, buf: []u8) []const u8 {
return switch (self._type) {
- .element => |el| el.getTagNameSpec(buf),
- .cdata => |cd| switch (cd._type) {
- .text => "#text",
- .cdata_section => "#cdata-section",
- .comment => "#comment",
- .processing_instruction => cd.subtype(CData.ProcessingInstruction)._target,
+ .element => self.subtype(Element).getTagNameSpec(buf),
+ .cdata => {
+ const cd = self.subtype(CData);
+ return switch (cd._type) {
+ .text => "#text",
+ .cdata_section => "#cdata-section",
+ .comment => "#comment",
+ .processing_instruction => cd.subtype(CData.ProcessingInstruction)._target,
+ };
},
.document => "#document",
- .document_type => |dt| dt.getName(),
+ .document_type => self.subtype(DocumentType).getName(),
.document_fragment => "#document-fragment",
- .attribute => |attr| attr._name.str(),
+ .attribute => self.subtype(Element.Attribute)._name.str(),
};
}
@@ -496,7 +532,7 @@ pub fn getNodeType(self: *const Node) u8 {
return switch (self._type) {
.element => 1,
.attribute => 2,
- .cdata => |cd| switch (cd._type) {
+ .cdata => switch (self.subtype(CData)._type) {
.text => 3,
.cdata_section => 4,
.processing_instruction => 7,
@@ -512,14 +548,14 @@ pub fn lookupNamespaceURI(self: *Node, prefix_arg: ?[]const u8, frame: *Frame) ?
const prefix: ?[]const u8 = if (prefix_arg) |p| (if (p.len == 0) null else p) else null;
switch (self._type) {
- .element => |el| return el.lookupNamespaceURIForElement(prefix, frame),
- .document => |doc| {
- const de = doc.getDocumentElement() orelse return null;
+ .element => return self.subtype(Element).lookupNamespaceURIForElement(prefix, frame),
+ .document => {
+ const de = self.subtype(Document).getDocumentElement() orelse return null;
return de.lookupNamespaceURIForElement(prefix, frame);
},
.document_type, .document_fragment => return null,
- .attribute => |attr| {
- const owner = attr.getOwnerElement() orelse return null;
+ .attribute => {
+ const owner = self.subtype(Element.Attribute).getOwnerElement() orelse return null;
return owner.lookupNamespaceURIForElement(prefix, frame);
},
.cdata => {
@@ -534,14 +570,14 @@ pub fn lookupPrefix(self: *Node, namespace_arg: ?[]const u8, frame: *Frame) ?[]c
if (namespace.len == 0) return null;
switch (self._type) {
- .element => |el| return el.lookupPrefixForElement(namespace, frame),
- .document => |doc| {
- const de = doc.getDocumentElement() orelse return null;
+ .element => return self.subtype(Element).lookupPrefixForElement(namespace, frame),
+ .document => {
+ const de = self.subtype(Document).getDocumentElement() orelse return null;
return de.lookupPrefixForElement(namespace, frame);
},
.document_type, .document_fragment => return null,
- .attribute => |attr| {
- const owner = attr.getOwnerElement() orelse return null;
+ .attribute => {
+ const owner = self.subtype(Element.Attribute).getOwnerElement() orelse return null;
return owner.lookupPrefixForElement(namespace, frame);
},
.cdata => {
@@ -620,7 +656,8 @@ pub fn isConnected(self: *const Node) bool {
switch (root._type) {
.document => return true,
- .document_fragment => |df| {
+ .document_fragment => {
+ const df = root.subtype(DocumentFragment);
const sr = df.is(ShadowRoot) orelse return false;
return sr._host.asNode().isConnected();
},
@@ -678,7 +715,7 @@ pub fn ownerDocument(self: *const Node, frame: *const Frame) ?*Document {
// An attribute node has no parent; its owner follows its element's
// (including across adoption into another document).
if (self._type == .attribute) {
- if (self._type.attribute._element) |element| {
+ if (self.subtype(Element.Attribute)._element) |element| {
return element.asNode().ownerDocument(frame);
}
}
@@ -691,16 +728,14 @@ pub fn ownerDocument(self: *const Node, frame: *const Frame) ?*Document {
// If the root is a document, then that's our owner.
if (current._type == .document) {
- return current._type.document;
+ return current.subtype(Document);
}
// A shadow tree's root is a parent-less ShadowRoot fragment; its owner
// is the host's owner document.
- // can't use current.is(ShadowRoot) without @constCast on `current`
if (current._type == .document_fragment) {
- const df = current._type.document_fragment;
- if (df._type == .shadow_root) {
- return df._type.shadow_root._host.asNode().ownerDocument(frame);
+ if (current.subtype(DocumentFragment).is(ShadowRoot)) |sr| {
+ return sr._host.asNode().ownerDocument(frame);
}
}
@@ -716,7 +751,7 @@ pub fn ownerDocument(self: *const Node, frame: *const Frame) ?*Document {
fn ownerDocumentIncludingSelf(self: *const Node, frame: *const Frame) ?*Document {
if (self._type == .document) {
- return self._type.document;
+ return self.subtype(Document);
}
return self.ownerDocument(frame);
}
@@ -977,8 +1012,8 @@ pub fn moveBefore(self: *Node, node_val: js.Value, child_val: js.Value, frame: *
if (self._type == .document) {
switch (node._type) {
- .cdata => |cd| {
- if (cd._type == .text) {
+ .cdata => {
+ if (node.subtype(CData)._type == .text) {
// A Text node cannot be a child of a document.
return error.HierarchyError;
}
@@ -1044,8 +1079,8 @@ pub fn moveBefore(self: *Node, node_val: js.Value, child_val: js.Value, frame: *
pub fn getNodeValue(self: *const Node) ?String {
return switch (self._type) {
- .cdata => |c| c.getData(),
- .attribute => |attr| attr._value,
+ .cdata => self.subtype(CData).getData(),
+ .attribute => self.subtype(Element.Attribute)._value,
.element => null,
.document => null,
.document_type => null,
@@ -1056,11 +1091,12 @@ pub fn getNodeValue(self: *const Node) ?String {
pub fn setNodeValue(self: *const Node, value: ?String, frame: *Frame) !void {
switch (self._type) {
// Per spec, setting nodeValue on CharacterData runs replaceData(0, length, value)
- .cdata => |c| {
+ .cdata => {
+ const c = self.subtype(CData);
const new_value: []const u8 = if (value) |v| v.str() else "";
try c.replaceData(0, c.getLength(), new_value, frame);
},
- .attribute => |attr| try attr.setValue(value, frame),
+ .attribute => try self.subtype(Element.Attribute).setValue(value, frame),
.element => {},
.document => {},
.document_type => {},
@@ -1072,12 +1108,12 @@ pub fn format(self: *Node, writer: *std.Io.Writer) !void {
// // If you need extra debugging:
// return @import("../dump.zig").deep(self, .{}, writer);
return switch (self._type) {
- .cdata => |cd| cd.format(writer),
- .element => |el| writer.print("{f}", .{el}),
+ .cdata => self.subtype(CData).format(writer),
+ .element => writer.print("{f}", .{self.subtype(Element)}),
.document => writer.writeAll("<document>"),
.document_type => writer.writeAll("<doctype>"),
.document_fragment => writer.writeAll("<document_fragment>"),
- .attribute => |attr| writer.print("{f}", .{attr}),
+ .attribute => writer.print("{f}", .{self.subtype(Element.Attribute)}),
};
}
@@ -1096,9 +1132,9 @@ pub fn getChildrenCount(self: *Node) usize {
pub fn getLength(self: *Node) u32 {
switch (self._type) {
- .cdata => |cdata| {
+ .cdata => {
// The node length of CharacterData is in UTF-16 code units.
- return @intCast(cdata.getLength());
+ return @intCast(self.subtype(CData).getLength());
},
.element, .document, .document_fragment => {
var count: u32 = 0;
@@ -1138,14 +1174,14 @@ pub fn getChildAt(self: *Node, index: u32) ?*Node {
pub fn getData(self: *const Node) String {
return switch (self._type) {
- .cdata => |c| c.getData(),
+ .cdata => self.subtype(CData).getData(),
else => .empty,
};
}
pub fn setData(self: *Node, data: []const u8, frame: *Frame) !void {
switch (self._type) {
- .cdata => |c| try c.setData(data, frame),
+ .cdata => try self.subtype(CData).setData(data, frame),
else => {},
}
}
@@ -1175,7 +1211,8 @@ const CloneError = error{
pub fn cloneNode(self: *Node, deep_: ?bool, frame: *Frame) CloneError!*Node {
const deep = deep_ orelse false;
switch (self._type) {
- .cdata => |cd| {
+ .cdata => {
+ const cd = self.subtype(CData);
const data = cd.getData().str();
return switch (cd._type) {
.text => Frame.node_factory.createTextNode(frame, data),
@@ -1184,8 +1221,9 @@ pub fn cloneNode(self: *Node, deep_: ?bool, frame: *Frame) CloneError!*Node {
.processing_instruction => Frame.node_factory.createProcessingInstruction(frame, cd.subtype(CData.ProcessingInstruction)._target, data),
};
},
- .element => |el| return el.clone(deep, frame),
- .document => |doc| {
+ .element => return self.subtype(Element).clone(deep, frame),
+ .document => {
+ const doc = self.subtype(Document);
const cloned = switch (doc._type) {
.xml => (frame._factory.document(Document.XMLDocument{ ._proto = undefined }) catch return error.CloneError).asDocument(),
else => (frame._factory.document(Document.HTMLDocument{ ._proto = undefined }) catch return error.CloneError).asDocument(),
@@ -1203,13 +1241,13 @@ pub fn cloneNode(self: *Node, deep_: ?bool, frame: *Frame) CloneError!*Node {
}
return cloned.asNode();
},
- .document_type => |dt| {
- const cloned = dt.clone(frame) catch return error.CloneError;
+ .document_type => {
+ const cloned = self.subtype(DocumentType).clone(frame) catch return error.CloneError;
return cloned.asNode();
},
- .document_fragment => |frag| return frag.cloneFragment(deep, frame),
- .attribute => |attr| {
- const cloned = attr.clone(frame) catch return error.CloneError;
+ .document_fragment => return self.subtype(DocumentFragment).cloneFragment(deep, frame),
+ .attribute => {
+ const cloned = self.subtype(Element.Attribute).clone(frame) catch return error.CloneError;
return cloned.asNode();
},
}
@@ -1703,8 +1741,8 @@ pub const JsApi = struct {
try self.getTextContent(&buf.writer);
return buf.written();
},
- .cdata => |cdata| return cdata._data.str(),
- .attribute => |attr| return attr._value.str(),
+ .cdata => return self.subtype(CData)._data.str(),
+ .attribute => return self.subtype(Element.Attribute)._value.str(),
.document => return null,
.document_type => return null,
}
@@ -1758,23 +1796,22 @@ pub const Build = struct {
// Calls `func_name` with `args` on the most specific type where it is
// implement. This could be on the Node itself (as a last-resort);
pub fn call(self: *const Node, comptime func_name: []const u8, args: anytype) !void {
- inline for (@typeInfo(Node.Type).@"union".fields) |f| {
- // The inner type has its own "call" method. Defer to it.
- if (@field(Node.Type, f.name) == self._type) {
- const S = reflect.Struct(f.type);
+ switch (self._type) {
+ inline else => |tag| {
+ const S = Subtype(tag);
if (@hasDecl(S, "Build")) {
+ // The inner type has its own "call" method. Defer to it.
if (@hasDecl(S.Build, "call")) {
- const sub = @field(self._type, f.name);
- if (try S.Build.call(sub, func_name, args)) {
+ if (try S.Build.call(self.subtype(S), func_name, args)) {
return;
}
}
// The inner type implements this function. Call it and we're done.
if (@hasDecl(S, func_name)) {
- return @call(.auto, @field(f.type, func_name), args);
+ return @call(.auto, @field(S, func_name), args);
}
}
- }
+ },
}
if (@hasDecl(Node.Build, func_name)) {
diff --git a/src/browser/webapi/Selection.zig b/src/browser/webapi/Selection.zig
index 251e22db1..509bbdfac 100644
--- a/src/browser/webapi/Selection.zig
+++ b/src/browser/webapi/Selection.zig
@@ -359,7 +359,7 @@ pub fn modify(
fn isTextNode(node: *const Node) bool {
return switch (node._type) {
- .cdata => |cd| cd._type == .text,
+ .cdata => node.subtype(Node.CData)._type == .text,
else => false,
};
}
diff --git a/src/browser/webapi/element/Html.zig b/src/browser/webapi/element/Html.zig
index 060c88acf..64e96684d 100644
--- a/src/browser/webapi/element/Html.zig
+++ b/src/browser/webapi/element/Html.zig
@@ -1488,30 +1488,36 @@ fn collectInnerText(self: *HtmlElement, state: *InnerTextState) std.Io.Writer.Er
var it = el.asNode().childrenIterator();
while (it.next()) |child| {
switch (child._type) {
- .element => |e| switch (e._type) {
- .svg => {},
- .html => |he| {
- const tag = e.getTag();
- switch (child_filter) {
- .none => {},
- .select => if (tag != .option and tag != .optgroup) continue,
- .optgroup => if (tag != .option) continue,
- }
- try handleChildElement(he, tag, state, &saw_cell, &saw_row);
- },
+ .element => {
+ const e = child.subtype(Node.Element);
+ switch (e._type) {
+ .svg => {},
+ .html => |he| {
+ const tag = e.getTag();
+ switch (child_filter) {
+ .none => {},
+ .select => if (tag != .option and tag != .optgroup) continue,
+ .optgroup => if (tag != .option) continue,
+ }
+ try handleChildElement(he, tag, state, &saw_cell, &saw_row);
+ },
+ }
},
- .cdata => |c| switch (c._type) {
- .text => {
- if (child_filter != .none) {
- // Text directly inside <select>/<optgroup> is skipped
- continue;
- }
- if (table_ctx and isAllAsciiWhitespace(c.getData().str())) {
- continue;
- }
- try writeText(c, state);
- },
- .comment, .cdata_section, .processing_instruction => {},
+ .cdata => {
+ const c = child.subtype(Node.CData);
+ switch (c._type) {
+ .text => {
+ if (child_filter != .none) {
+ // Text directly inside <select>/<optgroup> is skipped
+ continue;
+ }
+ if (table_ctx and isAllAsciiWhitespace(c.getData().str())) {
+ continue;
+ }
+ try writeText(c, state);
+ },
+ .comment, .cdata_section, .processing_instruction => {},
+ }
},
else => {},
}
diff --git a/src/browser/webapi/selector/List.zig b/src/browser/webapi/selector/List.zig
index e2bb92c68..4870e4ff8 100644
--- a/src/browser/webapi/selector/List.zig
+++ b/src/browser/webapi/selector/List.zig
@@ -648,9 +648,12 @@ fn matchesPseudoClass(el: *Node.Element, pseudo: Selector.PseudoClass, scope: *N
var it = node.childrenIterator();
while (it.next()) |child| {
switch (child._type) {
- .cdata => |cdata| switch (cdata._type) {
- .comment, .processing_instruction => {},
- else => if (cdata.getLength() > 0) return false,
+ .cdata => {
+ const cdata = child.subtype(Node.CData);
+ switch (cdata._type) {
+ .comment, .processing_instruction => {},
+ else => if (cdata.getLength() > 0) return false,
+ }
},
else => return false,
}
@@ -687,8 +690,8 @@ fn matchesPseudoClass(el: *Node.Element, pseudo: Selector.PseudoClass, scope: *N
var current: ?*Node = node;
while (current) |cur| : (current = cur.parentNode()) {
switch (cur._type) {
- .element => |ancestor| {
- if (ancestor.getAttributeSafe(comptime .wrap("lang"))) |value| {
+ .element => {
+ if (cur.subtype(Node.Element).getAttributeSafe(comptime .wrap("lang"))) |value| {
break :blk value;
}
},
diff --git a/src/browser/xpath/Evaluator.zig b/src/browser/xpath/Evaluator.zig
index 337e89ec3..523e9f75a 100644
--- a/src/browser/xpath/Evaluator.zig
+++ b/src/browser/xpath/Evaluator.zig
@@ -563,7 +563,7 @@ fn matchNameTest(node: *Node, name: []const u8, axis: ast.Axis, lowered_name: ?[
if (axis == .attribute) {
if (std.mem.eql(u8, name, "*")) return node._type == .attribute;
const attr = switch (node._type) {
- .attribute => |a| a,
+ .attribute => node.subtype(Element.Attribute),
else => return false,
};
return std.mem.eql(u8, attr._name.str(), lowered_name.?);
diff --git a/src/browser/xpath/result.zig b/src/browser/xpath/result.zig
index 5f240913e..baee093b5 100644
--- a/src/browser/xpath/result.zig
+++ b/src/browser/xpath/result.zig
@@ -52,8 +52,8 @@ pub const Result = union(enum) {
/// (concatenation buffer).
pub fn stringValueOf(arena: Allocator, node: *Node) error{WriteFailed}![]const u8 {
return switch (node._type) {
- .attribute => |attr| attr._value.str(),
- .cdata => |cd| cd._data.str(),
+ .attribute => node.subtype(Node.Element.Attribute)._value.str(),
+ .cdata => node.subtype(Node.CData)._data.str(),
.element, .document => blk: {
var buf = std.Io.Writer.Allocating.init(arena);
try node.getTextContent(&buf.writer);
diff --git a/src/cdp/AXNode.zig b/src/cdp/AXNode.zig
index 753c288a8..e3fa42bfa 100644
--- a/src/cdp/AXNode.zig
+++ b/src/cdp/AXNode.zig
@@ -343,161 +343,164 @@ pub const Writer = struct {
const dom_node = axnode.dom;
switch (dom_node._type) {
- .document => |document| {
- const uri = document.getURL(frame);
+ .document => {
+ const uri = dom_node.subtype(DOMNode.Document).getURL(frame);
try self.writeAXProperty(.{ .name = .url, .value = .{ .string = uri } }, w);
try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
try self.writeAXProperty(.{ .name = .focused, .value = .{ .booleanOrUndefined = true } }, w);
return;
},
.cdata => return,
- .element => |el| switch (el.getTag()) {
- .h1 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 1 } }, w),
- .h2 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 2 } }, w),
- .h3 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 3 } }, w),
- .h4 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 4 } }, w),
- .h5 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 5 } }, w),
- .h6 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 6 } }, w),
- .img => {
- const img = el.as(DOMNode.Element.Html.Image);
- const uri = try img.getSrc(self.frame);
- if (uri.len == 0) return;
- try self.writeAXProperty(.{ .name = .url, .value = .{ .string = uri } }, w);
- },
- .anchor => {
- const a = el.as(DOMNode.Element.Html.Anchor);
- const uri = try a.getHref(self.frame);
- if (uri.len == 0) return;
- try self.writeAXProperty(.{ .name = .url, .value = .{ .string = uri } }, w);
- try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
- },
- .input => {
- const input = el.as(DOMNode.Element.Html.Input);
- const is_disabled = el.isDisabled();
-
- switch (input._input_type) {
- .text, .email, .tel, .url, .search, .password, .number => {
- if (is_disabled) {
- try self.writeAXProperty(.{ .name = .disabled, .value = .{ .boolean = true } }, w);
- }
- try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
- if (!is_disabled) {
- try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
- }
- try self.writeAXProperty(.{ .name = .editable, .value = .{ .token = "plaintext" } }, w);
- if (!is_disabled) {
- try self.writeAXProperty(.{ .name = .settable, .value = .{ .booleanOrUndefined = true } }, w);
- }
- try self.writeAXProperty(.{ .name = .multiline, .value = .{ .boolean = false } }, w);
- try self.writeAXProperty(.{ .name = .readonly, .value = .{ .boolean = el.hasAttributeSafe(comptime .wrap("readonly")) } }, w);
- try self.writeAXProperty(.{ .name = .required, .value = .{ .boolean = el.hasAttributeSafe(comptime .wrap("required")) } }, w);
- },
- .button, .submit, .reset, .image => {
- try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
- if (!is_disabled) {
- try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
- }
- },
- .checkbox, .radio => {
- try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
- if (!is_disabled) {
- try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
- }
- const is_checked = el.hasAttributeSafe(comptime .wrap("checked"));
- try self.writeAXProperty(.{ .name = .checked, .value = .{ .token = if (is_checked) "true" else "false" } }, w);
- },
- else => {},
- }
- },
- .textarea => {
- const is_disabled = el.isDisabled();
-
- try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
- if (!is_disabled) {
+ .element => {
+ const el = dom_node.subtype(DOMNode.Element);
+ switch (el.getTag()) {
+ .h1 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 1 } }, w),
+ .h2 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 2 } }, w),
+ .h3 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 3 } }, w),
+ .h4 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 4 } }, w),
+ .h5 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 5 } }, w),
+ .h6 => try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = 6 } }, w),
+ .img => {
+ const img = el.as(DOMNode.Element.Html.Image);
+ const uri = try img.getSrc(self.frame);
+ if (uri.len == 0) return;
+ try self.writeAXProperty(.{ .name = .url, .value = .{ .string = uri } }, w);
+ },
+ .anchor => {
+ const a = el.as(DOMNode.Element.Html.Anchor);
+ const uri = try a.getHref(self.frame);
+ if (uri.len == 0) return;
+ try self.writeAXProperty(.{ .name = .url, .value = .{ .string = uri } }, w);
try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
- }
- try self.writeAXProperty(.{ .name = .editable, .value = .{ .token = "plaintext" } }, w);
- if (!is_disabled) {
- try self.writeAXProperty(.{ .name = .settable, .value = .{ .booleanOrUndefined = true } }, w);
- }
- try self.writeAXProperty(.{ .name = .multiline, .value = .{ .boolean = true } }, w);
- try self.writeAXProperty(.{ .name = .readonly, .value = .{ .boolean = el.hasAttributeSafe(comptime .wrap("readonly")) } }, w);
- try self.writeAXProperty(.{ .name = .required, .value = .{ .boolean = el.hasAttributeSafe(comptime .wrap("required")) } }, w);
- },
- .select => {
- const is_disabled = el.isDisabled();
+ },
+ .input => {
+ const input = el.as(DOMNode.Element.Html.Input);
+ const is_disabled = el.isDisabled();
+
+ switch (input._input_type) {
+ .text, .email, .tel, .url, .search, .password, .number => {
+ if (is_disabled) {
+ try self.writeAXProperty(.{ .name = .disabled, .value = .{ .boolean = true } }, w);
+ }
+ try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
+ if (!is_disabled) {
+ try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
+ }
+ try self.writeAXProperty(.{ .name = .editable, .value = .{ .token = "plaintext" } }, w);
+ if (!is_disabled) {
+ try self.writeAXProperty(.{ .name = .settable, .value = .{ .booleanOrUndefined = true } }, w);
+ }
+ try self.writeAXProperty(.{ .name = .multiline, .value = .{ .boolean = false } }, w);
+ try self.writeAXProperty(.{ .name = .readonly, .value = .{ .boolean = el.hasAttributeSafe(comptime .wrap("readonly")) } }, w);
+ try self.writeAXProperty(.{ .name = .required, .value = .{ .boolean = el.hasAttributeSafe(comptime .wrap("required")) } }, w);
+ },
+ .button, .submit, .reset, .image => {
+ try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
+ if (!is_disabled) {
+ try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
+ }
+ },
+ .checkbox, .radio => {
+ try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
+ if (!is_disabled) {
+ try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
+ }
+ const is_checked = el.hasAttributeSafe(comptime .wrap("checked"));
+ try self.writeAXProperty(.{ .name = .checked, .value = .{ .token = if (is_checked) "true" else "false" } }, w);
+ },
+ else => {},
+ }
+ },
+ .textarea => {
+ const is_disabled = el.isDisabled();
- try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
- if (!is_disabled) {
+ try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
+ if (!is_disabled) {
+ try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
+ }
+ try self.writeAXProperty(.{ .name = .editable, .value = .{ .token = "plaintext" } }, w);
+ if (!is_disabled) {
+ try self.writeAXProperty(.{ .name = .settable, .value = .{ .booleanOrUndefined = true } }, w);
+ }
+ try self.writeAXProperty(.{ .name = .multiline, .value = .{ .boolean = true } }, w);
+ try self.writeAXProperty(.{ .name = .readonly, .value = .{ .boolean = el.hasAttributeSafe(comptime .wrap("readonly")) } }, w);
+ try self.writeAXProperty(.{ .name = .required, .value = .{ .boolean = el.hasAttributeSafe(comptime .wrap("required")) } }, w);
+ },
+ .select => {
+ const is_disabled = el.isDisabled();
+
+ try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
+ if (!is_disabled) {
+ try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
+ }
+ try self.writeAXProperty(.{ .name = .hasPopup, .value = .{ .token = "menu" } }, w);
+ try self.writeAXProperty(.{ .name = .expanded, .value = .{ .booleanOrUndefined = false } }, w);
+ },
+ .option => {
+ const option = el.as(DOMNode.Element.Html.Option);
try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
- }
- try self.writeAXProperty(.{ .name = .hasPopup, .value = .{ .token = "menu" } }, w);
- try self.writeAXProperty(.{ .name = .expanded, .value = .{ .booleanOrUndefined = false } }, w);
- },
- .option => {
- const option = el.as(DOMNode.Element.Html.Option);
- try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
- // Check if this option is selected by examining the parent select
- const is_selected = blk: {
- // First check if explicitly selected
- if (option.getSelected()) break :blk true;
-
- // Check if implicitly selected (first enabled option in select with no explicit selection)
- const parent = dom_node._parent orelse break :blk false;
- const parent_el = parent.as(DOMNode.Element);
- if (parent_el.getTag() != .select) break :blk false;
-
- const select = parent_el.as(DOMNode.Element.Html.Select);
- const selected_idx = select.getSelectedIndex();
-
- // Find this option's index
- var idx: i32 = 0;
- var it = parent.childrenIterator();
- while (it.next()) |child| {
- if (child.is(DOMNode.Element.Html.Option) == null) continue;
- if (child == dom_node) {
- break :blk idx == selected_idx;
+ // Check if this option is selected by examining the parent select
+ const is_selected = blk: {
+ // First check if explicitly selected
+ if (option.getSelected()) break :blk true;
+
+ // Check if implicitly selected (first enabled option in select with no explicit selection)
+ const parent = dom_node._parent orelse break :blk false;
+ const parent_el = parent.as(DOMNode.Element);
+ if (parent_el.getTag() != .select) break :blk false;
+
+ const select = parent_el.as(DOMNode.Element.Html.Select);
+ const selected_idx = select.getSelectedIndex();
+
+ // Find this option's index
+ var idx: i32 = 0;
+ var it = parent.childrenIterator();
+ while (it.next()) |child| {
+ if (child.is(DOMNode.Element.Html.Option) == null) continue;
+ if (child == dom_node) {
+ break :blk idx == selected_idx;
+ }
+ idx += 1;
}
- idx += 1;
- }
- break :blk false;
- };
+ break :blk false;
+ };
- if (is_selected) {
- try self.writeAXProperty(.{ .name = .selected, .value = .{ .booleanOrUndefined = true } }, w);
- }
- },
- .button => {
- const is_disabled = el.isDisabled();
- try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
- if (!is_disabled) {
- try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
- }
- },
- .hr => {
- try self.writeAXProperty(.{ .name = .settable, .value = .{ .booleanOrUndefined = true } }, w);
- try self.writeAXProperty(.{ .name = .orientation, .value = .{ .token = "horizontal" } }, w);
- },
- .li => {
- // Calculate level by counting list ancestors (ul, ol, menu)
- var level: usize = 0;
- var current = dom_node._parent;
- while (current) |node| {
- if (node.is(DOMNode.Element) == null) {
- current = node._parent;
- continue;
+ if (is_selected) {
+ try self.writeAXProperty(.{ .name = .selected, .value = .{ .booleanOrUndefined = true } }, w);
}
- const current_el = node.as(DOMNode.Element);
- switch (current_el.getTag()) {
- .ul, .ol, .menu => level += 1,
- else => {},
+ },
+ .button => {
+ const is_disabled = el.isDisabled();
+ try self.writeAXProperty(.{ .name = .invalid, .value = .{ .token = "false" } }, w);
+ if (!is_disabled) {
+ try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);
}
- current = node._parent;
- }
- try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = level } }, w);
- },
- else => {},
+ },
+ .hr => {
+ try self.writeAXProperty(.{ .name = .settable, .value = .{ .booleanOrUndefined = true } }, w);
+ try self.writeAXProperty(.{ .name = .orientation, .value = .{ .token = "horizontal" } }, w);
+ },
+ .li => {
+ // Calculate level by counting list ancestors (ul, ol, menu)
+ var level: usize = 0;
+ var current = dom_node._parent;
+ while (current) |node| {
+ if (node.is(DOMNode.Element) == null) {
+ current = node._parent;
+ continue;
+ }
+ const current_el = node.as(DOMNode.Element);
+ switch (current_el.getTag()) {
+ .ul, .ol, .menu => level += 1,
+ else => {},
+ }
+ current = node._parent;
+ }
+ try self.writeAXProperty(.{ .name = .level, .value = .{ .integer = level } }, w);
+ },
+ else => {},
+ }
},
else => |tag| {
log.debug(.cdp, "invalid tag", .{ .tag = tag });
@@ -760,7 +763,8 @@ pub const AXRole = enum(u8) {
fn fromNode(node: *DOMNode) !AXRole {
return switch (node._type) {
.document => return .RootWebArea, // Chrome specific.
- .cdata => |cd| {
+ .cdata => {
+ const cd = node.subtype(DOMNode.CData);
if (cd.is(DOMNode.CData.Text) == null) {
log.debug(.cdp, "invalid tag", .{ .tag = cd });
return error.InvalidTag;
@@ -768,131 +772,134 @@ pub const AXRole = enum(u8) {
return .StaticText;
},
- .element => |el| switch (el.getTag()) {
- // Navigation & Structure
- .nav => .navigation,
- .main => .main,
- .aside => .complementary,
- // TODO conditions:
- // .banner Not descendant of article, aside, main, nav, section
- // (none) When descendant of article, aside, main, nav, section
- .header => .banner,
- // TODO conditions:
- // contentinfo Not descendant of article, aside, main, nav, section
- // (none) When descendant of article, aside, main, nav, section
- .footer => .contentinfo,
- // TODO conditions:
- // region Has accessible name (aria-label, aria-labelledby, or title) |
- // (none) No accessible name |
- .section => .region,
- .article, .hgroup => .article,
- .address => .group,
-
- // Headings
- .h1, .h2, .h3, .h4, .h5, .h6 => .heading,
- .ul, .ol, .menu => .list,
- .li => .listitem,
- .dt => .term,
- .dd => .definition,
-
- // Forms & Inputs
- // TODO conditions:
- // form Has accessible name
- // (none) No accessible name
- .form => .form,
- .input => {
- const input = el.as(DOMNode.Element.Html.Input);
- return switch (input._input_type) {
- .tel, .url, .email, .text, .password => .textbox,
- .image, .reset, .button, .submit => .button,
- .radio => .radio,
- .range => .slider,
- .number => .spinbutton,
- .search => .searchbox,
- .checkbox => .checkbox,
- .color => .color,
- .date => .date,
- .file => .file,
- .month => .month,
- .@"datetime-local", .week, .time => .combobox,
- .hidden => .none,
- };
- },
- .textarea => .textbox,
- .select => {
- if (el.getAttributeSafe(comptime .wrap("multiple")) != null) {
- return .listbox;
- }
- if (el.getAttributeSafe(comptime .wrap("size"))) |size| {
- if (!std.ascii.eqlIgnoreCase(size, "1")) {
+ .element => {
+ const el = node.subtype(DOMNode.Element);
+ return switch (el.getTag()) {
+ // Navigation & Structure
+ .nav => .navigation,
+ .main => .main,
+ .aside => .complementary,
+ // TODO conditions:
+ // .banner Not descendant of article, aside, main, nav, section
+ // (none) When descendant of article, aside, main, nav, section
+ .header => .banner,
+ // TODO conditions:
+ // contentinfo Not descendant of article, aside, main, nav, section
+ // (none) When descendant of article, aside, main, nav, section
+ .footer => .contentinfo,
+ // TODO conditions:
+ // region Has accessible name (aria-label, aria-labelledby, or title) |
+ // (none) No accessible name |
+ .section => .region,
+ .article, .hgroup => .article,
+ .address => .group,
+
+ // Headings
+ .h1, .h2, .h3, .h4, .h5, .h6 => .heading,
+ .ul, .ol, .menu => .list,
+ .li => .listitem,
+ .dt => .term,
+ .dd => .definition,
+
+ // Forms & Inputs
+ // TODO conditions:
+ // form Has accessible name
+ // (none) No accessible name
+ .form => .form,
+ .input => {
+ const input = el.as(DOMNode.Element.Html.Input);
+ return switch (input._input_type) {
+ .tel, .url, .email, .text, .password => .textbox,
+ .image, .reset, .button, .submit => .button,
+ .radio => .radio,
+ .range => .slider,
+ .number => .spinbutton,
+ .search => .searchbox,
+ .checkbox => .checkbox,
+ .color => .color,
+ .date => .date,
+ .file => .file,
+ .month => .month,
+ .@"datetime-local", .week, .time => .combobox,
+ .hidden => .none,
+ };
+ },
+ .textarea => .textbox,
+ .select => {
+ if (el.getAttributeSafe(comptime .wrap("multiple")) != null) {
return .listbox;
}
- }
- return .combobox;
- },
- .option => .option,
- .optgroup, .fieldset => .group,
- .button => .button,
- .output => .status,
- .progress => .progressbar,
- .meter => .meter,
- .datalist => .listbox,
-
- // Interactive Elements
- .anchor, .area => {
- if (el.getAttributeSafe(comptime .wrap("href")) == null) {
- return .none;
- }
+ if (el.getAttributeSafe(comptime .wrap("size"))) |size| {
+ if (!std.ascii.eqlIgnoreCase(size, "1")) {
+ return .listbox;
+ }
+ }
+ return .combobox;
+ },
+ .option => .option,
+ .optgroup, .fieldset => .group,
+ .button => .button,
+ .output => .status,
+ .progress => .progressbar,
+ .meter => .meter,
+ .datalist => .listbox,
+
+ // Interactive Elements
+ .anchor, .area => {
+ if (el.getAttributeSafe(comptime .wrap("href")) == null) {
+ return .none;
+ }
- return .link;
- },
- .details => .group,
- .summary => .button,
- .dialog => .dialog,
-
- // Media
- .img => .image,
- .figure => .figure,
-
- // Tables
- .table => .table,
- .caption => .caption,
- .thead, .tbody, .tfoot => .rowgroup,
- .tr => .row,
- .th => {
- if (el.getAttributeSafe(comptime .wrap("scope"))) |scope| {
- if (std.ascii.eqlIgnoreCase(scope, "row")) {
- return .rowheader;
+ return .link;
+ },
+ .details => .group,
+ .summary => .button,
+ .dialog => .dialog,
+
+ // Media
+ .img => .image,
+ .figure => .figure,
+
+ // Tables
+ .table => .table,
+ .caption => .caption,
+ .thead, .tbody, .tfoot => .rowgroup,
+ .tr => .row,
+ .th => {
+ if (el.getAttributeSafe(comptime .wrap("scope"))) |scope| {
+ if (std.ascii.eqlIgnoreCase(scope, "row")) {
+ return .rowheader;
+ }
}
- }
- return .columnheader;
- },
- .td => .cell,
-
- // Text & Semantics
- .p => .paragraph,
- .hr => .separator,
- .blockquote => .blockquote,
- .code => .code,
- .em => .emphasis,
- .strong => .strong,
- .s, .del => .deletion,
- .ins => .insertion,
- .sub => .subscript,
- .sup => .superscript,
- .time => .time,
- .dfn => .term,
-
- // Document Structure
- .html => .none,
- .body => .none,
-
- // Deprecated/Obsolete Elements
- .marquee => .marquee,
-
- .br => .LineBreak,
-
- else => .none,
+ return .columnheader;
+ },
+ .td => .cell,
+
+ // Text & Semantics
+ .p => .paragraph,
+ .hr => .separator,
+ .blockquote => .blockquote,
+ .code => .code,
+ .em => .emphasis,
+ .strong => .strong,
+ .s, .del => .deletion,
+ .ins => .insertion,
+ .sub => .subscript,
+ .sup => .superscript,
+ .time => .time,
+ .dfn => .term,
+
+ // Document Structure
+ .html => .none,
+ .body => .none,
+
+ // Deprecated/Obsolete Elements
+ .marquee => .marquee,
+
+ .br => .LineBreak,
+
+ else => .none,
+ };
},
else => |tag| {
log.debug(.cdp, "invalid tag", .{ .tag = tag });
@@ -980,21 +987,25 @@ fn writeName(
const node = axnode.dom;
return switch (node._type) {
- .document => |doc| switch (doc._type) {
+ .document => switch (node.subtype(DOMNode.Document)._type) {
.html => |doc_html| {
try w.write(try doc_html.getTitle(frame));
return .title;
},
else => null,
},
- .cdata => |cd| switch (cd._type) {
- .text => {
- try writeString(cd._data.str(), w);
- return .contents;
- },
- else => null,
+ .cdata => {
+ const cd = node.subtype(DOMNode.CData);
+ switch (cd._type) {
+ .text => {
+ try writeString(cd._data.str(), w);
+ return .contents;
+ },
+ else => return null,
+ }
},
- .element => |el| {
+ .element => {
+ const el = node.subtype(DOMNode.Element);
// Handle aria-labelledby attribute (highest priority)
if (el.getAttributeSafe(.wrap("aria-labelledby"))) |labelledby| {
// Get the document to look up elements by ID
@@ -1107,17 +1118,18 @@ fn writeAccessibleNameFallback(node: *DOMNode, writer: *std.Io.Writer, frame: *F
var it = node.childrenIterator();
while (it.next()) |child| {
switch (child._type) {
- .cdata => |cd| switch (cd._type) {
- .text => {
+ .cdata => {
+ const cd = child.subtype(DOMNode.CData);
+ if (cd._type == .text) {
const content = std.mem.trim(u8, cd._data.str(), &std.ascii.whitespace);
if (content.len > 0) {
try writer.writeAll(content);
try writer.writeByte(' ');
}
- },
- else => {},
+ }
},
- .element => |el| {
+ .element => {
+ const el = child.subtype(DOMNode.Element);
if (el.getTag() == .img) {
if (el.getAttributeSafe(.wrap("alt"))) |alt| {
try writer.writeAll(alt);