Skip to content

Commit

Permalink
feat!: enable turbo mode for everyone (#705)
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan authored Nov 29, 2023
1 parent e1aa64f commit 5094cb5
Show file tree
Hide file tree
Showing 49 changed files with 506 additions and 1,054 deletions.
9 changes: 4 additions & 5 deletions apps/next-app-router/app/Variant.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import dynamic from 'next/dynamic'
import { lazy } from 'react'

const DefaultVariant = dynamic(() => import('./variants/default'))
const GroqStoreVariant = dynamic(() => import('./variants/groq-store'))
const LiveStoreVariant = dynamic(() => import('./variants/live-store'))
const GroqStoreVariant = lazy(() => import('./variants/groq-store'))
const LiveStoreVariant = lazy(() => import('./variants/live-store'))

export default function Variant(props: React.PropsWithChildren) {
switch (process.env.VARIANT || 'default') {
case 'default':
return <DefaultVariant {...props} />
return <>{props.children}</>
case 'groq-store':
return <GroqStoreVariant {...props} />
case 'live-store':
Expand Down
2 changes: 2 additions & 0 deletions apps/next-app-router/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { unstable__adapter, unstable__environment } from '@sanity/client'
import DraftModeButton from './DraftModeButton'
import type { Metadata } from 'next'

export const runtime = 'edge'

export const metadata: Metadata = {
title: `next-app-router-${process.env.VARIANT || 'default'}`,
}
Expand Down
4 changes: 4 additions & 0 deletions apps/next-app-router/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import Variant from './Variant'
import { PreviewTable, PreviewFooter } from './previews'
import { Suspense } from 'react'

export const runtime = 'edge'

export default async function Page() {
const footer = await sanityFetch<FooterProps['data']>({
query: footerQuery,
Expand All @@ -32,6 +34,7 @@ export default async function Page() {
initialData={footer}
query={footerQuery}
as={PreviewFooter}
throwOnMissingProvider={false}
>
<Footer data={footer} />
</LiveQuery>
Expand All @@ -53,6 +56,7 @@ async function ServerTable() {
initialData={data}
query={tableQuery}
as={PreviewTable}
throwOnMissingProvider={false}
>
<Table data={data} />
</LiveQuery>
Expand Down
3 changes: 0 additions & 3 deletions apps/next-app-router/app/variants/default/index.tsx

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,7 @@ export default function PreviewProvider({
const { client } = suspend(() => import('./sanity.client'), [UniqueKey])
if (!token) throw new TypeError('Missing token')
return (
<LiveQueryProvider
client={client}
token={token}
logger={console}
cache={{ includeTypes: ['page'] }}
>
<LiveQueryProvider client={client} token={token} logger={console}>
{children}
</LiveQueryProvider>
)
Expand Down
3 changes: 2 additions & 1 deletion apps/next-app-router/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const nextConfig = {
fullUrl: true,
},
},
reactStrictMode: true,
serverActions: true,
productionBrowserSourceMaps: true,
// Support Vercel Authentication protection
Expand All @@ -21,7 +22,7 @@ const nextConfig = {
},
{
key: 'Content-Security-Policy',
value: `frame-ancestors 'self' https://*.sanity.build`,
value: `frame-ancestors 'self' https://*.sanity.build http://localhost:3333`,
},
],
},
Expand Down
3 changes: 2 additions & 1 deletion apps/next-pages-router/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const nextConfig = {
fullUrl: true,
},
},
reactStrictMode: true,
productionBrowserSourceMaps: true,
// Support Vercel Authentication protection
async headers() {
Expand All @@ -20,7 +21,7 @@ const nextConfig = {
},
{
key: 'Content-Security-Policy',
value: `frame-ancestors 'self' https://*.sanity.build`,
value: `frame-ancestors 'self' https://*.sanity.build http://localhost:3333`,
},
],
},
Expand Down
25 changes: 7 additions & 18 deletions apps/next-pages-router/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
tableQuery,
} from 'ui/react'
import dynamic from 'next/dynamic'
import { useIsEnabled } from '@sanity/preview-kit'
import { useIsEnabled, useLiveQuery } from '@sanity/preview-kit'
import { LiveQuery } from '@sanity/preview-kit/live-query'
import { sanityFetch, token } from '../sanity.fetch'

Expand Down Expand Up @@ -82,6 +82,8 @@ export default function Page(
client__environment: environment,
})
}, [])
const [table, , isLive] = useLiveQuery(props.table, tableQuery)
const [footer] = useLiveQuery(props.footer, footerQuery)

return (
<Container>
Expand All @@ -93,22 +95,10 @@ export default function Page(
)}
</form>
<Variant {...props}>
<LiveQuery
enabled={draftMode}
initialData={props.table}
query={tableQuery}
>
<Table data={props.table} />
</LiveQuery>
<LiveQuery
enabled={draftMode}
initialData={props.footer}
query={footerQuery}
>
<Footer data={props.footer} />
</LiveQuery>
<Table data={table} />
<Footer data={footer} />
{timestamp && <Timestamp date={timestamp} />}
<RefreshButton />
<RefreshButton isLive={isLive} />
</Variant>
<script
type="application/json"
Expand All @@ -120,8 +110,7 @@ export default function Page(
)
}

function RefreshButton() {
const isLive = useIsEnabled()
function RefreshButton({ isLive }: { isLive: boolean }) {
return (
<form
action="/api/revalidate"
Expand Down
2 changes: 2 additions & 0 deletions apps/remix/app/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,15 @@ export default function Index() {
enabled={previewDrafts}
initialData={table}
query={tableQuery}
throwOnMissingProvider={false}
>
<Table data={table} />
</LiveQuery>
<LiveQuery
enabled={previewDrafts}
initialData={footer}
query={footerQuery}
throwOnMissingProvider={false}
>
<Footer data={footer} />
</LiveQuery>
Expand Down
10 changes: 6 additions & 4 deletions apps/remix/app/variants/live-store/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { SerializeFrom } from '@vercel/remix'
import { lazy } from 'react'
import { StrictMode, lazy } from 'react'

import type { loader } from '~/routes'

Expand All @@ -12,9 +12,11 @@ export default function LiveStoreVariant({
studioUrl,
}: SerializeFrom<typeof loader> & React.PropsWithChildren) {
return previewDrafts ? (
<PreviewProvider token={token!} studioUrl={studioUrl}>
{children}
</PreviewProvider>
<StrictMode>
<PreviewProvider token={token!} studioUrl={studioUrl}>
{children}
</PreviewProvider>
</StrictMode>
) : (
children
)
Expand Down
4 changes: 0 additions & 4 deletions packages/preview-kit/.gitignore

This file was deleted.

55 changes: 0 additions & 55 deletions packages/preview-kit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
- [Advanced usage](#advanced-usage)
- [Using the `LiveQuery` wrapper component instead of the `useLiveQuery` hook](#using-the-livequery-wrapper-component-instead-of-the-uselivequery-hook)
- [Trouble-shooting and debugging](#trouble-shooting-and-debugging)
- [Fine-tuning `cache`](#fine-tuning-cache)
- [Content Source Map features](#content-source-map-features)
- [`@sanity/preview-kit/client`](#sanitypreview-kitclient)
- [Visual Editing with Content Source Maps](#visual-editing-with-content-source-maps)
Expand Down Expand Up @@ -656,62 +655,8 @@ If it's always `false` it's an indicator that you may need to lift your `LiveQue
- Next App Router: `src/app/layout.tsx`
- Next Pages Router: `src/pages/_app.tsx`

#### Fine-tuning `cache`

The defaults set for the `cache` prop are optimized for most use cases, but are conservative since the size of your documents can vary a lot. And your queries might only use some document types and it's not necessary to cache every type.
Thus you can fine-tune the cache by passing a custom `cache` prop to `LiveQueryProvider`:

```tsx
import { LiveQueryProvider } from '@sanity/preview-kit'

return (
<LiveQueryProvider
client={client}
token={token}
cache={{
// default: 3000, increased to 10000 for this example app as each document is small
maxDocuments: 10000,
// The default cache includes all document types, you can reduce the amount of documents
// by only including the ones you need.
// You can run the `array::unique(*._type)` GROQ query in `Vision` in your Studio to see how many types are in your dataset.
// Just be careful that you don't forget the document types you might be using in strong references, such as `project` or `sanity.imageAsset`
includeTypes: ['page', 'product', 'sanity.imageAsset'],
// Turn off using a mutation EventSource listener, this means content updates will require a manual refresh
listen: false,
}}
// If the cache is full it'll fallback to a polling interval mode, that refreshes every 10 seconds by default.
// You can opt-in to having an error thrown instead by setting this to `0`.
refreshInterval={10000}
// Passing a logger gives you more information on what to expect based on your configuration
logger={console}
>
{children}
</LiveQueryProvider>
)
```

#### Content Source Map features

When the `client` instance is configured to `client.config().resultSourceMap == true` the `LiveQueryProvider` will opt-in to a faster and smarter cache than the default mode.
It'll only listen for mutations on the documents that you are using in your queries, and apply the mutations to the cache in real-time.
This mode is best-effort, and if you're relying on features such as `upper` you may want to disable this mode.

```tsx
import { LiveQueryProvider } from '@sanity/preview-kit'

return (
<LiveQueryProvider
client={client}
token={token}
turboSourceMap={false}
// Passing a logger gives you more information on what to expect based on your configuration
logger={console}
>
{children}
</LiveQueryProvider>
)
```

For data that can't be traced with Content Source Maps there's a background refresh interval. Depending on your queries you might want to tweak this interval to get the best performance.

```tsx
Expand Down
55 changes: 42 additions & 13 deletions packages/preview-kit/package.config.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,52 @@
import terser from '@rollup/plugin-terser'
import { defineConfig } from '@sanity/pkg-utils'

const MODULE_PATHES_WHICH_USE_CLIENT_DIRECTIVE_SHOULD_BE_ADDED = [
'LiveQueryClientComponent.tsx',
]

export default defineConfig({
tsconfig: 'tsconfig.build.json',
legacyExports: true,
bundles: [
{
source: './src/_exports/internals/_create-conditional-live-query.ts',
import: './dist/internals/create-conditional-live-query.js',
runtime: 'node',
},
{
source: './src/_exports/internals/_live-query.ts',
import: './dist/internals/live-query.js',
runtime: 'node',
// Overriding the minify logiic in order to disable `compress: {directives: false}`
minify: false,
rollup: {
plugins: [
terser({
compress: { directives: false },
output: {
comments: (_node, comment) => {
const text = comment.value
const type = comment.type

// Check if this is a multiline comment
if (type == 'comment2') {
// Keep licensing comments
return /@preserve|@license|@cc_on/i.test(text)
}

return false
},
},
}),
],
output: {
preserveModules: true,
preserveModulesRoot: 'src',
banner: (chunkInfo) => {
if (
MODULE_PATHES_WHICH_USE_CLIENT_DIRECTIVE_SHOULD_BE_ADDED.find(
(modulePath) => chunkInfo.facadeModuleId?.endsWith(modulePath),
)
) {
return `"use client"`
}
return ''
},
},
],
},
extract: {
rules: {
'ae-forgotten-export': 'warn',
'ae-forgotten-export': 'error',
'ae-incompatible-release-tags': 'warn',
'ae-internal-missing-underscore': 'off',
'ae-missing-release-tag': 'warn',
Expand Down
Loading

7 comments on commit 5094cb5

@vercel
Copy link

@vercel vercel bot commented on 5094cb5 Nov 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

preview-kit-next-pages-router – ./apps/next-pages-router

preview-kit-next-pages-router.sanity.build
preview-kit-next-pages-router-git-main.sanity.build

@vercel
Copy link

@vercel vercel bot commented on 5094cb5 Nov 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

preview-kit-test-studio – ./apps/studio

preview-kit-test-studio.sanity.build
preview-kit-test-studio-git-main.sanity.build

@vercel
Copy link

@vercel vercel bot commented on 5094cb5 Nov 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

preview-kit-next-app-router – ./apps/next-app-router

preview-kit-next-app-router-git-main.sanity.build
preview-kit-next-app-router.sanity.build

@vercel
Copy link

@vercel vercel bot commented on 5094cb5 Nov 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

preview-kit-next-pages-router-live-store – ./apps/next-pages-router

preview-kit-next-pages-router-live-store.sanity.build
preview-kit-next-pages-router-live-store-git-main.sanity.build

@vercel
Copy link

@vercel vercel bot commented on 5094cb5 Nov 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

preview-kit-remix-live-store – ./apps/remix

preview-kit-remix-live-store.sanity.build
preview-kit-remix-live-store-git-main.sanity.build

@vercel
Copy link

@vercel vercel bot commented on 5094cb5 Nov 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

preview-kit-next-app-router-live-store – ./apps/next-app-router

preview-kit-next-app-router-live-store.sanity.build
preview-kit-next-app-router-live-store-git-main.sanity.build

@vercel
Copy link

@vercel vercel bot commented on 5094cb5 Nov 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

preview-kit-remix – ./apps/remix

preview-kit-remix-git-main.sanity.build
preview-kit-remix.sanity.build

Please sign in to comment.