Skip to content

Commit da307c1

Browse files
committed
range.selectNodeContents
1 parent f5a58c1 commit da307c1

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/browser/dom/range.zig

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,32 @@ pub const Range = struct {
9494
const doc_frag = try parser.documentParseFragmentFromStr(document, fragment);
9595
return doc_frag;
9696
}
97+
98+
pub fn _selectNodeContents(self: *Range, node: *parser.Node) !void {
99+
self.proto.start_container = node;
100+
self.proto.start_offset = 0;
101+
self.proto.end_container = node;
102+
103+
// Set end_offset
104+
switch (try parser.nodeType(node)) {
105+
.text, .cdata_section, .comment, .processing_instruction => {
106+
// For text-like nodes, end_offset should be the length of the text data
107+
if (try parser.nodeValue(node)) |text_data| {
108+
self.proto.end_offset = @intCast(text_data.len);
109+
} else {
110+
self.proto.end_offset = 0;
111+
}
112+
},
113+
else => {
114+
// For element and other nodes, end_offset is the number of children
115+
const child_nodes = try parser.nodeGetChildNodes(node);
116+
const child_count = try parser.nodeListLength(child_nodes);
117+
self.proto.end_offset = @intCast(child_count);
118+
},
119+
}
120+
121+
self.proto.updateCollapsed();
122+
}
97123
};
98124

99125
const testing = @import("../../testing.zig");
@@ -117,4 +143,22 @@ test "Browser.Range" {
117143
.{ "docRange instanceof Range", "true" },
118144
.{ "docRange.collapsed", "true" },
119145
}, .{});
146+
147+
try runner.testCases(&.{
148+
.{ "const container = document.getElementById('content');", null },
149+
150+
// Test text range
151+
.{ "const commentNode = container.childNodes[7];", null },
152+
.{ "commentNode.nodeValue", "comment" },
153+
.{ "const textRange = document.createRange();", null },
154+
.{ "textRange.selectNodeContents(commentNode)", "undefined" },
155+
.{ "textRange.startOffset", "0" },
156+
.{ "textRange.endOffset", "7" }, // length of `comment`
157+
158+
// Test Node range
159+
.{ "const nodeRange = document.createRange();", null },
160+
.{ "nodeRange.selectNodeContents(container)", "undefined" },
161+
.{ "nodeRange.startOffset", "0" },
162+
.{ "nodeRange.endOffset", "9" }, // length of container.childNodes
163+
}, .{});
120164
}

0 commit comments

Comments
 (0)