@sanity/visual-editing
Advanced tools
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"LoaderComlink.js","sources":["../../src/ui/LoaderComlink.tsx"],"sourcesContent":["import {createNode, createNodeMachine} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {useEffect} from 'react'\n\nimport {setLoaderClientConfig, setLoaderComlink, setLoaderPerspective} from './loader-comlink/context'\n\n/**\n * Creates a loader comlink node that connects to the Presentation Tool.\n * This enables `usePresentationQuery` to communicate with the Presentation Tool\n * for running queries and receiving live updates.\n * @internal\n */\nexport default function LoaderComlink(): null {\n useEffect(() => {\n const loaderComlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {\n name: 'loaders',\n connectTo: 'presentation',\n },\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n loaderComlink.on('loader/perspective', (data) => {\n setLoaderClientConfig(data.projectId, data.dataset)\n setLoaderPerspective(data.perspective)\n })\n\n const stop = loaderComlink.start()\n setLoaderComlink(loaderComlink)\n\n return () => {\n stop()\n setLoaderComlink(null)\n setLoaderClientConfig(null, null)\n setLoaderPerspective(null)\n }\n }, [])\n\n return null\n}\nLoaderComlink.displayName = 'LoaderComlink'\n"],"names":["LoaderComlink","$","_c","t0","Symbol","for","useEffect","_temp2","loaderComlink","createNode","name","connectTo","createNodeMachine","provide","actors","createCompatibilityActors","on","_temp","stop","start","setLoaderComlink","setLoaderClientConfig","setLoaderPerspective","data","projectId","dataset","perspective","displayName"],"mappings":";;;;;AAgBA,SAAeA,gBAAA;AAAA,QAAAC,IAAAC,EAAA,CAAA;AAAA,MAAAC;AAAA,SAAAF,EAAA,CAAA,MAAAG,uBAAAC,IAAA,2BAAA,KA0BVF,KAAA,CAAA,GAAEF,OAAAE,MAAAA,KAAAF,EAAA,CAAA,GAzBLK,UAAUC,QAyBPJ,EAAE,GAEE;AAAI;AA5BE,SAAAI,SAAA;AAEX,QAAAC,gBAAsBC,WACpB;AAAA,IAAAC,MACQ;AAAA,IAASC,WACJ;AAAA,EAAA,GAEbC,kBAAAA,EAAuDC,QAAS;AAAA,IAAAC,QACtDC,0BAAAA;AAAAA,EAAyC,CAClD,CACH;AAEAP,gBAAaQ,GAAI,sBAAsBC,KAGtC;AAED,QAAAC,OAAaV,cAAaW,MAAAA;AAC1BC,SAAAA,iBAAiBZ,aAAa,GAEvB,MAAA;AACLU,SAAAA,GACAE,iBAAiB,IAAI,GACrBC,sBAAsB,MAAM,IAAI,GAChCC,qBAAqB,IAAI;AAAA,EAAC;AAC3B;AAzBU,SAAAL,MAAAM,MAAA;AAaTF,wBAAsBE,KAAIC,WAAYD,KAAIE,OAAQ,GAClDH,qBAAqBC,KAAIG,WAAY;AAAC;AAgB5C1B,cAAc2B,cAAc;"} | ||
| {"version":3,"file":"LoaderComlink.js","sources":["../../src/ui/LoaderComlink.tsx"],"sourcesContent":["import {createNode, createNodeMachine} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {useEffect} from 'react'\n\nimport {\n setLoaderClientConfig,\n setLoaderComlink,\n setLoaderPerspective,\n} from './loader-comlink/context'\n\n/**\n * Creates a loader comlink node that connects to the Presentation Tool.\n * This enables `usePresentationQuery` to communicate with the Presentation Tool\n * for running queries and receiving live updates.\n * @internal\n */\nexport default function LoaderComlink(): null {\n useEffect(() => {\n const loaderComlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {\n name: 'loaders',\n connectTo: 'presentation',\n },\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n loaderComlink.on('loader/perspective', (data) => {\n setLoaderClientConfig(data.projectId, data.dataset)\n setLoaderPerspective(data.perspective)\n })\n\n const stop = loaderComlink.start()\n setLoaderComlink(loaderComlink)\n\n return () => {\n stop()\n setLoaderComlink(null)\n setLoaderClientConfig(null, null)\n setLoaderPerspective(null)\n }\n }, [])\n\n return null\n}\nLoaderComlink.displayName = 'LoaderComlink'\n"],"names":["LoaderComlink","$","_c","t0","Symbol","for","useEffect","_temp2","loaderComlink","createNode","name","connectTo","createNodeMachine","provide","actors","createCompatibilityActors","on","_temp","stop","start","setLoaderComlink","setLoaderClientConfig","setLoaderPerspective","data","projectId","dataset","perspective","displayName"],"mappings":";;;;;AAoBA,SAAeA,gBAAA;AAAA,QAAAC,IAAAC,EAAA,CAAA;AAAA,MAAAC;AAAA,SAAAF,EAAA,CAAA,MAAAG,uBAAAC,IAAA,2BAAA,KA0BVF,KAAA,CAAA,GAAEF,OAAAE,MAAAA,KAAAF,EAAA,CAAA,GAzBLK,UAAUC,QAyBPJ,EAAE,GAEE;AAAI;AA5BE,SAAAI,SAAA;AAEX,QAAAC,gBAAsBC,WACpB;AAAA,IAAAC,MACQ;AAAA,IAASC,WACJ;AAAA,EAAA,GAEbC,kBAAAA,EAAuDC,QAAS;AAAA,IAAAC,QACtDC,0BAAAA;AAAAA,EAAyC,CAClD,CACH;AAEAP,gBAAaQ,GAAI,sBAAsBC,KAGtC;AAED,QAAAC,OAAaV,cAAaW,MAAAA;AAC1BC,SAAAA,iBAAiBZ,aAAa,GAEvB,MAAA;AACLU,SAAAA,GACAE,iBAAiB,IAAI,GACrBC,sBAAsB,MAAM,IAAI,GAChCC,qBAAqB,IAAI;AAAA,EAAC;AAC3B;AAzBU,SAAAL,MAAAM,MAAA;AAaTF,wBAAsBE,KAAIC,WAAYD,KAAIE,OAAQ,GAClDH,qBAAqBC,KAAIG,WAAY;AAAC;AAgB5C1B,cAAc2B,cAAc;"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"mutations.js","sources":["../../../../node_modules/.pnpm/@sanity+util@5.8.1_@types+react@19.2.13_debug@4.4.3/node_modules/@sanity/util/lib/paths.js","../../src/react/useOptimisticActor.ts","../../src/react/useDocuments.ts","../../src/util/randomKey.ts","../../src/util/mutations.ts"],"sourcesContent":["import { isIndexSegment, isKeySegment, isIndexTuple } from \"@sanity/types\";\nconst rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g, reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/, EMPTY_PATH = [], FOCUS_TERMINATOR = \"$\", GROQ_DATA_TYPE_VALUES = [\"true\", \"false\", \"null\"];\nfunction get(obj, path, defaultVal) {\n const select = typeof path == \"string\" ? fromString(path) : path;\n if (!Array.isArray(select))\n throw new Error(\"Path must be an array or a string\");\n let acc = obj;\n for (let i = 0; i < select.length; i++) {\n const segment = select[i];\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc))\n return defaultVal;\n acc = acc[segment];\n }\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc))\n return defaultVal;\n acc = acc.find((item) => item._key === segment._key);\n }\n if (typeof segment == \"string\" && (acc = typeof acc == \"object\" && acc !== null ? acc[segment] : void 0), typeof acc > \"u\")\n return defaultVal;\n }\n return acc;\n}\nconst pathsMemo = /* @__PURE__ */ new Map();\nfunction pathFor(path) {\n if (path.length === 0)\n return EMPTY_PATH;\n const asString = toString(path);\n return pathsMemo.has(asString) ? pathsMemo.get(asString) : (pathsMemo.set(asString, path), Object.freeze(path), path);\n}\nfunction isEqual(path, otherPath) {\n return path.length === otherPath.length && path.every((segment, i) => isSegmentEqual(segment, otherPath[i]));\n}\nfunction numEqualSegments(path, otherPath) {\n const length = Math.min(path.length, otherPath.length);\n for (let i = 0; i < length; i++)\n if (!isSegmentEqual(path[i], otherPath[i]))\n return i;\n return length;\n}\nfunction isSegmentEqual(segmentA, segmentB) {\n return isKeySegment(segmentA) && isKeySegment(segmentB) ? segmentA._key === segmentB._key : isIndexSegment(segmentA) ? Number(segmentA) === Number(segmentB) : isIndexTuple(segmentA) && isIndexTuple(segmentB) ? segmentA[0] === segmentB[0] && segmentA[1] === segmentB[1] : segmentA === segmentB;\n}\nfunction hasFocus(focusPath, path) {\n const withoutTerminator = focusPath[focusPath.length - 1] === FOCUS_TERMINATOR ? focusPath.slice(0, -1) : focusPath;\n return isEqual(withoutTerminator, path);\n}\nfunction hasItemFocus(focusPath, item) {\n return focusPath.length === 1 && isSegmentEqual(focusPath[0], item);\n}\nfunction isExpanded(segment, focusPath) {\n const [head, ...tail] = focusPath;\n return tail.length > 0 && isSegmentEqual(segment, head);\n}\nfunction startsWith(prefix, path) {\n return prefix.every((segment, i) => isSegmentEqual(segment, path[i]));\n}\nfunction trimLeft(prefix, path) {\n if (prefix.length === 0 || path.length === 0)\n return path;\n const [prefixHead, ...prefixTail] = prefix, [pathHead, ...pathTail] = path;\n return isSegmentEqual(prefixHead, pathHead) ? pathFor(trimLeft(prefixTail, pathTail)) : path;\n}\nfunction trimRight(suffix, path) {\n const sufLen = suffix.length, pathLen = path.length;\n if (sufLen === 0 || pathLen === 0)\n return path;\n let i = 0;\n for (; i < sufLen && i < pathLen && isSegmentEqual(path[pathLen - i - 1], suffix[sufLen - i - 1]); )\n i++;\n return pathFor(path.slice(0, pathLen - i));\n}\nfunction trimChildPath(path, childPath) {\n return startsWith(path, childPath) ? trimLeft(path, childPath) : EMPTY_PATH;\n}\nfunction toString(path) {\n if (!Array.isArray(path))\n throw new Error(\"Path is not an array\");\n return path.reduce((target, segment, i) => {\n const isHead = i === 0;\n if (typeof segment == \"number\")\n return `${target}[${segment}]`;\n if (typeof segment == \"string\")\n return isHead ? segment : GROQ_DATA_TYPE_VALUES.includes(segment) ? `${target}[\"${segment}\"]` : `${target}.${segment}`;\n if (isKeySegment(segment) && segment._key)\n return `${target}[_key==\"${segment._key}\"]`;\n if (Array.isArray(segment)) {\n const [from, to] = segment;\n return `${target}[${from}:${to}]`;\n }\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``);\n }, \"\");\n}\nfunction _resolveKeyedPath(value, path) {\n if (path.length === 0)\n return path;\n const [next, ...rest] = path;\n if (typeof next == \"number\") {\n if (!Array.isArray(value) || !(next in value))\n return [];\n const item = value[next];\n return [typeof item?._key == \"string\" ? { _key: item._key } : next, ..._resolveKeyedPath(item, rest)];\n }\n const nextVal = get(value, [next]);\n return [next, ..._resolveKeyedPath(nextVal, rest)];\n}\nfunction resolveKeyedPath(value, path) {\n if (!Array.isArray(path))\n throw new Error(\"Path is not an array\");\n return pathFor(_resolveKeyedPath(value, path));\n}\nfunction fromString(path) {\n if (typeof path != \"string\")\n throw new Error(\"Path is not a string\");\n const segments = path.match(rePropName);\n if (!segments)\n throw new Error(\"Invalid path string\");\n return segments.map(normalizePathSegment);\n}\nfunction normalizePathSegment(segment) {\n return isIndexSegment(segment) ? normalizeIndexSegment(segment) : isKeySegment(segment) ? normalizeKeySegment(segment) : isIndexTuple(segment) ? normalizeIndexTupleSegment(segment) : segment;\n}\nfunction normalizeIndexSegment(segment) {\n return Number(segment.replace(/[^\\d]/g, \"\"));\n}\nfunction normalizeKeySegment(segment) {\n return { _key: segment.match(reKeySegment)[1] };\n}\nfunction normalizeIndexTupleSegment(segment) {\n const [from, to] = segment.split(\":\").map((seg) => seg === \"\" ? seg : Number(seg));\n return [from, to];\n}\nexport {\n FOCUS_TERMINATOR,\n _resolveKeyedPath,\n fromString,\n get,\n hasFocus,\n hasItemFocus,\n isEqual,\n isExpanded,\n isSegmentEqual,\n numEqualSegments,\n pathFor,\n resolveKeyedPath,\n startsWith,\n toString,\n trimChildPath,\n trimLeft,\n trimRight\n};\n//# sourceMappingURL=paths.js.map\n","import {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {\n actor,\n emptyActor,\n isEmptyActor,\n listeners,\n type EmptyActor,\n type MutatorActor,\n} from '../optimistic/context'\n\nexport function useOptimisticActor(): MutatorActor | EmptyActor {\n const subscribe = useCallback((listener: () => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n }, [])\n\n const actorRef = useSyncExternalStore(\n subscribe,\n () => actor,\n () => emptyActor,\n )\n\n return actorRef\n}\n\nexport function useOptimisticActorReady(): boolean {\n const actor = useOptimisticActor()\n return useMemo(() => !isEmptyActor(actor), [actor])\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {SanityDocument} from '@sanity/client'\n\nimport {getDraftId, getPublishedId} from '@sanity/client/csm'\nimport {createIfNotExists, patch} from '@sanity/mutate'\nimport {isMaybePreviewIframe, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport {get as getAtPath} from '@sanity/util/paths'\nimport {useCallback} from 'react'\n\nimport type {\n DocumentsGet,\n DocumentsMutate,\n OptimisticDocumentPatches,\n Path,\n PathValue,\n} from '../optimistic/types'\n\nimport {isEmptyActor, type MutatorActor} from '../optimistic/context'\nimport {useOptimisticActor} from './useOptimisticActor'\n\nfunction debounce<F extends (...args: Parameters<F>) => ReturnType<F>>(fn: F, timeout: number): F {\n let timer: ReturnType<typeof setTimeout>\n return ((...args: Parameters<F>) => {\n clearTimeout(timer)\n timer = setTimeout(() => {\n fn.apply(fn, args)\n }, timeout)\n }) as F\n}\n\nfunction getDocumentsAndSnapshot<T extends Record<string, any>>(id: string, actor: MutatorActor) {\n const inFrame = isMaybePreviewIframe()\n const inPopUp = isMaybePreviewWindow()\n\n if (isEmptyActor(actor) || (!inFrame && !inPopUp)) {\n throw new Error('The `useDocuments` hook cannot be used in this context')\n }\n\n const draftId = getDraftId(id)\n const publishedId = getPublishedId(id)\n const documents = actor.getSnapshot().context?.documents\n\n const draftDoc = documents?.[draftId]\n const publishedDoc = documents?.[publishedId]\n const doc = draftDoc || publishedDoc\n\n if (!doc) {\n throw new Error(`Document \"${id}\" not found`)\n }\n\n // Helper to get the snapshot from the draft document if it exists, otherwise\n // fall back to the published document\n const getDocumentSnapshot = () =>\n (draftDoc.getSnapshot().context?.local || publishedDoc.getSnapshot().context?.local) as\n | SanityDocument<T>\n | null\n | undefined\n\n const snapshot = getDocumentSnapshot()\n const snapshotPromise = new Promise<SanityDocument<T> | null>((resolve) => {\n if (snapshot) {\n resolve(snapshot)\n } else {\n const subscriber = doc.on('ready', (event) => {\n // Assert type here as the original document mutator machine doesn't\n // emit a 'ready' event. We provide a custom action to emit it in this\n // package's internal `createDatasetMutator` function. <3 xstate.\n const {snapshot} = event as unknown as {snapshot: SanityDocument<T> | null | undefined}\n resolve(snapshot || null)\n subscriber.unsubscribe()\n })\n }\n })\n\n const getSnapshot = () => snapshotPromise\n\n return {\n draftDoc,\n draftId,\n getSnapshot,\n publishedDoc,\n publishedId,\n /**\n * @deprecated - use `getSnapshot` instead\n */\n get snapshot() {\n // Maintain original error throwing behaviour, to avoid breaking changes\n if (!snapshot) {\n throw new Error(`Snapshot for document \"${id}\" not found`)\n }\n return snapshot\n },\n }\n}\n\nfunction createDocumentCommit<T extends Record<string, any>>(id: string, actor: MutatorActor) {\n return (): void => {\n const {draftDoc} = getDocumentsAndSnapshot<T>(id, actor)\n draftDoc.send({type: 'submit'})\n }\n}\n\n/**\n * @deprecated - superseded by `createDocumentGetSnapshot`\n */\nfunction createDocumentGet<T extends Record<string, any>>(id: string, actor: MutatorActor) {\n return <P extends Path<T, keyof T>>(\n path?: P,\n ): PathValue<T, P> | SanityDocument<T> | undefined => {\n const {snapshot} = getDocumentsAndSnapshot<T>(id, actor)\n\n return path\n ? (getAtPath(snapshot, path) as PathValue<T, P>)\n : (snapshot as unknown as SanityDocument<T>)\n }\n}\n\nfunction createDocumentGetSnapshot<T extends Record<string, any>>(\n id: string,\n actor: MutatorActor,\n): () => Promise<SanityDocument<T> | null> {\n const {getSnapshot} = getDocumentsAndSnapshot<T>(id, actor)\n return getSnapshot\n}\n\nfunction createDocumentPatch<T extends Record<string, any>>(id: string, actor: MutatorActor) {\n return async (\n patches: OptimisticDocumentPatches<T>,\n options?: {commit?: boolean | {debounce: number}},\n ): Promise<void> => {\n // Destructure the function result in two steps as we need access to the\n // `result.snapshot` property in the getter, but don't want to execute the\n // getter prematurely as it may throw\n const result = getDocumentsAndSnapshot<T>(id, actor)\n const {draftDoc, draftId, getSnapshot, publishedId} = result\n\n const {commit = true} = options || {}\n\n const context = {\n draftId,\n publishedId,\n /**\n * @deprecated - use `getSnapshot` instead\n */\n get snapshot() {\n return result.snapshot\n },\n getSnapshot,\n }\n\n const resolvedPatches = await (typeof patches === 'function' ? patches(context) : patches)\n\n const _snapshot = await getSnapshot()\n\n if (!_snapshot) {\n throw new Error(`Snapshot for document \"${id}\" not found`)\n }\n\n draftDoc.send({\n type: 'mutate',\n mutations: [\n // Attempt to create the draft document, it might not exist if the\n // snapshot was from the published document\n createIfNotExists({..._snapshot, _id: draftId}),\n // Patch the draft document with the resolved patches\n patch(draftId, resolvedPatches),\n ],\n })\n\n if (commit) {\n if (typeof commit === 'object' && 'debounce' in commit) {\n const debouncedCommit = debounce(() => draftDoc.send({type: 'submit'}), commit.debounce)\n debouncedCommit()\n } else {\n draftDoc.send({type: 'submit'})\n }\n }\n }\n}\n\nexport function useDocuments(): {\n getDocument: DocumentsGet\n mutateDocument: DocumentsMutate\n} {\n const actor = useOptimisticActor() as MutatorActor\n\n const getDocument: DocumentsGet = useCallback(\n <T extends Record<string, any>>(documentId: string) => {\n return {\n id: documentId,\n commit: createDocumentCommit(documentId, actor),\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Type instantiation is excessively deep and possibly infinite.\n get: createDocumentGet(documentId, actor),\n getSnapshot: createDocumentGetSnapshot<T>(documentId, actor),\n patch: createDocumentPatch<T>(documentId, actor),\n }\n },\n [actor],\n )\n\n const mutateDocument: DocumentsMutate = useCallback(\n (id, mutations, options) => {\n const {draftDoc} = getDocumentsAndSnapshot(id, actor)\n const {commit = true} = options || {}\n\n draftDoc.send({\n type: 'mutate',\n mutations: mutations,\n })\n\n if (commit) {\n if (typeof commit === 'object' && 'debounce' in commit) {\n const debouncedCommit = debounce(() => draftDoc.send({type: 'submit'}), commit.debounce)\n debouncedCommit()\n } else {\n draftDoc.send({type: 'submit'})\n }\n }\n },\n [actor],\n )\n\n return {getDocument, mutateDocument}\n}\n","// WHATWG crypto RNG - https://w3c.github.io/webcrypto/Overview.html\nfunction whatwgRNG(length = 16) {\n const rnds8 = new Uint8Array(length)\n crypto.getRandomValues(rnds8)\n return rnds8\n}\n\nconst getByteHexTable = (() => {\n let table: string[]\n return () => {\n if (table) {\n return table\n }\n table = []\n for (let i = 0; i < 256; ++i) {\n table[i] = (i + 0x100).toString(16).slice(1)\n }\n return table\n }\n})()\n\nexport function randomKey(length?: number): string {\n const table = getByteHexTable()\n return whatwgRNG(length)\n .reduce((str, n) => str + table[n], '')\n .slice(0, length)\n}\n","import type {SanityDocument} from '@sanity/client'\nimport type {SanityNode} from '@sanity/presentation-comlink'\n\nimport {at, insert, truncate, type NodePatchList} from '@sanity/mutate'\nimport {get} from '@sanity/util/paths'\n\nimport type {OptimisticDocument} from '../optimistic/types'\n\nimport {randomKey} from './randomKey'\n\nexport function getArrayItemKeyAndParentPath(pathOrNode: string | SanityNode): {\n path: string\n key: string\n hasExplicitKey: boolean\n} {\n const elementPath = typeof pathOrNode === 'string' ? pathOrNode : pathOrNode.path\n\n const lastDotIndex = elementPath.lastIndexOf('.')\n const lastPathItem = elementPath.substring(lastDotIndex + 1, elementPath.length)\n\n if (!lastPathItem.indexOf('[')) throw new Error('Invalid path: not an array')\n\n const lastArrayIndex = elementPath.lastIndexOf('[')\n const path = elementPath.substring(0, lastArrayIndex)\n\n let key\n let hasExplicitKey\n\n if (lastPathItem.includes('_key')) {\n // explicit [_key=\"...\"]\n\n const startIndex = lastPathItem.indexOf('\"') + 1\n const endIndex = lastPathItem.indexOf('\"', startIndex)\n\n key = lastPathItem.substring(startIndex, endIndex)\n\n hasExplicitKey = true\n } else {\n // indexes [int]\n const startIndex = lastPathItem.indexOf('[') + 1\n const endIndex = lastPathItem.indexOf(']', startIndex)\n\n key = lastPathItem.substring(startIndex, endIndex)\n\n hasExplicitKey = false\n }\n\n if (!path || !key) throw new Error('Invalid path')\n\n return {\n path,\n key,\n hasExplicitKey,\n }\n}\n\nexport function getArrayDuplicatePatches(\n node: SanityNode,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n snapshot: SanityDocument<Record<string, any>>,\n position: 'before' | 'after' = 'after',\n): NodePatchList {\n const {path: arrayPath, key: itemKey} = getArrayItemKeyAndParentPath(node)\n\n const item = get(snapshot, node.path) as object\n const duplicate = {...item, _key: randomKey()}\n\n return [at(arrayPath, insert(duplicate, position, {_key: itemKey}))]\n}\n\nexport function getArrayRemovePatches(\n node: SanityNode,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n snapshot: SanityDocument<Record<string, any>>,\n): NodePatchList {\n const {path: arrayPath, key: itemKey} = getArrayItemKeyAndParentPath(node)\n const array = get(snapshot, arrayPath) as {_key: string}[]\n const currentIndex = array.findIndex((item) => item._key === itemKey)\n return [at(arrayPath, truncate(currentIndex, currentIndex + 1))]\n}\n\nexport function getArrayInsertPatches(\n node: SanityNode,\n insertType: string,\n position: 'before' | 'after',\n): NodePatchList {\n const {path: arrayPath, key: itemKey} = getArrayItemKeyAndParentPath(node)\n const insertKey = randomKey()\n const referenceItem = {_key: itemKey}\n return [at(arrayPath, insert([{_type: insertType, _key: insertKey}], position, referenceItem))]\n}\n\nexport async function getArrayMovePatches(\n node: SanityNode,\n doc: OptimisticDocument,\n moveTo: 'previous' | 'next' | 'first' | 'last',\n): Promise<NodePatchList> {\n if (!node.type) throw new Error('Node type is missing')\n const {path: arrayPath, key: itemKey} = getArrayItemKeyAndParentPath(node)\n\n const snapshot = await doc.getSnapshot()\n const array = get(snapshot, arrayPath) as {_key: string}[]\n const item = get(snapshot, node.path)\n const currentIndex = array.findIndex((item) => item._key === itemKey)\n\n let nextIndex = -1\n let position: 'before' | 'after' = 'before'\n\n if (moveTo === 'first') {\n if (currentIndex === 0) return []\n nextIndex = 0\n position = 'before'\n } else if (moveTo === 'last') {\n if (currentIndex === array.length - 1) return []\n nextIndex = -1\n position = 'after'\n } else if (moveTo === 'next') {\n if (currentIndex === array.length - 1) return []\n nextIndex = currentIndex\n position = 'after'\n } else if (moveTo === 'previous') {\n if (currentIndex === 0) return []\n nextIndex = currentIndex - 1\n position = 'before'\n }\n\n return [\n at(arrayPath, truncate(currentIndex, currentIndex + 1)),\n at(arrayPath, insert(item, position, nextIndex)),\n ]\n}\n"],"names":["rePropName","reKeySegment","get","obj","path","defaultVal","select","fromString","Array","isArray","Error","acc","i","length","segment","isIndexSegment","isKeySegment","find","item","_key","segments","match","map","normalizePathSegment","normalizeIndexSegment","normalizeKeySegment","isIndexTuple","normalizeIndexTupleSegment","Number","replace","from","to","split","seg","useOptimisticActor","useSyncExternalStore","_temp","_temp2","_temp3","emptyActor","actor","listener","listeners","add","delete","useOptimisticActorReady","$","_c","t0","isEmptyActor","debounce","fn","timeout","timer","args","clearTimeout","setTimeout","apply","getDocumentsAndSnapshot","id","inFrame","isMaybePreviewIframe","inPopUp","isMaybePreviewWindow","draftId","getDraftId","publishedId","getPublishedId","documents","getSnapshot","context","draftDoc","publishedDoc","doc","snapshot","local","snapshotPromise","Promise","resolve","subscriber","on","event","unsubscribe","createDocumentCommit","send","type","createDocumentGet","getAtPath","createDocumentGetSnapshot","createDocumentPatch","patches","options","result","commit","resolvedPatches","_snapshot","mutations","createIfNotExists","_id","patch","useDocuments","documentId","getDocument","t1","t2","undefined","mutateDocument","whatwgRNG","rnds8","Uint8Array","crypto","getRandomValues","getByteHexTable","table","toString","slice","randomKey","reduce","str","n","getArrayItemKeyAndParentPath","pathOrNode","elementPath","lastDotIndex","lastIndexOf","lastPathItem","substring","indexOf","lastArrayIndex","key","hasExplicitKey","includes","startIndex","endIndex","getArrayDuplicatePatches","node","position","arrayPath","itemKey","duplicate","at","insert","getArrayRemovePatches","currentIndex","findIndex","truncate","getArrayInsertPatches","insertType","insertKey","_type","getArrayMovePatches","moveTo","array","nextIndex"],"mappings":";;;;;;;;;;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AM,OAAM,IAAI3E,MAAM,sBAAsB;AACtD,QAAM;AAAA,IAACN,MAAMqI;AAAAA,IAAWR,KAAKS;AAAAA,EAAAA,IAAWlB,6BAA6Be,IAAI,GAEnE7D,WAAW,MAAMD,IAAIJ,YAAAA,GACrBmF,QAAQtJ,IAAIwE,UAAU+D,SAAS,GAC/BvH,OAAOhB,IAAIwE,UAAU6D,KAAKnI,IAAI,GAC9B2I,eAAeS,MAAMR,UAAW9H,CAAAA,UAASA,MAAKC,SAASuH,OAAO;AAEpE,MAAIe,YAAY,IACZjB,WAA+B;AAEnC,MAAIe,WAAW,SAAS;AACtB,QAAIR,iBAAiB,EAAG,QAAO,CAAA;AAC/BU,gBAAY,GACZjB,WAAW;AAAA,EACb,WAAWe,WAAW,QAAQ;AAC5B,QAAIR,iBAAiBS,MAAM3I,SAAS,UAAU,CAAA;AAC9C4I,gBAAY,IACZjB,WAAW;AAAA,EACb,WAAWe,WAAW,QAAQ;AAC5B,QAAIR,iBAAiBS,MAAM3I,SAAS,UAAU,CAAA;AAC9C4I,gBAAYV,cACZP,WAAW;AAAA,EACb,WAAWe,WAAW,YAAY;AAChC,QAAIR,iBAAiB,EAAG,QAAO,CAAA;AAC/BU,gBAAYV,eAAe,GAC3BP,WAAW;AAAA,EACb;AAEA,SAAO,CACLI,GAAGH,WAAWQ,SAASF,cAAcA,eAAe,CAAC,CAAC,GACtDH,GAAGH,WAAWI,OAAO3H,MAAMsH,UAAUiB,SAAS,CAAC,CAAC;AAEpD;","x_google_ignoreList":[0]} | ||
| {"version":3,"file":"mutations.js","sources":["../../../../node_modules/.pnpm/@sanity+util@5.8.1_@types+react@19.2.13/node_modules/@sanity/util/lib/paths.js","../../src/react/useOptimisticActor.ts","../../src/react/useDocuments.ts","../../src/util/randomKey.ts","../../src/util/mutations.ts"],"sourcesContent":["import { isIndexSegment, isKeySegment, isIndexTuple } from \"@sanity/types\";\nconst rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g, reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/, EMPTY_PATH = [], FOCUS_TERMINATOR = \"$\", GROQ_DATA_TYPE_VALUES = [\"true\", \"false\", \"null\"];\nfunction get(obj, path, defaultVal) {\n const select = typeof path == \"string\" ? fromString(path) : path;\n if (!Array.isArray(select))\n throw new Error(\"Path must be an array or a string\");\n let acc = obj;\n for (let i = 0; i < select.length; i++) {\n const segment = select[i];\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc))\n return defaultVal;\n acc = acc[segment];\n }\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc))\n return defaultVal;\n acc = acc.find((item) => item._key === segment._key);\n }\n if (typeof segment == \"string\" && (acc = typeof acc == \"object\" && acc !== null ? acc[segment] : void 0), typeof acc > \"u\")\n return defaultVal;\n }\n return acc;\n}\nconst pathsMemo = /* @__PURE__ */ new Map();\nfunction pathFor(path) {\n if (path.length === 0)\n return EMPTY_PATH;\n const asString = toString(path);\n return pathsMemo.has(asString) ? pathsMemo.get(asString) : (pathsMemo.set(asString, path), Object.freeze(path), path);\n}\nfunction isEqual(path, otherPath) {\n return path.length === otherPath.length && path.every((segment, i) => isSegmentEqual(segment, otherPath[i]));\n}\nfunction numEqualSegments(path, otherPath) {\n const length = Math.min(path.length, otherPath.length);\n for (let i = 0; i < length; i++)\n if (!isSegmentEqual(path[i], otherPath[i]))\n return i;\n return length;\n}\nfunction isSegmentEqual(segmentA, segmentB) {\n return isKeySegment(segmentA) && isKeySegment(segmentB) ? segmentA._key === segmentB._key : isIndexSegment(segmentA) ? Number(segmentA) === Number(segmentB) : isIndexTuple(segmentA) && isIndexTuple(segmentB) ? segmentA[0] === segmentB[0] && segmentA[1] === segmentB[1] : segmentA === segmentB;\n}\nfunction hasFocus(focusPath, path) {\n const withoutTerminator = focusPath[focusPath.length - 1] === FOCUS_TERMINATOR ? focusPath.slice(0, -1) : focusPath;\n return isEqual(withoutTerminator, path);\n}\nfunction hasItemFocus(focusPath, item) {\n return focusPath.length === 1 && isSegmentEqual(focusPath[0], item);\n}\nfunction isExpanded(segment, focusPath) {\n const [head, ...tail] = focusPath;\n return tail.length > 0 && isSegmentEqual(segment, head);\n}\nfunction startsWith(prefix, path) {\n return prefix.every((segment, i) => isSegmentEqual(segment, path[i]));\n}\nfunction trimLeft(prefix, path) {\n if (prefix.length === 0 || path.length === 0)\n return path;\n const [prefixHead, ...prefixTail] = prefix, [pathHead, ...pathTail] = path;\n return isSegmentEqual(prefixHead, pathHead) ? pathFor(trimLeft(prefixTail, pathTail)) : path;\n}\nfunction trimRight(suffix, path) {\n const sufLen = suffix.length, pathLen = path.length;\n if (sufLen === 0 || pathLen === 0)\n return path;\n let i = 0;\n for (; i < sufLen && i < pathLen && isSegmentEqual(path[pathLen - i - 1], suffix[sufLen - i - 1]); )\n i++;\n return pathFor(path.slice(0, pathLen - i));\n}\nfunction trimChildPath(path, childPath) {\n return startsWith(path, childPath) ? trimLeft(path, childPath) : EMPTY_PATH;\n}\nfunction toString(path) {\n if (!Array.isArray(path))\n throw new Error(\"Path is not an array\");\n return path.reduce((target, segment, i) => {\n const isHead = i === 0;\n if (typeof segment == \"number\")\n return `${target}[${segment}]`;\n if (typeof segment == \"string\")\n return isHead ? segment : GROQ_DATA_TYPE_VALUES.includes(segment) ? `${target}[\"${segment}\"]` : `${target}.${segment}`;\n if (isKeySegment(segment) && segment._key)\n return `${target}[_key==\"${segment._key}\"]`;\n if (Array.isArray(segment)) {\n const [from, to] = segment;\n return `${target}[${from}:${to}]`;\n }\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``);\n }, \"\");\n}\nfunction _resolveKeyedPath(value, path) {\n if (path.length === 0)\n return path;\n const [next, ...rest] = path;\n if (typeof next == \"number\") {\n if (!Array.isArray(value) || !(next in value))\n return [];\n const item = value[next];\n return [typeof item?._key == \"string\" ? { _key: item._key } : next, ..._resolveKeyedPath(item, rest)];\n }\n const nextVal = get(value, [next]);\n return [next, ..._resolveKeyedPath(nextVal, rest)];\n}\nfunction resolveKeyedPath(value, path) {\n if (!Array.isArray(path))\n throw new Error(\"Path is not an array\");\n return pathFor(_resolveKeyedPath(value, path));\n}\nfunction fromString(path) {\n if (typeof path != \"string\")\n throw new Error(\"Path is not a string\");\n const segments = path.match(rePropName);\n if (!segments)\n throw new Error(\"Invalid path string\");\n return segments.map(normalizePathSegment);\n}\nfunction normalizePathSegment(segment) {\n return isIndexSegment(segment) ? normalizeIndexSegment(segment) : isKeySegment(segment) ? normalizeKeySegment(segment) : isIndexTuple(segment) ? normalizeIndexTupleSegment(segment) : segment;\n}\nfunction normalizeIndexSegment(segment) {\n return Number(segment.replace(/[^\\d]/g, \"\"));\n}\nfunction normalizeKeySegment(segment) {\n return { _key: segment.match(reKeySegment)[1] };\n}\nfunction normalizeIndexTupleSegment(segment) {\n const [from, to] = segment.split(\":\").map((seg) => seg === \"\" ? seg : Number(seg));\n return [from, to];\n}\nexport {\n FOCUS_TERMINATOR,\n _resolveKeyedPath,\n fromString,\n get,\n hasFocus,\n hasItemFocus,\n isEqual,\n isExpanded,\n isSegmentEqual,\n numEqualSegments,\n pathFor,\n resolveKeyedPath,\n startsWith,\n toString,\n trimChildPath,\n trimLeft,\n trimRight\n};\n//# sourceMappingURL=paths.js.map\n","import {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {\n actor,\n emptyActor,\n isEmptyActor,\n listeners,\n type EmptyActor,\n type MutatorActor,\n} from '../optimistic/context'\n\nexport function useOptimisticActor(): MutatorActor | EmptyActor {\n const subscribe = useCallback((listener: () => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n }, [])\n\n const actorRef = useSyncExternalStore(\n subscribe,\n () => actor,\n () => emptyActor,\n )\n\n return actorRef\n}\n\nexport function useOptimisticActorReady(): boolean {\n const actor = useOptimisticActor()\n return useMemo(() => !isEmptyActor(actor), [actor])\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {SanityDocument} from '@sanity/client'\n\nimport {getDraftId, getPublishedId} from '@sanity/client/csm'\nimport {createIfNotExists, patch} from '@sanity/mutate'\nimport {isMaybePreviewIframe, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport {get as getAtPath} from '@sanity/util/paths'\nimport {useCallback} from 'react'\n\nimport type {\n DocumentsGet,\n DocumentsMutate,\n OptimisticDocumentPatches,\n Path,\n PathValue,\n} from '../optimistic/types'\n\nimport {isEmptyActor, type MutatorActor} from '../optimistic/context'\nimport {useOptimisticActor} from './useOptimisticActor'\n\nfunction debounce<F extends (...args: Parameters<F>) => ReturnType<F>>(fn: F, timeout: number): F {\n let timer: ReturnType<typeof setTimeout>\n return ((...args: Parameters<F>) => {\n clearTimeout(timer)\n timer = setTimeout(() => {\n fn.apply(fn, args)\n }, timeout)\n }) as F\n}\n\nfunction getDocumentsAndSnapshot<T extends Record<string, any>>(id: string, actor: MutatorActor) {\n const inFrame = isMaybePreviewIframe()\n const inPopUp = isMaybePreviewWindow()\n\n if (isEmptyActor(actor) || (!inFrame && !inPopUp)) {\n throw new Error('The `useDocuments` hook cannot be used in this context')\n }\n\n const draftId = getDraftId(id)\n const publishedId = getPublishedId(id)\n const documents = actor.getSnapshot().context?.documents\n\n const draftDoc = documents?.[draftId]\n const publishedDoc = documents?.[publishedId]\n const doc = draftDoc || publishedDoc\n\n if (!doc) {\n throw new Error(`Document \"${id}\" not found`)\n }\n\n // Helper to get the snapshot from the draft document if it exists, otherwise\n // fall back to the published document\n const getDocumentSnapshot = () =>\n (draftDoc.getSnapshot().context?.local || publishedDoc.getSnapshot().context?.local) as\n | SanityDocument<T>\n | null\n | undefined\n\n const snapshot = getDocumentSnapshot()\n const snapshotPromise = new Promise<SanityDocument<T> | null>((resolve) => {\n if (snapshot) {\n resolve(snapshot)\n } else {\n const subscriber = doc.on('ready', (event) => {\n // Assert type here as the original document mutator machine doesn't\n // emit a 'ready' event. We provide a custom action to emit it in this\n // package's internal `createDatasetMutator` function. <3 xstate.\n const {snapshot} = event as unknown as {snapshot: SanityDocument<T> | null | undefined}\n resolve(snapshot || null)\n subscriber.unsubscribe()\n })\n }\n })\n\n const getSnapshot = () => snapshotPromise\n\n return {\n draftDoc,\n draftId,\n getSnapshot,\n publishedDoc,\n publishedId,\n /**\n * @deprecated - use `getSnapshot` instead\n */\n get snapshot() {\n // Maintain original error throwing behaviour, to avoid breaking changes\n if (!snapshot) {\n throw new Error(`Snapshot for document \"${id}\" not found`)\n }\n return snapshot\n },\n }\n}\n\nfunction createDocumentCommit<T extends Record<string, any>>(id: string, actor: MutatorActor) {\n return (): void => {\n const {draftDoc} = getDocumentsAndSnapshot<T>(id, actor)\n draftDoc.send({type: 'submit'})\n }\n}\n\n/**\n * @deprecated - superseded by `createDocumentGetSnapshot`\n */\nfunction createDocumentGet<T extends Record<string, any>>(id: string, actor: MutatorActor) {\n return <P extends Path<T, keyof T>>(\n path?: P,\n ): PathValue<T, P> | SanityDocument<T> | undefined => {\n const {snapshot} = getDocumentsAndSnapshot<T>(id, actor)\n\n return path\n ? (getAtPath(snapshot, path) as PathValue<T, P>)\n : (snapshot as unknown as SanityDocument<T>)\n }\n}\n\nfunction createDocumentGetSnapshot<T extends Record<string, any>>(\n id: string,\n actor: MutatorActor,\n): () => Promise<SanityDocument<T> | null> {\n const {getSnapshot} = getDocumentsAndSnapshot<T>(id, actor)\n return getSnapshot\n}\n\nfunction createDocumentPatch<T extends Record<string, any>>(id: string, actor: MutatorActor) {\n return async (\n patches: OptimisticDocumentPatches<T>,\n options?: {commit?: boolean | {debounce: number}},\n ): Promise<void> => {\n // Destructure the function result in two steps as we need access to the\n // `result.snapshot` property in the getter, but don't want to execute the\n // getter prematurely as it may throw\n const result = getDocumentsAndSnapshot<T>(id, actor)\n const {draftDoc, draftId, getSnapshot, publishedId} = result\n\n const {commit = true} = options || {}\n\n const context = {\n draftId,\n publishedId,\n /**\n * @deprecated - use `getSnapshot` instead\n */\n get snapshot() {\n return result.snapshot\n },\n getSnapshot,\n }\n\n const resolvedPatches = await (typeof patches === 'function' ? patches(context) : patches)\n\n const _snapshot = await getSnapshot()\n\n if (!_snapshot) {\n throw new Error(`Snapshot for document \"${id}\" not found`)\n }\n\n draftDoc.send({\n type: 'mutate',\n mutations: [\n // Attempt to create the draft document, it might not exist if the\n // snapshot was from the published document\n createIfNotExists({..._snapshot, _id: draftId}),\n // Patch the draft document with the resolved patches\n patch(draftId, resolvedPatches),\n ],\n })\n\n if (commit) {\n if (typeof commit === 'object' && 'debounce' in commit) {\n const debouncedCommit = debounce(() => draftDoc.send({type: 'submit'}), commit.debounce)\n debouncedCommit()\n } else {\n draftDoc.send({type: 'submit'})\n }\n }\n }\n}\n\nexport function useDocuments(): {\n getDocument: DocumentsGet\n mutateDocument: DocumentsMutate\n} {\n const actor = useOptimisticActor() as MutatorActor\n\n const getDocument: DocumentsGet = useCallback(\n <T extends Record<string, any>>(documentId: string) => {\n return {\n id: documentId,\n commit: createDocumentCommit(documentId, actor),\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Type instantiation is excessively deep and possibly infinite.\n get: createDocumentGet(documentId, actor),\n getSnapshot: createDocumentGetSnapshot<T>(documentId, actor),\n patch: createDocumentPatch<T>(documentId, actor),\n }\n },\n [actor],\n )\n\n const mutateDocument: DocumentsMutate = useCallback(\n (id, mutations, options) => {\n const {draftDoc} = getDocumentsAndSnapshot(id, actor)\n const {commit = true} = options || {}\n\n draftDoc.send({\n type: 'mutate',\n mutations: mutations,\n })\n\n if (commit) {\n if (typeof commit === 'object' && 'debounce' in commit) {\n const debouncedCommit = debounce(() => draftDoc.send({type: 'submit'}), commit.debounce)\n debouncedCommit()\n } else {\n draftDoc.send({type: 'submit'})\n }\n }\n },\n [actor],\n )\n\n return {getDocument, mutateDocument}\n}\n","// WHATWG crypto RNG - https://w3c.github.io/webcrypto/Overview.html\nfunction whatwgRNG(length = 16) {\n const rnds8 = new Uint8Array(length)\n crypto.getRandomValues(rnds8)\n return rnds8\n}\n\nconst getByteHexTable = (() => {\n let table: string[]\n return () => {\n if (table) {\n return table\n }\n table = []\n for (let i = 0; i < 256; ++i) {\n table[i] = (i + 0x100).toString(16).slice(1)\n }\n return table\n }\n})()\n\nexport function randomKey(length?: number): string {\n const table = getByteHexTable()\n return whatwgRNG(length)\n .reduce((str, n) => str + table[n], '')\n .slice(0, length)\n}\n","import type {SanityDocument} from '@sanity/client'\nimport type {SanityNode} from '@sanity/presentation-comlink'\n\nimport {at, insert, truncate, type NodePatchList} from '@sanity/mutate'\nimport {get} from '@sanity/util/paths'\n\nimport type {OptimisticDocument} from '../optimistic/types'\n\nimport {randomKey} from './randomKey'\n\nexport function getArrayItemKeyAndParentPath(pathOrNode: string | SanityNode): {\n path: string\n key: string\n hasExplicitKey: boolean\n} {\n const elementPath = typeof pathOrNode === 'string' ? pathOrNode : pathOrNode.path\n\n const lastDotIndex = elementPath.lastIndexOf('.')\n const lastPathItem = elementPath.substring(lastDotIndex + 1, elementPath.length)\n\n if (!lastPathItem.indexOf('[')) throw new Error('Invalid path: not an array')\n\n const lastArrayIndex = elementPath.lastIndexOf('[')\n const path = elementPath.substring(0, lastArrayIndex)\n\n let key\n let hasExplicitKey\n\n if (lastPathItem.includes('_key')) {\n // explicit [_key=\"...\"]\n\n const startIndex = lastPathItem.indexOf('\"') + 1\n const endIndex = lastPathItem.indexOf('\"', startIndex)\n\n key = lastPathItem.substring(startIndex, endIndex)\n\n hasExplicitKey = true\n } else {\n // indexes [int]\n const startIndex = lastPathItem.indexOf('[') + 1\n const endIndex = lastPathItem.indexOf(']', startIndex)\n\n key = lastPathItem.substring(startIndex, endIndex)\n\n hasExplicitKey = false\n }\n\n if (!path || !key) throw new Error('Invalid path')\n\n return {\n path,\n key,\n hasExplicitKey,\n }\n}\n\nexport function getArrayDuplicatePatches(\n node: SanityNode,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n snapshot: SanityDocument<Record<string, any>>,\n position: 'before' | 'after' = 'after',\n): NodePatchList {\n const {path: arrayPath, key: itemKey} = getArrayItemKeyAndParentPath(node)\n\n const item = get(snapshot, node.path) as object\n const duplicate = {...item, _key: randomKey()}\n\n return [at(arrayPath, insert(duplicate, position, {_key: itemKey}))]\n}\n\nexport function getArrayRemovePatches(\n node: SanityNode,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n snapshot: SanityDocument<Record<string, any>>,\n): NodePatchList {\n const {path: arrayPath, key: itemKey} = getArrayItemKeyAndParentPath(node)\n const array = get(snapshot, arrayPath) as {_key: string}[]\n const currentIndex = array.findIndex((item) => item._key === itemKey)\n return [at(arrayPath, truncate(currentIndex, currentIndex + 1))]\n}\n\nexport function getArrayInsertPatches(\n node: SanityNode,\n insertType: string,\n position: 'before' | 'after',\n): NodePatchList {\n const {path: arrayPath, key: itemKey} = getArrayItemKeyAndParentPath(node)\n const insertKey = randomKey()\n const referenceItem = {_key: itemKey}\n return [at(arrayPath, insert([{_type: insertType, _key: insertKey}], position, referenceItem))]\n}\n\nexport async function getArrayMovePatches(\n node: SanityNode,\n doc: OptimisticDocument,\n moveTo: 'previous' | 'next' | 'first' | 'last',\n): Promise<NodePatchList> {\n if (!node.type) throw new Error('Node type is missing')\n const {path: arrayPath, key: itemKey} = getArrayItemKeyAndParentPath(node)\n\n const snapshot = await doc.getSnapshot()\n const array = get(snapshot, arrayPath) as {_key: string}[]\n const item = get(snapshot, node.path)\n const currentIndex = array.findIndex((item) => item._key === itemKey)\n\n let nextIndex = -1\n let position: 'before' | 'after' = 'before'\n\n if (moveTo === 'first') {\n if (currentIndex === 0) return []\n nextIndex = 0\n position = 'before'\n } else if (moveTo === 'last') {\n if (currentIndex === array.length - 1) return []\n nextIndex = -1\n position = 'after'\n } else if (moveTo === 'next') {\n if (currentIndex === array.length - 1) return []\n nextIndex = currentIndex\n position = 'after'\n } else if (moveTo === 'previous') {\n if (currentIndex === 0) return []\n nextIndex = currentIndex - 1\n position = 'before'\n }\n\n return [\n at(arrayPath, truncate(currentIndex, currentIndex + 1)),\n at(arrayPath, insert(item, position, nextIndex)),\n ]\n}\n"],"names":["rePropName","reKeySegment","get","obj","path","defaultVal","select","fromString","Array","isArray","Error","acc","i","length","segment","isIndexSegment","isKeySegment","find","item","_key","segments","match","map","normalizePathSegment","normalizeIndexSegment","normalizeKeySegment","isIndexTuple","normalizeIndexTupleSegment","Number","replace","from","to","split","seg","useOptimisticActor","useSyncExternalStore","_temp","_temp2","_temp3","emptyActor","actor","listener","listeners","add","delete","useOptimisticActorReady","$","_c","t0","isEmptyActor","debounce","fn","timeout","timer","args","clearTimeout","setTimeout","apply","getDocumentsAndSnapshot","id","inFrame","isMaybePreviewIframe","inPopUp","isMaybePreviewWindow","draftId","getDraftId","publishedId","getPublishedId","documents","getSnapshot","context","draftDoc","publishedDoc","doc","snapshot","local","snapshotPromise","Promise","resolve","subscriber","on","event","unsubscribe","createDocumentCommit","send","type","createDocumentGet","getAtPath","createDocumentGetSnapshot","createDocumentPatch","patches","options","result","commit","resolvedPatches","_snapshot","mutations","createIfNotExists","_id","patch","useDocuments","documentId","getDocument","t1","t2","undefined","mutateDocument","whatwgRNG","rnds8","Uint8Array","crypto","getRandomValues","getByteHexTable","table","toString","slice","randomKey","reduce","str","n","getArrayItemKeyAndParentPath","pathOrNode","elementPath","lastDotIndex","lastIndexOf","lastPathItem","substring","indexOf","lastArrayIndex","key","hasExplicitKey","includes","startIndex","endIndex","getArrayDuplicatePatches","node","position","arrayPath","itemKey","duplicate","at","insert","getArrayRemovePatches","currentIndex","findIndex","truncate","getArrayInsertPatches","insertType","insertKey","_type","getArrayMovePatches","moveTo","array","nextIndex"],"mappings":";;;;;;;;;;;;;;;;;;;AAUA,MAAMA,aACJ,oGACIC,eAAe;AAWd,SAASC,IAAIC,KAAcC,MAAqBC,YAA+B;AACpF,QAAMC,SAAS,OAAOF,QAAS,WAAWG,WAAWH,IAAI,IAAIA;AAC7D,MAAI,CAACI,MAAMC,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QAAQtJ,IAAIwE,UAAU+D,SAAS,GAC/BvH,OAAOhB,IAAIwE,UAAU6D,KAAKnI,IAAI,GAC9B2I,eAAeS,MAAMR,UAAW9H,CAAAA,UAASA,MAAKC,SAASuH,OAAO;AAEpE,MAAIe,YAAY,IACZjB,WAA+B;AAEnC,MAAIe,WAAW,SAAS;AACtB,QAAIR,iBAAiB,EAAG,QAAO,CAAA;AAC/BU,gBAAY,GACZjB,WAAW;AAAA,EACb,WAAWe,WAAW,QAAQ;AAC5B,QAAIR,iBAAiBS,MAAM3I,SAAS,UAAU,CAAA;AAC9C4I,gBAAY,IACZjB,WAAW;AAAA,EACb,WAAWe,WAAW,QAAQ;AAC5B,QAAIR,iBAAiBS,MAAM3I,SAAS,UAAU,CAAA;AAC9C4I,gBAAYV,cACZP,WAAW;AAAA,EACb,WAAWe,WAAW,YAAY;AAChC,QAAIR,iBAAiB,EAAG,QAAO,CAAA;AAC/BU,gBAAYV,eAAe,GAC3BP,WAAW;AAAA,EACb;AAEA,SAAO,CACLI,GAAGH,WAAWQ,SAASF,cAAcA,eAAe,CAAC,CAAC,GACtDH,GAAGH,WAAWI,OAAO3H,MAAMsH,UAAUiB,SAAS,CAAC,CAAC;AAEpD;","x_google_ignoreList":[0]} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/ui/VisualEditing.tsx","../../src/react/useOptimisticActor.ts","../../src/ui/environment/context.ts","../../src/react/useVisualEditingEnvironment.ts","../../src/react/useIsPresentationTool.ts","../../src/react/usePresentationQuery.ts"],"mappings":";;;;;;;;;;cAuBa,aAAA;EAAA,QAAwB,oBAAA;IAAwB,MAAA;EAAA,IAAmB,KAAA,CAAM,SAAA;;;iBCZtE,kBAAA,CAAA,GAAsB,YAAA,GAAe,UAAA;;;;;;;KCLzC,wBAAA;;;;iBCCI,2BAAA,CAAA,GAA+B,wBAAA;;;;;;iBCA/B,qBAAA,CAAA;;KCUJ,mCAAA;EACV,IAAA;EACA,SAAA;EACA,WAAA;AAAA;;KAIU,iCAAA;EACV,IAAA,EAAM,YAAA,CAAa,WAAA;EACnB,SAAA,EAAW,gBAAA;EACX,WAAA,EAAa,iBAAA;AAAA;;;;;;KAQH,2BAAA,+BACR,mCAAA,GACA,iCAAA,CAAkC,WAAA;;;AJ1BtC;;;;;;ACLA;iBGiFgB,oBAAA,kCAAA,CAAuD,KAAA;EACrE,KAAA,EAAO,WAAA;EACP,MAAA,GAAS,WAAA,GAAc,OAAA,CAAQ,WAAA;EAC/B,KAAA;AAAA,IACE,2BAAA,CAA4B,WAAA"} | ||
| {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/ui/VisualEditing.tsx","../../src/react/useOptimisticActor.ts","../../src/ui/environment/context.ts","../../src/react/useVisualEditingEnvironment.ts","../../src/react/useIsPresentationTool.ts","../../src/react/usePresentationQuery.ts"],"mappings":";;;;;;;;;;cA4Ba,aAAA;EAAA,QAAwB,oBAAA;IAAwB,MAAA;EAAA,IAAmB,KAAA,CAAM,SAAA;;;iBCjBtE,kBAAA,CAAA,GAAsB,YAAA,GAAe,UAAA;;;;;;;KCLzC,wBAAA;;;;iBCCI,2BAAA,CAAA,GAA+B,wBAAA;;;;;;iBCA/B,qBAAA,CAAA;;KCUJ,mCAAA;EACV,IAAA;EACA,SAAA;EACA,WAAA;AAAA;;KAIU,iCAAA;EACV,IAAA,EAAM,YAAA,CAAa,WAAA;EACnB,SAAA,EAAW,gBAAA;EACX,WAAA,EAAa,iBAAA;AAAA;;;;;;KAQH,2BAAA,+BACR,mCAAA,GACA,iCAAA,CAAkC,WAAA;;;AJ1BtC;;;;;;ACLA;iBGiFgB,oBAAA,kCAAA,CAAuD,KAAA;EACrE,KAAA,EAAO,WAAA;EACP,MAAA,GAAS,WAAA,GAAc,OAAA,CAAQ,WAAA;EAC/B,KAAA;AAAA,IACE,2BAAA,CAA4B,WAAA"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.js","sources":["../../src/react/useVisualEditingEnvironment.ts","../../src/react/useIsPresentationTool.ts","../../src/react/usePresentationQuery.ts"],"sourcesContent":["import {useDeferredValue, useSyncExternalStore} from 'react'\n\nimport {type VisualEditingEnvironment, subscribe, getSnapshot} from '../ui/environment/context'\n\n/**\n * @alpha - unstable API, may have breaking changes in a minor release\n */\nexport function useVisualEditingEnvironment(): VisualEditingEnvironment {\n const environment = useSyncExternalStore(subscribe, getSnapshot, () => null)\n return useDeferredValue(environment, null)\n}\n","import {useVisualEditingEnvironment} from './useVisualEditingEnvironment'\n\n/**\n * Initially returns `null`, until `<VisualEditing />` is rendered on the page.\n * Returns `false` if there's no parent window context with Presentation Tool connected over comlink.\n * Returns `true` when a connection is established over comlink and window.postMessage, the handshake might take a while and the hook may return `false` initially before it eventually returns `true`.\n */\nexport function useIsPresentationTool(): null | boolean {\n const env = useVisualEditingEnvironment()\n if (env === null) return null\n return env === 'presentation-iframe' || env === 'presentation-window'\n}\n","import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} from '@sanity/client'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\n\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport {dequal} from 'dequal/lite'\nimport {useEffect, useEffectEvent, useMemo, useReducer, useSyncExternalStore} from 'react'\n\nimport {\n addQueryListener,\n comlink as comlinkSnapshot,\n comlinkDataset,\n comlinkPerspective,\n comlinkProjectId,\n subscribe,\n} from '../ui/loader-comlink/context'\n\n/** @alpha */\nexport type UsePresentationQueryReturnsInactive = {\n data: null\n sourceMap: null\n perspective: null\n}\n\n/** @alpha */\nexport type UsePresentationQueryReturnsActive<QueryString extends string> = {\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n perspective: ClientPerspective\n}\n\n/**\n * Returns the inactive state when no Presentation Tool connection is available,\n * or the active state with query results when connected.\n * @alpha\n */\nexport type UsePresentationQueryReturns<QueryString extends string> =\n | UsePresentationQueryReturnsInactive\n | UsePresentationQueryReturnsActive<QueryString>\n\ntype Action<QueryString extends string> = {\n type: 'query-change'\n payload: UsePresentationQueryReturnsActive<QueryString>\n}\n\nfunction reducer<QueryString extends string>(\n state: UsePresentationQueryReturns<QueryString>,\n {type, payload}: Action<QueryString>,\n): UsePresentationQueryReturns<QueryString> {\n switch (type) {\n case 'query-change':\n return dequal(state, payload)\n ? state\n : {\n ...state,\n data: dequal(state.data, payload.data)\n ? (state.data as ClientReturn<QueryString>)\n : payload.data,\n sourceMap: dequal(state.sourceMap, payload.sourceMap)\n ? state.sourceMap\n : payload.sourceMap,\n perspective: dequal(state.perspective, payload.perspective)\n ? (state.perspective as Exclude<ClientPerspective, 'raw'>)\n : payload.perspective,\n }\n default:\n return state\n }\n}\n\nconst initialState: UsePresentationQueryReturnsInactive = {\n data: null,\n sourceMap: null,\n perspective: null,\n}\n\nconst EMPTY_QUERY_PARAMS: QueryParams = {}\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * Experimental hook that can run queries in Presentation Tool.\n * Query results are sent back over postMessage whenever the query results change.\n * It also works with optimistic updates in the studio itself, offering low latency updates.\n * It's not as low latency as the `useOptimistic` hook, but it's a good compromise for some use cases.\n *\n * Requires `<VisualEditing />` to be rendered on the page to establish the comlink connection.\n * @alpha\n */\nexport function usePresentationQuery<const QueryString extends string>(props: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n}): UsePresentationQueryReturns<QueryString> {\n const [state, dispatch] = useReducer(reducer, initialState)\n const {query, params = EMPTY_QUERY_PARAMS, stega = true} = props\n\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n\n const projectId = useSyncExternalStore(\n subscribe,\n () => comlinkProjectId,\n () => null,\n )\n\n const dataset = useSyncExternalStore(\n subscribe,\n () => comlinkDataset,\n () => null,\n )\n\n const perspective = useSyncExternalStore(\n subscribe,\n () => comlinkPerspective,\n () => null,\n )\n\n // Register this hook instance as a query listener so LoaderComlink is mounted\n useEffect(() => addQueryListener(), [])\n\n const handleQueryHeartbeat = useEffectEvent(\n (comlink: NonNullable<typeof comlinkSnapshot>) => {\n if (!projectId || !dataset || !perspective) return\n comlink.post('loader/query-listen', {\n projectId,\n dataset,\n perspective,\n query,\n params,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n },\n )\n\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {projectId, dataset, query, params},\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n dispatch({\n type: 'query-change',\n payload: {\n data: event.result,\n sourceMap: event.resultSourceMap || null,\n perspective: event.perspective,\n },\n })\n }\n },\n )\n\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n\n // Send initial heartbeat immediately\n handleQueryHeartbeat(comlink)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n return useMemo(() => {\n if (stega && state.sourceMap) {\n return {\n ...state,\n data: stegaEncodeSourceMap(state.data, state.sourceMap, {enabled: true, studioUrl: '/'}),\n }\n }\n return state\n }, [state, stega])\n}\n"],"names":["useVisualEditingEnvironment","environment","useSyncExternalStore","subscribe","getSnapshot","_temp","useDeferredValue","useIsPresentationTool","env","reducer","state","type","payload","dequal","data","sourceMap","perspective","initialState","EMPTY_QUERY_PARAMS","LISTEN_HEARTBEAT_INTERVAL","usePresentationQuery","props","$","_c","dispatch","useReducer","query","params","t0","stega","t1","undefined","comlink","_temp2","projectId","_temp3","_temp4","dataset","_temp5","_temp6","_temp7","_temp8","t2","Symbol","for","useEffect","_temp9","t3","comlink_0","post","heartbeat","handleQueryHeartbeat","useEffectEvent","t4","event","result","resultSourceMap","handleQueryChange","t5","unsubscribe","on","interval","setInterval","clearInterval","t6","t7","bb0","t8","stegaEncodeSourceMap","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,UAAAiD;AAAAjD,QAAA,EAAA,MAAAZ,SAAAY,UAAA6C,MAFnFI,KAAA;AAAA,QAAA,GACF7D;AAAAA,QAAKI,MACFqD;AAAAA,MAAAA,GACP7C,QAAAZ,OAAAY,QAAA6C,IAAA7C,QAAAiD,MAAAA,KAAAjD,EAAA,EAAA,GAHD2C,KAAOM;AAAP,YAAAL;AAAAA,IAGC;AAEHD,SAAOvD;AAAAA,EAAK;AAAA,SAPPuD;AAQW;AAjGb,SAAAnB,SAAA;AAAA,SAiCW0B,iBAAAA;AAAkB;AAjC7B,SAAA/B,SAAA;AAAA,SA6BG;AAAI;AA7BP,SAAAD,SAAA;AAAA,SA4BGiC;AAAkB;AA5BrB,SAAAlC,SAAA;AAAA,SAuBG;AAAI;AAvBP,SAAAD,SAAA;AAAA,SAsBGoC;AAAc;AAtBjB,SAAAtC,SAAA;AAAA,SAiBG;AAAI;AAjBP,SAAAD,SAAA;AAAA,SAgBGwC;AAAgB;AAhBnB,SAAA1C,SAAA;AAAA,SAWG;AAAI;AAXP,SAAA5B,QAAA;AAAA,SAUGuE;AAAe;"} | ||
| {"version":3,"file":"index.js","sources":["../../src/react/useVisualEditingEnvironment.ts","../../src/react/useIsPresentationTool.ts","../../src/react/usePresentationQuery.ts"],"sourcesContent":["import {useDeferredValue, useSyncExternalStore} from 'react'\n\nimport {type VisualEditingEnvironment, subscribe, getSnapshot} from '../ui/environment/context'\n\n/**\n * @alpha - unstable API, may have breaking changes in a minor release\n */\nexport function useVisualEditingEnvironment(): VisualEditingEnvironment {\n const environment = useSyncExternalStore(subscribe, getSnapshot, () => null)\n return useDeferredValue(environment, null)\n}\n","import {useVisualEditingEnvironment} from './useVisualEditingEnvironment'\n\n/**\n * Initially returns `null`, until `<VisualEditing />` is rendered on the page.\n * Returns `false` if there's no parent window context with Presentation Tool connected over comlink.\n * Returns `true` when a connection is established over comlink and window.postMessage, the handshake might take a while and the hook may return `false` initially before it eventually returns `true`.\n */\nexport function useIsPresentationTool(): null | boolean {\n const env = useVisualEditingEnvironment()\n if (env === null) return null\n return env === 'presentation-iframe' || env === 'presentation-window'\n}\n","import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} from '@sanity/client'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\n\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport {dequal} from 'dequal/lite'\nimport {useEffect, useEffectEvent, useMemo, useReducer, useSyncExternalStore} from 'react'\n\nimport {\n addQueryListener,\n comlink as comlinkSnapshot,\n comlinkDataset,\n comlinkPerspective,\n comlinkProjectId,\n subscribe,\n} from '../ui/loader-comlink/context'\n\n/** @alpha */\nexport type UsePresentationQueryReturnsInactive = {\n data: null\n sourceMap: null\n perspective: null\n}\n\n/** @alpha */\nexport type UsePresentationQueryReturnsActive<QueryString extends string> = {\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n perspective: ClientPerspective\n}\n\n/**\n * Returns the inactive state when no Presentation Tool connection is available,\n * or the active state with query results when connected.\n * @alpha\n */\nexport type UsePresentationQueryReturns<QueryString extends string> =\n | UsePresentationQueryReturnsInactive\n | UsePresentationQueryReturnsActive<QueryString>\n\ntype Action<QueryString extends string> = {\n type: 'query-change'\n payload: UsePresentationQueryReturnsActive<QueryString>\n}\n\nfunction reducer<QueryString extends string>(\n state: UsePresentationQueryReturns<QueryString>,\n {type, payload}: Action<QueryString>,\n): UsePresentationQueryReturns<QueryString> {\n switch (type) {\n case 'query-change':\n return dequal(state, payload)\n ? state\n : {\n ...state,\n data: dequal(state.data, payload.data)\n ? (state.data as ClientReturn<QueryString>)\n : payload.data,\n sourceMap: dequal(state.sourceMap, payload.sourceMap)\n ? state.sourceMap\n : payload.sourceMap,\n perspective: dequal(state.perspective, payload.perspective)\n ? (state.perspective as Exclude<ClientPerspective, 'raw'>)\n : payload.perspective,\n }\n default:\n return state\n }\n}\n\nconst initialState: UsePresentationQueryReturnsInactive = {\n data: null,\n sourceMap: null,\n perspective: null,\n}\n\nconst EMPTY_QUERY_PARAMS: QueryParams = {}\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * Experimental hook that can run queries in Presentation Tool.\n * Query results are sent back over postMessage whenever the query results change.\n * It also works with optimistic updates in the studio itself, offering low latency updates.\n * It's not as low latency as the `useOptimistic` hook, but it's a good compromise for some use cases.\n *\n * Requires `<VisualEditing />` to be rendered on the page to establish the comlink connection.\n * @alpha\n */\nexport function usePresentationQuery<const QueryString extends string>(props: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n}): UsePresentationQueryReturns<QueryString> {\n const [state, dispatch] = useReducer(reducer, initialState)\n const {query, params = EMPTY_QUERY_PARAMS, stega = true} = props\n\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n\n const projectId = useSyncExternalStore(\n subscribe,\n () => comlinkProjectId,\n () => null,\n )\n\n const dataset = useSyncExternalStore(\n subscribe,\n () => comlinkDataset,\n () => null,\n )\n\n const perspective = useSyncExternalStore(\n subscribe,\n () => comlinkPerspective,\n () => null,\n )\n\n // Register this hook instance as a query listener so LoaderComlink is mounted\n useEffect(() => addQueryListener(), [])\n\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n if (!projectId || !dataset || !perspective) return\n comlink.post('loader/query-listen', {\n projectId,\n dataset,\n perspective,\n query,\n params,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {projectId, dataset, query, params},\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n dispatch({\n type: 'query-change',\n payload: {\n data: event.result,\n sourceMap: event.resultSourceMap || null,\n perspective: event.perspective,\n },\n })\n }\n },\n )\n\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n\n // Send initial heartbeat immediately\n handleQueryHeartbeat(comlink)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n return useMemo(() => {\n if (stega && state.sourceMap) {\n return {\n ...state,\n data: stegaEncodeSourceMap(state.data, state.sourceMap, {enabled: true, studioUrl: '/'}),\n }\n }\n return state\n }, [state, stega])\n}\n"],"names":["useVisualEditingEnvironment","environment","useSyncExternalStore","subscribe","getSnapshot","_temp","useDeferredValue","useIsPresentationTool","env","reducer","state","type","payload","dequal","data","sourceMap","perspective","initialState","EMPTY_QUERY_PARAMS","LISTEN_HEARTBEAT_INTERVAL","usePresentationQuery","props","$","_c","dispatch","useReducer","query","params","t0","stega","t1","undefined","comlink","_temp2","projectId","_temp3","_temp4","dataset","_temp5","_temp6","_temp7","_temp8","t2","Symbol","for","useEffect","_temp9","t3","comlink_0","post","heartbeat","handleQueryHeartbeat","useEffectEvent","t4","event","result","resultSourceMap","handleQueryChange","t5","unsubscribe","on","interval","setInterval","clearInterval","t6","t7","bb0","t8","stegaEncodeSourceMap","enabled","studioUrl","t9","addQueryListener","comlinkPerspective","comlinkDataset","comlinkProjectId","comlinkSnapshot"],"mappings":";;;;;;;;;;;AAOO,SAAAA,8BAAA;AACL,QAAAC,cAAoBC,qBAAqBC,WAAWC,aAAaC,OAAU;AAAC,SACrEC,iBAAiBL,aAAa,IAAI;AAAC;AAFrC,SAAAI,UAAA;AAAA,SACkE;AAAI;ACDtE,SAAAE,wBAAA;AACL,QAAAC,MAAYR,4BAAAA;AACZ,SAAIQ,QAAQ,OAAa,OAClBA,QAAQ,yBAAyBA,QAAQ;AAAqB;ACkCvE,SAASC,QACPC,OACA;AAAA,EAACC;AAAAA,EAAMC;AAA4B,GACO;AAC1C,SAAQD,SACD,iBACIE,OAAOH,OAAOE,OAAO,IACxBF,QACA;AAAA,IACE,GAAGA;AAAAA,IACHI,MAAM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c;AAtBjB,SAAAtC,SAAA;AAAA,SAiBG;AAAI;AAjBP,SAAAD,SAAA;AAAA,SAgBGwC;AAAgB;AAhBnB,SAAA1C,SAAA;AAAA,SAWG;AAAI;AAXP,SAAA5B,QAAA;AAAA,SAUGuE;AAAe;"} |
+8
-8
| { | ||
| "name": "@sanity/visual-editing", | ||
| "version": "5.3.3", | ||
| "version": "5.3.4", | ||
| "keywords": [ | ||
@@ -64,8 +64,8 @@ "overlays", | ||
| "xstate": "^5.26.0", | ||
| "@sanity/insert-menu": "^3.0.4", | ||
| "@sanity/visual-editing-csm": "^3.0.6", | ||
| "@sanity/preview-url-secret": "^4.0.4" | ||
| "@sanity/insert-menu": "^3.0.5", | ||
| "@sanity/visual-editing-csm": "^3.0.7", | ||
| "@sanity/preview-url-secret": "^4.0.5" | ||
| }, | ||
| "devDependencies": { | ||
| "@sanity/client": "^7.18.0", | ||
| "@sanity/client": "^7.21.0", | ||
| "@sanity/demo": "^2.0.0", | ||
@@ -93,4 +93,4 @@ "@sanity/pkg-utils": "^10.4.4", | ||
| "ls-engines": "^0.10.0", | ||
| "react": "^19.2.4", | ||
| "react-dom": "^19.2.4", | ||
| "react": "^19.2.5", | ||
| "react-dom": "^19.2.5", | ||
| "react-router": "^7.7.1", | ||
@@ -109,3 +109,3 @@ "rimraf": "^5.0.5", | ||
| "peerDependencies": { | ||
| "@sanity/client": "^7.18.0", | ||
| "@sanity/client": "^7.21.0", | ||
| "@sveltejs/kit": ">= 2", | ||
@@ -112,0 +112,0 @@ "next": ">=16.0.0-0", |
@@ -123,15 +123,13 @@ import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} from '@sanity/client' | ||
| const handleQueryHeartbeat = useEffectEvent( | ||
| (comlink: NonNullable<typeof comlinkSnapshot>) => { | ||
| if (!projectId || !dataset || !perspective) return | ||
| comlink.post('loader/query-listen', { | ||
| projectId, | ||
| dataset, | ||
| perspective, | ||
| query, | ||
| params, | ||
| heartbeat: LISTEN_HEARTBEAT_INTERVAL, | ||
| }) | ||
| }, | ||
| ) | ||
| const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => { | ||
| if (!projectId || !dataset || !perspective) return | ||
| comlink.post('loader/query-listen', { | ||
| projectId, | ||
| dataset, | ||
| perspective, | ||
| query, | ||
| params, | ||
| heartbeat: LISTEN_HEARTBEAT_INTERVAL, | ||
| }) | ||
| }) | ||
@@ -138,0 +136,0 @@ const handleQueryChange = useEffectEvent( |
@@ -28,6 +28,3 @@ import type {ClientPerspective} from '@sanity/client' | ||
| /** @internal */ | ||
| export function setLoaderClientConfig( | ||
| projectId: string | null, | ||
| dataset: string | null, | ||
| ): void { | ||
| export function setLoaderClientConfig(projectId: string | null, dataset: string | null): void { | ||
| comlinkProjectId = projectId | ||
@@ -34,0 +31,0 @@ comlinkDataset = dataset |
@@ -9,3 +9,7 @@ import {createNode, createNodeMachine} from '@sanity/comlink' | ||
| import {setLoaderClientConfig, setLoaderComlink, setLoaderPerspective} from './loader-comlink/context' | ||
| import { | ||
| setLoaderClientConfig, | ||
| setLoaderComlink, | ||
| setLoaderPerspective, | ||
| } from './loader-comlink/context' | ||
@@ -12,0 +16,0 @@ /** |
@@ -0,1 +1,2 @@ | ||
| import type {ClientPerspective} from '@sanity/client' | ||
| import type {VisualEditingControllerMsg} from '@sanity/presentation-comlink' | ||
@@ -6,3 +7,2 @@ | ||
| import type {OverlayMsg, VisualEditingNode} from '../types' | ||
| import type { ClientPerspective } from '@sanity/client' | ||
@@ -9,0 +9,0 @@ export function usePerspectiveSync( |
+14
-10
| import {isMaybePreviewIframe, isMaybePreviewWindow} from '@sanity/presentation-comlink' | ||
| import {lazy, startTransition, Suspense, useDeferredValue, useEffect, useState, useSyncExternalStore} from 'react' | ||
| import { | ||
| lazy, | ||
| startTransition, | ||
| Suspense, | ||
| useDeferredValue, | ||
| useEffect, | ||
| useState, | ||
| useSyncExternalStore, | ||
| } from 'react' | ||
| import {createPortal} from 'react-dom' | ||
@@ -9,6 +17,3 @@ | ||
| import {History} from './History' | ||
| import { | ||
| getQueryListenerStatus, | ||
| subscribeQueryListenerStatus, | ||
| } from './loader-comlink/context' | ||
| import {getQueryListenerStatus, subscribeQueryListenerStatus} from './loader-comlink/context' | ||
| import {Meta} from './Meta' | ||
@@ -54,7 +59,6 @@ import {Overlays} from './Overlays' | ||
| const hasQueryListeners = useDeferredValue(useSyncExternalStore( | ||
| subscribeQueryListenerStatus, | ||
| getQueryListenerStatus, | ||
| () => false, | ||
| ), false) | ||
| const hasQueryListeners = useDeferredValue( | ||
| useSyncExternalStore(subscribeQueryListenerStatus, getQueryListenerStatus, () => false), | ||
| false, | ||
| ) | ||
@@ -61,0 +65,0 @@ useEffect(() => { |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
1048143
0.05%13641
0.02%