@sanity/sdk-react 0.0.0-alpha.13 → 0.0.0-alpha.15
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/README.md +36 -33
- package/dist/_chunks-es/context.js +1 -1
- package/dist/_chunks-es/context.js.map +1 -1
- package/dist/_chunks-es/useLogOut.js +21 -6
- package/dist/_chunks-es/useLogOut.js.map +1 -1
- package/dist/components.d.ts +18 -2
- package/dist/components.js +29 -8
- package/dist/components.js.map +1 -1
- package/dist/context.d.ts +2 -2
- package/dist/hooks.d.ts +245 -71
- package/dist/hooks.js +97 -246
- package/dist/hooks.js.map +1 -1
- package/package.json +3 -4
- package/src/_exports/components.ts +1 -0
- package/src/_exports/hooks.ts +8 -2
- package/src/components/Login/LoginLinks.test.tsx +1 -1
- package/src/components/SDKProvider.test.tsx +79 -0
- package/src/components/SDKProvider.tsx +31 -0
- package/src/components/SanityApp.test.tsx +103 -1
- package/src/components/SanityApp.tsx +34 -19
- package/src/components/auth/authTestHelpers.tsx +1 -1
- package/src/components/utils.ts +19 -0
- package/src/context/SanityProvider.test.tsx +1 -1
- package/src/context/SanityProvider.tsx +4 -4
- package/src/hooks/auth/useCurrentUser.tsx +26 -21
- package/src/hooks/client/useClient.ts +4 -30
- package/src/hooks/context/useSanityInstance.test.tsx +1 -1
- package/src/hooks/context/useSanityInstance.ts +19 -3
- package/src/hooks/datasets/useDatasets.ts +12 -0
- package/src/hooks/document/useDocument.test.ts +2 -2
- package/src/hooks/document/useDocument.ts +14 -19
- package/src/hooks/document/useDocumentEvent.test.ts +13 -3
- package/src/hooks/document/useDocumentEvent.ts +11 -3
- package/src/hooks/document/useDocumentSyncStatus.ts +1 -1
- package/src/hooks/document/useEditDocument.test.ts +19 -12
- package/src/hooks/document/useEditDocument.ts +11 -9
- package/src/hooks/document/usePermissions.ts +57 -3
- package/src/hooks/documentCollection/types.ts +19 -0
- package/src/hooks/documentCollection/useDocuments.ts +3 -20
- package/src/hooks/documentCollection/useSearch.test.ts +100 -0
- package/src/hooks/documentCollection/useSearch.ts +75 -0
- package/src/hooks/helpers/createStateSourceHook.test.tsx +66 -0
- package/src/hooks/helpers/createStateSourceHook.tsx +30 -7
- package/src/hooks/projection/useProjection.test.tsx +218 -0
- package/src/hooks/projection/useProjection.ts +135 -0
- package/src/hooks/projects/useProject.ts +21 -0
- package/src/hooks/projects/useProjects.ts +19 -0
- package/src/hooks/users/useUsers.test.ts +2 -3
- package/src/hooks/users/useUsers.ts +41 -7
- package/src/hooks/client/useClient.test.tsx +0 -130
package/dist/hooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.js","sources":["../src/hooks/auth/useAuthToken.tsx","../src/hooks/auth/useCurrentUser.tsx","../src/hooks/client/useClient.ts","../src/hooks/comlink/useFrameConnection.ts","../src/hooks/comlink/useWindowConnection.ts","../src/hooks/document/useApplyActions.ts","../src/hooks/document/useDocument.ts","../src/hooks/document/useDocumentEvent.ts","../src/hooks/document/useDocumentSyncStatus.ts","../src/hooks/document/useEditDocument.ts","../src/hooks/document/usePermissions.ts","../src/hooks/documentCollection/useDocuments.ts","../src/hooks/preview/usePreview.tsx","../../../node_modules/.pnpm/@sanity+access-api@2.2.6/node_modules/@sanity/access-api/lib/index.js","../src/hooks/users/useUsers.ts"],"sourcesContent":["import {getTokenState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * Hook to get the currently logged in user\n * @internal\n * @returns The current user or null if not authenticated\n */\nexport const useAuthToken = createStateSourceHook(getTokenState)\n","import {type CurrentUser, getCurrentUserState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @TODO This should suspend! And possibly not return `null`?\n *\n * @public\n *\n * Provides the currently authenticated user’s profile information (their name, email, roles, etc).\n * If no users are currently logged in, the hook returns null.\n *\n * @category Authentication\n * @returns The current user data, or `null` if not authenticated\n *\n * @example Rendering a basic user profile\n * ```\n * const user = useCurrentUser()\n *\n * return (\n * <figure>\n * <img src={user?.profileImage} alt=`Profile image for ${user?.name}` />\n * <h2>{user?.name}</h2>\n * </figure>\n * )\n * ```\n */\nexport const useCurrentUser: () => CurrentUser | null = createStateSourceHook(getCurrentUserState)\n","import {type SanityClient} from '@sanity/client'\nimport {type ClientOptions, getClient, getSubscribableClient} from '@sanity/sdk'\nimport {useCallback, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * A React hook that provides a client that subscribes to changes in your application,\n * such as user authentication changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to changes\n * and ensure consistency between server and client rendering.\n *\n * @category Platform\n * @returns A Sanity client\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const client = useClient()\n * const [document, setDocument] = useState(null)\n * useEffect(async () => {\n * const doc = client.fetch('*[_id == \"myDocumentId\"]')\n * setDocument(doc)\n * }, [])\n * return <div>{JSON.stringify(document) ?? 'Loading...'}</div>\n * }\n * ```\n *\n * @public\n */\nexport function useClient(options: ClientOptions): SanityClient {\n const instance = useSanityInstance()\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n const client$ = getSubscribableClient(instance, options)\n const subscription = client$.subscribe({\n next: onStoreChange,\n error: (error) => {\n // @TODO: We should tackle error handling / error boundaries soon\n // eslint-disable-next-line no-console\n console.error('Error in useClient subscription:', error)\n },\n })\n return () => subscription.unsubscribe()\n },\n [instance, options],\n )\n\n const getSnapshot = useCallback(() => {\n return getClient(instance, options)\n }, [instance, options])\n\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n","import {type Status} from '@sanity/comlink'\nimport {\n type FrameMessage,\n getOrCreateChannel,\n getOrCreateController,\n releaseChannel,\n type WindowMessage,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type FrameMessageHandler<TWindowMessage extends WindowMessage> = (\n event: TWindowMessage['data'],\n) => TWindowMessage['response'] | Promise<TWindowMessage['response']>\n\n/**\n * @internal\n */\nexport interface UseFrameConnectionOptions<TWindowMessage extends WindowMessage> {\n name: string\n connectTo: string\n targetOrigin: string\n onMessage?: {\n [K in TWindowMessage['type']]: (data: Extract<TWindowMessage, {type: K}>['data']) => void\n }\n heartbeat?: boolean\n}\n\n/**\n * @internal\n */\nexport interface FrameConnection<TFrameMessage extends FrameMessage> {\n connect: (frameWindow: Window) => () => void // Return cleanup function\n sendMessage: <T extends TFrameMessage['type']>(\n ...params: Extract<TFrameMessage, {type: T}>['data'] extends undefined\n ? [type: T]\n : [type: T, data: Extract<TFrameMessage, {type: T}>['data']]\n ) => void\n status: Status\n}\n\n/**\n * @internal\n */\nexport function useFrameConnection<\n TFrameMessage extends FrameMessage,\n TWindowMessage extends WindowMessage,\n>(options: UseFrameConnectionOptions<TWindowMessage>): FrameConnection<TFrameMessage> {\n const {onMessage, targetOrigin, name, connectTo, heartbeat} = options\n const instance = useSanityInstance()\n const [status, setStatus] = useState<Status>('idle')\n\n const controller = useMemo(\n () => getOrCreateController(instance, targetOrigin),\n [instance, targetOrigin],\n )\n\n const channel = useMemo(\n () =>\n getOrCreateChannel(instance, {\n name,\n connectTo,\n heartbeat,\n }),\n [instance, name, connectTo, heartbeat],\n )\n\n useEffect(() => {\n if (!channel) return\n\n const unsubscribe = channel.onStatus((event) => {\n setStatus(event.status)\n })\n\n return unsubscribe\n }, [channel])\n\n useEffect(() => {\n if (!channel || !onMessage) return\n\n const unsubscribers: Array<() => void> = []\n\n Object.entries(onMessage).forEach(([type, handler]) => {\n // type assertion, but we've already constrained onMessage to have the correct handler type\n const unsubscribe = channel.on(type, handler as FrameMessageHandler<TWindowMessage>)\n unsubscribers.push(unsubscribe)\n })\n\n return () => {\n unsubscribers.forEach((unsub) => unsub())\n }\n }, [channel, onMessage])\n\n const connect = useCallback(\n (frameWindow: Window) => {\n const removeTarget = controller?.addTarget(frameWindow)\n return () => {\n removeTarget?.()\n }\n },\n [controller],\n )\n\n const sendMessage = useCallback(\n <T extends TFrameMessage['type']>(\n type: T,\n data?: Extract<TFrameMessage, {type: T}>['data'],\n ) => {\n channel?.post(type, data)\n },\n [channel],\n )\n\n // cleanup channel on unmount\n useEffect(() => {\n return () => {\n releaseChannel(instance, name)\n }\n }, [name, instance])\n\n return {\n connect,\n sendMessage,\n status,\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {type FrameMessage, getOrCreateNode, releaseNode, type WindowMessage} from '@sanity/sdk'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type WindowMessageHandler<TFrameMessage extends FrameMessage> = (\n event: TFrameMessage['data'],\n) => TFrameMessage['response']\n\n/**\n * @internal\n */\nexport interface UseWindowConnectionOptions<TMessage extends FrameMessage> {\n name: string\n connectTo: string\n onMessage?: Record<TMessage['type'], WindowMessageHandler<TMessage>>\n}\n\n/**\n * @internal\n */\nexport interface WindowConnection<TMessage extends WindowMessage> {\n sendMessage: <TType extends TMessage['type']>(\n type: TType,\n data?: Extract<TMessage, {type: TType}>['data'],\n ) => void\n status: Status\n}\n\n/**\n * @internal\n */\nexport function useWindowConnection<\n TWindowMessage extends WindowMessage,\n TFrameMessage extends FrameMessage,\n>(options: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage> {\n const {name, onMessage, connectTo} = options\n const instance = useSanityInstance()\n const [status, setStatus] = useState<Status>('idle')\n\n const node = useMemo(\n () => getOrCreateNode(instance, {name, connectTo}),\n [instance, name, connectTo],\n )\n\n useEffect(() => {\n const unsubscribe = node.onStatus((newStatus) => {\n setStatus(newStatus)\n })\n\n return unsubscribe\n }, [node, instance, name])\n\n useEffect(() => {\n if (!onMessage) return\n\n const unsubscribers: Array<() => void> = []\n\n Object.entries(onMessage).forEach(([type, handler]) => {\n const unsubscribe = node.on(type, handler as WindowMessageHandler<TFrameMessage>)\n unsubscribers.push(unsubscribe)\n })\n\n return () => {\n unsubscribers.forEach((unsub) => unsub())\n }\n }, [node, onMessage])\n\n const sendMessage = useCallback(\n <TType extends WindowMessage['type']>(\n type: TType,\n data?: Extract<WindowMessage, {type: TType}>['data'],\n ) => {\n node?.post(type, data)\n },\n [node],\n )\n\n // cleanup node on unmount\n useEffect(() => {\n return () => {\n releaseNode(instance, name)\n }\n }, [instance, name])\n\n return {\n sendMessage,\n status,\n }\n}\n","import {\n type ActionsResult,\n applyActions,\n type ApplyActionsOptions,\n type DocumentAction,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n *\n * @beta\n *\n * Provides a callback for applying one or more actions to a document.\n *\n * @category Documents\n * @returns A function that takes one more more {@link DocumentAction}s and returns a promise that resolves to an {@link ActionsResult}.\n * @example Publish or unpublish a document\n * ```\n * import { publishDocument, unpublishDocument } from '@sanity/sdk'\n * import { useApplyActions } from '@sanity/sdk-react'\n *\n * const apply = useApplyActions()\n * const myDocument = { _id: 'my-document-id', _type: 'my-document-type' }\n *\n * return (\n * <button onClick={() => apply(publishDocument(myDocument))}>Publish</button>\n * <button onClick={() => apply(unpublishDocument(myDocument))}>Unpublish</button>\n * )\n * ```\n *\n * @example Create and publish a new document\n * ```\n * import { createDocument, publishDocument } from '@sanity/sdk'\n * import { useApplyActions } from '@sanity/sdk-react'\n *\n * const apply = useApplyActions()\n *\n * const handleCreateAndPublish = () => {\n * const handle = { _id: window.crypto.randomUUID(), _type: 'my-document-type' }\n * apply([\n * createDocument(handle),\n * publishDocument(handle),\n * ])\n * }\n *\n * return (\n * <button onClick={handleCreateAndPublish}>\n * I’m feeling lucky\n * </button>\n * )\n * ```\n */\nexport function useApplyActions(): <TDocument extends SanityDocument>(\n action: DocumentAction<TDocument> | DocumentAction<TDocument>[],\n options?: ApplyActionsOptions,\n) => Promise<ActionsResult<TDocument>>\n\n/** @beta */\nexport function useApplyActions(): (\n action: DocumentAction | DocumentAction[],\n options?: ApplyActionsOptions,\n) => Promise<ActionsResult> {\n return _useApplyActions()\n}\n\nconst _useApplyActions = createCallbackHook(applyActions)\n","import {\n type DocumentHandle,\n getDocumentState,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @beta\n *\n * ## useDocument(doc, path)\n * Read and subscribe to nested values in a document\n * @category Documents\n * @param doc - The document to read state from\n * @param path - The path to the nested value to read from\n * @returns The value at the specified path\n * @example\n * ```tsx\n * import {type DocumentHandle, useDocument} from '@sanity/sdk-react'\n *\n * function OrderLink({documentHandle}: {documentHandle: DocumentHandle}) {\n * const title = useDocument(documentHandle, 'title')\n * const id = useDocument(documentHandle, '_id')\n *\n * return (\n * <a href=`/order/${id}`>Order {title} today!</a>\n * )\n * }\n * ```\n *\n */\nexport function useDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(doc: string | DocumentHandle<TDocument>, path: TPath): JsonMatch<TDocument, TPath> | undefined\n\n/**\n * @beta\n * ## useDocument(doc)\n * Read and subscribe to an entire document\n * @param doc - The document to read state from\n * @returns The document state as an object\n * @example\n * ```tsx\n * import {type SanityDocument, type DocumentHandle, useDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument {\n * title: string\n * author: string\n * summary: string\n * }\n *\n * function DocumentView({documentHandle}: {documentHandle: DocumentHandle}) {\n * const book = useDocument<Book>(documentHandle)\n *\n * return (\n * <article>\n * <h1>{book?.title}</h1>\n * <address>By {book?.author}</address>\n *\n * <h2>Summary</h2>\n * {book?.summary}\n *\n * <h2>Order</h2>\n * <a href=`/order/${book._id}`>Order {book?.title} today!</a>\n * </article>\n * )\n * }\n * ```\n *\n */\nexport function useDocument<TDocument extends SanityDocument>(\n doc: string | DocumentHandle<TDocument>,\n): TDocument | null\n\n/**\n * @beta\n * Reads and subscribes to a document’s realtime state, incorporating both local and remote changes.\n * When called with a `path` argument, the hook will return the nested value’s state.\n * When called without a `path` argument, the entire document’s state will be returned.\n *\n * @remarks\n * `useDocument` is designed to be used within a realtime context in which local updates to documents\n * need to be displayed before they are persisted to the remote copy. This can be useful within a collaborative\n * or realtime editing interface where local changes need to be reflected immediately.\n *\n * However, this hook can be too resource intensive for applications where static document values simply\n * need to be displayed (or when changes to documents don’t need to be reflected immediately);\n * consider using `usePreview` or `useQuery` for these use cases instead. These hooks leverage the Sanity\n * Live Content API to provide a more efficient way to read and subscribe to document state.\n */\nexport function useDocument(doc: string | DocumentHandle, path?: string): unknown {\n const documentId = typeof doc === 'string' ? doc : doc._id\n const instance = useSanityInstance()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, documentId).getCurrent() !== undefined,\n [instance, documentId],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, documentId)\n\n const {subscribe, getCurrent} = useMemo(\n () => getDocumentState(instance, documentId, path),\n [documentId, instance, path],\n )\n\n return useSyncExternalStore(subscribe, getCurrent)\n}\n","import {type DocumentEvent, subscribeDocumentEvents} from '@sanity/sdk'\nimport {useCallback, useEffect, useInsertionEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n *\n * @beta\n *\n * Subscribes an event handler to events in your application’s document store, such as document\n * creation, deletion, and updates.\n *\n * @category Documents\n * @param handler - The event handler to register.\n * @example\n * ```\n * import {useDocumentEvent} from '@sanity/sdk-react'\n * import {type DocumentEvent} from '@sanity/sdk'\n *\n * useDocumentEvent((event) => {\n * if (event.type === DocumentEvent.DocumentDeletedEvent) {\n * alert(`Document with ID ${event.documentId} deleted!`)\n * } else {\n * console.log(event)\n * }\n * })\n * ```\n */\nexport function useDocumentEvent(handler: (documentEvent: DocumentEvent) => void): void {\n const ref = useRef(handler)\n\n useInsertionEffect(() => {\n ref.current = handler\n })\n\n const stableHandler = useCallback((documentEvent: DocumentEvent) => {\n return ref.current(documentEvent)\n }, [])\n\n const instance = useSanityInstance()\n useEffect(() => {\n return subscribeDocumentEvents(instance, stableHandler)\n }, [instance, stableHandler])\n}\n","import {type DocumentHandle, getDocumentSyncStatus} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseDocumentSyncStatus = {\n /**\n * Exposes the document’s sync status between local and remote document states.\n *\n * @category Documents\n * @param doc - The document handle to get sync status for\n * @returns `true` if local changes are synced with remote, `false` if the changes are not synced, and `undefined` if the document is not found\n * @example Disable a Save button when there are no changes to sync\n * ```\n * const myDocumentHandle = { _id: 'documentId', _type: 'documentType' }\n * const documentSynced = useDocumentSyncStatus(myDocumentHandle)\n *\n * return (\n * <button disabled={documentSynced}>\n * Save Changes\n * </button>\n * )\n * ```\n */\n (doc: DocumentHandle): boolean | undefined\n}\n\n/** @beta */\nexport const useDocumentSyncStatus: UseDocumentSyncStatus =\n createStateSourceHook(getDocumentSyncStatus)\n","import {\n type ActionsResult,\n type DocumentHandle,\n editDocument,\n getDocumentState,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useApplyActions} from './useApplyActions'\n\nconst ignoredKeys = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']\n\ntype Updater<TValue> = TValue | ((nextValue: TValue) => TValue)\n\n/**\n *\n * @beta\n *\n * ## useEditDocument(doc, path)\n * Edit a nested value within a document\n *\n * @category Documents\n * @param doc - The document to be edited; either as a document handle or the document’s ID a string\n * @param path - The path to the nested value to be edited\n * @returns A function to update the nested value. Accepts either a new value, or an updater function that exposes the previous value and returns a new value.\n * @example Update a document’s name by providing the new value directly\n * ```\n * const handle = { _id: 'documentId', _type: 'documentType' }\n * const name = useDocument(handle, 'name')\n * const editName = useEditDocument(handle, 'name')\n *\n * function handleNameChange(event: React.ChangeEvent<HTMLInputElement>) {\n * editName(event.target.value)\n * }\n *\n * return (\n * <input type='text' value={name} onChange={handleNameChange} />\n * )\n * ```\n *\n * @example Update a count on a document by providing an updater function\n * ```\n * const handle = { _id: 'documentId', _type: 'documentType' }\n * const count = useDocument(handle, 'count')\n * const editCount = useEditDocument(handle, 'count')\n *\n * function incrementCount() {\n * editCount(previousCount => previousCount + 1)\n * }\n *\n * return (\n * <>\n * <button onClick={incrementCount}>\n * Increment\n * </button>\n * Current count: {count}\n * </>\n * )\n * ```\n */\nexport function useEditDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(\n doc: string | DocumentHandle<TDocument>,\n path: TPath,\n): (nextValue: Updater<JsonMatch<TDocument, TPath>>) => Promise<ActionsResult<TDocument>>\n\n/**\n *\n * @beta\n *\n * ## useEditDocument(doc)\n * Edit an entire document\n * @param doc - The document to be edited; either as a document handle or the document’s ID a string\n * @returns A function to update the document state. Accepts either a new document state, or an updater function that exposes the previous document state and returns the new document state.\n * @example\n * ```\n * const myDocumentHandle = { _id: 'documentId', _type: 'documentType' }\n *\n * const myDocument = useDocument(myDocumentHandle)\n * const { title, price } = myDocument\n *\n * const editMyDocument = useEditDocument(myDocumentHandle)\n *\n * function handleFieldChange(e: React.ChangeEvent<HTMLInputElement>) {\n * const {name, value} = e.currentTarget\n * // Use an updater function to update the document state based on the previous state\n * editMyDocument(previousDocument => ({\n * ...previousDocument,\n * [name]: value\n * }))\n * }\n *\n * function handleSaleChange(e: React.ChangeEvent<HTMLInputElement>) {\n * const { checked } = e.currentTarget\n * if (checked) {\n * // Use an updater function to add a new salePrice field;\n * // set it at a 20% discount off the normal price\n * editMyDocument(previousDocument => ({\n * ...previousDocument,\n * salePrice: previousDocument.price * 0.8,\n * }))\n * } else {\n * // Get the document state without the salePrice field\n * const { salePrice, ...rest } = myDocument\n * // Update the document state to remove the salePrice field\n * editMyDocument(rest)\n * }\n * }\n *\n * return (\n * <>\n * <form onSubmit={e => e.preventDefault()}>\n * <input name='title' type='text' value={title} onChange={handleFieldChange} />\n * <input name='price' type='number' value={price} onChange={handleFieldChange} />\n * <input\n * name='salePrice'\n * type='checkbox'\n * checked={Object(myDocument).hasOwnProperty('salePrice')}\n * onChange={handleSaleChange}\n * />\n * </form>\n * <pre><code>\n * {JSON.stringify(myDocument, null, 2)}\n * </code></pre>\n * </>\n * )\n * ```\n */\nexport function useEditDocument<TDocument extends SanityDocument>(\n doc: string | DocumentHandle<TDocument>,\n): (nextValue: Updater<TDocument>) => Promise<ActionsResult<TDocument>>\n\n/**\n *\n * @beta\n *\n * Enables editing of a document’s state.\n * When called with a `path` argument, the hook will return a function for updating a nested value.\n * When called without a `path` argument, the hook will return a function for updating the entire document.\n */\nexport function useEditDocument(\n doc: string | DocumentHandle,\n path?: string,\n): (updater: Updater<unknown>) => Promise<ActionsResult> {\n const documentId = typeof doc === 'string' ? doc : doc._id\n const instance = useSanityInstance()\n const apply = useApplyActions()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, documentId).getCurrent() !== undefined,\n [instance, documentId],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, documentId)\n\n return useCallback(\n (updater: Updater<unknown>) => {\n if (path) {\n const nextValue =\n typeof updater === 'function'\n ? updater(getDocumentState(instance, documentId, path).getCurrent())\n : updater\n\n return apply(editDocument(documentId, {set: {[path]: nextValue}}))\n }\n\n const current = getDocumentState(instance, documentId).getCurrent()\n const nextValue = typeof updater === 'function' ? updater(current) : updater\n\n if (typeof nextValue !== 'object' || !nextValue) {\n throw new Error(\n `No path was provided to \\`useEditDocument\\` and the value provided was not a document object.`,\n )\n }\n\n const allKeys = Object.keys({...current, ...nextValue})\n const editActions = allKeys\n .filter((key) => !ignoredKeys.includes(key))\n .filter((key) => current?.[key] !== nextValue[key])\n .map((key) =>\n key in nextValue\n ? editDocument(documentId, {set: {[key]: nextValue[key]}})\n : editDocument(documentId, {unset: [key]}),\n )\n\n return apply(editActions)\n },\n [apply, documentId, instance, path],\n )\n}\n","import {type DocumentAction, getPermissionsState, type PermissionsResult} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/** @beta */\nexport function usePermissions(actions: DocumentAction | DocumentAction[]): PermissionsResult {\n const instance = useSanityInstance()\n const isDocumentReady = useCallback(\n () => getPermissionsState(instance, actions).getCurrent() !== undefined,\n [actions, instance],\n )\n if (!isDocumentReady()) {\n throw firstValueFrom(\n getPermissionsState(instance, actions).observable.pipe(\n filter((result) => result !== undefined),\n ),\n )\n }\n\n const {subscribe, getCurrent} = useMemo(\n () => getPermissionsState(instance, actions),\n [actions, instance],\n )\n\n return useSyncExternalStore(subscribe, getCurrent) as PermissionsResult\n}\n","import {createDocumentListStore, type DocumentHandle, type DocumentListOptions} from '@sanity/sdk'\nimport {useCallback, useEffect, useState, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * A live collection of {@link DocumentHandle}s, along with metadata about the collection and a function for loading more of them.\n * @category Types\n */\nexport interface DocumentHandleCollection {\n /** Retrieve more documents matching the provided options */\n loadMore: () => void\n /** The retrieved document handles of the documents matching the provided options */\n results: DocumentHandle[]\n /** Whether a retrieval of documents is in flight */\n isPending: boolean\n /** Whether more documents exist that match the provided options than have been retrieved */\n hasMore: boolean\n /** The total number of documents in the collection */\n count: number\n}\n\ntype DocumentListStore = ReturnType<typeof createDocumentListStore>\ntype DocumentListState = ReturnType<DocumentListStore['getState']>['getCurrent']\nconst STABLE_EMPTY = {\n results: [],\n isPending: false,\n hasMore: false,\n count: 0,\n}\n\n/**\n * @public\n *\n * Retrieves and provides access to a live collection of {@link DocumentHandle}s, with an optional filter and sort applied.\n * The returned document handles are canonical — that is, they refer to the document in its current state, whether draft, published, or within a release or perspective.\n * Because the returned document handle collection is live, the results will update in real time until the component invoking the hook is unmounted.\n *\n * @remarks\n * {@link DocumentHandle}s are used by many other hooks (such as {@link usePreview}, {@link useDocument}, and {@link useEditDocument})\n * to work with documents in various ways without the entire document needing to be fetched upfront.\n *\n * @category Documents\n * @param options - Options for narrowing and sorting the document collection\n * @returns The collection of document handles matching the provided options (if any), as well as properties describing the collection and a function to load more.\n *\n * @example Retrieving document handles for all documents of type 'movie'\n * ```\n * const { results, isPending } = useDocuments({ filter: '_type == \"movie\"' })\n *\n * return (\n * <div>\n * <h1>Movies</h1>\n * {results && (\n * <ul>\n * {results.map(movie => (<li key={movie._id}>…</li>))}\n * </ul>\n * )}\n * {isPending && <div>Loading movies…</div>}\n * </div>\n * )\n * ```\n *\n * @example Retrieving document handles for all movies released since 1980, sorted by director’s last name\n * ```\n * const { results } = useDocuments({\n * filter: '_type == \"movie\" && releaseDate >= \"1980-01-01\"',\n * sort: [\n * {\n * // Expand the `director` reference field with the dereferencing operator `->`\n * field: 'director->lastName',\n * sort: 'asc',\n * },\n * ],\n * })\n *\n * return (\n * <div>\n * <h1>Movies released since 1980</h1>\n * {results && (\n * <ol>\n * {results.map(movie => (<li key={movie._id}>…</li>))}\n * </ol>\n * )}\n * </div>\n * )\n * ```\n */\nexport function useDocuments(options: DocumentListOptions = {}): DocumentHandleCollection {\n const instance = useSanityInstance()\n\n // NOTE: useState is used because it guaranteed to return a stable reference\n // across renders\n const [ref] = useState<{\n storeInstance: DocumentListStore | null\n getCurrent: DocumentListState\n initialOptions: DocumentListOptions\n }>(() => ({\n storeInstance: null,\n getCurrent: () => STABLE_EMPTY,\n initialOptions: options,\n }))\n\n // serialize options to ensure it only calls `setOptions` when the values\n // themselves changes (in cases where devs put config inline)\n const serializedOptions = JSON.stringify(options)\n useEffect(() => {\n ref.storeInstance?.setOptions(JSON.parse(serializedOptions))\n }, [ref, serializedOptions])\n\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n // to match the lifecycle of `useSyncExternalState`, we create the store\n // instance after subscribe and mutate the ref to connect everything\n ref.storeInstance = createDocumentListStore(instance)\n ref.storeInstance.setOptions(ref.initialOptions)\n const state = ref.storeInstance.getState()\n ref.getCurrent = state.getCurrent\n const unsubscribe = state.subscribe(onStoreChanged)\n\n return () => {\n // unsubscribe to clean up the state subscriptions\n unsubscribe()\n // dispose of the instance\n ref.storeInstance?.dispose()\n }\n },\n [instance, ref],\n )\n\n const getSnapshot = useCallback(() => {\n return ref.getCurrent()\n }, [ref])\n\n const state = useSyncExternalStore(subscribe, getSnapshot)\n\n const loadMore = useCallback(() => {\n ref.storeInstance?.loadMore()\n }, [ref])\n\n return {loadMore, ...state}\n}\n","import {type DocumentHandle, getPreviewState, type PreviewValue, resolvePreview} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @beta\n * @category Types\n */\nexport interface UsePreviewOptions {\n document: DocumentHandle\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @beta\n * @category Types\n */\nexport interface UsePreviewResults {\n /** The results of resolving the document’s preview values */\n results: PreviewValue\n /** True when preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @beta\n *\n * Returns the preview values of a document (specified via a `DocumentHandle`),\n * including the document’s `title`, `subtitle`, `media`, and `status`. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the preview values, an optional `ref` can be passed to the hook so that preview\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * @category Documents\n * @param options - The document handle for the document you want to resolve preview values for, and an optional ref\n * @returns The preview values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Combining with useDocuments to render a collection of document previews\n * ```\n * // PreviewComponent.jsx\n * export default function PreviewComponent({ document }) {\n * const { results: { title, subtitle, media }, isPending } = usePreview({ document })\n * return (\n * <article style={{ opacity: isPending ? 0.5 : 1}}>\n * {media?.type === 'image-asset' ? <img src={media.url} alt='' /> : ''}\n * <h2>{title}</h2>\n * <p>{subtitle}</p>\n * </article>\n * )\n * }\n *\n * // DocumentList.jsx\n * const { results, isPending } = useDocuments({ filter: '_type == \"movie\"' })\n * return (\n * <div>\n * <h1>Movies</h1>\n * <ul>\n * {isPending ? 'Loading…' : results.map(movie => (\n * <li key={movie._id}>\n * <Suspense fallback='Loading…'>\n * <PreviewComponent document={movie} />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function usePreview({document: {_id, _type}, ref}: UsePreviewOptions): UsePreviewResults {\n const instance = useSanityInstance()\n\n const stateSource = useMemo(\n () => getPreviewState(instance, {document: {_id, _type}}),\n [instance, _id, _type],\n )\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // for environments that don't have an intersection observer\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n // Create getSnapshot function to return current state\n const getSnapshot = useCallback(() => {\n const currentState = stateSource.getCurrent()\n if (currentState.results === null) throw resolvePreview(instance, {document: {_id, _type}})\n return currentState as UsePreviewResults\n }, [_id, _type, instance, stateSource])\n\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n","var A=async(t,r)=>{let e=typeof r==\"function\"?await r(t):r;if(e)return t.scheme===\"bearer\"?`Bearer ${e}`:t.scheme===\"basic\"?`Basic ${btoa(e)}`:e},R={bodySerializer:t=>JSON.stringify(t,(r,e)=>typeof e==\"bigint\"?e.toString():e)},k=t=>{switch(t){case \"label\":return \".\";case \"matrix\":return \";\";case \"simple\":return \",\";default:return \"&\"}},_=t=>{switch(t){case \"form\":return \",\";case \"pipeDelimited\":return \"|\";case \"spaceDelimited\":return \"%20\";default:return \",\"}},D=t=>{switch(t){case \"label\":return \".\";case \"matrix\":return \";\";case \"simple\":return \",\";default:return \"&\"}},q=({allowReserved:t,explode:r,name:e,style:i,value:a})=>{if(!r){let s=(t?a:a.map(l=>encodeURIComponent(l))).join(_(i));switch(i){case \"label\":return `.${s}`;case \"matrix\":return `;${e}=${s}`;case \"simple\":return s;default:return `${e}=${s}`}}let o=k(i),n=a.map(s=>i===\"label\"||i===\"simple\"?t?s:encodeURIComponent(s):y({allowReserved:t,name:e,value:s})).join(o);return i===\"label\"||i===\"matrix\"?o+n:n},y=({allowReserved:t,name:r,value:e})=>{if(e==null)return \"\";if(typeof e==\"object\")throw new Error(\"Deeply-nested arrays/objects aren\\u2019t supported. Provide your own `querySerializer()` to handle these.\");return `${r}=${t?e:encodeURIComponent(e)}`},S=({allowReserved:t,explode:r,name:e,style:i,value:a})=>{if(a instanceof Date)return `${e}=${a.toISOString()}`;if(i!==\"deepObject\"&&!r){let s=[];Object.entries(a).forEach(([f,u])=>{s=[...s,f,t?u:encodeURIComponent(u)];});let l=s.join(\",\");switch(i){case \"form\":return `${e}=${l}`;case \"label\":return `.${l}`;case \"matrix\":return `;${e}=${l}`;default:return l}}let o=D(i),n=Object.entries(a).map(([s,l])=>y({allowReserved:t,name:i===\"deepObject\"?`${e}[${s}]`:s,value:l})).join(o);return i===\"label\"||i===\"matrix\"?o+n:n};var H=/\\{[^{}]+\\}/g,B=({path:t,url:r})=>{let e=r,i=r.match(H);if(i)for(let a of i){let o=false,n=a.substring(1,a.length-1),s=\"simple\";n.endsWith(\"*\")&&(o=true,n=n.substring(0,n.length-1)),n.startsWith(\".\")?(n=n.substring(1),s=\"label\"):n.startsWith(\";\")&&(n=n.substring(1),s=\"matrix\");let l=t[n];if(l==null)continue;if(Array.isArray(l)){e=e.replace(a,q({explode:o,name:n,style:s,value:l}));continue}if(typeof l==\"object\"){e=e.replace(a,S({explode:o,name:n,style:s,value:l}));continue}if(s===\"matrix\"){e=e.replace(a,`;${y({name:n,value:l})}`);continue}let f=encodeURIComponent(s===\"label\"?`.${l}`:l);e=e.replace(a,f);}return e},E=({allowReserved:t,array:r,object:e}={})=>a=>{let o=[];if(a&&typeof a==\"object\")for(let n in a){let s=a[n];if(s!=null){if(Array.isArray(s)){o=[...o,q({allowReserved:t,explode:true,name:n,style:\"form\",value:s,...r})];continue}if(typeof s==\"object\"){o=[...o,S({allowReserved:t,explode:true,name:n,style:\"deepObject\",value:s,...e})];continue}o=[...o,y({allowReserved:t,name:n,value:s})];}}return o.join(\"&\")},P=t=>{if(!t)return \"stream\";let r=t.split(\";\")[0]?.trim();if(r){if(r.startsWith(\"application/json\")||r.endsWith(\"+json\"))return \"json\";if(r===\"multipart/form-data\")return \"formData\";if([\"application/\",\"audio/\",\"image/\",\"video/\"].some(e=>r.startsWith(e)))return \"blob\";if(r.startsWith(\"text/\"))return \"text\"}},I=async({security:t,...r})=>{for(let e of t){let i=await A(e,r.auth);if(!i)continue;let a=e.name??\"Authorization\";switch(e.in){case \"query\":r.query||(r.query={}),r.query[a]=i;break;case \"header\":default:r.headers.set(a,i);break}return}},O=t=>W({baseUrl:t.baseUrl??\"\",path:t.path,query:t.query,querySerializer:typeof t.querySerializer==\"function\"?t.querySerializer:E(t.querySerializer),url:t.url}),W=({baseUrl:t,path:r,query:e,querySerializer:i,url:a})=>{let o=a.startsWith(\"/\")?a:`/${a}`,n=t+o;r&&(n=B({path:r,url:n}));let s=e?i(e):\"\";return s.startsWith(\"?\")&&(s=s.substring(1)),s&&(n+=`?${s}`),n},C=(t,r)=>{let e={...t,...r};return e.baseUrl?.endsWith(\"/\")&&(e.baseUrl=e.baseUrl.substring(0,e.baseUrl.length-1)),e.headers=x(t.headers,r.headers),e},x=(...t)=>{let r=new Headers;for(let e of t){if(!e||typeof e!=\"object\")continue;let i=e instanceof Headers?e.entries():Object.entries(e);for(let[a,o]of i)if(o===null)r.delete(a);else if(Array.isArray(o))for(let n of o)r.append(a,n);else o!==undefined&&r.set(a,typeof o==\"object\"?JSON.stringify(o):o);}return r},h=class{_fns;constructor(){this._fns=[];}clear(){this._fns=[];}exists(r){return this._fns.indexOf(r)!==-1}eject(r){let e=this._fns.indexOf(r);e!==-1&&(this._fns=[...this._fns.slice(0,e),...this._fns.slice(e+1)]);}use(r){this._fns=[...this._fns,r];}},v=()=>({error:new h,request:new h,response:new h}),N=E({allowReserved:false,array:{explode:true,style:\"form\"},object:{explode:true,style:\"deepObject\"}}),Q={\"Content-Type\":\"application/json\"},w=(t={})=>({...R,baseUrl:\"\",headers:Q,parseAs:\"auto\",querySerializer:N,...t});var J=(t={})=>{let r=C(w(),t),e=()=>({...r}),i=n=>(r=C(r,n),e()),a=v(),o=async n=>{let s={...r,...n,fetch:n.fetch??r.fetch??globalThis.fetch,headers:x(r.headers,n.headers)};s.security&&await I({...s,security:s.security}),s.body&&s.bodySerializer&&(s.body=s.bodySerializer(s.body)),s.body||s.headers.delete(\"Content-Type\");let l=O(s),f={redirect:\"follow\",...s},u=new Request(l,f);for(let p of a.request._fns)u=await p(u,s);let $=s.fetch,c=await $(u);for(let p of a.response._fns)c=await p(c,u,s);let m={request:u,response:c};if(c.ok){if(c.status===204||c.headers.get(\"Content-Length\")===\"0\")return {data:{},...m};let p=(s.parseAs===\"auto\"?P(c.headers.get(\"Content-Type\")):s.parseAs)??\"json\";if(p===\"stream\")return {data:c.body,...m};let b=await c[p]();return p===\"json\"&&(s.responseValidator&&await s.responseValidator(b),s.responseTransformer&&(b=await s.responseTransformer(b))),{data:b,...m}}let g=await c.text();try{g=JSON.parse(g);}catch{}let d=g;for(let p of a.error._fns)d=await p(g,c,u,s);if(d=d||{},s.throwOnError)throw d;return {error:d,...m}};return {buildUrl:O,connect:n=>o({...n,method:\"CONNECT\"}),delete:n=>o({...n,method:\"DELETE\"}),get:n=>o({...n,method:\"GET\"}),getConfig:e,head:n=>o({...n,method:\"HEAD\"}),interceptors:a,options:n=>o({...n,method:\"OPTIONS\"}),patch:n=>o({...n,method:\"PATCH\"}),post:n=>o({...n,method:\"POST\"}),put:n=>o({...n,method:\"PUT\"}),request:o,setConfig:i,trace:n=>o({...n,method:\"TRACE\"})}};\n\n// This file is auto-generated by @hey-api/openapi-ts\nconst client = J(w({\n throwOnError: true\n}));\n\n// This file is auto-generated by @hey-api/openapi-ts\n/**\n * Get Permissions.\n * Gets the available permissions within the scope of a resource. These permissions can be applied to roles and are used to determine user/robot access to resources. <br /> <br /> Requires permission: `sanity.{resourceType}.roles.read`\n *\n */\nconst getPermissions = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/permissions' }, options));\n};\n/**\n * Create a permission.\n * Creates a custom permission on a resource. <br /> <br /> Requires permission: `sanity.{resourceType}.roles.create` <br /> Requires feature: `advancedRolesManagement` <br /> <br /> See Example. It creates a permission to allow a user to read legal documents in project `c7ja4siy` and dataset `production`.\n *\n */\nconst createPermission = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).post(Object.assign(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/permissions' }, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));\n};\n/**\n * Delete a permission\n * Deletes a specific permission for a resource. Can only be used with custom permissions. Requires permission\n * - `sanity.{resourceType}.roles.delete`\n * Requires feature:\n * - `advancedRolesManagement`\n *\n */\nconst deletePermission = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).delete(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/permissions/{permissionName}' }, options));\n};\n/**\n * Get a permission\n * Gets a permission for a resource by name. Requires permission\n * - `sanity.{resourceType}.roles.read`\n *\n */\nconst getPermission = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/permissions/{permissionName}' }, options));\n};\n/**\n * Update a permission\n * Updates a permission for a resource. Requires permission\n * - `sanity.{resourceType}.roles.update`\n * Requires feature:\n * - `advancedRolesManagement`\n *\n */\nconst updatePermission = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).put(Object.assign(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/permissions/{permissionName}' }, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));\n};\n/**\n * Get current user permissions.\n * Gets the available permissions within the scope of a resource. These permissions can be applied to roles and are used to determine user/robot access to resources.\n *\n */\nconst getMyPermissions = (options) => {\n var _a;\n return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/permissions/me' }, options));\n};\n/**\n * Get current user permissions.\n * Gets current user permissions within scope of a resource. These permissions can be applied to roles and are used to determine user/robot access to resources.\n *\n */\nconst getUserPermissions = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/user-permissions/me' }, options));\n};\n/**\n * List all users of a resource and their assigned roles.\n * Retrieve a list of all users of a resource along with their assigned roles. When the resourceType is `organization`, this endpoint will return users of projects owned by the organization. Requires permission\n * - `sanity.{resourceType}.members.read`\n *\n */\nconst getUsers = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/users' }, options));\n};\n/**\n * Apply organization default role to all users.\n * Add default role to all resource users. Limited to Organization. Requires permission\n * - `sanity.organization.members.update`\n *\n */\nconst addDefaultRoleToUsers = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).put(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/organization/{resourceId}/users/roles/default' }, options));\n};\n/**\n * Remove a user from a resource.\n * This removes all roles. If the resourceType is `organization`, this will also remove the user from all projects owned by the organization. Requires permission\n * - `sanity.{resourceType}.members.delete`\n *\n */\nconst removeUser = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).delete(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/users/{sanityUserId}' }, options));\n};\n/**\n * Get user and roles.\n * Get the users for a single user of a resource. Requires permission - `sanity.{resourceType}.members.read`\n */\nconst getUser = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/users/{sanityUserId}' }, options));\n};\n/**\n * Remove a role from a user in a resource.\n * You cannot remove the last role from a user. You must have at least one role assigned to a user. Requires permission\n * - `sanity.{resourceType}.members.update`\n *\n */\nconst removeRoleFromUser = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).delete(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/users/{sanityUserId}/roles/{roleName}' }, options));\n};\n/**\n * Add a role to a user.\n * Add a role to a user. Requires permission\n * - `sanity.{resourceType}.members.update`\n *\n */\nconst addRoleToUser = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).put(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/users/{sanityUserId}/roles/{roleName}' }, options));\n};\n/**\n * List permissions for a user\n * Normalized list of permission resources for a user across all assigned roles. Requires permissions:\n * - `sanity.{resourceType}.members.read` for resource scoped roles (e.g. project admin)\n *\n */\nconst getuserPermissions = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/users/{sanityUserId}/permissions' }, options));\n};\n/**\n * List roles assignable to a user on this resource.\n * Requires permission\n * - `sanity.{resourceType}.roles.read`\n *\n */\nconst getRoles = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/roles' }, options));\n};\n/**\n * Create a role\n * Requires permission:\n * - `sanity.{resourceType}.roles.create`\n * Requires feature:\n * - `advancedRolesManagement`\n *\n */\nconst createRole = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).post(Object.assign(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/roles' }, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));\n};\n/**\n * Delete a role\n * Requires permission:\n * - `sanity.{resourceType}.roles.delete` for resource scoped roles (e.g. project admin)\n *\n * Requires feature:\n * - `advancedRolesManagement`\n *\n * Cannot delete a role that is assigned to a user. The role needs to be removed from users first.\n *\n */\nconst deleteRole = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).delete(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/roles/{roleName}' }, options));\n};\n/**\n * Get a role\n * Requires permission\n * - `sanity.{resourceType}.roles.read`\n *\n */\nconst getRole = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/roles/{roleName}' }, options));\n};\n/**\n * Update a role\n * Requires permission:\n * - `sanity.{resourceType}.roles.update`\n *\n * Requires feature:\n * - `advancedRolesManagement`\n *\n * Replaces existing object values including permissions.\n *\n */\nconst updateRole = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).put(Object.assign(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/roles/{roleName}' }, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));\n};\n/**\n * List all requests for given project/organization.\n * Permissions `sanity.{resourceType}.members.read`\n */\nconst getRequests = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/v2024-07-01/access/{resourceType}/{resourceId}/requests' }, options));\n};\n/**\n * Create a new Request\n * Creates a new request for the given project/organization. Requires an authenticated user.\n */\nconst createRequest = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).post(Object.assign(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/v2024-07-01/access/{resourceType}/{resourceId}/requests' }, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));\n};\n/**\n * Accept request\n * Permissions `sanity.{resourceType}.members.invite`\n */\nconst acceptRequest = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).put(Object.assign(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/v2024-07-01/access/{resourceType}/{resourceId}/requests/{requestId}/accept' }, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));\n};\n/**\n * Decline request\n * Permissions `sanity.{resourceType}.members.invite`\n */\nconst declineRequest = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).put(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/v2024-07-01/access/{resourceType}/{resourceId}/requests/{requestId}/decline' }, options));\n};\n/**\n * List all request for current user\n * Requires an authenticated user.\n */\nconst getMyRequests = (options) => {\n var _a;\n return ((_a = options === null || options === void 0 ? void 0 : options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/v2024-07-01/access/requests/me' }, options));\n};\n/**\n * Get invites\n * Retrieves a list of invites for the specified resource.\n *\n * Only pending invites are retrieved by default. Use the optional `status`\n * parameter to change the filter behavior. You can select multiple\n * statuses by repeating the parameter.\n *\n * ### Children invites\n *\n * By default, only invites for the specified resource are returned. Use the\n * optional `includeChildren` parameter to include invites for children\n * resources as well. This only applies to `organization` resources.\n *\n * ### Authorization\n *\n * This endpoint requires an authenticated user session with the following\n * permissions:\n * - `sanity.{resourceType}.members.read`\n *\n */\nconst getInvites = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/invites' }, options));\n};\n/**\n * Create invite\n * Creates an invite for the specified resource.\n *\n * The invitee will receive an email with a link to accept the invite.\n *\n * Each invitee can only receive one invite per resource and role.\n * Attempting to create an invite using a non-existent role, or a role that\n * cannot be granted to users will result in a Bad Request error.\n *\n * ### Unavailable resources\n *\n * If the underlying resource is unavailable then a Bad Request error will\n * be returned. A common example of an unavailable resource is a project\n * that is blocked or archived.\n *\n * ### Authorization\n *\n * This endpoint requires an authenticated user session with the following\n * permissions:\n * - `sanity.{resourceType}.members.invite`\n *\n * Additionally, only administrators can invite other administrators.\n *\n */\nconst createInvite = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).post(Object.assign(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/invites' }, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));\n};\n/**\n * Revoke invite\n * Revokes an invite.\n *\n * Attempting to revoke an invite that has already been accepted or revoked\n * will result in a Bad Request error.\n *\n * ### Authorization\n *\n * This endpoint requires an authenticated user session with the following\n * permissions:\n * - `sanity.{resourceType}.members.invite`\n *\n */\nconst revokeInvite = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).delete(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/invites/{inviteId}' }, options));\n};\n/**\n * Get invite\n * Retrieves an invite using its token.\n *\n * ### Authorization\n *\n * This endpoint does not require authentication.\n *\n */\nconst getInviteByToken = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/invites/token/{inviteToken}' }, options));\n};\n/**\n * Accept invite\n * Accepts an invite using its token.\n *\n * Attempting to accept an invite that is already accepted or revoked will\n * result in a Bad Request error.\n *\n * Once the invite has been accepted, the user will have access to the\n * resource with the role assigned as part of the invitation.\n *\n * > **Access is propagated internally and may take a up to a few minutes to\n * > be fully available across all systems.**\n *\n * ### Unavailable resources\n *\n * If the underlying resource is unavailable then a Bad Request error will\n * be returned. A common example of an unavailable resource is a project\n * that is blocked or archived.\n *\n * ### Member quota\n *\n * Some resources have a limit on the number of members. If accepting an\n * invite would go over this limit, then a Payment Required error is\n * returned.\n *\n * ### Authorization\n *\n * This endpoint requires an authenticated user session.\n *\n */\nconst acceptInvite = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).post(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/invites/token/{inviteToken}/accept' }, options));\n};\n/**\n * Get robots with access to this resource\n * Retrieves a list of robots that have access to the specified resource.\n *\n * ### Access to children resources\n *\n * By default, this endpoint returns robots that have at least one role on\n * the specified resource. Use the optional `includeChildren` parameter to\n * include robots that have a role on children resources as well. This\n * only applies to `organization` resources.\n *\n * ### Authorization\n *\n * This endpoint requires an authenticated user session with the following\n * permissions:\n * - `sanity.{resourceType}.tokens.read`\n *\n */\nconst getRobots = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/robots' }, options));\n};\n/**\n * Create robot and associated token\n * Creates a robot with the specified role grants and returns its secret\n * token.\n *\n * The API currently only supports organization-scoped robots. This means\n * that `organization` must be provided to the `resourceType` parameter.\n *\n * Only the specified resource and its children resources can be specified\n * in the role grants. The robot will not have access to other resources.\n *\n * ### Secret token\n *\n * The secret token is only returned once and can not be retrieved again.\n * If the token is lost, a new robot must be created. The previous robot\n * should be deleted.\n *\n * ### Authorization\n *\n * This endpoint requires an authenticated user session with the following\n * permissions:\n * - `sanity.{resourceType}.tokens.create`\n *\n */\nconst createRobot = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).post(Object.assign(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/robots' }, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers) }));\n};\n/**\n * Delete robot and associated token\n * Deletes a robot and revokes its token.\n *\n * ### Authorization\n *\n * This endpoint requires an authenticated user session with the following\n * permissions:\n * - `sanity.{resourceType}.tokens.delete`\n *\n */\nconst deleteRobot = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).delete(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/robots/{robotId}' }, options));\n};\n/**\n * Get robot metadata\n * Retrieves a robot using its unique identifier.\n *\n * It's not possible to retrieve a robot token.\n *\n * ### Authorization\n *\n * This endpoint requires an authenticated user session with the following\n * permissions:\n * - `sanity.{resourceType}.tokens.read`\n *\n */\nconst getRobot = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/robots/{robotId}' }, options));\n};\n/**\n * Check if current user has specified permissions\n * Checks if the current user has the specified permissions for the given resource.\n * Returns an object mapping each requested permission to a boolean indicating whether the user has that permission.\n *\n */\nconst checkUserPermissions = (options) => {\n var _a;\n return ((_a = options.client) !== null && _a !== void 0 ? _a : client).get(Object.assign({ security: [\n {\n scheme: 'bearer',\n type: 'http'\n }\n ], url: '/vX/access/{resourceType}/{resourceId}/user-permissions/me/check' }, options));\n};\n\nexport { acceptInvite, acceptRequest, addDefaultRoleToUsers, addRoleToUser, checkUserPermissions, client, createInvite, createPermission, createRequest, createRobot, createRole, declineRequest, deletePermission, deleteRobot, deleteRole, getInviteByToken, getInvites, getMyPermissions, getMyRequests, getPermission, getPermissions, getRequests, getRobot, getRobots, getRole, getRoles, getUser, getUserPermissions, getUsers, getuserPermissions, removeRoleFromUser, removeUser, revokeInvite, updatePermission, updateRole };\n","import {type ResourceType, type User} from '@sanity/access-api'\nimport {createUsersStore} from '@sanity/sdk'\nimport {useCallback, useEffect, useState, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n */\ninterface UseUsersParams {\n /**\n * The type of resource to fetch users for.\n */\n resourceType: ResourceType\n /**\n * The ID of the resource to fetch users for.\n */\n resourceId: string\n /**\n * The limit of users to fetch.\n */\n limit?: number\n}\n\n/** @public */\nexport interface UseUsersResult {\n /**\n * The users fetched.\n */\n users: User[]\n /**\n * Whether there are more users to fetch.\n */\n hasMore: boolean\n /**\n * Load more users.\n */\n loadMore: () => void\n}\n\n/** @public */\nexport function useUsers(params: UseUsersParams): UseUsersResult {\n const instance = useSanityInstance()\n const [store] = useState(() => createUsersStore(instance))\n\n useEffect(() => {\n store.setOptions({\n resourceType: params.resourceType,\n resourceId: params.resourceId,\n })\n }, [params.resourceType, params.resourceId, store])\n\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n if (store.getState().getCurrent().initialFetchCompleted === false) {\n store.resolveUsers()\n }\n const unsubscribe = store.getState().subscribe(onStoreChanged)\n\n return () => {\n unsubscribe()\n store.dispose()\n }\n },\n [store],\n )\n\n const getSnapshot = useCallback(() => store.getState().getCurrent(), [store])\n\n const {users, hasMore} = useSyncExternalStore(subscribe, getSnapshot) || {}\n\n return {users, hasMore, loadMore: store.loadMore}\n}\n"],"names":["nextValue","state"],"mappings":";;;;;AASa,MAAA,eAAe,sBAAsB,aAAa,GCkBlD,iBAA2C,sBAAsB,mBAAmB;ACK1F,SAAS,UAAU,SAAsC;AACxD,QAAA,WAAW,qBAEX,YAAY;AAAA,IAChB,CAAC,kBAA8B;AAE7B,YAAM,eADU,sBAAsB,UAAU,OAAO,EAC1B,UAAU;AAAA,QACrC,MAAM;AAAA,QACN,OAAO,CAAC,UAAU;AAGR,kBAAA,MAAM,oCAAoC,KAAK;AAAA,QAAA;AAAA,MACzD,CACD;AACM,aAAA,MAAM,aAAa,YAAY;AAAA,IACxC;AAAA,IACA,CAAC,UAAU,OAAO;AAAA,EAAA,GAGd,cAAc,YAAY,MACvB,UAAU,UAAU,OAAO,G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;AAAA,EAAA,GAGF,cAAc,YAAY,MAAM,MAAM,SAAS,EAAE,cAAc,CAAC,KAAK,CAAC,GAEtE,EAAC,OAAO,YAAW,qBAAqB,WAAW,WAAW,KAAK,CAAC;AAE1E,SAAO,EAAC,OAAO,SAAS,UAAU,MAAM,SAAQ;AAClD;","x_google_ignoreList":[13]}
|
|
1
|
+
{"version":3,"file":"hooks.js","sources":["../src/hooks/auth/useAuthToken.tsx","../src/hooks/auth/useCurrentUser.tsx","../src/hooks/client/useClient.ts","../src/hooks/comlink/useFrameConnection.ts","../src/hooks/comlink/useWindowConnection.ts","../src/hooks/datasets/useDatasets.ts","../src/hooks/document/useApplyActions.ts","../src/hooks/document/useDocument.ts","../src/hooks/document/useDocumentEvent.ts","../src/hooks/document/useDocumentSyncStatus.ts","../src/hooks/document/useEditDocument.ts","../src/hooks/document/usePermissions.ts","../src/hooks/documentCollection/useDocuments.ts","../src/hooks/documentCollection/useSearch.ts","../src/hooks/preview/usePreview.tsx","../src/hooks/projects/useProject.ts","../src/hooks/projects/useProjects.ts","../src/hooks/users/useUsers.ts","../src/hooks/projection/useProjection.ts"],"sourcesContent":["import {getTokenState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * Hook to get the currently logged in user\n * @internal\n * @returns The current user or null if not authenticated\n */\nexport const useAuthToken = createStateSourceHook(getTokenState)\n","import {type CurrentUser, getCurrentUserState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseCurrentUser = {\n /**\n * @public\n *\n * Provides the currently authenticated user’s profile information.\n *\n * @category Users\n * @returns The current user data\n *\n * @example Rendering a basic user profile\n * ```\n * const user = useCurrentUser()\n *\n * return (\n * <figure>\n * <img src={user?.profileImage} alt=`Profile image for ${user?.name}` />\n * <h2>{user?.name}</h2>\n * </figure>\n * )\n * ```\n */\n (): CurrentUser | null\n}\n\n/**\n * @public\n * @TODO This should not return null — users of a custom app will always be authenticated via Core\n */\nexport const useCurrentUser: UseCurrentUser = createStateSourceHook(getCurrentUserState)\n","import {getClientState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * A React hook that provides a client that subscribes to changes in your application,\n * such as user authentication changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to changes\n * and ensure consistency between server and client rendering.\n *\n * @category Platform\n * @returns A Sanity client\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const client = useClient({apiVersion: '2024-11-12'})\n * const [document, setDocument] = useState(null)\n * useEffect(async () => {\n * const doc = client.fetch('*[_id == \"myDocumentId\"]')\n * setDocument(doc)\n * }, [])\n * return <div>{JSON.stringify(document) ?? 'Loading...'}</div>\n * }\n * ```\n *\n * @public\n */\nexport const useClient = createStateSourceHook(getClientState)\n","import {type Status} from '@sanity/comlink'\nimport {\n type FrameMessage,\n getOrCreateChannel,\n getOrCreateController,\n releaseChannel,\n type WindowMessage,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type FrameMessageHandler<TWindowMessage extends WindowMessage> = (\n event: TWindowMessage['data'],\n) => TWindowMessage['response'] | Promise<TWindowMessage['response']>\n\n/**\n * @internal\n */\nexport interface UseFrameConnectionOptions<TWindowMessage extends WindowMessage> {\n name: string\n connectTo: string\n targetOrigin: string\n onMessage?: {\n [K in TWindowMessage['type']]: (data: Extract<TWindowMessage, {type: K}>['data']) => void\n }\n heartbeat?: boolean\n}\n\n/**\n * @internal\n */\nexport interface FrameConnection<TFrameMessage extends FrameMessage> {\n connect: (frameWindow: Window) => () => void // Return cleanup function\n sendMessage: <T extends TFrameMessage['type']>(\n ...params: Extract<TFrameMessage, {type: T}>['data'] extends undefined\n ? [type: T]\n : [type: T, data: Extract<TFrameMessage, {type: T}>['data']]\n ) => void\n status: Status\n}\n\n/**\n * @internal\n */\nexport function useFrameConnection<\n TFrameMessage extends FrameMessage,\n TWindowMessage extends WindowMessage,\n>(options: UseFrameConnectionOptions<TWindowMessage>): FrameConnection<TFrameMessage> {\n const {onMessage, targetOrigin, name, connectTo, heartbeat} = options\n const instance = useSanityInstance()\n const [status, setStatus] = useState<Status>('idle')\n\n const controller = useMemo(\n () => getOrCreateController(instance, targetOrigin),\n [instance, targetOrigin],\n )\n\n const channel = useMemo(\n () =>\n getOrCreateChannel(instance, {\n name,\n connectTo,\n heartbeat,\n }),\n [instance, name, connectTo, heartbeat],\n )\n\n useEffect(() => {\n if (!channel) return\n\n const unsubscribe = channel.onStatus((event) => {\n setStatus(event.status)\n })\n\n return unsubscribe\n }, [channel])\n\n useEffect(() => {\n if (!channel || !onMessage) return\n\n const unsubscribers: Array<() => void> = []\n\n Object.entries(onMessage).forEach(([type, handler]) => {\n // type assertion, but we've already constrained onMessage to have the correct handler type\n const unsubscribe = channel.on(type, handler as FrameMessageHandler<TWindowMessage>)\n unsubscribers.push(unsubscribe)\n })\n\n return () => {\n unsubscribers.forEach((unsub) => unsub())\n }\n }, [channel, onMessage])\n\n const connect = useCallback(\n (frameWindow: Window) => {\n const removeTarget = controller?.addTarget(frameWindow)\n return () => {\n removeTarget?.()\n }\n },\n [controller],\n )\n\n const sendMessage = useCallback(\n <T extends TFrameMessage['type']>(\n type: T,\n data?: Extract<TFrameMessage, {type: T}>['data'],\n ) => {\n channel?.post(type, data)\n },\n [channel],\n )\n\n // cleanup channel on unmount\n useEffect(() => {\n return () => {\n releaseChannel(instance, name)\n }\n }, [name, instance])\n\n return {\n connect,\n sendMessage,\n status,\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {type FrameMessage, getOrCreateNode, releaseNode, type WindowMessage} from '@sanity/sdk'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type WindowMessageHandler<TFrameMessage extends FrameMessage> = (\n event: TFrameMessage['data'],\n) => TFrameMessage['response']\n\n/**\n * @internal\n */\nexport interface UseWindowConnectionOptions<TMessage extends FrameMessage> {\n name: string\n connectTo: string\n onMessage?: Record<TMessage['type'], WindowMessageHandler<TMessage>>\n}\n\n/**\n * @internal\n */\nexport interface WindowConnection<TMessage extends WindowMessage> {\n sendMessage: <TType extends TMessage['type']>(\n type: TType,\n data?: Extract<TMessage, {type: TType}>['data'],\n ) => void\n status: Status\n}\n\n/**\n * @internal\n */\nexport function useWindowConnection<\n TWindowMessage extends WindowMessage,\n TFrameMessage extends FrameMessage,\n>(options: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage> {\n const {name, onMessage, connectTo} = options\n const instance = useSanityInstance()\n const [status, setStatus] = useState<Status>('idle')\n\n const node = useMemo(\n () => getOrCreateNode(instance, {name, connectTo}),\n [instance, name, connectTo],\n )\n\n useEffect(() => {\n const unsubscribe = node.onStatus((newStatus) => {\n setStatus(newStatus)\n })\n\n return unsubscribe\n }, [node, instance, name])\n\n useEffect(() => {\n if (!onMessage) return\n\n const unsubscribers: Array<() => void> = []\n\n Object.entries(onMessage).forEach(([type, handler]) => {\n const unsubscribe = node.on(type, handler as WindowMessageHandler<TFrameMessage>)\n unsubscribers.push(unsubscribe)\n })\n\n return () => {\n unsubscribers.forEach((unsub) => unsub())\n }\n }, [node, onMessage])\n\n const sendMessage = useCallback(\n <TType extends WindowMessage['type']>(\n type: TType,\n data?: Extract<WindowMessage, {type: TType}>['data'],\n ) => {\n node?.post(type, data)\n },\n [node],\n )\n\n // cleanup node on unmount\n useEffect(() => {\n return () => {\n releaseNode(instance, name)\n }\n }, [instance, name])\n\n return {\n sendMessage,\n status,\n }\n}\n","import {type DatasetsResponse} from '@sanity/client'\nimport {getDatasetsState, resolveDatasets, type SanityInstance, type StateSource} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/** @public */\nexport const useDatasets = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getDatasetsState as (instance: SanityInstance) => StateSource<DatasetsResponse>,\n shouldSuspend: (instance) => getDatasetsState(instance).getCurrent() === undefined,\n suspender: resolveDatasets,\n})\n","import {\n type ActionsResult,\n applyActions,\n type ApplyActionsOptions,\n type DocumentAction,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n *\n * @beta\n *\n * Provides a callback for applying one or more actions to a document.\n *\n * @category Documents\n * @returns A function that takes one more more {@link DocumentAction}s and returns a promise that resolves to an {@link ActionsResult}.\n * @example Publish or unpublish a document\n * ```\n * import { publishDocument, unpublishDocument } from '@sanity/sdk'\n * import { useApplyActions } from '@sanity/sdk-react'\n *\n * const apply = useApplyActions()\n * const myDocument = { _id: 'my-document-id', _type: 'my-document-type' }\n *\n * return (\n * <button onClick={() => apply(publishDocument(myDocument))}>Publish</button>\n * <button onClick={() => apply(unpublishDocument(myDocument))}>Unpublish</button>\n * )\n * ```\n *\n * @example Create and publish a new document\n * ```\n * import { createDocument, publishDocument } from '@sanity/sdk'\n * import { useApplyActions } from '@sanity/sdk-react'\n *\n * const apply = useApplyActions()\n *\n * const handleCreateAndPublish = () => {\n * const handle = { _id: window.crypto.randomUUID(), _type: 'my-document-type' }\n * apply([\n * createDocument(handle),\n * publishDocument(handle),\n * ])\n * }\n *\n * return (\n * <button onClick={handleCreateAndPublish}>\n * I’m feeling lucky\n * </button>\n * )\n * ```\n */\nexport function useApplyActions(): <TDocument extends SanityDocument>(\n action: DocumentAction<TDocument> | DocumentAction<TDocument>[],\n options?: ApplyActionsOptions,\n) => Promise<ActionsResult<TDocument>>\n\n/** @beta */\nexport function useApplyActions(): (\n action: DocumentAction | DocumentAction[],\n options?: ApplyActionsOptions,\n) => Promise<ActionsResult> {\n return _useApplyActions()\n}\n\nconst _useApplyActions = createCallbackHook(applyActions)\n","import {\n type DocumentHandle,\n getDocumentState,\n getResourceId,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n type ResourceId,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @beta\n *\n * ## useDocument(doc, path)\n * Read and subscribe to nested values in a document\n * @category Documents\n * @param doc - The document to read state from\n * @param path - The path to the nested value to read from\n * @returns The value at the specified path\n * @example\n * ```tsx\n * import {type DocumentHandle, useDocument} from '@sanity/sdk-react'\n *\n * function OrderLink({documentHandle}: {documentHandle: DocumentHandle}) {\n * const title = useDocument(documentHandle, 'title')\n * const id = useDocument(documentHandle, '_id')\n *\n * return (\n * <a href=`/order/${id}`>Order {title} today!</a>\n * )\n * }\n * ```\n *\n */\nexport function useDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(doc: DocumentHandle<TDocument>, path: TPath): JsonMatch<TDocument, TPath> | undefined\n\n/**\n * @beta\n * ## useDocument(doc)\n * Read and subscribe to an entire document\n * @param doc - The document to read state from\n * @returns The document state as an object\n * @example\n * ```tsx\n * import {type SanityDocument, type DocumentHandle, useDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument {\n * title: string\n * author: string\n * summary: string\n * }\n *\n * function DocumentView({documentHandle}: {documentHandle: DocumentHandle}) {\n * const book = useDocument<Book>(documentHandle)\n *\n * return (\n * <article>\n * <h1>{book?.title}</h1>\n * <address>By {book?.author}</address>\n *\n * <h2>Summary</h2>\n * {book?.summary}\n *\n * <h2>Order</h2>\n * <a href=`/order/${book._id}`>Order {book?.title} today!</a>\n * </article>\n * )\n * }\n * ```\n *\n */\nexport function useDocument<TDocument extends SanityDocument>(\n doc: DocumentHandle<TDocument>,\n): TDocument | null\n\n/**\n * @beta\n * Reads and subscribes to a document’s realtime state, incorporating both local and remote changes.\n * When called with a `path` argument, the hook will return the nested value’s state.\n * When called without a `path` argument, the entire document’s state will be returned.\n *\n * @remarks\n * `useDocument` is designed to be used within a realtime context in which local updates to documents\n * need to be displayed before they are persisted to the remote copy. This can be useful within a collaborative\n * or realtime editing interface where local changes need to be reflected immediately.\n *\n * However, this hook can be too resource intensive for applications where static document values simply\n * need to be displayed (or when changes to documents don’t need to be reflected immediately);\n * consider using `usePreview` or `useQuery` for these use cases instead. These hooks leverage the Sanity\n * Live Content API to provide a more efficient way to read and subscribe to document state.\n */\nexport function useDocument(doc: DocumentHandle, path?: string): unknown {\n return _useDocument(doc, path)\n}\n\nconst _useDocument = createStateSourceHook<[doc: DocumentHandle, path?: string], unknown>({\n getState: getDocumentState,\n shouldSuspend: (instance, doc) => getDocumentState(instance, doc._id).getCurrent() === undefined,\n suspender: resolveDocument,\n getResourceId: (doc) => getResourceId(doc.resourceId) as ResourceId,\n})\n","import {\n type DocumentEvent,\n type DocumentHandle,\n getResourceId,\n subscribeDocumentEvents,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useInsertionEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n *\n * @beta\n *\n * Subscribes an event handler to events in your application’s document store, such as document\n * creation, deletion, and updates.\n *\n * @category Documents\n * @param handler - The event handler to register.\n * @example\n * ```\n * import {useDocumentEvent} from '@sanity/sdk-react'\n * import {type DocumentEvent} from '@sanity/sdk'\n *\n * useDocumentEvent((event) => {\n * if (event.type === DocumentEvent.DocumentDeletedEvent) {\n * alert(`Document with ID ${event.documentId} deleted!`)\n * } else {\n * console.log(event)\n * }\n * })\n * ```\n */\nexport function useDocumentEvent(\n handler: (documentEvent: DocumentEvent) => void,\n doc: DocumentHandle,\n): void {\n const ref = useRef(handler)\n\n useInsertionEffect(() => {\n ref.current = handler\n })\n\n const stableHandler = useCallback((documentEvent: DocumentEvent) => {\n return ref.current(documentEvent)\n }, [])\n\n const instance = useSanityInstance(getResourceId(doc.resourceId))\n useEffect(() => {\n return subscribeDocumentEvents(instance, stableHandler)\n }, [instance, stableHandler])\n}\n","import {type DocumentHandle, getDocumentSyncStatus} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseDocumentSyncStatus = {\n /**\n * Exposes the document’s sync status between local and remote document states.\n *\n * @category Documents\n * @param doc - The document handle to get sync status for\n * @returns `true` if local changes are synced with remote, `false` if the changes are not synced, and `undefined` if the document is not found\n * @example Disable a Save button when there are no changes to sync\n * ```\n * const myDocumentHandle = { _id: 'documentId', _type: 'documentType', resourceId: 'document:projectId:dataset:documentId' }\n * const documentSynced = useDocumentSyncStatus(myDocumentHandle)\n *\n * return (\n * <button disabled={documentSynced}>\n * Save Changes\n * </button>\n * )\n * ```\n */\n (doc: DocumentHandle): boolean | undefined\n}\n\n/** @beta */\nexport const useDocumentSyncStatus: UseDocumentSyncStatus =\n createStateSourceHook(getDocumentSyncStatus)\n","import {\n type ActionsResult,\n type DocumentHandle,\n editDocument,\n getDocumentState,\n getResourceId,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useApplyActions} from './useApplyActions'\n\nconst ignoredKeys = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']\n\ntype Updater<TValue> = TValue | ((nextValue: TValue) => TValue)\n\n/**\n *\n * @beta\n *\n * ## useEditDocument(doc, path)\n * Edit a nested value within a document\n *\n * @category Documents\n * @param doc - The document to be edited; either as a document handle or the document’s ID a string\n * @param path - The path to the nested value to be edited\n * @returns A function to update the nested value. Accepts either a new value, or an updater function that exposes the previous value and returns a new value.\n * @example Update a document’s name by providing the new value directly\n * ```\n * const handle = { _id: 'documentId', _type: 'documentType' }\n * const name = useDocument(handle, 'name')\n * const editName = useEditDocument(handle, 'name')\n *\n * function handleNameChange(event: React.ChangeEvent<HTMLInputElement>) {\n * editName(event.target.value)\n * }\n *\n * return (\n * <input type='text' value={name} onChange={handleNameChange} />\n * )\n * ```\n *\n * @example Update a count on a document by providing an updater function\n * ```\n * const handle = { _id: 'documentId', _type: 'documentType' }\n * const count = useDocument(handle, 'count')\n * const editCount = useEditDocument(handle, 'count')\n *\n * function incrementCount() {\n * editCount(previousCount => previousCount + 1)\n * }\n *\n * return (\n * <>\n * <button onClick={incrementCount}>\n * Increment\n * </button>\n * Current count: {count}\n * </>\n * )\n * ```\n */\nexport function useEditDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(\n doc: DocumentHandle<TDocument>,\n path: TPath,\n): (nextValue: Updater<JsonMatch<TDocument, TPath>>) => Promise<ActionsResult<TDocument>>\n\n/**\n *\n * @beta\n *\n * ## useEditDocument(doc)\n * Edit an entire document\n * @param doc - The document to be edited; either as a document handle or the document’s ID a string\n * @returns A function to update the document state. Accepts either a new document state, or an updater function that exposes the previous document state and returns the new document state.\n * @example\n * ```\n * const myDocumentHandle = { _id: 'documentId', _type: 'documentType' }\n *\n * const myDocument = useDocument(myDocumentHandle)\n * const { title, price } = myDocument\n *\n * const editMyDocument = useEditDocument(myDocumentHandle)\n *\n * function handleFieldChange(e: React.ChangeEvent<HTMLInputElement>) {\n * const {name, value} = e.currentTarget\n * // Use an updater function to update the document state based on the previous state\n * editMyDocument(previousDocument => ({\n * ...previousDocument,\n * [name]: value\n * }))\n * }\n *\n * function handleSaleChange(e: React.ChangeEvent<HTMLInputElement>) {\n * const { checked } = e.currentTarget\n * if (checked) {\n * // Use an updater function to add a new salePrice field;\n * // set it at a 20% discount off the normal price\n * editMyDocument(previousDocument => ({\n * ...previousDocument,\n * salePrice: previousDocument.price * 0.8,\n * }))\n * } else {\n * // Get the document state without the salePrice field\n * const { salePrice, ...rest } = myDocument\n * // Update the document state to remove the salePrice field\n * editMyDocument(rest)\n * }\n * }\n *\n * return (\n * <>\n * <form onSubmit={e => e.preventDefault()}>\n * <input name='title' type='text' value={title} onChange={handleFieldChange} />\n * <input name='price' type='number' value={price} onChange={handleFieldChange} />\n * <input\n * name='salePrice'\n * type='checkbox'\n * checked={Object(myDocument).hasOwnProperty('salePrice')}\n * onChange={handleSaleChange}\n * />\n * </form>\n * <pre><code>\n * {JSON.stringify(myDocument, null, 2)}\n * </code></pre>\n * </>\n * )\n * ```\n */\nexport function useEditDocument<TDocument extends SanityDocument>(\n doc: DocumentHandle<TDocument>,\n): (nextValue: Updater<TDocument>) => Promise<ActionsResult<TDocument>>\n\n/**\n *\n * @beta\n *\n * Enables editing of a document’s state.\n * When called with a `path` argument, the hook will return a function for updating a nested value.\n * When called without a `path` argument, the hook will return a function for updating the entire document.\n */\nexport function useEditDocument(\n doc: DocumentHandle,\n path?: string,\n): (updater: Updater<unknown>) => Promise<ActionsResult> {\n const documentId = doc._id\n const instance = useSanityInstance(getResourceId(doc.resourceId))\n const apply = useApplyActions()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, documentId).getCurrent() !== undefined,\n [instance, documentId],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, documentId)\n\n return useCallback(\n (updater: Updater<unknown>) => {\n if (path) {\n const nextValue =\n typeof updater === 'function'\n ? updater(getDocumentState(instance, documentId, path).getCurrent())\n : updater\n\n return apply(editDocument(doc, {set: {[path]: nextValue}}))\n }\n\n const current = getDocumentState(instance, documentId).getCurrent()\n const nextValue = typeof updater === 'function' ? updater(current) : updater\n\n if (typeof nextValue !== 'object' || !nextValue) {\n throw new Error(\n `No path was provided to \\`useEditDocument\\` and the value provided was not a document object.`,\n )\n }\n\n const allKeys = Object.keys({...current, ...nextValue})\n const editActions = allKeys\n .filter((key) => !ignoredKeys.includes(key))\n .filter((key) => current?.[key] !== nextValue[key])\n .map((key) =>\n key in nextValue\n ? editDocument(doc, {set: {[key]: nextValue[key]}})\n : editDocument(doc, {unset: [key]}),\n )\n\n return apply(editActions)\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [apply, doc._id, instance, path],\n )\n}\n","import {\n type DocumentAction,\n getPermissionsState,\n getResourceId,\n type PermissionsResult,\n} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n *\n * @beta\n *\n * Check if the current user has the specified permissions for the given document actions.\n *\n * @category Permissions\n * @param actions - One more more calls to a particular document action function for a given document\n * @returns An object that specifies whether the action is allowed; if the action is not allowed, an explanatory message and list of reasons is also provided.\n *\n * @example Checking for permission to publish a document\n * ```ts\n * import {usePermissions, useApplyActions} from '@sanity/sdk-react'\n * import {publishDocument} from '@sanity/sdk'\n *\n * export function PublishButton({doc}: {doc: DocumentHandle}) {\n * const canPublish = usePermissions(publishDocument(doc))\n * const applyAction = useApplyActions()\n *\n * return (\n * <>\n * <button\n * disabled={!canPublish.allowed}\n * onClick={() => applyAction(publishDocument(doc))}\n * popoverTarget={`${canPublish.allowed ? undefined : 'publishButtonPopover'}`}\n * >\n * Publish\n * </button>\n * {!canPublish.allowed && (\n * <div popover id=\"publishButtonPopover\">\n * {canPublish.message}\n * </div>\n * )}\n * </>\n * )\n * }\n * ```\n */\nexport function usePermissions(actions: DocumentAction | DocumentAction[]): PermissionsResult {\n // if actions is an array, we need to check each action to see if the resourceId is the same\n if (Array.isArray(actions)) {\n const resourceIds = actions.map((action) => action.resourceId)\n const uniqueResourceIds = new Set(resourceIds)\n if (uniqueResourceIds.size !== 1) {\n throw new Error('All actions must have the same resourceId')\n }\n }\n const resourceId = Array.isArray(actions)\n ? getResourceId(actions[0].resourceId)\n : getResourceId(actions.resourceId)\n\n const instance = useSanityInstance(resourceId)\n const isDocumentReady = useCallback(\n () => getPermissionsState(instance, actions).getCurrent() !== undefined,\n [actions, instance],\n )\n if (!isDocumentReady()) {\n throw firstValueFrom(\n getPermissionsState(instance, actions).observable.pipe(\n filter((result) => result !== undefined),\n ),\n )\n }\n\n const {subscribe, getCurrent} = useMemo(\n () => getPermissionsState(instance, actions),\n [actions, instance],\n )\n\n return useSyncExternalStore(subscribe, getCurrent) as PermissionsResult\n}\n","import {createDocumentListStore, type DocumentListOptions} from '@sanity/sdk'\nimport {useCallback, useEffect, useState, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {type DocumentHandleCollection} from './types'\n\ntype DocumentListStore = ReturnType<typeof createDocumentListStore>\ntype DocumentListState = ReturnType<DocumentListStore['getState']>['getCurrent']\nconst STABLE_EMPTY = {\n results: [],\n isPending: false,\n hasMore: false,\n count: 0,\n}\n\n/**\n * @public\n *\n * Retrieves and provides access to a live collection of {@link DocumentHandle}s, with an optional filter and sort applied.\n * The returned document handles are canonical — that is, they refer to the document in its current state, whether draft, published, or within a release or perspective.\n * Because the returned document handle collection is live, the results will update in real time until the component invoking the hook is unmounted.\n *\n * @remarks\n * {@link DocumentHandle}s are used by many other hooks (such as {@link usePreview}, {@link useDocument}, and {@link useEditDocument})\n * to work with documents in various ways without the entire document needing to be fetched upfront.\n *\n * @category Documents\n * @param options - Options for narrowing and sorting the document collection\n * @returns The collection of document handles matching the provided options (if any), as well as properties describing the collection and a function to load more.\n *\n * @example Retrieving document handles for all documents of type 'movie'\n * ```\n * const { results, isPending } = useDocuments({ filter: '_type == \"movie\"' })\n *\n * return (\n * <div>\n * <h1>Movies</h1>\n * {results && (\n * <ul>\n * {results.map(movie => (<li key={movie._id}>…</li>))}\n * </ul>\n * )}\n * {isPending && <div>Loading movies…</div>}\n * </div>\n * )\n * ```\n *\n * @example Retrieving document handles for all movies released since 1980, sorted by director’s last name\n * ```\n * const { results } = useDocuments({\n * filter: '_type == \"movie\" && releaseDate >= \"1980-01-01\"',\n * sort: [\n * {\n * // Expand the `director` reference field with the dereferencing operator `->`\n * field: 'director->lastName',\n * sort: 'asc',\n * },\n * ],\n * })\n *\n * return (\n * <div>\n * <h1>Movies released since 1980</h1>\n * {results && (\n * <ol>\n * {results.map(movie => (<li key={movie._id}>…</li>))}\n * </ol>\n * )}\n * </div>\n * )\n * ```\n */\nexport function useDocuments(options: DocumentListOptions = {}): DocumentHandleCollection {\n const instance = useSanityInstance(options.resourceId)\n\n // NOTE: useState is used because it guaranteed to return a stable reference\n // across renders\n const [ref] = useState<{\n storeInstance: DocumentListStore | null\n getCurrent: DocumentListState\n initialOptions: DocumentListOptions\n }>(() => ({\n storeInstance: null,\n getCurrent: () => STABLE_EMPTY,\n initialOptions: options,\n }))\n\n // serialize options to ensure it only calls `setOptions` when the values\n // themselves changes (in cases where devs put config inline)\n const serializedOptions = JSON.stringify(options)\n useEffect(() => {\n ref.storeInstance?.setOptions(JSON.parse(serializedOptions))\n }, [ref, serializedOptions])\n\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n // to match the lifecycle of `useSyncExternalState`, we create the store\n // instance after subscribe and mutate the ref to connect everything\n ref.storeInstance = createDocumentListStore(instance)\n ref.storeInstance.setOptions(ref.initialOptions)\n const state = ref.storeInstance.getState()\n ref.getCurrent = state.getCurrent\n const unsubscribe = state.subscribe(onStoreChanged)\n\n return () => {\n // unsubscribe to clean up the state subscriptions\n unsubscribe()\n // dispose of the instance\n ref.storeInstance?.dispose()\n }\n },\n [instance, ref],\n )\n\n const getSnapshot = useCallback(() => {\n return ref.getCurrent()\n }, [ref])\n\n const state = useSyncExternalStore(subscribe, getSnapshot)\n\n const loadMore = useCallback(() => {\n ref.storeInstance?.loadMore()\n }, [ref])\n\n return {loadMore, ...state}\n}\n","import {type DocumentListOptions} from '@sanity/sdk'\nimport {useMemo} from 'react'\n\nimport {type DocumentHandleCollection} from './types'\nimport {useDocuments} from './useDocuments'\n\ninterface SearchOptions extends DocumentListOptions {\n query?: string\n}\n\n/**\n * @public\n * Hook for searching documents using full-text search.\n *\n * @param options - The options for the search.\n * @example\n * ```tsx\n * function SearchResults() {\n * const [query, setQuery] = useState('')\n * const {results, isPending} = useSearch({\n * filter: '_type == \"book\"',\n * query,\n * sort: [{field: '_createdAt', direction: 'desc'}]\n * })\n *\n * return (\n * <div>\n * <input\n * type=\"search\"\n * value={query}\n * onChange={(e) => setQuery(e.target.value)}\n * placeholder=\"Search books...\"\n * />\n * {isPending ? (\n * <div>Searching...</div>\n * ) : (\n * <ul>\n * {results.map((doc) => (\n * <li key={doc._id}>{doc._id}</li>\n * ))}\n * </ul>\n * )}\n * </div>\n * )\n * }\n * ```\n */\nexport function useSearch({\n query,\n filter: additionalFilter,\n ...options\n}: SearchOptions = {}): DocumentHandleCollection {\n // Build the complete GROQ filter\n const filter = useMemo(() => {\n const conditions: string[] = []\n\n // Add search query if specified\n if (query?.trim()) {\n conditions.push(`[@] match text::query(\"${query.trim()}\")`)\n }\n\n // Add additional filter if specified\n if (additionalFilter) {\n conditions.push(`(${additionalFilter})`)\n }\n\n return conditions.length ? conditions.join(' && ') : ''\n }, [query, additionalFilter])\n\n // Use the existing useDocuments hook with our constructed filter\n return useDocuments({\n ...options,\n filter,\n })\n}\n","import {type DocumentHandle, getPreviewState, type PreviewValue, resolvePreview} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @beta\n * @category Types\n */\nexport interface UsePreviewOptions {\n document: DocumentHandle\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @beta\n * @category Types\n */\nexport interface UsePreviewResults {\n /** The results of resolving the document’s preview values */\n results: PreviewValue\n /** True when preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @beta\n *\n * Returns the preview values of a document (specified via a `DocumentHandle`),\n * including the document’s `title`, `subtitle`, `media`, and `status`. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the preview values, an optional `ref` can be passed to the hook so that preview\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * @category Documents\n * @param options - The document handle for the document you want to resolve preview values for, and an optional ref\n * @returns The preview values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Combining with useDocuments to render a collection of document previews\n * ```\n * // PreviewComponent.jsx\n * export default function PreviewComponent({ document }) {\n * const { results: { title, subtitle, media }, isPending } = usePreview({ document })\n * return (\n * <article style={{ opacity: isPending ? 0.5 : 1}}>\n * {media?.type === 'image-asset' ? <img src={media.url} alt='' /> : ''}\n * <h2>{title}</h2>\n * <p>{subtitle}</p>\n * </article>\n * )\n * }\n *\n * // DocumentList.jsx\n * const { results, isPending } = useDocuments({ filter: '_type == \"movie\"' })\n * return (\n * <div>\n * <h1>Movies</h1>\n * <ul>\n * {isPending ? 'Loading…' : results.map(movie => (\n * <li key={movie._id}>\n * <Suspense fallback='Loading…'>\n * <PreviewComponent document={movie} />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function usePreview({document: {_id, _type}, ref}: UsePreviewOptions): UsePreviewResults {\n const instance = useSanityInstance()\n\n const stateSource = useMemo(\n () => getPreviewState(instance, {document: {_id, _type}}),\n [instance, _id, _type],\n )\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // for environments that don't have an intersection observer\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n // Create getSnapshot function to return current state\n const getSnapshot = useCallback(() => {\n const currentState = stateSource.getCurrent()\n if (currentState.results === null) throw resolvePreview(instance, {document: {_id, _type}})\n return currentState as UsePreviewResults\n }, [_id, _type, instance, stateSource])\n\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n","import {\n getProjectState,\n resolveProject,\n type SanityInstance,\n type SanityProject,\n type StateSource,\n} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/** @public */\nexport const useProject = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getProjectState as (\n instance: SanityInstance,\n projectId: string,\n ) => StateSource<SanityProject>,\n shouldSuspend: (instance, projectId) =>\n getProjectState(instance, projectId).getCurrent() === undefined,\n suspender: resolveProject,\n})\n","import {\n getProjectsState,\n resolveProjects,\n type SanityInstance,\n type SanityProject,\n type StateSource,\n} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/** @public */\nexport const useProjects = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getProjectsState as (\n instance: SanityInstance,\n ) => StateSource<Omit<SanityProject, 'members'>[]>,\n shouldSuspend: (instance) => getProjectsState(instance).getCurrent() === undefined,\n suspender: resolveProjects,\n})\n","import {createUsersStore, type ResourceType, type SanityUser} from '@sanity/sdk'\nimport {useCallback, useEffect, useState, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Users\n */\nexport interface UseUsersParams {\n /**\n * The type of resource to fetch users for.\n */\n resourceType: ResourceType\n /**\n * The ID of the resource to fetch users for.\n */\n resourceId: string\n /**\n * The limit of users to fetch.\n */\n limit?: number\n}\n\n/**\n * @public\n * @category Users\n */\nexport interface UseUsersResult {\n /**\n * The users fetched.\n */\n users: SanityUser[]\n /**\n * Whether there are more users to fetch.\n */\n hasMore: boolean\n /**\n * Load more users.\n */\n loadMore: () => void\n}\n\n/**\n *\n * @public\n *\n * Retrieves the users for a given resource (either a project or an organization).\n *\n * @category Users\n * @param params - The resource type and its ID, and the limit of users to fetch\n * @returns A list of users, a boolean indicating whether there are more users to fetch, and a function to load more users\n *\n * @example\n * ```\n * const { users, hasMore, loadMore } = useUsers({\n * resourceType: 'organization',\n * resourceId: 'my-org-id',\n * limit: 10,\n * })\n *\n * return (\n * <div>\n * {users.map(user => (\n * <figure key={user.sanityUserId}>\n * <img src={user.profile.imageUrl} alt='' />\n * <figcaption>{user.profile.displayName}</figcaption>\n * <address>{user.profile.email}</address>\n * </figure>\n * ))}\n * {hasMore && <button onClick={loadMore}>Load More</button>}\n * </div>\n * )\n * ```\n */\nexport function useUsers(params: UseUsersParams): UseUsersResult {\n const instance = useSanityInstance(params.resourceId)\n const [store] = useState(() => createUsersStore(instance))\n\n useEffect(() => {\n store.setOptions({\n resourceType: params.resourceType,\n resourceId: params.resourceId,\n })\n }, [params.resourceType, params.resourceId, store])\n\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n if (store.getState().getCurrent().initialFetchCompleted === false) {\n store.resolveUsers()\n }\n const unsubscribe = store.getState().subscribe(onStoreChanged)\n\n return () => {\n unsubscribe()\n store.dispose()\n }\n },\n [store],\n )\n\n const getSnapshot = useCallback(() => store.getState().getCurrent(), [store])\n\n const {users, hasMore} = useSyncExternalStore(subscribe, getSnapshot) || {}\n\n return {users, hasMore, loadMore: store.loadMore}\n}\n","import {\n type DocumentHandle,\n getProjectionState,\n resolveProjection,\n type ValidProjection,\n} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\ninterface UseProjectionOptions {\n document: DocumentHandle\n projection: ValidProjection\n ref?: React.RefObject<unknown>\n}\n\ninterface UseProjectionResults<TResult extends object> {\n results: TResult\n isPending: boolean\n}\n\n/**\n * @beta\n *\n * Returns the projection values of a document (specified via a `DocumentHandle`),\n * based on the provided projection string. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the projection values, an optional `ref` can be passed to the hook so that projection\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * @category Documents\n * @param options - The document handle for the document you want to project values from, the projection string, and an optional ref\n * @returns The projection values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Using a projection to display specific document fields\n * ```\n * // ProjectionComponent.jsx\n * export default function ProjectionComponent({ document }) {\n * const ref = useRef(null)\n * const { results: { title, description, authors }, isPending } = useProjection({\n * document,\n * projection: '{title, \"description\": pt::text(\"description\"), \"authors\": array::join(authors[]->name, \", \")}',\n * ref\n * })\n *\n * return (\n * <article ref={ref} style={{ opacity: isPending ? 0.5 : 1}}>\n * <h2>{title}</h2>\n * <p>{description}</p>\n * <p>{authors}</p>\n * </article>\n * )\n * }\n * ```\n *\n * @example Combining with useDocuments to render a collection with specific fields\n * ```\n * // DocumentList.jsx\n * const { results, isPending } = useDocuments({ filter: '_type == \"article\"' })\n * return (\n * <div>\n * <h1>Articles</h1>\n * <ul>\n * {isPending ? 'Loading…' : results.map(article => (\n * <li key={article._id}>\n * <Suspense fallback='Loading…'>\n * <ProjectionComponent\n * document={article}\n * />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function useProjection<TResult extends object>({\n document: {_id, _type},\n projection,\n ref,\n}: UseProjectionOptions): UseProjectionResults<TResult> {\n const instance = useSanityInstance()\n\n const stateSource = useMemo(\n () => getProjectionState<TResult>(instance, {document: {_id, _type}, projection}),\n [instance, _id, _type, projection],\n )\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // for environments that don't have an intersection observer\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n // Create getSnapshot function to return current state\n const getSnapshot = useCallback(() => {\n const currentState = stateSource.getCurrent()\n if (currentState.results === null)\n throw resolveProjection(instance, {document: {_id, _type}, projection})\n return currentState as UseProjectionResults<TResult>\n }, [_id, _type, projection, instance, stateSource])\n\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n"],"names":["nextValue","state","filter"],"mappings":";;;;;AASa,MAAA,eAAe,sBAAsB,aAAa,GCuBlD,iBAAiC,sBAAsB,mBAAmB,GCF1E,YAAY,sBAAsB,cAAc;ACkBtD,SAAS,mBAGd,SAAoF;AACpF,QAAM,EAAC,WAAW,cAAc,MAAM,WAAW,cAAa,SACxD,WAAW,kBAAkB,GAC7B,CAAC,QAAQ,SAAS,IAAI,SAAiB,MAAM,GAE7C,aAAa;AAAA,IACjB,MAAM,sBAAsB,UAAU,YAAY;AAAA,IAClD,CAAC,UAAU,YAAY;AAAA,KAGnB,UAAU;AAAA,IACd,MACE,mBAAmB,UAAU;AAAA,MAC3B;AAAA,MACA;AAAA,MACA;AAAA,IAAA,CACD;AAAA,IACH,CAAC,UAAU,MAAM,WAAW,SAAS;AAAA,EACvC;AAEA,YAAU,MACH,UAEe,QAAQ,SAAS,CAAC,UAAU;AAC9C,cAAU,MAAM,MAAM;AAAA,EACvB,CAAA,IAJa,QAOb,CAAC,OAAO,CAAC,GAEZ,UAAU,MAAM;AACV,QAAA,CAAC,WAAW,CAAC,UAAW;AAE5B,UAAM,gBAAmC,CAAC;AAEnC,WAAA,OAAA,QAAQ,SAAS,EAAE,QAAQ,CAAC,CAAC,MAAM,OAAO,MAAM;AAErD,YAAM,cAAc,QAAQ,GAAG,MAAM,OAA8C;AACnF,oBAAc,KAAK,WAAW;AAAA,IAC/B,CAAA,GAEM,MAAM;AACX,oBAAc,QAAQ,CAAC,UAAU,MAAA,CAAO;AAAA,IAC1C;AAAA,EAAA,GACC,CAAC,SAAS,SAAS,CAAC;AA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AAA,UAAU,EAAC,MAAM,gBAAe;AAE5B,aAAA,MAAM,aAAa,YAAY;AAAA,IACxC;AAAA,IACA,CAAC,aAAa,GAAG;AAAA,EAAA,GAIb,cAAc,YAAY,MAAM;AAC9B,UAAA,eAAe,YAAY,WAAW;AAC5C,QAAI,aAAa,YAAY;AACrB,YAAA,kBAAkB,UAAU,EAAC,UAAU,EAAC,KAAK,MAAA,GAAQ,YAAW;AACjE,WAAA;AAAA,EAAA,GACN,CAAC,KAAK,OAAO,YAAY,UAAU,WAAW,CAAC;AAE3C,SAAA,qBAAqB,WAAW,WAAW;AACpD;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/sdk-react",
|
|
3
|
-
"version": "0.0.0-alpha.
|
|
3
|
+
"version": "0.0.0-alpha.15",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Sanity SDK React toolkit for Content OS",
|
|
6
6
|
"keywords": [
|
|
@@ -71,11 +71,10 @@
|
|
|
71
71
|
"@sanity/types": "^3.67.1",
|
|
72
72
|
"react-error-boundary": "^4.1.2",
|
|
73
73
|
"rxjs": "^7.8.1",
|
|
74
|
-
"@sanity/sdk": "0.0.0-alpha.
|
|
74
|
+
"@sanity/sdk": "0.0.0-alpha.14"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
|
-
"@sanity/
|
|
78
|
-
"@sanity/client": "^6.28.2",
|
|
77
|
+
"@sanity/client": "^6.28.1",
|
|
79
78
|
"@sanity/comlink": "^2.0.5",
|
|
80
79
|
"@sanity/pkg-utils": "^6.13.4",
|
|
81
80
|
"@sanity/prettier-config": "^1.0.3",
|
package/src/_exports/hooks.ts
CHANGED
|
@@ -18,18 +18,24 @@ export {
|
|
|
18
18
|
type WindowMessageHandler,
|
|
19
19
|
} from '../hooks/comlink/useWindowConnection'
|
|
20
20
|
export {useSanityInstance} from '../hooks/context/useSanityInstance'
|
|
21
|
+
export {useDatasets} from '../hooks/datasets/useDatasets'
|
|
21
22
|
export {useApplyActions} from '../hooks/document/useApplyActions'
|
|
22
23
|
export {useDocument} from '../hooks/document/useDocument'
|
|
23
24
|
export {useDocumentEvent} from '../hooks/document/useDocumentEvent'
|
|
24
25
|
export {useDocumentSyncStatus} from '../hooks/document/useDocumentSyncStatus'
|
|
25
26
|
export {useEditDocument} from '../hooks/document/useEditDocument'
|
|
26
27
|
export {usePermissions} from '../hooks/document/usePermissions'
|
|
27
|
-
export {type DocumentHandleCollection
|
|
28
|
+
export {type DocumentHandleCollection} from '../hooks/documentCollection/types'
|
|
29
|
+
export {useDocuments} from '../hooks/documentCollection/useDocuments'
|
|
30
|
+
export {useSearch} from '../hooks/documentCollection/useSearch'
|
|
28
31
|
export {
|
|
29
32
|
usePreview,
|
|
30
33
|
type UsePreviewOptions,
|
|
31
34
|
type UsePreviewResults,
|
|
32
35
|
} from '../hooks/preview/usePreview'
|
|
33
|
-
export {
|
|
36
|
+
export {useProject} from '../hooks/projects/useProject'
|
|
37
|
+
export {useProjects} from '../hooks/projects/useProjects'
|
|
38
|
+
export {useUsers, type UseUsersParams, type UseUsersResult} from '../hooks/users/useUsers'
|
|
39
|
+
export {useProjection} from '../hooks/projection/useProjection'
|
|
34
40
|
export {type CurrentUser, type DocumentHandle} from '@sanity/sdk'
|
|
35
41
|
export {type SanityDocument} from '@sanity/types'
|
|
@@ -48,7 +48,7 @@ describe('LoginLinks', () => {
|
|
|
48
48
|
|
|
49
49
|
const sanityInstance = createSanityInstance({projectId: 'test-project-id', dataset: 'production'})
|
|
50
50
|
const renderWithWrappers = (ui: React.ReactElement) => {
|
|
51
|
-
return render(<SanityProvider
|
|
51
|
+
return render(<SanityProvider sanityInstances={[sanityInstance]}>{ui}</SanityProvider>)
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
it('renders auth provider links correctly when not authenticated', () => {
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import * as SanitySDK from '@sanity/sdk'
|
|
2
|
+
import {render} from '@testing-library/react'
|
|
3
|
+
import {type ReactNode} from 'react'
|
|
4
|
+
import {describe, expect, it, vi} from 'vitest'
|
|
5
|
+
|
|
6
|
+
import {type SanityProviderProps} from '../context/SanityProvider'
|
|
7
|
+
import {SDKProvider} from './SDKProvider'
|
|
8
|
+
|
|
9
|
+
// Mock the SDK module
|
|
10
|
+
vi.mock('@sanity/sdk', () => ({
|
|
11
|
+
createSanityInstance: vi.fn(() => ({
|
|
12
|
+
// Mock return value of createSanityInstance
|
|
13
|
+
id: 'mock-instance',
|
|
14
|
+
})),
|
|
15
|
+
}))
|
|
16
|
+
|
|
17
|
+
// Mock the SanityProvider context to verify the instance is passed correctly
|
|
18
|
+
vi.mock('../context/SanityProvider', () => ({
|
|
19
|
+
SanityProvider: ({children, sanityInstances}: SanityProviderProps) => (
|
|
20
|
+
<div data-testid="sanity-provider" data-instances={JSON.stringify(sanityInstances)}>
|
|
21
|
+
{children}
|
|
22
|
+
</div>
|
|
23
|
+
),
|
|
24
|
+
useSanity: vi.fn(),
|
|
25
|
+
}))
|
|
26
|
+
|
|
27
|
+
// Mock the AuthBoundary component
|
|
28
|
+
vi.mock('./auth/AuthBoundary', () => ({
|
|
29
|
+
AuthBoundary: ({children}: {children: ReactNode}) => (
|
|
30
|
+
<div data-testid="auth-boundary">{children}</div>
|
|
31
|
+
),
|
|
32
|
+
}))
|
|
33
|
+
|
|
34
|
+
describe('SDKProvider', () => {
|
|
35
|
+
const mockConfig = {
|
|
36
|
+
projectId: 'test-project',
|
|
37
|
+
dataset: 'test-dataset',
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
it('creates a Sanity instance with the provided config', () => {
|
|
41
|
+
render(
|
|
42
|
+
<SDKProvider sanityConfigs={[mockConfig]}>
|
|
43
|
+
<div>Test Child</div>
|
|
44
|
+
</SDKProvider>,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
expect(SanitySDK.createSanityInstance).toHaveBeenCalledWith(mockConfig)
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('renders children within SanityProvider and AuthBoundary', () => {
|
|
51
|
+
const {getByText, getByTestId} = render(
|
|
52
|
+
<SDKProvider sanityConfigs={[mockConfig]}>
|
|
53
|
+
<div>Test Child</div>
|
|
54
|
+
</SDKProvider>,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
// Verify the component hierarchy
|
|
58
|
+
const sanityProvider = getByTestId('sanity-provider')
|
|
59
|
+
const authBoundary = getByTestId('auth-boundary')
|
|
60
|
+
const childElement = getByText('Test Child')
|
|
61
|
+
|
|
62
|
+
expect(sanityProvider).toBeInTheDocument()
|
|
63
|
+
expect(authBoundary).toBeInTheDocument()
|
|
64
|
+
expect(childElement).toBeInTheDocument()
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('passes the created Sanity instance to SanityProvider', () => {
|
|
68
|
+
const {getByTestId} = render(
|
|
69
|
+
<SDKProvider sanityConfigs={[mockConfig]}>
|
|
70
|
+
<div>Test Child</div>
|
|
71
|
+
</SDKProvider>,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
const sanityProvider = getByTestId('sanity-provider')
|
|
75
|
+
const passedInstances = JSON.parse(sanityProvider.dataset['instances'] || '[]')
|
|
76
|
+
|
|
77
|
+
expect(passedInstances).toEqual([{id: 'mock-instance'}])
|
|
78
|
+
})
|
|
79
|
+
})
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {createSanityInstance, type SanityConfig} from '@sanity/sdk'
|
|
2
|
+
import {type ReactElement, type ReactNode} from 'react'
|
|
3
|
+
|
|
4
|
+
import {SanityProvider} from '../context/SanityProvider'
|
|
5
|
+
import {AuthBoundary} from './auth/AuthBoundary'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @internal
|
|
9
|
+
*/
|
|
10
|
+
export interface SDKProviderProps {
|
|
11
|
+
children: ReactNode
|
|
12
|
+
sanityConfigs: SanityConfig[]
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Marking this as internal since this should not be used directly by consumers
|
|
16
|
+
/**
|
|
17
|
+
* @internal
|
|
18
|
+
*
|
|
19
|
+
* Top-level context provider that provides access to the Sanity SDK.
|
|
20
|
+
*/
|
|
21
|
+
export function SDKProvider({children, sanityConfigs}: SDKProviderProps): ReactElement {
|
|
22
|
+
const sanityInstances = sanityConfigs.map((sanityConfig: SanityConfig) =>
|
|
23
|
+
createSanityInstance(sanityConfig),
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
return (
|
|
27
|
+
<SanityProvider sanityInstances={sanityInstances}>
|
|
28
|
+
<AuthBoundary>{children}</AuthBoundary>
|
|
29
|
+
</SanityProvider>
|
|
30
|
+
)
|
|
31
|
+
}
|