feat: ssr live preview (#6239)

This commit is contained in:
Jacob Fletcher
2024-05-08 11:08:15 -04:00
committed by GitHub
parent 86b19d4c74
commit 731f023c6d
38 changed files with 972 additions and 441 deletions

View File

@@ -0,0 +1,284 @@
---
title: Client-side Live Preview
label: Client-side
order: 40
desc: Learn how to implement Live Preview in your client-side front-end application.
keywords: live preview, frontend, react, next.js, vue, nuxt.js, svelte, hook, useLivePreview
---
<Banner type="info">
If your front-end application is supports Server Components like the [Next.js App Router](https://nextjs.org/docs/app), etc., we suggest setting up [server-side Live Preview](./server).
</Banner>
While using Live Preview, the Admin panel emits a new `window.postMessage` event every time your document has changed. Your front-end application can listen for these events and re-render accordingly.
If your front-end application is built with [React](#react) or [Vue](#vue), use the `useLivePreview` hooks that Payload provides. In the future, all other major frameworks like Svelte will be officially supported. If you are using any of these frameworks today, you can still integrate with Live Preview yourself using the underlying tooling that Payload provides. See [building your own hook](#building-your-own-hook) for more information.
By default, all hooks accept the following args:
| Path | Description |
| ------------------ | -------------------------------------------------------------------------------------- |
| **`serverURL`** \* | The URL of your Payload server. |
| **`initialData`** | The initial data of the document. The live data will be merged in as changes are made. |
| **`depth`** | The depth of the relationships to fetch. Defaults to `0`. |
| **`apiRoute`** | The path of your API route as defined in `routes.api`. Defaults to `/api`. |
_\* An asterisk denotes that a property is required._
And return the following values:
| Path | Description |
| --------------- | ---------------------------------------------------------------- |
| **`data`** | The live data of the document, merged with the initial data. |
| **`isLoading`** | A boolean that indicates whether or not the document is loading. |
<Banner type="info">
If your front-end is tightly coupled to required fields, you should ensure that your UI does not
break when these fields are removed. For example, if you are rendering something like
`data.relatedPosts[0].title`, your page will break once you remove the first related post. To get
around this, use conditional logic, optional chaining, or default values in your UI where needed.
For example, `data?.relatedPosts?.[0]?.title`.
</Banner>
<Banner type="info">
It is important that the `depth` argument matches exactly with the depth of your initial page request. The depth property is used to populated relationships and uploads beyond their IDs. See [Depth](../getting-started/concepts#depth) for more information.
</Banner>
### React
If your front-end application is built with client-side [React](https://react.dev) like [Next.js Pages Router](https://nextjs.org/docs/pages), you can use the `useLivePreview` hook that Payload provides.
First, install the `@payloadcms/live-preview-react` package:
```bash
npm install @payloadcms/live-preview-react
```
Then, use the `useLivePreview` hook in your React component:
```tsx
'use client'
import { useLivePreview } from '@payloadcms/live-preview-react'
import { Page as PageType } from '@/payload-types'
// Fetch the page in a server component, pass it to the client component, then thread it through the hook
// The hook will take over from there and keep the preview in sync with the changes you make
// The `data` property will contain the live data of the document
export const PageClient: React.FC<{
page: {
title: string
}
}> = ({ page: initialPage }) => {
const { data } = useLivePreview<PageType>({
initialData: initialPage,
serverURL: PAYLOAD_SERVER_URL,
depth: 2,
})
return <h1>{data.title}</h1>
}
```
### Vue
If your front-end application is built with [Vue 3](https://vuejs.org) or [Nuxt 3](https://nuxt.js), you can use the `useLivePreview` composable that Payload provides.
First, install the `@payloadcms/live-preview-vue` package:
```bash
npm install @payloadcms/live-preview-vue
```
Then, use the `useLivePreview` hook in your Vue component:
```vue
<script setup lang="ts">
import type { PageData } from '~/types';
import { defineProps } from 'vue';
import { useLivePreview } from '@payloadcms/live-preview-vue';
// Fetch the initial data on the parent component or using async state
const props = defineProps<{ initialData: PageData }>();
// The hook will take over from here and keep the preview in sync with the changes you make.
// The `data` property will contain the live data of the document only when viewed from the Preview view of the Admin UI.
const { data } = useLivePreview<PageData>({
initialData: props.initialData,
serverURL: "<PAYLOAD_SERVER_URL>",
depth: 2,
});
</script>
<template>
<h1>{{ data.title }}</h1>
</template>
```
### 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.
First, install the base `@payloadcms/live-preview` package:
```bash
npm install @payloadcms/live-preview
```
This package provides the following functions:
| Path | Description |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| **`subscribe`** | Subscribes to the Admin panel's `window.postMessage` events and calls the provided callback function. |
| **`unsubscribe`** | Unsubscribes from the Admin panel's `window.postMessage` events. |
| **`ready`** | Sends a `window.postMessage` event to the Admin panel to indicate that the front-end is ready to receive messages. |
| **`isLivePreviewEvent`** | Checks if a `MessageEvent` originates from the Admin panel and is a Live Preview event, i.e. debounced form state. |
The `subscribe` function takes the following args:
| Path | Description |
| ------------------ | ------------------------------------------------------------------------------------------- |
| **`callback`** \* | A callback function that is called with `data` every time a change is made to the document. |
| **`serverURL`** \* | The URL of your Payload server. |
| **`initialData`** | The initial data of the document. The live data will be merged in as changes are made. |
| **`depth`** | The depth of the relationships to fetch. Defaults to `0`. |
With these functions, you can build your own hook using your front-end framework of choice:
```tsx
import { subscribe, unsubscribe } from '@payloadcms/live-preview'
// To build your own hook, subscribe to Live Preview events using the `subscribe` function
// It handles everything from:
// 1. Listening to `window.postMessage` events
// 2. Merging initial data with active form state
// 3. Populating relationships and uploads
// 4. Calling the `onChange` callback with the result
// Your hook should also:
// 1. Tell the Admin panel when it is ready to receive messages
// 2. Handle the results of the `onChange` callback to update the UI
// 3. Unsubscribe from the `window.postMessage` events when it unmounts
```
Here is an example of what the same `useLivePreview` React hook from above looks like under the hood:
```tsx
import { subscribe, unsubscribe, ready } from '@payloadcms/live-preview'
import { useCallback, useEffect, useState, useRef } from 'react'
export const useLivePreview = <T extends any>(props: {
depth?: number
initialData: T
serverURL: string
}): {
data: T
isLoading: boolean
} => {
const { depth = 0, initialData, serverURL } = props
const [data, setData] = useState<T>(initialData)
const [isLoading, setIsLoading] = useState<boolean>(true)
const hasSentReadyMessage = useRef<boolean>(false)
const onChange = useCallback((mergedData) => {
// When a change is made, the `onChange` callback will be called with the merged data
// Set this merged data into state so that React will re-render the UI
setData(mergedData)
setIsLoading(false)
}, [])
useEffect(() => {
// Listen for `window.postMessage` events from the Admin panel
// When a change is made, the `onChange` callback will be called with the merged data
const subscription = subscribe({
callback: onChange,
depth,
initialData,
serverURL,
})
// Once subscribed, send a `ready` message back up to the Admin panel
// This will indicate that the front-end is ready to receive messages
if (!hasSentReadyMessage.current) {
hasSentReadyMessage.current = true
ready({
serverURL,
})
}
// When the component unmounts, unsubscribe from the `window.postMessage` events
return () => {
unsubscribe(subscription)
}
}, [serverURL, onChange, depth, initialData])
return {
data,
isLoading,
}
}
```
<Banner type="info">
When building your own hook, ensure that the args and return values are consistent with the ones
listed at the top of this document. This will ensure that all hooks follow the same API.
</Banner>
## Example
For a working demonstration of this, check out the official [Live Preview Example](https://github.com/payloadcms/payload/tree/main/examples/live-preview/payload). There you will find examples of various front-end frameworks and how to integrate each one of them, including:
- [Next.js App Router](https://github.com/payloadcms/payload/tree/main/examples/live-preview/next-app)
- [Next.js Pages Router](https://github.com/payloadcms/payload/tree/main/examples/live-preview/next-pages)
## Troubleshooting
#### Relationships and/or uploads are not populating
If you are using relationships or uploads in your front-end application, and your front-end application runs on a different domain than your Payload server, you may need to configure [CORS](../configuration/overview) to allow requests to be made between the two domains. This includes sites that are running on a different port or subdomain. Similarly, if you are protecting resources behind user authentication, you may also need to configure [CSRF](../authentication/overview#csrf-protection) to allow cookies to be sent between the two domains. For example:
```ts
// payload.config.ts
{
// ...
// If your site is running on a different domain than your Payload server,
// This will allows requests to be made between the two domains
cors: {
[
'http://localhost:3001' // Your front-end application
],
},
// If you are protecting resources behind user authentication,
// This will allow cookies to be sent between the two domains
csrf: {
[
'http://localhost:3001' // Your front-end application
],
},
}
```
#### Relationships and/or uploads disappear after editing a document
It is possible that either you are setting an improper [`depth`](../getting-started/concepts#depth) in your initial request and/or your `useLivePreview` hook, or they're mismatched. Ensure that the `depth` parameter is set to the correct value, and that it matches exactly in both places. For example:
```tsx
// Your initial request
const { docs } = await payload.find({
collection: 'pages',
depth: 1, // Ensure this is set to the proper depth for your application
where: {
slug: {
equals: 'home',
},
},
})
```
```tsx
// Your hook
const { data } = useLivePreview<PageType>({
initialData: initialPage,
serverURL: PAYLOAD_SERVER_URL,
depth: 1, // Ensure this matches the depth of your initial request
})
```

View File

@@ -1,279 +1,16 @@
---
title: Implementing Live Preview in your app
label: Frontend Implementation
title: Implementing Live Preview in your frontend
label: Frontend
order: 20
desc: Learn how to implement Live Preview in your front-end application.
keywords: live preview, frontend, react, next.js, vue, nuxt.js, svelte, hook, useLivePreview
---
While using Live Preview, the Admin panel emits a new `window.postMessage` event every time a change is made to the document. Your front-end application can listen for these events and re-render accordingly.
There are two ways to use Live Preview in your own application depending on whether your front-end framework supports server components:
Wiring your front-end into Live Preview is easy. If your front-end application is built with React, Next.js, Vue or Nuxt.js, use the `useLivePreview` hook that Payload provides. In the future, all other major frameworks like Svelte will be officially supported. If you are using any of these frameworks today, you can still integrate with Live Preview yourself using the underlying tooling that Payload provides. See [building your own hook](#building-your-own-hook) for more information.
By default, all hooks accept the following args:
| Path | Description |
| ------------------ | -------------------------------------------------------------------------------------- |
| **`serverURL`** \* | The URL of your Payload server. |
| **`initialData`** | The initial data of the document. The live data will be merged in as changes are made. |
| **`depth`** | The depth of the relationships to fetch. Defaults to `0`. |
| **`apiRoute`** | The path of your API route as defined in `routes.api`. Defaults to `/api`. |
_\* An asterisk denotes that a property is required._
And return the following values:
| Path | Description |
| --------------- | ---------------------------------------------------------------- |
| **`data`** | The live data of the document, merged with the initial data. |
| **`isLoading`** | A boolean that indicates whether or not the document is loading. |
- [Server-side Live Preview (suggested)](./server)
- [Client-side Live Preview](./client)
<Banner type="info">
If your front-end is tightly coupled to required fields, you should ensure that your UI does not
break when these fields are removed. For example, if you are rendering something like
`data.relatedPosts[0].title`, your page will break once you remove the first related post. To get
around this, use conditional logic, optional chaining, or default values in your UI where needed.
For example, `data?.relatedPosts?.[0]?.title`.
We suggest using server-side Live Preview if your framework supports it, it is both simpler to setup and more performant to run than the client-side alternative.
</Banner>
<Banner type="info">
It is important that the `depth` argument matches exactly with the depth of your initial page request. The depth property is used to populated relationships and uploads beyond their IDs. See [Depth](../getting-started/concepts#depth) for more information.
</Banner>
### React
If your front-end application is built with React or Next.js, you can use the `useLivePreview` hook that Payload provides.
First, install the `@payloadcms/live-preview-react` package:
```bash
npm install @payloadcms/live-preview-react
```
Then, use the `useLivePreview` hook in your React component:
```tsx
'use client'
import { useLivePreview } from '@payloadcms/live-preview-react'
import { Page as PageType } from '@/payload-types'
// Fetch the page in a server component, pass it to the client component, then thread it through the hook
// The hook will take over from there and keep the preview in sync with the changes you make
// The `data` property will contain the live data of the document
export const PageClient: React.FC<{
page: {
title: string
}
}> = ({ page: initialPage }) => {
const { data } = useLivePreview<PageType>({
initialData: initialPage,
serverURL: PAYLOAD_SERVER_URL,
depth: 2,
})
return <h1>{data.title}</h1>
}
```
### Vue
If your front-end application is built with Vue 3 or Nuxt 3, you can use the `useLivePreview` composable that Payload provides.
First, install the `@payloadcms/live-preview-vue` package:
```bash
npm install @payloadcms/live-preview-vue
```
Then, use the `useLivePreview` hook in your Vue component:
```vue
<script setup lang="ts">
import type { PageData } from '~/types';
import { defineProps } from 'vue';
import { useLivePreview } from '@payloadcms/live-preview-vue';
// Fetch the initial data on the parent component or using async state
const props = defineProps<{ initialData: PageData }>();
// The hook will take over from here and keep the preview in sync with the changes you make.
// The `data` property will contain the live data of the document only when viewed from the Preview view of the Admin UI.
const { data } = useLivePreview<PageData>({
initialData: props.initialData,
serverURL: "<PAYLOAD_SERVER_URL>",
depth: 2,
});
</script>
<template>
<h1>{{ data.title }}</h1>
</template>
```
## 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.
First, install the base `@payloadcms/live-preview` package:
```bash
npm install @payloadcms/live-preview
```
This package provides the following functions:
| Path | Description |
| ----------------- | ------------------------------------------------------------------------------------------------------------------ |
| **`subscribe`** | Subscribes to the Admin panel's `window.postMessage` events and calls the provided callback function. |
| **`unsubscribe`** | Unsubscribes from the Admin panel's `window.postMessage` events. |
| **`ready`** | Sends a `window.postMessage` event to the Admin panel to indicate that the front-end is ready to receive messages. |
The `subscribe` function takes the following args:
| Path | Description |
| ------------------ | ------------------------------------------------------------------------------------------- |
| **`callback`** \* | A callback function that is called with `data` every time a change is made to the document. |
| **`serverURL`** \* | The URL of your Payload server. |
| **`initialData`** | The initial data of the document. The live data will be merged in as changes are made. |
| **`depth`** | The depth of the relationships to fetch. Defaults to `0`. |
With these functions, you can build your own hook using your front-end framework of choice:
```tsx
import { subscribe, unsubscribe } from '@payloadcms/live-preview'
// To build your own hook, subscribe to Live Preview events using the`subscribe` function
// It handles everything from:
// 1. Listening to `window.postMessage` events
// 2. Merging initial data with active form state
// 3. Populating relationships and uploads
// 4. Calling the `onChange` callback with the result
// Your hook should also:
// 1. Tell the Admin panel when it is ready to receive messages
// 2. Handle the results of the `onChange` callback to update the UI
// 3. Unsubscribe from the `window.postMessage` events when it unmounts
```
Here is an example of what the same `useLivePreview` React hook from above looks like under the hood:
```tsx
import { subscribe, unsubscribe, ready } from '@payloadcms/live-preview'
import { useCallback, useEffect, useState, useRef } from 'react'
export const useLivePreview = <T extends any>(props: {
depth?: number
initialData: T
serverURL: string
}): {
data: T
isLoading: boolean
} => {
const { depth = 0, initialData, serverURL } = props
const [data, setData] = useState<T>(initialData)
const [isLoading, setIsLoading] = useState<boolean>(true)
const hasSentReadyMessage = useRef<boolean>(false)
const onChange = useCallback((mergedData) => {
// When a change is made, the `onChange` callback will be called with the merged data
// Set this merged data into state so that React will re-render the UI
setData(mergedData)
setIsLoading(false)
}, [])
useEffect(() => {
// Listen for `window.postMessage` events from the Admin panel
// When a change is made, the `onChange` callback will be called with the merged data
const subscription = subscribe({
callback: onChange,
depth,
initialData,
serverURL,
})
// Once subscribed, send a `ready` message back up to the Admin panel
// This will indicate that the front-end is ready to receive messages
if (!hasSentReadyMessage.current) {
hasSentReadyMessage.current = true
ready({
serverURL,
})
}
// When the component unmounts, unsubscribe from the `window.postMessage` events
return () => {
unsubscribe(subscription)
}
}, [serverURL, onChange, depth, initialData])
return {
data,
isLoading,
}
}
```
<Banner type="info">
When building your own hook, ensure that the args and return values are consistent with the ones
listed at the top of this document. This will ensure that all hooks follow the same API.
</Banner>
## Example
For a working demonstration of this, check out the official [Live Preview Example](https://github.com/payloadcms/payload/tree/main/examples/live-preview/payload). There you will find examples of various front-end frameworks and how to integrate each one of them, including:
- [Next.js App Router](https://github.com/payloadcms/payload/tree/main/examples/live-preview/next-app)
- [Next.js Pages Router](https://github.com/payloadcms/payload/tree/main/examples/live-preview/next-pages)
## Troubleshooting
#### Relationships and/or uploads are not populating
If you are using relationships or uploads in your front-end application, and your front-end application runs on a different domain than your Payload server, you may need to configure [CORS](../configuration/overview) to allow requests to be made between the two domains. This includes sites that are running on a different port or subdomain. Similarly, if you are protecting resources behind user authentication, you may also need to configure [CSRF](../authentication/overview#csrf-protection) to allow cookies to be sent between the two domains. For example:
```ts
// payload.config.ts
{
// ...
// If your site is running on a different domain than your Payload server,
// This will allows requests to be made between the two domains
cors: {
[
'http://localhost:3001' // Your front-end application
],
},
// If you are protecting resources behind user authentication,
// This will allow cookies to be sent between the two domains
csrf: {
[
'http://localhost:3001' // Your front-end application
],
},
}
```
#### Relationships and/or uploads disappear after editing a document
It is possible that either you are setting an improper [`depth`](../getting-started/concepts#depth) in your initial request and/or your `useLivePreview` hook, or they're mismatched. Ensure that the `depth` parameter is set to the correct value, and that it matches exactly in both places. For example:
```tsx
// Your initial request
const { docs } = await payload.find({
collection: 'pages',
depth: 1, // Ensure this is set to the proper depth for your application
where: {
slug: {
equals: 'home',
},
},
})
```
```tsx
// Your hook
const { data } = useLivePreview<PageType>({
initialData: initialPage,
serverURL: PAYLOAD_SERVER_URL,
depth: 1, // Ensure this matches the depth of your initial request
})
```

View File

@@ -8,7 +8,7 @@ keywords: live preview, preview, live, iframe, iframe preview, visual editing, d
**With Live Preview you can render your front-end application directly within the Admin panel. As you type, your changes take effect in real-time. No need to save a draft or publish your changes.**
Live Preview works by rendering an iframe on the page that loads your front-end application. The Admin panel communicates with your app through [`window.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) events. These events are emitted every time a change is made to the document. Your app then listens for these events and re-renders itself with the data it receives.
Live Preview works by rendering an iframe on the page that loads your front-end application. The Admin panel communicates with your app through [`window.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) events. These events are emitted every time a change is made to the document. Your app then listens for these events and re-renders itself with the data it receives. Live Preview works in both server-side as well as client-side environments. See [Front-End](./frontend) for more details.
{/* IMAGE OF LIVE PREVIEW HERE */}

View File

@@ -0,0 +1,174 @@
---
title: Server-side Live Preview
label: Server-side
order: 30
desc: Learn how to implement Live Preview in your server-side front-end application.
keywords: live preview, frontend, react, next.js, vue, nuxt.js, svelte, hook, useLivePreview
---
<Banner type="info">
Server-side Live Preview is only for front-end frameworks that support the concept of Server Components, i.e. [React Server Components](https://react.dev/reference/rsc/server-components). If your front-end application is built with a client-side framework like the [Next.js Pages Router](https://nextjs.org/docs/pages), [React Router](https://reactrouter.com), [Vue 3](https://vuejs.org), etc., see [client-side Live Preview](./client).
</Banner>
Server-side Live Preview works by making a roundtrip to the server every time your document is saved, i.e. draft save, autosave, or publish. While using Live Preview, the Admin panel emits a new `window.postMessage` event which your front-end application can use to invoke this process. In Next.js, this means simply calling `router.refresh()` which will hydrate the HTML using new data straight from the [Local API](../local-api/overview).
<Banner type="warning">
It is recommended that you enable [Autosave](../versions/autosave) alongside Live Preview to make the experience feel more responsive.
</Banner>
If your front-end application is built with [React](#react), you can use the `RefreshRouteOnChange` function that Payload provides and give it your own router refresh function. In the future, all other major frameworks like Vue and Svelte will be officially supported. If you are using any of these frameworks today, you can still integrate with Live Preview yourself using the underlying tooling that Payload provides. See [building your own router refresh component](#building-your-own-router-refresh-component) for more information.
### React
If your front-end application is built with [React](https://react.dev) or [Next.js](https://nextjs.org), you can use the `RefreshRouteOnSave` component that Payload provides.
First, install the `@payloadcms/live-preview-react` package:
```bash
npm install @payloadcms/live-preview-react
```
Then, render `RefreshRouteOnSave` anywhere in your `page.tsx`. Here's an example:
`page.tsx`:
```tsx
import { RefreshRouteOnSave } from './RefreshRouteOnSave.tsx'
import { getPayloadHMR } from '@payloadcms/next'
import config from '../payload.config'
export default async function Page() {
const payload = await getPayloadHMR({ config })
const page = await payload.find({
collection: 'pages',
draft: true
})
return (
<Fragment>
<RefreshRouteOnSave />
<h1>Hello, world!</h1>
</Fragment>
)
}
```
`RefreshRouteOnSave.tsx`:
```tsx
'use client'
import { RefreshRouteOnSave as PayloadLivePreview } from '@payloadcms/live-preview-react'
import { useRouter } from 'next/navigation.js'
import React from 'react'
export const RefreshRouteOnSave: React.FC = () => {
const router = useRouter()
return <PayloadLivePreview refresh={router.refresh} serverURL={process.env.PAYLOAD_SERVER_URL} />
}
```
## Building your own router refresh component
No matter what front-end framework you are using, you can build your own component using the same underlying tooling that Payload provides.
First, install the base `@payloadcms/live-preview` package:
```bash
npm install @payloadcms/live-preview
```
This package provides the following functions:
| Path | Description |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| **`ready`** | Sends a `window.postMessage` event to the Admin panel to indicate that the front-end is ready to receive messages. |
| **`isDocumentEvent`** | Checks if a `MessageEvent` originates from the Admin panel and is a document-level event, i.e. draft save, autosave, publish, etc. |
With these functions, you can build your own hook using your front-end framework of choice:
```tsx
import { ready, isDocumentEvent } from '@payloadcms/live-preview'
// To build your own component:
// 1. Listen for document-level `window.postMessage` events sent from the Admin panel
// 2. Tell the Admin panel when it is ready to receive messages
// 3. Refresh the route every time a new document-level event is received
// 4. Unsubscribe from the `window.postMessage` events when it unmounts
```
Here is an example of what the same `RefreshRouteOnSave` React component from above looks like under the hood:
```tsx
'use client'
import type React from 'react'
import { isDocumentEvent, ready } from '@payloadcms/live-preview'
import { useCallback, useEffect, useRef } from 'react'
export const RefreshRouteOnSave: React.FC<{
apiRoute?: string
depth?: number
refresh: () => void
serverURL: string
}> = (props) => {
const { apiRoute, depth, refresh, serverURL } = props
const hasSentReadyMessage = useRef<boolean>(false)
const onMessage = useCallback(
(event: MessageEvent) => {
if (isDocumentEvent(event, serverURL)) {
if (typeof refresh === 'function') {
refresh()
}
}
},
[refresh, serverURL],
)
useEffect(() => {
if (typeof window !== 'undefined') {
window.addEventListener('message', onMessage)
}
if (!hasSentReadyMessage.current) {
hasSentReadyMessage.current = true
ready({
serverURL,
})
}
return () => {
if (typeof window !== 'undefined') {
window.removeEventListener('message', onMessage)
}
}
}, [serverURL, onMessage, depth, apiRoute])
return null
}
```
## Example
{/* TODO: add example once beta has been release and an example can be created */}
## Troubleshooting
#### Updates do not appear as fast as client-side Live Preview
If you are noticing that updates feel less snappy than client-side Live Preview (i.e. the `useLivePreview` hook), this is because of how the two differ in how they work—instead of emitting events against form state as you type, server-side Live Preview refreshes the route after a new document is saved. You can use autosave to mimic this effect. Try decreasing the value of `versions.autoSave.interval` to make the experience feel more responsive:
```ts
// collection.ts
{
versions: {
drafts: {
autosave: {
interval: 10,
},
},
},
}
```

View File

@@ -0,0 +1,52 @@
'use client'
import type React from 'react'
import { isDocumentEvent, ready } from '@payloadcms/live-preview'
import { useCallback, useEffect, useRef } from 'react'
export const RefreshRouteOnSave: React.FC<{
apiRoute?: string
depth?: number
refresh: () => void
serverURL: string
}> = (props) => {
const { apiRoute, depth, refresh, serverURL } = props
const hasSentReadyMessage = useRef<boolean>(false)
const onMessage = useCallback(
(event: MessageEvent) => {
if (isDocumentEvent(event, serverURL)) {
if (typeof refresh === 'function') {
refresh()
} else {
// eslint-disable-next-line no-console
console.error('You must provide a refresh function to `RefreshRouteOnSave`')
}
}
},
[refresh, serverURL],
)
useEffect(() => {
if (typeof window !== 'undefined') {
window.addEventListener('message', onMessage)
}
if (!hasSentReadyMessage.current) {
hasSentReadyMessage.current = true
ready({
serverURL,
})
}
return () => {
if (typeof window !== 'undefined') {
window.removeEventListener('message', onMessage)
}
}
}, [serverURL, onMessage, depth, apiRoute])
return null
}

View File

@@ -1,54 +1,2 @@
import { ready, subscribe, unsubscribe } from '@payloadcms/live-preview'
import { useCallback, useEffect, useRef, useState } from 'react'
// To prevent the flicker of missing data on initial load,
// you can pass in the initial page data from the server
// To prevent the flicker of stale data while the post message is being sent,
// you can conditionally render loading UI based on the `isLoading` state
export const useLivePreview = <T extends any>(props: {
apiRoute?: string
depth?: number
initialData: T
serverURL: string
}): {
data: T
isLoading: boolean
} => {
const { apiRoute, depth, initialData, serverURL } = props
const [data, setData] = useState<T>(initialData)
const [isLoading, setIsLoading] = useState<boolean>(true)
const hasSentReadyMessage = useRef<boolean>(false)
const onChange = useCallback((mergedData) => {
setData(mergedData)
setIsLoading(false)
}, [])
useEffect(() => {
const subscription = subscribe({
apiRoute,
callback: onChange,
depth,
initialData,
serverURL,
})
if (!hasSentReadyMessage.current) {
hasSentReadyMessage.current = true
ready({
serverURL,
})
}
return () => {
unsubscribe(subscription)
}
}, [serverURL, onChange, depth, initialData, apiRoute])
return {
data,
isLoading,
}
}
export { RefreshRouteOnSave } from './RefreshRouteOnSave.js'
export { useLivePreview } from './useLivePreview.js'

View File

@@ -0,0 +1,55 @@
'use client'
import { ready, subscribe, unsubscribe } from '@payloadcms/live-preview'
import { useCallback, useEffect, useRef, useState } from 'react'
// To prevent the flicker of missing data on initial load,
// you can pass in the initial page data from the server
// To prevent the flicker of stale data while the post message is being sent,
// you can conditionally render loading UI based on the `isLoading` state
export const useLivePreview = <T extends any>(props: {
apiRoute?: string
depth?: number
initialData: T
serverURL: string
}): {
data: T
isLoading: boolean
} => {
const { apiRoute, depth, initialData, serverURL } = props
const [data, setData] = useState<T>(initialData)
const [isLoading, setIsLoading] = useState<boolean>(true)
const hasSentReadyMessage = useRef<boolean>(false)
const onChange = useCallback((mergedData) => {
setData(mergedData)
setIsLoading(false)
}, [])
useEffect(() => {
const subscription = subscribe({
apiRoute,
callback: onChange,
depth,
initialData,
serverURL,
})
if (!hasSentReadyMessage.current) {
hasSentReadyMessage.current = true
ready({
serverURL,
})
}
return () => {
unsubscribe(subscription)
}
}, [serverURL, onChange, depth, initialData, apiRoute])
return {
data,
isLoading,
}
}

View File

@@ -1,8 +0,0 @@
export declare const handleMessage: <T>(args: {
apiRoute?: string
depth?: number
event: MessageEvent
initialData: T
serverURL: string
}) => Promise<T>
//# sourceMappingURL=handleMessage.d.ts.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"handleMessage.d.ts","sourceRoot":"","sources":["handleMessage.ts"],"names":[],"mappings":"AAYA,eAAO,MAAM,aAAa;eACb,MAAM;YACT,MAAM;WACP,YAAY;;eAER,MAAM;gBAyClB,CAAA"}

View File

@@ -1,3 +1,4 @@
import { isLivePreviewEvent } from './isLivePreviewEvent.js'
import { mergeData } from './mergeData.js'
// For performance reasons, `fieldSchemaJSON` will only be sent once on the initial message
@@ -19,12 +20,7 @@ export const handleMessage = async <T>(args: {
}): Promise<T> => {
const { apiRoute, depth, event, initialData, serverURL } = args
if (
event.origin === serverURL &&
event.data &&
typeof event.data === 'object' &&
event.data.type === 'payload-live-preview'
) {
if (isLivePreviewEvent(event, serverURL)) {
const { data, externallyUpdatedRelationship, fieldSchemaJSON } = event.data
if (!payloadLivePreviewFieldSchema && fieldSchemaJSON) {

View File

@@ -1,6 +0,0 @@
export { handleMessage } from './handleMessage.js'
export { mergeData } from './mergeData.js'
export { ready } from './ready.js'
export { subscribe } from './subscribe.js'
export { unsubscribe } from './unsubscribe.js'
//# sourceMappingURL=index.d.ts.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA"}

View File

@@ -1,4 +1,6 @@
export { handleMessage } from './handleMessage.js'
export { isDocumentEvent } from './isDocumentEvent.js'
export { isLivePreviewEvent } from './isLivePreviewEvent.js'
export { mergeData } from './mergeData.js'
export { ready } from './ready.js'
export { subscribe } from './subscribe.js'

View File

@@ -0,0 +1,5 @@
export const isDocumentEvent = (event: MessageEvent, serverURL: string): boolean =>
event.origin === serverURL &&
event.data &&
typeof event.data === 'object' &&
event.data.type === 'payload-document-event'

View File

@@ -0,0 +1,5 @@
export const isLivePreviewEvent = (event: MessageEvent, serverURL: string): boolean =>
event.origin === serverURL &&
event.data &&
typeof event.data === 'object' &&
event.data.type === 'payload-live-preview'

View File

@@ -1,26 +0,0 @@
import type { fieldSchemaToJSON } from 'payload/utilities'
import type { UpdatedDocument } from './types.js'
export declare const mergeData: <T>(args: {
apiRoute?: string
collectionPopulationRequestHandler?: ({
apiPath,
endpoint,
serverURL,
}: {
apiPath: string
endpoint: string
serverURL: string
}) => Promise<Response>
depth?: number
externallyUpdatedRelationship?: UpdatedDocument
fieldSchema: ReturnType<typeof fieldSchemaToJSON>
incomingData: Partial<T>
initialData: T
returnNumberOfRequests?: boolean
serverURL: string
}) => Promise<
T & {
_numberOfRequests?: number
}
>
//# sourceMappingURL=mergeData.d.ts.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"mergeData.d.ts","sourceRoot":"","sources":["mergeData.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AAE1D,OAAO,KAAK,EAA2B,eAAe,EAAE,MAAM,YAAY,CAAA;AAc1E,eAAO,MAAM,SAAS;eACT,MAAM;;iBAMN,MAAM;kBACL,MAAM;mBACL,MAAM;UACb,QAAQ,QAAQ,CAAC;YACf,MAAM;oCACkB,eAAe;iBAClC,WAAW,wBAAwB,CAAC;;;6BAGxB,OAAO;eACrB,MAAM;;wBAGK,MAAM;EA6D7B,CAAA"}

View File

@@ -1,8 +0,0 @@
export declare const subscribe: <T>(args: {
apiRoute?: string
callback: (data: T) => void
depth?: number
initialData: T
serverURL: string
}) => (event: MessageEvent) => void
//# sourceMappingURL=subscribe.d.ts.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"subscribe.d.ts","sourceRoot":"","sources":["subscribe.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,SAAS;eACT,MAAM;2BACM,IAAI;YACnB,MAAM;;eAEH,MAAM;cACN,YAAY,KAAK,IAa7B,CAAA"}

View File

@@ -10,7 +10,14 @@ export const subscribe = <T>(args: {
const { apiRoute, callback, depth, initialData, serverURL } = args
const onMessage = async (event: MessageEvent) => {
const mergedData = await handleMessage<T>({ apiRoute, depth, event, initialData, serverURL })
const mergedData = await handleMessage<T>({
apiRoute,
depth,
event,
initialData,
serverURL,
})
callback(mergedData)
}

View File

@@ -1,10 +0,0 @@
import type { fieldSchemaToJSON } from 'payload/utilities'
import type { PopulationsByCollection, UpdatedDocument } from './types.js'
export declare const traverseFields: <T>(args: {
externallyUpdatedRelationship?: UpdatedDocument
fieldSchema: ReturnType<typeof fieldSchemaToJSON>
incomingData: T
populationsByCollection: PopulationsByCollection
result: T
}) => void
//# sourceMappingURL=traverseFields.d.ts.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"traverseFields.d.ts","sourceRoot":"","sources":["traverseFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AAE1D,OAAO,KAAK,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAI1E,eAAO,MAAM,cAAc;oCACO,eAAe;iBAClC,WAAW,wBAAwB,CAAC;;6BAExB,uBAAuB;;MAE9C,IA4QH,CAAA"}

View File

@@ -3,6 +3,7 @@ export { GRAPHQL_PLAYGROUND_GET, GRAPHQL_POST } from './graphql/index.js'
export {
DELETE as REST_DELETE,
GET as REST_GET,
OPTIONS as REST_OPTIONS,
PATCH as REST_PATCH,
POST as REST_POST,
} from './rest/index.js'

View File

@@ -36,6 +36,7 @@ export const LivePreview: React.FC<EditViewProps> = (props) => {
const [fields] = useAllFormFields()
// For client-side apps, send data through `window.postMessage`
// The preview could either be an iframe embedded on the page
// Or it could be a separate popup window
// We need to transmit data to both accordingly
@@ -83,6 +84,25 @@ export const LivePreview: React.FC<EditViewProps> = (props) => {
mostRecentUpdate,
])
// To support SSR, we transmit a `window.postMessage` event without a payload
// This is because the event will ultimately trigger a server-side roundtrip
// i.e., save, save draft, autosave, etc. will fire `router.refresh()`
useEffect(() => {
const message = {
type: 'payload-document-event',
}
// Post message to external popup window
if (previewWindowType === 'popup' && popupRef.current) {
popupRef.current.postMessage(message, url)
}
// Post message to embedded iframe
if (previewWindowType === 'iframe' && iframeRef.current) {
iframeRef.current.contentWindow?.postMessage(message, url)
}
}, [mostRecentUpdate, iframeRef, popupRef, previewWindowType, url])
if (previewWindowType === 'iframe') {
return (
<div

View File

@@ -2,6 +2,7 @@
// TODO: abstract the `next/navigation` dependency out from this component
import type { ClientCollectionConfig, ClientGlobalConfig } from 'payload/types'
import { useDocumentEvents } from '@payloadcms/ui/providers/DocumentEvents'
import React, { useEffect, useRef, useState } from 'react'
import { useAllFormFields, useFormModified } from '../../forms/Form/context.js'
@@ -34,6 +35,7 @@ export const Autosave: React.FC<Props> = ({
serverURL,
} = useConfig()
const { docConfig, getVersions, versions } = useDocumentInfo()
const { reportUpdate } = useDocumentEvents()
const versionsConfig = docConfig?.versions
const [fields] = useAllFormFields()
@@ -74,14 +76,17 @@ export const Autosave: React.FC<Props> = ({
let url: string
let method: string
let entitySlug: string
if (collection && id) {
url = `${serverURL}${api}/${collection.slug}/${id}?draft=true&autosave=true&locale=${localeRef.current}`
entitySlug = collection.slug
url = `${serverURL}${api}/${entitySlug}/${id}?draft=true&autosave=true&locale=${localeRef.current}`
method = 'PATCH'
}
if (globalDoc) {
url = `${serverURL}${api}/globals/${globalDoc.slug}?draft=true&autosave=true&locale=${localeRef.current}`
entitySlug = globalDoc.slug
url = `${serverURL}${api}/globals/${entitySlug}?draft=true&autosave=true&locale=${localeRef.current}`
method = 'POST'
}
@@ -103,7 +108,13 @@ export const Autosave: React.FC<Props> = ({
})
if (res.status === 200) {
setLastSaved(new Date().getTime())
const newDate = new Date()
setLastSaved(newDate.getTime())
reportUpdate({
id,
entitySlug,
updatedAt: newDate.toISOString(),
})
void getVersions()
}
}
@@ -115,7 +126,18 @@ export const Autosave: React.FC<Props> = ({
}
void autosave()
}, [i18n, debouncedFields, modified, serverURL, api, collection, globalDoc, id, getVersions])
}, [
i18n,
debouncedFields,
modified,
serverURL,
api,
collection,
globalDoc,
reportUpdate,
id,
getVersions,
])
useEffect(() => {
if (versions?.docs?.[0]) {

View File

@@ -1,9 +1,10 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY it because it could be re-written at any time. */
import config from '@payload-config'
import { REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes/index.js'
import { REST_DELETE, REST_GET, REST_OPTIONS, REST_PATCH, REST_POST } from '@payloadcms/next/routes'
export const GET = REST_GET(config)
export const POST = REST_POST(config)
export const DELETE = REST_DELETE(config)
export const PATCH = REST_PATCH(config)
export const OPTIONS = REST_OPTIONS(config)

View File

@@ -5,6 +5,7 @@ import React from 'react'
import type { Page as PageType } from '../../../../payload-types.js'
import { renderedPageTitleID } from '../../../../shared.js'
import { PAYLOAD_SERVER_URL } from '../../_api/serverURL.js'
import { Blocks } from '../../_components/Blocks/index.js'
import { Gutter } from '../../_components/Gutter/index.js'
@@ -22,7 +23,7 @@ export const PageClient: React.FC<{
return (
<React.Fragment>
<Gutter>
<h1 id="page-title">{data.title}</h1>
<div id={renderedPageTitleID}>{data.title}</div>
</Gutter>
<Hero {...data?.hero} />
<Blocks

View File

@@ -0,0 +1,12 @@
'use client'
import { RefreshRouteOnSave as PayloadLivePreview } from '@payloadcms/live-preview-react'
import { useRouter } from 'next/navigation.js'
import React from 'react'
import { PAYLOAD_SERVER_URL } from '../../../_api/serverURL.js'
export const RefreshRouteOnSave: React.FC = () => {
const router = useRouter()
return <PayloadLivePreview refresh={() => router.refresh()} serverURL={PAYLOAD_SERVER_URL} />
}

View File

@@ -0,0 +1,94 @@
/* eslint-disable no-restricted-exports */
import { Gutter } from '@payloadcms/ui/elements/Gutter'
import { notFound } from 'next/navigation.js'
import React, { Fragment } from 'react'
import type { Post } from '../../../../../payload-types.js'
import { ssrPostsSlug } from '../../../../../shared.js'
import { renderedPageTitleID } from '../../../../../shared.js'
import { fetchDoc } from '../../../_api/fetchDoc.js'
import { fetchDocs } from '../../../_api/fetchDocs.js'
import { Blocks } from '../../../_components/Blocks/index.js'
import { PostHero } from '../../../_heros/PostHero/index.js'
import { RefreshRouteOnSave } from './RefreshRouteOnSave.js'
export default async function SSRPost({ params: { slug = '' } }) {
let data: Post | null = null
try {
data = await fetchDoc<Post>({
slug,
collection: ssrPostsSlug,
draft: true,
})
} catch (error) {
console.error(error) // eslint-disable-line no-console
}
if (!data) {
notFound()
}
return (
<Fragment>
<RefreshRouteOnSave />
<Gutter>
<div id={renderedPageTitleID}>{data.title}</div>
</Gutter>
<PostHero post={data} />
<Blocks blocks={data?.layout} />
<Blocks
blocks={[
{
blockName: 'Related Posts',
blockType: 'relatedPosts',
docs: data?.relatedPosts,
introContent: [
{
type: 'h4',
children: [
{
text: 'Related posts',
},
],
},
{
type: 'p',
children: [
{
text: 'The posts displayed here are individually selected for this page. Admins can select any number of related posts to display here and the layout will adjust accordingly. Alternatively, you could swap this out for the "Archive" block to automatically populate posts by category complete with pagination. To manage related posts, ',
},
{
type: 'link',
children: [
{
text: 'navigate to the admin dashboard',
},
],
url: `/admin/collections/ssr/${data?.id}`,
},
{
text: '.',
},
],
},
],
relationTo: 'posts',
},
]}
disableTopPadding
/>
</Fragment>
)
}
export async function generateStaticParams() {
process.env.PAYLOAD_DROP_DATABASE = 'false'
try {
const ssrPosts = await fetchDocs<Post>(ssrPostsSlug)
return ssrPosts?.map(({ slug }) => slug)
} catch (error) {
return []
}
}

View File

@@ -1,10 +1,12 @@
'use client'
import { useLivePreview } from '@payloadcms/live-preview-react'
import { Gutter } from '@payloadcms/ui/elements/Gutter'
import React from 'react'
import type { Post as PostType } from '../../../../../payload-types.js'
import { renderedPageTitleID } from '../../../../../shared.js'
import { PAYLOAD_SERVER_URL } from '../../../_api/serverURL.js'
import { Blocks } from '../../../_components/Blocks/index.js'
import { PostHero } from '../../../_heros/PostHero/index.js'
@@ -20,6 +22,9 @@ export const PostClient: React.FC<{
return (
<React.Fragment>
<Gutter>
<div id={renderedPageTitleID}>{data.title}</div>
</Gutter>
<PostHero post={data} />
<Blocks blocks={data?.layout} />
<Blocks

View File

@@ -1,8 +1,10 @@
/* eslint-disable no-restricted-exports */
import { notFound } from 'next/navigation.js'
import React from 'react'
import type { Post } from '../../../../../payload-types.js'
import { postsSlug } from '../../../../../collections/Posts.js'
import { fetchDoc } from '../../../_api/fetchDoc.js'
import { fetchDocs } from '../../../_api/fetchDocs.js'
import { PostClient } from './page.client.js'
@@ -13,7 +15,7 @@ export default async function Post({ params: { slug = '' } }) {
try {
post = await fetchDoc<Post>({
slug,
collection: 'posts',
collection: postsSlug,
})
} catch (error) {
console.error(error) // eslint-disable-line no-console
@@ -29,8 +31,8 @@ export default async function Post({ params: { slug = '' } }) {
export async function generateStaticParams() {
process.env.PAYLOAD_DROP_DATABASE = 'false'
try {
const posts = await fetchDocs<Post>('posts')
return posts?.map(({ slug }) => slug)
const ssrPosts = await fetchDocs<Post>(postsSlug)
return ssrPosts?.map(({ slug }) => slug)
} catch (error) {
return []
}

View File

@@ -6,10 +6,11 @@ import { getPayloadHMR } from '@payloadcms/next/utilities/getPayloadHMR.js'
export const fetchDoc = async <T>(args: {
collection: string
depth?: number
draft?: boolean
slug?: string
}): Promise<T> => {
const payload = await getPayloadHMR({ config })
const { slug, collection, depth = 2 } = args || {}
const { slug, collection, depth = 2, draft } = args || {}
const where: Where = {}
@@ -24,6 +25,7 @@ export const fetchDoc = async <T>(args: {
collection,
depth,
where,
draft,
})
if (docs[0]) return docs[0] as T

View File

@@ -0,0 +1,107 @@
import type { CollectionConfig } from 'payload/types'
import { Archive } from '../blocks/ArchiveBlock/index.js'
import { CallToAction } from '../blocks/CallToAction/index.js'
import { Content } from '../blocks/Content/index.js'
import { MediaBlock } from '../blocks/MediaBlock/index.js'
import { hero } from '../fields/hero.js'
import { ssrPostsSlug, tenantsSlug } from '../shared.js'
export const PostsSSR: CollectionConfig = {
slug: ssrPostsSlug,
labels: {
singular: 'SSR Post',
plural: 'SSR Posts',
},
access: {
read: () => true,
create: () => true,
update: () => true,
delete: () => true,
},
versions: {
drafts: {
autosave: {
interval: 10,
},
},
},
admin: {
useAsTitle: 'title',
defaultColumns: ['id', 'title', 'slug', 'createdAt'],
},
fields: [
{
name: 'slug',
type: 'text',
required: true,
admin: {
position: 'sidebar',
},
},
{
name: 'tenant',
type: 'relationship',
relationTo: tenantsSlug,
admin: {
position: 'sidebar',
},
},
{
name: 'title',
type: 'text',
required: true,
},
{
type: 'tabs',
tabs: [
{
label: 'Hero',
fields: [hero],
},
{
label: 'Content',
fields: [
{
name: 'layout',
type: 'blocks',
blocks: [CallToAction, Content, MediaBlock, Archive],
},
{
name: 'relatedPosts',
type: 'relationship',
relationTo: 'posts',
hasMany: true,
filterOptions: ({ id }) => {
return {
id: {
not_in: [id],
},
}
},
},
],
},
],
},
{
name: 'meta',
type: 'group',
fields: [
{
name: 'title',
type: 'text',
},
{
name: 'description',
type: 'textarea',
},
{
name: 'image',
type: 'upload',
relationTo: 'media',
},
],
},
],
}

View File

@@ -2,13 +2,14 @@ import { buildConfigWithDefaults } from '../buildConfigWithDefaults.js'
import Categories from './collections/Categories.js'
import { Media } from './collections/Media.js'
import { Pages } from './collections/Pages.js'
import { Posts } from './collections/Posts.js'
import { Posts, postsSlug } from './collections/Posts.js'
import { PostsSSR } from './collections/PostsSSR.js'
import { Tenants } from './collections/Tenants.js'
import { Users } from './collections/Users.js'
import { Footer } from './globals/Footer.js'
import { Header } from './globals/Header.js'
import { seed } from './seed/index.js'
import { mobileBreakpoint } from './shared.js'
import { mobileBreakpoint, pagesSlug, ssrPostsSlug } from './shared.js'
import { formatLivePreviewURL } from './utilities/formatLivePreviewURL.js'
export default buildConfigWithDefaults({
@@ -18,13 +19,13 @@ export default buildConfigWithDefaults({
// The Live Preview config cascades from the top down, properties are inherited from here
url: formatLivePreviewURL,
breakpoints: [mobileBreakpoint],
collections: ['pages', 'posts'],
collections: [pagesSlug, postsSlug, ssrPostsSlug],
globals: ['header', 'footer'],
},
},
cors: ['http://localhost:3000', 'http://localhost:3001'],
csrf: ['http://localhost:3000', 'http://localhost:3001'],
collections: [Users, Pages, Posts, Tenants, Categories, Media],
collections: [Users, Pages, Posts, PostsSSR, Tenants, Categories, Media],
globals: [Header, Footer],
onInit: seed,
})

View File

@@ -14,7 +14,7 @@ import {
import { AdminUrlUtil } from '../helpers/adminUrlUtil.js'
import { initPayloadE2ENoConfig } from '../helpers/initPayloadE2ENoConfig.js'
import { POLL_TOPASS_TIMEOUT, TEST_TIMEOUT_LONG } from '../playwright.config.js'
import { mobileBreakpoint } from './shared.js'
import { mobileBreakpoint, pagesSlug, renderedPageTitleID, ssrPostsSlug } from './shared.js'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
@@ -23,16 +23,18 @@ const { beforeAll, describe } = test
describe('Live Preview', () => {
let page: Page
let serverURL: string
let url: AdminUrlUtil
const goToDoc = async (page: Page) => {
await page.goto(url.list)
await page.waitForURL(url.list)
let pagesURLUtil: AdminUrlUtil
let ssrPostsURLUtil: AdminUrlUtil
const goToDoc = async (page: Page, urlUtil: AdminUrlUtil) => {
await page.goto(urlUtil.list)
await page.waitForURL(urlUtil.list)
await navigateToListCellLink(page)
}
const goToCollectionPreview = async (page: Page): Promise<void> => {
await goToDoc(page)
const goToCollectionPreview = async (page: Page, urlUtil: AdminUrlUtil): Promise<void> => {
await goToDoc(page, urlUtil)
await page.goto(`${page.url()}/preview`)
await page.waitForURL(`**/preview`)
}
@@ -47,7 +49,10 @@ describe('Live Preview', () => {
beforeAll(async ({ browser }, testInfo) => {
testInfo.setTimeout(TEST_TIMEOUT_LONG)
;({ serverURL } = await initPayloadE2ENoConfig({ dirname }))
url = new AdminUrlUtil(serverURL, 'pages')
pagesURLUtil = new AdminUrlUtil(serverURL, pagesSlug)
ssrPostsURLUtil = new AdminUrlUtil(serverURL, ssrPostsSlug)
const context = await browser.newContext()
page = await context.newPage()
@@ -57,7 +62,7 @@ describe('Live Preview', () => {
})
test('collection — has tab', async () => {
await goToDoc(page)
await goToDoc(page, pagesURLUtil)
const livePreviewTab = page.locator('.doc-tab', {
hasText: exactText('Live Preview'),
@@ -75,46 +80,82 @@ describe('Live Preview', () => {
})
test('collection — has route', async () => {
await goToDoc(page)
await goToCollectionPreview(page)
await goToCollectionPreview(page, pagesURLUtil)
await expect(page.locator('.live-preview')).toBeVisible()
})
test('collection — renders iframe', async () => {
await goToCollectionPreview(page)
await goToCollectionPreview(page, pagesURLUtil)
const iframe = page.locator('iframe.live-preview-iframe')
await expect(iframe).toBeVisible()
})
test('collection — can edit fields and can preview updated value', async () => {
await goToCollectionPreview(page)
const titleValue = 'Title 1'
const field = page.locator('#field-title')
test('collection — re-renders iframe client-side when form state changes', async () => {
await goToCollectionPreview(page, pagesURLUtil)
const titleField = page.locator('#field-title')
const frame = page.frameLocator('iframe.live-preview-iframe').first()
await expect(field).toBeVisible()
await expect(titleField).toBeVisible()
// Forces the test to wait for the nextjs route to render before we try editing a field
await expect(() => expect(frame.locator('#page-title')).toBeVisible()).toPass({
const renderedPageTitleLocator = `#${renderedPageTitleID}`
// Forces the test to wait for the Next.js route to render before we try editing a field
await expect(() => expect(frame.locator(renderedPageTitleLocator)).toBeVisible()).toPass({
timeout: POLL_TOPASS_TIMEOUT,
})
await field.fill(titleValue)
await expect(frame.locator(renderedPageTitleLocator)).toHaveText('Home')
await expect(() => expect(frame.locator('#page-title')).toHaveText(titleValue)).toPass({
const newTitleValue = 'Home (Edited)'
await titleField.fill(newTitleValue)
await expect(() =>
expect(frame.locator(renderedPageTitleLocator)).toHaveText(newTitleValue),
).toPass({
timeout: POLL_TOPASS_TIMEOUT,
})
await saveDocAndAssert(page)
})
test('collection — should show live-preview view level action in live-preview view', async () => {
await goToCollectionPreview(page)
test('collection — re-render iframe server-side when autosave is made', async () => {
await goToCollectionPreview(page, ssrPostsURLUtil)
const titleField = page.locator('#field-title')
const frame = page.frameLocator('iframe.live-preview-iframe').first()
await expect(titleField).toBeVisible()
const renderedPageTitleLocator = `#${renderedPageTitleID}`
// Forces the test to wait for the Next.js route to render before we try editing a field
await expect(() => expect(frame.locator(renderedPageTitleLocator)).toBeVisible()).toPass({
timeout: POLL_TOPASS_TIMEOUT,
})
await expect(frame.locator(renderedPageTitleLocator)).toHaveText('SSR Post 1')
const newTitleValue = 'SSR Post 1 (Edited)'
await titleField.fill(newTitleValue)
await expect(() =>
expect(frame.locator(renderedPageTitleLocator)).toHaveText(newTitleValue),
).toPass({
timeout: POLL_TOPASS_TIMEOUT,
})
await saveDocAndAssert(page)
})
test('collection — should show live-preview view-level action in live-preview view', async () => {
await goToCollectionPreview(page, pagesURLUtil)
await expect(page.locator('.app-header .collection-live-preview-button')).toHaveCount(1)
})
test('global — should show live-preview view level action in live-preview view', async () => {
test('global — should show live-preview view-level action in live-preview view', async () => {
await goToGlobalPreview(page, 'footer')
await expect(page.locator('.app-header .global-live-preview-button')).toHaveCount(1)
})
@@ -164,13 +205,13 @@ describe('Live Preview', () => {
})
test('properly measures iframe and displays size', async () => {
await page.goto(url.create)
await page.waitForURL(url.create)
await page.goto(pagesURLUtil.create)
await page.waitForURL(pagesURLUtil.create)
await page.locator('#field-title').fill('Title 3')
await page.locator('#field-slug').fill('slug-3')
await saveDocAndAssert(page)
await goToCollectionPreview(page)
await goToCollectionPreview(page, pagesURLUtil)
const iframe = page.locator('iframe')
@@ -213,13 +254,13 @@ describe('Live Preview', () => {
})
test('resizes iframe to specified breakpoint', async () => {
await page.goto(url.create)
await page.waitForURL(url.create)
await page.goto(pagesURLUtil.create)
await page.waitForURL(pagesURLUtil.create)
await page.locator('#field-title').fill('Title 4')
await page.locator('#field-slug').fill('slug-4')
await saveDocAndAssert(page)
await goToCollectionPreview(page)
await goToCollectionPreview(page, pagesURLUtil)
// Check that the breakpoint select is present
const breakpointSelector = page.locator(

View File

@@ -6,7 +6,7 @@ import { fileURLToPath } from 'url'
import { devUser } from '../../credentials.js'
import removeFiles from '../../helpers/removeFiles.js'
import { postsSlug } from '../collections/Posts.js'
import { pagesSlug, tenantsSlug } from '../shared.js'
import { pagesSlug, ssrPostsSlug, tenantsSlug } from '../shared.js'
import { footer } from './footer.js'
import { header } from './header.js'
import { home } from './home.js'
@@ -61,6 +61,22 @@ export const seed: Config['onInit'] = async (payload) => {
),
})
await payload.create({
collection: ssrPostsSlug,
data: {
...JSON.parse(
JSON.stringify(post1)
.replace(/"\{\{IMAGE\}\}"/g, mediaID)
.replace(/"\{\{TENANT_1_ID\}\}"/g, tenantID),
),
title: 'SSR Post 1',
meta: {
title: 'SSR Post 1',
description: 'This is the first SSR post.',
},
},
})
const post2Doc = await payload.create({
collection: postsSlug,
data: JSON.parse(

View File

@@ -2,9 +2,13 @@ export const pagesSlug = 'pages'
export const tenantsSlug = 'tenants'
export const ssrPostsSlug = 'posts-ssr'
export const mobileBreakpoint = {
label: 'Mobile',
name: 'mobile',
width: 375,
height: 667,
}
export const renderedPageTitleID = 'rendered-page-title'

View File

@@ -35,7 +35,7 @@
"@payloadcms/ui/utilities/*": ["../../packages/ui/src/utilities/*.ts"],
"@payloadcms/ui/scss": ["../../packages/ui/src/scss.scss"],
"@payloadcms/ui/scss/app.scss": ["../../packages/ui/src/scss/app.scss"],
"payload/types": ["../../packages/payload/src/exports/types/index.ts"],
"payload/types": ["../../packages/payload/src/exports/types.ts"],
"@payloadcms/next/*": ["../../packages/next/src/*"],
"@payloadcms/next": ["../../packages/next/src/exports/*"],
}