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

Shallow routing #11307

Merged
merged 34 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
5a3ed3f
shallow routing
Rich-Harris Dec 14, 2023
f93c41c
add types
Rich-Harris Dec 14, 2023
cbc33e9
drive-by fix - bad merge
Rich-Harris Dec 14, 2023
48cec22
warn on use of history.pushState and history.replaceState
Rich-Harris Dec 14, 2023
eaa539b
regenerate types
Rich-Harris Dec 14, 2023
efe9f00
make url the first argument, even though it's optional — this is more…
Rich-Harris Dec 14, 2023
b3abca5
tests
Rich-Harris Dec 14, 2023
2cd0d8e
remove state from goto
Rich-Harris Dec 14, 2023
711ee3e
Merge branch 'version-2' into shallow-routing-version-2
Rich-Harris Dec 14, 2023
45d6e87
tidy up
Rich-Harris Dec 14, 2023
1e18fb5
Merge branch 'version-2' into shallow-routing-version-2
benmccann Dec 14, 2023
22489bf
tidy up internal navigate API a bit
Rich-Harris Dec 14, 2023
2900902
more
Rich-Harris Dec 14, 2023
3fcabe2
use current.url for invalidation, not location.href
Rich-Harris Dec 14, 2023
4a88ae6
Merge branch 'shallow-routing-version-2' of github.com:sveltejs/kit i…
Rich-Harris Dec 14, 2023
0d25f49
add docs
Rich-Harris Dec 14, 2023
4135f2a
copy-paste fail
Rich-Harris Dec 14, 2023
f4f38f2
on second thoughts
Rich-Harris Dec 14, 2023
dc6f168
links
Rich-Harris Dec 14, 2023
0ce07b9
link
Rich-Harris Dec 14, 2023
f6b42ba
regenerate types
Rich-Harris Dec 14, 2023
7af49f9
update preloadData docs
Rich-Harris Dec 14, 2023
c76c150
fix preloadData docs
Rich-Harris Dec 14, 2023
dad37a7
drive-by fix
Rich-Harris Dec 14, 2023
3f31983
Apply suggestions from code review
dummdidumm Dec 14, 2023
89c3161
tweaks
dummdidumm Dec 14, 2023
f93df90
changeset, breaking change docs
dummdidumm Dec 14, 2023
54fdf2d
code-golf
dummdidumm Dec 14, 2023
f9354c5
this seems unnecessary
dummdidumm Dec 14, 2023
edecbe6
mention preloadData
dummdidumm Dec 14, 2023
f4152ef
use original replace state
dummdidumm Dec 14, 2023
82d6737
oops
dummdidumm Dec 14, 2023
3a2ff3b
handle SPA case
dummdidumm Dec 14, 2023
5c6e6ae
more involved example - show importing a +page.svelte and correctly h…
Rich-Harris Dec 14, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/light-moons-dress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sveltejs/kit": minor
---

feat: implement shallow routing
5 changes: 5 additions & 0 deletions .changeset/serious-months-happen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sveltejs/kit": major
---

breaking: remove state option from goto in favor of shallow routing
97 changes: 97 additions & 0 deletions documentation/docs/30-advanced/67-shallow-routing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
---
title: Shallow routing
---

As you navigate around a SvelteKit app, you create _history entries_. Clicking the back and forward buttons traverses through this list of entries, re-running any `load` functions and replacing page components as necessary.

Sometimes, it's useful to create history entries _without_ navigating. For example, you might want to show a modal dialog that the user can dismiss by navigating back. This is particularly valuable on mobile devices, where swipe gestures are often more natural than interacting directly with the UI. In these cases, a modal that is _not_ associated with a history entry can be a source of frustration, as a user may swipe backwards in an attempt to dismiss it and find themselves on the wrong page.

SvelteKit makes this possible with the [`pushState`](/docs/modules#$app-navigation-pushstate) and [`replaceState`](/docs/modules#$app-navigation-replacestate) functions, which allow you to associate state with a history entry without navigating. For example, to implement a history-driven modal:

```svelte
<!--- file: +page.svelte --->
<script>
import { pushState } from '$app/navigation';
import { page } from '$app/stores';
import Modal from './Modal.svelte';

function showModal() {
pushState('', {
showModal: true
});
}
</script>

{#if $page.state.showModal}
<Modal close={() => history.back()} />
{/if}
```

The modal can be dismissed by navigating back (unsetting `$page.state.showModal`) or by interacting with it in a way that causes the `close` callback to run, which will navigate back programmatically.

## API

The first argument to `pushState` is the URL, relative to the current URL. To stay on the current URL, use `''`.

The second argument is the new page state, which can be accessed via the [page store](/docs/modules#$app-stores-page) as `$page.state`. You can make page state type-safe by declaring an [`App.PageState`](/docs/types#app) interface (usually in `src/app.d.ts`).

To set page state without creating a new history entry, use `replaceState` instead of `pushState`.

## Loading data for a route

When shallow routing, you may want to render another `+page.svelte` inside the current page. For example, clicking on a photo thumbnail could pop up the detail view without navigating to the photo page.

For this to work, you need to load the data that the `+page.svelte` expects. A convenient way to do this is to use [`preloadData`](/docs/modules#$app-navigation-preloaddata) inside the `click` handler of an `<a>` element. If the element (or a parent) uses [`data-sveltekit-preload-data`](/docs/link-options#data-sveltekit-preload-data), the data will have already been requested, and `preloadData` will reuse that request.

```svelte
<!--- file: src/routes/photos/+page.svelte --->
<script>
import { preloadData, pushState, goto } from '$app/navigation';
import Modal from './Modal.svelte';
import PhotoPage from './[id]/+page.svelte';

export let data;
</script>

{#each data.thumbnails as thumbnail}
<a
href="/photos/{thumbnail.id}"
on:click={async (e) => {
// bail if opening a new tab, or we're on too small a screen
if (e.metaKey || innerWidth < 640) return;

// prevent navigation
e.preventDefault();

const { href } = e.currentTarget;

// run `load` functions (or rather, get the result of the `load` functions
// that are already running because of `data-sveltekit-preload-data`)
const result = await preloadData(href);

if (result.type === 'loaded' && result.status === 200) {
pushState(href, { selected: result.data });
} else {
// something bad happened! try navigating
goto(href);
}
}}
>
<img alt={thumbnail.alt} src={thumbnail.src} />
</a>
{/each}

{#if $page.state.selected}
<Modal on:close={() => history.goBack()}>
<!-- pass page data to the +page.svelte component,
just like SvelteKit would on navigation -->
<PhotoPage data={$page.state.selected} />
</Modal>
{/if}
```

## Caveats

During server-side rendering, `$page.state` is always an empty object. The same is true for the first page the user lands on — if the user reloads the page, state will _not_ be applied until they navigate.

Shallow routing is a feature that requires JavaScript to work. Be mindful when using it and try to think of sensible fallback behavior in case JavaScript isn't available.
4 changes: 2 additions & 2 deletions documentation/docs/60-appendix/30-migrating-to-sveltekit-2.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ export function load({ fetch }) {
}
```

## goto(...) no longer accepts external URLs
## goto(...) changes

To navigate to an external URL, use `window.location = url`.
`goto(...)` no longer accepts external URLs. To navigate to an external URL, use `window.location = url`. The `state` option was removed in favor of [shallow routing](shallow-routing).

## paths are now relative by default

Expand Down
1 change: 1 addition & 0 deletions packages/create-svelte/templates/default/src/app.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ declare global {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
Expand Down
1 change: 1 addition & 0 deletions packages/create-svelte/templates/skeleton/src/app.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ declare global {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
Expand Down
1 change: 1 addition & 0 deletions packages/create-svelte/templates/skeletonlib/src/app.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ declare global {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
Expand Down
4 changes: 4 additions & 0 deletions packages/kit/src/exports/public.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -961,6 +961,10 @@ export interface Page<
* The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`.
*/
data: App.PageData & Record<string, any>;
/**
* The page state, which can be manipulated using the [`pushState`](https://kit.svelte.dev/docs/modules#$app-navigation-pushstate) and [`replaceState`](https://kit.svelte.dev/docs/modules#$app-navigation-replacestate) functions from `$app/navigation`.
*/
state: App.PageState;
/**
* Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info.
*/
Expand Down
35 changes: 24 additions & 11 deletions packages/kit/src/runtime/app/navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,13 @@ export const disableScrollHandling = /* @__PURE__ */ client_method('disable_scro
* Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`.
* For external URLs, use `window.location = url` instead of calling `goto(url)`.
*
* @type {(url: string | URL, opts?: {
* replaceState?: boolean;
* noScroll?: boolean;
* keepFocus?: boolean;
* invalidateAll?: boolean;
* state?: any
* }) => Promise<void>}
* @type {(url: string | URL, opts?: { replaceState?: boolean; noScroll?: boolean; keepFocus?: boolean; invalidateAll?: boolean; }) => Promise<void>}
* @param {string | URL} url Where to navigate to. Note that if you've set [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths) and the URL is root-relative, you need to prepend the base path if you want to navigate within the app.
* @param {Object} [opts] Options related to the navigation
* @param {boolean} [opts.replaceState] If `true`, will replace the current `history` entry rather than creating a new one with `pushState`
* @param {boolean} [opts.noScroll] If `true`, the browser will maintain its scroll position rather than scrolling to the top of the page after navigation
* @param {boolean} [opts.keepFocus] If `true`, the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the body
* @param {boolean} [opts.invalidateAll] If `true`, all `load` functions of the page will be rerun. See https://kit.svelte.dev/docs/load#rerunning-load-functions for more info on invalidation.
* @param {any} [opts.state] The state of the new/updated history entry
* @returns {Promise<void>}
*/
export const goto = /* @__PURE__ */ client_method('goto');
Expand Down Expand Up @@ -64,11 +57,11 @@ export const invalidateAll = /* @__PURE__ */ client_method('invalidate_all');
*
* This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `<a>` element with `data-sveltekit-preload-data`.
* If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous.
* Returns a Promise that resolves when the preload is complete.
* Returns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete.
*
* @type {(href: string) => Promise<void>}
* @type {(href: string) => Promise<Record<string, any>>}
* @param {string} href Page to preload
* @returns {Promise<void>}
* @returns {Promise<{ type: 'loaded'; status: number; data: Record<string, any> } | { type: 'redirect'; location: string }>}
*/
export const preloadData = /* @__PURE__ */ client_method('preload_data');

Expand Down Expand Up @@ -126,3 +119,23 @@ export const onNavigate = /* @__PURE__ */ client_method('on_navigate');
* @returns {void}
*/
export const afterNavigate = /* @__PURE__ */ client_method('after_navigate');

/**
* Programmatically create a new history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](https://kit.svelte.dev/docs/shallow-routing).
*
* @type {(url: string | URL, state: App.PageState) => void}
dummdidumm marked this conversation as resolved.
Show resolved Hide resolved
* @param {string | URL} url
* @param {App.PageState} state
* @returns {void}
*/
export const pushState = /* @__PURE__ */ client_method('push_state');

/**
* Programmatically replace the current history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](https://kit.svelte.dev/docs/shallow-routing).
*
* @type {(url: string | URL, state: App.PageState) => void}
dummdidumm marked this conversation as resolved.
Show resolved Hide resolved
* @param {string | URL} url
* @param {App.PageState} state
* @returns {void}
*/
export const replaceState = /* @__PURE__ */ client_method('replace_state');
Loading
Loading