Fragment
A value a link should carry but the server has no use for, such as which slide is showing, can live in the fragment of the URL. That value goes in hash.
On this page
The hash schema
deck-state.tsimport { definePageState, useAppState } from '@k8ordo/state';
import * as z from 'zod';
export const deckState = definePageState('deck', {
url: z.object({ mode: z.enum(['view', 'present']).default('view') }),
hash: z.coerce.number().int().min(1).default(1),
});
// /slides/intro#3
const [{ hash, mode }, update] = useAppState(deckState);
// hash === 3A fragment is one string, so hash takes a schema for one value, not an object of fields. The value is the field hash of the state, returned by useAppState beside the url and entry values.
The schema follows the rules of url: give it .default() or .optional() for when there is no value, and write a boolean as z.stringbool(). A url or entry field named hash beside it is an error when the definition is made.
A fragment is never sent to the server, so the server render and the hydration render show the default.
Writing
update({ hash: 4 }); // /slides/intro#4
update({ hash: 5 }, { history: 'push' });
update({ hash: 1 }); // /slides/introWriting works as it does for url. By default it rewrites the current history entry, and { history: 'push' } adds one. Writing the default removes the fragment from the URL. A run of writes is thinned out as url writes are.
Writing a fragment does not move the viewport. If an element on the page has that value as its id, though, the browser scrolls to it.
deckState.href('/slides/intro', { hash: 4 });
// '/slides/intro#4'Build a link with href(). The hash value becomes the fragment.
Living with in-page links
A fragment the schema rejects is not treated as this state’s value. Under the schema above, #main reads as the default, 1, and stays in the URL as it is.
Neither writing the default nor writing a url or entry value removes #main. Only a value other than the default replaces the fragment.
When a visitor follows an in-page link, the value goes back to its default. A screen that must keep the value, such as a slide deck, stops moves to in-page links itself.