diff --git a/src/dom/document.zig b/src/dom/document.zig index 713313fa..72537992 100644 --- a/src/dom/document.zig +++ b/src/dom/document.zig @@ -166,6 +166,13 @@ pub const Document = struct { return try parser.documentCreateAttributeNS(self, ns, qname); } + // ParentNode + // https://dom.spec.whatwg.org/#parentnode + pub fn get_children(self: *parser.Document) !collection.HTMLCollection { + const root = try parser.documentGetDocumentElement(self); + return try collection.HTMLCollectionChildren(parser.elementToNode(root), true); + } + pub fn deinit(_: *parser.Document, _: std.mem.Allocator) void {} }; diff --git a/src/dom/html_collection.zig b/src/dom/html_collection.zig index 63b7eb7b..871b1d8d 100644 --- a/src/dom/html_collection.zig +++ b/src/dom/html_collection.zig @@ -115,8 +115,21 @@ pub fn HTMLCollectionByClassName( }; } +pub fn HTMLCollectionChildren( + root: *parser.Node, + include_root: bool, +) !HTMLCollection { + return HTMLCollection{ + .root = root, + .walker = Walker{ .walkerChildren = .{} }, + .matcher = Matcher{ .matchTrue = .{} }, + .include_root = include_root, + }; +} + const Walker = union(enum) { walkerDepthFirst: WalkerDepthFirst, + walkerChildren: WalkerChildren, pub fn get_next(self: Walker, root: *parser.Node, cur: ?*parser.Node) !?*parser.Node { switch (self) { @@ -175,6 +188,27 @@ pub const WalkerDepthFirst = struct { } }; +// WalkerChildren iterates over the root's children only. +pub const WalkerChildren = struct { + pub fn get_next(_: WalkerChildren, root: *parser.Node, cur: ?*parser.Node) !?*parser.Node { + // On wlak start, we return the first root's child. + if (cur == null) return try parser.nodeFirstChild(root); + + // If cur is root, then return null. + // This is a special case, if the root is included in the walk, we + // don't want to go further to find children. + if (root == cur.?) return null; + + // TODO deinit last. + const last = try parser.nodeLastChild(root); + if (last == cur.?) { + return null; + } + + return try parser.nodeNextSibling(cur.?); + } +}; + // WEB IDL https://dom.spec.whatwg.org/#htmlcollection // HTMLCollection is re implemented in zig here because libdom // dom_html_collection expects a comparison function callback as arguement. @@ -323,6 +357,8 @@ pub fn testExecFn( .{ .src = "getElementsByTagNameAll.item(7).localName", .ex = "p" }, .{ .src = "getElementsByTagNameAll.namedItem('para-empty-child').localName", .ex = "span" }, + .{ .src = "document.children.length", .ex = "1" }, + // check liveness .{ .src = "let content = document.getElementById('content')", .ex = "undefined" }, .{ .src = "let pe = document.getElementById('para-empty')", .ex = "undefined" },