The Router and Forms
Morphs and the Router
Same-origin clicks and back/forward fetch the page and morph it in, with no full reload. A form action morphs the page too. Layouts stay mounted.
goto('/login') // or goto(url, { replace: true })
invalidate() // run this page's load again
page.value.url.pathname // page: { url, route, status, form, state }
navigating.value // { from, to } while loading, else null
pushState('?tab=2', { tab: 2 }) // history entry, no navigation
replaceState('', { tab: 3 }) // this entry's state ('' keeps the URL)
- In a browser extension, give
gotothe path of the file:goto('/options/index.html').goto('/options')fails there. - The morph keeps an element that matches by tag and
id, or by tag in the same place. - A slot that shows its default (
<wisp-slot default>) keeps what it showed on a link orgoto. Back, Forward, a refresh and a form's answer show what a load of that address shows (Slots). - Only attributes the server changed are set, so what scripts did to the rest stays.
data-wisp-keepon an element whose children a script owns (a widget, a chart, an editor) leaves it and everything inside alone. - A
+template.wispis not kept. Its element has the path in itsid, so a navigation to another path replaces it, and the instances in it start fresh (Templates). - A component instance on a kept element keeps its state and gets the new
data.data-wisp-reseton an element around it starts it fresh. - The router prefetches on hover (60 ms), touch, press (
pointerdown) and keyboard focus held 60 ms, never with data saver on.use:preloadfetches once the link is in view.data-wisp-preload="off"stops the prefetch. - Back restores scroll once the page is tall enough.
use:keepscrollrestores a scrolling element's scroll too. Focus moves to[autofocus]. - The new page shows after its head stylesheets load, as on a full page load, so it does not shift when they arrive. Only the sheets that the shown page does not have count. The wait is 3 s at most, and a sheet that fails does not hold it.
- View transitions run when available.
data-wisp-notransitionon a link (or<body>) skips them. - The router follows a redirect in place. A redirect to another site, or a sixth in a row, is a full load.
data-wisp-reloadon a link or parent forces a full load. The router does not touch links with a target (or a<base target>),download,rel="external"or a path under/_app/(/wisp/in an extension build). It does not touch links and forms outside the base path either: the browser follows them.pushState(url, state)(shallow routing, for tabs and modals) adds an entry aturl('': this one) and loads nothing.page.value.stateis reactive ({}on other entries). Back/forward restores it with no request.documentevents:wisp:navigate wisp:update wisp:answers wisp:goto wisp:refresh wisp:stay wisp:error wisp:push wisp:pop.wisp:answersfires after streamed{#await}answers went in.wisp:stayfires when a navigation ended with the page staying (a download or adata-wisp-cutslot). Form events:wisp:submit(cancelable) andwisp:result.
Link and Navigation Options
data-wisp-noscroll, data-wisp-keepfocus, data-wisp-replacestate, data-wisp-notransition (on or around a link) keep scroll, keep focus, replace history and skip the view transition. goto(url, { noscroll, keepfocus, replace, novt }) does the same.
Hooks from 'wisp' return an unsubscribe:
| Hook | Does |
|---|---|
beforeNavigate(({ from, to, pop, type, willUnload, cancel }) => ..) | Before leaving. cancel() does not stop back/forward. type is link, goto or popstate. A server redirect is goto, and cancel() stops it. A redirect comes from a form, goto, invalidate, invalidateAll, a refresh of the page (on focus, after a form or a live send, a page shown from back/forward memory) or a wisp dev reload. Before the page unloads, type is leave, to is null, willUnload is true and cancel() makes the browser ask the visitor to stay. A beforeNavigate listener adds a beforeunload listener, which disables the back/forward cache in Firefox. |
disableScrollHandling() | Called in onNavigate or afterNavigate: this navigation leaves the scroll where it is. |
afterNavigate | After the swap. |
onNavigate | After fetch, before the swap. The router waits for a returned promise, and runs a returned function after the swap. |
preloadData(url), preloadCode(url) | Fetch ahead. |
invalidateAll() | Rerun every load and forget pages kept for back (call it after a sign-out that uses goto). |
updated.value | A newer wisp.js or build exists. With version_poll = N in [package.metadata.wisp], the page also reads /_app/version.json every N seconds. |
A page whose head has <meta name="wisp-csr" content="off"> loads whole: the router does not swap it in. That load is leave for beforeNavigate, so the app's guard can ask the visitor to stay.
The build fills in these names of 'wisp' in a named import (not import * as w). They need no runtime file. A release build without source maps deletes the dead branch of if (dev), if (!dev) and its else, also for browser and building. The body must be a block or one line that ends with ;, and the file must use the name only in such if heads and in its import. An app that imports none of these names pays no byte:
| Name | Value |
|---|---|
browser | true |
dev | false in a release build |
building | false. No browser code runs where the build evaluates a page. |
version | the id of the build, the same as <meta name="wisp-build"> and /_app/version.json. The build id is a hash of each file in src/ and static/, of build.rs, Cargo.toml and the nearest Cargo.lock (up to 8 parent folders, with the Cargo.toml beside it). It is an empty string in wisp dev. |
settled() | a promise that resolves after the pending state updates are drawn, and after updates that the draw started in a promise callback. It does not wait for {:#await} holes or the network. |
resolve(route, params) | the URL of a route under the base path, each parameter encoded: resolve('/blog/[slug]', { slug }). The route must be a string literal (no variable, no ${}), and a route the app does not have is a build error. A .. value stays ..: encode the dots of a visitor's value yourself. |
asset(path) | the URL of a file: a built file (/_app/…) from the asset base, any other path under the base path |
import { dev, resolve } from 'wisp';
if (dev) console.log(resolve('/blog/[slug]', { slug: 'hello' }));
+page.js load gets depends(key) (a fetched URL counts). invalidate('key') reruns only those loads.
Snapshots
Back, forward and reload restore each changed <input>, <textarea>, <select> from sessionStorage, except passwords, files, hidden, autocomplete="off" and cc-*, one-time-code, new-password, current-password. A script keeps its own state with snapshot. A script can export only snapshot:
<script lang="ts">
let open = false
export const snapshot = { capture: () => open, restore: (v) => (open = v) } // capture: any JSON
</script>
Phones and Offline
<body data-wisp-revalidate="30">refetches data when the tab or network returns (at most every N s, default 30), keeping focus, scroll and typed text.- A navigation to a page of another build (a deploy while the tab sat open) fires
wisp:stale(theupdatedstore) and loads the page whole. - Turn Cloudflare's Rocket Loader off (see Deploy).
- Offline,
<form data-wisp-queue>(safe to send twice) waits insessionStorageand is sent in order when the network is back, then the page refreshes (wisp:sent). A multipart form with a file is not kept, nor is a form with a password field or a field whoseautocompleteiscc-*,one-time-codeor*-password. Such a form gets the offline message. The queue code is in/_app/c/queue.js. wisp.js loads it only when a form waits, or when a page starts with posts that wait. - Other forms show "You are offline" and fire
wisp:resultwitherror: "offline".
Slow and Flaky Networks
- The router morphs an answer that comes within 100 ms into the page. A slower one shows its
+loading.wispand a progress bar,#wisp-progress(color--wisp-progress;#wisp-progress { display: none }hides it). - Back and Forward show the page as left (the last 10 pages, in memory), then ask the server again. The router never keeps
Cache-Control: no-storeorprivatepages. A form post clears them all. - A newer navigation aborts the last request. An answer that does not start within 15 s loads the page whole.
- If a GET fails, Wisp retries once after 300 ms, then loads the page whole. Offline, a link says "You are offline." and fires
wisp:stay. - A post whose answer fails keeps the form's values and fires
wisp:resultwithok: falseanderror. The submit button is disabled while the post is out. listen(url, f)reconnects a dropped stream after 1 s, 2 s, 4 s… (at most 30 s), and at once when the network is back. It returns{ close(), source }.
Forms: use:enhance
Example: Forms That Feel Instant shows its code and downloads as a project.
Plain forms already update in place. use:enhance adds hooks:
<form method="post" action="?/add" use:enhance="submit">
<input name="text" bind:value="text">
<button disabled={:pending}>Send</button>
</form>
<script lang="ts">
let text = '', pending = false
function submit({ formData, cancel }) {
pending = true
return (result) => { pending = false } // then the page updates
}
</script>
- The first function gets
{ form, formData, submitter, action, cancel }.cancel()stops the post. The function it returns gets{ ok, status, location?, data?, error?, apply }when the answer is in, before the page changes. - The update (reset on success, morph, follow a redirect) runs after, unless it returns
falseor callsapplyitself:
return (r) => r.apply({ reset: false }) // keep what was typed (a search box, a chat input)
return async (r) => { await r.apply(); focus() } // code that needs the new page
return (r) => false // no morph: the script shows the result itself
return (r) => { // a redirect or an error, handled here
if (r.location) { goto(r.location); return false }
if (!r.ok) { toast(r.status); return false }
}
page.value.routeis the route's pattern (/blog/[slug]), ascx.route()on the server.- An action answering JSON (
Response::json_of(…)) leaves the form on the page.dataandpage.value.formhold it.
+page.js
Example: Search With +page.js shows its code and downloads as a project.
It runs in the browser on every navigation. Its return value is the script's data. While it runs, the page shows a +loading.wisp that fits the address, else its static markup with the {…} holes empty and aria-busy on their parent. A load that throws shows the nearest +error.wisp.
export async function load({ data, url, params, route, fetch }) {
return { ...data, results: await (await fetch('/api/search?q=' + url.searchParams.get('q'))).json() }
}
With a server load, the whole Data (#[derive(Json)]) is sent. Use params.slug for blog/[slug]. route.id is /blog/[slug].
+layout.js and parent()
A +layout.js (or +layout.ts) next to a +layout.wisp is the browser load of the layout. It gets the same event as a +page.js. Its return value is the data of the layout's script.
A +page.js or +layout.js load can call parent(). It gives the data of the +layout.js loads above, merged outermost first: a key of an inner layout wins. With no +layout.js above, it gives {} at once. A load that does not call parent() does not wait for the layouts.
// src/routes/+layout.js
export async function load({ fetch }) {
return { user: await (await fetch('/api/me')).json() }
}
// src/routes/account/+page.js
export async function load({ parent }) {
const { user } = await parent()
return { name: user.name }
}
A layout that stays across a navigation runs its load again only when a route param or a part of the URL that it read changed, invalidate() or invalidateAll() hit it, or a layout above ran again and it read parent(). Else it keeps its last data. A start after a form answer keeps the data of a kept layout: call invalidateAll() in the form callback to load again. Only an app with a +layout.js loads /_app/c/parent.js, the code of parent().
Types: ./$types
wisp dev, wisp build and wisp check --types write a $types.d.ts per route folder to .wisp/route-types/ (git-ignored). Point TypeScript at them in tsconfig.json: { "compilerOptions": { "rootDirs": [".", ".wisp/route-types"] } }, then:
// src/routes/blog/[slug]/+page.ts
import type { PageLoad } from './$types'
export const load: PageLoad = ({ data, params }) => ({ ...data, slug: params.slug })
PageParams/LayoutParams:[slug]and[...rest]arestring,[[lang]]islang?: string, none isRecord<string, never>.PageData/LayoutData: the RustDatafields as TypeScript (Vec<Item>isItem[],Option<T>isT | null).PageLoad/LayoutLoad:load's event (data,url,params,route,fetch,depends,parent).Actions/ActionData: what each#[action]answers as JSON, elseunknown.
Is This Page Useful?