sanity-plugin-visual-editor 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +263 -16
- package/TESTING.md +133 -0
- package/dist/PreviewBar-D_rw0bhP.js +3503 -0
- package/dist/PreviewBar-D_rw0bhP.js.map +1 -0
- package/dist/bar.d.ts +22 -0
- package/dist/bar.js +67 -0
- package/dist/bar.js.map +1 -0
- package/dist/cloudflare.d.ts +87 -0
- package/dist/cloudflare.js +1134 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/data-D0qotTtt.d.ts +177 -0
- package/dist/host-x2eXr-LJ.js +619 -0
- package/dist/host-x2eXr-LJ.js.map +1 -0
- package/dist/host.d.ts +162 -0
- package/dist/host.js +3 -0
- package/dist/index-hDzatlg7.d.ts +276 -0
- package/dist/index.d.ts +18 -18
- package/dist/index.js +7 -8
- package/dist/link-search-JtZkxz4k.js +14 -0
- package/dist/link-search-JtZkxz4k.js.map +1 -0
- package/dist/next-client.d.ts +22 -0
- package/dist/next-client.js +112 -0
- package/dist/next-client.js.map +1 -0
- package/dist/next.d.ts +135 -0
- package/dist/next.js +176 -0
- package/dist/next.js.map +1 -0
- package/dist/node-labels-CDiW5rMq.js +122 -0
- package/dist/node-labels-CDiW5rMq.js.map +1 -0
- package/dist/page-documents-BFFcH8lD.d.ts +54 -0
- package/dist/page-documents-mGfw_flR.js +67 -0
- package/dist/page-documents-mGfw_flR.js.map +1 -0
- package/dist/perspective-BmS9TVtr.js +106 -0
- package/dist/perspective-BmS9TVtr.js.map +1 -0
- package/dist/preview-links-BZDZyIey.js +119 -0
- package/dist/preview-links-BZDZyIey.js.map +1 -0
- package/dist/preview-links-DM6BCiLV.d.ts +87 -0
- package/dist/protocol-BNO38gYy.js +280 -0
- package/dist/protocol-BNO38gYy.js.map +1 -0
- package/dist/protocol-BnRCy2wJ.d.ts +386 -0
- package/dist/server-B8MqMyaN.js +748 -0
- package/dist/server-B8MqMyaN.js.map +1 -0
- package/dist/server.d.ts +4 -0
- package/dist/server.js +3 -0
- package/dist/shell-DZotxRXX.d.ts +37 -0
- package/dist/studio.d.ts +93 -0
- package/dist/studio.js +1263 -0
- package/dist/studio.js.map +1 -0
- package/dist/sveltekit.d.ts +281 -0
- package/dist/sveltekit.js +394 -0
- package/dist/sveltekit.js.map +1 -0
- package/package.json +120 -39
- package/dist/index.d.mts +0 -21
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -8
- package/dist/index.mjs.map +0 -1
- package/sanity.json +0 -8
- package/src/index.ts +0 -27
- package/v2-incompatible.js +0 -11
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"studio.js","names":["NO_LOCATIONS"],"sources":["../src/studio/live-edit.tsx","../src/studio/locations.tsx","../src/studio/studio-bar-data.ts","../src/studio/VisualEditorTool.tsx","../src/studio/index.ts"],"sourcesContent":["import {createContext, useCallback, useContext, useEffect, useRef, type ReactNode} from 'react'\nimport {useEditor} from '@portabletext/editor'\nimport {\n definePlugin,\n isDocumentSchemaType,\n useClient,\n useCurrentUser,\n type InputProps,\n type PortableTextPluginsProps,\n type SanityClient,\n type SchemaType,\n} from 'sanity'\nimport {createPreviewSecret} from '@sanity/preview-url-secret/create-secret'\n\n/**\n * Streams the open document's unsaved form value to the storefront's realtime preview hub, so\n * preview tabs update as the editor types instead of after the Studio's autosave (at most one save\n * per second while typing).\n *\n * The Studio is served on the storefront's origin (e.g. `/studio`), so requests go to the same\n * origin. Edits go over a WebSocket to the hub (`<endpoint>/socket`, opened when a document\n * opens), or as POSTs where one cannot open. Without a session, the plugin creates a Sanity\n * preview secret with the editor's own login and trades it for a signed cookie limited to the\n * live-edit routes (`<endpoint>/session`).\n *\n * Rich text: the Portable Text editor hands its changes to the form in batches (250 ms after\n * typing pauses, every second while it continues), but emits each keystroke at once as a `patch`\n * event. A Portable Text plugin (inside every rich-text editor) reports the editor's value on each\n * patch, with the field's path from its input, and the document is sent with that value in place.\n */\n\nexport type LiveEditOptions = {\n /** Storefront live-edit base endpoint. Default `/api/preview/live-edit`. */\n endpoint?: string\n /** Studio base path used when creating the preview secret. Default `/studio`. */\n studioPath?: string\n /** Source label passed to `createPreviewSecret`. Default `'visual-editor-live-edit'`. */\n source?: string\n}\n\nconst DEFAULT_ENDPOINT = '/api/preview/live-edit'\nconst DEFAULT_STUDIO_PATH = '/studio'\nconst DEFAULT_SOURCE = 'visual-editor-live-edit'\nconst API_VERSION = '2025-02-19'\n/** At most one send per document this often (a frame) while typing; the last value always goes. */\nconst THROTTLE_MS = 16\n/** After a socket fails to open even with a fresh session, edits use POSTs for this long. */\nconst SOCKET_RETRY_MS = 30_000\n/** Keeps the socket open through proxies that close quiet connections. */\nconst PING_MS = 20_000\n/** A socket that has not opened by then is given up on (edits go as POSTs meanwhile). */\nconst SOCKET_OPEN_TIMEOUT_MS = 5_000\nconst SYSTEM_FIELDS = new Set(['_rev', '_updatedAt', '_createdAt', '_system'])\n/**\n * A rich-text field's editor value stays over the form's this long after its last keystroke: the\n * form catches up within ~1 s, and after that the form is the authority (a collaborator's change,\n * an undo from history).\n */\nconst RICH_TEXT_HOLD_MS = 2_000\n\ntype PathSegment = string | number | {_key: string} | [number | '', number | '']\ntype RichTextOverride = {path: PathSegment[]; blocks: unknown; at: number}\ntype Doc = {_id: string; _type: string; [field: string]: unknown}\n\n/** Lets a rich-text field hand its editor's current value to the document's broadcaster. */\nconst RichTextContext = createContext<((path: PathSegment[], blocks: unknown) => void) | null>(null)\n/** The rich-text field's path, for the Portable Text plugin rendered inside its editor. */\nconst RichTextPathContext = createContext<PathSegment[] | null>(null)\n\n/** `value` with `replacement` at `path` (object keys, array indexes, `{ _key }` array items). */\nfunction setAtPath(value: unknown, path: PathSegment[], replacement: unknown): unknown {\n if (!path.length) return replacement\n const [head, ...rest] = path\n if (Array.isArray(value)) {\n const index =\n typeof head === 'number'\n ? head\n : typeof head === 'object' && head && '_key' in head\n ? value.findIndex((item) => (item as {_key?: string} | null)?._key === head._key)\n : -1\n if (index < 0 || index >= value.length) return value\n const copy = [...value]\n copy[index] = setAtPath(copy[index], rest, replacement)\n return copy\n }\n if (typeof head !== 'string') return value\n const object = (value ?? {}) as Record<string, unknown>\n return {...object, [head]: setAtPath(object[head], rest, replacement)}\n}\n\n/** A Portable Text field: an array whose members include a `block` type. */\nfunction isRichText(schemaType: SchemaType): boolean {\n if (schemaType.jsonType !== 'array') return false\n return schemaType.of.some((member) => {\n for (let type: SchemaType | undefined = member; type; type = type.type) {\n if (type.name === 'block') return true\n }\n return false\n })\n}\n\nfunction createTransport(endpoint: string, studioPath: string, source: string) {\n let seq = 0\n let disabled = false\n let session: Promise<boolean> | null = null\n let socket: WebSocket | null = null\n let opening: Promise<WebSocket | null> | null = null\n let socketRetryAt = 0\n const senders = new Map<\n string,\n {pending: Doc | null; timer: ReturnType<typeof setTimeout> | null}\n >()\n\n function post(document: Doc): Promise<Response> {\n return fetch(endpoint, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {'content-type': 'application/json'},\n body: JSON.stringify({document, seq: ++seq}),\n })\n }\n\n /** Trade a fresh preview secret for the live-edit cookie. Shared by concurrent callers. */\n function startSession(client: SanityClient, userId: string | undefined): Promise<boolean> {\n session ??= (async () => {\n try {\n const {secret} = await createPreviewSecret(\n client,\n source,\n `${location.origin}${studioPath}`,\n userId,\n )\n const url = `${endpoint}/session?sanity-preview-secret=${encodeURIComponent(secret)}`\n // A JSON body keeps SvelteKit's CSRF check (which refuses form-like POSTs) out of the way.\n const response = await fetch(url, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {'content-type': 'application/json'},\n body: '{}',\n })\n return response.ok\n } catch {\n return false\n } finally {\n // Let a later 401 (an expired cookie) start a new session.\n setTimeout(() => (session = null), 5_000)\n }\n })()\n return session\n }\n\n /** Open the edit socket; `null` if it closes first (no session cookie, or no hub). */\n function openSocket(): Promise<WebSocket | null> {\n return new Promise((resolve) => {\n const url = new URL(`${endpoint}/socket`, location.href)\n url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'\n const ws = new WebSocket(url)\n let ping: ReturnType<typeof setInterval> | undefined\n // An upgrade nothing answers (Vite dev) neither opens nor closes: give up on it.\n const timeout = setTimeout(() => ws.close(), SOCKET_OPEN_TIMEOUT_MS)\n ws.addEventListener('open', () => {\n clearTimeout(timeout)\n ping = setInterval(() => ws.send('ping'), PING_MS)\n resolve(ws)\n })\n ws.addEventListener('close', () => {\n clearTimeout(timeout)\n clearInterval(ping)\n if (socket === ws) socket = null\n resolve(null)\n })\n })\n }\n\n /** The edit socket, opened on first use and reopened after it drops. */\n function editSocket(client: SanityClient, userId: string | undefined): Promise<WebSocket | null> {\n if (socket?.readyState === WebSocket.OPEN) return Promise.resolve(socket)\n if (Date.now() < socketRetryAt) return Promise.resolve(null)\n opening ??= (async () => {\n let ws = await openSocket()\n // A refused upgrade (no session cookie yet) only shows as a close: start one and retry.\n if (!ws && (await startSession(client, userId))) ws = await openSocket()\n if (!ws) socketRetryAt = Date.now() + SOCKET_RETRY_MS\n socket = ws\n return ws\n })().finally(() => (opening = null))\n return opening\n }\n\n async function send(document: Doc, client: SanityClient, userId: string | undefined) {\n // Never wait for the socket: use it when it is open, otherwise POST this edit and let the\n // socket open (or reopen) in the background for the next one.\n if (socket?.readyState === WebSocket.OPEN) {\n socket.send(JSON.stringify({document, seq: ++seq}))\n return\n }\n void editSocket(client, userId)\n try {\n let response = await post(document)\n if (response.status === 401 && (await startSession(client, userId))) {\n response = await post(document)\n }\n // No route (a Studio not served by the storefront) or no hub: stop trying.\n if (response.status === 404 || response.status === 503) disabled = true\n } catch {\n // Offline or the storefront is down; the saved draft still reaches the hub.\n }\n }\n\n function queue(document: Doc, client: SanityClient, userId: string | undefined) {\n if (disabled) return\n let sender = senders.get(document._id)\n if (!sender) senders.set(document._id, (sender = {pending: null, timer: null}))\n sender.pending = document\n if (sender.timer) return\n const flush = () => {\n const next = sender.pending\n sender.pending = null\n if (!next) {\n sender.timer = null\n return\n }\n void send(next, client, userId)\n sender.timer = setTimeout(flush, THROTTLE_MS)\n }\n flush()\n }\n\n return {editSocket, queue}\n}\n\ntype Transport = ReturnType<typeof createTransport>\n\n/** Inside each rich-text editor: reports the editor's value on every patch. */\nfunction LiveRichTextPlugins(props: PortableTextPluginsProps) {\n return (\n <>\n {props.renderDefault(props)}\n <RichTextPatches />\n </>\n )\n}\n\nfunction RichTextPatches(): ReactNode {\n const editor = useEditor()\n const report = useContext(RichTextContext)\n const path = useContext(RichTextPathContext)\n useEffect(() => {\n if (!report || !path) return\n // One call per settled burst of patches (a keystroke, a paste), with the editor's new value.\n const subscription = editor.on(\n 'patch',\n () => report(path, editor.getSnapshot().context.value),\n {\n batch: true,\n },\n )\n return () => subscription.unsubscribe()\n }, [editor, report, path])\n return null\n}\n\nfunction createLiveDocumentInput(transport: Transport) {\n return function LiveDocumentInput(props: InputProps) {\n const value = props.value as Doc | undefined\n const client = useClient({apiVersion: API_VERSION})\n const user = useCurrentUser()\n const last = useRef<string | null>(null)\n const latest = useRef(value)\n latest.current = value\n const richText = useRef(new Map<string, RichTextOverride>())\n\n // Open the edit socket with the document, so the first keystroke does not wait for it.\n const id = value?._id\n useEffect(() => {\n if (id) void transport.editSocket(client, user?.id)\n }, [id, client, user?.id])\n\n const broadcast = useCallback(\n (base: Doc | undefined) => {\n if (!base?._id || !base._id.startsWith('drafts.')) return\n let doc = base\n const now = Date.now()\n for (const [key, override] of richText.current) {\n if (now - override.at > RICH_TEXT_HOLD_MS) richText.current.delete(key)\n else doc = setAtPath(doc, override.path, override.blocks) as Doc\n }\n // Ignore autosaves: they change only `_rev`/`_updatedAt`, not what the page shows.\n const json = JSON.stringify(doc, (key, field: unknown) =>\n SYSTEM_FIELDS.has(key) ? undefined : field,\n )\n // The first value is what the editor opened; only edits after that are sent.\n if (last.current === null) {\n last.current = json\n return\n }\n if (json === last.current) return\n last.current = json\n transport.queue(doc, client, user?.id)\n },\n [client, user?.id],\n )\n\n useEffect(() => broadcast(value), [value, broadcast])\n\n const reportRichText = useCallback(\n (path: PathSegment[], blocks: unknown) => {\n if (blocks === undefined) return\n richText.current.set(JSON.stringify(path), {path, blocks, at: Date.now()})\n broadcast(latest.current)\n },\n [broadcast],\n )\n\n return (\n <RichTextContext.Provider value={reportRichText}>\n {props.renderDefault(props)}\n </RichTextContext.Provider>\n )\n }\n}\n\n/** Streams unsaved edits of the open document to the realtime preview hub. */\nexport const liveEditPlugin = definePlugin<LiveEditOptions | void>((options) => {\n const endpoint = (options?.endpoint ?? DEFAULT_ENDPOINT).replace(/\\/+$/, '')\n const studioPath = options?.studioPath ?? DEFAULT_STUDIO_PATH\n const source = options?.source ?? DEFAULT_SOURCE\n const transport = createTransport(endpoint, studioPath, source)\n const LiveDocumentInput = createLiveDocumentInput(transport)\n\n function LiveEditInput(props: InputProps) {\n if (isDocumentSchemaType(props.schemaType)) return <LiveDocumentInput {...props} />\n if (isRichText(props.schemaType)) {\n return (\n <RichTextPathContext.Provider value={props.path as PathSegment[]}>\n {props.renderDefault(props)}\n </RichTextPathContext.Provider>\n )\n }\n return props.renderDefault(props)\n }\n\n return {\n name: 'sanity-plugin-visual-editor/live-edit',\n form: {components: {input: LiveEditInput, portableText: {plugins: LiveRichTextPlugins}}},\n }\n})\n","/**\n * \"Used on\" for the Visual Editor: Presentation's document locations (`resolve.locations`, the same\n * `defineLocations` resolvers) without the Presentation tool. Every document form gets\n * Presentation's banner: \"Used on N pages\", expanding to the pages, each opening the Visual Editor\n * on that page.\n *\n * Resolvers take Presentation's three forms: per type, `{select, resolve}` (the selected fields,\n * live through the preview store) or a fixed state; or one function for every type, given the\n * document and the Studio's document store.\n */\nimport ChevronRightIcon from '@sanity/icons/ChevronRight'\nimport DesktopIcon from '@sanity/icons/Desktop'\nimport ErrorOutlineIcon from '@sanity/icons/ErrorOutline'\nimport InfoOutlineIcon from '@sanity/icons/InfoOutline'\nimport WarningOutlineIcon from '@sanity/icons/WarningOutline'\nimport {Box, Card, Flex, Spinner, Text} from '@sanity/ui'\nimport {\n type ComponentType,\n type CSSProperties,\n createElement,\n type MouseEvent,\n type ReactNode,\n useContext,\n useEffect,\n useState,\n} from 'react'\nimport {\n FormRow,\n getPublishedId,\n getVersionFromId,\n type InputProps,\n isDocumentSchemaType,\n type ObjectSchemaType,\n useDocumentPreviewStore,\n useDocumentStore,\n usePerspective,\n useWorkspace,\n} from 'sanity'\nimport {PresentationDocumentContext} from 'sanity/_singletons'\nimport type {\n DocumentLocation,\n DocumentLocationResolver,\n DocumentLocationResolvers,\n DocumentLocationsState,\n} from 'sanity/presentation'\nimport {useRouter} from 'sanity/router'\n\nexport type VisualEditorLocations = DocumentLocationResolvers | DocumentLocationResolver\n\ntype Status = 'empty' | 'resolving' | 'resolved'\ntype Result = {state: DocumentLocationsState; status: Status}\n\nconst NO_LOCATIONS: DocumentLocationsState = {locations: []}\n\ntype Subscribable<T> = {subscribe: (next: (value: T) => void) => {unsubscribe: () => void}}\n\nfunction isSubscribable<T>(value: unknown): value is Subscribable<T> {\n return typeof (value as Subscribable<T> | null)?.subscribe === 'function'\n}\n\n/** Presentation's `useDocumentLocations`: the resolver's state, live. */\nfunction useDocumentLocations({\n id,\n version,\n schemaType,\n resolvers,\n}: {\n id: string\n version: string | undefined\n schemaType: ObjectSchemaType\n resolvers: VisualEditorLocations\n}): Result {\n const documentStore = useDocumentStore()\n const previewStore = useDocumentPreviewStore()\n const {perspectiveStack} = usePerspective()\n const resolver = typeof resolvers === 'function' ? resolvers : resolvers[schemaType.name]\n const [result, setResult] = useState<Result>({\n state: NO_LOCATIONS,\n status: resolver ? 'resolving' : 'empty',\n })\n const stackKey = JSON.stringify(perspectiveStack)\n\n useEffect(() => {\n if (!resolver) {\n setResult({state: NO_LOCATIONS, status: 'empty'})\n return\n }\n const settle = (state: DocumentLocationsState | null | undefined | void) =>\n setResult(state ? {state, status: 'resolved'} : {state: NO_LOCATIONS, status: 'empty'})\n\n if (typeof resolver === 'object' && 'select' in resolver && 'resolve' in resolver) {\n // The selected fields, through the preview store, as Presentation reads them.\n const subscription = previewStore\n .observeForPreview(\n {_type: 'reference', _ref: id} as never,\n {...schemaType, preview: {select: resolver.select}} as never,\n {perspective: perspectiveStack as never},\n )\n .subscribe((preview) =>\n settle(resolver.resolve((preview.snapshot as Record<string, unknown> | null) ?? null)),\n )\n return () => subscription.unsubscribe()\n }\n const source: unknown =\n typeof resolver === 'function'\n ? resolver(\n {id, type: schemaType.name, version, perspectiveStack: perspectiveStack as never},\n {documentStore},\n )\n : resolver\n\n if (!isSubscribable<DocumentLocationsState | null | undefined>(source)) {\n settle(source as DocumentLocationsState | null | undefined)\n return\n }\n const subscription = source.subscribe(settle)\n return () => subscription.unsubscribe()\n // `perspectiveStack` by value.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [resolver, id, version, schemaType, documentStore, previewStore, stackKey])\n\n return result\n}\n\nconst TONE_ICONS = {\n positive: InfoOutlineIcon,\n caution: WarningOutlineIcon,\n critical: ErrorOutlineIcon,\n}\n\n/** ui5's `Icon size={1}` in the Studio: 21px, pulled in by `-0.375rem`. */\nfunction BannerIcon({icon, style}: {icon: ComponentType; style?: CSSProperties}) {\n return (\n <span\n aria-hidden=\"true\"\n style={{display: 'block', fontSize: 21, lineHeight: 0, margin: '-0.375rem', ...style}}\n >\n {createElement(icon as ComponentType<{style?: CSSProperties}>, {\n style: {display: 'block'},\n })}\n </span>\n )\n}\n\nfunction countLabel(count: number) {\n if (count === 0) return 'Not used on any pages'\n if (count === 1) return 'Used on one page'\n return `Used on ${count} pages`\n}\n\n/** A page the document is on: opens the Visual Editor there, keeping the Studio's perspective. */\nfunction LocationItem({location, toolName}: {location: DocumentLocation; toolName: string}) {\n const {basePath} = useWorkspace()\n const router = useRouter()\n const search = new URLSearchParams({preview: location.href})\n if (typeof window !== 'undefined') {\n const current = new URLSearchParams(window.location.search)\n for (const key of ['perspective', 'excludedPerspectives']) {\n const value = current.get(key)\n if (value) search.set(key, value)\n }\n }\n const href = `${basePath.replace(/\\/$/, '')}/${toolName}?${search}`\n const Icon = location.icon ?? DesktopIcon\n return (\n <Card\n as=\"a\"\n href={href}\n padding={3}\n radius={1}\n tone=\"inherit\"\n onClick={(event: MouseEvent<HTMLAnchorElement>) => {\n if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) return\n event.preventDefault()\n router.navigateUrl({path: href})\n }}\n >\n <Flex gap={3}>\n <Box flex=\"none\">\n <BannerIcon icon={Icon} />\n </Box>\n <Flex flex={1} gap={2} direction=\"column\">\n <Text size={1} weight=\"medium\" as=\"div\">\n {location.title}\n </Text>\n {location.showHref !== false && (\n <Text muted size={1} textOverflow=\"ellipsis\" as=\"div\">\n {location.href}\n </Text>\n )}\n </Flex>\n </Flex>\n </Card>\n )\n}\n\n/** Presentation's `LocationsBanner`. */\nfunction LocationsBanner({\n id,\n version,\n schemaType,\n resolvers,\n toolName,\n}: {\n id: string\n version: string | undefined\n schemaType: ObjectSchemaType\n resolvers: VisualEditorLocations\n toolName: string\n}) {\n const {state, status} = useDocumentLocations({id, version, schemaType, resolvers})\n const [expanded, setExpanded] = useState(false)\n if (status === 'empty') return null\n const {locations, message, tone} = state\n const count = locations?.length ?? 0\n const resolving = status === 'resolving'\n const title = resolving ? 'Resolving locations...' : message || countLabel(count)\n const ToneIcon = tone ? TONE_ICONS[tone] : undefined\n\n let content: ReactNode\n if (!locations) {\n content = (\n <Flex align=\"flex-start\" gap={3} padding={3}>\n {ToneIcon && (\n <Box flex=\"none\">\n <BannerIcon icon={ToneIcon} />\n </Box>\n )}\n <Box flex={1}>\n <Text size={1} weight=\"medium\" as=\"div\">\n {title}\n </Text>\n </Box>\n </Flex>\n )\n } else {\n content = (\n <>\n <Card\n as={count ? 'button' : undefined}\n onClick={count ? () => setExpanded((value) => !value) : undefined}\n padding={3}\n radius={1}\n tone=\"inherit\"\n >\n <Flex gap={3}>\n <Box flex=\"none\">\n {resolving ? (\n <Spinner size={1} />\n ) : count === 0 ? (\n <BannerIcon icon={InfoOutlineIcon} />\n ) : (\n <BannerIcon\n icon={ChevronRightIcon}\n style={{\n transform: `rotate(${expanded ? '90deg' : 0})`,\n transition: 'transform 100ms ease-in-out',\n }}\n />\n )}\n </Box>\n <Box flex={1}>\n <Text size={1} weight=\"medium\" as=\"div\">\n {title}\n </Text>\n </Box>\n </Flex>\n </Card>\n <Flex hidden={!expanded} marginTop={1} gap={1} direction=\"column\">\n {locations.map((location) => (\n <LocationItem key={location.href} location={location} toolName={toolName} />\n ))}\n </Flex>\n </>\n )\n }\n\n // Presentation's `LocationStack` in a `FormRow`: a column with 8px gaps, 20px above the form.\n return (\n <FormRow>\n <div style={{display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 20}}>\n <Card padding={1} radius={2} border tone={tone}>\n <div style={{margin: -1}}>{content}</div>\n </Card>\n </div>\n </FormRow>\n )\n}\n\n/**\n * The document form's input: the banner above the form, as Presentation's. Not inside the preview\n * bar's own document panes (the Visual Editor's, the site's), which sit beside the page already;\n * they provide `PresentationDocumentContext` to hide Presentation's banner, and that hides this one.\n */\nexport function locationsInput(resolvers: VisualEditorLocations, toolName: string) {\n return function VisualEditorDocumentInput(props: InputProps) {\n const inPreviewBarPane = useContext(PresentationDocumentContext) !== null\n const value = props.value as {_id?: string} | undefined\n if (inPreviewBarPane || !isDocumentSchemaType(props.schemaType) || !value?._id) {\n return props.renderDefault(props)\n }\n return (\n <>\n <LocationsBanner\n id={getPublishedId(value._id)}\n version={getVersionFromId(value._id)}\n schemaType={props.schemaType}\n resolvers={resolvers}\n toolName={toolName}\n />\n {props.renderDefault(props)}\n </>\n )\n }\n}\n","/**\n * The bar's data in the Visual Editor tool, from the Studio instead of the site, so the bar\n * renders the moment the tool does (as Presentation's toolbar does): the workspace (title, icon,\n * base path, project), the project's name, the active releases (live, from the Studio's releases\n * store), the Studio's perspective, and Presentation's \"Share this preview\" state (read with the\n * editor's own client). What the Studio can't know, the tool's options say.\n */\nimport {fetchSharedAccessQuery} from '@sanity/preview-url-secret/constants'\nimport {useEffect, useMemo, useState} from 'react'\nimport {\n useActiveReleases,\n useClient,\n usePerspective,\n useProject,\n useSchema,\n useWorkspace,\n} from 'sanity'\nimport type {PreviewBarData} from '../core/data'\nimport {perspectiveStack, type ReleaseDocument, serializePerspective} from '../core/perspective'\n\nexport type StudioBarDataOptions = {\n /** The bar's route on the site (its share, perspective, search and resolve endpoints). */\n barPath: string\n /** The site serves short preview links (`links` in `createPreviewBar`). */\n links: boolean\n /** Document types the Studio search opens filtered to (default: all), as the site's `search`. */\n searchTypes?: string[]\n}\n\nexport function useStudioBarData({barPath, links, searchTypes}: StudioBarDataOptions) {\n const workspace = useWorkspace()\n const project = useProject()\n const schema = useSchema()\n const {data: releases, error: releasesError} = useActiveReleases()\n const {selectedPerspectiveName, excludedPerspectives} = usePerspective()\n const client = useClient({apiVersion: '2025-02-19'})\n\n // Presentation's sharing secret exists only while \"Share this preview\" is on.\n const [sharing, setSharing] = useState(false)\n useEffect(() => {\n if (!links) return\n let cancelled = false\n client\n .fetch<string | null>(fetchSharedAccessQuery, {}, {tag: 'preview-bar.sharing'})\n .then((secret) => {\n if (!cancelled) setSharing(Boolean(secret))\n })\n .catch(() => {})\n return () => {\n cancelled = true\n }\n }, [client, links])\n\n const releaseList = releases as unknown as ReleaseDocument[]\n // Seeds the bar's switcher; later switches go through the tool's perspective messages.\n const perspective = serializePerspective(\n perspectiveStack({\n selected: selectedPerspectiveName ?? 'drafts',\n releases: releaseList,\n excluded: excludedPerspectives ?? [],\n }),\n )\n const searchKey = searchTypes?.join(',')\n\n return useMemo<PreviewBarData>(\n () => ({\n brand: {\n title: workspace.title,\n icon: workspace.icon as PreviewBarData['brand']['icon'],\n project: project?.displayName,\n },\n studioPath: workspace.basePath || '/',\n projectId: workspace.projectId,\n basePath: barPath,\n releases: releaseList,\n releasesError: Boolean(releasesError),\n sharing,\n links,\n perspective,\n // The tool resolves the page's document itself and tells the bar (`editor-state`).\n pageDocuments: false,\n // The Studio's own search, filtered to these types (all types when none are given).\n search: (searchTypes ?? []).map((type) => ({\n kind: type,\n title: schema.get(type)?.title ?? type,\n })),\n }),\n // `perspective` only seeds the bar, and `searchTypes` is compared by value.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [workspace, project, releaseList, releasesError, sharing, links, barPath, schema, searchKey],\n )\n}\n","/**\n * The Visual Editor tool: Presentation's layout with the preview bar. The bar runs along the top,\n * rendered natively in the Studio (`PreviewBarView`, with the Studio's own context), the site\n * (framed under `PREVIEW_BAR_FRAME_NAME`, at desktop width or as a 375px phone) fills the middle,\n * and the Studio's own document pane sits on the right.\n *\n * The tool is the bar's host, through the same `sanity-visual-editor:*` messages the site's host\n * uses (in process, no frame), and talks to the framed site's `mountPreviewBarFrame`: paths,\n * refreshes after a perspective switch, navigation from search. The site is framed on its origin,\n * which must be this Studio's origin (an embedded Studio). The bar's data comes from the Studio\n * (`useStudioBarData`), so it renders with the tool; the site is only asked to store the\n * perspective cookie, mint share links and resolve search results.\n *\n * The tool's own layout uses the Studio's CSS variables and plain elements.\n */\nimport {createPreviewSecret} from '@sanity/preview-url-secret/create-secret'\nimport {\n urlSearchParamPreviewPathname,\n urlSearchParamPreviewSecret,\n} from '@sanity/preview-url-secret/constants'\nimport {Button, Card, Flex, Stack, Text} from '@sanity/ui'\nimport {\n type CSSProperties,\n type RefObject,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport * as sanityModule from 'sanity'\nimport {type Tool, useClient, useCurrentUser, usePerspective, useSchema, useWorkspace} from 'sanity'\nimport {PresentationDocumentContext} from 'sanity/_singletons'\nimport {useRouter} from 'sanity/router'\nimport {DocumentPane, PaneLayout, PaneRouterContext, StructureToolProvider} from 'sanity/structure'\nimport {DocumentPanel, type PanelEntry, type StructureModule} from '../bar/DocumentPanel'\nimport {type BarHost, PreviewBarView} from '../bar/PreviewBar'\nimport type {MoreMenuOptions} from '../bar/shell'\nimport {useStudioBarData} from './studio-bar-data'\nimport type {LiveEditOptions} from './live-edit'\nimport type {VisualEditorLocations} from './locations'\nimport {PaneResizer} from '../bar/StudioLayer'\nimport {applyEdit, PANEL_WIDTH, panelLayout, readNumber, store} from '../bar/pane-state'\nimport {clientDocumentFetcher, createNodeDescriber, type LabelSchema} from '../core/node-labels'\nimport {findPageDocumentRule, type PageDocumentRule} from '../core/page-documents'\nimport {sameOriginPath} from '../core/paths'\nimport {\n isPreviewBarMessage,\n PREVIEW_BAR_FRAME_NAME,\n PREVIEW_BAR_HEIGHT,\n PREVIEW_BAR_ROUTE,\n type PreviewBarMessage,\n type PreviewBarSelection,\n type PreviewBarViewport,\n} from '../core/protocol'\n\nexport type VisualEditorToolOptions = {\n /** The tool's name, in its URL. Default `visual-editor`. */\n name?: string\n /** Default `Visual Editor`. */\n title?: string\n previewUrl?: {\n /** The page opened without `?preview=`. Default `/`. */\n initial?: string\n /**\n * The site's preview-mode route, as in Presentation's `previewUrl.previewMode.enable`. The tool\n * creates a preview secret and opens the page through it. Default `/preview/enable`.\n */\n previewMode?: {enable: string}\n }\n /** The bar's route on the site. Default `/__visual-editor`. */\n barPath?: string\n /**\n * Presentation's document resolvers, with its API (`defineDocuments`, `defineLocations`):\n * - `mainDocuments`: which document each page shows; the pane opens it as you browse. Resolved\n * with the editor's client; without it, the site's `/__visual-editor/document` route is asked.\n * - `locations`: where each document appears; every document form shows \"Used on N pages\", each\n * page opening here.\n */\n resolve?: {\n mainDocuments?: PageDocumentRule[]\n locations?: VisualEditorLocations\n }\n /** @deprecated Use `resolve.mainDocuments`. */\n mainDocuments?: PageDocumentRule[]\n /** The site serves short preview links (`links` in `createPreviewBar`). Default `true`. */\n links?: boolean\n /** Document types the bar's Studio search opens filtered to. Default: all types. */\n searchTypes?: string[]\n /** The document pane's width. Default 420. */\n paneWidth?: number\n /**\n * Hide the Studio's navbar while the tool is open, so the preview bar is the only toolbar (its\n * logo goes back to the Studio). Default `true`.\n */\n hideStudioNavbar?: boolean\n /**\n * Stream unsaved edits (and Portable Text keystrokes) to the storefront's realtime preview hub.\n * Enabled by default (`true`); pass `false` to disable, or an options object to customize.\n */\n liveEdit?: boolean | LiveEditOptions\n /** The bar's \"…\" menu: a code link (e.g. the repository) and a document for site preferences. */\n menu?: MoreMenuOptions\n}\n\n/** Device widths: Presentation's narrow viewport, and a portrait tablet. */\nconst VIEWPORT_WIDTHS = {tablet: 768, mobile: 375} as const\n\nconst structure = {\n DocumentPane,\n PaneLayout,\n PaneRouterContext,\n StructureToolProvider,\n} as unknown as StructureModule\n\n/** Presentation's locations banner is redundant beside the page; see the bar's `NO_LOCATIONS`. */\nconst NO_LOCATIONS = {options: [{}], register: () => () => {}}\n\nfunction sameSelection(a: PreviewBarSelection, b: PreviewBarSelection) {\n return (\n a.selected === b.selected && [...a.excluded].sort().join() === [...b.excluded].sort().join()\n )\n}\n\nfunction publishedId(id: string) {\n return id.replace(/^drafts\\./, '').replace(/^versions\\.[^.]+\\./, '')\n}\n\n// The pulse moves between the Studio's two (opaque) skeleton colours rather than fading the bone:\n// the page skeleton covers the loading site, which must never show through it, so the page\n// appears at once when it's removed.\nconst SKELETON_CSS = `\n@keyframes preview-bar-skeleton {\n from { background-color: var(--card-skeleton-color-from, #eeeef1); }\n to { background-color: var(--card-skeleton-color-to, #f7f7f8); }\n}\n.preview-bar-skeleton { background-color: var(--card-skeleton-color-from, #eeeef1); border-radius: 3px; animation: preview-bar-skeleton 0.9s ease-in-out infinite alternate; }\n`\n\nfunction Bone({\n width,\n height,\n style,\n}: {\n width: number | string\n height: number | string\n style?: CSSProperties\n}) {\n return <div className=\"preview-bar-skeleton\" style={{width, height, flex: 'none', ...style}} />\n}\n\n/** The page area until the framed site reports its first page: one bone over the whole page. */\nfunction PageSkeleton() {\n return (\n <div\n aria-busy=\"true\"\n aria-label=\"Loading the page\"\n className=\"preview-bar-skeleton\"\n style={{position: 'absolute', inset: 0, borderRadius: 0}}\n >\n <style>{SKELETON_CSS}</style>\n </div>\n )\n}\n\n/**\n * How long the tool waits, after the frame's `load`, for the page's `mountPreviewBarFrame` to\n * report its path before it stops showing the skeleton and says the page didn't connect.\n */\nexport const FRAME_CONNECT_TIMEOUT_MS = 8000\n\n/**\n * The page area when the site can't be shown: preview mode couldn't be enabled (`message`), or\n * the page loaded but never connected (Presentation's \"Unable to connect\").\n */\nfunction PageError({\n message,\n enablePath,\n pageUrl,\n onRetry,\n}: {\n message: string | null\n enablePath: string\n pageUrl: string | null\n onRetry: () => void\n}) {\n return (\n <Flex\n align=\"center\"\n justify=\"center\"\n padding={4}\n style={{position: 'absolute', inset: 0, overflow: 'auto'}}\n >\n <Card role=\"alert\" padding={4} radius={3} shadow={1} style={{maxWidth: 440, width: '100%'}}>\n <Stack gap={4}>\n <Text size={2} weight=\"semibold\">\n {message ? 'Couldn’t open the preview' : 'Unable to connect to the page'}\n </Text>\n {message ? (\n <Text size={1} muted>\n {message}\n </Text>\n ) : (\n <Stack gap={3}>\n <Text size={1} muted>\n The page loaded but didn’t connect to the Visual Editor. Check that:\n </Text>\n <ul style={{margin: 0, paddingLeft: 20, display: 'grid', gap: 12}}>\n <li>\n <Text size={1} muted>\n <code>previewMode.enable</code> (<code>{enablePath}</code>) is your site’s\n preview-mode route, and its secret check passes\n </Text>\n </li>\n <li>\n <Text size={1} muted>\n the page loads without an error\n </Text>\n </li>\n <li>\n <Text size={1} muted>\n your layout calls <code>mountPreviewBarFrame</code> when{' '}\n <code>isPreviewBarFrame()</code> is true\n </Text>\n </li>\n </ul>\n </Stack>\n )}\n <Flex gap={2}>\n <Button mode=\"default\" tone=\"primary\" text=\"Retry\" onClick={onRetry} />\n {pageUrl && (\n <Button\n as=\"a\"\n mode=\"ghost\"\n text=\"Open in new tab\"\n href={pageUrl}\n target=\"_blank\"\n rel=\"noopener\"\n />\n )}\n </Flex>\n </Stack>\n </Card>\n </Flex>\n )\n}\n\n/**\n * The pane column until the page's document is known, laid out as the Studio's document pane is\n * (measured at 420px): the 50px header with the Published and Draft chips and its icon buttons,\n * the title's breadcrumb, the type label and the title, and the footer's status, Publish and\n * actions. No fields: they differ per type.\n */\nfunction PaneSkeleton() {\n const round = {borderRadius: 999}\n // An icon button's glyph, centred in its 25px slot.\n const icon = (right: number) => (\n <Bone width={17} height={17} style={{position: 'absolute', top: 16, right, ...round}} />\n )\n return (\n <div\n aria-busy=\"true\"\n aria-label=\"Loading the document\"\n style={{position: 'relative', height: '100%'}}\n >\n <style>{SKELETON_CSS}</style>\n <div\n style={{\n position: 'relative',\n height: 50,\n borderBottom: '1px solid var(--card-border-color)',\n }}\n >\n <div style={{position: 'absolute', top: 12, left: 12, display: 'flex', gap: 4}}>\n <Bone width={98} height={25} style={round} />\n <Bone width={68} height={25} style={round} />\n </div>\n {icon(16)}\n {icon(45)}\n {icon(74)}\n {icon(103)}\n </div>\n <div style={{position: 'absolute', left: 20, right: 20, top: 69}}>\n <Bone width={96} height={12} />\n </div>\n <div style={{position: 'absolute', left: 20, right: 20, top: 131}}>\n <Bone width={36} height={12} />\n </div>\n <div style={{position: 'absolute', left: 20, right: 20, top: 159}}>\n <Bone width=\"45%\" height={21} />\n </div>\n <div\n style={{\n position: 'absolute',\n left: 16,\n right: 16,\n bottom: 12,\n height: 25,\n display: 'flex',\n alignItems: 'center',\n gap: 8,\n }}\n >\n <Bone width={21} height={21} style={round} />\n <Bone width={68} height={12} />\n <div style={{flex: 1}} />\n <Bone width={79} height={25} />\n <Bone width={17} height={17} style={{...round, margin: '0 4px'}} />\n </div>\n </div>\n )\n}\n\n/** The tool pane's width, apart from the site pane's (the tool's pane is full height). */\nconst PANE_WIDTH_KEY = 'sanity-visual-editor:visual-editor-pane-width'\n\n/**\n * Below this tool width the page and the document no longer sit side by side: one shows at a time\n * under the bar, as in Presentation, and the bar's Edit toggles between them. It leaves the page\n * about 480px beside a 420px pane, so neither is squeezed (the pane's header clips under 400px).\n */\nexport const NARROW_TOOL_WIDTH = 900\n\ntype NarrowView = 'preview' | 'document'\n\n/** An element's width, kept current: the tool lays out by its own space, not the window's. */\nfunction useElementWidth(ref: RefObject<HTMLElement | null>) {\n const [width, setWidth] = useState(() => window.innerWidth)\n useLayoutEffect(() => {\n const element = ref.current\n if (!element) return\n setWidth(element.getBoundingClientRect().width)\n const observer = new ResizeObserver(([entry]) => {\n if (entry) setWidth(entry.contentRect.width)\n })\n observer.observe(element)\n return () => observer.disconnect()\n }, [ref])\n return width\n}\n\nexport function VisualEditorTool({tool}: {tool: Tool<VisualEditorToolOptions>}) {\n const options = tool.options ?? {}\n const barPath = options.barPath ?? PREVIEW_BAR_ROUTE\n const enablePath = options.previewUrl?.previewMode?.enable ?? '/preview/enable'\n // The pane resizes from its inner edge, as the site's pane does: live while dragging, clamped so\n // the page keeps its minimum width, remembered on release. Sized by the tool's own width.\n const rootRef = useRef<HTMLDivElement | null>(null)\n const toolWidth = useElementWidth(rootRef)\n const narrow = toolWidth < NARROW_TOOL_WIDTH\n const [narrowView, setNarrowView] = useState<NarrowView>('preview')\n const [preferredPaneWidth, setPreferredPaneWidth] = useState(\n () => readNumber(PANE_WIDTH_KEY) ?? options.paneWidth ?? PANEL_WIDTH,\n )\n const paneWidth = panelLayout(preferredPaneWidth, toolWidth).width\n const [resizing, setResizing] = useState(false)\n const paneWidthRef = useRef(paneWidth)\n paneWidthRef.current = paneWidth\n const paneResize = useMemo(\n () => ({\n start: () => setResizing(true),\n to: (width: number) => setPreferredPaneWidth(width),\n end: () => {\n setResizing(false)\n setPreferredPaneWidth(paneWidthRef.current)\n store('localStorage', PANE_WIDTH_KEY, String(paneWidthRef.current))\n },\n }),\n [],\n )\n const origin = window.location.origin\n\n const router = useRouter()\n const {basePath} = useWorkspace()\n const basePathRef = useRef(basePath)\n basePathRef.current = basePath\n const routerRef = useRef(router)\n routerRef.current = router\n const initialPath = useMemo(() => {\n const preview = new URLSearchParams(\n (router.state._searchParams as [string, string][] | undefined) ?? [],\n ).get('preview')\n // Same-origin paths only: the page is framed under the tool's bar and goes to the site's\n // enable route as its redirect.\n return sameOriginPath(preview) ?? options.previewUrl?.initial ?? '/'\n // Only the first page: the frame navigates itself after that.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n // The bar's data, from the Studio: it renders with the tool.\n const barData = useStudioBarData({\n barPath,\n links: options.links ?? true,\n searchTypes: options.searchTypes,\n })\n\n // Perspective, both ways: the bar's switches move the Studio's sticky params; the Studio's own\n // switches (the pane's chips, the navbar menu) go to the bar, which stores them and refreshes.\n const {selectedPerspectiveName, excludedPerspectives, perspectiveStack} = usePerspective()\n const studioSelection = useMemo<PreviewBarSelection>(\n () => ({selected: selectedPerspectiveName ?? 'drafts', excluded: excludedPerspectives ?? []}),\n [selectedPerspectiveName, excludedPerspectives],\n )\n const studioSelectionRef = useRef(studioSelection)\n studioSelectionRef.current = studioSelection\n\n /** Stores a perspective in the site's cookie; `false` outside preview mode (the route 404s). */\n const storePerspective = useCallback(\n async (selection: PreviewBarSelection) => {\n const response = await fetch(`${barPath}/perspective`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {'content-type': 'application/json'},\n body: JSON.stringify(selection),\n })\n return response.ok\n },\n [barPath],\n )\n\n // Start: store the Studio's perspective for the site. That also tells whether the editor is in\n // preview mode already (the route answers only then): if so, the site loads directly; otherwise\n // preview mode is enabled as Presentation does it, through a preview secret, and the perspective\n // is stored once the site is in.\n const client = useClient({apiVersion: '2025-02-19'})\n const currentUser = useCurrentUser()\n const [frameSrc, setFrameSrc] = useState<string | null>(null)\n const [frameError, setFrameError] = useState<string | null>(null)\n // Bumped by Retry: starts over (enabling preview mode again) with a new frame.\n const [attempt, setAttempt] = useState(0)\n const perspectiveStored = useRef(false)\n useEffect(() => {\n let cancelled = false\n async function start() {\n const stored = await storePerspective(studioSelectionRef.current).catch(() => false)\n if (cancelled) return\n if (stored) {\n perspectiveStored.current = true\n setFrameSrc(new URL(initialPath, origin).toString())\n return\n }\n const {secret} = await createPreviewSecret(\n client,\n 'sanity-plugin-visual-editor/visual-editor',\n window.location.href,\n currentUser?.id,\n )\n if (cancelled) return\n const url = new URL(enablePath, origin)\n url.searchParams.set(urlSearchParamPreviewSecret, secret)\n url.searchParams.set(urlSearchParamPreviewPathname, initialPath)\n setFrameSrc(url.toString())\n }\n start().catch((error: unknown) => {\n console.error('sanity-visual-editor: could not enable preview mode', error)\n if (!cancelled)\n setFrameError('Couldn’t open the preview. Check that you can edit this dataset.')\n })\n return () => {\n cancelled = true\n }\n // Once per tool mount, and again on Retry.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [attempt])\n\n const siteFrame = useRef<HTMLIFrameElement | null>(null)\n const [viewport, setViewport] = useState<PreviewBarViewport>('desktop')\n const device = viewport === 'desktop' ? null : VIEWPORT_WIDTHS[viewport]\n const [path, setPath] = useState<string | null>(null)\n const [mainDocument, setMainDocument] = useState<{id: string; type: string} | null>(null)\n const [mainDocumentLoaded, setMainDocumentLoaded] = useState(false)\n // The pane: open with the page's document by default; closing it is remembered until Edit.\n const [stack, setStack] = useState<PanelEntry[]>([])\n const [paneWanted, setPaneWanted] = useState(true)\n\n // The bar's host, in process: its messages go to `handleBarMessage`, the tool's to its listeners.\n const barListeners = useRef(new Set<(message: PreviewBarMessage) => void>())\n const postToBar = useCallback((message: PreviewBarMessage) => {\n for (const listener of barListeners.current) listener(message)\n }, [])\n const handleBarMessage = useRef<(message: PreviewBarMessage) => void>(() => {})\n const pathRef = useRef<string | null>(null)\n const barHost = useMemo<BarHost>(\n () => ({\n post: (message) => handleBarMessage.current(message),\n subscribe(listener) {\n barListeners.current.add(listener)\n return () => barListeners.current.delete(listener)\n },\n initialPath: () => pathRef.current,\n }),\n [],\n )\n\n const postToSite = useCallback(\n (message: PreviewBarMessage) => siteFrame.current?.contentWindow?.postMessage(message, origin),\n [origin],\n )\n\n // Click-to-edit's labels and drift check for the framed page: the Studio's schema, and documents\n // in the Studio's perspective.\n const schema = useSchema()\n const describerKey = JSON.stringify(perspectiveStack)\n const describer = useMemo(\n () =>\n createNodeDescriber(\n schema as unknown as LabelSchema,\n clientDocumentFetcher(\n client as unknown as Parameters<typeof clientDocumentFetcher>[0],\n perspectiveStack,\n ),\n ),\n // `perspectiveStack` by value.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [schema, client, describerKey],\n )\n const describerRef = useRef(describer)\n describerRef.current = describer\n const reportFocus = useCallback(\n (focus: {id: string; path: string} | null) =>\n postToSite({\n type: 'sanity-visual-editor:focus',\n id: focus?.id ?? '',\n path: focus?.path ?? '',\n }),\n [postToSite],\n )\n\n // Enabled through a secret: store the perspective once the site is in, then refresh it.\n const pathKnown = path !== null\n useEffect(() => {\n if (!pathKnown || perspectiveStored.current) return\n perspectiveStored.current = true\n storePerspective(studioSelectionRef.current)\n .then((stored) => {\n if (stored) postToSite({type: 'sanity-visual-editor:refresh'})\n })\n .catch(() => {})\n }, [pathKnown, storePerspective, postToSite])\n\n // The page's main document: Presentation's `mainDocuments` rules resolved here with the editor's\n // client in the Studio's perspective, or the site's route without them.\n const mainDocuments = options.resolve?.mainDocuments ?? options.mainDocuments\n const stackKey = JSON.stringify(perspectiveStack)\n // The first page is known before the site loads (`?preview=`), so the pane starts with it.\n const documentPath = path ?? initialPath\n useEffect(() => {\n let cancelled = false\n let lookup: Promise<{_id: string; _type: string} | null>\n if (mainDocuments) {\n const rule = findPageDocumentRule(mainDocuments, documentPath, origin)\n lookup = rule\n ? client\n .withConfig({perspective: perspectiveStack as never})\n .fetch<{_id: string; _type: string} | null>(\n `*[${rule.filter}][0]{_id, _type}`,\n rule.params,\n {tag: 'preview-bar.main-document'},\n )\n : Promise.resolve(null)\n } else {\n lookup = fetch(`${barPath}/document?${new URLSearchParams({path: documentPath})}`, {\n credentials: 'same-origin',\n })\n .then((response) => (response.ok ? response.json() : {document: null}))\n .then(({document}: {document: {_id: string; _type: string} | null}) => document)\n }\n lookup\n .then((document) => {\n if (!cancelled)\n setMainDocument(document ? {id: publishedId(document._id), type: document._type} : null)\n })\n .catch(() => {\n if (!cancelled) setMainDocument(null)\n })\n .finally(() => {\n if (!cancelled) setMainDocumentLoaded(true)\n })\n return () => {\n cancelled = true\n }\n // `perspectiveStack` by value.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [documentPath, barPath, mainDocuments, client, stackKey])\n\n // The pane follows the page while it's wanted.\n useEffect(() => {\n if (!paneWanted) return\n setStack((current) => {\n if (!mainDocument) return []\n return current[0]?.id === mainDocument.id\n ? current\n : [{id: mainDocument.id, type: mainDocument.type, params: {}}]\n })\n }, [mainDocument, paneWanted])\n\n // The page's document for the bar's page picker, which previews it with the Studio's own\n // `Preview` (the type's icon or media, the live title).\n useEffect(() => {\n if (mainDocumentLoaded)\n postToBar({type: 'sanity-visual-editor:page-document', document: mainDocument})\n }, [mainDocument, mainDocumentLoaded, postToBar])\n\n const paneOpen = stack.length > 0\n // The pane's column shows while its document loads too, so the bar lays out for it from the start.\n const paneLoading = paneWanted && !mainDocumentLoaded\n const columnOpen = paneOpen || paneLoading\n const editorAvailable = mainDocument !== null\n // Narrow, the document shows only while there's one to show; otherwise the page does.\n const view: NarrowView = narrowView === 'document' && columnOpen ? 'document' : 'preview'\n // The bar's Edit hides while the pane is beside the page. Narrow, it's a toggle: pressed while\n // the document shows instead of the page.\n const barEditorOpen = narrow ? view === 'document' : columnOpen\n useEffect(() => {\n postToBar({\n type: 'sanity-visual-editor:editor-state',\n open: barEditorOpen,\n available: editorAvailable,\n toggle: narrow,\n })\n }, [barEditorOpen, editorAvailable, narrow, postToBar])\n\n const changeStack = useCallback((next: PanelEntry[]) => {\n if (next.length === 0) {\n setPaneWanted(false)\n setNarrowView('preview')\n }\n setStack(next)\n }, [])\n\n const lastBarSelection = useRef<PreviewBarSelection | null>(null)\n useEffect(() => {\n const fromBar = lastBarSelection.current\n if (!fromBar || sameSelection(fromBar, studioSelection)) return\n postToBar({type: 'sanity-visual-editor:set-perspective', selection: studioSelection})\n }, [studioSelection, postToBar])\n\n const menu = options.menu\n const barOptions = useMemo(\n () => ({\n menu: {\n code: menu?.code,\n editPreferences: menu?.preferences\n ? () => routerRef.current.navigateIntent('edit', menu.preferences!)\n : undefined,\n },\n }),\n [menu],\n )\n\n const onIntent = useCallback((name: string, params: Record<string, string>) => {\n if (name === 'edit' && params.id && params.type) {\n setStack((current) => [...current, {id: params.id!, type: params.type!, params: {}}])\n return\n }\n routerRef.current.navigateIntent(name, params)\n }, [])\n\n // Messages from the bar (in process) and the framed site (`postMessage`).\n /** The bar's inspector, resent to the framed page after each load. */\n const inspectorRef = useRef(false)\n const latest = useRef({\n path,\n barEditorOpen,\n studioSelection,\n mainDocument,\n mainDocumentLoaded,\n stack,\n })\n latest.current = {path, barEditorOpen, studioSelection, mainDocument, mainDocumentLoaded, stack}\n pathRef.current = path\n const narrowRef = useRef(narrow)\n narrowRef.current = narrow\n /**\n * Edit: the page's document. Narrow, a pane already open (perhaps on another document) is behind\n * the page, so it's shown as it is.\n */\n const openEditor = useCallback(() => {\n const {mainDocument: main, stack: current} = latest.current\n if (current.length && narrowRef.current) {\n setNarrowView('document')\n return\n }\n if (!main) return\n setPaneWanted(true)\n setStack([{id: main.id, type: main.type, params: {}}])\n setNarrowView('document')\n }, [])\n handleBarMessage.current = (message) => {\n switch (message.type) {\n case 'sanity-visual-editor:ready':\n // After the bar's other listeners subscribe (the same commit's effects run first).\n queueMicrotask(() => {\n const {\n path: current,\n barEditorOpen: open,\n mainDocument: main,\n mainDocumentLoaded: loaded,\n } = latest.current\n if (current) postToBar({type: 'sanity-visual-editor:path', path: current})\n postToBar({\n type: 'sanity-visual-editor:editor-state',\n open,\n available: main !== null,\n toggle: narrowRef.current,\n })\n if (loaded) postToBar({type: 'sanity-visual-editor:page-document', document: main})\n })\n break\n case 'sanity-visual-editor:refresh':\n postToSite({type: 'sanity-visual-editor:refresh'})\n break\n case 'sanity-visual-editor:navigate':\n postToSite({type: 'sanity-visual-editor:navigate', href: message.href})\n break\n case 'sanity-visual-editor:viewport':\n setViewport(message.mode)\n break\n case 'sanity-visual-editor:open-document': {\n const {id, type, template, templateParameters} = message.document\n const entry: PanelEntry = {id, type, params: {}, template, templateParameters}\n setPaneWanted(true)\n setNarrowView('document')\n // The page's document replaces the stack; anything else (a new document, a search result\n // without a page) goes on top, so × goes back.\n setStack((current) =>\n !template && id === latest.current.mainDocument?.id\n ? [entry]\n : current.length\n ? [...current, entry]\n : [entry],\n )\n break\n }\n case 'sanity-visual-editor:perspective': {\n lastBarSelection.current = message.selection\n if (sameSelection(message.selection, latest.current.studioSelection)) break\n const {selected, excluded} = message.selection\n routerRef.current.navigate({\n stickyParams: {\n perspective: selected === 'drafts' ? null : selected,\n excludedPerspectives: excluded.length ? excluded.join(',') : null,\n },\n } as never)\n break\n }\n case 'sanity-visual-editor:open-editor':\n openEditor()\n break\n case 'sanity-visual-editor:close-editor':\n // Narrow: back to the page. The pane stays as it is behind it, for the next Edit.\n setNarrowView('preview')\n break\n case 'sanity-visual-editor:inspector':\n inspectorRef.current = message.active\n postToSite(message)\n break\n case 'sanity-visual-editor:studio-home':\n // The workspace's root, through the Studio's router (its default tool), no reload.\n routerRef.current.navigateUrl({path: basePathRef.current || '/'})\n break\n // `menu` (overlays need no unclipping here) and `hide` don't apply in the tool.\n }\n }\n useEffect(() => {\n function onMessage(event: MessageEvent) {\n if (event.origin !== origin || event.source !== siteFrame.current?.contentWindow) return\n if (!isPreviewBarMessage(event.data)) return\n const message = event.data\n switch (message.type) {\n case 'sanity-visual-editor:frame-path': {\n setPath(message.path)\n setConnectFailed(false)\n // A new page in the frame starts with click-to-edit off.\n postToSite({type: 'sanity-visual-editor:inspector', active: inspectorRef.current})\n postToBar({type: 'sanity-visual-editor:path', path: message.path})\n // The Studio's URL follows the page, as Presentation's `?preview=` does.\n const {state, navigate} = routerRef.current\n const params = ((state._searchParams as [string, string][] | undefined) ?? []).filter(\n ([key]) => key !== 'preview',\n )\n navigate({...state, _searchParams: [...params, ['preview', message.path]]} as never, {\n replace: true,\n })\n break\n }\n case 'sanity-visual-editor:refreshed':\n postToBar({type: 'sanity-visual-editor:refreshed'})\n break\n // Click-to-edit in the page: the page's document opens (or focuses) at the path, any\n // other document goes on the pane's stack.\n case 'sanity-visual-editor:edit': {\n const {stack: current, mainDocument: main} = latest.current\n setPaneWanted(true)\n setNarrowView('document')\n // From a closed pane, another document still opens above the page's (the pane follows\n // the page, and × goes back to it).\n const base =\n current.length || !main ? current : [{id: main.id, type: main.type, params: {}}]\n applyEdit(base, message, main?.id ?? null, setStack)\n break\n }\n case 'sanity-visual-editor:toggle-inspector':\n postToBar(message)\n break\n case 'sanity-visual-editor:describe':\n describerRef\n .current(message.nodes)\n .then((labels) => postToSite({type: 'sanity-visual-editor:labels', labels}))\n .catch((error: unknown) =>\n console.warn('sanity-visual-editor: could not describe the page', error),\n )\n break\n case 'sanity-visual-editor:live-status':\n postToBar(message)\n break\n }\n }\n window.addEventListener('message', onMessage)\n return () => window.removeEventListener('message', onMessage)\n }, [origin, postToBar, postToSite])\n\n // Everything shows as soon as it's ready: the bar at once (Studio data), the page and the pane\n // each behind a skeleton until theirs arrives. The pane's column is held from the start, so the\n // page doesn't shift when the document opens.\n // The frame's `load` without a `frame-path` (a wrong enable route, a failed secret check, an\n // error page, a layout without `mountPreviewBarFrame`) would leave the skeleton up for good: after\n // a while, it gives way to an error card.\n const [frameLoads, setFrameLoads] = useState(0)\n const [connectFailed, setConnectFailed] = useState(false)\n useEffect(() => {\n if (frameLoads === 0 || path !== null) return\n const timer = setTimeout(() => setConnectFailed(true), FRAME_CONNECT_TIMEOUT_MS)\n return () => clearTimeout(timer)\n }, [frameLoads, path])\n const retry = useCallback(() => {\n setConnectFailed(false)\n setFrameError(null)\n setFrameLoads(0)\n setPath(null)\n setFrameSrc(null)\n perspectiveStored.current = false\n setAttempt((value) => value + 1)\n }, [])\n const pageLoading = path === null && !frameError && !connectFailed\n\n // Like the bar on the site: the document pane runs top to bottom on the right, and the bar sits\n // beside it, above the page. Narrow, the pane takes the page's place under the bar instead, one\n // at a time. Both stay mounted (the hidden one keeps its size, out of sight), so the bar's Edit\n // toggles between them without reloading the page or losing the form's place.\n const documentShown = narrow && view === 'document'\n return (\n <div\n ref={rootRef}\n style={{\n position: 'relative',\n display: 'flex',\n height: '100%',\n minHeight: 0,\n background: 'var(--card-bg-color)',\n }}\n >\n <div style={{display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0, minHeight: 0}}>\n <div style={{position: 'relative', flex: 'none', height: PREVIEW_BAR_HEIGHT}}>\n <PreviewBarView\n data={barData}\n host={barHost}\n sanity={sanityModule}\n options={barOptions}\n editorState={{open: barEditorOpen, available: editorAvailable, toggle: narrow}}\n pageDocument={mainDocumentLoaded ? mainDocument : undefined}\n />\n </div>\n <div\n style={{\n position: 'relative',\n display: 'flex',\n // A device wider than the space (a tablet beside the pane) scrolls sideways; `safe`\n // keeps its left edge reachable instead of centring it off-screen.\n justifyContent: 'safe center',\n flex: 1,\n minHeight: 0,\n overflowX: device ? 'auto' : 'hidden',\n overflowY: 'hidden',\n // Presentation's frame backdrop: the muted card colour around the phone.\n background: 'var(--card-muted-bg-color, var(--card-bg-color))',\n visibility: documentShown ? 'hidden' : 'visible',\n }}\n >\n {frameSrc ? (\n <iframe\n key={attempt}\n ref={siteFrame}\n name={PREVIEW_BAR_FRAME_NAME}\n onLoad={() => setFrameLoads((value) => value + 1)}\n title=\"Preview\"\n src={frameSrc}\n allow=\"clipboard-write\"\n style={{\n display: 'block',\n flex: 'none',\n // Shopify's phone frame: a 4px gap above and below (square corners).\n width: device ?? '100%',\n // The Studio's global styles cap iframes at `max-width: 100%`.\n maxWidth: 'none',\n height: device ? 'calc(100% - 8px)' : '100%',\n margin: device ? '4px 0' : 0,\n border: 0,\n background: 'var(--card-bg-color)',\n boxShadow: device ? '0 0 0 1px var(--card-border-color)' : 'none',\n // The resizer's pointer stays with it while dragging over the page.\n pointerEvents: resizing ? 'none' : undefined,\n transition: ['width', 'height', 'margin']\n .map((property) => `${property} 300ms cubic-bezier(0.2, 0, 0, 1)`)\n .join(', '),\n }}\n />\n ) : null}\n {pageLoading && <PageSkeleton />}\n {(frameError || connectFailed) && (\n <PageError\n message={frameError}\n enablePath={enablePath}\n pageUrl={frameError ? null : new URL(path ?? initialPath, origin).toString()}\n onRetry={retry}\n />\n )}\n </div>\n </div>\n {(paneOpen || paneLoading) && (\n <div\n data-preview-bar-panel=\"\"\n style={{\n position: 'relative',\n flex: 'none',\n width: paneWidth,\n height: '100%',\n minHeight: 0,\n overflow: 'hidden',\n borderLeft: '1px solid var(--card-border-color)',\n // Narrow: in the page's place, under the bar.\n ...(narrow && {\n position: 'absolute',\n top: PREVIEW_BAR_HEIGHT,\n right: 0,\n bottom: 0,\n left: 0,\n width: 'auto',\n height: 'auto',\n borderLeft: 0,\n visibility: documentShown ? 'visible' : 'hidden',\n }),\n }}\n >\n {!narrow && <PaneResizer width={paneWidth} side=\"right\" resize={paneResize} />}\n {paneOpen ? (\n <PresentationDocumentContext.Provider value={NO_LOCATIONS as never}>\n <DocumentPanel\n structure={structure}\n stack={stack}\n onChange={changeStack}\n onIntent={onIntent}\n onFocusPath={reportFocus}\n fallback={<PaneSkeleton />}\n />\n </PresentationDocumentContext.Provider>\n ) : (\n <PaneSkeleton />\n )}\n </div>\n )}\n </div>\n )\n}\n","/**\n * `sanity-plugin-visual-editor/studio`: the Visual Editor tool for the Studio. Presentation's layout with\n * the preview bar on top, the site in the middle (desktop or a 375px phone) and the document pane\n * on the right. The bar's **Edit** on the site opens a page here (`visualEditor` bar option).\n *\n * ```ts\n * // sanity.config.ts\n * import {visualEditorTool} from 'sanity-plugin-visual-editor/studio'\n * plugins: [visualEditorTool({previewUrl: {previewMode: {enable: '/preview/enable'}}})]\n * ```\n */\nimport EditIcon from '@sanity/icons/Edit'\nimport {createElement, type ReactNode} from 'react'\nimport {definePlugin} from 'sanity'\nimport {route, useRouter} from 'sanity/router'\nimport type {\n DocumentLocationResolverObject,\n DocumentLocationsState,\n DocumentResolver,\n} from 'sanity/presentation'\nimport {liveEditPlugin, type LiveEditOptions} from './live-edit'\nimport {locationsInput} from './locations'\nimport {VisualEditorTool, type VisualEditorToolOptions} from './VisualEditorTool'\n\nexport type {LiveEditOptions, VisualEditorToolOptions}\nexport type VisualEditorOptions = VisualEditorToolOptions\nexport {liveEditPlugin}\nexport type {VisualEditorLocations} from './locations'\nexport type {\n DocumentLocation,\n DocumentLocationResolver,\n DocumentLocationResolverObject,\n DocumentLocationResolvers,\n DocumentLocationsState,\n DocumentResolver,\n DocumentResolverContext,\n} from 'sanity/presentation'\n\n/**\n * Presentation's `defineLocations`, for `resolve.locations`: types a resolver, does nothing else.\n * The same resolvers work in both tools.\n */\nexport function defineLocations<K extends string>(\n resolver: DocumentLocationResolverObject<K> | DocumentLocationsState,\n): typeof resolver {\n return resolver\n}\n\n/** Presentation's `defineDocuments`, for `resolve.mainDocuments`: types the list, nothing else. */\nexport function defineDocuments(resolvers: DocumentResolver[]): typeof resolvers {\n return resolvers\n}\n\ntype NavbarProps = {renderDefault: (props: NavbarProps) => ReactNode}\n\n/**\n * The Studio's navbar, except in the Visual Editor, where the preview bar is the toolbar (the\n * approach of `studio.components.navbar` middleware that renders nothing for one tool).\n */\nfunction navbarFor(toolName: string) {\n return function VisualEditorNavbar(props: NavbarProps) {\n const {state} = useRouter()\n return state.tool === toolName ? null : props.renderDefault(props)\n }\n}\n\nexport const visualEditor = definePlugin<VisualEditorToolOptions | void>((options) => {\n const settings = options ?? {}\n const toolName = settings.name ?? 'visual-editor'\n const locations = settings.resolve?.locations\n const liveEdit = settings.liveEdit ?? true\n return {\n name: 'sanity-plugin-visual-editor/visual-editor',\n // \"Used on N pages\" above every document form, as Presentation's `resolve.locations` does.\n ...(locations ? {form: {components: {input: locationsInput(locations, toolName)}}} : {}),\n ...(settings.hideStudioNavbar === false\n ? {}\n : {studio: {components: {navbar: navbarFor(toolName) as never}}}),\n ...(liveEdit !== false\n ? {plugins: [liveEditPlugin(liveEdit === true ? undefined : liveEdit)]}\n : {}),\n tools: [\n {\n name: toolName,\n title: settings.title ?? 'Visual Editor',\n icon: EditIcon,\n options: settings,\n // `?preview=/path` at the top level, as Presentation's router does.\n router: route.create('/', {__unsafe_disableScopedSearchParams: true}),\n component: (props: {tool: unknown}) =>\n createElement(VisualEditorTool, props as Parameters<typeof VisualEditorTool>[0]),\n },\n ],\n }\n})\n\n/** @deprecated Use `visualEditor`. */\nexport const visualEditorTool = visualEditor\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwCA,MAYM,gCAAgB,IAAI,IAAI;CAAC;CAAQ;CAAc;CAAc;AAAS,CAAC,GAavE,kBAAkB,cAAuE,IAAI,GAE7F,sBAAsB,cAAoC,IAAI;;AAGpE,SAAS,UAAU,OAAgB,MAAqB,aAA+B;CACrF,IAAI,CAAC,KAAK,QAAQ,OAAO;CACzB,IAAM,CAAC,MAAM,GAAG,QAAQ;CACxB,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,IAAM,QACJ,OAAO,QAAS,WACZ,OACA,OAAO,QAAS,YAAY,QAAQ,UAAU,OAC5C,MAAM,WAAW,SAAU,MAAiC,SAAS,KAAK,IAAI,IAC9E;EACR,IAAI,QAAQ,KAAK,SAAS,MAAM,QAAQ,OAAO;EAC/C,IAAM,OAAO,CAAC,GAAG,KAAK;EAEtB,OADA,KAAK,SAAS,UAAU,KAAK,QAAQ,MAAM,WAAW,GAC/C;CACT;CACA,IAAI,OAAO,QAAS,UAAU,OAAO;CACrC,IAAM,SAAU,SAAS,CAAC;CAC1B,OAAO;EAAC,GAAG;GAAS,OAAO,UAAU,OAAO,OAAO,MAAM,WAAW;CAAC;AACvE;;AAGA,SAAS,WAAW,YAAiC;CAEnD,OADI,WAAW,aAAa,WACrB,WAAW,GAAG,MAAM,WAAW;EACpC,KAAK,IAAI,OAA+B,QAAQ,MAAM,OAAO,KAAK,MAChE,IAAI,KAAK,SAAS,SAAS,OAAO;EAEpC,OAAO;CACT,CAAC;AACH;AAEA,SAAS,gBAAgB,UAAkB,YAAoB,QAAgB;CAC7E,IAAI,MAAM,GACN,WA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AmB,OAAoB;EACrD,IAAM,EAAC,UAAS,UAAU;EAC1B,OAAO,MAAM,SAAS,WAAW,OAAO,MAAM,cAAc,KAAK;CACnE;AACF;AAEA,MAAa,eAAe,cAA8C,YAAY;CACpF,IAAM,WAAW,WAAW,CAAC,GACvB,WAAW,SAAS,QAAQ,iBAC5B,YAAY,SAAS,SAAS,WAC9B,WAAW,SAAS,YAAY;CACtC,OAAO;EACL,MAAM;EAEN,GAAI,YAAY,EAAC,MAAM,EAAC,YAAY,EAAC,OAAO,eAAe,WAAW,QAAQ,EAAC,EAAC,EAAC,IAAI,CAAC;EACtF,GAAI,SAAS,qBAAqB,KAC9B,CAAC,IACD,EAAC,QAAQ,EAAC,YAAY,EAAC,QAAQ,UAAU,QAAQ,EAAU,EAAC,EAAC;EACjE,GAAI,aAAa,KAEb,CAAC,IADD,EAAC,SAAS,CAAC,eAAe,aAAa,KAAO,KAAA,IAAY,QAAQ,CAAC,EAAC;EAExE,OAAO,CACL;GACE,MAAM;GACN,OAAO,SAAS,SAAS;GACzB,MAAM;GACN,SAAS;GAET,QAAQ,MAAM,OAAO,KAAK,EAAC,oCAAoC,GAAI,CAAC;GACpE,YAAY,UACV,cAAc,kBAAkB,KAA+C;EACnF,CACF;CACF;AACF,CAAC,GAGY,mBAAmB"}
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SvelteKit adapter, for sites using `@sanity/sveltekit`'s `handlePreviewMode` (the
|
|
3
|
+
* `__sanity_preview` cookie and `event.locals.sanity`). Each route file re-exports one handler; see
|
|
4
|
+
* the README for the full set.
|
|
5
|
+
*
|
|
6
|
+
* Short links never hand out the preview secret: opening one sets a signed link-session cookie
|
|
7
|
+
* that expires with the link, and `previewBar.handle` turns preview on for it.
|
|
8
|
+
*/
|
|
9
|
+
import { D as PreviewHubFetcher, E as PreviewHubClientLike, T as PreviewHub, a as PreviewModeSwitch, i as PreviewContext, m as PreviewLinkErrorRenderer, n as PreviewBarOptions, r as PreviewClient, t as PreviewBar } from "./index-hDzatlg7.js";
|
|
10
|
+
import { s as PreviewLinkStore } from "./preview-links-DM6BCiLV.js";
|
|
11
|
+
import { r as PageDocumentRule } from "./page-documents-BFFcH8lD.js";
|
|
12
|
+
import "./index.js";
|
|
13
|
+
import { C as SearchConfig, n as PreviewBarData, s as PreviewPerspective, t as PreviewBarBrand } from "./data-D0qotTtt.js";
|
|
14
|
+
import { validatePreviewUrl } from "@sanity/preview-url-secret";
|
|
15
|
+
import { RequestEvent } from "@sveltejs/kit";
|
|
16
|
+
/** `handlePreviewMode`'s default preview cookie. */
|
|
17
|
+
export declare const SANITY_PREVIEW_COOKIE = "__sanity_preview";
|
|
18
|
+
type Handle = (input: {
|
|
19
|
+
event: RequestEvent;
|
|
20
|
+
resolve: (event: RequestEvent) => Response | Promise<Response>;
|
|
21
|
+
}) => Response | Promise<Response>;
|
|
22
|
+
export type SvelteKitPreviewBarOptions = {
|
|
23
|
+
/** From `createPreviewBar` (`sanity-plugin-visual-editor/server`). */
|
|
24
|
+
bar: PreviewBar;
|
|
25
|
+
/**
|
|
26
|
+
* The `handlePreviewMode` secret, which is the `__sanity_preview` cookie's value. Also the key
|
|
27
|
+
* that signs link-session cookies; it never reaches a link's recipient.
|
|
28
|
+
*/
|
|
29
|
+
previewSecret: string | (() => string);
|
|
30
|
+
/** Default `__sanity_preview`. */
|
|
31
|
+
previewCookie?: string;
|
|
32
|
+
/** The cookie a short link leaves: signed, expiring with the link. Default `__sanity_preview_link`. */
|
|
33
|
+
linkSessionCookie?: string;
|
|
34
|
+
};
|
|
35
|
+
export declare function createSvelteKitPreviewBar(options: SvelteKitPreviewBarOptions): {
|
|
36
|
+
handle: Handle;
|
|
37
|
+
/** The underlying server bar instance. */
|
|
38
|
+
bar: {
|
|
39
|
+
options: {
|
|
40
|
+
studioPath: string;
|
|
41
|
+
basePath: string;
|
|
42
|
+
linkRoute: string;
|
|
43
|
+
brand: PreviewBarBrand;
|
|
44
|
+
projectId?: string;
|
|
45
|
+
pageDocuments?: PageDocumentRule[];
|
|
46
|
+
search?: SearchConfig | false;
|
|
47
|
+
links?: {
|
|
48
|
+
store: PreviewLinkStore | (() => PreviewLinkStore);
|
|
49
|
+
route?: string;
|
|
50
|
+
ttlSeconds?: number;
|
|
51
|
+
} | false;
|
|
52
|
+
};
|
|
53
|
+
resolveLink: (code: string) => Promise<{
|
|
54
|
+
status: 200;
|
|
55
|
+
link: {
|
|
56
|
+
pathname: string;
|
|
57
|
+
perspective: PreviewPerspective;
|
|
58
|
+
expiresAt: number;
|
|
59
|
+
};
|
|
60
|
+
} | {
|
|
61
|
+
status: 404 | 503;
|
|
62
|
+
}>;
|
|
63
|
+
loadBar: (ctx: PreviewContext) => Promise<PreviewBarData | null>;
|
|
64
|
+
perspective: (ctx: PreviewContext) => Promise<Response>;
|
|
65
|
+
exit: (ctx: Pick<PreviewContext, "request">, disablePreview: PreviewModeSwitch) => Promise<Response>;
|
|
66
|
+
resolveHref: (ctx: PreviewContext) => Promise<Response>;
|
|
67
|
+
pageDocument: (ctx: PreviewContext) => Promise<Response>;
|
|
68
|
+
share: (ctx: PreviewContext) => Promise<Response>;
|
|
69
|
+
openLink: (request: Request, code: string, enablePreview: PreviewModeSwitch) => Promise<Response>;
|
|
70
|
+
};
|
|
71
|
+
/** The configured bar base path (default `/__visual-editor`). */
|
|
72
|
+
basePath: string;
|
|
73
|
+
/** The configured short preview link prefix (default `/p`). */
|
|
74
|
+
linkRoute: string;
|
|
75
|
+
/** The preview cookie name (default `__sanity_preview`). */
|
|
76
|
+
previewCookie: string;
|
|
77
|
+
/** The signed cookie a short link leaves (default `__sanity_preview_link`). */
|
|
78
|
+
linkSessionCookie: string;
|
|
79
|
+
/** Resolves the configured preview secret. */
|
|
80
|
+
getSecret: () => string;
|
|
81
|
+
/** `/__visual-editor/+page.server.ts`: `export const load = previewBar.loadBar`. */
|
|
82
|
+
loadBar(event: RequestEvent): Promise<PreviewBarData>;
|
|
83
|
+
/** `/__visual-editor/perspective/+server.ts`: `export const POST = previewBar.perspective`. */
|
|
84
|
+
perspective: (event: RequestEvent) => Promise<Response>;
|
|
85
|
+
/** `/__visual-editor/exit/+server.ts`: `export const POST = previewBar.exit`. */
|
|
86
|
+
exit: (event: RequestEvent) => Promise<Response>;
|
|
87
|
+
/** `/__visual-editor/resolve/+server.ts`: `export const GET = previewBar.resolveHref`. */
|
|
88
|
+
resolveHref: (event: RequestEvent) => Promise<Response>;
|
|
89
|
+
/** `/__visual-editor/document/+server.ts`: `export const GET = previewBar.pageDocument`. */
|
|
90
|
+
pageDocument: (event: RequestEvent) => Promise<Response>;
|
|
91
|
+
/** `/__visual-editor/share/+server.ts`: `export const POST = previewBar.share`. */
|
|
92
|
+
share: (event: RequestEvent) => Promise<Response>;
|
|
93
|
+
/**
|
|
94
|
+
* `/p/[code]/+page.server.ts`: `export const load = previewBar.openLink`. Redirects into
|
|
95
|
+
* preview, or throws 404/503 for `+error.svelte` to render the expired-link page. Preview
|
|
96
|
+
* comes from a signed link-session cookie that expires with the link (never the preview
|
|
97
|
+
* secret), so it needs `previewBar.handle` in `hooks.server.ts`.
|
|
98
|
+
*/
|
|
99
|
+
openLink(event: RequestEvent & {
|
|
100
|
+
params: {
|
|
101
|
+
code?: string;
|
|
102
|
+
};
|
|
103
|
+
}): Promise<never>;
|
|
104
|
+
};
|
|
105
|
+
export type SvelteKitPreviewBar = ReturnType<typeof createSvelteKitPreviewBar>;
|
|
106
|
+
export type HandleVisualEditorLiveEditOptions = {
|
|
107
|
+
/** Secret used to sign and verify the live-edit session cookie. */
|
|
108
|
+
secret: string | (() => string);
|
|
109
|
+
/** Server Sanity client used to validate preview secrets on session start. */
|
|
110
|
+
client: Parameters<typeof validatePreviewUrl>[0];
|
|
111
|
+
/** Resolve the preview hub for a perspective name (`drafts`, `rABC,drafts`). */
|
|
112
|
+
hubFor: (name: string) => PreviewHub | null;
|
|
113
|
+
/** Resolve the preview hub for the current request's Sanity client. */
|
|
114
|
+
previewHub: (client: PreviewHubClientLike) => PreviewHub | null;
|
|
115
|
+
/** Live-edit base path. Default `/api/preview/live-edit`. */
|
|
116
|
+
liveEditPath?: string;
|
|
117
|
+
/** Realtime preview events long-poll path. Default `/api/preview/events`. */
|
|
118
|
+
eventsPath?: string;
|
|
119
|
+
/** Realtime preview WebSocket path. Default `/api/preview/socket`. */
|
|
120
|
+
socketPath?: string;
|
|
121
|
+
/** Debug hub prefix (`/stats` and `/bench`). Default `/api/preview/hub`. */
|
|
122
|
+
debugPath?: string;
|
|
123
|
+
/** Cookie name for the live-edit session. Default `sanity-live-edit`. */
|
|
124
|
+
cookieName?: string;
|
|
125
|
+
/** Max live-edit payload size in bytes. Default `1_000_000`. */
|
|
126
|
+
maxBytes?: number;
|
|
127
|
+
};
|
|
128
|
+
export type HandleVisualEditorOptions = {
|
|
129
|
+
/** From `createSvelteKitPreviewBar`. */
|
|
130
|
+
bar: SvelteKitPreviewBar;
|
|
131
|
+
/**
|
|
132
|
+
* Published client used when `?studio-preview` suppresses preview mode on Studio thumbnail
|
|
133
|
+
* iframes. Defaults to `sanity.client.withConfig({ perspective: 'published', useCdn: true })`.
|
|
134
|
+
*/
|
|
135
|
+
publishedClient?: () => PreviewClient;
|
|
136
|
+
/** Realtime preview hub + Studio live-edit routes and WebSocket upgrades. */
|
|
137
|
+
liveEdit?: HandleVisualEditorLiveEditOptions;
|
|
138
|
+
/**
|
|
139
|
+
* Handle short preview links (`/p/<code>`) directly inside `handleVisualEditor`, eliminating
|
|
140
|
+
* `src/routes/p/*`. Default `true`. Pass `false` to keep custom SvelteKit `/p/` route files.
|
|
141
|
+
*/
|
|
142
|
+
handleLinks?: boolean;
|
|
143
|
+
/**
|
|
144
|
+
* Custom renderer for expired or unavailable `/p/<code>` link screens (HTML string or `Response`).
|
|
145
|
+
* Defaults to `renderPreviewLinkErrorHtml`.
|
|
146
|
+
*/
|
|
147
|
+
renderLinkError?: PreviewLinkErrorRenderer;
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* Single SvelteKit `Handle` (Better Auth style) that wires the entire Visual Editor server surface:
|
|
151
|
+
* - Applies the perspective cookie (`handlePreviewPerspective`) and `?studio-preview` bypass.
|
|
152
|
+
* - Handles `/p/<code>` short preview link redirects and customizable error HTML screens.
|
|
153
|
+
* - Handles all `/__visual-editor/{perspective,exit,resolve,document,share}` endpoints.
|
|
154
|
+
* - When `liveEdit` is configured, handles `/api/preview/{socket,events,live-edit,live-edit/session,live-edit/socket,hub/*}`
|
|
155
|
+
* including Cloudflare WebSocket `101` upgrades before `resolve()`.
|
|
156
|
+
*
|
|
157
|
+
* Place in `sequence(...)` right after `@sanity/sveltekit`'s `handlePreviewMode`.
|
|
158
|
+
*/
|
|
159
|
+
export declare function handleVisualEditor(options: HandleVisualEditorOptions): ({ event, resolve }: {
|
|
160
|
+
event: RequestEvent;
|
|
161
|
+
resolve: (event: RequestEvent) => Response | Promise<Response>;
|
|
162
|
+
}) => Promise<Response>;
|
|
163
|
+
export type CreateSvelteKitVisualEditorOptions = PreviewBarOptions & {
|
|
164
|
+
/** Shared preview secret (used for both `__sanity_preview` cookie and live-edit session HMAC). */
|
|
165
|
+
secret: string | (() => string);
|
|
166
|
+
/** Default `__sanity_preview`. */
|
|
167
|
+
previewCookie?: string;
|
|
168
|
+
/** Server Sanity client (for live-edit session validation and `?studio-preview` published client). */
|
|
169
|
+
client?: Parameters<typeof validatePreviewUrl>[0] & PreviewClient;
|
|
170
|
+
/** Optional custom published client factory for `?studio-preview`. */
|
|
171
|
+
publishedClient?: () => PreviewClient;
|
|
172
|
+
/** Cloudflare service binding getter (`() => env.PREVIEW_HUB`) for the realtime preview hub. */
|
|
173
|
+
hub?: () => PreviewHubFetcher | undefined;
|
|
174
|
+
/** Extra live-edit path/cookie overrides (only needed if using non-default paths). */
|
|
175
|
+
liveEdit?: Omit<HandleVisualEditorLiveEditOptions, 'secret' | 'client' | 'hubFor' | 'previewHub'>;
|
|
176
|
+
/** Handle `/p/<code>` directly inside `handle`. Default `true`. */
|
|
177
|
+
handleLinks?: boolean;
|
|
178
|
+
/** Custom renderer for expired/unavailable `/p/<code>` screens (HTML string or `Response`). */
|
|
179
|
+
renderLinkError?: PreviewLinkErrorRenderer;
|
|
180
|
+
};
|
|
181
|
+
/**
|
|
182
|
+
* One-stop SvelteKit setup: combines `createPreviewBar`, `createSvelteKitPreviewBar`,
|
|
183
|
+
* `createPreviewHubClient`, and `handleVisualEditor` into a single config object.
|
|
184
|
+
*
|
|
185
|
+
* Returns `{ handle, loadBar, openLink, hubFor, previewHub, bar }`.
|
|
186
|
+
*/
|
|
187
|
+
export declare function createSvelteKitVisualEditor(options: CreateSvelteKitVisualEditorOptions): {
|
|
188
|
+
handle: ({ event, resolve }: {
|
|
189
|
+
event: RequestEvent;
|
|
190
|
+
resolve: (event: RequestEvent) => Response | Promise<Response>;
|
|
191
|
+
}) => Promise<Response>;
|
|
192
|
+
loadBar: (event: RequestEvent) => Promise<PreviewBarData>;
|
|
193
|
+
openLink: (event: RequestEvent & {
|
|
194
|
+
params: {
|
|
195
|
+
code?: string;
|
|
196
|
+
};
|
|
197
|
+
}) => Promise<never>;
|
|
198
|
+
hubFor: (name: string) => PreviewHub | null;
|
|
199
|
+
previewHub: (client: PreviewHubClientLike) => PreviewHub | null;
|
|
200
|
+
bar: {
|
|
201
|
+
handle: Handle;
|
|
202
|
+
/** The underlying server bar instance. */
|
|
203
|
+
bar: {
|
|
204
|
+
options: {
|
|
205
|
+
studioPath: string;
|
|
206
|
+
basePath: string;
|
|
207
|
+
linkRoute: string;
|
|
208
|
+
brand: PreviewBarBrand;
|
|
209
|
+
projectId?: string;
|
|
210
|
+
pageDocuments?: PageDocumentRule[];
|
|
211
|
+
search?: SearchConfig | false;
|
|
212
|
+
links?: {
|
|
213
|
+
store: PreviewLinkStore | (() => PreviewLinkStore);
|
|
214
|
+
route?: string;
|
|
215
|
+
ttlSeconds?: number;
|
|
216
|
+
} | false;
|
|
217
|
+
};
|
|
218
|
+
resolveLink: (code: string) => Promise<{
|
|
219
|
+
status: 200;
|
|
220
|
+
link: {
|
|
221
|
+
pathname: string;
|
|
222
|
+
perspective: PreviewPerspective;
|
|
223
|
+
expiresAt: number;
|
|
224
|
+
};
|
|
225
|
+
} | {
|
|
226
|
+
status: 404 | 503;
|
|
227
|
+
}>;
|
|
228
|
+
loadBar: (ctx: PreviewContext) => Promise<PreviewBarData | null>;
|
|
229
|
+
perspective: (ctx: PreviewContext) => Promise<Response>;
|
|
230
|
+
exit: (ctx: Pick<PreviewContext, "request">, disablePreview: PreviewModeSwitch) => Promise<Response>;
|
|
231
|
+
resolveHref: (ctx: PreviewContext) => Promise<Response>;
|
|
232
|
+
pageDocument: (ctx: PreviewContext) => Promise<Response>;
|
|
233
|
+
share: (ctx: PreviewContext) => Promise<Response>;
|
|
234
|
+
openLink: (request: Request, code: string, enablePreview: PreviewModeSwitch) => Promise<Response>;
|
|
235
|
+
};
|
|
236
|
+
/** The configured bar base path (default `/__visual-editor`). */
|
|
237
|
+
basePath: string;
|
|
238
|
+
/** The configured short preview link prefix (default `/p`). */
|
|
239
|
+
linkRoute: string;
|
|
240
|
+
/** The preview cookie name (default `__sanity_preview`). */
|
|
241
|
+
previewCookie: string;
|
|
242
|
+
/** The signed cookie a short link leaves (default `__sanity_preview_link`). */
|
|
243
|
+
linkSessionCookie: string;
|
|
244
|
+
/** Resolves the configured preview secret. */
|
|
245
|
+
getSecret: () => string;
|
|
246
|
+
/** `/__visual-editor/+page.server.ts`: `export const load = previewBar.loadBar`. */
|
|
247
|
+
loadBar(event: RequestEvent): Promise<PreviewBarData>;
|
|
248
|
+
/** `/__visual-editor/perspective/+server.ts`: `export const POST = previewBar.perspective`. */
|
|
249
|
+
perspective: (event: RequestEvent) => Promise<Response>;
|
|
250
|
+
/** `/__visual-editor/exit/+server.ts`: `export const POST = previewBar.exit`. */
|
|
251
|
+
exit: (event: RequestEvent) => Promise<Response>;
|
|
252
|
+
/** `/__visual-editor/resolve/+server.ts`: `export const GET = previewBar.resolveHref`. */
|
|
253
|
+
resolveHref: (event: RequestEvent) => Promise<Response>;
|
|
254
|
+
/** `/__visual-editor/document/+server.ts`: `export const GET = previewBar.pageDocument`. */
|
|
255
|
+
pageDocument: (event: RequestEvent) => Promise<Response>;
|
|
256
|
+
/** `/__visual-editor/share/+server.ts`: `export const POST = previewBar.share`. */
|
|
257
|
+
share: (event: RequestEvent) => Promise<Response>;
|
|
258
|
+
/**
|
|
259
|
+
* `/p/[code]/+page.server.ts`: `export const load = previewBar.openLink`. Redirects into
|
|
260
|
+
* preview, or throws 404/503 for `+error.svelte` to render the expired-link page. Preview
|
|
261
|
+
* comes from a signed link-session cookie that expires with the link (never the preview
|
|
262
|
+
* secret), so it needs `previewBar.handle` in `hooks.server.ts`.
|
|
263
|
+
*/
|
|
264
|
+
openLink(event: RequestEvent & {
|
|
265
|
+
params: {
|
|
266
|
+
code?: string;
|
|
267
|
+
};
|
|
268
|
+
}): Promise<never>;
|
|
269
|
+
};
|
|
270
|
+
};
|
|
271
|
+
/**
|
|
272
|
+
* Applies the perspective cookie to `event.locals.sanity.client` in preview, without stega: preview
|
|
273
|
+
* pages read clean strings (and the realtime preview hub, which has no source maps). Add it to
|
|
274
|
+
* `sequence(...)` after `handlePreviewMode`. Typed structurally rather than as Kit's `Handle`,
|
|
275
|
+
* which moved to `@sveltejs/kit/hooks` in Kit 3, so it fits both majors.
|
|
276
|
+
*/
|
|
277
|
+
export declare const handlePreviewPerspective: ({ event, resolve }: {
|
|
278
|
+
event: RequestEvent;
|
|
279
|
+
resolve: (event: RequestEvent) => Response | Promise<Response>;
|
|
280
|
+
}) => Response | Promise<Response>;
|
|
281
|
+
export {};
|