diff --git a/.changeset/little-countries-cough.md b/.changeset/little-countries-cough.md new file mode 100644 index 000000000000..7649ca44df4e --- /dev/null +++ b/.changeset/little-countries-cough.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/kit': minor +--- + +feat: add snapshot mechanism for preserving ephemeral DOM state diff --git a/documentation/docs/30-advanced/65-snapshots.md b/documentation/docs/30-advanced/65-snapshots.md new file mode 100644 index 000000000000..41971b98e941 --- /dev/null +++ b/documentation/docs/30-advanced/65-snapshots.md @@ -0,0 +1,33 @@ +--- +title: Snapshots +--- + +Ephemeral DOM state — like scroll positions on sidebars, the content of `` elements and so on — is discarded when you navigate from one page to another. + +For example, if the user fills out a form but clicks a link before submitting, then hits the browser's back button, the values they filled in will be lost. In cases where it's valuable to preserve that input, you can take a _snapshot_ of DOM state, which can then be restored if the user navigates back. + +To do this, export a `snapshot` object with `capture` and `restore` methods from a `+page.svelte` or `+layout.svelte`: + +```svelte +/// file: +page.svelte + + +
+``` + +When you navigate away from this page, the `capture` function is called immediately before the page updates, and the returned value is associated with the current entry in the browser's history stack. If you navigate back, the `restore` function is called with the stored value as soon as the page is updated. + +The data must be serializable as JSON so that it can be persisted to `sessionStorage`. This allows the state to be restored when the page is reloaded, or when the user navigates back from a different site. + +> Avoid returning very large objects from `capture` — once captured, objects will be retained in memory for the duration of the session, and in extreme cases may be too large to persist to `sessionStorage`. \ No newline at end of file diff --git a/packages/kit/src/core/sync/write_root.js b/packages/kit/src/core/sync/write_root.js index e40fe3021870..a82e2d00770f 100644 --- a/packages/kit/src/core/sync/write_root.js +++ b/packages/kit/src/core/sync/write_root.js @@ -21,16 +21,16 @@ export function write_root(manifest_data, output) { let l = max_depth; - let pyramid = `