Skip to content

Commit

Permalink
Shallow routing (#11307)
Browse files Browse the repository at this point in the history
* shallow routing

* add types

* drive-by fix - bad merge

* warn on use of history.pushState and history.replaceState

* regenerate types

* make url the first argument, even though it's optional — this is more future-proof, as we may add options in future

* tests

* remove state from goto

* tidy up

* tidy up internal navigate API a bit

* more

* use current.url for invalidation, not location.href

* add docs

* copy-paste fail

* on second thoughts

* links

* link

* regenerate types

* update preloadData docs

* fix preloadData docs

* drive-by fix

* Apply suggestions from code review

Co-authored-by: Ignatius Bagus <[email protected]>

* tweaks

* changeset, breaking change docs

* code-golf

* this seems unnecessary

* mention preloadData

* use original replace state

* oops

* handle SPA case

* more involved example - show importing a +page.svelte and correctly handling a click event, and avoid

---------

Co-authored-by: Rich Harris <[email protected]>
Co-authored-by: Ben McCann <[email protected]>
Co-authored-by: Simon H <[email protected]>
Co-authored-by: Ignatius Bagus <[email protected]>
Co-authored-by: Simon Holthausen <[email protected]>
  • Loading branch information
6 people authored Dec 14, 2023
1 parent a00183a commit 052adf9
Show file tree
Hide file tree
Showing 30 changed files with 673 additions and 164 deletions.
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}
* @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}
* @param {string | URL} url
* @param {App.PageState} state
* @returns {void}
*/
export const replaceState = /* @__PURE__ */ client_method('replace_state');
Loading

0 comments on commit 052adf9

Please sign in to comment.