Lightpanda: the headless browser designed for AI and automation
webapi: IntersectionObserver attributes and constructor checks
orezraey8143c6827186
diff --git a/src/browser/tests/intersection_observer/attributes.html b/src/browser/tests/intersection_observer/attributes.htmlnew file mode 100644index 000000000..3a06ed109--- /dev/null+++ b/src/browser/tests/intersection_observer/attributes.html@@ -0,0 +1,89 @@+<!DOCTYPE html>+<script src="../testing.js"></script>+<div id="root"></div>++<script id="attributes">+{+ const root = document.getElementById("root");+ const observer = new IntersectionObserver(() => {}, { root, rootMargin: "10px 5%", threshold: [1, 0, 0.5] });+ testing.expectEqual(root, observer.root);+ testing.expectEqual("10px 5% 10px 5%", observer.rootMargin);+ testing.expectEqual("0px 0px 0px 0px", observer.scrollMargin);+ testing.expectEqual("0,0.5,1", observer.thresholds.join());+ testing.expectEqual(0, observer.delay);+ testing.expectEqual(false, observer.trackVisibility);++ const defaults = new IntersectionObserver(() => {});+ testing.expectEqual(null, defaults.root);+ testing.expectEqual("0px 0px 0px 0px", defaults.rootMargin);+ testing.expectEqual("0", defaults.thresholds.join());+ testing.expectEqual(document, new IntersectionObserver(() => {}, { root: document }).root);+}+</script>++<script id="margins">+{+ // One to four px lengths or percentages, expanded like CSS margins.+ const margin = (value) => {+ try {+ return new IntersectionObserver(() => {}, { rootMargin: value }).rootMargin;+ } catch (err) {+ return err.name;+ }+ };+ testing.expectEqual("7px 7px 7px 7px", margin("7px"));+ testing.expectEqual("10px 20px 30px 20px", margin("10px 20px 30px"));+ testing.expectEqual("1px 2px 3px 4px", margin(" 1px 2px 3px\t4px "));+ testing.expectEqual("-10px 5% -10px 5%", margin("-10px 5%"));+ testing.expectEqual("10px 10px 10px 10px", margin("10PX"));+ testing.expectEqual("10px 10px 10px 10px", margin("1e1px"));+ testing.expectEqual("3px 3px 3px 3px", margin("+3px"));+ // Serialized as given (Chrome truncates px values to integers, "1px").+ testing.expectEqual("1.5px 1.5px 1.5px 1.5px", margin("1.50px"));+ testing.expectEqual("0px 0px 0px 0px", margin(""));+ for (const bad of ["0", "10em", "calc(10px)", "10px,20px", "10 px", "1px 2px 3px 4px 5px", "px", "1.px"]) {+ testing.expectEqual(`${bad}: SyntaxError`, `${bad}: ${margin(bad)}`);+ }+ testing.expectEqual("-4px 5% -4px 5%", new IntersectionObserver(() => {}, { scrollMargin: "-4px 5%" }).scrollMargin);+}+</script>++<script id="thresholds-and-delay">+{+ const outcome = (options, read) => {+ try {+ return read(new IntersectionObserver(() => {}, options));+ } catch (err) {+ return err.name;+ }+ };+ const thresholds = (threshold) => outcome({ threshold }, (o) => o.thresholds.join());+ testing.expectEqual("0", thresholds([]));+ // Kept as doubles (Chrome stores floats: 0.10000000149011612).+ testing.expectEqual("0.1,0.3,0.3", thresholds([0.3, 0.1, 0.3]));+ testing.expectEqual("0", thresholds(null));+ testing.expectEqual("RangeError", thresholds(-0.1));+ testing.expectEqual("RangeError", thresholds([0.5, 1.5]));+ testing.expectEqual("TypeError", thresholds(Infinity));+ testing.expectEqual("TypeError", thresholds([0.5, NaN]));++ const delay = (options) => outcome(options, (o) => `${o.delay} ${o.trackVisibility}`);+ testing.expectEqual("50 false", delay({ delay: 50 }));+ testing.expectEqual("1 false", delay({ delay: 1.7 }));+ testing.expectEqual("150 true", delay({ trackVisibility: true, delay: 150 }));+ // Tracking visibility raises the delay to 100ms (Chrome throws a+ // NotSupportedError instead, as an earlier draft did).+ testing.expectEqual("100 true", delay({ trackVisibility: true }));+ testing.expectEqual("100 true", delay({ trackVisibility: true, delay: 20 }));+ testing.expectEqual("TypeError", outcome({ root: document.createTextNode("x") }, (o) => o.root));++ // The options' conversion errors (a root of the wrong type, a non-finite+ // threshold) come before a rootMargin's SyntaxError, which comes before a+ // threshold's RangeError.+ const margin = (options) => outcome(options, (o) => o.rootMargin);+ testing.expectEqual("TypeError", margin({ root: document.createTextNode("x"), rootMargin: "x" }));+ testing.expectEqual("TypeError", margin({ threshold: NaN, rootMargin: "x" }));+ testing.expectEqual("SyntaxError", margin({ threshold: 2, rootMargin: "x" }));+ testing.expectEqual("0px 0px 0px 0px", margin({ rootMargin: "-0px" }));+}+</script>diff --git a/src/browser/webapi/IntersectionObserver.zig b/src/browser/webapi/IntersectionObserver.zigindex a450fe07c..966f8c686 100644--- a/src/browser/webapi/IntersectionObserver.zig+++ b/src/browser/webapi/IntersectionObserver.zig@@ -43,17 +43,28 @@ _arena: *lp.Arena,_callback: js.Function.Global,_observing: std.ArrayList(*Element) = .empty,_root: ?*Element = null,-_root_margin: []const u8 = "0px",+/// The `root` option as given (an Element or the Document), for the getter;+/// `_root` is the element intersections are computed against.+_root_node: ?*Node = null,+/// rootMargin and scrollMargin, parsed and serialized back (four values).+_root_margin: []const u8 = "0px 0px 0px 0px",+_scroll_margin: []const u8 = "0px 0px 0px 0px",+/// Sorted ascending, each in [0, 1]._threshold: []const f64 = &.{0.0},+_delay: i32 = 0,+_track_visibility: bool = false,// these are RC'd (by us, and v8)_pending_entries: std.ArrayList(*IntersectionObserverEntry) = .empty,// tracked targets that aren't reported yet_tracked: std.AutoHashMapUnmanaged(*Element, void) = .{},const ObserverInit = struct {+ delay: i32 = 0,root: ?*Node = null,rootMargin: ?[]const u8 = null,+ scrollMargin: ?[]const u8 = null,threshold: Threshold = .{ .scalar = 0.0 },+ trackVisibility: bool = false,const Threshold = union(enum) {scalar: f64,@@ -66,16 +77,17 @@ pub fn init(callback: js.Function.Global, options: ?ObserverInit, frame: *Frame)errdefer arena.release();const opts = options orelse ObserverInit{};- const root_margin = if (opts.rootMargin) |rm| try arena.dupe(u8, rm) else "0px";-- const threshold = switch (opts.threshold) {- .scalar => |s| blk: {- const arr = try arena.alloc(f64, 1);- arr[0] = s;- break :blk arr;- },- .array => |arr| try arena.dupe(f64, arr),++ // The options' WebIDL conversion comes first, so its TypeErrors do: a+ // root that's neither an Element nor a Document (below), and a threshold+ // that isn't a finite (restricted) double.+ const given_thresholds: []const f64 = switch (opts.threshold) {+ .scalar => |*value| value[0..1],+ .array => |arr| arr,};+ for (given_thresholds) |value| {+ if (!std.math.isFinite(value)) return error.TypeError;+ }const root: ?*Element = blk: {const root_opt = opts.root orelse break :blk null;@@ -91,17 +103,133 @@ pub fn init(callback: js.Function.Global, options: ?ObserverInit, frame: *Frame)}};+ const root_margin = try serializeMargin(arena.allocator(), try parseMargin(opts.rootMargin orelse "0px"));+ const scroll_margin = try serializeMargin(arena.allocator(), try parseMargin(opts.scrollMargin orelse "0px"));++ // Each threshold is in [0, 1], sorted ascending; an empty list is [0].+ const threshold = blk: {+ if (given_thresholds.len == 0) {+ break :blk &[_]f64{0.0};+ }+ const sorted = try arena.dupe(f64, given_thresholds);+ for (sorted) |value| {+ if (value < 0 or value > 1) return error.RangeError;+ }+ std.mem.sort(f64, sorted, {}, std.sort.asc(f64));+ break :blk sorted;+ };++ // Tracking visibility raises the delay to at least 100ms.+ const delay = if (opts.trackVisibility and opts.delay < 100) 100 else opts.delay;+const self = try arena.create(IntersectionObserver);self.* = .{._arena = arena,._callback = callback,._root = root,+ ._root_node = opts.root,._root_margin = root_margin,+ ._scroll_margin = scroll_margin,._threshold = threshold,+ ._delay = delay,+ ._track_visibility = opts.trackVisibility,};return self;}+/// One side of a rootMargin or scrollMargin: a length in px, or a percentage.+const Margin = struct {+ value: f64,+ percent: bool,+};++/// "Parse a margin": one to four whitespace-separated px lengths or+/// percentages, expanded like CSS margins to top, right, bottom, left. An+/// empty string is all zero. Any other token (a unitless number, another+/// unit, calc(), a comma) is a SyntaxError.+fn parseMargin(text: []const u8) error{SyntaxError}![4]Margin {+ var margins: [4]Margin = undefined;+ var count: usize = 0;+ var it = std.mem.tokenizeAny(u8, text, " \t\n\r\x0c");+ while (it.next()) |token| {+ if (count == 4) return error.SyntaxError;+ margins[count] = try parseMarginToken(token);+ count += 1;+ }+ const zero: Margin = .{ .value = 0, .percent = false };+ return switch (count) {+ 0 => .{ zero, zero, zero, zero },+ 1 => .{ margins[0], margins[0], margins[0], margins[0] },+ 2 => .{ margins[0], margins[1], margins[0], margins[1] },+ 3 => .{ margins[0], margins[1], margins[2], margins[1] },+ else => margins,+ };+}++/// A CSS <number> followed by "px" (ASCII case-insensitive) or "%".+fn parseMarginToken(token: []const u8) error{SyntaxError}!Margin {+ var i: usize = 0;+ if (i < token.len and (token[i] == '+' or token[i] == '-')) i += 1;+ var digits: usize = 0;+ while (i < token.len and std.ascii.isDigit(token[i])) : (i += 1) digits += 1;+ if (i < token.len and token[i] == '.') {+ i += 1;+ var fraction: usize = 0;+ while (i < token.len and std.ascii.isDigit(token[i])) : (i += 1) fraction += 1;+ if (fraction == 0) return error.SyntaxError;+ digits += fraction;+ }+ if (digits == 0) return error.SyntaxError;+ if (i < token.len and (token[i] == 'e' or token[i] == 'E')) {+ var j = i + 1;+ if (j < token.len and (token[j] == '+' or token[j] == '-')) j += 1;+ const exponent_start = j;+ while (j < token.len and std.ascii.isDigit(token[j])) j += 1;+ // An "e" without digits starts the unit instead (as "1em" would).+ if (j > exponent_start) i = j;+ }+ const value = std.fmt.parseFloat(f64, token[0..i]) catch return error.SyntaxError;+ const unit = token[i..];+ if (std.ascii.eqlIgnoreCase(unit, "px")) return .{ .value = value, .percent = false };+ if (std.mem.eql(u8, unit, "%")) return .{ .value = value, .percent = true };+ return error.SyntaxError;+}++/// The four margins as the rootMargin/scrollMargin attributes give them.+fn serializeMargin(allocator: std.mem.Allocator, margins: [4]Margin) ![]const u8 {+ var out: std.Io.Writer.Allocating = .init(allocator);+ for (margins, 0..) |margin, i| {+ if (i > 0) try out.writer.writeByte(' ');+ // + 0 turns -0 into 0, which a JS number prints as "0".+ try out.writer.print("{d}{s}", .{ margin.value + 0, if (margin.percent) "%" else "px" });+ }+ return out.written();+}++pub fn getRoot(self: *const IntersectionObserver) ?*Node {+ return self._root_node;+}++pub fn getRootMargin(self: *const IntersectionObserver) []const u8 {+ return self._root_margin;+}++pub fn getScrollMargin(self: *const IntersectionObserver) []const u8 {+ return self._scroll_margin;+}++pub fn getThresholds(self: *const IntersectionObserver) []const f64 {+ return self._threshold;+}++pub fn getDelay(self: *const IntersectionObserver) i32 {+ return self._delay;+}++pub fn getTrackVisibility(self: *const IntersectionObserver) bool {+ return self._track_visibility;+}+pub fn deinit(self: *IntersectionObserver, page: *Page) void {self._callback.release();releaseAll(self._pending_entries.items, page);@@ -397,6 +525,13 @@ pub const JsApi = struct {pub const constructor = bridge.constructor(init, .{});+ pub const root = bridge.accessor(IntersectionObserver.getRoot, null, .{});+ pub const rootMargin = bridge.accessor(IntersectionObserver.getRootMargin, null, .{});+ pub const scrollMargin = bridge.accessor(IntersectionObserver.getScrollMargin, null, .{});+ pub const thresholds = bridge.accessor(IntersectionObserver.getThresholds, null, .{});+ pub const delay = bridge.accessor(IntersectionObserver.getDelay, null, .{});+ pub const trackVisibility = bridge.accessor(IntersectionObserver.getTrackVisibility, null, .{});+pub const observe = bridge.function(IntersectionObserver.observe, .{});pub const unobserve = bridge.function(IntersectionObserver.unobserve, .{});pub const disconnect = bridge.function(IntersectionObserver.disconnect, .{});