Skip to content

Commit

Permalink
refactor: migrate @sanity/presentation@corel codebase (#8312) (#8317)
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan authored Jan 20, 2025
1 parent b47e306 commit 69d60cd
Show file tree
Hide file tree
Showing 20 changed files with 104 additions and 289 deletions.
2 changes: 1 addition & 1 deletion dev/test-studio/preview/loader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const client = createClient({
projectId: 'ppsg7ml5',
dataset: 'playground',
useCdn: true,
apiVersion: '2023-02-06',
apiVersion: 'X',
stega: {
enabled: true,
studioUrl: '/presentation',
Expand Down
43 changes: 6 additions & 37 deletions packages/sanity/src/presentation/PresentationTool.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
type SanityDocument,
type Tool,
useDataset,
usePerspective,
useProjectId,
useUnique,
useWorkspace,
Expand Down Expand Up @@ -52,7 +53,6 @@ import {
presentationReducer,
presentationReducerInit,
} from './reducers/presentationReducer'
import {RevisionSwitcher} from './RevisionSwitcher'
import {
type FrameState,
type PresentationNavigate,
Expand Down Expand Up @@ -106,11 +106,15 @@ export default function PresentationTool(props: {
state: PresentationStateParams
}
const routerSearchParams = useUnique(Object.fromEntries(routerState._searchParams || []))
const {perspectiveStack, selectedPerspectiveName = 'previewDrafts'} = usePerspective()
const perspective = (
selectedPerspectiveName.startsWith('r') ? perspectiveStack : selectedPerspectiveName
) as PresentationPerspective

const initialPreviewUrl = usePreviewUrl(
_previewUrl || '/',
name,
routerSearchParams.perspective === 'published' ? 'published' : 'previewDrafts',
perspective,
routerSearchParams.preview || null,
canCreateUrlPreviewSecrets,
)
Expand Down Expand Up @@ -180,11 +184,6 @@ export default function PresentationTool(props: {

const [state, dispatch] = useReducer(presentationReducer, {}, presentationReducerInit)

const perspective = useMemo(
() => (params.perspective ? 'published' : 'previewDrafts'),
[params.perspective],
)

const viewport = useMemo(() => (params.viewport ? 'mobile' : 'desktop'), [params.viewport])

const [documentsOnPage, setDocumentsOnPage] = useDocumentsOnPage(perspective, frameStateRef)
Expand Down Expand Up @@ -308,7 +307,6 @@ export default function PresentationTool(props: {

const stop = comlink.start()
setVisualEditingComlink(comlink)

return () => {
stop()
setVisualEditingComlink(null)
Expand Down Expand Up @@ -436,15 +434,6 @@ export default function PresentationTool(props: {
unstable_navigator,
})

// Handle edge case where the `&rev=` parameter gets "stuck"
const idRef = useRef<string | undefined>(params.id)
useEffect(() => {
if (params.rev && idRef.current && params.id !== idRef.current) {
navigate({}, {rev: undefined})
}
idRef.current = params.id
})

const refreshRef = useRef<number>(undefined)
const handleRefresh = useCallback(
(fallback: () => void) => {
Expand Down Expand Up @@ -498,16 +487,6 @@ export default function PresentationTool(props: {
[navigate],
)

const setPerspective = useCallback(
(next: PresentationPerspective) => {
// Omit the perspective URL search param if the next perspective state is
// the default: 'previewDrafts'
const perspective = next === 'previewDrafts' ? undefined : next
navigate({}, {perspective})
},
[navigate],
)

return (
<>
<PresentationProvider
Expand Down Expand Up @@ -551,7 +530,6 @@ export default function PresentationTool(props: {
previewUrl={params.preview}
perspective={perspective}
ref={iframeRef}
setPerspective={setPerspective}
setViewport={setViewport}
targetOrigin={targetOrigin}
toggleNavigator={toggleNavigator}
Expand Down Expand Up @@ -626,15 +604,6 @@ export default function PresentationTool(props: {
<PostMessagePerspective comlink={visualEditingComlink} perspective={perspective} />
)}
{visualEditingComlink && <PostMessageTelemetry comlink={visualEditingComlink} />}
{params.id && params.type && (
<RevisionSwitcher
documentId={params.id}
documentRevision={params.rev}
documentType={params.type}
navigate={navigate}
perspective={perspective}
/>
)}
</Suspense>
</>
)
Expand Down
40 changes: 0 additions & 40 deletions packages/sanity/src/presentation/RevisionSwitcher.tsx

This file was deleted.

2 changes: 1 addition & 1 deletion packages/sanity/src/presentation/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const EDIT_INTENT_MODE = 'presentation'
export const MAX_TIME_TO_OVERLAYS_CONNECTION = 3_000 // ms

// The API version to use when using `@sanity/client`
export const API_VERSION = '2023-10-16'
export const API_VERSION = 'vX'

// Heartbeats shouldn't fire on intervals that are so short it causes performance issues
export const MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL = 1000 // ms
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export function DocumentListPane(props: {
() =>
refs
.filter((r) => getPublishedId(r._id) !== mainDocumentState?.document?._id)
.map((r) => r._id),
.map((r) => getPublishedId(r._id)),
[mainDocumentState, refs],
)

Expand Down
6 changes: 0 additions & 6 deletions packages/sanity/src/presentation/i18n/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,8 @@ export default {
'preview-frame.overlay.toggle-button.tooltip_disable': 'Disable edit overlay',
/** The text shown on the overlay toggle tooltip when overlays are disabled */
'preview-frame.overlay.toggle-button.tooltip_enable': 'Enable edit overlay',
/** The text description for the previewDrafts perspective switcher menu item */
'preview-frame.perspective.previewDrafts.text': 'View this page with latest draft content',
/** The title for the previewDrafts perspective switcher menu item */
'preview-frame.perspective.previewDrafts.title': 'Drafts',
/** The text description for the published perspective switcher menu item */
'preview-frame.perspective.published.text': 'View this page with published content',
/** The title for the published perspective switcher menu item */
'preview-frame.perspective.published.title': 'Published',
/** The `aria-label` for the refresh button */
'preview-frame.refresh-button.aria-label': 'Refresh preview',
/** The tooltip text for the refresh button */
Expand Down
10 changes: 7 additions & 3 deletions packages/sanity/src/presentation/loader/LiveQueries.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import {
import {useEffectEvent} from 'use-effect-event'

// import {useEffectEvent} from 'use-effect-event'
import {MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL} from '../constants'
import {API_VERSION, MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL} from '../constants'
import {
type LiveQueriesState,
type LiveQueriesStateValue,
Expand Down Expand Up @@ -184,7 +184,7 @@ export default function LoaderQueries(props: LoaderQueriesProps): React.JSX.Elem

const [syncTagsInUse] = useState(() => new Set<SyncTag[]>())
const [lastLiveEventId, setLastLiveEventId] = useState<string | null>(null)
const studioClient = useClient({apiVersion: '2023-10-16'})
const studioClient = useClient({apiVersion: API_VERSION})
const clientConfig = useMemo(() => studioClient.config(), [studioClient])
const client = useMemo(
() =>
Expand Down Expand Up @@ -483,7 +483,11 @@ export function turboChargeResultIfSourceMap<T = unknown>(
}
return changedValue
},
perspective,
// TODO: Update applySourceDocuments to support releases.
Array.isArray(perspective) &&
perspective.some((part) => typeof part === 'string' && part.startsWith('r') && part !== 'raw')
? 'previewDrafts'
: (perspective as ClientPerspective),
)
}

Expand Down
9 changes: 7 additions & 2 deletions packages/sanity/src/presentation/loader/LoaderQueries.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
} from 'sanity'

import {
API_VERSION,
LIVE_QUERY_CACHE_BATCH_SIZE,
LIVE_QUERY_CACHE_SIZE,
MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL,
Expand Down Expand Up @@ -161,7 +162,7 @@ export default function LoaderQueries(props: LoaderQueriesProps): React.JSX.Elem
}, [controller, dataset, onDocumentsOnPage, onLoadersConnection, projectId])

const [cache] = useState(() => new LRUCache<string, SanityDocument>(LIVE_QUERY_CACHE_SIZE))
const studioClient = useClient({apiVersion: '2023-10-16'})
const studioClient = useClient({apiVersion: API_VERSION})
const clientConfig = useMemo(() => studioClient.config(), [studioClient])
const client = useMemo(
() =>
Expand Down Expand Up @@ -553,7 +554,11 @@ export function turboChargeResultIfSourceMap<T = unknown>(
}
return changedValue
},
perspective,
// TODO: Update applySourceDocuments to support releases.
Array.isArray(perspective) &&
perspective.some((part) => typeof part === 'string' && part.startsWith('r') && part !== 'raw')
? 'previewDrafts'
: (perspective as ClientPerspective),
)
}

Expand Down
14 changes: 12 additions & 2 deletions packages/sanity/src/presentation/overlays/PostMessageDocuments.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {type MutationEvent, type ReconnectEvent, type WelcomeEvent} from '@sanity/client'
import {type FunctionComponent, memo, useEffect} from 'react'
import {filter, first, merge, shareReplay} from 'rxjs'
import {useClient} from 'sanity'
import {isDraftId, useClient} from 'sanity'

import {API_VERSION} from '../constants'
import {type VisualEditingConnection} from '../types'
Expand Down Expand Up @@ -79,7 +79,17 @@ const PostMessageDocuments: FunctionComponent<PostMessageDocumentsProps> = (prop

useEffect(() => {
return comlink.on('visual-editing/fetch-snapshot', async (data) => {
const snapshot = await client.getDocument(data.documentId, {
/**
* This is a temporary hack to get around the fact that the `drafts.versions.versionName.id` format is not supported
* `versions.` don't have draft documents.
*
* Where is the drafts. prefix coming from and why it's added to the `versions.` documents?
* */
const cleanId =
data.documentId.includes('versions.') && isDraftId(data.documentId)
? data.documentId.replace('drafts.', '')
: data.documentId
const snapshot = await client.getDocument(cleanId, {
tag: 'document.snapshots',
})
return {snapshot}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {type ClientPerspective} from '@sanity/client'
import {type UnresolvedPath} from '@sanity/presentation-comlink'
import {useRootTheme} from '@sanity/ui'
import {memo, useEffect} from 'react'
import {useClient, useWorkspace} from 'sanity'
import {getPublishedId, useClient, useWorkspace} from 'sanity'

import {API_VERSION} from '../../constants'
import {type VisualEditingConnection} from '../../types'
Expand Down Expand Up @@ -67,7 +67,14 @@ function PostMessageSchema(props: PostMessageSchemaProps): React.JSX.Element | n
const arr = Array.from(paths)
const projection = arr.map((path, i) => `"${i}": ${path}[0]._type`).join(',')
const query = `*[_id == $id][0]{${projection}}`
const result = await client.fetch(query, {id}, {perspective, tag: 'presentation-schema'})
const result = await client.fetch(
query,
{id: getPublishedId(id)},
{
tag: 'presentation-schema',
perspective,
},
)
const mapped = arr.map((path, i) => ({path: path, type: result[i]}))
return {id, paths: mapped}
}),
Expand Down
4 changes: 2 additions & 2 deletions packages/sanity/src/presentation/preview/Preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
type PresentationViewport,
} from '../types'
import {usePresentationTool} from '../usePresentationTool'
import {encodeStudioPerspective} from '../util/encodeStudioPerspective'
import {IFrame} from './IFrame'
import {usePresentationPreviewHeader} from './PreviewHeader'

Expand All @@ -59,7 +60,6 @@ export interface PreviewProps extends Pick<PresentationState, 'iframe' | 'visual
overlaysConnection: ConnectionStatus
perspective: PresentationPerspective
previewUrl?: string
setPerspective: (perspective: 'previewDrafts' | 'published') => void
setViewport: (mode: 'desktop' | 'mobile') => void
targetOrigin: string
toggleNavigator?: () => void
Expand All @@ -86,7 +86,7 @@ export const Preview = memo(
const url = new URL(initialUrl)
// Always set the perspective that's being used, even if preview mode isn't configured
if (!url.searchParams.get(urlSearchParamPreviewPerspective)) {
url.searchParams.set(urlSearchParamPreviewPerspective, perspective)
url.searchParams.set(urlSearchParamPreviewPerspective, encodeStudioPerspective(perspective))
}

if (vercelProtectionBypass || url.searchParams.get(urlSearchParamVercelProtectionBypass)) {
Expand Down
Loading

0 comments on commit 69d60cd

Please sign in to comment.