Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add onNavigate lifecycle function, to enable view transitions #9605

Merged
merged 27 commits into from
Aug 29, 2023
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fifty-plants-repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': minor
---

feat: onNavigate lifecycle function
1 change: 1 addition & 0 deletions packages/kit/src/runtime/app/navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ export const invalidateAll = BROWSER ? client.invalidateAll : guard('invalidateA
export const preloadData = BROWSER ? client.preload_data : guard('preloadData');
export const preloadCode = BROWSER ? client.preload_code : guard('preloadCode');
export const beforeNavigate = BROWSER ? client.before_navigate : () => {};
export const onNavigate = BROWSER ? client.on_navigate : () => {};
export const afterNavigate = BROWSER ? client.after_navigate : () => {};
92 changes: 70 additions & 22 deletions packages/kit/src/runtime/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ export function create_client(app, target) {
/** @type {Array<(navigation: import('types').BeforeNavigate) => void>} */
before_navigate: [],

/** @type {Array<(navigation: import('types').OnNavigate) => import('types').MaybePromise<(() => void) | void>>} */
on_navigate: [],

/** @type {Array<(navigation: import('types').AfterNavigate) => void>} */
after_navigate: []
};
Expand Down Expand Up @@ -261,6 +264,7 @@ export function create_client(app, target) {
* @param {import('./types').NavigationIntent | undefined} intent
* @param {URL} url
* @param {string[]} redirect_chain
* @param {import('types').NavigationType} [type]
* @param {number} [previous_history_index]
* @param {{hash?: string, scroll: { x: number, y: number } | null, keepfocus: boolean, details: { replaceState: boolean, state: any } | null}} [opts]
* @param {{}} [nav_token] To distinguish between different navigation events and determine the latest. Needed for example for redirects to keep the original token
Expand All @@ -270,6 +274,7 @@ export function create_client(app, target) {
intent,
url,
redirect_chain,
type,
previous_history_index,
opts,
nav_token = {},
Expand Down Expand Up @@ -372,13 +377,40 @@ export function create_client(app, target) {
load_cache = null;

if (started) {
const navigation = /** @type {import('types').OnNavigate} */ (
create_navigation(
current,
intent,
url,
/** @type {import('types').NavigationType} */ (type)
)
);

current = navigation_result.state;

// reset url before updating page store
if (navigation_result.props.page) {
navigation_result.props.page.url = url;
}

const after_navigate = (
await Promise.all(callbacks.on_navigate.map((fn) => fn(navigation)))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we consider what happens here if any of these callbacks reject? Or at least document the behavior? I'm not sure if it's the right behavior, but right now a rejected promise will prevent the navigation from completing.

).filter((value) => typeof value === 'function');

if (after_navigate.length > 0) {
function cleanup() {
callbacks.after_navigate = callbacks.after_navigate.filter(
// @ts-ignore
(fn) => !after_navigate.includes(fn)
);
}

after_navigate.push(cleanup);

// @ts-ignore
callbacks.after_navigate.push(...after_navigate);
}

root.$set(navigation_result.props);
} else {
initialize(navigation_result);
Expand Down Expand Up @@ -1072,20 +1104,7 @@ export function create_client(app, target) {
let should_block = false;

/** @type {import('types').Navigation} */
const navigation = {
from: {
params: current.params,
route: { id: current.route?.id ?? null },
url: current.url
},
to: {
params: intent?.params ?? null,
route: { id: intent?.route?.id ?? null },
url
},
willUnload: !intent,
type
};
const navigation = create_navigation(current, intent, url, type);

if (delta !== undefined) {
navigation.delta = delta;
Expand Down Expand Up @@ -1158,6 +1177,7 @@ export function create_client(app, target) {
intent,
url,
redirect_chain,
type,
previous_history_index,
{
scroll,
Expand Down Expand Up @@ -1364,6 +1384,17 @@ export function create_client(app, target) {
});
},

on_navigate: (fn) => {
onMount(() => {
callbacks.on_navigate.push(fn);

return () => {
const i = callbacks.on_navigate.indexOf(fn);
callbacks.on_navigate.splice(i, 1);
};
});
},

disable_scroll_handling: () => {
if (DEV && started && !updating) {
throw new Error('Can only disable scroll handling during navigation');
Expand Down Expand Up @@ -1473,14 +1504,7 @@ export function create_client(app, target) {
// it's due to an external or full-page-reload link, for which we don't want to call the hook again.
/** @type {import('types').BeforeNavigate} */
const navigation = {
from: {
params: current.params,
route: { id: current.route?.id ?? null },
url: current.url
},
to: null,
willUnload: true,
type: 'leave',
...create_navigation(current, undefined, null, 'leave'),
cancel: () => (should_block = true)
};

Expand Down Expand Up @@ -1941,6 +1965,30 @@ function reset_focus() {
}
}

/**
* @param {import('./types').NavigationState} current
* @param {import('./types').NavigationIntent | undefined} intent
* @param {URL | null} url
* @param {import('types').NavigationType} type
* @returns {import('types').Navigation}
*/
function create_navigation(current, intent, url, type) {
return {
from: {
params: current.params,
route: { id: current.route?.id ?? null },
url: current.url
},
to: url && {
params: intent?.params ?? null,
route: { id: intent?.route?.id ?? null },
url
},
willUnload: !intent,
type
};
}

if (DEV) {
// Nasty hack to silence harmless warnings the user can do nothing about
const console_warn = console.warn;
Expand Down
2 changes: 2 additions & 0 deletions packages/kit/src/runtime/client/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { applyAction } from '$app/forms';
import {
afterNavigate,
beforeNavigate,
onNavigate,
goto,
invalidate,
invalidateAll,
Expand Down Expand Up @@ -51,6 +52,7 @@ export interface Client {
// public API, exposed via $app/navigation
after_navigate: typeof afterNavigate;
before_navigate: typeof beforeNavigate;
on_navigate: typeof onNavigate;
disable_scroll_handling(): void;
goto: typeof goto;
invalidate: typeof invalidate;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@
</script>

<h1>{from?.url.pathname} -> {to?.url.pathname}</h1>
<a href="/after-navigate/b">/b</a>
<a href="/navigation-lifecycle/after-navigate/b">/b</a>
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@
</script>

<h1>{from?.url.pathname} -> {to?.url.pathname}</h1>
<a href="/after-navigate/a">/a</a>
<a href="/navigation-lifecycle/after-navigate/a">/a</a>
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
</script>

<h1>prevent navigation</h1>
<a href="/before-navigate/a">a</a>
<a href="/before-navigate/redirect">redirect</a>
<a href="/before-navigate/prevent-navigation?x=1">self</a>
<a href="/navigation-lifecycle/before-navigate/a">a</a>
<a href="/navigation-lifecycle/before-navigate/redirect">redirect</a>
<a href="/navigation-lifecycle/before-navigate/prevent-navigation?x=1">self</a>
<a href="https://google.com" target="_blank" rel="noreferrer">_blank</a>
<a href="https://google.de">external</a>
<pre>{times_triggered} {unload} {navigation_type}</pre>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { redirect } from '@sveltejs/kit';

export function load() {
throw redirect(307, '/navigation-lifecycle/before-navigate/prevent-navigation');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<script>
import { onNavigate } from '$app/navigation';

/** @type {import('@sveltejs/kit').NavigationTarget} */
let from;

/** @type {import('@sveltejs/kit').NavigationTarget} */
let to;

/** @type {Omit<import('@sveltejs/kit').NavigationType, 'enter' | 'leave'>} */
let type;

onNavigate((navigation) => {
from = navigation.from;
to = navigation.to;
type = navigation.type;
});
</script>

<h1>{from?.url.pathname} -> {to?.url.pathname} ({type ?? '...'})</h1>
<a href="/navigation-lifecycle/on-navigate/b">/b</a>