next-sanity 12.0.1 → 12.0.2-canary.1
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/dist/NextStudio.js.map +1 -1
- package/dist/SanityLiveStream.js.map +1 -1
- package/dist/VisualEditing.js +2 -2
- package/dist/VisualEditing.js.map +1 -1
- package/dist/constants.d.ts +0 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/defineLive.d.ts +0 -4
- package/dist/defineLive.d.ts.map +1 -1
- package/dist/draft-mode/index.d.ts +0 -4
- package/dist/draft-mode/index.d.ts.map +1 -1
- package/dist/experimental/client-components/live.d.ts +0 -5
- package/dist/experimental/client-components/live.d.ts.map +1 -1
- package/dist/experimental/client-components/live.js.map +1 -1
- package/dist/experimental/live.d.ts +0 -4
- package/dist/experimental/live.d.ts.map +1 -1
- package/dist/hooks/index.d.ts +0 -12
- package/dist/hooks/index.d.ts.map +1 -1
- package/dist/hooks/index.js.map +1 -1
- package/dist/image/index.d.ts +0 -6
- package/dist/image/index.d.ts.map +1 -1
- package/dist/index.d.ts +0 -4
- package/dist/isCorsOriginError.d.ts +0 -3
- package/dist/isCorsOriginError.d.ts.map +1 -1
- package/dist/live/client-components/live/index.d.ts +0 -4
- package/dist/live/client-components/live/index.d.ts.map +1 -1
- package/dist/live/client-components/live/index.js.map +1 -1
- package/dist/live/client-components/live-stream/index.d.ts +0 -6
- package/dist/live/client-components/live-stream/index.d.ts.map +1 -1
- package/dist/live/server-actions/index.d.ts +0 -3
- package/dist/live/server-actions/index.d.ts.map +1 -1
- package/dist/live/server-actions/index.js +2 -2
- package/dist/live/server-actions/index.js.map +1 -1
- package/dist/live.js.map +1 -1
- package/dist/live.server-only.d.ts +0 -3
- package/dist/live.server-only.d.ts.map +1 -1
- package/dist/studio/client-component/index.d.ts +0 -5
- package/dist/studio/client-component/index.d.ts.map +1 -1
- package/dist/studio/index.d.ts +0 -10
- package/dist/studio/index.d.ts.map +1 -1
- package/dist/visual-editing/client-component/index.d.ts +0 -6
- package/dist/visual-editing/client-component/index.d.ts.map +1 -1
- package/dist/visual-editing/index.d.ts +0 -4
- package/dist/visual-editing/index.d.ts.map +1 -1
- package/dist/visual-editing/server-actions/index.d.ts +0 -2
- package/dist/visual-editing/server-actions/index.d.ts.map +1 -1
- package/dist/visual-editing/server-actions/index.js +1 -1
- package/dist/visual-editing/server-actions/index.js.map +1 -1
- package/dist/webhook/index.d.ts +0 -3
- package/dist/webhook/index.d.ts.map +1 -1
- package/package.json +2 -3
- package/src/experimental/client-components/live.tsx +1 -1
- package/src/live/client-components/live/SanityLive.tsx +1 -1
- package/src/live/client-components/live-stream/SanityLiveStream.tsx +2 -5
- package/src/live/defineLive.tsx +5 -4
- package/src/live/hooks/usePresentationQuery.ts +5 -4
- package/src/live/server-actions/index.ts +2 -2
- package/src/studio/client-component/createHashHistoryForStudio.ts +1 -0
- package/src/visual-editing/client-component/VisualEditing.tsx +5 -2
- package/src/visual-editing/server-actions/index.ts +1 -1
package/dist/NextStudio.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NextStudio.js","names":[],"sources":["../src/studio/client-component/createHashHistoryForStudio.ts","../src/studio/client-component/useIsMounted.ts","../src/studio/client-component/NextStudio.tsx"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"NextStudio.js","names":[],"sources":["../src/studio/client-component/createHashHistoryForStudio.ts","../src/studio/client-component/useIsMounted.ts","../src/studio/client-component/NextStudio.tsx"],"sourcesContent":["// oxlint-disable unbound-method\nimport {createHashHistory, type History, type Listener} from 'history'\n\n/** @internal */\nexport function createHashHistoryForStudio(): History {\n const history = createHashHistory()\n return {\n get action() {\n return history.action\n },\n get location() {\n return history.location\n },\n get createHref() {\n return history.createHref\n },\n get push() {\n return history.push\n },\n get replace() {\n return history.replace\n },\n get go() {\n return history.go\n },\n get back() {\n return history.back\n },\n get forward() {\n return history.forward\n },\n get block() {\n return history.block\n },\n // Overriding listen to workaround a problem where native history provides history.listen(location => void), but the npm package is history.listen(({action, location}) => void)\n listen(listener: Listener) {\n // return history.listen(({ action, location }) => {\n return history.listen(({location}) => {\n // console.debug('history.listen', action, location)\n // @ts-expect-error -- working around a bug? in studio\n listener(location)\n })\n },\n }\n}\n","import {useSyncExternalStore} from 'react'\n\n/** @internal */\nexport function useIsMounted(): boolean {\n return useSyncExternalStore(\n emptySubscribe,\n () => true,\n () => false,\n )\n}\n// eslint-disable-next-line no-empty-function\nconst emptySubscribe = () => () => {}\n","import {useMemo} from 'react'\nimport {Studio, type StudioProps} from 'sanity'\n\nimport {NextStudioLayout} from '../NextStudioLayout'\nimport {NextStudioNoScript} from '../NextStudioNoScript'\nimport {createHashHistoryForStudio} from './createHashHistoryForStudio'\nimport {useIsMounted} from './useIsMounted'\n\n/** @public */\nexport interface NextStudioProps extends StudioProps {\n children?: React.ReactNode\n /**\n * Render the <noscript> tag\n * @defaultValue true\n * @alpha\n */\n unstable__noScript?: boolean\n /**\n * The 'hash' option is new feature that is not yet stable for production, but is available for testing and its API won't change in a breaking way.\n * If 'hash' doesn't work for you, or if you want to use a memory based history, you can use the `unstable_history` prop instead.\n * @alpha\n * @defaultValue 'browser'\n */\n history?: 'browser' | 'hash'\n}\n/**\n * Override how the Studio renders by passing children.\n * This is useful for advanced use cases where you're using StudioProvider and StudioLayout instead of Studio:\n * ```\n * import {StudioProvider, StudioLayout} from 'sanity'\n * import {NextStudio} from 'next-sanity/studio'\n * <NextStudio config={config}>\n * <StudioProvider config={config}>\n * <CustomComponentThatUsesContextFromStudioProvider />\n * <StudioLayout />\n * </StudioProvider>\n * </NextStudio>\n * ```\n * @public\n */\nexport default function NextStudioComponent({\n children,\n config,\n unstable__noScript = true,\n scheme,\n history,\n ...props\n}: NextStudioProps): React.JSX.Element {\n const isMounted = useIsMounted()\n const unstableHistory = useMemo<typeof props.unstable_history>(() => {\n if (props.unstable_history && history) {\n throw new Error('Cannot use both `unstable_history` and `history` props at the same time')\n }\n\n if (isMounted && history === 'hash') {\n return createHashHistoryForStudio()\n }\n return props.unstable_history\n }, [history, isMounted, props.unstable_history])\n\n return (\n <>\n {unstable__noScript && <NextStudioNoScript />}\n <NextStudioLayout>\n {history === 'hash' && !isMounted\n ? null\n : children || (\n <Studio\n config={config}\n scheme={scheme}\n unstable_globalStyles\n {...props}\n unstable_history={unstableHistory}\n />\n )}\n </NextStudioLayout>\n </>\n )\n}\n"],"mappings":";;;;;AAIA,SAAgB,6BAAsC;CACpD,MAAM,UAAU,mBAAmB;AACnC,QAAO;EACL,IAAI,SAAS;AACX,UAAO,QAAQ;;EAEjB,IAAI,WAAW;AACb,UAAO,QAAQ;;EAEjB,IAAI,aAAa;AACf,UAAO,QAAQ;;EAEjB,IAAI,OAAO;AACT,UAAO,QAAQ;;EAEjB,IAAI,UAAU;AACZ,UAAO,QAAQ;;EAEjB,IAAI,KAAK;AACP,UAAO,QAAQ;;EAEjB,IAAI,OAAO;AACT,UAAO,QAAQ;;EAEjB,IAAI,UAAU;AACZ,UAAO,QAAQ;;EAEjB,IAAI,QAAQ;AACV,UAAO,QAAQ;;EAGjB,OAAO,UAAoB;AAEzB,UAAO,QAAQ,QAAQ,EAAC,eAAc;AAGpC,aAAS,SAAS;KAClB;;EAEL;;ACxCH,SAAgB,eAAwB;AACtC,QAAO,qBACL,sBACM,YACA,MACP;;AAGH,MAAM,6BAA6B;AC6BnC,SAAwB,oBAAoB,EAC1C,UACA,QACA,qBAAqB,MACrB,QACA,SACA,GAAG,SACkC;CACrC,MAAM,YAAY,cAAc;CAChC,MAAM,kBAAkB,cAA6C;AACnE,MAAI,MAAM,oBAAoB,QAC5B,OAAM,IAAI,MAAM,0EAA0E;AAG5F,MAAI,aAAa,YAAY,OAC3B,QAAO,4BAA4B;AAErC,SAAO,MAAM;IACZ;EAAC;EAAS;EAAW,MAAM;EAAiB,CAAC;AAEhD,QACE,qBAAA,UAAA,EAAA,UAAA,CACG,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB,EAC7C,oBAAC,kBAAA,EAAA,UACE,YAAY,UAAU,CAAC,YACpB,OACA,YACE,oBAAC,QAAA;EACS;EACA;EACR,uBAAA;EACA,GAAI;EACJ,kBAAkB;GAClB,EAAA,CAES,CAAA,EAAA,CAClB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SanityLiveStream.js","names":["comlink","comlinkSnapshot","children"],"sources":["../src/live/client-components/live-stream/SanityLiveStream.tsx"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"SanityLiveStream.js","names":["comlink","comlinkSnapshot","children"],"sources":["../src/live/client-components/live-stream/SanityLiveStream.tsx"],"sourcesContent":["// oxlint-disable no-unsafe-type-assertion\nimport {\n type ClientPerspective,\n type ContentSourceMap,\n type InitializedClientConfig,\n type QueryParams,\n} from '@sanity/client'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\nimport {dequal} from 'dequal/lite'\nimport {use, useCallback, useEffect, useState, useSyncExternalStore, useEffectEvent} from 'react'\nimport {comlinkListeners, comlink as comlinkSnapshot} from '../../hooks/context'\n\n/**\n * @public\n */\nexport interface SanityLiveStreamProps extends Pick<\n InitializedClientConfig,\n 'projectId' | 'dataset'\n> {\n query: string\n params?: QueryParams\n perspective?: Exclude<ClientPerspective, 'raw'>\n stega?: boolean\n initial: Promise<React.ReactNode>\n children: (result: {\n data: unknown\n sourceMap: ContentSourceMap | null\n tags: string[]\n }) => Promise<React.ReactNode>\n}\n\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * @public\n */\nexport default function SanityLiveStream(props: SanityLiveStreamProps): React.JSX.Element | null {\n const {query, dataset, params = {}, perspective, projectId, stega} = props\n\n const subscribe = useCallback((listener: () => void) => {\n comlinkListeners.add(listener)\n return () => comlinkListeners.delete(listener)\n }, [])\n\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n const [children, setChildren] = useState<React.ReactNode | undefined>(undefined)\n\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n comlink.post('loader/query-listen', {\n projectId: projectId!,\n dataset: dataset!,\n perspective: perspective! as ClientPerspective,\n query,\n params: params,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {\n projectId,\n dataset,\n query,\n params,\n },\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n const {result, resultSourceMap, tags} = event\n const data = stega\n ? stegaEncodeSourceMap(result, resultSourceMap, {enabled: true, studioUrl: '/'})\n : result\n // eslint-disable-next-line no-console\n // console.log('server function streaming is disabled', {\n // startTransition,\n // setPromise,\n // data,\n // resultSourceMap,\n // tags,\n // })\n // console.log('rendering with server action')\n // startTransition(() =>\n // setPromise(\n // props.children({\n // data,\n // sourceMap: resultSourceMap!,\n // tags: tags || [],\n // }) as Promise<React.JSX.Element>,\n // ),\n // )\n console.groupCollapsed('rendering with server action')\n ;(\n props.children({\n data,\n sourceMap: resultSourceMap!,\n tags: tags || [],\n }) as Promise<React.JSX.Element>\n )\n .then(\n (children) => {\n console.log('setChildren(children)')\n // startTransition(() => setChildren(children))\n setChildren(children)\n },\n (reason: unknown) => {\n console.error('rendering with server action: render children error', reason)\n },\n )\n .finally(() => console.groupEnd())\n }\n },\n )\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n if (!comlink || children === undefined) {\n return use(props.initial) as React.JSX.Element\n }\n\n return <>{children}</>\n}\n"],"mappings":";;;;;;AAgCA,MAAM,4BAA4B;AAKlC,SAAwB,iBAAiB,OAAwD;CAC/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AG,UAAA,CAAY"}
|
package/dist/VisualEditing.js
CHANGED
|
@@ -64,7 +64,7 @@ function VisualEditing(props) {
|
|
|
64
64
|
case "push": return routerRef.current.push(removePathPrefix(update.url, basePath));
|
|
65
65
|
case "pop": return routerRef.current.back();
|
|
66
66
|
case "replace": return routerRef.current.replace(removePathPrefix(update.url, basePath));
|
|
67
|
-
default: throw new Error(`Unknown update type:
|
|
67
|
+
default: throw new Error(`Unknown update type`, { cause: update });
|
|
68
68
|
}
|
|
69
69
|
}
|
|
70
70
|
}), [basePath]);
|
|
@@ -73,7 +73,7 @@ function VisualEditing(props) {
|
|
|
73
73
|
useEffect(() => {
|
|
74
74
|
if (navigate) navigate({
|
|
75
75
|
type: "push",
|
|
76
|
-
url: normalizePathTrailingSlash(addPathPrefix(`${pathname}${searchParams?.size ? `?${searchParams}` : ""}`, basePath), trailingSlash)
|
|
76
|
+
url: normalizePathTrailingSlash(addPathPrefix(`${pathname}${searchParams?.size ? `?${searchParams.toString()}` : ""}`, basePath), trailingSlash)
|
|
77
77
|
});
|
|
78
78
|
}, [
|
|
79
79
|
basePath,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VisualEditing.js","names":["VisualEditingComponent"],"sources":["../src/visual-editing/client-component/utils.ts","../src/visual-editing/client-component/VisualEditing.tsx"],"sourcesContent":["/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/path-has-prefix.ts#L10-L17\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nfunction pathHasPrefix(path: string, prefix: string): boolean {\n if (typeof path !== 'string') {\n return false\n }\n\n const {pathname} = parsePath(path)\n return pathname === prefix || pathname.startsWith(`${prefix}/`)\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/parse-path.ts#L6-L22\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nfunction parsePath(path: string): {\n pathname: string\n query: string\n hash: string\n} {\n const hashIndex = path.indexOf('#')\n const queryIndex = path.indexOf('?')\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined) : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n }\n }\n\n return {pathname: path, query: '', hash: ''}\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/add-path-prefix.ts#L3C1-L14C2\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string): string {\n if (!path.startsWith('/') || !prefix) {\n return path\n }\n // If the path is exactly '/' then return just the prefix\n if (path === '/' && prefix) {\n return prefix\n }\n\n const {pathname, query, hash} = parsePath(path)\n return `${prefix}${pathname}${query}${hash}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/remove-path-prefix.ts#L3-L39\n * Given a path and a prefix it will remove the prefix when it exists in the\n * given path. It ensures it matches exactly without containing extra chars\n * and if the prefix is not there it will be noop.\n *\n * @param path The path to remove the prefix from.\n * @param prefix The prefix to be removed.\n */\nexport function removePathPrefix(path: string, prefix: string): string {\n // If the path doesn't start with the prefix we can return it as is. This\n // protects us from situations where the prefix is a substring of the path\n // prefix such as:\n //\n // For prefix: /blog\n //\n // /blog -> true\n // /blog/ -> true\n // /blog/1 -> true\n // /blogging -> false\n // /blogging/ -> false\n // /blogging/1 -> false\n if (!pathHasPrefix(path, prefix)) {\n return path\n }\n\n // Remove the prefix from the path via slicing.\n const withoutPrefix = path.slice(prefix.length)\n\n // If the path without the prefix starts with a `/` we can return it as is.\n if (withoutPrefix.startsWith('/')) {\n return withoutPrefix\n }\n\n // If the path without the prefix doesn't start with a `/` we need to add it\n // back to the path to make sure it's a valid path.\n return `/${withoutPrefix}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/dfe7fc03e2268e7cb765dce6a89e02c831c922d5/packages/next/src/client/normalize-trailing-slash.ts#L16\n * Normalizes the trailing slash of a path according to the `trailingSlash` option\n * in `next.config.js`.\n */\nexport const normalizePathTrailingSlash = (path: string, trailingSlash: boolean): string => {\n const {pathname, query, hash} = parsePath(path)\n if (trailingSlash) {\n if (pathname.endsWith('/')) {\n return `${pathname}${query}${hash}`\n }\n return `${pathname}/${query}${hash}`\n }\n\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/dfe7fc03e2268e7cb765dce6a89e02c831c922d5/packages/next/src/shared/lib/router/utils/remove-trailing-slash.ts#L8\n * Removes the trailing slash for a given route or page path. Preserves the\n * root page. Examples:\n * - `/foo/bar/` -> `/foo/bar`\n * - `/foo/bar` -> `/foo/bar`\n * - `/` -> `/`\n */\nfunction removeTrailingSlash(route: string) {\n return route.replace(/\\/$/, '') || '/'\n}\n","import {\n type HistoryAdapter,\n type HistoryAdapterNavigate,\n type HistoryRefresh,\n VisualEditing as VisualEditingComponent,\n type VisualEditingOptions,\n} from '@sanity/visual-editing/react'\nimport {usePathname, useRouter, useSearchParams} from 'next/navigation'\nimport {revalidateRootLayout} from 'next-sanity/visual-editing/server-actions'\nimport {useCallback, useEffect, useMemo, useRef, useState} from 'react'\n\nimport {addPathPrefix, normalizePathTrailingSlash, removePathPrefix} from './utils'\n\n/**\n * @public\n */\nexport interface VisualEditingProps extends Omit<VisualEditingOptions, 'history'> {\n /**\n * @deprecated The histoy adapter is already implemented\n */\n history?: never\n /**\n * If next.config.ts is configured with a basePath we try to configure it automatically,\n * you can disable this by setting basePath to ''.\n * @example basePath=\"/my-custom-base-path\"\n * @alpha experimental and may change without notice\n * @defaultValue process.env.__NEXT_ROUTER_BASEPATH || ''\n */\n basePath?: string\n /**\n * If next.config.ts is configured with a `trailingSlash` we try to detect it automatically,\n * it can be controlled manually by passing a boolean.\n * @example trailingSlash={true}\n * @alpha experimental and may change without notice\n * @defaultValue Boolean(process.env.__NEXT_TRAILING_SLASH)\n */\n trailingSlash?: boolean\n}\n\nexport default function VisualEditing(props: VisualEditingProps): React.JSX.Element | null {\n const {basePath = '', plugins, components, refresh, trailingSlash = false, zIndex} = props\n\n const router = useRouter()\n const routerRef = useRef(router)\n const [navigate, setNavigate] = useState<HistoryAdapterNavigate | undefined>()\n\n useEffect(() => {\n routerRef.current = router\n }, [router])\n\n const history = useMemo<HistoryAdapter>(\n () => ({\n subscribe: (_navigate) => {\n setNavigate(() => _navigate)\n return () => setNavigate(undefined)\n },\n update: (update) => {\n switch (update.type) {\n case 'push':\n return routerRef.current.push(removePathPrefix(update.url, basePath))\n case 'pop':\n return routerRef.current.back()\n case 'replace':\n return routerRef.current.replace(removePathPrefix(update.url, basePath))\n default:\n throw new Error(`Unknown update type: ${update.type}`)\n }\n },\n }),\n [basePath],\n )\n\n const pathname = usePathname()\n const searchParams = useSearchParams()\n useEffect(() => {\n if (navigate) {\n navigate({\n type: 'push',\n url: normalizePathTrailingSlash(\n addPathPrefix(`${pathname}${searchParams?.size ? `?${searchParams}` : ''}`, basePath),\n trailingSlash,\n ),\n })\n }\n }, [basePath, navigate, pathname, searchParams, trailingSlash])\n\n const handleRefresh = useCallback(\n (payload: HistoryRefresh) => {\n if (refresh) return refresh(payload)\n\n const manualFastRefresh = () => {\n // eslint-disable-next-line no-console\n console.debug(\n 'Live preview is setup, calling router.refresh() to refresh the server components without refetching cached data',\n )\n routerRef.current.refresh()\n return Promise.resolve()\n }\n const manualFallbackRefresh = () => {\n // eslint-disable-next-line no-console\n console.debug(\n 'No loaders in live mode detected, or preview kit setup, revalidating root layout',\n )\n return revalidateRootLayout()\n }\n\n const mutationFallbackRefresh = () => {\n // eslint-disable-next-line no-console\n console.debug(\n 'No loaders in live mode detected, or preview kit setup, revalidating root layout',\n )\n return revalidateRootLayout()\n }\n\n switch (payload.source) {\n case 'manual':\n return payload.livePreviewEnabled ? manualFastRefresh() : manualFallbackRefresh()\n case 'mutation':\n return payload.livePreviewEnabled ? mutationFastRefresh() : mutationFallbackRefresh()\n default:\n throw new Error('Unknown refresh source', {cause: payload})\n }\n },\n [refresh],\n )\n\n return (\n <VisualEditingComponent\n plugins={plugins}\n components={components}\n history={history}\n portal\n refresh={handleRefresh}\n zIndex={zIndex}\n />\n )\n}\n\nfunction mutationFastRefresh(): false {\n // eslint-disable-next-line no-console\n console.debug(\n 'Live preview is setup, mutation is skipped assuming its handled by the live preview',\n )\n return false\n}\n"],"mappings":";;;;;AAQA,SAAS,cAAc,MAAc,QAAyB;AAC5D,KAAI,OAAO,SAAS,SAClB,QAAO;CAGT,MAAM,EAAC,aAAY,UAAU,KAAK;AAClC,QAAO,aAAa,UAAU,SAAS,WAAW,GAAG,OAAO,GAAG;;AASjE,SAAS,UAAU,MAIjB;CACA,MAAM,YAAY,KAAK,QAAQ,IAAI;CACnC,MAAM,aAAa,KAAK,QAAQ,IAAI;CACpC,MAAM,WAAW,aAAa,OAAO,YAAY,KAAK,aAAa;AAEnE,KAAI,YAAY,YAAY,GAC1B,QAAO;EACL,UAAU,KAAK,UAAU,GAAG,WAAW,aAAa,UAAU;EAC9D,OAAO,WAAW,KAAK,UAAU,YAAY,YAAY,KAAK,YAAY,KAAA,EAAU,GAAG;EACvF,MAAM,YAAY,KAAK,KAAK,MAAM,UAAU,GAAG;EAChD;AAGH,QAAO;EAAC,UAAU;EAAM,OAAO;EAAI,MAAM;EAAG;;AAQ9C,SAAgB,cAAc,MAAc,QAA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O,UAAU,QAAQ,QAAQ,iBAAiB,OAAO,KAAK,SAAS,CAAC;IAC1E,QACE,OAAM,IAAI,MAAM,wBAAwB,OAAO,OAAO;;;EAG7D,GACD,CAAC,SAAS,CACX;CAED,MAAM,WAAW,aAAa;CAC9B,MAAM,eAAe,iBAAiB;AACtC,iBAAgB;AACd,MAAI,SACF,UAAS;GACP,MAAM;GACN,KAAK,2BACH,cAAc,GAAG,WAAW,cAAc,OAAO,IAAI,iBAAiB,MAAM,SAAS,EACrF,cACD;GACF,CAAC;IAEH;EAAC;EAAU;EAAU;EAAU;EAAc;EAAc,CAAC;AA0C/D,QACE,oBAACA,iBAAAA;EACU;EACG;EACH;EACT,QAAA;EACA,SA9CkB,aACnB,YAA4B;AAC3B,OAAI,QAAS,QAAO,QAAQ,QAAQ;GAEpC,MAAM,0BAA0B;AAE9B,YAAQ,MACN,kHACD;AACD,cAAU,QAAQ,SAAS;AAC3B,WAAO,QAAQ,SAAS;;GAE1B,MAAM,8BAA8B;AAElC,YAAQ,MACN,mFACD;AACD,WAAO,sBAAsB;;GAG/B,MAAM,gCAAgC;AAEpC,YAAQ,MACN,mFACD;AACD,WAAO,sBAAsB;;AAG/B,WAAQ,QAAQ,QAAhB;IACE,KAAK,SACH,QAAO,QAAQ,qBAAqB,mBAAmB,GAAG,uBAAuB;IACnF,KAAK,WACH,QAAO,QAAQ,qBAAqB,qBAAqB,GAAG,yBAAyB;IACvF,QACE,OAAM,IAAI,MAAM,0BAA0B,EAAC,OAAO,SAAQ,CAAC;;KAGjE,CAAC,QAAQ,CACV;EASW;GACR;;AAIN,SAAS,sBAA6B;AAEpC,SAAQ,MACN,sFACD;AACD,QAAO"}
|
|
1
|
+
{"version":3,"file":"VisualEditing.js","names":["VisualEditingComponent"],"sources":["../src/visual-editing/client-component/utils.ts","../src/visual-editing/client-component/VisualEditing.tsx"],"sourcesContent":["/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/path-has-prefix.ts#L10-L17\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nfunction pathHasPrefix(path: string, prefix: string): boolean {\n if (typeof path !== 'string') {\n return false\n }\n\n const {pathname} = parsePath(path)\n return pathname === prefix || pathname.startsWith(`${prefix}/`)\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/parse-path.ts#L6-L22\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nfunction parsePath(path: string): {\n pathname: string\n query: string\n hash: string\n} {\n const hashIndex = path.indexOf('#')\n const queryIndex = path.indexOf('?')\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined) : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n }\n }\n\n return {pathname: path, query: '', hash: ''}\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/add-path-prefix.ts#L3C1-L14C2\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string): string {\n if (!path.startsWith('/') || !prefix) {\n return path\n }\n // If the path is exactly '/' then return just the prefix\n if (path === '/' && prefix) {\n return prefix\n }\n\n const {pathname, query, hash} = parsePath(path)\n return `${prefix}${pathname}${query}${hash}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/5469e6427b54ab7e9876d4c85b47f9c3afdc5c1f/packages/next/src/shared/lib/router/utils/remove-path-prefix.ts#L3-L39\n * Given a path and a prefix it will remove the prefix when it exists in the\n * given path. It ensures it matches exactly without containing extra chars\n * and if the prefix is not there it will be noop.\n *\n * @param path The path to remove the prefix from.\n * @param prefix The prefix to be removed.\n */\nexport function removePathPrefix(path: string, prefix: string): string {\n // If the path doesn't start with the prefix we can return it as is. This\n // protects us from situations where the prefix is a substring of the path\n // prefix such as:\n //\n // For prefix: /blog\n //\n // /blog -> true\n // /blog/ -> true\n // /blog/1 -> true\n // /blogging -> false\n // /blogging/ -> false\n // /blogging/1 -> false\n if (!pathHasPrefix(path, prefix)) {\n return path\n }\n\n // Remove the prefix from the path via slicing.\n const withoutPrefix = path.slice(prefix.length)\n\n // If the path without the prefix starts with a `/` we can return it as is.\n if (withoutPrefix.startsWith('/')) {\n return withoutPrefix\n }\n\n // If the path without the prefix doesn't start with a `/` we need to add it\n // back to the path to make sure it's a valid path.\n return `/${withoutPrefix}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/dfe7fc03e2268e7cb765dce6a89e02c831c922d5/packages/next/src/client/normalize-trailing-slash.ts#L16\n * Normalizes the trailing slash of a path according to the `trailingSlash` option\n * in `next.config.js`.\n */\nexport const normalizePathTrailingSlash = (path: string, trailingSlash: boolean): string => {\n const {pathname, query, hash} = parsePath(path)\n if (trailingSlash) {\n if (pathname.endsWith('/')) {\n return `${pathname}${query}${hash}`\n }\n return `${pathname}/${query}${hash}`\n }\n\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n}\n\n/**\n * From: https://github.com/vercel/next.js/blob/dfe7fc03e2268e7cb765dce6a89e02c831c922d5/packages/next/src/shared/lib/router/utils/remove-trailing-slash.ts#L8\n * Removes the trailing slash for a given route or page path. Preserves the\n * root page. Examples:\n * - `/foo/bar/` -> `/foo/bar`\n * - `/foo/bar` -> `/foo/bar`\n * - `/` -> `/`\n */\nfunction removeTrailingSlash(route: string) {\n return route.replace(/\\/$/, '') || '/'\n}\n","import {\n type HistoryAdapter,\n type HistoryAdapterNavigate,\n type HistoryRefresh,\n VisualEditing as VisualEditingComponent,\n type VisualEditingOptions,\n} from '@sanity/visual-editing/react'\nimport {usePathname, useRouter, useSearchParams} from 'next/navigation'\nimport {revalidateRootLayout} from 'next-sanity/visual-editing/server-actions'\nimport {useCallback, useEffect, useMemo, useRef, useState} from 'react'\n\nimport {addPathPrefix, normalizePathTrailingSlash, removePathPrefix} from './utils'\n\n/**\n * @public\n */\nexport interface VisualEditingProps extends Omit<VisualEditingOptions, 'history'> {\n /**\n * @deprecated The histoy adapter is already implemented\n */\n history?: never\n /**\n * If next.config.ts is configured with a basePath we try to configure it automatically,\n * you can disable this by setting basePath to ''.\n * @example basePath=\"/my-custom-base-path\"\n * @alpha experimental and may change without notice\n * @defaultValue process.env.__NEXT_ROUTER_BASEPATH || ''\n */\n basePath?: string\n /**\n * If next.config.ts is configured with a `trailingSlash` we try to detect it automatically,\n * it can be controlled manually by passing a boolean.\n * @example trailingSlash={true}\n * @alpha experimental and may change without notice\n * @defaultValue Boolean(process.env.__NEXT_TRAILING_SLASH)\n */\n trailingSlash?: boolean\n}\n\nexport default function VisualEditing(props: VisualEditingProps): React.JSX.Element | null {\n const {basePath = '', plugins, components, refresh, trailingSlash = false, zIndex} = props\n\n const router = useRouter()\n const routerRef = useRef(router)\n const [navigate, setNavigate] = useState<HistoryAdapterNavigate | undefined>()\n\n useEffect(() => {\n routerRef.current = router\n }, [router])\n\n const history = useMemo<HistoryAdapter>(\n () => ({\n subscribe: (_navigate) => {\n setNavigate(() => _navigate)\n return () => setNavigate(undefined)\n },\n update: (update) => {\n switch (update.type) {\n case 'push':\n return routerRef.current.push(removePathPrefix(update.url, basePath))\n case 'pop':\n return routerRef.current.back()\n case 'replace':\n return routerRef.current.replace(removePathPrefix(update.url, basePath))\n default:\n throw new Error(`Unknown update type`, {cause: update})\n }\n },\n }),\n [basePath],\n )\n\n const pathname = usePathname()\n const searchParams = useSearchParams()\n useEffect(() => {\n if (navigate) {\n navigate({\n type: 'push',\n url: normalizePathTrailingSlash(\n addPathPrefix(\n `${pathname}${searchParams?.size ? `?${searchParams.toString()}` : ''}`,\n basePath,\n ),\n trailingSlash,\n ),\n })\n }\n }, [basePath, navigate, pathname, searchParams, trailingSlash])\n\n const handleRefresh = useCallback(\n (payload: HistoryRefresh) => {\n if (refresh) return refresh(payload)\n\n const manualFastRefresh = () => {\n // eslint-disable-next-line no-console\n console.debug(\n 'Live preview is setup, calling router.refresh() to refresh the server components without refetching cached data',\n )\n routerRef.current.refresh()\n return Promise.resolve()\n }\n const manualFallbackRefresh = () => {\n // eslint-disable-next-line no-console\n console.debug(\n 'No loaders in live mode detected, or preview kit setup, revalidating root layout',\n )\n return revalidateRootLayout()\n }\n\n const mutationFallbackRefresh = () => {\n // eslint-disable-next-line no-console\n console.debug(\n 'No loaders in live mode detected, or preview kit setup, revalidating root layout',\n )\n return revalidateRootLayout()\n }\n\n switch (payload.source) {\n case 'manual':\n return payload.livePreviewEnabled ? manualFastRefresh() : manualFallbackRefresh()\n case 'mutation':\n return payload.livePreviewEnabled ? mutationFastRefresh() : mutationFallbackRefresh()\n default:\n throw new Error('Unknown refresh source', {cause: payload})\n }\n },\n [refresh],\n )\n\n return (\n <VisualEditingComponent\n plugins={plugins}\n components={components}\n history={history}\n portal\n refresh={handleRefresh}\n zIndex={zIndex}\n />\n )\n}\n\nfunction mutationFastRefresh(): false {\n // eslint-disable-next-line no-console\n console.debug(\n 'Live preview is setup, mutation is skipped assuming its handled by the live preview',\n )\n return false\n}\n"],"mappings":";;;;;AAQA,SAAS,cAAc,MAAc,QAAyB;AAC5D,KAAI,OAAO,SAAS,SAClB,QAAO;CAGT,MAAM,EAAC,aAAY,UAAU,KAAK;AAClC,QAAO,aAAa,UAAU,SAAS,WAAW,GAAG,OAAO,GAAG;;AASjE,SAAS,UAAU,MAIjB;CACA,MAAM,YAAY,KAAK,QAAQ,IAAI;CACnC,MAAM,aAAa,KAAK,QAAQ,IAAI;CAC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AG,yBAAyB;IACvF,QACE,OAAM,IAAI,MAAM,0BAA0B,EAAC,OAAO,SAAQ,CAAC;;KAGjE,CAAC,QAAQ,CACV;EASW;GACR;;AAIN,SAAS,sBAA6B;AAEpC,SAAQ,MACN,sFACD;AACD,QAAO"}
|
package/dist/constants.d.ts
CHANGED
package/dist/constants.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.ts","names":[],"sources":["../src/experimental/constants.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"constants.d.ts","names":[],"sources":["../src/experimental/constants.ts"],"sourcesContent":[],"mappings":"AAAa,cAAA,yBAAA,GAAA,KAAA;AACA,cAAA,qBAAA,GAAA,KAAA"}
|
package/dist/defineLive.d.ts
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
import { ClientPerspective, ClientReturn, ContentSourceMap, LiveEventGoAway, QueryParams, SanityClient, SyncTag } from "@sanity/client";
|
|
2
|
-
|
|
3
|
-
//#region src/live/defineLive.d.ts
|
|
4
|
-
|
|
5
2
|
/**
|
|
6
3
|
* @public
|
|
7
4
|
*/
|
|
@@ -174,6 +171,5 @@ declare function defineLive(config: DefineSanityLiveOptions): {
|
|
|
174
171
|
*/
|
|
175
172
|
SanityLiveStream: DefinedSanityLiveStreamType;
|
|
176
173
|
};
|
|
177
|
-
//#endregion
|
|
178
174
|
export { defineLive as a, DefinedSanityLiveStreamType as i, DefinedSanityFetchType as n, DefinedSanityLiveProps as r, DefineSanityLiveOptions as t };
|
|
179
175
|
//# sourceMappingURL=defineLive.d.ts.map
|
package/dist/defineLive.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defineLive.d.ts","names":[],"sources":["../src/live/defineLive.tsx"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"defineLive.d.ts","names":[],"sources":["../src/live/defineLive.tsx"],"sourcesContent":[],"mappings":";;AAkBA;;AAEW,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/
|
|
@@ -39,6 +36,5 @@ interface EnableDraftMode {
|
|
|
39
36
|
* @public
|
|
40
37
|
*/
|
|
41
38
|
declare function defineEnableDraftMode(options: DefineEnableDraftModeOptions): EnableDraftMode;
|
|
42
|
-
//#endregion
|
|
43
39
|
export { DefineEnableDraftModeOptions, EnableDraftMode, defineEnableDraftMode };
|
|
44
40
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/draft-mode/define-enable-draft-mode.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/draft-mode/define-enable-draft-mode.ts"],"sourcesContent":[],"mappings":";;AASA;AAcA;AACiB,UAfA,4BAAA,CAeA;EAAoB,MAAA,EAd3B,YAc2B;EAAR;;AAoB7B;;;;;;;;;UArBiB,eAAA;iBACA,YAAY,QAAQ;;;;;;;;;;;;;;;;;;;iBAoBrB,qBAAA,UAA+B,+BAA+B"}
|
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
import { n as PUBLISHED_SYNC_TAG_PREFIX, t as DRAFT_SYNC_TAG_PREFIX } from "../../constants.js";
|
|
2
2
|
import { ClientPerspective, InitializedClientConfig, LiveEventGoAway, SyncTag } from "@sanity/client";
|
|
3
|
-
|
|
4
|
-
//#region src/experimental/types.d.ts
|
|
5
3
|
interface SanityClientConfig extends Pick<InitializedClientConfig, "projectId" | "dataset" | "apiHost" | "apiVersion" | "useProjectHostname" | "token" | "requestTagPrefix"> {}
|
|
6
|
-
//#endregion
|
|
7
|
-
//#region src/experimental/client-components/live.d.ts
|
|
8
4
|
/**
|
|
9
5
|
* @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.
|
|
10
6
|
*/
|
|
@@ -29,6 +25,5 @@ interface SanityLiveProps {
|
|
|
29
25
|
* @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.
|
|
30
26
|
*/
|
|
31
27
|
declare function SanityLive(props: SanityLiveProps): React.JSX.Element | null;
|
|
32
|
-
//#endregion
|
|
33
28
|
export { SanityLiveProps, SanityLive as default };
|
|
34
29
|
//# sourceMappingURL=live.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.d.ts","names":[],"sources":["../../../src/experimental/types.ts","../../../src/experimental/client-components/live.tsx"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"live.d.ts","names":[],"sources":["../../../src/experimental/types.ts","../../../src/experimental/client-components/live.tsx"],"sourcesContent":[],"mappings":";;UAEiB,kBAAA,SAA2B,KAC1C;AADF;;ACgCA;AACU,UADO,eAAA,CACP;EAYW,MAAA,EAZX,kBAYW;EAED,gBAAA,EAAA,OAAA;EAAmC,cAAA,CAAA,EAAA,OAAA;EAAwB,cAAA,CAAA,EAAA,OAAA;EACxE,kBAAA,CAAA,EAAA,OAAA;EACsC,UAAA,EAAA,MAAA,GAAA,SAAA;EAAR;;;;;;qBAJhB;uCAED,mCAAmC,wBAAwB,gBACxE;qCAC8B,QAAQ;;;;;iBAsCrB,UAAA,QAAkB,kBAAkB,KAAA,CAAM,GAAA,CAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.js","names":[],"sources":["../../../src/experimental/client-components/live.tsx"],"sourcesContent":["'use client'\n\nimport {\n createClient,\n type ClientPerspective,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent} from 'react'\nimport {setEnvironment, setPerspective} from '../../live/hooks/context'\nimport {isCorsOriginError} from '../../isCorsOriginError'\nimport type {SanityClientConfig} from '../types'\nimport {sanitizePerspective} from '../../live/utils'\nimport {PUBLISHED_SYNC_TAG_PREFIX, type DRAFT_SYNC_TAG_PREFIX} from '../constants'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('../../live/client-components/live/RefreshOnMount'), {\n ssr: false,\n})\nconst RefreshOnFocus = dynamic(() => import('../../live/client-components/live/RefreshOnFocus'), {\n ssr: false,\n})\nconst RefreshOnReconnect = dynamic(\n () => import('../../live/client-components/live/RefreshOnReconnect'),\n {ssr: false},\n)\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface SanityLiveProps {\n config: SanityClientConfig\n draftModeEnabled: boolean\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n requestTag: string | undefined\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n revalidateSyncTags: (\n tags: `${typeof PUBLISHED_SYNC_TAG_PREFIX | typeof DRAFT_SYNC_TAG_PREFIX}${SyncTag}`[],\n ) => Promise<void | 'refresh'>\n resolveDraftModePerspective: () => Promise<ClientPerspective>\n}\n\nfunction handleError(error: unknown) {\n /* eslint-disable no-console */\n if (isCorsOriginError(error)) {\n console.warn(\n `Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`,\n error.addOriginUrl && `Add it here:`,\n error.addOriginUrl?.toString(),\n )\n } else {\n console.error(error)\n }\n /* eslint-enable no-console */\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n /* eslint-disable no-console */\n if (intervalOnGoAway) {\n console.warn(\n 'Sanity Live connection closed, switching to long polling set to a interval of',\n intervalOnGoAway / 1000,\n 'seconds and the server gave this reason:',\n event.reason,\n )\n } else {\n console.error(\n 'Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:',\n event.reason,\n )\n }\n /* eslint-enable no-console */\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport default function SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n draftModeEnabled,\n refreshOnMount = false,\n refreshOnFocus = draftModeEnabled\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag = 'next-loader.live',\n onError = handleError,\n onGoAway = handleOnGoAway,\n revalidateSyncTags,\n resolveDraftModePerspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n const [longPollingInterval, setLongPollingInterval] = useState<number | false>(false)\n const [resolvedInitialPerspective, setResolvedInitialPerspective] = useState(false)\n\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // eslint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : draftModeEnabled\n ? 'automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool.'\n : 'automatic revalidation of published content',\n )\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n setLongPollingInterval(false)\n } else if (event.type === 'message') {\n revalidateSyncTags(\n event.tags.map((tag: SyncTag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}` as const),\n ).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(intervalOnGoAway)\n }\n })\n // @TODO previous version that handle both published and draft events\n // useEffect(() => {\n // const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n // next: handleLiveEvent,\n // error: (err: unknown) => {\n // onError(err)\n // },\n // })\n // return () => subscription.unsubscribe()\n // }, [client.live, onError, requestTag, token])\n useEffect(() => {\n const subscription = client.live.events({tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * Handle live events for drafts differently, only use it to trigger refreshes, don't expire the cache\n */\n const handleLiveDraftEvent = useEffectEvent((event: LiveEvent) => {\n if (event.type === 'message') {\n // Just refresh, due to cache bypass in draft mode it'll fetch fresh content (though we wish cache worked as in production)\n // @TODO if draft content is published, then this extra refresh is unnecessary, it's tricky to check since `event.id` are different on the two EventSource connections\n router.refresh()\n }\n })\n useEffect(() => {\n if (!token) return\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n next: handleLiveDraftEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (resolvedInitialPerspective) return undefined\n\n if (!draftModeEnabled) {\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n return undefined\n }\n\n const controller = new AbortController()\n resolveDraftModePerspective()\n .then((perspective) => {\n if (controller.signal.aborted) return\n setResolvedInitialPerspective(true)\n setPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n .catch((err) => {\n if (controller.signal.aborted) return\n console.error('Failed to resolve draft mode perspective', err)\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n })\n return () => controller.abort()\n }, [draftModeEnabled, resolveDraftModePerspective, resolvedInitialPerspective])\n\n const [loadComlink, setLoadComlink] = useState(false)\n /**\n * 3. Notify what environment we're in, when in Draft Mode\n */\n useEffect(() => {\n // If we might be in Presentation Tool, then skip detecting here as it's handled later\n if (isMaybePresentation()) return\n\n // If we're definitely not in Presentation Tool, then we can set the environment as stand-alone live preview\n // if we have both a browser token, and draft mode is enabled\n if (draftModeEnabled && token) {\n setEnvironment('live')\n return\n }\n // If we're in draft mode, but don't have a browser token, then we're in static mode\n // which means that published content is still live, but draft changes likely need manual refresh\n if (draftModeEnabled) {\n setEnvironment('static')\n return\n }\n\n // Fallback to `unknown` otherwise, as we simply don't know how it's setup\n setEnvironment('unknown')\n return\n }, [draftModeEnabled, token])\n\n /**\n * 4. If Presentation Tool is detected, load up the comlink and integrate with it\n */\n useEffect(() => {\n if (!isMaybePresentation()) return\n const controller = new AbortController()\n // Wait for a while to see if Presentation Tool is detected, before assuming the env to be stand-alone live preview\n const timeout = setTimeout(() => setEnvironment('live'), 3_000)\n window.addEventListener(\n 'message',\n ({data}: MessageEvent<unknown>) => {\n if (\n data &&\n typeof data === 'object' &&\n 'domain' in data &&\n data.domain === 'sanity/channels' &&\n 'from' in data &&\n data.from === 'presentation'\n ) {\n clearTimeout(timeout)\n setEnvironment(isMaybePreviewWindow() ? 'presentation-window' : 'presentation-iframe')\n setLoadComlink(true)\n controller.abort()\n }\n },\n {signal: controller.signal},\n )\n return () => {\n clearTimeout(timeout)\n controller.abort()\n }\n }, [])\n\n /**\n * 5. Warn if draft mode is being disabled\n * @TODO move logic into PresentationComlink, or maybe VisualEditing?\n */\n const draftModeEnabledWarnRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n useEffect(() => {\n if (!draftModeEnabled) return\n clearTimeout(draftModeEnabledWarnRef.current)\n return () => {\n draftModeEnabledWarnRef.current = setTimeout(() => {\n // eslint-disable-next-line no-console\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\n\n return (\n <>\n {draftModeEnabled && loadComlink && resolvedInitialPerspective && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n draftModeEnabled={draftModeEnabled}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,sBAAsB,cAAc,OAAO,iCAA0B,EAAC,KAAK,OAAM,CAAC;AACxF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,qBAAqB,cACnB,OAAO,gCACb,EAAC,KAAK,OAAM,CACb;AAyBD,SAAS,YAAY,OAAgB;AAEnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E,OAAO,OAAO,yEAC5F,MAAM,gBAAgB,gBACtB,MAAM,cAAc,UAAU,CAC/B;KAED,SAAQ,MAAM,MAAM;;AAKxB,SAAS,eAAe,OAAwB,kBAAkC;AAEhF,KAAI,iBACF,SAAQ,KACN,iFACA,mBAAmB,KACnB,4CACA,MAAM,OACP;KAED,SAAQ,MACN,mGACA,MAAM,OACP;;AAQL,SAAwB,WAAW,OAAkD;CACnF,MAAM,EACJ,QACA,kBACA,iBAAiB,OACjB,iBAAiB,mBACb,QACA,OAAO,WAAW,cAChB,OACA,OAAO,SAAS,OAAO,KAC7B,qBAAqB,MACrB,mBAAmB,KACnB,aAAa,oBACb,UAAU,aACV,WAAW,gBACX,oBACA,gCACE;CACJ,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,OAAO,qBACzE;CAEF,MAAM,SAAS,cAEX,aAAa;EACX;EACA;EACA;EACA;EACA;EACA,2BAA2B;EAC3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AAU;AAC5F,iBAAgB;AACd,MAAI,CAAC,iBAAkB;AACvB,eAAa,wBAAwB,QAAQ;AAC7C,eAAa;AACX,2BAAwB,UAAU,iBAAiB;AAEjD,YAAQ,KAAK,iEAAiE;KAC9E;;IAEH,CAAC,iBAAiB,CAAC;AAKtB,iBAAgB;AACd,MAAI,CAAC,oBAAqB;EAC1B,MAAM,WAAW,kBAAkB,OAAO,SAAS,EAAE,oBAAoB;AACzE,eAAa,cAAc,SAAS;IACnC,CAAC,qBAAqB,OAAO,CAAC;AAEjC,QACE,qBAAA,UAAA,EAAA,UAAA;EACG,oBAAoB,eAAe,8BAClC,oBAAC,qBAAA;GACY;GACF;GACS;IAClB;EAEH,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB;KACjE"}
|
|
1
|
+
{"version":3,"file":"live.js","names":[],"sources":["../../../src/experimental/client-components/live.tsx"],"sourcesContent":["'use client'\n\nimport {\n createClient,\n type ClientPerspective,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useRef, useState, useEffectEvent} from 'react'\nimport {setEnvironment, setPerspective} from '../../live/hooks/context'\nimport {isCorsOriginError} from '../../isCorsOriginError'\nimport type {SanityClientConfig} from '../types'\nimport {sanitizePerspective} from '../../live/utils'\nimport {PUBLISHED_SYNC_TAG_PREFIX, type DRAFT_SYNC_TAG_PREFIX} from '../constants'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'), {ssr: false})\nconst RefreshOnMount = dynamic(() => import('../../live/client-components/live/RefreshOnMount'), {\n ssr: false,\n})\nconst RefreshOnFocus = dynamic(() => import('../../live/client-components/live/RefreshOnFocus'), {\n ssr: false,\n})\nconst RefreshOnReconnect = dynamic(\n () => import('../../live/client-components/live/RefreshOnReconnect'),\n {ssr: false},\n)\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport interface SanityLiveProps {\n config: SanityClientConfig\n draftModeEnabled: boolean\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n requestTag: string | undefined\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n revalidateSyncTags: (\n tags: `${typeof PUBLISHED_SYNC_TAG_PREFIX | typeof DRAFT_SYNC_TAG_PREFIX}${SyncTag}`[],\n ) => Promise<void | 'refresh'>\n resolveDraftModePerspective: () => Promise<ClientPerspective>\n}\n\nfunction handleError(error: unknown) {\n /* eslint-disable no-console */\n if (isCorsOriginError(error)) {\n console.warn(\n `Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`,\n error.addOriginUrl && `Add it here:`,\n error.addOriginUrl?.toString(),\n )\n } else {\n console.error(error)\n }\n /* eslint-enable no-console */\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n /* eslint-disable no-console */\n if (intervalOnGoAway) {\n console.warn(\n 'Sanity Live connection closed, switching to long polling set to a interval of',\n intervalOnGoAway / 1000,\n 'seconds and the server gave this reason:',\n event.reason,\n )\n } else {\n console.error(\n 'Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:',\n event.reason,\n )\n }\n /* eslint-enable no-console */\n}\n\n/**\n * @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.\n */\nexport default function SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n draftModeEnabled,\n refreshOnMount = false,\n refreshOnFocus = draftModeEnabled\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag = 'next-loader.live',\n onError = handleError,\n onGoAway = handleOnGoAway,\n revalidateSyncTags,\n resolveDraftModePerspective,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n const [longPollingInterval, setLongPollingInterval] = useState<number | false>(false)\n const [resolvedInitialPerspective, setResolvedInitialPerspective] = useState(false)\n\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // eslint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : draftModeEnabled\n ? 'automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool.'\n : 'automatic revalidation of published content',\n )\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n setLongPollingInterval(false)\n } else if (event.type === 'message') {\n void revalidateSyncTags(\n event.tags.map((tag: SyncTag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}` as const),\n ).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(intervalOnGoAway)\n }\n })\n // @TODO previous version that handle both published and draft events\n // useEffect(() => {\n // const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n // next: handleLiveEvent,\n // error: (err: unknown) => {\n // onError(err)\n // },\n // })\n // return () => subscription.unsubscribe()\n // }, [client.live, onError, requestTag, token])\n useEffect(() => {\n const subscription = client.live.events({tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * Handle live events for drafts differently, only use it to trigger refreshes, don't expire the cache\n */\n const handleLiveDraftEvent = useEffectEvent((event: LiveEvent) => {\n if (event.type === 'message') {\n // Just refresh, due to cache bypass in draft mode it'll fetch fresh content (though we wish cache worked as in production)\n // @TODO if draft content is published, then this extra refresh is unnecessary, it's tricky to check since `event.id` are different on the two EventSource connections\n router.refresh()\n }\n })\n useEffect(() => {\n if (!token) return\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n next: handleLiveDraftEvent,\n error: (err: unknown) => {\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n /**\n * 2. Notify what perspective we're in, when in Draft Mode\n */\n useEffect(() => {\n if (resolvedInitialPerspective) return undefined\n\n if (!draftModeEnabled) {\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n return undefined\n }\n\n const controller = new AbortController()\n resolveDraftModePerspective()\n .then((perspective) => {\n if (controller.signal.aborted) return\n setResolvedInitialPerspective(true)\n setPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n .catch((err) => {\n if (controller.signal.aborted) return\n console.error('Failed to resolve draft mode perspective', err)\n setResolvedInitialPerspective(true)\n setPerspective('unknown')\n })\n return () => controller.abort()\n }, [draftModeEnabled, resolveDraftModePerspective, resolvedInitialPerspective])\n\n const [loadComlink, setLoadComlink] = useState(false)\n /**\n * 3. Notify what environment we're in, when in Draft Mode\n */\n useEffect(() => {\n // If we might be in Presentation Tool, then skip detecting here as it's handled later\n if (isMaybePresentation()) return\n\n // If we're definitely not in Presentation Tool, then we can set the environment as stand-alone live preview\n // if we have both a browser token, and draft mode is enabled\n if (draftModeEnabled && token) {\n setEnvironment('live')\n return\n }\n // If we're in draft mode, but don't have a browser token, then we're in static mode\n // which means that published content is still live, but draft changes likely need manual refresh\n if (draftModeEnabled) {\n setEnvironment('static')\n return\n }\n\n // Fallback to `unknown` otherwise, as we simply don't know how it's setup\n setEnvironment('unknown')\n return\n }, [draftModeEnabled, token])\n\n /**\n * 4. If Presentation Tool is detected, load up the comlink and integrate with it\n */\n useEffect(() => {\n if (!isMaybePresentation()) return\n const controller = new AbortController()\n // Wait for a while to see if Presentation Tool is detected, before assuming the env to be stand-alone live preview\n const timeout = setTimeout(() => setEnvironment('live'), 3_000)\n window.addEventListener(\n 'message',\n ({data}: MessageEvent<unknown>) => {\n if (\n data &&\n typeof data === 'object' &&\n 'domain' in data &&\n data.domain === 'sanity/channels' &&\n 'from' in data &&\n data.from === 'presentation'\n ) {\n clearTimeout(timeout)\n setEnvironment(isMaybePreviewWindow() ? 'presentation-window' : 'presentation-iframe')\n setLoadComlink(true)\n controller.abort()\n }\n },\n {signal: controller.signal},\n )\n return () => {\n clearTimeout(timeout)\n controller.abort()\n }\n }, [])\n\n /**\n * 5. Warn if draft mode is being disabled\n * @TODO move logic into PresentationComlink, or maybe VisualEditing?\n */\n const draftModeEnabledWarnRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n useEffect(() => {\n if (!draftModeEnabled) return\n clearTimeout(draftModeEnabledWarnRef.current)\n return () => {\n draftModeEnabledWarnRef.current = setTimeout(() => {\n // eslint-disable-next-line no-console\n console.warn('Sanity Live: Draft mode was enabled, but is now being disabled')\n })\n }\n }, [draftModeEnabled])\n\n /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\n\n return (\n <>\n {draftModeEnabled && loadComlink && resolvedInitialPerspective && (\n <PresentationComlink\n projectId={projectId!}\n dataset={dataset!}\n draftModeEnabled={draftModeEnabled}\n />\n )}\n {!draftModeEnabled && refreshOnMount && <RefreshOnMount />}\n {!draftModeEnabled && refreshOnFocus && <RefreshOnFocus />}\n {!draftModeEnabled && refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,sBAAsB,cAAc,OAAO,iCAA0B,EAAC,KAAK,OAAM,CAAC;AACxF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,iBAAiB,cAAc,OAAO,4BAAqD,EAC/F,KAAK,OACN,CAAC;AACF,MAAM,qBAAqB,cACnB,OAAO,gCACb,EAAC,KAAK,OAAM,CACb;AAyBD,SAAS,YAAY,OAAgB;AAEnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E,OAAO,OAAO,yEAC5F,MAAM,gBAAgB,gBACtB,MAAM,cAAc,UAAU,CAC/B;KAED,SAAQ,MAAM,MAAM;;AAKxB,SAAS,eAAe,OAAwB,kBAAkC;AAEhF,KAAI,iBACF,SAAQ,KACN,iFACA,mBAAmB,KACnB,4CACA,MAAM,OACP;KAED,SAAQ,MACN,mGACA,MAAM,OACP;;AAQL,SAAwB,WAAW,OAAkD;CACnF,MAAM,EACJ,QACA,kBACA,iBAAiB,OACjB,iBAAiB,mBACb,QACA,OAAO,WAAW,cAChB,OACA,OAAO,SAAS,OAAO,KAC7B,qBAAqB,MACrB,mBAAmB,KACnB,aAAa,oBACb,UAAU,aACV,WAAW,gBACX,oBACA,gCACE;CACJ,MAAM,EAAC,WAAW,SAAS,SAAS,YAAY,oBAAoB,OAAO,qBACzE;CAEF,MAAM,SAAS,cAEX,aAAa;EACX;EACA;EACA;EACA;EACA;EACA,2BAA2B;EAC3B;EACA,QAAQ;EACR;EACD,CAAC,EACJ;EAAC;EAAS;EAAY;EAAS;EAAW;EAAkB;EAAO;EAAmB,CACvF;CACD,MAAM,CAAC,qBAAqB,0BAA0B,SAAyB,MAAM;CACrF,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C9E;;IAEH,CAAC,iBAAiB,CAAC;AAKtB,iBAAgB;AACd,MAAI,CAAC,oBAAqB;EAC1B,MAAM,WAAW,kBAAkB,OAAO,SAAS,EAAE,oBAAoB;AACzE,eAAa,cAAc,SAAS;IACnC,CAAC,qBAAqB,OAAO,CAAC;AAEjC,QACE,qBAAA,UAAA,EAAA,UAAA;EACG,oBAAoB,eAAe,8BAClC,oBAAC,qBAAA;GACY;GACF;GACS;IAClB;EAEH,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,kBAAkB,oBAAC,gBAAA,EAAA,CAAiB;EACzD,CAAC,oBAAoB,sBAAsB,oBAAC,oBAAA,EAAA,CAAqB;KACjE"}
|
|
@@ -2,9 +2,6 @@ import { n as PUBLISHED_SYNC_TAG_PREFIX, t as DRAFT_SYNC_TAG_PREFIX } from "../c
|
|
|
2
2
|
import { cookies } from "next/headers";
|
|
3
3
|
import "server-only";
|
|
4
4
|
import { ClientPerspective, ClientReturn, ContentSourceMap, LiveEventGoAway, QueryParams, SanityClient, SyncTag } from "next-sanity";
|
|
5
|
-
|
|
6
|
-
//#region src/experimental/live.d.ts
|
|
7
|
-
|
|
8
5
|
/**
|
|
9
6
|
* @alpha CAUTION: This API does not follow semver and could have breaking changes in future minor releases.
|
|
10
7
|
*/
|
|
@@ -141,6 +138,5 @@ declare function defineLive(config: DefineSanityLiveOptions): {
|
|
|
141
138
|
*/
|
|
142
139
|
SanityLive: React.ComponentType<DefinedSanityLiveProps>;
|
|
143
140
|
};
|
|
144
|
-
//#endregion
|
|
145
141
|
export { DefineSanityLiveOptions, DefinedSanityFetchType, DefinedSanityLiveProps, SanityFetchOptions, defineLive, resolvePerspectiveFromCookies };
|
|
146
142
|
//# sourceMappingURL=live.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.d.ts","names":[],"sources":["../../src/experimental/live.tsx"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"live.d.ts","names":[],"sources":["../../src/experimental/live.tsx"],"sourcesContent":[],"mappings":";;;;;AA2BA;;AAGqC,iBAHf,6BAAA,CAGe;EAAA,OAAA,EAF1B;CAE0B,EAAA;EAAlB,OAAA,EAAR,OAAQ,CAAA,UAAA,CAAA,OAAkB,OAAlB,CAAA,CAAA;CAAR,CAAA,EACP,OADO,CACC,OADD,CACS,iBADT,EAAA,KAAA,CAAA,CAAA;;;;AACP,UAoEa,kBApEb,CAAA,oBAAA,MAAA,CAAA,CAAA;EAoEJ,KAAiB,EACR,WADQ;EACR,MAAA,CAAA,EACE,WADF;EACE;;;EAIK,WAAA,CAAA,EAAA,OAAA,CAAQ,iBAAR,EAAA,KAAA,CAAA;EAqBhB;;;;EAGQ,KAAA,CAAA,EAAA,OAAA;EAKK;;;AAUb;;EAoDoB,UAAA,CAAA,EAAA,MAAA;EAAmC;;;EAUT,IAAA,CAAA,EAAA,MAAA,EAAA;;;AAM9C;AAoBA;AAAmC,KA1GvB,sBAAA,GA0GuB,CAAA,0BAAA,MAAA,CAAA,CAAA,OAAA,EAzGxB,kBAyGwB,CAzGL,WAyGK,CAAA,EAAA,GAxG9B,OAwG8B,CAAA;EAIpB,IAAA,EA3GP,YA2GO,CA3GM,WA2GN,EAAA,OAAA,CAAA;EAImB;;;;aA1GrB;;;;;;;;;UAUI,sBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA4CI;;;;;wCAQD,mCAAmC,wBAAwB,gBACxE;;;;sCAS+B,QAAQ;;;;;UAM7B,uBAAA;;;;UAIP;;;;;;;;;;;;;;;iBAgBM,UAAA,SAAmB;;;;eAIpB;;;;cAID,KAAA,CAAM,cAAc"}
|
package/dist/hooks/index.d.ts
CHANGED
|
@@ -2,9 +2,6 @@ import "@sanity/comlink";
|
|
|
2
2
|
import "@sanity/presentation-comlink";
|
|
3
3
|
import { useOptimistic } from "@sanity/visual-editing/react";
|
|
4
4
|
import { ClientPerspective, ClientPerspective as ClientPerspective$1, ClientReturn, ContentSourceMap, QueryParams } from "@sanity/client";
|
|
5
|
-
|
|
6
|
-
//#region src/live/hooks/context.d.ts
|
|
7
|
-
|
|
8
5
|
/**
|
|
9
6
|
* The Sanity Client perspective used when fetching data in Draft Mode, in the `sanityFetch` calls
|
|
10
7
|
* used by React Server Components on the page. Note that some of them might set the `perspective` to a different value.
|
|
@@ -17,8 +14,6 @@ type DraftPerspective = "checking" | "unknown" | ClientPerspective$1;
|
|
|
17
14
|
* @public
|
|
18
15
|
*/
|
|
19
16
|
type DraftEnvironment = "checking" | "presentation-iframe" | "presentation-window" | "live" | "static" | "unknown";
|
|
20
|
-
//#endregion
|
|
21
|
-
//#region src/live/hooks/useDraftMode.d.ts
|
|
22
17
|
/**
|
|
23
18
|
* Reports the current draft mode environment.
|
|
24
19
|
* Use it to determine how to adapt the UI based on wether:
|
|
@@ -37,8 +32,6 @@ declare function useDraftModeEnvironment(): DraftEnvironment;
|
|
|
37
32
|
* @public
|
|
38
33
|
*/
|
|
39
34
|
declare function useDraftModePerspective(): DraftPerspective;
|
|
40
|
-
//#endregion
|
|
41
|
-
//#region src/live/hooks/useIsPresentationTool.d.ts
|
|
42
35
|
/**
|
|
43
36
|
* Detects if the application is being previewed inside Sanity Presentation Tool.
|
|
44
37
|
* Presentation Tool can open the application in an iframe, or in a new window.
|
|
@@ -50,8 +43,6 @@ declare function useDraftModePerspective(): DraftPerspective;
|
|
|
50
43
|
* @public
|
|
51
44
|
*/
|
|
52
45
|
declare function useIsPresentationTool(): boolean | null;
|
|
53
|
-
//#endregion
|
|
54
|
-
//#region src/live/hooks/useIsLivePreview.d.ts
|
|
55
46
|
/**
|
|
56
47
|
* Detects if the application is considered to be in a "Live Preview" mode.
|
|
57
48
|
* Live Preview means that the application is either:
|
|
@@ -68,8 +59,6 @@ declare function useIsPresentationTool(): boolean | null;
|
|
|
68
59
|
* @public
|
|
69
60
|
*/
|
|
70
61
|
declare function useIsLivePreview(): boolean | null;
|
|
71
|
-
//#endregion
|
|
72
|
-
//#region src/live/hooks/usePresentationQuery.d.ts
|
|
73
62
|
/** @alpha */
|
|
74
63
|
type UsePresentationQueryReturnsInactive = {
|
|
75
64
|
data: null;
|
|
@@ -96,6 +85,5 @@ declare function usePresentationQuery<const QueryString extends string>(props: {
|
|
|
96
85
|
params?: QueryParams | Promise<QueryParams>;
|
|
97
86
|
stega?: boolean;
|
|
98
87
|
}): UsePresentationQueryReturns<QueryString>;
|
|
99
|
-
//#endregion
|
|
100
88
|
export { type ClientPerspective, type DraftEnvironment, type DraftPerspective, UsePresentationQueryReturns, UsePresentationQueryReturnsActive, UsePresentationQueryReturnsInactive, useDraftModeEnvironment, useDraftModePerspective, useIsLivePreview, useIsPresentationTool, useOptimistic, usePresentationQuery };
|
|
101
89
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["perspectiveListeners: Set<() => void>","perspective: DraftPerspective","environmentListeners: Set<() => void>","environment: DraftEnvironment","comlinkListeners: Set<() => void>","comlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null","comlinkProjectId: string | null","comlinkDataset: string | null"],"sources":["../../src/live/hooks/context.ts","../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["perspectiveListeners: Set<() => void>","perspective: DraftPerspective","environmentListeners: Set<() => void>","environment: DraftEnvironment","comlinkListeners: Set<() => void>","comlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null","comlinkProjectId: string | null","comlinkDataset: string | null"],"sources":["../../src/live/hooks/context.ts","../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":[],"mappings":";;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comlinkSnapshot","perspective"],"sources":["../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":["import {useCallback, useSyncExternalStore} from 'react'\nimport {\n environment,\n environmentListeners,\n perspective,\n perspectiveListeners,\n type DraftEnvironment,\n type DraftPerspective,\n} from './context'\n\n/**\n * Reports the current draft mode environment.\n * Use it to determine how to adapt the UI based on wether:\n * - Your app is previewed in a iframe, inside Presentation Tool in a Sanity Studio.\n * - Your app is previewed in a new window, spawned from Presentation Tool in a Sanity Studio.\n * - Your app is live previewing drafts in a standalone context.\n * - Your app is previewing drafts, but not live.\n * - Your app is not previewing anything (that could be detected).\n * @public\n */\nexport function useDraftModeEnvironment(): DraftEnvironment {\n const subscribe = useCallback((listener: () => void) => {\n environmentListeners.add(listener)\n return () => environmentListeners.delete(listener)\n }, [])\n\n return useSyncExternalStore(\n subscribe,\n () => environment,\n () => 'checking',\n )\n}\n\n/**\n * Reports the Sanity Client perspective used to fetch data in `sanityFetch` used on the page.\n * If the hook is used outside Draft Mode it will resolve to `'unknown'`.\n * If the hook is used but the `<SanityLive />` component is not present then it'll stay in `'checking'` and console warn after a timeout that it seems like you're missing the component.\n * @public\n */\nexport function useDraftModePerspective(): DraftPerspective {\n const subscribe = useCallback((listener: () => void) => {\n perspectiveListeners.add(listener)\n return () => perspectiveListeners.delete(listener)\n }, [])\n\n return useSyncExternalStore(\n subscribe,\n () => perspective,\n () => 'checking',\n )\n}\n","import {useDraftModeEnvironment} from './useDraftMode'\n\n/**\n * Detects if the application is being previewed inside Sanity Presentation Tool.\n * Presentation Tool can open the application in an iframe, or in a new window.\n * When in this context there are some UI you usually don't want to show,\n * for example a Draft Mode toggle, or a \"Viewing draft content\" indicators, these are unnecessary and add clutter to\n * the editorial experience.\n * The hook returns `null` initially, when it's not yet sure if the application is running inside Presentation Tool,\n * then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsPresentationTool(): boolean | null {\n const environment = useDraftModeEnvironment()\n return environment === 'checking'\n ? null\n : environment === 'presentation-iframe' || environment === 'presentation-window'\n}\n","import {useDraftModeEnvironment} from './useDraftMode'\n\n/**\n * Detects if the application is considered to be in a \"Live Preview\" mode.\n * Live Preview means that the application is either:\n * - being previewed inside Sanity Presentation Tool\n * - being previewed in Draft Mode, with a `browserToken` given to `defineLive`, also known as \"Standalone Live Preview'\"\n * When in Live Preview mode, you typically want UI to update as new content comes in, without any manual intervention.\n * This is very different from Live Production mode, where you usually want to delay updates that might cause layout shifts,\n * to avoid interrupting the user that is consuming your content.\n * This hook lets you adapt to this difference, making sure production doesn't cause layout shifts that worsen the UX,\n * while in Live Preview mode layout shift is less of an issue and it's better for the editorial experience to auto refresh in real time.\n *\n * The hook returns `null` initially, to signal it doesn't yet know if it's live previewing or not.\n * Then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsLivePreview(): boolean | null {\n const environment = useDraftModeEnvironment()\n return environment === 'checking'\n ? null\n : environment === 'presentation-iframe' ||\n environment === 'presentation-window' ||\n environment === 'live'\n}\n","import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} from '@sanity/client'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\nimport {dequal} from 'dequal/lite'\nimport {useEffect, useMemo, useReducer, useSyncExternalStore, useEffectEvent} from 'react'\nimport {\n comlinkDataset,\n comlinkListeners,\n comlinkProjectId,\n comlink as comlinkSnapshot,\n} from './context'\nimport {useDraftModePerspective} from './useDraftMode'\n\n/** @alpha */\nexport type UsePresentationQueryReturnsInactive = {\n data: null\n sourceMap: null\n perspective: null\n}\n\n/** @alpha */\nexport type UsePresentationQueryReturnsActive<QueryString extends string> = {\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n perspective: ClientPerspective\n}\n\nexport type UsePresentationQueryReturns<QueryString extends string> =\n | UsePresentationQueryReturnsInactive\n | UsePresentationQueryReturnsActive<QueryString>\n\ntype Action<QueryString extends string> = {\n type: 'query-change'\n payload: UsePresentationQueryReturnsActive<QueryString>\n}\n\nfunction reducer<QueryString extends string>(\n state: UsePresentationQueryReturns<QueryString>,\n {type, payload}: Action<QueryString>,\n): UsePresentationQueryReturns<QueryString> {\n switch (type) {\n case 'query-change':\n return dequal(state, payload)\n ? state\n : {\n ...state,\n data: dequal(state.data, payload.data)\n ? (state.data as ClientReturn<QueryString>)\n : payload.data,\n sourceMap: dequal(state.sourceMap, payload.sourceMap)\n ? (state.sourceMap as ContentSourceMap | null)\n : payload.sourceMap,\n perspective: dequal(state.perspective, payload.perspective)\n ? (state.perspective as Exclude<ClientPerspective, 'raw'>)\n : payload.perspective,\n }\n default:\n return state\n }\n}\nconst initialState: UsePresentationQueryReturnsInactive = {\n data: null,\n sourceMap: null,\n perspective: null,\n}\n\nfunction subscribe(listener: () => void) {\n comlinkListeners.add(listener)\n return () => comlinkListeners.delete(listener)\n}\n\nconst EMPTY_QUERY_PARAMS: QueryParams = {}\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * Experimental hook that can run queries in Presentation Tool.\n * Query results are sent back over postMessage whenever the query results change.\n * It also works with optimistic updates in the studio itself, offering low latency updates.\n * It's not as low latency as the `useOptimistic` hook, but it's a good compromise for some use cases.\n * Especially until `useOptimistic` propagates edits in the Studio parent window back into the iframe.\n * @alpha\n */\nexport function usePresentationQuery<const QueryString extends string>(props: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n}): UsePresentationQueryReturns<QueryString> {\n const [state, dispatch] = useReducer(reducer, initialState)\n const {query, params = EMPTY_QUERY_PARAMS, stega = true} = props\n\n /**\n * Comlink forwards queries we want to run to the parent window where Presentation Tool handles it for us\n */\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n /**\n * The comlink events requires projectId and dataset, Presentation Tool uses it to protect against project and dataset mismatch errors.\n * We don't want to force the consumers of the `usePresentationQuery` hook to provide these,\n * so we set them in the component that establishes the comlink connection and propagates it to all the subscribes.\n */\n const projectId = useSyncExternalStore(\n subscribe,\n () => comlinkProjectId,\n () => null,\n )\n const dataset = useSyncExternalStore(\n subscribe,\n () => comlinkDataset,\n () => null,\n )\n /**\n * The perspective is kept in sync with Presentation Tool's perspective, and even knows what perspective the page loaded with initially and can forward it to the Sanity Studio.\n */\n const perspective = useDraftModePerspective()\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n // Handle odd case where the comlink can take events but some data is missing\n if (!projectId || !dataset || !perspective) {\n // eslint-disable-next-line no-console\n console.warn('usePresentationQuery: projectId, dataset and perspective must be set', {\n projectId,\n dataset,\n perspective,\n })\n return\n }\n // Another odd case where the initial perspective states haven't resolved to the actual perspective state\n if (perspective === 'checking' || perspective === 'unknown') {\n return\n }\n comlink.post('loader/query-listen', {\n projectId,\n dataset,\n perspective,\n query,\n params,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {\n projectId,\n dataset,\n query,\n params,\n },\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n dispatch({\n type: 'query-change',\n payload: {\n data: event.result,\n sourceMap: event.resultSourceMap || null,\n perspective: event.perspective,\n },\n })\n }\n },\n )\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n return useMemo(() => {\n if (stega && state.sourceMap) {\n return {\n ...state,\n data: stegaEncodeSourceMap(state.data, state.sourceMap, {enabled: true, studioUrl: '/'}),\n }\n }\n return state\n }, [state, stega])\n}\n"],"m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3D,MAAMC,YAAU,qBACd,iBACMC,eACA,KACP;CAMD,MAAM,YAAY,qBAChB,iBACM,wBACA,KACP;CACD,MAAM,UAAU,qBACd,iBACM,sBACA,KACP;CAID,MAAMC,gBAAc,yBAAyB;CAC7C,MAAM,uBAAuB,gBAAgB,cAAiD;AAE5F,MAAI,CAAC,aAAa,CAAC,WAAW,CAACA,eAAa;AAE1C,WAAQ,KAAK,wEAAwE;IACnF;IACA;IACA,aAAA;IACD,CAAC;AACF;;AAGF,MAAIA,kBAAgB,cAAcA,kBAAgB,UAChD;AAEF,YAAQ,KAAK,uBAAuB;GAClC;GACA;GACA,aAAA;GACA;GACA;GACA,WAAW;GACZ,CAAC;GACF;CACF,MAAM,oBAAoB,gBACvB,UAA+E;AAC9E,MACE,OACE;GACE;GACA;GACA;GACA;GACD,EACD;GACE,WAAW,MAAM;GACjB,SAAS,MAAM;GACf,OAAO,MAAM;GACb,QAAQ,MAAM;GACf,CACF,CAED,UAAS;GACP,MAAM;GACN,SAAS;IACP,MAAM,MAAM;IACZ,WAAW,MAAM,mBAAmB;IACpC,aAAa,MAAM;IACpB;GACF,CAAC;GAGP;AACD,iBAAgB;AACd,MAAI,CAACF,UAAS;EAEd,MAAM,cAAcA,UAAQ,GAAG,uBAAuB,kBAAkB;EACxE,MAAM,WAAW,kBAAkB,qBAAqBA,UAAQ,EAAE,0BAA0B;AAC5F,eAAa;AACX,iBAAc,SAAS;AACvB,gBAAa;;IAEd,CAACA,UAAQ,CAAC;AAEb,QAAO,cAAc;AACnB,MAAI,SAAS,MAAM,UACjB,QAAO;GACL,GAAG;GACH,MAAM,qBAAqB,MAAM,MAAM,MAAM,WAAW;IAAC,SAAS;IAAM,WAAW;IAAI,CAAC;GACzF;AAEH,SAAO;IACN,CAAC,OAAO,MAAM,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["environment","environment","initialState: UsePresentationQueryReturnsInactive","EMPTY_QUERY_PARAMS: QueryParams","comlink","comlinkSnapshot","perspective"],"sources":["../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":["import {useCallback, useSyncExternalStore} from 'react'\nimport {\n environment,\n environmentListeners,\n perspective,\n perspectiveListeners,\n type DraftEnvironment,\n type DraftPerspective,\n} from './context'\n\n/**\n * Reports the current draft mode environment.\n * Use it to determine how to adapt the UI based on wether:\n * - Your app is previewed in a iframe, inside Presentation Tool in a Sanity Studio.\n * - Your app is previewed in a new window, spawned from Presentation Tool in a Sanity Studio.\n * - Your app is live previewing drafts in a standalone context.\n * - Your app is previewing drafts, but not live.\n * - Your app is not previewing anything (that could be detected).\n * @public\n */\nexport function useDraftModeEnvironment(): DraftEnvironment {\n const subscribe = useCallback((listener: () => void) => {\n environmentListeners.add(listener)\n return () => environmentListeners.delete(listener)\n }, [])\n\n return useSyncExternalStore(\n subscribe,\n () => environment,\n () => 'checking',\n )\n}\n\n/**\n * Reports the Sanity Client perspective used to fetch data in `sanityFetch` used on the page.\n * If the hook is used outside Draft Mode it will resolve to `'unknown'`.\n * If the hook is used but the `<SanityLive />` component is not present then it'll stay in `'checking'` and console warn after a timeout that it seems like you're missing the component.\n * @public\n */\nexport function useDraftModePerspective(): DraftPerspective {\n const subscribe = useCallback((listener: () => void) => {\n perspectiveListeners.add(listener)\n return () => perspectiveListeners.delete(listener)\n }, [])\n\n return useSyncExternalStore(\n subscribe,\n () => perspective,\n () => 'checking',\n )\n}\n","import {useDraftModeEnvironment} from './useDraftMode'\n\n/**\n * Detects if the application is being previewed inside Sanity Presentation Tool.\n * Presentation Tool can open the application in an iframe, or in a new window.\n * When in this context there are some UI you usually don't want to show,\n * for example a Draft Mode toggle, or a \"Viewing draft content\" indicators, these are unnecessary and add clutter to\n * the editorial experience.\n * The hook returns `null` initially, when it's not yet sure if the application is running inside Presentation Tool,\n * then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsPresentationTool(): boolean | null {\n const environment = useDraftModeEnvironment()\n return environment === 'checking'\n ? null\n : environment === 'presentation-iframe' || environment === 'presentation-window'\n}\n","import {useDraftModeEnvironment} from './useDraftMode'\n\n/**\n * Detects if the application is considered to be in a \"Live Preview\" mode.\n * Live Preview means that the application is either:\n * - being previewed inside Sanity Presentation Tool\n * - being previewed in Draft Mode, with a `browserToken` given to `defineLive`, also known as \"Standalone Live Preview'\"\n * When in Live Preview mode, you typically want UI to update as new content comes in, without any manual intervention.\n * This is very different from Live Production mode, where you usually want to delay updates that might cause layout shifts,\n * to avoid interrupting the user that is consuming your content.\n * This hook lets you adapt to this difference, making sure production doesn't cause layout shifts that worsen the UX,\n * while in Live Preview mode layout shift is less of an issue and it's better for the editorial experience to auto refresh in real time.\n *\n * The hook returns `null` initially, to signal it doesn't yet know if it's live previewing or not.\n * Then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsLivePreview(): boolean | null {\n const environment = useDraftModeEnvironment()\n return environment === 'checking'\n ? null\n : environment === 'presentation-iframe' ||\n environment === 'presentation-window' ||\n environment === 'live'\n}\n","import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} from '@sanity/client'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\nimport {dequal} from 'dequal/lite'\nimport {useEffect, useMemo, useReducer, useSyncExternalStore, useEffectEvent} from 'react'\nimport {\n comlinkDataset,\n comlinkListeners,\n comlinkProjectId,\n comlink as comlinkSnapshot,\n} from './context'\nimport {useDraftModePerspective} from './useDraftMode'\n\n/** @alpha */\nexport type UsePresentationQueryReturnsInactive = {\n data: null\n sourceMap: null\n perspective: null\n}\n\n/** @alpha */\nexport type UsePresentationQueryReturnsActive<QueryString extends string> = {\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n perspective: ClientPerspective\n}\n\nexport type UsePresentationQueryReturns<QueryString extends string> =\n | UsePresentationQueryReturnsInactive\n | UsePresentationQueryReturnsActive<QueryString>\n\ntype Action<QueryString extends string> = {\n type: 'query-change'\n payload: UsePresentationQueryReturnsActive<QueryString>\n}\n\nfunction reducer<QueryString extends string>(\n state: UsePresentationQueryReturns<QueryString>,\n {type, payload}: Action<QueryString>,\n): UsePresentationQueryReturns<QueryString> {\n switch (type) {\n case 'query-change':\n return dequal(state, payload)\n ? state\n : {\n ...state,\n data: dequal(state.data, payload.data)\n ? // oxlint-disable-next-line no-unsafe-type-assertion\n (state.data as ClientReturn<QueryString>)\n : payload.data,\n sourceMap: dequal(state.sourceMap, payload.sourceMap)\n ? state.sourceMap\n : payload.sourceMap,\n perspective: dequal(state.perspective, payload.perspective)\n ? // oxlint-disable-next-line no-unsafe-type-assertion\n (state.perspective as Exclude<ClientPerspective, 'raw'>)\n : payload.perspective,\n }\n default:\n return state\n }\n}\nconst initialState: UsePresentationQueryReturnsInactive = {\n data: null,\n sourceMap: null,\n perspective: null,\n}\n\nfunction subscribe(listener: () => void) {\n comlinkListeners.add(listener)\n return () => comlinkListeners.delete(listener)\n}\n\nconst EMPTY_QUERY_PARAMS: QueryParams = {}\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * Experimental hook that can run queries in Presentation Tool.\n * Query results are sent back over postMessage whenever the query results change.\n * It also works with optimistic updates in the studio itself, offering low latency updates.\n * It's not as low latency as the `useOptimistic` hook, but it's a good compromise for some use cases.\n * Especially until `useOptimistic` propagates edits in the Studio parent window back into the iframe.\n * @alpha\n */\nexport function usePresentationQuery<const QueryString extends string>(props: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n}): UsePresentationQueryReturns<QueryString> {\n const [state, dispatch] = useReducer(reducer, initialState)\n const {query, params = EMPTY_QUERY_PARAMS, stega = true} = props\n\n /**\n * Comlink forwards queries we want to run to the parent window where Presentation Tool handles it for us\n */\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n /**\n * The comlink events requires projectId and dataset, Presentation Tool uses it to protect against project and dataset mismatch errors.\n * We don't want to force the consumers of the `usePresentationQuery` hook to provide these,\n * so we set them in the component that establishes the comlink connection and propagates it to all the subscribes.\n */\n const projectId = useSyncExternalStore(\n subscribe,\n () => comlinkProjectId,\n () => null,\n )\n const dataset = useSyncExternalStore(\n subscribe,\n () => comlinkDataset,\n () => null,\n )\n /**\n * The perspective is kept in sync with Presentation Tool's perspective, and even knows what perspective the page loaded with initially and can forward it to the Sanity Studio.\n */\n const perspective = useDraftModePerspective()\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n // Handle odd case where the comlink can take events but some data is missing\n if (!projectId || !dataset || !perspective) {\n console.warn('usePresentationQuery: projectId, dataset and perspective must be set', {\n projectId,\n dataset,\n perspective,\n })\n return\n }\n // Another odd case where the initial perspective states haven't resolved to the actual perspective state\n if (perspective === 'checking' || perspective === 'unknown') {\n return\n }\n comlink.post('loader/query-listen', {\n projectId,\n dataset,\n perspective,\n query,\n params,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {\n projectId,\n dataset,\n query,\n params,\n },\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n dispatch({\n type: 'query-change',\n payload: {\n data: event.result,\n sourceMap: event.resultSourceMap || null,\n perspective: event.perspective,\n },\n })\n }\n },\n )\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n return useMemo(() => {\n if (stega && state.sourceMap) {\n return {\n ...state,\n data: stegaEncodeSourceMap(state.data, state.sourceMap, {enabled: true, studioUrl: '/'}),\n }\n }\n return state\n }, [state, stega])\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,SAAQ;CAK3D,MAAMC,YAAU,qBACd,iBACMC,eACA,KACP;CAMD,MAAM,YAAY,qBAChB,iBACM,wBACA,KACP;CACD,MAAM,UAAU,qBACd,iBACM,sBACA,KACP;CAID,MAAMC,gBAAc,yBAAyB;CAC7C,MAAM,uBAAuB,gBAAgB,cAAiD;AAE5F,MAAI,CAAC,aAAa,CAAC,WAAW,CAACA,eAAa;AAC1C,WAAQ,KAAK,wEAAwE;IACnF;IACA;IACA,aAAA;IACD,CAAC;AACF;;AAGF,MAAIA,kBAAgB,cAAcA,kBAAgB,UAChD;AAEF,YAAQ,KAAK,uBAAuB;GAClC;GACA;GACA,aAAA;GACA;GACA;GACA,WAAW;GACZ,CAAC;GACF;CACF,MAAM,oBAAoB,gBACvB,UAA+E;AAC9E,MACE,OACE;GACE;GACA;GACA;GACA;GACD,EACD;GACE,WAAW,MAAM;GACjB,SAAS,MAAM;GACf,OAAO,MAAM;GACb,QAAQ,MAAM;GACf,CACF,CAED,UAAS;GACP,MAAM;GACN,SAAS;IACP,MAAM,MAAM;IACZ,WAAW,MAAM,mBAAmB;IACpC,aAAa,MAAM;IACpB;GACF,CAAC;GAGP;AACD,iBAAgB;AACd,MAAI,CAACF,UAAS;EAEd,MAAM,cAAcA,UAAQ,GAAG,uBAAuB,kBAAkB;EACxE,MAAM,WAAW,kBAAkB,qBAAqBA,UAAQ,EAAE,0BAA0B;AAC5F,eAAa;AACX,iBAAc,SAAS;AACvB,gBAAa;;IAEd,CAACA,UAAQ,CAAC;AAEb,QAAO,cAAc;AACnB,MAAI,SAAS,MAAM,UACjB,QAAO;GACL,GAAG;GACH,MAAM,qBAAqB,MAAM,MAAM,MAAM,WAAW;IAAC,SAAS;IAAM,WAAW;IAAI,CAAC;GACzF;AAEH,SAAO;IACN,CAAC,OAAO,MAAM,CAAC"}
|
package/dist/image/index.d.ts
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
import { ImageLoader, ImageProps as ImageProps$1 } from "next/image";
|
|
2
|
-
|
|
3
|
-
//#region src/image/Image.d.ts
|
|
4
|
-
|
|
5
2
|
/**
|
|
6
3
|
* @alpha
|
|
7
4
|
*/
|
|
@@ -19,12 +16,9 @@ interface ImageProps extends Omit<ImageProps$1, "loader" | "src"> {
|
|
|
19
16
|
* @alpha
|
|
20
17
|
*/
|
|
21
18
|
declare function Image(props: ImageProps): React.JSX.Element;
|
|
22
|
-
//#endregion
|
|
23
|
-
//#region src/image/imageLoader.d.ts
|
|
24
19
|
/**
|
|
25
20
|
* @alpha
|
|
26
21
|
*/
|
|
27
22
|
declare const imageLoader: ImageLoader;
|
|
28
|
-
//#endregion
|
|
29
23
|
export { Image, type ImageProps, imageLoader };
|
|
30
24
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["imageLoader: ImageLoader"],"sources":["../../src/image/Image.tsx","../../src/image/imageLoader.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["imageLoader: ImageLoader"],"sources":["../../src/image/Image.tsx","../../src/image/imageLoader.ts"],"sourcesContent":[],"mappings":";;AAOA;AAcA;UAdiB,UAAA,SAAmB,KAAK;ECFzC;;;;;;;;;;;;iBDgBgB,KAAA,QAAa,aAAa,KAAA,CAAM,GAAA,CAAI;;AAdpD;AAcA;cChBaA,aAAa"}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,8 +5,4 @@ import { CreateDataAttribute, CreateDataAttributeProps, createDataAttribute } fr
|
|
|
5
5
|
import groq, { defineQuery } from "groq";
|
|
6
6
|
export * from "@sanity/client";
|
|
7
7
|
export * from "@portabletext/react";
|
|
8
|
-
|
|
9
|
-
//#region rolldown:runtime
|
|
10
|
-
|
|
11
|
-
//#endregion
|
|
12
8
|
export { type CreateDataAttribute, type CreateDataAttributeProps, createClient, createDataAttribute, defineQuery, groq, isCorsOriginError, stegaClean, unstable__adapter, unstable__environment };
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { CorsOriginError as CorsOriginError$1 } from "@sanity/client";
|
|
2
|
-
|
|
3
|
-
//#region src/isCorsOriginError.d.ts
|
|
4
2
|
/** @public */
|
|
5
3
|
declare function isCorsOriginError(error: unknown): error is CorsOriginError$1;
|
|
6
|
-
//#endregion
|
|
7
4
|
export { isCorsOriginError as t };
|
|
8
5
|
//# sourceMappingURL=isCorsOriginError.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isCorsOriginError.d.ts","names":[],"sources":["../src/isCorsOriginError.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"isCorsOriginError.d.ts","names":[],"sources":["../src/isCorsOriginError.ts"],"sourcesContent":[],"mappings":";;AAGgB,iBAAA,iBAAA,CAA4C,KAAA,EAAA,OAAA,CAAA,EAAA,KAAA,IAAA,iBAAA"}
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
import { ClientPerspective, InitializedClientConfig, LiveEventGoAway, SyncTag } from "@sanity/client";
|
|
2
|
-
|
|
3
|
-
//#region src/live/client-components/live/SanityLive.d.ts
|
|
4
|
-
|
|
5
2
|
/**
|
|
6
3
|
* @public
|
|
7
4
|
*/
|
|
@@ -25,6 +22,5 @@ interface SanityLiveProps extends Pick<InitializedClientConfig, "projectId" | "d
|
|
|
25
22
|
* @public
|
|
26
23
|
*/
|
|
27
24
|
declare function SanityLive(props: SanityLiveProps): React.JSX.Element | null;
|
|
28
|
-
//#endregion
|
|
29
25
|
export { type SanityLiveProps, SanityLive as default };
|
|
30
26
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/client-components/live/SanityLive.tsx"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/live/client-components/live/SanityLive.tsx"],"sourcesContent":[],"mappings":";;AAwBA;;AAYyB,UAZR,eAAA,SAAwB,IAYhB,CAXvB,uBAWuB,EAAA,WAAA,GAAA,SAAA,GAAA,SAAA,GAAA,YAAA,GAAA,oBAAA,GAAA,OAAA,GAAA,kBAAA,CAAA,CAAA;EAWJ,gBAAA,EAAA,OAAA;EACS,oBAAA,CAAA,EAZL,iBAYK;EAAc,cAAA,CAAA,EAAA,OAAA;EAxBH,cAAA,CAAA,EAAA,OAAA;EAAA,kBAAA,CAAA,EAAA,OAAA;EA8DzC,UAAgB,EAAA,MAAA,GAAA,SAAkB;;;;;;;qBAvCb;8BACS,cAAc;;;;;iBAsC5B,UAAA,QAAkB,kBAAkB,KAAA,CAAM,GAAA,CAAI"}
|