Lightpanda: the headless browser designed for AI and automation
webapi: Fire navigate event
Karl Seguin329f9f8fc53e
diff --git a/src/browser/EventManager.zig b/src/browser/EventManager.zigindex fac568c15..561699501 100644--- a/src/browser/EventManager.zig+++ b/src/browser/EventManager.zig@@ -288,7 +288,7 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event) !void {// activation behavior (ancestors only for bubbling events).if (event.is(@import("webapi/event/MouseEvent.zig")) != null) {if (Frame.user_input.findClickActivationTarget(target, event._bubbles)) |activation_target| {- Frame.user_input.handleClick(frame, activation_target, target) catch |err| {+ Frame.user_input.handleClick(frame, activation_target, target, event._is_trusted) catch |err| {log.debug(.event, "frame.click", .{ .err = err });};}diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex ff9a8c7af..ae3993a1b 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -39,6 +39,7 @@ const IdMap = @import("IdMap.zig");const css_charset = @import("css/charset.zig");const referrer = @import("referrer.zig");const Blob = @import("webapi/Blob.zig");+const FormData = @import("webapi/net/FormData.zig");const FileList = @import("webapi/FileList.zig");const MediaQueryList = @import("webapi/css/MediaQueryList.zig");const Node = @import("webapi/Node.zig");@@ -68,6 +69,8 @@ const HashChangeEvent = @import("webapi/event/HashChangeEvent.zig");const popover = @import("webapi/element/popover.zig");const slotting = @import("webapi/element/slotting.zig");const NavigationKind = @import("webapi/navigation/root.zig").NavigationKind;+const OngoingNavigation = @import("webapi/navigation/root.zig").OngoingNavigation;+const NavigateEventResult = @import("webapi/navigation/Navigation.zig").NavigateEventResult;const sys_url = @import("../sys/url.zig");const HttpClient = @import("../network/HttpClient.zig");@@ -232,6 +235,9 @@ _notified_network_almost_idle: IdleNotification = .init,// next tick._queued_navigation: ?*QueuedNavigation = null,+// Only on a root frame: see Navigation.fireNavigateEvent.+_ongoing_navigate: ?OngoingNavigation = null,+// Is there a <meta http-equiv=refresh> we need to fire on "load"?// Exactly which we need to fire can change, so rather than keeping it in sync// it's easier to scan for it on "load", but this is hint to avoid that scan@@ -662,6 +668,11 @@ pub fn getPinnedArena(self: *Frame, size_or_bucket: anytype, debug: []const u8)return self._session.getPinnedArena(size_or_bucket, debug);}+// HTML's "completely loaded": the load event has been dispatched.+pub fn isCompletelyLoaded(self: *const Frame) bool {+ return self._load_state == .complete and self._load_event_in_progress == false;+}+fn sameOrigin(a: *const Frame, b: *const Frame) bool {const a_origin = a.origin orelse return false;const b_origin = b.origin orelse return false;@@ -1074,12 +1085,30 @@ fn scheduleNavigationWithArena(originator: *Frame, arena: *lp.Arena, request_url// change, no hashchange and no new history entry either. It's still a// fragment navigation, which Chrome reports.if (std.mem.eql(u8, target.url, resolved_url)) {+ var same_url_opts = opts;+ same_url_opts.kind = .{ .replace = null };+ const result = try fireNavigateEvent(originator, target, resolved_url, true, same_url_opts);+ if (result == .canceled) {+ arena.release();+ return;+ }+session.notification.dispatch(.frame_navigated_within_document, &.{.url = target.url,.frame_id = target._frame_id,.navigation_type = .fragment,});arena.release();++ if (result == .fired) {+ try session.navigationFor(target).commitSameDocument(result.fired, target);+ }+ return;+ }++ const result = try fireNavigateEvent(originator, target, resolved_url, true, opts);+ if (result == .canceled) {+ arena.release();return;}@@ -1110,6 +1139,16 @@ fn scheduleNavigationWithArena(originator: *Frame, arena: *lp.Arena, request_urltry History.firePopState(target, null);try target.queueHashChange(old_url, target.url);+ // don't defer this, the caller is responsible for freeing it on error+ arena.release();++ if (result == .fired) {+ try session.navigationFor(target).commitSameDocument(result.fired, target);+ }+ return;+ }++ if (try fireNavigateEvent(originator, target, resolved_url, false, opts) == .canceled) {// don't defer this, the caller is responsible for freeing it on errorarena.release();return;@@ -1131,6 +1170,8 @@ fn scheduleNavigationWithArena(originator: *Frame, arena: *lp.Arena, request_url// runs (processRootQueuedNavigation rebuilds the Page in-place), so// allocate from the QueuedNavigation arena which outlives that tear-down.var nav_opts = opts;+ nav_opts.source_element = null;+ nav_opts.form_data = null;const referrer_source = originator.referrerSource();if (std.mem.startsWith(u8, referrer_source, "http")) {if (nav_opts.referer == null) {@@ -1169,6 +1210,28 @@ fn scheduleNavigationWithArena(originator: *Frame, arena: *lp.Arena, request_urltarget.abortedDocumentIsComplete();}+// The navigate event of a navigation started by the page: a script, a link or+// a form. The browser's own (CDP) don't fire it, and the Navigation API's+// methods fire theirs.+fn fireNavigateEvent(originator: *Frame, target: *Frame, url: [:0]const u8, same_document: bool, opts: NavigateOpts) !NavigateEventResult {+ switch (opts.reason) {+ .address_bar, .history, .initialFrameNavigation, .navigation => return .not_fired,+ .anchor, .form, .script => {},+ }+ // Not shown to a document of another origin.+ if (target != originator and sameOrigin(originator, target) == false) {+ return .not_fired;+ }+ return target._session.navigationFor(target).fireNavigateEvent(.{+ .navigation_type = opts.kind.toNavigationType(),+ .url = url,+ .same_document = same_document,+ .source_element = opts.source_element,+ .form_data = opts.form_data,+ .user_initiated = opts.user_initiated,+ }, target);+}+// A script can have multiple competing navigation events, say it starts off// by doing top.location = 'x' and then does a form submission.// You might think that we just stop at the first one, but that doesn't seem@@ -1291,6 +1354,12 @@ fn neuter(self: *Frame) void {}pub fn stopLoading(self: *Frame) void {+ if (self._ongoing_navigate != null) {+ self._session.navigationFor(self).abortOngoing(self) catch |err| {+ log.debug(.frame, "stop abort navigation", .{ .err = err });+ };+ }+var i: usize = 0;while (i < self.child_frames.items.len) : (i += 1) {// Each frame will cancel its requests, which can fire JS callbacks@@ -3936,6 +4005,10 @@ pub const NavigateOpts = struct {initiator_origin: ?[]const u8 = null,force: bool = false,kind: NavigationKind = .{ .push = null },+ // For the navigate event, read by scheduleNavigation only.+ source_element: ?*Element = null,+ form_data: ?*FormData = null,+ user_initiated: bool = false,};pub const NavigatedOpts = struct {@@ -4061,6 +4134,8 @@ fn findFrameByName(frame: *Frame, name: []const u8) ?*Frame {const SubmitFormOpts = struct {fire_event: bool = true,+ // Submitted by a trusted (user) event.+ user_initiated: bool = false,};pub fn submitForm(self: *Frame, submitter_: ?*Element, form_: ?*Element.Html.Form, submit_opts: SubmitFormOpts) !void {const form = form_ orelse return;@@ -4141,8 +4216,6 @@ pub fn submitForm(self: *Frame, submitter_: ?*Element, form_: ?*Element.Html.For}}- const FormData = @import("webapi/net/FormData.zig");-// Resolved before the entry list is built: a hidden `_charset_` field// takes the submission encoding's name as its value.const charset: []const u8 = blk: {@@ -4236,8 +4309,11 @@ pub fn submitForm(self: *Frame, submitter_: ?*Element, form_: ?*Element.Html.Forvar opts = NavigateOpts{.reason = .form,.kind = .{ .push = null },+ .source_element = submitter_ orelse form_element,+ .user_initiated = submit_opts.user_initiated,};if (is_post) {+ opts.form_data = form_data;opts.method = .POST;opts.body = buf.written();opts.header = switch (encoding) {diff --git a/src/browser/frame/user_input.zig b/src/browser/frame/user_input.zigindex b0427d210..378bb52d3 100644--- a/src/browser/frame/user_input.zig+++ b/src/browser/frame/user_input.zig@@ -1284,14 +1284,15 @@ const JavascriptUrlTask = struct {// target is the element that's being activated. Imagine a span inside an anchor// the span is clicked (event_target), but it's the anchor that we're activating// (target).-pub fn handleClick(frame: *Frame, target: *Node, event_target: *Node) !void {+// user_initiated: a trusted click, for the navigate event it can start.+pub fn handleClick(frame: *Frame, target: *Node, event_target: *Node, user_initiated: bool) !void {// TODO: Also support <area> elements when implementconst element = target.is(Element) orelse return;if (element.is(Element.Svg.Graphics.A) != null) {const href = element.svgAnchorHref() orelse return;const target_name = element.getAttributeInterned("target") orelse "";- return followLink(frame, target, element, href, target_name);+ return followLink(frame, target, element, href, target_name, user_initiated);}const html_element = element.is(Element.Html) orelse return;@@ -1300,7 +1301,7 @@ pub fn handleClick(frame: *Frame, target: *Node, event_target: *Node) !void {.anchor => {const anchor = html_element.subtype(Element.Html.Anchor);const href = element.getAttributeInterned("href") orelse return;- return followLink(frame, target, element, href, anchor.getTarget());+ return followLink(frame, target, element, href, anchor.getTarget(), user_initiated);},.input => {const input = html_element.subtype(Element.Html.Input);@@ -1315,7 +1316,7 @@ pub fn handleClick(frame: *Frame, target: *Node, event_target: *Node) !void {if (element.isDisabled()) {return;}- return frame.submitForm(element, input.getForm(), .{});+ return frame.submitForm(element, input.getForm(), .{ .user_initiated = user_initiated });}if (input._input_type == .reset) {if (element.isDisabled()) {@@ -1331,7 +1332,7 @@ pub fn handleClick(frame: *Frame, target: *Node, event_target: *Node) !void {if (element.isDisabled()) {return;}- return frame.submitForm(element, button.getForm(), .{});+ return frame.submitForm(element, button.getForm(), .{ .user_initiated = user_initiated });}if (std.mem.eql(u8, button.getType(), "reset")) {if (element.isDisabled()) {@@ -1380,7 +1381,7 @@ pub fn handleClick(frame: *Frame, target: *Node, event_target: *Node) !void {}// Follow a link on activation. Shared by HTML <a> and SVG <a>.-fn followLink(frame: *Frame, target: *Node, element: *Element, href: []const u8, target_name: []const u8) !void {+fn followLink(frame: *Frame, target: *Node, element: *Element, href: []const u8, target_name: []const u8, user_initiated: bool) !void {if (href.len == 0) {return;}@@ -1410,6 +1411,8 @@ fn followLink(frame: *Frame, target: *Node, element: *Element, href: []const u8,try owner.scheduleNavigation(href, .{.reason = .script,.kind = .{ .push = null },+ .source_element = element,+ .user_initiated = user_initiated,}, .{ .anchor = target_frame });}@@ -1495,6 +1498,8 @@ pub fn textForKey(keyboard_event: *const KeyboardEvent) ?[]const u8 {/// `keypress` on `target` and, unless a listener cancels it, performs the/// text edit it stands for.pub fn typeChar(frame: *Frame, target: *Element, keypress: *KeyboardEvent, text: []const u8) !void {+ // read before dispatch, which can free the event+ const user_initiated = keypress.asEvent()._is_trusted;if (try frame._event_manager.dispatchCancelable(target.asEventTarget(), keypress.asEvent())) {return;}@@ -1506,7 +1511,7 @@ pub fn typeChar(frame: *Frame, target: *Element, keypress: *KeyboardEvent, text:if (target.is(Element.Html.Input)) |input| {if (is_enter) {try input.dispatchChangeIfEdited(frame);- return implicitFormSubmission(frame, input);+ return implicitFormSubmission(frame, input, user_initiated);}_ = try applyEdit(frame, input, .{ .insert = text });} else if (target.is(Element.Html.TextArea)) |textarea| {@@ -1518,7 +1523,7 @@ pub fn typeChar(frame: *Frame, target: *Element, keypress: *KeyboardEvent, text:/// its activation submits the form with it as the submitter; otherwise the/// form submits itself (SubmitEvent.submitter is null)./// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#implicit-submission-fn implicitFormSubmission(frame: *Frame, input: *Element.Html.Input) !void {+fn implicitFormSubmission(frame: *Frame, input: *Element.Html.Input, user_initiated: bool) !void {const form = input.getForm() orelse return;if (form.getDefaultButton(frame)) |button| {if (button.isDisabled()) {@@ -1529,7 +1534,7 @@ fn implicitFormSubmission(frame: *Frame, input: *Element.Html.Input) !void {if (!form.canSubmitImplicitly(input, frame)) {return;}- return frame.submitForm(form.asElement(), form, .{});+ return frame.submitForm(form.asElement(), form, .{ .user_initiated = user_initiated });}fn keypressFor(frame: *Frame, keydown: *const KeyboardEvent) !*KeyboardEvent {diff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zigindex 5e674ec84..c3e4314c2 100644--- a/src/browser/js/Context.zig+++ b/src/browser/js/Context.zig@@ -1188,6 +1188,17 @@ pub fn queueResizeDelivery(self: *Context) !void {}.run);}+pub fn queueNavigateSuccess(self: *Context) !void {+ self.enqueueMicrotask(struct {+ fn run(ctx: *Context) void {+ switch (ctx.global) {+ .frame => |frame| frame._session.navigationFor(frame).finishSameDocument(frame),+ .worker => unreachable,+ }+ }+ }.run);+}+pub fn queueCustomElementBackupDrain(self: *Context) !void {self.enqueueMicrotask(struct {fn run(ctx: *Context) void {diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex 9fbffa9c7..461805378 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -1182,6 +1182,7 @@ pub const PageJsApis = flattenTypes(&.{@import("../webapi/event/MessageEvent.zig"),@import("../webapi/event/ProgressEvent.zig"),@import("../webapi/event/NavigationCurrentEntryChangeEvent.zig"),+ @import("../webapi/event/NavigateEvent.zig"),@import("../webapi/event/PageTransitionEvent.zig"),@import("../webapi/event/PopStateEvent.zig"),@import("../webapi/event/HashChangeEvent.zig"),@@ -1283,6 +1284,7 @@ pub const PageJsApis = flattenTypes(&.{@import("../webapi/navigation/Navigation.zig"),@import("../webapi/navigation/NavigationHistoryEntry.zig"),@import("../webapi/navigation/NavigationActivation.zig"),+ @import("../webapi/navigation/NavigationDestination.zig"),@import("../webapi/canvas/CanvasRenderingContext2D.zig"),@import("../webapi/canvas/WebGLRenderingContext.zig"),@import("../webapi/canvas/OffscreenCanvas.zig"),diff --git a/src/browser/tests/navigation/navigate_event.html b/src/browser/tests/navigation/navigate_event.htmlnew file mode 100644index 000000000..8332ba1f4--- /dev/null+++ b/src/browser/tests/navigation/navigate_event.html@@ -0,0 +1,618 @@+<!DOCTYPE html>+<script src="../testing.js"></script>+<!--+ navigate_event_target.html doesn't exist on purpose: every navigation to it+ is canceled, superseded or stopped. A 404 for it means one leaked.+-->++<a id=link href="navigate_event_target.html?a">link</a>+<form id=post_form method=post action="navigate_event_target.html?f"><input name=x value=1><button id=post_submit>go</button></form>+<form id=get_form method=get action="navigate_event_target.html"><input name=y value=2></form>++<script>+ // The module scripts below interleave at each await, but they all change the+ // one document URL. Each takes a turn, and the next one starts after the+ // previous one releases it.+ // Resolves once the document is completely loaded: after the load event.+ const loaded = new Promise((resolve) => window.addEventListener('load', () => setTimeout(resolve)));++ // A task later, so the previous test's navigations are done.+ function settled() {+ return loaded.then(() => new Promise((resolve) => setTimeout(resolve)));+ }++ let turn = Promise.resolve();+ function takeTurn() {+ let release;+ const mine = new Promise((resolve) => { release = resolve; });+ const ready = turn.then(() => release);+ turn = mine;+ return ready;+ }++ // Records the navigate events fired while fn runs, cancelling them when+ // `cancel` is set. Restores the URL afterwards, which aborts a same-document+ // navigation still waiting for its navigatesuccess: `aborted` is each+ // event's signal state before that.+ function recordNavigations(fn, cancel) {+ const original = location.href;+ const events = [];+ const errors = [];+ const onnavigate = (e) => {+ events.push(e);+ if (cancel) {+ e.preventDefault();+ }+ };+ const onerror = (e) => errors.push(e);+ navigation.addEventListener('navigate', onnavigate);+ navigation.addEventListener('navigateerror', onerror);+ let aborted;+ try {+ fn();+ } finally {+ aborted = events.map((e) => e.signal.aborted);+ navigation.removeEventListener('navigate', onnavigate);+ navigation.removeEventListener('navigateerror', onerror);+ history.replaceState(null, '', original);+ }+ return {events, errors, aborted};+ }++ function relative(url) {+ return url.replace(location.origin, '');+ }++ const PAGE = location.pathname;+ const DIR = PAGE.replace(/[^/]*$/, '');+</script>++<script id=interfaces>+ testing.expectEqual('function', typeof NavigateEvent);+ testing.expectEqual('function', typeof NavigationDestination);+ testing.withError((err) => testing.expectEqual('TypeError', err.name), () => new NavigationDestination());+ testing.withError((err) => testing.expectEqual('TypeError', err.name), () => new NavigateEvent('navigate'));++ const {events} = recordNavigations(() => history.pushState(null, '', '?interfaces'));+ const e = events[0];+ testing.expectTrue(e instanceof NavigateEvent);+ testing.expectTrue(e.destination instanceof NavigationDestination);+ testing.expectEqual(e.destination, e.destination);++ const signal = new AbortController().signal;+ const constructed = new NavigateEvent('navigate', {destination: e.destination, signal: signal, navigationType: 'reload', info: 5});+ testing.expectEqual('reload', constructed.navigationType);+ testing.expectEqual(e.destination, constructed.destination);+ testing.expectEqual(signal, constructed.signal);+ testing.expectEqual(5, constructed.info);+ testing.expectFalse(constructed.isTrusted);+ testing.expectFalse(constructed.cancelable);+</script>++<script id=push_state>+ {+ const order = [];+ const oncurrent = () => order.push('currententrychange');+ const {events, aborted} = recordNavigations(() => {+ navigation.addEventListener('currententrychange', oncurrent);+ navigation.addEventListener('navigate', () => order.push('navigate:' + location.search), {once: true});+ history.pushState({s: 1}, '', '?pushed');+ navigation.removeEventListener('currententrychange', oncurrent);+ });++ testing.expectEqual(['navigate:', 'currententrychange'], order);+ testing.expectEqual(1, events.length);+ const e = events[0];+ testing.expectEqual('navigate', e.type);+ testing.expectEqual('push', e.navigationType);+ testing.expectEqual(PAGE + '?pushed', relative(e.destination.url));+ testing.expectEqual('', e.destination.key);+ testing.expectEqual('', e.destination.id);+ testing.expectEqual(-1, e.destination.index);+ testing.expectTrue(e.destination.sameDocument);+ testing.expectEqual(undefined, e.destination.getState());+ testing.expectFalse(e.hashChange);+ testing.expectFalse(e.userInitiated);+ testing.expectTrue(e.cancelable);+ testing.expectFalse(e.bubbles);+ testing.expectTrue(e.isTrusted);+ testing.expectEqual(null, e.formData);+ testing.expectEqual(null, e.sourceElement);+ testing.expectEqual(null, e.downloadRequest);+ testing.expectEqual(undefined, e.info);+ testing.expectFalse(e.hasUAVisualTransition);+ testing.expectEqual([false], aborted);+ }+</script>++<script id=replace_state>+ {+ const {events} = recordNavigations(() => history.replaceState(null, '', '?replaced'));+ testing.expectEqual(1, events.length);+ testing.expectEqual('replace', events[0].navigationType);+ testing.expectTrue(events[0].destination.sameDocument);+ }+</script>++<script id=history_fragment_not_hash_change>+ {+ // pushState/replaceState never report a hashChange, even for a fragment.+ const {events} = recordNavigations(() => {+ history.pushState(null, '', '#frag1');+ history.replaceState({a: 1}, '', '#frag2');+ });+ testing.expectEqual(['push', 'replace'], events.map((e) => e.navigationType));+ testing.expectEqual([false, false], events.map((e) => e.hashChange));+ }+</script>++<script id=reload_keeps_state>+ {+ const before = navigation.currentEntry.getState();+ navigation.updateCurrentEntry({state: {s: 7}});+ let state;+ recordNavigations(() => {+ navigation.addEventListener('navigate', (e) => state = e.destination.getState(), {once: true});+ navigation.reload().committed.catch(() => {});+ }, true);+ testing.expectEqual({s: 7}, state);+ navigation.updateCurrentEntry({state: before});+ }+</script>++<script id=cancel_push_state>+ {+ const before = location.href;+ const length = history.length;+ let url_in_listener;+ const {events, errors} = recordNavigations(() => {+ navigation.addEventListener('navigate', () => url_in_listener = location.href, {once: true});+ history.pushState(null, '', '?canceled');+ testing.expectEqual(before, location.href);+ }, true);++ testing.expectEqual(before, url_in_listener);+ testing.expectEqual(length, history.length);+ testing.expectEqual(1, events.length);+ testing.expectTrue(events[0].signal.aborted);+ testing.expectEqual(1, errors.length);+ testing.expectTrue(errors[0] instanceof ErrorEvent);+ testing.expectEqual('AbortError', errors[0].error.name);+ testing.expectEqual('Navigation was aborted', errors[0].error.message);+ testing.expectEqual(events[0].signal.reason, errors[0].error);+ }+</script>++<script id=superseded>+ {+ // Nothing waits for the first one's navigatesuccess microtask before the+ // second starts: the second aborts it.+ const {events, errors, aborted} = recordNavigations(() => {+ history.pushState(null, '', '?first');+ history.pushState(null, '', '?second');+ });+ testing.expectEqual(2, events.length);+ testing.expectEqual([true, false], aborted);+ testing.expectEqual(1, errors.length);+ }+</script>++<script id=navigate_success_async type=module>+ {+ const my_turn = takeTurn();+ const state = await testing.async();+ const release = await my_turn;+ const order = [];+ const original = location.href;+ navigation.addEventListener('navigatesuccess', () => order.push('navigatesuccess'), {once: true});+ history.pushState(null, '', '?success');+ order.push('sync');+ setTimeout(() => {+ history.replaceState(null, '', original);+ release();+ state.resolve(order);+ });+ state.done((order) => testing.expectEqual(['sync', 'navigatesuccess'], order));+ }+</script>++<script id=hash>+ {+ // Until the document is completely loaded, a Location navigation replaces+ // its entry.+ const length = history.length;+ const {events} = recordNavigations(() => {+ location.hash = '#h1';+ // the same fragment doesn't navigate+ location.hash = '#h1';+ testing.expectEqual(length, history.length);+ });+ testing.expectEqual(1, events.length);+ testing.expectEqual('replace', events[0].navigationType);+ testing.expectTrue(events[0].hashChange);+ testing.expectTrue(events[0].destination.sameDocument);+ }+</script>++<script id=hash_after_load type=module>+ {+ const my_turn = takeTurn();+ const state = await testing.async();+ const release = await my_turn;+ await settled();+ // A push creates an entry with a new key, a replace keeps the key. (Not+ // history.length: Chrome caps it at 50.)+ const key = navigation.currentEntry.key;+ let pushed;+ const {events} = recordNavigations(() => {+ location.hash = '#loaded';+ pushed = navigation.currentEntry.key !== key;+ });+ release();+ state.resolve({events, pushed});+ state.done(({events, pushed}) => {+ testing.expectEqual(1, events.length);+ testing.expectEqual('push', events[0].navigationType);+ testing.expectTrue(pushed);+ });+ }+</script>++<script id=cancel_hash>+ {+ const length = history.length;+ const {events} = recordNavigations(() => {+ location.hash = '#canceled';+ testing.expectEqual('', location.hash);+ }, true);+ testing.expectEqual(1, events.length);+ testing.expectEqual(length, history.length);+ }+</script>++<script id=navigation_navigate type=module>+ {+ const my_turn = takeTurn();+ const state = await testing.async();+ const release = await my_turn;+ const original = location.href;+ const events = [];+ const order = [];+ const onnavigate = (e) => events.push(e);+ const onsuccess = () => order.push('navigatesuccess');+ navigation.addEventListener('navigate', onnavigate);+ navigation.addEventListener('navigatesuccess', onsuccess);++ const r = navigation.navigate('#n1', {info: 'I', state: {k: 1}});+ Promise.all([+ r.committed.then(() => order.push('committed')),+ r.finished.then(() => order.push('finished')),+ ]).then(() => {+ navigation.removeEventListener('navigate', onnavigate);+ navigation.removeEventListener('navigatesuccess', onsuccess);+ history.replaceState(null, '', original);+ release();+ state.resolve();+ });++ state.done(() => {+ testing.expectEqual(1, events.length);+ const e = events[0];+ testing.expectEqual('push', e.navigationType);+ testing.expectEqual('I', e.info);+ testing.expectEqual({k: 1}, e.destination.getState());+ testing.expectTrue(e.hashChange);+ testing.expectTrue(order.includes('navigatesuccess'));+ testing.expectEqual(order.indexOf('navigatesuccess') < order.indexOf('finished'), true);+ });+ }+</script>++<script id=cancel_navigation_navigate type=module>+ {+ const my_turn = takeTurn();+ const state = await testing.async();+ const release = await my_turn;+ const original = location.href;+ let event;+ let error_event;+ navigation.addEventListener('navigate', (e) => {+ event = e;+ e.preventDefault();+ }, {once: true});+ navigation.addEventListener('navigateerror', (e) => error_event = e, {once: true});++ const r = navigation.navigate('#n2', {info: 'J'});+ Promise.all([+ r.committed.then(() => 'resolved', (err) => err),+ r.finished.then(() => 'resolved', (err) => err),+ ]).then((results) => {+ release();+ state.resolve(results);+ });++ state.done(([committed, finished]) => {+ testing.expectEqual(original, location.href);+ testing.expectEqual('J', event.info);+ testing.expectEqual('AbortError', committed.name);+ testing.expectEqual(committed, finished);+ testing.expectEqual(committed, event.signal.reason);+ testing.expectEqual(committed, error_event.error);+ });+ }+</script>++<script id=committed_before_currententrychange type=module>+ {+ // currententrychange fires after the committed promise resolved: a+ // navigation its listener starts aborts only the finished promise.+ const my_turn = takeTurn();+ const state = await testing.async();+ const release = await my_turn;++ const original = location.href;+ navigation.addEventListener('currententrychange', () => history.pushState(null, '', '#inner'), {once: true});+ const r = navigation.navigate('#outer');+ const results = await Promise.all([+ r.committed.then(() => 'resolved', (e) => 'rejected ' + e.name),+ r.finished.then(() => 'resolved', (e) => 'rejected ' + e.name),+ ]);+ history.replaceState(null, '', original);+ release();+ state.resolve(results);++ state.done((results) => testing.expectEqual(['resolved', 'rejected AbortError'], results));+ }+</script>++<script id=cross_document_cancel>+ {+ const before = location.href;+ const {events} = recordNavigations(() => {+ location.href = 'navigate_event_target.html?x';+ location.replace('navigate_event_target.html?r');+ location.reload();+ document.getElementById('link').click();+ location.href = 'javascript:void 0';+ }, true);++ testing.expectEqual(before, location.href);+ testing.expectEqual(4, events.length);+ const summary = events.map((e) => [e.navigationType, relative(e.destination.url), e.destination.sameDocument]);+ // During the load, replace: see the hash test+ testing.expectEqual([+ ['replace', DIR + 'navigate_event_target.html?x', false],+ ['replace', DIR + 'navigate_event_target.html?r', false],+ ['reload', relative(before), false],+ ['push', DIR + 'navigate_event_target.html?a', false],+ ], summary);++ testing.expectEqual(document.getElementById('link'), events[3].sourceElement);+ testing.expectEqual(null, events[3].formData);++ for (const e of events) {+ testing.expectTrue(e.cancelable);+ testing.expectFalse(e.hashChange);+ testing.expectFalse(e.userInitiated);+ }+ }+</script>++<script id=form_submission type=module>+ {+ // Chrome fires a form's navigate event in a task, we fire it right away.+ const my_turn = takeTurn();+ const state = await testing.async();+ const release = await my_turn;++ function submitted(submit) {+ return new Promise((resolve) => {+ navigation.addEventListener('navigate', (e) => {+ e.preventDefault();+ resolve(e);+ }, {once: true});+ submit();+ });+ }+ const post = await submitted(() => document.getElementById('post_submit').click());+ const get = await submitted(() => document.getElementById('get_form').submit());+ release();+ state.resolve({post, get});++ state.done(({post, get}) => {+ testing.expectEqual('push', post.navigationType);+ testing.expectEqual(DIR + 'navigate_event_target.html?f', relative(post.destination.url));+ testing.expectFalse(post.destination.sameDocument);+ // POST form: its entries and its submitter+ testing.expectEqual(document.getElementById('post_submit'), post.sourceElement);+ testing.expectEqual([['x', '1']], [...post.formData]);++ testing.expectEqual(DIR + 'navigate_event_target.html?y=2', relative(get.destination.url));+ // GET form, no submitter+ testing.expectEqual(document.getElementById('get_form'), get.sourceElement);+ testing.expectEqual(null, get.formData);+ });+ }+</script>++<script id=cross_document_superseded type=module>+ {+ // window.stop() while parsing would abort the document's load.+ const my_turn = takeTurn();+ const state = await testing.async();+ const release = await my_turn;+ await settled();++ const before = location.href;+ let first;+ let first_aborted_before;+ const {events, errors} = recordNavigations(() => {+ // Not canceled: it stays ongoing until the next navigation aborts it.+ navigation.addEventListener('navigate', (e) => first = e, {once: true});+ location.href = 'navigate_event_target.html?s1';+ first_aborted_before = first.signal.aborted;++ navigation.addEventListener('navigate', (e) => e.preventDefault(), {once: true});+ location.href = 'navigate_event_target.html?s2';++ // Like Chrome, aborting the first one's event doesn't stop its load:+ // stop it to stay on this page.+ window.stop();+ });+ release();+ state.resolve();++ state.done(() => {+ testing.expectEqual(before, location.href);+ testing.expectEqual(2, events.length);+ testing.expectEqual('push', events[0].navigationType);+ testing.expectFalse(first_aborted_before);+ testing.expectTrue(first.signal.aborted);+ // the first one superseded, the second one canceled+ testing.expectEqual(2, errors.length);+ });+ }+</script>++<script id=stop type=module>+ {+ const my_turn = takeTurn();+ const state = await testing.async();+ const release = await my_turn;+ await settled();++ let event;+ const {errors} = recordNavigations(() => {+ navigation.addEventListener('navigate', (e) => event = e, {once: true});+ location.href = 'navigate_event_target.html?stopped';+ window.stop();+ });+ release();+ state.resolve();++ state.done(() => {+ testing.expectTrue(event.signal.aborted);+ testing.expectEqual(1, errors.length);+ });+ }+</script>++<script id=navigation_in_listener>+ {+ // A navigation started by a listener aborts the one being dispatched.+ const {events, errors, aborted} = recordNavigations(() => {+ navigation.addEventListener('navigate', (e) => {+ history.pushState(null, '', '?inner');+ }, {once: true});+ location.href = 'navigate_event_target.html?outer';+ testing.expectEqual('?inner', location.search);+ });+ testing.expectEqual(2, events.length);+ testing.expectTrue(events[0].defaultPrevented);+ testing.expectEqual([true, false], aborted);+ testing.expectEqual(1, errors.length);+ }+</script>++<script id=traverse type=module>+ {+ // Chrome traverses in a task, we do it right away.+ const my_turn = takeTurn();+ const state = await testing.async();+ const release = await my_turn;+ await settled();++ const original = location.href;+ history.pushState({t: 1}, '', '?t1');+ history.pushState({t: 2}, '', '?t2');+ const target = navigation.entries()[navigation.currentEntry.index - 1];++ const pops = [];+ const onpop = () => pops.push(location.search);+ window.addEventListener('popstate', onpop);+ const nextTask = () => new Promise((resolve) => setTimeout(resolve));++ const canceled = await new Promise((resolve) => {+ navigation.addEventListener('navigate', (e) => {+ e.preventDefault();+ resolve(e);+ }, {once: true});+ history.back();+ });+ await nextTask();+ const after_cancel = [location.search, pops.length];++ // [destination's, target's] read together: Chrome prunes history at 50+ // entries, which shifts indexes.+ let index_in_dispatch;+ const traversed = await new Promise((resolve) => {+ navigation.addEventListener('navigate', (e) => {+ index_in_dispatch = [e.destination.index, target.index];+ resolve(e);+ }, {once: true});+ history.back();+ });+ await nextTask();+ const after_traverse = [location.search, pops.slice()];++ window.removeEventListener('popstate', onpop);+ history.replaceState(null, '', original);+ release();+ state.resolve();++ state.done(() => {+ testing.expectEqual('traverse', canceled.navigationType);+ testing.expectEqual(['?t2', 0], after_cancel);++ testing.expectEqual(['?t1', ['?t1']], after_traverse);+ testing.expectEqual('traverse', traversed.navigationType);+ testing.expectEqual(target.key, traversed.destination.key);+ testing.expectEqual(target.id, traversed.destination.id);+ testing.expectEqual(index_in_dispatch[1], index_in_dispatch[0]);+ testing.expectTrue(index_in_dispatch[0] >= 0);+ // live: the replaceState above took the entry out of the history+ testing.expectEqual(-1, traversed.destination.index);+ // a pushState entry has no Navigation API state+ testing.expectEqual(undefined, traversed.destination.getState());+ testing.expectTrue(traversed.destination.sameDocument);+ testing.expectTrue(traversed.cancelable);+ });+ }+</script>++<script id=onnavigate>+ {+ let count = 0;+ recordNavigations(() => {+ navigation.onnavigate = () => count += 1;+ history.pushState(null, '', '?handler');+ navigation.onnavigate = null;+ });+ testing.expectEqual(1, count);+ }+</script>++<script id=intercept_not_supported>+ {+ // Chrome differs: canIntercept is true there. We don't support intercept().+ let in_dispatch;+ let scroll_in_dispatch;+ const {events} = recordNavigations(() => {+ navigation.addEventListener('navigate', (e) => {+ try { e.intercept(); } catch (err) { in_dispatch = err; }+ try { e.scroll(); } catch (err) { scroll_in_dispatch = err; }+ }, {once: true});+ history.pushState(null, '', '?intercept');+ });+ const e = events[0];+ testing.expectFalse(e.canIntercept);+ testing.expectEqual('SecurityError', in_dispatch.name);+ testing.expectEqual('InvalidStateError', scroll_in_dispatch.name);+ testing.expectEqual('intercept() must be called before scroll()', scroll_in_dispatch.message);++ testing.withError((err) => {+ testing.expectEqual('InvalidStateError', err.name);+ testing.expectEqual('intercept() may only be called while the navigate event is being dispatched.', err.message);+ }, () => e.intercept());+ }+</script>diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zigindex 96631d010..fe74ff528 100644--- a/src/browser/webapi/Document.zig+++ b/src/browser/webapi/Document.zig@@ -156,7 +156,7 @@ pub fn getLocation(self: *const Document) ?*Location {fn setLocation(self: *Document, url: [:0]const u8) !void {if (self._type != .html) return;const frame = self._frame orelse return;- return frame.scheduleNavigation(url, .{ .reason = .script, .kind = .{ .push = null } }, .{ .script = frame });+ return frame.scheduleNavigation(url, .{ .reason = .script, .kind = Location.historyHandling(frame) }, .{ .script = frame });}// Approximation of quirks mode: an HTML document without a doctype is in quirks mode.diff --git a/src/browser/webapi/Event.zig b/src/browser/webapi/Event.zigindex a58107787..807c8a4ad 100644--- a/src/browser/webapi/Event.zig+++ b/src/browser/webapi/Event.zig@@ -85,6 +85,7 @@ pub const Type = union(enum) {message_event: *@import("event/MessageEvent.zig"),progress_event: *@import("event/ProgressEvent.zig"),navigation_current_entry_change_event: *@import("event/NavigationCurrentEntryChangeEvent.zig"),+ navigate_event: *@import("event/NavigateEvent.zig"),page_transition_event: *@import("event/PageTransitionEvent.zig"),pop_state_event: *@import("event/PopStateEvent.zig"),hash_change_event: *@import("event/HashChangeEvent.zig"),@@ -216,6 +217,7 @@ pub fn is(self: *Event, comptime T: type) ?*T {.message_event => |e| return if (T == @import("event/MessageEvent.zig")) e else null,.progress_event => |e| return if (T == @import("event/ProgressEvent.zig")) e else null,.navigation_current_entry_change_event => |e| return if (T == @import("event/NavigationCurrentEntryChangeEvent.zig")) e else null,+ .navigate_event => |e| return if (T == @import("event/NavigateEvent.zig")) e else null,.page_transition_event => |e| return if (T == @import("event/PageTransitionEvent.zig")) e else null,.pop_state_event => |e| return if (T == @import("event/PopStateEvent.zig")) e else null,.hash_change_event => |e| return if (T == @import("event/HashChangeEvent.zig")) e else null,diff --git a/src/browser/webapi/History.zig b/src/browser/webapi/History.zigindex 813d384f4..f30d2884a 100644--- a/src/browser/webapi/History.zig+++ b/src/browser/webapi/History.zig@@ -64,7 +64,14 @@ pub fn pushState(self: *History, state: js.Value, _: ?[]const u8, _url: ?[]consttry arena.dupeSentinel(u8, target.url, 0);const json = state.toJson(arena.allocator()) catch return error.DataClone;- _ = try session.navigationFor(target).pushEntry(url, .{ .source = .history, .value = json }, target, true);++ const navigation = session.navigationFor(target);+ const result = try navigation.fireNavigateEvent(.{ .navigation_type = .push, .url = url, .same_document = true, .classic_history = true }, target);+ if (result == .canceled) {+ return;+ }++ _ = try navigation.pushEntry(url, .{ .source = .history, .value = json }, target, true);target.url = url;// setHref == reinitializing.@@ -77,6 +84,10 @@ pub fn pushState(self: *History, state: js.Value, _: ?[]const u8, _url: ?[]const.frame_id = target._frame_id,.navigation_type = .historyApi,});++ if (result == .fired) {+ try navigation.commitSameDocument(result.fired, target);+ }}fn replaceState(self: *History, state: js.Value, _: ?[]const u8, _url: ?[]const u8) !void {@@ -90,7 +101,14 @@ fn replaceState(self: *History, state: js.Value, _: ?[]const u8, _url: ?[]consttry arena.dupeSentinel(u8, target.url, 0);const json = state.toJson(arena.allocator()) catch return error.DataClone;- _ = try session.navigationFor(target).replaceEntry(url, .{ .source = .history, .value = json }, target, true);++ const navigation = session.navigationFor(target);+ const result = try navigation.fireNavigateEvent(.{ .navigation_type = .replace, .url = url, .same_document = true, .classic_history = true }, target);+ if (result == .canceled) {+ return;+ }++ _ = try navigation.replaceEntry(url, .{ .source = .history, .value = json }, target, true);target.url = url;// setHref == reinitializing.@@ -103,6 +121,10 @@ fn replaceState(self: *History, state: js.Value, _: ?[]const u8, _url: ?[]const.frame_id = target._frame_id,.navigation_type = .historyApi,});++ if (result == .fired) {+ try navigation.commitSameDocument(result.fired, target);+ }}fn goInner(delta: i32, frame: *Frame) !void {@@ -121,9 +143,10 @@ fn goInner(delta: i32, frame: *Frame) !void {// document replaces this one instead.const same_document = entry.sameDocument(frame);- _ = try navigation.navigateInner(entry._url, .{ .traverse = index }, frame);+ _ = try navigation.navigateInner(entry._url, .{ .traverse = index }, .{ .api_method = false }, frame);- if (same_document) {+ // The index doesn't move when the navigate event was canceled.+ if (same_document and navigation._index == index) {try firePopState(frame, entry._state.value);// hashchange is queued by navigateInner.}diff --git a/src/browser/webapi/Location.zig b/src/browser/webapi/Location.zigindex 58e63f33c..a41c19ee5 100644--- a/src/browser/webapi/Location.zig+++ b/src/browser/webapi/Location.zig@@ -24,6 +24,7 @@ const Page = @import("../Page.zig");const URL = @import("URL.zig");const U = @import("../URL.zig");const Frame = @import("../Frame.zig");+const NavigationKind = @import("navigation/root.zig").NavigationKind;const Location = @This();@@ -86,12 +87,20 @@ pub fn getHash(self: *const Location) []const u8 {return self._url.getHash();}+pub fn historyHandling(target: *const Frame) NavigationKind {+ if (target.isCompletelyLoaded()) {+ return .{ .push = null };+ }+ // if the document isn't completely loaded, a navigation replaces its entry.+ return .{ .replace = null };+}+pub fn setPathname(self: *const Location, pathname: []const u8, frame: *Frame) !void {const target = self._frame;const new_url = try U.setPathname(target.url, pathname, frame.call_arena);return target.scheduleNavigation(new_url, .{.reason = .script,- .kind = .{ .push = null },+ .kind = historyHandling(target),}, .{ .script = target });}@@ -100,7 +109,7 @@ fn setSearch(self: *const Location, search: []const u8, frame: *Frame) !void {const new_url = try U.setSearch(target.url, search, frame.call_arena);return target.scheduleNavigation(new_url, .{.reason = .script,- .kind = .{ .push = null },+ .kind = historyHandling(target),}, .{ .script = target });}@@ -136,7 +145,7 @@ fn setHash(self: *const Location, hash: []const u8, frame: *Frame) !void {return target.scheduleNavigation(target_url, .{.reason = .script,- .kind = .{ .replace = null },+ .kind = historyHandling(target),}, .{ .script = target });}@@ -155,7 +164,7 @@ fn parseFromCaller(self: *const Location, url: [:0]const u8, frame: *Frame) ![]cpub fn assign(self: *const Location, url: [:0]const u8, frame: *Frame) !void {const target_url = try self.parseFromCaller(url, frame);- return self._frame.scheduleNavigation(target_url, .{ .reason = .script, .kind = .{ .push = null } }, .{ .script = self._frame });+ return self._frame.scheduleNavigation(target_url, .{ .reason = .script, .kind = historyHandling(self._frame) }, .{ .script = self._frame });}pub fn replace(self: *const Location, url: [:0]const u8, frame: *Frame) !void {diff --git a/src/browser/webapi/event/NavigateEvent.zig b/src/browser/webapi/event/NavigateEvent.zignew file mode 100644index 000000000..346b24052--- /dev/null+++ b/src/browser/webapi/event/NavigateEvent.zig@@ -0,0 +1,251 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");+const lp = @import("lightpanda");++const js = @import("../../js/js.zig");+const Page = @import("../../Page.zig");+const Frame = @import("../../Frame.zig");++const Event = @import("../Event.zig");+const Element = @import("../Element.zig");+const AbortSignal = @import("../AbortSignal.zig");+const DOMException = @import("../DOMException.zig");+const FormData = @import("../net/FormData.zig");+const NavigationType = @import("../navigation/root.zig").NavigationType;+const NavigationDestination = @import("../navigation/NavigationDestination.zig");++const String = lp.String;++// https://developer.mozilla.org/en-US/docs/Web/API/NavigateEvent+const NavigateEvent = @This();++pub const Proto = Event;++_proto: *Event,+_navigation_type: NavigationType,+_destination: *NavigationDestination,+_can_intercept: bool, // TODO. Not supported, currently always false+_user_initiated: bool,+_hash_change: bool,+_signal: *AbortSignal,+_form_data: ?*FormData,+_download_request: ?[]const u8,+_info: ?js.Value.Global,+_has_ua_visual_transition: bool,+_source_element: ?*Element,++const NavigateEventOptions = struct {+ canIntercept: bool = false,+ destination: *NavigationDestination,+ downloadRequest: ?[]const u8 = null,+ formData: ?*FormData = null,+ hasUAVisualTransition: bool = false,+ hashChange: bool = false,+ info: ?js.Value.Global = null,+ navigationType: []const u8 = "push",+ signal: *AbortSignal,+ sourceElement: ?*Element = null,+ userInitiated: bool = false,+};++pub const Options = Event.inheritOptions(NavigateEvent, NavigateEventOptions);++pub fn init(typ: []const u8, opts: Options, frame: *Frame) !*NavigateEvent {+ const arena = try frame.getArena(.tiny, "NavigateEvent");+ errdefer arena.release();+ const type_string = try String.init(arena.allocator(), typ, .{});+ return initWithTrusted(arena, type_string, opts, false, frame);+}++pub fn initTrusted(opts: Options, frame: *Frame) !*NavigateEvent {+ const arena = try frame.getArena(.tiny, "NavigateEvent.trusted");+ errdefer arena.release();+ return initWithTrusted(arena, comptime .wrap("navigate"), opts, true, frame);+}++fn initWithTrusted(arena: *lp.Arena, typ: String, opts: Options, trusted: bool, frame: *Frame) !*NavigateEvent {+ const navigation_type = std.meta.stringToEnum(NavigationType, opts.navigationType) orelse return error.TypeError;+ const download_request = if (opts.downloadRequest) |dr| try arena.dupe(u8, dr) else null;++ const event = try frame._factory.event(+ arena,+ typ,+ NavigateEvent{+ ._proto = undefined,+ ._navigation_type = navigation_type,+ ._destination = opts.destination,+ ._can_intercept = opts.canIntercept,+ ._user_initiated = opts.userInitiated,+ ._hash_change = opts.hashChange,+ ._signal = opts.signal,+ ._form_data = opts.formData,+ ._download_request = download_request,+ ._info = opts.info,+ ._has_ua_visual_transition = opts.hasUAVisualTransition,+ ._source_element = opts.sourceElement,+ },+ );+ if (opts.formData) |fd| {+ fd.acquireRef();+ }++ Event.populatePrototypes(event, opts, trusted);+ return event;+}++pub fn deinit(self: *NavigateEvent, page: *Page) void {+ if (self._info) |info| {+ info.release();+ }+ if (self._form_data) |fd| {+ fd.releaseRef(page);+ }+ self._proto.deinit(page);+}++pub fn acquireRef(self: *NavigateEvent) void {+ self._proto.acquireRef();+}++pub fn releaseRef(self: *NavigateEvent, page: *Page) void {+ self._proto._rc.release(self, page);+}++pub fn asEvent(self: *NavigateEvent) *Event {+ return self._proto;+}++fn getNavigationType(self: *const NavigateEvent) []const u8 {+ return @tagName(self._navigation_type);+}++fn getDestination(self: *const NavigateEvent) *NavigationDestination {+ return self._destination;+}++fn getCanIntercept(self: *const NavigateEvent) bool {+ return self._can_intercept;+}++fn getUserInitiated(self: *const NavigateEvent) bool {+ return self._user_initiated;+}++fn getHashChange(self: *const NavigateEvent) bool {+ return self._hash_change;+}++fn getSignal(self: *const NavigateEvent) *AbortSignal {+ return self._signal;+}++fn getFormData(self: *const NavigateEvent) ?*FormData {+ return self._form_data;+}++fn getDownloadRequest(self: *const NavigateEvent) ?[]const u8 {+ return self._download_request;+}++const InfoReturn = union(enum) { value: js.Value.Global, undefined: void };++fn getInfo(self: *const NavigateEvent) InfoReturn {+ const info = self._info orelse return .undefined;+ return .{ .value = info };+}++fn getHasUAVisualTransition(self: *const NavigateEvent) bool {+ return self._has_ua_visual_transition;+}++fn getSourceElement(self: *const NavigateEvent) ?*Element {+ return self._source_element;+}++const Thrown = union(enum) { exception: js.Exception, undefined: void };++// The messages match Chrome's.+fn sharedChecks(self: *const NavigateEvent, comptime method: []const u8, frame: *Frame) ?js.Exception {+ const local = frame.js.local.?;+ const event = self._proto;+ if (event._is_trusted == false) {+ return local.newException(DOMException.init(method ++ "() may only be called on a trusted event.", "SecurityError"));+ }+ if (event._prevent_default) {+ return local.newException(DOMException.init(method ++ "() may not be called if the event has been canceled.", "InvalidStateError"));+ }+ // A trusted navigate event is being dispatched while it's the ongoing+ // navigation's (direct dispatch doesn't set the event phase).+ if (frame._ongoing_navigate) |ongoing| {+ if (ongoing.event == self) {+ return null;+ }+ }+ return local.newException(DOMException.init(method ++ "() may only be called while the navigate event is being dispatched.", "InvalidStateError"));+}++// Not supported: canIntercept is always false, so this always throws.+fn intercept(self: *const NavigateEvent, _: ?js.Value, frame: *Frame) !Thrown {+ const local = frame.js.local.?;+ if (self.sharedChecks("intercept", frame)) |exception| {+ return .{ .exception = exception };+ }++ if (self._can_intercept == false) {+ const message = try frame.page_arena.print(+ "A navigation with URL '{s}' cannot be intercepted by in a window with origin '{s}' and URL '{s}'.",+ .{ self._destination._url, frame.origin orelse "null", frame.url },+ );+ return .{ .exception = local.newException(DOMException.init(message, "SecurityError")) };+ }+ return .undefined;+}++fn scroll(self: *const NavigateEvent, frame: *Frame) Thrown {+ if (self.sharedChecks("scroll", frame)) |exception| {+ return .{ .exception = exception };+ }+ // Only an intercepted navigation can be scrolled, and we never intercept.+ return .{ .exception = frame.js.local.?.newException(DOMException.init("intercept() must be called before scroll()", "InvalidStateError")) };+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(NavigateEvent);++ pub const Meta = struct {+ pub const name = "NavigateEvent";+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const constructor = bridge.constructor(NavigateEvent.init, .{});+ pub const navigationType = bridge.accessor(NavigateEvent.getNavigationType, null, .{});+ pub const destination = bridge.accessor(NavigateEvent.getDestination, null, .{});+ pub const canIntercept = bridge.accessor(NavigateEvent.getCanIntercept, null, .{});+ pub const userInitiated = bridge.accessor(NavigateEvent.getUserInitiated, null, .{});+ pub const hashChange = bridge.accessor(NavigateEvent.getHashChange, null, .{});+ pub const signal = bridge.accessor(NavigateEvent.getSignal, null, .{});+ pub const formData = bridge.accessor(NavigateEvent.getFormData, null, .{});+ pub const downloadRequest = bridge.accessor(NavigateEvent.getDownloadRequest, null, .{});+ pub const info = bridge.accessor(NavigateEvent.getInfo, null, .{});+ pub const hasUAVisualTransition = bridge.accessor(NavigateEvent.getHasUAVisualTransition, null, .{});+ pub const sourceElement = bridge.accessor(NavigateEvent.getSourceElement, null, .{});+ pub const intercept = bridge.function(NavigateEvent.intercept, .{});+ pub const scroll = bridge.function(NavigateEvent.scroll, .{});+};diff --git a/src/browser/webapi/navigation/Navigation.zig b/src/browser/webapi/navigation/Navigation.zigindex b26d9bc57..7e0cd1e5a 100644--- a/src/browser/webapi/navigation/Navigation.zig+++ b/src/browser/webapi/navigation/Navigation.zig@@ -25,8 +25,13 @@ const Frame = @import("../../Frame.zig");const Factory = @import("../../Factory.zig");const Event = @import("../Event.zig");+const Element = @import("../Element.zig");const EventTarget = @import("../EventTarget.zig");+const AbortSignal = @import("../AbortSignal.zig");+const DOMException = @import("../DOMException.zig");+const FormData = @import("../net/FormData.zig");const ErrorEvent = @import("../event/ErrorEvent.zig");+const NavigateEvent = @import("../event/NavigateEvent.zig");const log = lp.log;@@ -35,12 +40,15 @@ const Navigation = @This();pub const Proto = EventTarget;+const NavigationType = @import("root.zig").NavigationType;const NavigationKind = @import("root.zig").NavigationKind;const NavigationActivation = @import("NavigationActivation.zig");const NavigationTransition = @import("root.zig").NavigationTransition;const NavigationState = @import("root.zig").NavigationState;+const OngoingNavigation = @import("root.zig").OngoingNavigation;const NavigationHistoryEntry = @import("NavigationHistoryEntry.zig");+const NavigationDestination = @import("NavigationDestination.zig");const NavigationCurrentEntryChangeEvent = @import("../event/NavigationCurrentEntryChangeEvent.zig");_proto: *EventTarget,@@ -99,7 +107,11 @@ const NavigationReturn = struct {finished: js.Promise.Global,};-pub fn back(self: *Navigation, frame: *Frame) !NavigationReturn {+const NavigationOptions = struct {+ info: ?js.Value = null,+};++pub fn back(self: *Navigation, _opts: ?NavigationOptions, frame: *Frame) !NavigationReturn {if (!self.getCanGoBack()) {return error.InvalidStateError;}@@ -107,14 +119,15 @@ pub fn back(self: *Navigation, frame: *Frame) !NavigationReturn {const new_index = self._index - 1;const next_entry = self._entries.items[new_index];- return self.navigateInner(next_entry._url, .{ .traverse = new_index }, frame);+ const opts = _opts orelse NavigationOptions{};+ return self.navigateInner(next_entry._url, .{ .traverse = new_index }, .{ .info = opts.info }, frame);}pub fn entries(self: *const Navigation) []*NavigationHistoryEntry {return self._entries.items;}-pub fn forward(self: *Navigation, frame: *Frame) !NavigationReturn {+pub fn forward(self: *Navigation, _opts: ?NavigationOptions, frame: *Frame) !NavigationReturn {if (!self.getCanGoForward()) {return error.InvalidStateError;}@@ -122,7 +135,8 @@ pub fn forward(self: *Navigation, frame: *Frame) !NavigationReturn {const new_index = self._index + 1;const next_entry = self._entries.items[new_index];- return self.navigateInner(next_entry._url, .{ .traverse = new_index }, frame);+ const opts = _opts orelse NavigationOptions{};+ return self.navigateInner(next_entry._url, .{ .traverse = new_index }, .{ .info = opts.info }, frame);}pub fn updateEntries(@@ -303,6 +317,221 @@ pub fn replaceEntry(return entry;}+pub const NavigateEventParams = struct {+ navigation_type: NavigationType,+ url: [:0]const u8,+ same_document: bool,+ // The entry a traversal goes to.+ entry: ?*NavigationHistoryEntry = null,+ // Serialized state given to navigation.navigate() or reload().+ state: ?[]const u8 = null,+ info: ?js.Value = null,+ source_element: ?*Element = null,+ // The entry list of a POST form submission.+ form_data: ?*FormData = null,+ user_initiated: bool = false,+ // pushState/replaceState: never a hashChange, even for a fragment-only URL.+ classic_history: bool = false,+ // The promises of a Navigation API method.+ committed: ?js.PromiseResolver = null,+ finished: ?js.PromiseResolver = null,+};++pub const NavigateEventResult = union(enum) {+ // Don't navigate: a listener canceled the event, or started a navigation+ // that aborted this one.+ canceled,+ // No event: an iframe, the initial about:blank, or nothing could observe it.+ not_fired,+ // Navigate. A same-document navigation then calls commitSameDocument.+ fired: *AbortSignal,+};++// Fires `navigate` at a navigation about to happen in `frame`, aborting the+// ongoing one first.+// https://html.spec.whatwg.org/multipage/nav-history-apis.html#inner-navigate-event-firing-algorithm+pub fn fireNavigateEvent(self: *Navigation, params: NavigateEventParams, frame: *Frame) !NavigateEventResult {+ // A page has one Navigation, shared by its iframes. An iframe's own+ // navigations must not show up on it.+ if (frame.parent != null) {+ return .not_fired;+ }+ // The initial about:blank has "entries and events disabled".+ if (self._initial_entry) {+ return .not_fired;+ }++ try self.abortOngoing(frame);++ const target = self.asEventTarget();+ if (params.finished == null and+ frame.hasDirectListeners(target, "navigate") == false and+ frame.hasDirectListeners(target, "navigateerror") == false and+ frame.hasDirectListeners(target, "navigatesuccess") == false)+ {+ return .not_fired;+ }++ const destination = try frame.page_arena.create(NavigationDestination);+ destination.* = .{+ ._url = try frame.page_arena.dupe(u8, params.url),+ ._same_document = params.same_document,+ ._state = params.state,+ };+ if (params.entry) |entry| {+ destination._entry = entry;+ destination._state = entry.navigationState();+ }++ // A fragment change: the URLs differ only by their fragment.+ const hash_change = params.same_document and+ params.classic_history == false and+ URL.eqlDocument(frame.url, params.url) and+ std.mem.eql(u8, frame.url, params.url) == false;++ const signal = try AbortSignal.init(&frame.js.execution);+ const event = try NavigateEvent.initTrusted(.{+ // A traversal to another document can't be canceled.+ .cancelable = params.navigation_type != .traverse or params.same_document,+ .navigationType = @tagName(params.navigation_type),+ .destination = destination,+ .userInitiated = params.user_initiated,+ .hashChange = hash_change,+ .signal = signal,+ .formData = params.form_data,+ .info = if (params.info) |info| try info.persist() else null,+ .sourceElement = params.source_element,+ }, frame);+ event.acquireRef();+ defer event.releaseRef(frame.page);++ frame._ongoing_navigate = .{+ .signal = signal,+ .event = event,+ .committed = if (params.committed) |c| try c.persist() else null,+ .finished = if (params.finished) |f| try f.persist() else null,+ };++ {+ errdefer if (ongoingFor(signal, frame)) |ongoing| {+ ongoing.event = null;+ };+ try self.dispatch(event.asEvent(), frame);+ }++ // Gone when a listener started a navigation, which aborted this one.+ const ongoing = ongoingFor(signal, frame) orelse return .canceled;+ ongoing.event = null;++ if (event.asEvent().getDefaultPrevented()) {+ try self.abortOngoing(frame);+ return .canceled;+ }++ if (params.same_document == false) {+ // The promises of a navigation to another document never settle: this+ // document goes away. It stays ongoing until then, so that a newer+ // navigation or window.stop() still aborts it.+ ongoing.releasePromises();+ }+ return .{ .fired = signal };+}++fn ongoingFor(signal: *AbortSignal, frame: *Frame) ?*OngoingNavigation {+ if (frame._ongoing_navigate) |*ongoing| {+ if (ongoing.signal == signal) {+ return ongoing;+ }+ }+ return null;+}++// https://html.spec.whatwg.org/multipage/nav-history-apis.html#abort-the-ongoing-navigation+pub fn abortOngoing(self: *Navigation, frame: *Frame) !void {+ var ongoing = frame._ongoing_navigate orelse return;+ frame._ongoing_navigate = null;+ defer ongoing.releasePromises();++ if (ongoing.event) |event| {+ // Aborted by one of its own listeners: the event is now canceled.+ event.asEvent()._prevent_default = true;+ }++ // One instance, so the signal's reason, navigateerror's error and the+ // rejections are the same object. The message matches Chrome's.+ const dom = try frame.page_arena.create(DOMException);+ dom.* = .init("Navigation was aborted", "AbortError");+ try ongoing.signal.abort(.{ .dom = dom }, &frame.js.execution);++ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ const local = &ls.local;++ const err = try local.zigValueToJs(dom, .{});+ try self.fireNavigateError(err, frame);++ if (ongoing.committed) |c| {+ c.local(local).rejectValue(err) catch |e| {+ log.debug(.event, "Navigation.abort committed", .{ .err = e });+ };+ }+ if (ongoing.finished) |f| {+ f.local(local).rejectValue(err) catch |e| {+ log.debug(.event, "Navigation.abort finished", .{ .err = e });+ };+ }+}++// A same-document navigation updated the URL and entries: the committed+// promise resolves now, navigatesuccess and the finished promise follow in a+// microtask.+pub fn commitSameDocument(_: *Navigation, signal: *AbortSignal, frame: *Frame) !void {+ // Gone when the commit steps (currententrychange, popstate) started a+ // navigation that aborted this one.+ resolveCommitted(signal, frame);+ const ongoing = ongoingFor(signal, frame) orelse return;+ ongoing.committed_same_document = true;+ try frame.js.queueNavigateSuccess();+}++// Before the entry update: its currententrychange listeners can start a+// navigation that aborts this one, which mustn't reject the committed promise.+fn resolveCommitted(signal: *AbortSignal, frame: *Frame) void {+ const ongoing = ongoingFor(signal, frame) orelse return;+ const committed = ongoing.committed orelse return;+ ongoing.committed = null;+ defer committed.release();++ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ committed.local(&ls.local).resolve("navigation committed", {});+}++// The microtask queued by commitSameDocument.+pub fn finishSameDocument(self: *Navigation, frame: *Frame) void {+ var ongoing = frame._ongoing_navigate orelse return;+ if (ongoing.committed_same_document == false) {+ // A newer navigation replaced it+ return;+ }++ frame._ongoing_navigate = null;+ defer ongoing.releasePromises();++ self.fireNavigateSuccess(frame) catch |err| {+ log.debug(.event, "Navigation.navigatesuccess", .{ .err = err });+ };++ if (ongoing.finished) |f| {+ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ f.local(&ls.local).resolve("navigation finished", {});+ }+}+fn fireNavigateSuccess(self: *Navigation, frame: *Frame) !void {if (!frame.hasDirectListeners(self.asEventTarget(), "navigatesuccess")) {return;@@ -320,6 +549,20 @@ fn fireNavigateSuccess(self: *Navigation, frame: *Frame) !void {try self.dispatch(event, frame);}+fn fireNavigateError(self: *Navigation, err: js.Value, frame: *Frame) !void {+ if (!frame.hasDirectListeners(self.asEventTarget(), "navigateerror")) {+ return;+ }++ const event = try ErrorEvent.initTrusted(.wrap("navigateerror"), .{+ .@"error" = try err.persist(),+ .message = "AbortError: Navigation was aborted",+ .filename = frame.url,+ }, frame.page);++ try self.dispatch(event.asEvent(), frame);+}+fn fireCurrentEntryChangeEvent(self: *Navigation,previous: *NavigationHistoryEntry,@@ -346,26 +589,26 @@ fn fireCurrentEntryChangeEvent(try self.dispatch(event.asEvent(), frame);}-fn resolveFinished(- self: *Navigation,- resolver: js.PromiseResolver,- comptime source: []const u8,- frame: *Frame,-) !void {- resolver.resolve(source, {});- try self.fireNavigateSuccess(frame);-}-const NavigateOptions = struct {history: ?[]const u8 = null,info: ?js.Value = null,state: ?js.Value = null,};+// The options of a Navigation API method, for its navigate event.+const ApiOptions = struct {+ info: ?js.Value = null,+ // Serialized, reload()'s. navigate()'s is in its NavigationKind.+ state: ?[]const u8 = null,+ // false for history.back()/forward()/go(), which return no promises.+ api_method: bool = true,+};+pub fn navigateInner(self: *Navigation,_url: ?[:0]const u8,kind: NavigationKind,+ api: ApiOptions,frame: *Frame,) !NavigationReturn {const arena = frame._session.arena;@@ -378,14 +621,17 @@ pub fn navigateInner(const local = frame.js.local.?;const committed = local.createPromiseResolver();const finished = local.createPromiseResolver();+ // Per spec, a rejection is reported through the committed promise only.+ finished.promise().markAsHandled();var new_url = try URL.resolve(arena.allocator(), frame.url, url, .{});const is_same_url = URL.eqlDocument(new_url, frame.url);// navigate() stays in the document only for a fragment change, but a// traversal stays in it whenever the entry belongs to it, whatever URL- // pushState gave the entry.+ // pushState gave the entry. A reload never does.const is_same_document = switch (kind) {.traverse => |index| self._entries.items[index].sameDocument(frame),+ .reload => false,else => is_same_url,};@@ -396,13 +642,39 @@ pub fn navigateInner(new_url = try arena.dupeSentinel(u8, new_url, 0);}+ const result = try self.fireNavigateEvent(.{+ .navigation_type = kind.toNavigationType(),+ .url = new_url,+ .same_document = is_same_document,+ .entry = switch (kind) {+ .traverse => |index| self._entries.items[index],+ else => null,+ },+ .state = switch (kind) {+ .push, .replace => |state| state,+ // reload() without a state keeps the current entry's+ .reload => api.state orelse self.getCurrentEntry().navigationState(),+ .traverse => null,+ },+ .info = api.info,+ .committed = if (api.api_method) committed else null,+ .finished = if (api.api_method) finished else null,+ }, frame);++ const signal: ?*AbortSignal = switch (result) {+ // aborting the navigation rejected the promises+ .canceled => return returnPromises(committed, finished),+ .not_fired => null,+ .fired => |signal| signal,+ };+// Captured before a same-document navigation overwrites frame.url; used// to queue the hashchange once below.const old_url = frame.url;const previous = self.getCurrentEntry();- if (is_same_document and kind != .reload) {+ if (is_same_document) {frame.url = new_url;frame._session.notification.dispatch(.frame_navigated_within_document, &.{@@ -410,25 +682,27 @@ pub fn navigateInner(.frame_id = frame._frame_id,.navigation_type = .fragment,});++ if (signal) |s| {+ resolveCommitted(s, frame);+ } else {+ committed.resolve("navigation committed", {});+ }}switch (kind) {.push => |state| {if (is_same_document) {- committed.resolve("navigation push", {});- // todo: Fire navigate event_ = try self.pushEntry(url, .{ .source = .navigation, .value = state }, frame, true);- try self.resolveFinished(finished, "navigation push", frame);+ try self.settleSameDocument(finished, signal, frame);} else {try frame.scheduleNavigation(url, .{ .reason = .navigation, .kind = kind }, .{ .script = frame });}},.replace => |state| {if (is_same_document) {- committed.resolve("navigation replace", {});- // todo: Fire navigate event_ = try self.replaceEntry(url, .{ .source = .navigation, .value = state }, frame, true);- try self.resolveFinished(finished, "navigation replace", frame);+ try self.settleSameDocument(finished, signal, frame);} else {try frame.scheduleNavigation(url, .{ .reason = .navigation, .kind = kind }, .{ .script = frame });}@@ -441,15 +715,17 @@ pub fn navigateInner(// `:target` matches off the fragment, which might have just changed.frame.styleChanged();- committed.resolve("navigation traverse", {});- // todo: Fire navigate eventtry self.fireCurrentEntryChangeEvent(previous, kind, frame);- try self.resolveFinished(finished, "navigation traverse", frame);+ try self.settleSameDocument(finished, signal, frame);} else {try frame.scheduleNavigation(url, .{ .reason = .navigation, .kind = kind }, .{ .script = frame });}},.reload => {+ if (api.state) |state| {+ previous._state = .{ .source = .navigation, .value = state };+ try self.fireCurrentEntryChangeEvent(previous, .reload, frame);+ }try frame.scheduleNavigation(url, .{ .reason = .navigation, .kind = kind }, .{ .script = frame });},}@@ -458,8 +734,24 @@ pub fn navigateInner(try frame.queueHashChange(old_url, new_url);}- _ = try committed.persist();- _ = try finished.persist();+ return returnPromises(committed, finished);+}++fn settleSameDocument(+ self: *Navigation,+ finished: js.PromiseResolver,+ signal: ?*AbortSignal,+ frame: *Frame,+) !void {+ if (signal) |s| {+ return self.commitSameDocument(s, frame);+ }+ // No navigate event fired, nothing can abort it.+ finished.resolve("navigation finished", {});+ try self.fireNavigateSuccess(frame);+}++fn returnPromises(committed: js.PromiseResolver, finished: js.PromiseResolver) !NavigationReturn {return .{.committed = try committed.promise().persist(),.finished = try finished.promise().persist(),@@ -476,7 +768,7 @@ pub fn navigate(self: *Navigation, _url: [:0]const u8, _opts: ?NavigateOptions,else.{ .push = json };- return try self.navigateInner(_url, kind, frame);+ return try self.navigateInner(_url, kind, .{ .info = opts.info }, frame);}const ReloadOptions = struct {@@ -488,31 +780,16 @@ pub fn reload(self: *Navigation, _opts: ?ReloadOptions, frame: *Frame) !Navigaticonst arena = frame._session.arena;const opts = _opts orelse ReloadOptions{};- const entry = self.getCurrentEntry();- if (opts.state) |state| {- const previous = entry;- entry._state = .{- .source = .navigation,- .value = state.toJson(arena.allocator()) catch return error.DataClone,- };- try self.fireCurrentEntryChangeEvent(previous, .reload, frame);- }+ const state = if (opts.state) |state| state.toJson(arena.allocator()) catch return error.DataClone else null;- return self.navigateInner(entry._url, .reload, frame);+ return self.navigateInner(self.getCurrentEntry()._url, .reload, .{ .info = opts.info, .state = state }, frame);}-const TraverseToOptions = struct {- info: ?js.Value = null,-};--pub fn traverseTo(self: *Navigation, key: []const u8, _opts: ?TraverseToOptions, frame: *Frame) !NavigationReturn {- if (_opts != null) {- log.debug(.not_implemented, "Navigation.traverseTo", .{ .has_options = true });- }-+pub fn traverseTo(self: *Navigation, key: []const u8, _opts: ?NavigationOptions, frame: *Frame) !NavigationReturn {+ const opts = _opts orelse NavigationOptions{};for (self._entries.items, 0..) |entry, i| {if (std.mem.eql(u8, key, entry._key)) {- return try self.navigateInner(entry._url, .{ .traverse = i }, frame);+ return try self.navigateInner(entry._url, .{ .traverse = i }, .{ .info = opts.info }, frame);}}@@ -560,6 +837,7 @@ pub const JsApi = struct {pub const traverseTo = bridge.function(Navigation.traverseTo, .{});pub const updateCurrentEntry = bridge.function(Navigation.updateCurrentEntry, .{});+ pub const onnavigate = EventTarget.handlerAccessor(Navigation, "navigate");pub const oncurrententrychange = EventTarget.handlerAccessor(Navigation, "currententrychange");pub const onnavigatesuccess = EventTarget.handlerAccessor(Navigation, "navigatesuccess");pub const onnavigateerror = EventTarget.handlerAccessor(Navigation, "navigateerror");@@ -620,3 +898,7 @@ test "Navigation: reload on empty stack seeds an entry" {);try testing.expect(result.isTrue());}++test "WebApi: NavigateEvent" {+ try testing.htmlRunner("navigation", .{});+}diff --git a/src/browser/webapi/navigation/NavigationDestination.zig b/src/browser/webapi/navigation/NavigationDestination.zignew file mode 100644index 000000000..8c71432d8--- /dev/null+++ b/src/browser/webapi/navigation/NavigationDestination.zig@@ -0,0 +1,78 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const js = @import("../../js/js.zig");+const Frame = @import("../../Frame.zig");++const NavigationHistoryEntry = @import("NavigationHistoryEntry.zig");++// https://developer.mozilla.org/en-US/docs/Web/API/NavigationDestination+const NavigationDestination = @This();++_url: []const u8,+_entry: ?*NavigationHistoryEntry = null,+_same_document: bool,+// null for the History API and plain navigations (getState() is then undefined)+_state: ?[]const u8 = null,++fn getUrl(self: *const NavigationDestination) []const u8 {+ return self._url;+}++fn getKey(self: *const NavigationDestination) []const u8 {+ const entry = self._entry orelse return "";+ return entry._key;+}++fn getId(self: *const NavigationDestination) []const u8 {+ const entry = self._entry orelse return "";+ return entry._id;+}++// Live, like Chrome: -1 once the entry has left the history.+fn getIndex(self: *const NavigationDestination, frame: *Frame) i64 {+ const entry = self._entry orelse return -1;+ return entry.index(frame);+}++fn getSameDocument(self: *const NavigationDestination) bool {+ return self._same_document;+}++const StateReturn = union(enum) { value: ?js.Value, undefined: void };++fn getState(self: *const NavigationDestination, frame: *Frame) !StateReturn {+ const state = self._state orelse return .undefined;+ return .{ .value = try frame.js.local.?.parseJSON(state) };+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(NavigationDestination);++ pub const Meta = struct {+ pub const name = "NavigationDestination";+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const url = bridge.accessor(NavigationDestination.getUrl, null, .{});+ pub const key = bridge.accessor(NavigationDestination.getKey, null, .{});+ pub const id = bridge.accessor(NavigationDestination.getId, null, .{});+ pub const index = bridge.accessor(NavigationDestination.getIndex, null, .{});+ pub const sameDocument = bridge.accessor(NavigationDestination.getSameDocument, null, .{});+ pub const getState = bridge.function(NavigationDestination.getState, .{});+};diff --git a/src/browser/webapi/navigation/NavigationHistoryEntry.zig b/src/browser/webapi/navigation/NavigationHistoryEntry.zigindex 7af0c906b..dc5c5d18b 100644--- a/src/browser/webapi/navigation/NavigationHistoryEntry.zig+++ b/src/browser/webapi/navigation/NavigationHistoryEntry.zig@@ -74,16 +74,19 @@ pub fn url(self: *const NavigationHistoryEntry) ?[:0]const u8 {return self._url;}-const StateReturn = union(enum) { value: ?js.Value, undefined: void };--pub fn getState(self: *const NavigationHistoryEntry, frame: *Frame) !StateReturn {+// The serialized Navigation API state, not the History API's.+pub fn navigationState(self: *const NavigationHistoryEntry) ?[]const u8 {if (self._state.source == .navigation) {- if (self._state.value) |value| {- return .{ .value = try frame.js.local.?.parseJSON(value) };- }+ return self._state.value;}+ return null;+}++const StateReturn = union(enum) { value: ?js.Value, undefined: void };- return .undefined;+pub fn getState(self: *const NavigationHistoryEntry, frame: *Frame) !StateReturn {+ const state = self.navigationState() orelse return .undefined;+ return .{ .value = try frame.js.local.?.parseJSON(state) };}pub fn fireDispose(self: *NavigationHistoryEntry, frame: *Frame) !void {diff --git a/src/browser/webapi/navigation/root.zig b/src/browser/webapi/navigation/root.zigindex 26c963ace..8dadad0ab 100644--- a/src/browser/webapi/navigation/root.zig+++ b/src/browser/webapi/navigation/root.zig@@ -20,6 +20,8 @@ const std = @import("std");const js = @import("../../js/js.zig");+const AbortSignal = @import("../AbortSignal.zig");+const NavigateEvent = @import("../event/NavigateEvent.zig");const NavigationHistoryEntry = @import("NavigationHistoryEntry.zig");pub const NavigationType = enum {@@ -51,3 +53,26 @@ pub const NavigationTransition = struct {from: NavigationHistoryEntry,navigation_type: NavigationType,};++// Frame._ongoing_navigate. Aborted by a new navigation, window.stop() or+// canceling the event.+pub const OngoingNavigation = struct {+ signal: *AbortSignal,+ // Only set while the event is being dispatched+ event: ?*NavigateEvent = null,+ // Promises of navigation.navigate()/reload()/traverseTo()/back()/forward()+ committed: ?js.PromiseResolver.Global = null,+ finished: ?js.PromiseResolver.Global = null,+ committed_same_document: bool = false,++ pub fn releasePromises(self: *OngoingNavigation) void {+ if (self.committed) |c| {+ c.release();+ self.committed = null;+ }+ if (self.finished) |f| {+ f.release();+ self.finished = null;+ }+ }+};