Skip to content

feat: added live preview svelte package #12250

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions .github/workflows/pr-title.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ jobs:
graphql
live-preview
live-preview-react
live-preview-svelte
live-preview-vue
next
payload-cloud
plugin-cloud
Expand Down
41 changes: 41 additions & 0 deletions docs/live-preview/client.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,47 @@ const { data } = useLivePreview<PageData>({
</template>
```

### Svelte

If your front-end application is built with [Svelte 5](https://svelte.dev/) or [SvelteKit 2](https://svelte.dev/docs/kit/introduction), you can use the `useLivePreview` writeable rune that Payload provides.

First, install the `@payloadcms/live-preview-svelte` package:

```bash
npm install @payloadcms/live-preview-svelte
```

Then, use the `useLivePreview` hook in your Svelte component:

```ts
<script lang="ts">
import type { PageProps } from './$types';
import { useLivePreview } from '@payloadcms/live-preview-svelte';
import { convertLexicalToHTML } from '@payloadcms/richtext-lexical/html';
import { readable } from 'svelte/store';
import { PUBLIC_PAYLOAD_URL } from '$env/static/public';

let { data }: PageProps = $props();

let payloadDocStore = useLivePreview(data, {
serverURL: PUBLIC_PAYLOAD_URL,
});

const article: typeof data = $derived.by<typeof data>(() => {
const doc = $payloadDocStore;
return {
...doc,
content: convertLexicalToHTML({ data: doc.content }),
};
});
</script>

<article>
<h1>{article.title}</h1>
<div>{@html article.content}</div>
</article>
```

## Building your own hook

No matter what front-end framework you are using, you can build your own hook using the same underlying tooling that Payload provides.
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"build:graphql": "turbo build --filter \"@payloadcms/graphql\"",
"build:live-preview": "turbo build --filter \"@payloadcms/live-preview\"",
"build:live-preview-react": "turbo build --filter \"@payloadcms/live-preview-react\"",
"build:live-preview-svelte": "turbo build --filter \"@payloadcms/live-preview-svelte\"",
"build:live-preview-vue": "turbo build --filter \"@payloadcms/live-preview-vue\"",
"build:next": "turbo build --filter \"@payloadcms/next\"",
"build:packages": "turbo build --filter=./packages/*",
Expand Down
10 changes: 10 additions & 0 deletions packages/live-preview-svelte/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.tmp
**/.git
**/.hg
**/.pnp.*
**/.svn
**/.yarn/**
**/build
**/dist/**
**/node_modules
**/temp
15 changes: 15 additions & 0 deletions packages/live-preview-svelte/.swcrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/swcrc",
"sourceMaps": "inline",
"jsc": {
"target": "esnext",
"parser": {
"syntax": "typescript",
"tsx": true,
"dts": true
}
},
"module": {
"type": "commonjs"
}
}
22 changes: 22 additions & 0 deletions packages/live-preview-svelte/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2018-2025 Payload CMS, Inc. <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
123 changes: 123 additions & 0 deletions packages/live-preview-svelte/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Payload Live Preview - Svelte

Svelte live preview using `@payloadcms/live-preview` package and Svelte `writable` and `readable` store.

The `useLivePreview` returns a readable subscribe and loading, which is also a readable.

## Simple Example without loading or $derived

With this example, we a auto-subscribing to the response and then use `$article` in the body to access the data.
In many cases you will want to use a $derived rune to alter the data, such as converting RichText.

```svelte
<script lang="ts">
import type { PageProps } from './$types';
import { useLivePreview } from '@payloadcms/live-preview-svelte';
import { readable } from 'svelte/store';
import { PUBLIC_PAYLOAD_URL } from '$env/static/public';

let { data }: PageProps = $props();
let article = useLivePreview(data, {
serverURL: PUBLIC_PAYLOAD_URL,
});
</script>

<article>
<h1>{$article.title}</h1>
<div>{@html $article.content}</div>
</article>

```

## Example without loading with $derived

In this example we check to see if it's livePreview and then conditionally load useLivePreview.
We also use $derived to alter the content field.

```svelte

<script lang="ts">
import type { PageProps } from './$types';
import { page } from '$app/state';
import { useLivePreview } from '@payloadcms/live-preview-svelte';
import { convertLexicalToHTML } from '@payloadcms/richtext-lexical/html';
import { readable } from 'svelte/store';
import { PUBLIC_PAYLOAD_URL } from '$env/static/public';

const url = page.url;
const isLivePreview = url.searchParams.get('livePreview') === 'true';

let { data }: PageProps = $props();

let payloadDocStore = readable(data);

if (isLivePreview) {
payloadDocStore = useLivePreview(data, {
serverURL: PUBLIC_PAYLOAD_URL,
});
}

const article: typeof data = $derived.by<typeof data>(() => {
const doc = $payloadDocStore;
return {
...doc,
content: convertLexicalToHTML({ data: doc.content }),
};
});
</script>

<article>
<h1>{article.title}</h1>
<div>{@html article.content}</div>
</article>

```

## Example with loading and $derived

Loading is in there mainly to replicate the other useLivePreview packages,
however, in my tests, it's not really needed, as the data loads instantly.

```svelte
<script lang="ts">
import type { PageProps } from './$types';
import { page } from '$app/state';
import { useLivePreview } from '@payloadcms/live-preview-svelte';
import { convertLexicalToHTML } from '@payloadcms/richtext-lexical/html';
import { readable } from 'svelte/store';
import { PUBLIC_PAYLOAD_URL } from '$env/static/public';

const url = page.url;
const isLivePreview = url.searchParams.get('livePreview') === 'true';

let { data }: PageProps = $props();

let payloadDocStore = readable(data);
let loading = readable(false);

if (isLivePreview) {
const livePreviewStore = useLivePreview(data, {
serverURL: PUBLIC_PAYLOAD_URL,
});

payloadDocStore = livePreviewStore;
loading = livePreviewStore.loading;
}

const article: typeof data = $derived.by<typeof data>(() => {
const doc = $payloadDocStore;
return {
...doc,
content: convertLexicalToHTML({ data: doc.content }),
};
});
</script>

<article>
{#if $loading}
<div>Loading...</div>
{/if}
<h1>{article.title}</h1>
<div>{@html article.content}</div>
</article>
```
18 changes: 18 additions & 0 deletions packages/live-preview-svelte/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { rootEslintConfig, rootParserOptions } from '../../eslint.config.js'

/** @typedef {import('eslint').Linter.Config} Config */

/** @type {Config[]} */
export const index = [
...rootEslintConfig,
{
languageOptions: {
parserOptions: {
...rootParserOptions,
tsconfigRootDir: import.meta.dirname,
},
},
},
]

export default index
66 changes: 66 additions & 0 deletions packages/live-preview-svelte/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
{
"name": "@payloadcms/live-preview-svelte",
"version": "3.35.1",
"description": "The official Svelte SDK for Payload Live Preview",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",
"url": "https://github.com/payloadcms/payload.git",
"directory": "packages/live-preview-svelte"
},
"license": "MIT",
"author": "Payload <[email protected]> (https://payloadcms.com)",
"maintainers": [
{
"name": "Payload",
"email": "[email protected]",
"url": "https://payloadcms.com"
}
],
"type": "module",
"exports": {
".": {
"import": "./src/index.ts",
"types": "./src/index.ts",
"default": "./src/index.ts"
}
},
"main": "./src/index.ts",
"types": "./src/index.ts",
"files": [
"dist"
],
"scripts": {
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
"build:types": "tsc --emitDeclarationOnly --outDir dist",
"clean": "rimraf -g {dist,*.tsbuildinfo}",
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"prepublishOnly": "pnpm clean && pnpm turbo build"
},
"dependencies": {
"@payloadcms/live-preview": "workspace:*"
},
"devDependencies": {
"@payloadcms/eslint-config": "workspace:*",
"payload": "workspace:*",
"svelte": "^5.0.0"
},
"peerDependencies": {
"svelte": "^5.0.0"
},
"publishConfig": {
"exports": {
".": {
"default": "./dist/index.js",
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"main": "./dist/index.js",
"registry": "https://registry.npmjs.org/",
"types": "./dist/index.d.ts"
}
}
74 changes: 74 additions & 0 deletions packages/live-preview-svelte/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import {
subscribe as payloadSubscribe,
unsubscribe as payloadUnsubscribe,
ready,
} from '@payloadcms/live-preview'
import { type Readable, writable } from 'svelte/store'

interface LivePreviewStoreOptions<T extends Record<string, unknown>> {
initialData: T
serverURL: string
}

interface LivePreviewStore<T> {
loading: Readable<boolean>
subscribe: Readable<T>['subscribe']
}

function createLivePreviewStore<T extends Record<string, unknown>>({
initialData,
serverURL,
}: LivePreviewStoreOptions<T>): LivePreviewStore<T> {
let subscription: ReturnType<typeof payloadSubscribe> | undefined
let initialized = false

const loading = writable(false)
const { subscribe } = writable<T>(initialData, (set) => {
// Called when the store gets its first subscriber

if (typeof window === 'undefined') {
return
}

if (!initialized) {
initialized = true
ready({ serverURL })

loading.set(true)
subscription = payloadSubscribe({
callback: (doc) => {
set(doc)
loading.set(false)
},
depth: 1,
initialData,
serverURL,
})
}

return () => {
// Called when the last subscriber unsubscribes
if (typeof window !== 'undefined' && subscription) {
payloadUnsubscribe(subscription)
subscription = undefined
}
}
})

return {
loading: { subscribe: loading.subscribe },
subscribe,
}
}

export function useLivePreview<T extends Record<string, unknown>>(
initialData: T,
options: {
serverURL: string
},
) {
return createLivePreviewStore({
initialData,
serverURL: options.serverURL,
})
}
Loading