next-sanity 13.0.0-cache-components.17 → 13.0.0-cache-components.18

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.
@@ -1,4 +1,4 @@
1
- import { f as setPerspective, l as setComlink, u as setComlinkClientConfig } from "./context.js";
1
+ import { c as setComlinkPerspective, o as setComlink, s as setComlinkClientConfig } from "./context.js";
2
2
  import { t as sanitizePerspective } from "./sanitizePerspective.js";
3
3
  import { useEffect, useEffectEvent } from "react";
4
4
  import { createNode, createNodeMachine } from "@sanity/comlink";
@@ -9,7 +9,7 @@ function PresentationComlink(props) {
9
9
  setComlinkClientConfig(projectId, dataset);
10
10
  }, [dataset, projectId]);
11
11
  const handlePerspectiveChange = useEffectEvent((perspective) => {
12
- setPerspective(sanitizePerspective(perspective, "drafts"));
12
+ setComlinkPerspective(sanitizePerspective(perspective, "drafts"));
13
13
  });
14
14
  useEffect(() => {
15
15
  const controller = new AbortController();
@@ -1 +1 @@
1
- {"version":3,"file":"PresentationComlink.js","names":[],"sources":["../src/live/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\n\nimport {setComlink, setComlinkClientConfig, setPerspective} from '#live/context'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {createNode, createNodeMachine} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {useEffect, useEffectEvent} from 'react'\n\nexport default function PresentationComlink(props: {\n projectId: string\n dataset: string\n}): React.JSX.Element | null {\n const {projectId, dataset} = props\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent((perspective: ClientPerspective) => {\n setPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n\n useEffect(() => {\n const controller = new AbortController()\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {name: 'loaders', connectTo: 'presentation'},\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n comlink.on('loader/perspective', (data) => {\n if (controller.signal.aborted) return\n\n handlePerspectiveChange(data.perspective)\n })\n\n const stop = comlink.start()\n setComlink(comlink)\n return () => {\n stop()\n controller.abort()\n }\n }, [])\n\n return null\n}\n\nPresentationComlink.displayName = 'PresentationComlink'\n"],"mappings":";;;;;AAYA,SAAwB,oBAAoB,OAGf;CAC3B,MAAM,EAAC,WAAW,YAAW;AAE7B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAAgB,gBAAmC;AACjF,iBAAe,oBAAoB,aAAa,SAAS,CAAC;GAC1D;AAEF,iBAAgB;EACd,MAAM,aAAa,IAAI,iBAAiB;EACxC,MAAM,UAAU,WACd;GAAC,MAAM;GAAW,WAAW;GAAe,EAC5C,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;AAED,UAAQ,GAAG,uBAAuB,SAAS;AACzC,OAAI,WAAW,OAAO,QAAS;AAE/B,2BAAwB,KAAK,YAAY;IACzC;EAEF,MAAM,OAAO,QAAQ,OAAO;AAC5B,aAAW,QAAQ;AACnB,eAAa;AACX,SAAM;AACN,cAAW,OAAO;;IAEnB,EAAE,CAAC;AAEN,QAAO;;AAGT,oBAAoB,cAAc"}
1
+ {"version":3,"file":"PresentationComlink.js","names":[],"sources":["../src/live/client-components/PresentationComlink.tsx"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\n\nimport {setComlink, setComlinkClientConfig, setComlinkPerspective} from '#live/context'\nimport {sanitizePerspective} from '#live/sanitizePerspective'\nimport {createNode, createNodeMachine} from '@sanity/comlink'\nimport {\n createCompatibilityActors,\n type LoaderControllerMsg,\n type LoaderNodeMsg,\n} from '@sanity/presentation-comlink'\nimport {useEffect, useEffectEvent} from 'react'\n\nexport default function PresentationComlink(props: {\n projectId: string\n dataset: string\n}): React.JSX.Element | null {\n const {projectId, dataset} = props\n\n useEffect(() => {\n setComlinkClientConfig(projectId, dataset)\n }, [dataset, projectId])\n\n const handlePerspectiveChange = useEffectEvent((perspective: ClientPerspective) => {\n setComlinkPerspective(sanitizePerspective(perspective, 'drafts'))\n })\n\n useEffect(() => {\n const controller = new AbortController()\n const comlink = createNode<LoaderNodeMsg, LoaderControllerMsg>(\n {name: 'loaders', connectTo: 'presentation'},\n createNodeMachine<LoaderNodeMsg, LoaderControllerMsg>().provide({\n actors: createCompatibilityActors<LoaderNodeMsg>(),\n }),\n )\n\n comlink.on('loader/perspective', (data) => {\n if (controller.signal.aborted) return\n\n handlePerspectiveChange(data.perspective)\n })\n\n const stop = comlink.start()\n setComlink(comlink)\n return () => {\n stop()\n controller.abort()\n }\n }, [])\n\n return null\n}\n\nPresentationComlink.displayName = 'PresentationComlink'\n"],"mappings":";;;;;AAYA,SAAwB,oBAAoB,OAGf;CAC3B,MAAM,EAAC,WAAW,YAAW;AAE7B,iBAAgB;AACd,yBAAuB,WAAW,QAAQ;IACzC,CAAC,SAAS,UAAU,CAAC;CAExB,MAAM,0BAA0B,gBAAgB,gBAAmC;AACjF,wBAAsB,oBAAoB,aAAa,SAAS,CAAC;GACjE;AAEF,iBAAgB;EACd,MAAM,aAAa,IAAI,iBAAiB;EACxC,MAAM,UAAU,WACd;GAAC,MAAM;GAAW,WAAW;GAAe,EAC5C,mBAAuD,CAAC,QAAQ,EAC9D,QAAQ,2BAA0C,EACnD,CAAC,CACH;AAED,UAAQ,GAAG,uBAAuB,SAAS;AACzC,OAAI,WAAW,OAAO,QAAS;AAE/B,2BAAwB,KAAK,YAAY;IACzC;EAEF,MAAM,OAAO,QAAQ,OAAO;AAC5B,aAAW,QAAQ;AACnB,eAAa;AACX,SAAM;AACN,cAAW,OAAO;;IAEnB,EAAE,CAAC;AAEN,QAAO;;AAGT,oBAAoB,cAAc"}
@@ -1,12 +1,11 @@
1
1
  import { n as PUBLISHED_SYNC_TAG_PREFIX } from "./constants.js";
2
- import { d as setEnvironment } from "./context.js";
3
2
  import { t as isCorsOriginError } from "./isCorsOriginError.js";
4
3
  import { useRouter } from "next/navigation";
5
4
  import { useEffect, useEffectEvent, useMemo, useState } from "react";
6
5
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
6
  import { createClient } from "@sanity/client";
8
7
  import dynamic from "next/dynamic";
9
- import { isMaybePresentation, isMaybePreviewWindow } from "@sanity/presentation-comlink";
8
+ import { isMaybePresentation } from "@sanity/presentation-comlink";
10
9
  const PresentationComlink = dynamic(() => import("./PresentationComlink.js"));
11
10
  const RefreshOnMount = dynamic(() => import("./RefreshOnMount.js"));
12
11
  const RefreshOnFocus = dynamic(() => import("./RefreshOnFocus.js"));
@@ -77,17 +76,13 @@ function SanityLive(props) {
77
76
  useEffect(() => {
78
77
  if (!isMaybePresentation()) return;
79
78
  const controller = new AbortController();
80
- const timeout = setTimeout(() => setEnvironment("live"), 3e3);
81
79
  window.addEventListener("message", ({ data }) => {
82
80
  if (data && typeof data === "object" && "domain" in data && data.domain === "sanity/channels" && "from" in data && data.from === "presentation") {
83
- clearTimeout(timeout);
84
- setEnvironment(isMaybePreviewWindow() ? "presentation-window" : "presentation-iframe");
85
81
  setLoadComlink(true);
86
82
  controller.abort();
87
83
  }
88
84
  }, { signal: controller.signal });
89
85
  return () => {
90
- clearTimeout(timeout);
91
86
  controller.abort();
92
87
  };
93
88
  }, []);
@@ -1 +1 @@
1
- {"version":3,"file":"SanityLive.js","names":[],"sources":["../src/live/client-components/SanityLive.tsx"],"sourcesContent":["import {PUBLISHED_SYNC_TAG_PREFIX} from '#live/constants'\nimport {setEnvironment} from '#live/context'\nimport {isCorsOriginError} from '#live/isCorsOriginError'\nimport {\n createClient,\n type ClientPerspective,\n type InitializedClientConfig,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {isMaybePresentation, isMaybePreviewWindow} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useState, useEffectEvent} from 'react'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'))\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'))\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'))\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'))\n\ninterface SanityClientConfig extends Pick<\n InitializedClientConfig,\n | 'projectId'\n | 'dataset'\n | 'apiHost'\n | 'apiVersion'\n | 'useProjectHostname'\n | 'token'\n | 'requestTagPrefix'\n> {}\n\nexport interface SanityLiveProps {\n config: SanityClientConfig\n /**\n * Setting this to 'published' opens one live event connection, setting it to any other value opens both the live event connections if needed\n */\n perspective: Exclude<ClientPerspective, 'raw'>\n\n onLiveEvent: (tags: string[]) => Promise<void | 'refresh'>\n onLiveEventIncludingDrafts: (tags: string[]) => Promise<void | 'refresh'>\n\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n requestTag: string\n\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n}\n\nfunction handleError(error: unknown) {\n if (isCorsOriginError(error)) {\n console.warn(\n `Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`,\n error.addOriginUrl && `Add it here:`,\n error.addOriginUrl?.toString(),\n )\n } else {\n console.error(error)\n }\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n if (intervalOnGoAway) {\n console.warn(\n 'Sanity Live connection closed, switching to long polling set to a interval of',\n intervalOnGoAway / 1000,\n 'seconds and the server gave this reason:',\n event.reason,\n )\n } else {\n console.error(\n 'Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:',\n event.reason,\n )\n }\n}\n\nfunction SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n onLiveEvent,\n // onLiveEventIncludingDrafts,\n perspective,\n\n refreshOnMount = false,\n refreshOnFocus = perspective !== 'published'\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag,\n onError = handleError,\n onGoAway = handleOnGoAway,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n const [longPollingInterval, setLongPollingInterval] = useState<number | false>(false)\n\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : perspective === 'published'\n ? 'automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool.'\n : 'automatic revalidation of published content',\n )\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n setLongPollingInterval(false)\n } else if (event.type === 'message') {\n void onLiveEvent(\n event.tags.map((tag: SyncTag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}` as const),\n ).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(intervalOnGoAway)\n }\n })\n useEffect(() => {\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n // console.error('What?', err)\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n const [loadComlink, setLoadComlink] = useState(false)\n\n /**\n * 4. If Presentation Tool is detected, load up the comlink and integrate with it\n */\n useEffect(() => {\n if (!isMaybePresentation()) return\n const controller = new AbortController()\n // Wait for a while to see if Presentation Tool is detected, before assuming the env to be stand-alone live preview\n const timeout = setTimeout(() => setEnvironment('live'), 3_000)\n window.addEventListener(\n 'message',\n ({data}: MessageEvent<unknown>) => {\n if (\n data &&\n typeof data === 'object' &&\n 'domain' in data &&\n data.domain === 'sanity/channels' &&\n 'from' in data &&\n data.from === 'presentation'\n ) {\n clearTimeout(timeout)\n setEnvironment(isMaybePreviewWindow() ? 'presentation-window' : 'presentation-iframe')\n setLoadComlink(true)\n controller.abort()\n }\n },\n {signal: controller.signal},\n )\n return () => {\n clearTimeout(timeout)\n controller.abort()\n }\n }, [])\n\n /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\n\n return (\n <>\n {loadComlink && <PresentationComlink projectId={projectId!} dataset={dataset!} />}\n {refreshOnMount && <RefreshOnMount />}\n {refreshOnFocus && <RefreshOnFocus />}\n {refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n\nSanityLive.displayName = 'SanityLiveClientComponent'\n\nexport default SanityLive\n"],"mappings":";;;;;;;;;AAgBA,MAAM,sBAAsB,cAAc,OAAO,4BAAyB;AAC1E,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,iBAAiB,cAAc,OAAO,uBAAoB;AAChE,MAAM,qBAAqB,cAAc,OAAO,2BAAwB;AAqCxE,SAAS,YAAY,OAAgB;AACnC,KAAI,kBAAkB,MAAM,CAC1B,SAAQ,KACN,8EAA8E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X} from '#live/constants'\nimport {isCorsOriginError} from '#live/isCorsOriginError'\nimport {\n createClient,\n type ClientPerspective,\n type InitializedClientConfig,\n type LiveEvent,\n type LiveEventGoAway,\n type SyncTag,\n} from '@sanity/client'\nimport {\n isMaybePresentation,\n\n // isMaybePreviewWindow\n} from '@sanity/presentation-comlink'\nimport dynamic from 'next/dynamic'\nimport {useRouter} from 'next/navigation'\nimport {useEffect, useMemo, useState, useEffectEvent} from 'react'\n\nconst PresentationComlink = dynamic(() => import('./PresentationComlink'))\nconst RefreshOnMount = dynamic(() => import('./RefreshOnMount'))\nconst RefreshOnFocus = dynamic(() => import('./RefreshOnFocus'))\nconst RefreshOnReconnect = dynamic(() => import('./RefreshOnReconnect'))\n\ninterface SanityClientConfig extends Pick<\n InitializedClientConfig,\n | 'projectId'\n | 'dataset'\n | 'apiHost'\n | 'apiVersion'\n | 'useProjectHostname'\n | 'token'\n | 'requestTagPrefix'\n> {}\n\nexport interface SanityLiveProps {\n config: SanityClientConfig\n /**\n * Setting this to 'published' opens one live event connection, setting it to any other value opens both the live event connections if needed\n */\n perspective: Exclude<ClientPerspective, 'raw'>\n\n onLiveEvent: (tags: string[]) => Promise<void | 'refresh'>\n onLiveEventIncludingDrafts: (tags: string[]) => Promise<void | 'refresh'>\n\n refreshOnMount?: boolean\n refreshOnFocus?: boolean\n refreshOnReconnect?: boolean\n requestTag: string\n\n /**\n * Handle errors from the Live Events subscription.\n * By default it's reported using `console.error`, you can override this prop to handle it in your own way.\n */\n onError?: (error: unknown) => void\n intervalOnGoAway?: number | false\n onGoAway?: (event: LiveEventGoAway, intervalOnGoAway: number | false) => void\n}\n\nfunction handleError(error: unknown) {\n if (isCorsOriginError(error)) {\n console.warn(\n `Sanity Live is unable to connect to the Sanity API as the current origin - ${window.origin} - is not in the list of allowed CORS origins for this Sanity Project.`,\n error.addOriginUrl && `Add it here:`,\n error.addOriginUrl?.toString(),\n )\n } else {\n console.error(error)\n }\n}\n\nfunction handleOnGoAway(event: LiveEventGoAway, intervalOnGoAway: number | false) {\n if (intervalOnGoAway) {\n console.warn(\n 'Sanity Live connection closed, switching to long polling set to a interval of',\n intervalOnGoAway / 1000,\n 'seconds and the server gave this reason:',\n event.reason,\n )\n } else {\n console.error(\n 'Sanity Live connection closed, automatic revalidation is disabled, the server gave this reason:',\n event.reason,\n )\n }\n}\n\nfunction SanityLive(props: SanityLiveProps): React.JSX.Element | null {\n const {\n config,\n onLiveEvent,\n // onLiveEventIncludingDrafts,\n perspective,\n\n refreshOnMount = false,\n refreshOnFocus = perspective !== 'published'\n ? false\n : typeof window === 'undefined'\n ? true\n : window.self === window.top,\n refreshOnReconnect = true,\n intervalOnGoAway = 30_000,\n requestTag,\n onError = handleError,\n onGoAway = handleOnGoAway,\n } = props\n const {projectId, dataset, apiHost, apiVersion, useProjectHostname, token, requestTagPrefix} =\n config\n\n const client = useMemo(\n () =>\n createClient({\n projectId,\n dataset,\n apiHost,\n apiVersion,\n useProjectHostname,\n ignoreBrowserTokenWarning: true,\n token,\n useCdn: false,\n requestTagPrefix,\n }),\n [apiHost, apiVersion, dataset, projectId, requestTagPrefix, token, useProjectHostname],\n )\n const [longPollingInterval, setLongPollingInterval] = useState<number | false>(false)\n\n /**\n * 1. Handle Live Events and call revalidateTag or router.refresh when needed\n */\n const router = useRouter()\n const handleLiveEvent = useEffectEvent((event: LiveEvent) => {\n if (process.env.NODE_ENV !== 'production' && event.type === 'welcome') {\n // oxlint-disable-next-line no-console\n console.info(\n 'Sanity is live with',\n token\n ? 'automatic revalidation for draft content changes as well as published content'\n : perspective === 'published'\n ? 'automatic revalidation for only published content. Provide a `browserToken` to `defineLive` to support draft content outside of Presentation Tool.'\n : 'automatic revalidation of published content',\n )\n // Disable long polling when welcome event is received, this is a no-op if long polling is already disabled\n setLongPollingInterval(false)\n } else if (event.type === 'message') {\n void onLiveEvent(\n event.tags.map((tag: SyncTag) => `${PUBLISHED_SYNC_TAG_PREFIX}${tag}` as const),\n ).then((result) => {\n if (result === 'refresh') router.refresh()\n })\n } else if (event.type === 'restart' || event.type === 'reconnect') {\n router.refresh()\n } else if (event.type === 'goaway') {\n onGoAway(event, intervalOnGoAway)\n setLongPollingInterval(intervalOnGoAway)\n }\n })\n useEffect(() => {\n const subscription = client.live.events({includeDrafts: !!token, tag: requestTag}).subscribe({\n next: handleLiveEvent,\n error: (err: unknown) => {\n // console.error('What?', err)\n onError(err)\n },\n })\n return () => subscription.unsubscribe()\n }, [client.live, onError, requestTag, token])\n\n const [loadComlink, setLoadComlink] = useState(false)\n\n /**\n * 4. If Presentation Tool is detected, load up the comlink and integrate with it\n */\n useEffect(() => {\n if (!isMaybePresentation()) return\n const controller = new AbortController()\n // Wait for a while to see if Presentation Tool is detected, before assuming the env to be stand-alone live preview\n // const timeout = setTimeout(() => setEnvironment('live'), 3_000)\n window.addEventListener(\n 'message',\n ({data}: MessageEvent<unknown>) => {\n if (\n data &&\n typeof data === 'object' &&\n 'domain' in data &&\n data.domain === 'sanity/channels' &&\n 'from' in data &&\n data.from === 'presentation'\n ) {\n // clearTimeout(timeout)\n // setEnvironment(isMaybePreviewWindow() ? 'presentation-window' : 'presentation-iframe')\n setLoadComlink(true)\n controller.abort()\n }\n },\n {signal: controller.signal},\n )\n return () => {\n // clearTimeout(timeout)\n controller.abort()\n }\n }, [])\n\n /**\n * 6. Handle switching to long polling when needed\n */\n useEffect(() => {\n if (!longPollingInterval) return\n const interval = setInterval(() => router.refresh(), longPollingInterval)\n return () => clearInterval(interval)\n }, [longPollingInterval, router])\n\n return (\n <>\n {loadComlink && <PresentationComlink projectId={projectId!} dataset={dataset!} />}\n {refreshOnMount && <RefreshOnMount />}\n {refreshOnFocus && <RefreshOnFocus />}\n {refreshOnReconnect && <RefreshOnReconnect />}\n </>\n )\n}\n\nSanityLive.displayName = 'SanityLiveClientComponent'\n\nexport default SanityLive\n"],"mappings":";;;;;;;;AAmBA,MAAM,sBAAsB,cAAc,OAAO,4BAAyB;AAC1E,MAAM,iBAAiB,cAAc,OA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E__ */ new Set();
2
- let perspective = "checking";
3
- function setPerspective(nextPerspective) {
4
- if (perspective.toString() === nextPerspective.toString()) return;
5
- perspective = nextPerspective;
6
- for (const onPerspectiveChange of perspectiveListeners) onPerspectiveChange();
7
- }
8
- const environmentListeners = /* @__PURE__ */ new Set();
9
- let environment = "checking";
10
- function setEnvironment(nextEnvironment) {
11
- environment = nextEnvironment;
12
- for (const onEnvironmentChange of environmentListeners) onEnvironmentChange();
13
- }
14
1
  const comlinkListeners = /* @__PURE__ */ new Set();
15
2
  let comlink = null;
16
3
  let comlinkProjectId = null;
17
4
  let comlinkDataset = null;
5
+ let comlinkPerspective = null;
18
6
  function setComlink(nextComlink) {
19
7
  comlink = nextComlink;
20
8
  for (const onComlinkChange of comlinkListeners) onComlinkChange();
@@ -24,6 +12,11 @@ function setComlinkClientConfig(nextComlinkProjectId, nextComlinkDataset) {
24
12
  comlinkDataset = nextComlinkDataset;
25
13
  for (const onComlinkChange of comlinkListeners) onComlinkChange();
26
14
  }
27
- export { environment as a, perspectiveListeners as c, setEnvironment as d, setPerspective as f, comlinkProjectId as i, setComlink as l, comlinkDataset as n, environmentListeners as o, comlinkListeners as r, perspective as s, comlink as t, setComlinkClientConfig as u };
15
+ function setComlinkPerspective(nextComlinkPerspective) {
16
+ if (comlinkPerspective?.toString() === nextComlinkPerspective?.toString()) return;
17
+ comlinkPerspective = nextComlinkPerspective;
18
+ for (const onComlinkChange of comlinkListeners) onComlinkChange();
19
+ }
20
+ export { comlinkProjectId as a, setComlinkPerspective as c, comlinkPerspective as i, comlinkDataset as n, setComlink as o, comlinkListeners as r, setComlinkClientConfig as s, comlink as t };
28
21
 
29
22
  //# sourceMappingURL=context.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../src/live/shared/context.ts"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport type {Node} from '@sanity/comlink'\nimport type {LoaderControllerMsg, LoaderNodeMsg} from '@sanity/presentation-comlink'\n\nexport type LivePerspective = 'checking' | 'unknown' | ClientPerspective\n\nexport const perspectiveListeners: Set<() => void> = new Set()\nexport let perspective: LivePerspective = 'checking'\nexport function setPerspective(nextPerspective: LivePerspective): void {\n if (perspective.toString() === nextPerspective.toString()) return\n perspective = nextPerspective\n for (const onPerspectiveChange of perspectiveListeners) {\n onPerspectiveChange()\n }\n}\n\nexport type LiveEnvironment =\n | 'checking'\n | 'presentation-iframe'\n | 'presentation-window'\n | 'live'\n | 'static'\n | 'unknown'\n\nexport const environmentListeners: Set<() => void> = new Set()\nexport let environment: LiveEnvironment = 'checking'\nexport function setEnvironment(nextEnvironment: LiveEnvironment): void {\n environment = nextEnvironment\n for (const onEnvironmentChange of environmentListeners) {\n onEnvironmentChange()\n }\n}\n\nexport const comlinkListeners: Set<() => void> = new Set()\nexport let comlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null = null\nexport let comlinkProjectId: string | null = null\nexport let comlinkDataset: string | null = null\nexport function setComlink(nextComlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null): void {\n comlink = nextComlink\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\nexport function setComlinkClientConfig(\n nextComlinkProjectId: string | null,\n nextComlinkDataset: string | null,\n): void {\n comlinkProjectId = nextComlinkProjectId\n comlinkDataset = nextComlinkDataset\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\n"],"mappings":"AAMA,MAAa,uCAAwC,IAAI,KAAK;AAC9D,IAAW,cAA+B;AAC1C,SAAgB,eAAe,iBAAwC;AACrE,KAAI,YAAY,UAAU,KAAK,gBAAgB,UAAU,CAAE;AAC3D,eAAc;AACd,MAAK,MAAM,uBAAuB,qBAChC,sBAAqB;;AAYzB,MAAa,uCAAwC,IAAI,KAAK;AAC9D,IAAW,cAA+B;AAC1C,SAAgB,eAAe,iBAAwC;AACrE,eAAc;AACd,MAAK,MAAM,uBAAuB,qBAChC,sBAAqB;;AAIzB,MAAa,mCAAoC,IAAI,KAAK;AAC1D,IAAW,UAA2D;AACtE,IAAW,mBAAkC;AAC7C,IAAW,iBAAgC;AAC3C,SAAgB,WAAW,aAAoE;AAC7F,WAAU;AACV,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB;;AAGrB,SAAgB,uBACd,sBACA,oBACM;AACN,oBAAmB;AACnB,kBAAiB;AACjB,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../src/live/shared/context.ts"],"sourcesContent":["import type {ClientPerspective} from '@sanity/client'\nimport type {Node} from '@sanity/comlink'\nimport type {LoaderControllerMsg, LoaderNodeMsg} from '@sanity/presentation-comlink'\n\nexport const comlinkListeners: Set<() => void> = new Set()\nexport let comlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null = null\nexport let comlinkProjectId: string | null = null\nexport let comlinkDataset: string | null = null\nexport let comlinkPerspective: ClientPerspective | null = null\nexport function setComlink(nextComlink: Node<LoaderNodeMsg, LoaderControllerMsg> | null): void {\n comlink = nextComlink\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\nexport function setComlinkClientConfig(\n nextComlinkProjectId: string | null,\n nextComlinkDataset: string | null,\n): void {\n comlinkProjectId = nextComlinkProjectId\n comlinkDataset = nextComlinkDataset\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\nexport function setComlinkPerspective(nextComlinkPerspective: ClientPerspective | null): void {\n if (comlinkPerspective?.toString() === nextComlinkPerspective?.toString()) return\n comlinkPerspective = nextComlinkPerspective\n for (const onComlinkChange of comlinkListeners) {\n onComlinkChange()\n }\n}\n"],"mappings":"AAIA,MAAa,mCAAoC,IAAI,KAAK;AAC1D,IAAW,UAA2D;AACtE,IAAW,mBAAkC;AAC7C,IAAW,iBAAgC;AAC3C,IAAW,qBAA+C;AAC1D,SAAgB,WAAW,aAAoE;AAC7F,WAAU;AACV,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB;;AAGrB,SAAgB,uBACd,sBACA,oBACM;AACN,oBAAmB;AACnB,kBAAiB;AACjB,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB;;AAGrB,SAAgB,sBAAsB,wBAAwD;AAC5F,KAAI,oBAAoB,UAAU,KAAK,wBAAwB,UAAU,CAAE;AAC3E,sBAAqB;AACrB,MAAK,MAAM,mBAAmB,iBAC5B,kBAAiB"}
@@ -1,38 +1,5 @@
1
1
  import { useOptimistic } from "@sanity/visual-editing/react";
2
2
  import { ClientPerspective, ClientReturn, ContentSourceMap, QueryParams } from "@sanity/client";
3
- import "@sanity/comlink";
4
- import "@sanity/presentation-comlink";
5
- type LivePerspective = "checking" | "unknown" | ClientPerspective;
6
- type LiveEnvironment = "checking" | "presentation-iframe" | "presentation-window" | "live" | "static" | "unknown";
7
- /**
8
- * Reports the current draft mode environment.
9
- * Use it to determine how to adapt the UI based on wether:
10
- * - Your app is previewed in a iframe, inside Presentation Tool in a Sanity Studio.
11
- * - Your app is previewed in a new window, spawned from Presentation Tool in a Sanity Studio.
12
- * - Your app is live previewing drafts in a standalone context.
13
- * - Your app is previewing drafts, but not live.
14
- * - Your app is not previewing anything (that could be detected).
15
- * @public
16
- */
17
- declare function useDraftModeEnvironment(): LiveEnvironment;
18
- /**
19
- * Reports the Sanity Client perspective used to fetch data in `sanityFetch` used on the page.
20
- * If the hook is used outside Draft Mode it will resolve to `'unknown'`.
21
- * If the hook is used but the `<SanityLive />` component is not present then it'll stay in `'checking'` and console warn after a timeout that it seems like you're missing the component.
22
- * @public
23
- */
24
- declare function useDraftModePerspective(): LivePerspective;
25
- /**
26
- * Detects if the application is being previewed inside Sanity Presentation Tool.
27
- * Presentation Tool can open the application in an iframe, or in a new window.
28
- * When in this context there are some UI you usually don't want to show,
29
- * for example a Draft Mode toggle, or a "Viewing draft content" indicators, these are unnecessary and add clutter to
30
- * the editorial experience.
31
- * The hook returns `null` initially, when it's not yet sure if the application is running inside Presentation Tool,
32
- * then `true` if it is, and `false` otherwise.
33
- * @public
34
- */
35
- declare function useIsPresentationTool(): boolean | null;
36
3
  /**
37
4
  * Detects if the application is considered to be in a "Live Preview" mode.
38
5
  * Live Preview means that the application is either:
@@ -49,6 +16,7 @@ declare function useIsPresentationTool(): boolean | null;
49
16
  * @public
50
17
  */
51
18
  declare function useIsLivePreview(): boolean | null;
19
+ declare function useLiveEnvironment(): null;
52
20
  /** @alpha */
53
21
  type UsePresentationQueryReturnsInactive = {
54
22
  data: null;
@@ -75,5 +43,18 @@ declare function usePresentationQuery<const QueryString extends string>(props: {
75
43
  params?: QueryParams | Promise<QueryParams>;
76
44
  stega?: boolean;
77
45
  }): UsePresentationQueryReturns<QueryString>;
78
- export { UsePresentationQueryReturns, UsePresentationQueryReturnsActive, UsePresentationQueryReturnsInactive, useDraftModeEnvironment, useDraftModePerspective, useIsLivePreview, useIsPresentationTool, useOptimistic, usePresentationQuery };
46
+ /**
47
+ * Detects if the application is being previewed inside Sanity Presentation Tool.
48
+ * Presentation Tool can open the application in an iframe, or in a new window.
49
+ * When in this context there are some UI you usually don't want to show,
50
+ * for example a Draft Mode toggle, or a "Viewing draft content" indicators, these are unnecessary and add clutter to
51
+ * the editorial experience.
52
+ * The hook returns `null` initially, when it's not yet sure if the application is running inside Presentation Tool,
53
+ * then `true` if it is, and `false` otherwise.
54
+ * @public
55
+ */
56
+ declare function useIsPresentationTool(): boolean | null;
57
+ type VisualEditingEnvironment = null | "unknown" | "presentation-iframe" | "presentation-window" | "standalone";
58
+ declare function useVisualEditingEnvironment(): VisualEditingEnvironment;
59
+ export { UsePresentationQueryReturns, UsePresentationQueryReturnsActive, UsePresentationQueryReturnsInactive, useIsLivePreview, useIsPresentationTool, useLiveEnvironment, useOptimistic, usePresentationQuery, useVisualEditingEnvironment };
79
60
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/live/shared/context.ts","../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":[],"mappings":";;;;KAIY,eAAA,4BAA2C;KAY3C,eAAA;;;;;AAZZ;AAYA;;ACIA;AAmBA;;AC3BgB,iBDQA,uBAAA,CAAA,CCRA,EDQ2B,eCR3B;;ACKhB;;ACDA;AAOA;;AACQ,iBHeQ,uBAAA,CAAA,CGfR,EHemC,eGfnC;;;;;;AJpBR;AAYA;;ACIA;AAmBA;iBC3BgB,qBAAA,CAAA;;;;;;AFRhB;AAYA;;ACIA;AAmBA;;AC3BA;;ACKA;;ACDY,iBDCI,gBAAA,CAAA,CCDJ,EAAA,OAAA,GAAA,IAAA;;KAAA,mCAAA;;;EJZZ,WAAY,EAAA,IAAA;AAYZ,CAAA;;ACIgB,KGGJ,iCHH+B,CAAA,oBAAA,MAAA,CAAA,GAAA;EAmB3C,IAAgB,EGfR,YHeQ,CGfK,WHeL,CAAA;aGdH;EFbb,WAAgB,EEcD,iBFdC;;ACKA,KCYJ,2BDZI,CAAA,oBAAA,MAAA,CAAA,GCaZ,mCDbY,GCcZ,iCDdY,CCcsB,WDdtB,CAAA;;ACDhB;AAOA;;;;;;AAMY,iBAyDI,oBAzDJ,CAAA,0BAAA,MAAA,CAAA,CAAA,KAAA,EAAA;EACR,KAAA,EAyDK,WAzDL;EACkC,MAAA,CAAA,EAyD3B,WAzD2B,GAyDb,OAzDa,CAyDL,WAzDK,CAAA;EAAlC,KAAA,CAAA,EAAA,OAAA;CAAA,CAAA,EA2DA,2BA3DA,CA2D4B,WA3D5B,CAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/hooks/useIsLivePreview.ts","../../src/live/hooks/useLiveEnvironment.ts","../../src/live/hooks/usePresentationQuery.ts","../../src/visual-editing/hooks/useIsPresentationTool.ts","../../src/visual-editing/hooks/useVisualEditingEnvironment.ts"],"sourcesContent":[],"mappings":";;;;;AAeA;;ACfA;;ACeA;AAOA;;;;;;AAMA;AACI,iBFdY,gBAAA,CAAA,CEcZ,EAAA,OAAA,GAAA,IAAA;iBD7BY,kBAAA,CAAA;;KCeJ,mCAAA;EFAZ,IAAgB,EAAA,IAAA;;ECfhB,WAAgB,EAAA,IAAA;;ACehB;AAOY,KAAA,iCAAA,CAAA,oBAAA,MAAA,CAAA,GAAA;EACS,IAAA,EAAb,YAAa,CAAA,WAAA,CAAA;EAAb,SAAA,EACK,gBADL,GAAA,IAAA;EACK,WAAA,EACE,iBADF;CACE;AAAA,KAGH,2BAHG,CAAA,oBAAA,MAAA,CAAA,GAIX,mCAJW,GAKX,iCALW,CAKuB,WALvB,CAAA;AAGf;;;;;AAyDA;;;AAEiC,iBAFjB,oBAEiB,CAAA,0BAAA,MAAA,CAAA,CAAA,KAAA,EAAA;EAAR,KAAA,EADhB,WACgB;EAEO,MAAA,CAAA,EAFrB,WAEqB,GAFP,OAEO,CAFC,WAED,CAAA;EAA5B,KAAA,CAAA,EAAA,OAAA;CAAA,CAAA,EAAA,2BAAA,CAA4B,WAA5B,CAAA;;;;AF1EJ;;ACfA;;ACeA;AAOA;;AACQ,iBCbQ,qBAAA,CAAA,CDaR,EAAA,OAAA,GAAA,IAAA;KEvBH,wBAAA;iBAOW,2BAAA,CAAA,GAA+B"}
@@ -1,28 +1,16 @@
1
1
  "use client";
2
- import { a as environment, c as perspectiveListeners, i as comlinkProjectId, n as comlinkDataset, o as environmentListeners, r as comlinkListeners, s as perspective, t as comlink } from "../context.js";
3
- import { useCallback, useEffect, useEffectEvent, useMemo, useReducer, useSyncExternalStore } from "react";
2
+ import { a as comlinkProjectId, i as comlinkPerspective, n as comlinkDataset, r as comlinkListeners, t as comlink } from "../context.js";
4
3
  import { stegaEncodeSourceMap } from "@sanity/client/stega";
5
4
  import { dequal } from "dequal/lite";
5
+ import { useEffect, useEffectEvent, useMemo, useReducer, useSyncExternalStore } from "react";
6
6
  import { useOptimistic } from "@sanity/visual-editing/react";
7
- function useDraftModeEnvironment() {
8
- return useSyncExternalStore(useCallback((listener) => {
9
- environmentListeners.add(listener);
10
- return () => environmentListeners.delete(listener);
11
- }, []), () => environment, () => "checking");
12
- }
13
- function useDraftModePerspective() {
14
- return useSyncExternalStore(useCallback((listener) => {
15
- perspectiveListeners.add(listener);
16
- return () => perspectiveListeners.delete(listener);
17
- }, []), () => perspective, () => "checking");
18
- }
19
- function useIsPresentationTool() {
20
- const environment$1 = useDraftModeEnvironment();
21
- return environment$1 === "checking" ? null : environment$1 === "presentation-iframe" || environment$1 === "presentation-window";
22
- }
23
7
  function useIsLivePreview() {
24
- const environment$1 = useDraftModeEnvironment();
25
- return environment$1 === "checking" ? null : environment$1 === "presentation-iframe" || environment$1 === "presentation-window" || environment$1 === "live";
8
+ console.log("TODO: Implement useIsLivePreview");
9
+ return null;
10
+ }
11
+ function useLiveEnvironment() {
12
+ console.log("TODO: Implement useLiveEnvironment");
13
+ return null;
26
14
  }
27
15
  function reducer(state, { type, payload }) {
28
16
  switch (type) {
@@ -52,21 +40,21 @@ function usePresentationQuery(props) {
52
40
  const comlink$1 = useSyncExternalStore(subscribe, () => comlink, () => null);
53
41
  const projectId = useSyncExternalStore(subscribe, () => comlinkProjectId, () => null);
54
42
  const dataset = useSyncExternalStore(subscribe, () => comlinkDataset, () => null);
55
- const perspective$1 = useDraftModePerspective();
43
+ const perspective = useSyncExternalStore(subscribe, () => comlinkPerspective, () => null);
56
44
  const handleQueryHeartbeat = useEffectEvent((comlink$2) => {
57
- if (!projectId || !dataset || !perspective$1) {
45
+ if (!projectId || !dataset || !perspective) {
58
46
  console.warn("usePresentationQuery: projectId, dataset and perspective must be set", {
59
47
  projectId,
60
48
  dataset,
61
- perspective: perspective$1
49
+ perspective
62
50
  });
63
51
  return;
64
52
  }
65
- if (perspective$1 === "checking" || perspective$1 === "unknown") return;
53
+ if (perspective === null) return;
66
54
  comlink$2.post("loader/query-listen", {
67
55
  projectId,
68
56
  dataset,
69
- perspective: perspective$1,
57
+ perspective,
70
58
  query,
71
59
  params,
72
60
  heartbeat: LISTEN_HEARTBEAT_INTERVAL
@@ -112,6 +100,14 @@ function usePresentationQuery(props) {
112
100
  return state;
113
101
  }, [state, stega]);
114
102
  }
115
- export { useDraftModeEnvironment, useDraftModePerspective, useIsLivePreview, useIsPresentationTool, useOptimistic, usePresentationQuery };
103
+ function useIsPresentationTool() {
104
+ console.log("TODO: Implement useIsPresentationTool");
105
+ return null;
106
+ }
107
+ function useVisualEditingEnvironment() {
108
+ console.log("TODO: Implement useVisualEditingEnvironment");
109
+ return null;
110
+ }
111
+ export { useIsLivePreview, useIsPresentationTool, useLiveEnvironment, useOptimistic, usePresentationQuery, useVisualEditingEnvironment };
116
112
 
117
113
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["environment","environment","comlink","comlinkSnapshot","perspective"],"sources":["../../src/live/hooks/useDraftMode.ts","../../src/live/hooks/useIsPresentationTool.ts","../../src/live/hooks/useIsLivePreview.ts","../../src/live/hooks/usePresentationQuery.ts"],"sourcesContent":["import {\n environment,\n environmentListeners,\n perspective,\n perspectiveListeners,\n type LiveEnvironment,\n type LivePerspective,\n} from '#live/context'\nimport {useCallback, useSyncExternalStore} from 'react'\n\n/**\n * Reports the current draft mode environment.\n * Use it to determine how to adapt the UI based on wether:\n * - Your app is previewed in a iframe, inside Presentation Tool in a Sanity Studio.\n * - Your app is previewed in a new window, spawned from Presentation Tool in a Sanity Studio.\n * - Your app is live previewing drafts in a standalone context.\n * - Your app is previewing drafts, but not live.\n * - Your app is not previewing anything (that could be detected).\n * @public\n */\nexport function useDraftModeEnvironment(): LiveEnvironment {\n const subscribe = useCallback((listener: () => void) => {\n environmentListeners.add(listener)\n return () => environmentListeners.delete(listener)\n }, [])\n\n return useSyncExternalStore(\n subscribe,\n () => environment,\n () => 'checking',\n )\n}\n\n/**\n * Reports the Sanity Client perspective used to fetch data in `sanityFetch` used on the page.\n * If the hook is used outside Draft Mode it will resolve to `'unknown'`.\n * If the hook is used but the `<SanityLive />` component is not present then it'll stay in `'checking'` and console warn after a timeout that it seems like you're missing the component.\n * @public\n */\nexport function useDraftModePerspective(): LivePerspective {\n const subscribe = useCallback((listener: () => void) => {\n perspectiveListeners.add(listener)\n return () => perspectiveListeners.delete(listener)\n }, [])\n\n return useSyncExternalStore(\n subscribe,\n () => perspective,\n () => 'checking',\n )\n}\n","import {useDraftModeEnvironment} from './useDraftMode'\n\n/**\n * Detects if the application is being previewed inside Sanity Presentation Tool.\n * Presentation Tool can open the application in an iframe, or in a new window.\n * When in this context there are some UI you usually don't want to show,\n * for example a Draft Mode toggle, or a \"Viewing draft content\" indicators, these are unnecessary and add clutter to\n * the editorial experience.\n * The hook returns `null` initially, when it's not yet sure if the application is running inside Presentation Tool,\n * then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsPresentationTool(): boolean | null {\n const environment = useDraftModeEnvironment()\n return environment === 'checking'\n ? null\n : environment === 'presentation-iframe' || environment === 'presentation-window'\n}\n","import {useDraftModeEnvironment} from './useDraftMode'\n\n/**\n * Detects if the application is considered to be in a \"Live Preview\" mode.\n * Live Preview means that the application is either:\n * - being previewed inside Sanity Presentation Tool\n * - being previewed in Draft Mode, with a `browserToken` given to `defineLive`, also known as \"Standalone Live Preview'\"\n * When in Live Preview mode, you typically want UI to update as new content comes in, without any manual intervention.\n * This is very different from Live Production mode, where you usually want to delay updates that might cause layout shifts,\n * to avoid interrupting the user that is consuming your content.\n * This hook lets you adapt to this difference, making sure production doesn't cause layout shifts that worsen the UX,\n * while in Live Preview mode layout shift is less of an issue and it's better for the editorial experience to auto refresh in real time.\n *\n * The hook returns `null` initially, to signal it doesn't yet know if it's live previewing or not.\n * Then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsLivePreview(): boolean | null {\n const environment = useDraftModeEnvironment()\n return environment === 'checking'\n ? null\n : environment === 'presentation-iframe' ||\n environment === 'presentation-window' ||\n environment === 'live'\n}\n","import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} from '@sanity/client'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\n\nimport {\n comlinkDataset,\n comlinkListeners,\n comlinkProjectId,\n comlink as comlinkSnapshot,\n} from '#live/context'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport {dequal} from 'dequal/lite'\nimport {useEffect, useMemo, useReducer, useSyncExternalStore, useEffectEvent} from 'react'\n\nimport {useDraftModePerspective} from './useDraftMode'\n\n/** @alpha */\nexport type UsePresentationQueryReturnsInactive = {\n data: null\n sourceMap: null\n perspective: null\n}\n\n/** @alpha */\nexport type UsePresentationQueryReturnsActive<QueryString extends string> = {\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n perspective: ClientPerspective\n}\n\nexport type UsePresentationQueryReturns<QueryString extends string> =\n | UsePresentationQueryReturnsInactive\n | UsePresentationQueryReturnsActive<QueryString>\n\ntype Action<QueryString extends string> = {\n type: 'query-change'\n payload: UsePresentationQueryReturnsActive<QueryString>\n}\n\nfunction reducer<QueryString extends string>(\n state: UsePresentationQueryReturns<QueryString>,\n {type, payload}: Action<QueryString>,\n): UsePresentationQueryReturns<QueryString> {\n switch (type) {\n case 'query-change':\n return dequal(state, payload)\n ? state\n : {\n ...state,\n data: dequal(state.data, payload.data)\n ? // oxlint-disable-next-line no-unsafe-type-assertion\n (state.data as ClientReturn<QueryString>)\n : payload.data,\n sourceMap: dequal(state.sourceMap, payload.sourceMap)\n ? state.sourceMap\n : payload.sourceMap,\n perspective: dequal(state.perspective, payload.perspective)\n ? // oxlint-disable-next-line no-unsafe-type-assertion\n (state.perspective as Exclude<ClientPerspective, 'raw'>)\n : payload.perspective,\n }\n default:\n return state\n }\n}\nconst initialState: UsePresentationQueryReturnsInactive = {\n data: null,\n sourceMap: null,\n perspective: null,\n}\n\nfunction subscribe(listener: () => void) {\n comlinkListeners.add(listener)\n return () => comlinkListeners.delete(listener)\n}\n\nconst EMPTY_QUERY_PARAMS: QueryParams = {}\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * Experimental hook that can run queries in Presentation Tool.\n * Query results are sent back over postMessage whenever the query results change.\n * It also works with optimistic updates in the studio itself, offering low latency updates.\n * It's not as low latency as the `useOptimistic` hook, but it's a good compromise for some use cases.\n * Especially until `useOptimistic` propagates edits in the Studio parent window back into the iframe.\n * @alpha\n */\nexport function usePresentationQuery<const QueryString extends string>(props: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n}): UsePresentationQueryReturns<QueryString> {\n const [state, dispatch] = useReducer(reducer, initialState)\n const {query, params = EMPTY_QUERY_PARAMS, stega = true} = props\n\n /**\n * Comlink forwards queries we want to run to the parent window where Presentation Tool handles it for us\n */\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n /**\n * The comlink events requires projectId and dataset, Presentation Tool uses it to protect against project and dataset mismatch errors.\n * We don't want to force the consumers of the `usePresentationQuery` hook to provide these,\n * so we set them in the component that establishes the comlink connection and propagates it to all the subscribes.\n */\n const projectId = useSyncExternalStore(\n subscribe,\n () => comlinkProjectId,\n () => null,\n )\n const dataset = useSyncExternalStore(\n subscribe,\n () => comlinkDataset,\n () => null,\n )\n /**\n * The perspective is kept in sync with Presentation Tool's perspective, and even knows what perspective the page loaded with initially and can forward it to the Sanity Studio.\n */\n const perspective = useDraftModePerspective()\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n // Handle odd case where the comlink can take events but some data is missing\n if (!projectId || !dataset || !perspective) {\n console.warn('usePresentationQuery: projectId, dataset and perspective must be set', {\n projectId,\n dataset,\n perspective,\n })\n return\n }\n // Another odd case where the initial perspective states haven't resolved to the actual perspective state\n if (perspective === 'checking' || perspective === 'unknown') {\n return\n }\n comlink.post('loader/query-listen', {\n projectId,\n dataset,\n perspective,\n query,\n params,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {\n projectId,\n dataset,\n query,\n params,\n },\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n dispatch({\n type: 'query-change',\n payload: {\n data: event.result,\n sourceMap: event.resultSourceMap || null,\n perspective: event.perspective,\n },\n })\n }\n },\n )\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n return useMemo(() => {\n if (stega && state.sourceMap) {\n return {\n ...state,\n data: stegaEncodeSourceMap(state.data, state.sourceMap, {enabled: true, studioUrl: '/'}),\n }\n }\n return state\n }, [state, stega])\n}\n"],"mappings":";;;;;;AAoBA,SAAgB,0BAA2C;AAMzD,QAAO,qBALW,aAAa,aAAyB;AACtD,uBAAqB,IAAI,SAAS;AAClC,eAAa,qBAAqB,OAAO,SAAS;IACjD,EAAE,CAAC,QAIE,mBACA,WACP;;AASH,SAAgB,0BAA2C;AAMzD,QAAO,qBALW,aAAa,aAAyB;AACtD,uBAAqB,IAAI,SAAS;AAClC,eAAa,qBAAqB,OAAO,SAAS;IACjD,EAAE,CAAC,QAIE,mBACA,WACP;;ACrCH,SAAgB,wBAAwC;CACtD,MAAMA,gBAAc,yBAAyB;AAC7C,QAAOA,kBAAgB,aACnB,OACAA,kBAAgB,yBAAyBA,kBAAgB;;ACC/D,SAAgB,mBAAmC;CACjD,MAAMC,gBAAc,yBAAyB;AAC7C,QAAOA,kBAAgB,aACnB,OACAA,kBAAgB,yBACdA,kBAAgB,yBAChBA,kBAAgB;;ACexB,SAAS,QACP,OACA,EAAC,MAAM,WACmC;AAC1C,SAAQ,MAAR;EACE,KAAK,eACH,QAAO,OAAO,OAAO,QAAQ,GACzB,QACA;GACE,GAAG;GACH,MAAM,OAAO,MAAM,MAAM,QAAQ,KAA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AAgB;AACd,MAAI,CAACF,UAAS;EAEd,MAAM,cAAcA,UAAQ,GAAG,uBAAuB,kBAAkB;EACxE,MAAM,WAAW,kBAAkB,qBAAqBA,UAAQ,EAAE,0BAA0B;AAC5F,eAAa;AACX,iBAAc,SAAS;AACvB,gBAAa;;IAEd,CAACA,UAAQ,CAAC;AAEb,QAAO,cAAc;AACnB,MAAI,SAAS,MAAM,UACjB,QAAO;GACL,GAAG;GACH,MAAM,qBAAqB,MAAM,MAAM,MAAM,WAAW;IAAC,SAAS;IAAM,WAAW;IAAI,CAAC;GACzF;AAEH,SAAO;IACN,CAAC,OAAO,MAAM,CAAC"}
1
+ {"version":3,"file":"index.js","names":["comlink","comlinkSnapshot"],"sources":["../../src/hooks/useIsLivePreview.ts","../../src/live/hooks/useLiveEnvironment.ts","../../src/live/hooks/usePresentationQuery.ts","../../src/visual-editing/hooks/useIsPresentationTool.ts","../../src/visual-editing/hooks/useVisualEditingEnvironment.ts"],"sourcesContent":["/**\n * Detects if the application is considered to be in a \"Live Preview\" mode.\n * Live Preview means that the application is either:\n * - being previewed inside Sanity Presentation Tool\n * - being previewed in Draft Mode, with a `browserToken` given to `defineLive`, also known as \"Standalone Live Preview'\"\n * When in Live Preview mode, you typically want UI to update as new content comes in, without any manual intervention.\n * This is very different from Live Production mode, where you usually want to delay updates that might cause layout shifts,\n * to avoid interrupting the user that is consuming your content.\n * This hook lets you adapt to this difference, making sure production doesn't cause layout shifts that worsen the UX,\n * while in Live Preview mode layout shift is less of an issue and it's better for the editorial experience to auto refresh in real time.\n *\n * The hook returns `null` initially, to signal it doesn't yet know if it's live previewing or not.\n * Then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsLivePreview(): boolean | null {\n // oxlint-disable-next-line no-console\n console.log('TODO: Implement useIsLivePreview')\n\n return null\n}\n","export function useLiveEnvironment(): null {\n // oxlint-disable-next-line no-console\n console.log('TODO: Implement useLiveEnvironment')\n\n return null\n}\n","import type {ClientPerspective, ClientReturn, ContentSourceMap, QueryParams} from '@sanity/client'\nimport type {LoaderControllerMsg} from '@sanity/presentation-comlink'\n\nimport {\n comlinkDataset,\n comlinkListeners,\n comlinkProjectId,\n comlinkPerspective,\n comlink as comlinkSnapshot,\n} from '#live/context'\nimport {stegaEncodeSourceMap} from '@sanity/client/stega'\nimport {dequal} from 'dequal/lite'\nimport {useEffect, useMemo, useReducer, useSyncExternalStore, useEffectEvent} from 'react'\n\n/** @alpha */\nexport type UsePresentationQueryReturnsInactive = {\n data: null\n sourceMap: null\n perspective: null\n}\n\n/** @alpha */\nexport type UsePresentationQueryReturnsActive<QueryString extends string> = {\n data: ClientReturn<QueryString>\n sourceMap: ContentSourceMap | null\n perspective: ClientPerspective\n}\n\nexport type UsePresentationQueryReturns<QueryString extends string> =\n | UsePresentationQueryReturnsInactive\n | UsePresentationQueryReturnsActive<QueryString>\n\ntype Action<QueryString extends string> = {\n type: 'query-change'\n payload: UsePresentationQueryReturnsActive<QueryString>\n}\n\nfunction reducer<QueryString extends string>(\n state: UsePresentationQueryReturns<QueryString>,\n {type, payload}: Action<QueryString>,\n): UsePresentationQueryReturns<QueryString> {\n switch (type) {\n case 'query-change':\n return dequal(state, payload)\n ? state\n : {\n ...state,\n data: dequal(state.data, payload.data)\n ? // oxlint-disable-next-line no-unsafe-type-assertion\n (state.data as ClientReturn<QueryString>)\n : payload.data,\n sourceMap: dequal(state.sourceMap, payload.sourceMap)\n ? state.sourceMap\n : payload.sourceMap,\n perspective: dequal(state.perspective, payload.perspective)\n ? // oxlint-disable-next-line no-unsafe-type-assertion\n (state.perspective as Exclude<ClientPerspective, 'raw'>)\n : payload.perspective,\n }\n default:\n return state\n }\n}\nconst initialState: UsePresentationQueryReturnsInactive = {\n data: null,\n sourceMap: null,\n perspective: null,\n}\n\nfunction subscribe(listener: () => void) {\n comlinkListeners.add(listener)\n return () => comlinkListeners.delete(listener)\n}\n\nconst EMPTY_QUERY_PARAMS: QueryParams = {}\nconst LISTEN_HEARTBEAT_INTERVAL = 10_000\n\n/**\n * Experimental hook that can run queries in Presentation Tool.\n * Query results are sent back over postMessage whenever the query results change.\n * It also works with optimistic updates in the studio itself, offering low latency updates.\n * It's not as low latency as the `useOptimistic` hook, but it's a good compromise for some use cases.\n * Especially until `useOptimistic` propagates edits in the Studio parent window back into the iframe.\n * @alpha\n */\nexport function usePresentationQuery<const QueryString extends string>(props: {\n query: QueryString\n params?: QueryParams | Promise<QueryParams>\n stega?: boolean\n}): UsePresentationQueryReturns<QueryString> {\n const [state, dispatch] = useReducer(reducer, initialState)\n const {query, params = EMPTY_QUERY_PARAMS, stega = true} = props\n\n /**\n * Comlink forwards queries we want to run to the parent window where Presentation Tool handles it for us\n */\n const comlink = useSyncExternalStore(\n subscribe,\n () => comlinkSnapshot,\n () => null,\n )\n /**\n * The comlink events requires projectId and dataset, Presentation Tool uses it to protect against project and dataset mismatch errors.\n * We don't want to force the consumers of the `usePresentationQuery` hook to provide these,\n * so we set them in the component that establishes the comlink connection and propagates it to all the subscribes.\n */\n const projectId = useSyncExternalStore(\n subscribe,\n () => comlinkProjectId,\n () => null,\n )\n const dataset = useSyncExternalStore(\n subscribe,\n () => comlinkDataset,\n () => null,\n )\n /**\n * The perspective is kept in sync with Presentation Tool's perspective, and even knows what perspective the page loaded with initially and can forward it to the Sanity Studio.\n */\n const perspective = useSyncExternalStore(\n subscribe,\n () => comlinkPerspective,\n () => null,\n )\n\n const handleQueryHeartbeat = useEffectEvent((comlink: NonNullable<typeof comlinkSnapshot>) => {\n // Handle odd case where the comlink can take events but some data is missing\n if (!projectId || !dataset || !perspective) {\n console.warn('usePresentationQuery: projectId, dataset and perspective must be set', {\n projectId,\n dataset,\n perspective,\n })\n return\n }\n // Another odd case where the initial perspective states haven't resolved to the actual perspective state\n if (perspective === null) {\n return\n }\n comlink.post('loader/query-listen', {\n projectId,\n dataset,\n perspective,\n query,\n params,\n heartbeat: LISTEN_HEARTBEAT_INTERVAL,\n })\n })\n const handleQueryChange = useEffectEvent(\n (event: Extract<LoaderControllerMsg, {type: 'loader/query-change'}>['data']) => {\n if (\n dequal(\n {\n projectId,\n dataset,\n query,\n params,\n },\n {\n projectId: event.projectId,\n dataset: event.dataset,\n query: event.query,\n params: event.params,\n },\n )\n ) {\n dispatch({\n type: 'query-change',\n payload: {\n data: event.result,\n sourceMap: event.resultSourceMap || null,\n perspective: event.perspective,\n },\n })\n }\n },\n )\n useEffect(() => {\n if (!comlink) return\n\n const unsubscribe = comlink.on('loader/query-change', handleQueryChange)\n const interval = setInterval(() => handleQueryHeartbeat(comlink), LISTEN_HEARTBEAT_INTERVAL)\n return () => {\n clearInterval(interval)\n unsubscribe()\n }\n }, [comlink])\n\n return useMemo(() => {\n if (stega && state.sourceMap) {\n return {\n ...state,\n data: stegaEncodeSourceMap(state.data, state.sourceMap, {enabled: true, studioUrl: '/'}),\n }\n }\n return state\n }, [state, stega])\n}\n","/**\n * Detects if the application is being previewed inside Sanity Presentation Tool.\n * Presentation Tool can open the application in an iframe, or in a new window.\n * When in this context there are some UI you usually don't want to show,\n * for example a Draft Mode toggle, or a \"Viewing draft content\" indicators, these are unnecessary and add clutter to\n * the editorial experience.\n * The hook returns `null` initially, when it's not yet sure if the application is running inside Presentation Tool,\n * then `true` if it is, and `false` otherwise.\n * @public\n */\nexport function useIsPresentationTool(): boolean | null {\n // oxlint-disable-next-line no-console\n console.log('TODO: Implement useIsPresentationTool')\n\n return null\n}\n","type VisualEditingEnvironment =\n | null\n | 'unknown'\n | 'presentation-iframe'\n | 'presentation-window'\n | 'standalone'\n\nexport function useVisualEditingEnvironment(): VisualEditingEnvironment {\n // oxlint-disable-next-line no-console\n console.log('TODO: Implement useVisualEditingEnvironment')\n\n return null\n}\n"],"mappings":";;;;;;AAeA,SAAgB,mBAAmC;AAEjD,SAAQ,IAAI,mCAAmC;AAE/C,QAAO;;ACnBT,SAAgB,qBAA2B;AAEzC,SAAQ,IAAI,qCAAqC;AAEjD,QAAO;;ACiCT,SAAS,QACP,OACA,EAAC,MAAM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ACP,MAAM;GACN,SAAS;IACP,MAAM,MAAM;IACZ,WAAW,MAAM,mBAAmB;IACpC,aAAa,MAAM;IACpB;GACF,CAAC;GAGP;AACD,iBAAgB;AACd,MAAI,CAACD,UAAS;EAEd,MAAM,cAAcA,UAAQ,GAAG,uBAAuB,kBAAkB;EACxE,MAAM,WAAW,kBAAkB,qBAAqBA,UAAQ,EAAE,0BAA0B;AAC5F,eAAa;AACX,iBAAc,SAAS;AACvB,gBAAa;;IAEd,CAACA,UAAQ,CAAC;AAEb,QAAO,cAAc;AACnB,MAAI,SAAS,MAAM,UACjB,QAAO;GACL,GAAG;GACH,MAAM,qBAAqB,MAAM,MAAM,MAAM,WAAW;IAAC,SAAS;IAAM,WAAW;IAAI,CAAC;GACzF;AAEH,SAAO;IACN,CAAC,OAAO,MAAM,CAAC;;AC1LpB,SAAgB,wBAAwC;AAEtD,SAAQ,IAAI,wCAAwC;AAEpD,QAAO;;ACPT,SAAgB,8BAAwD;AAEtE,SAAQ,IAAI,8CAA8C;AAE1D,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/client-components/SanityLive.tsx","../../../src/live/client-components/index.ts"],"sourcesContent":[],"mappings":";UAqBU,kBAAA,SAA2B,KACnC;AADQ,UAWO,eAAA,CAXP;EAWV,MAAiB,EACP,kBADO;EACP;;;EAMyB,WAAA,EAFpB,OAEoB,CAFZ,iBAEY,EAAA,KAAA,CAAA;EACe,WAAA,EAAA,CAAA,IAAA,EAAA,MAAA,EAAA,EAAA,GADf,OACe,CAAA,IAAA,GAAA,SAAA,CAAA;EAa7B,0BAAA,EAAA,CAAA,IAAA,EAAA,MAAA,EAAA,EAAA,GAb6B,OAa7B,CAAA,IAAA,GAAA,SAAA,CAAA;EAAA,cAAA,CAAA,EAAA,OAAA;;EC7CrB,kBAA6C,CAAA,EAAA,OAAA;;;;;;;;qBD6CxB;;;AA3Cd;AAsBP;AACU,cCzBG,UDyBH,ECzBe,KAAA,CAAM,aDyBrB,CCzBmC,eDyBnC,CAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/live/client-components/SanityLive.tsx","../../../src/live/client-components/index.ts"],"sourcesContent":[],"mappings":";UAwBU,kBAAA,SAA2B,KACnC;AADQ,UAWO,eAAA,CAXP;EAWV,MAAiB,EACP,kBADO;EACP;;;EAMyB,WAAA,EAFpB,OAEoB,CAFZ,iBAEY,EAAA,KAAA,CAAA;EACe,WAAA,EAAA,CAAA,IAAA,EAAA,MAAA,EAAA,EAAA,GADf,OACe,CAAA,IAAA,GAAA,SAAA,CAAA;EAa7B,0BAAA,EAAA,CAAA,IAAA,EAAA,MAAA,EAAA,EAAA,GAb6B,OAa7B,CAAA,IAAA,GAAA,SAAA,CAAA;EAAA,cAAA,CAAA,EAAA,OAAA;;EChDrB,kBAA6C,CAAA,EAAA,OAAA;;;;;;;;qBDgDxB;;;AA/Cd;AA0BP;AACU,cC5BG,UD4BH,EC5Be,KAAA,CAAM,aD4BrB,CC5BmC,eD4BnC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-sanity",
3
- "version": "13.0.0-cache-components.17",
3
+ "version": "13.0.0-cache-components.18",
4
4
  "description": "Sanity.io toolkit for Next.js",
5
5
  "keywords": [
6
6
  "live",
@@ -30,9 +30,9 @@
30
30
  "types": "./dist/index.d.ts",
31
31
  "imports": {
32
32
  "#env": {
33
- "next-js": "./src/env/next-js.ts",
34
- "react-server": "./src/env/react-server.ts",
35
- "default": "./src/env/default.ts"
33
+ "next-js": "./src/_env/next-js.ts",
34
+ "react-server": "./src/_env/react-server.ts",
35
+ "default": "./src/_env/default.ts"
36
36
  },
37
37
  "#live/*": "./src/live/shared/*.ts"
38
38
  },
@@ -68,7 +68,7 @@
68
68
  "@sanity/preview-url-secret": "^4.0.2",
69
69
  "@sanity/visual-editing": "^5.1.0",
70
70
  "dequal": "^2.0.3",
71
- "groq": "^5.2.0",
71
+ "groq": "^5.3.0",
72
72
  "history": "^5.3.0"
73
73
  },
74
74
  "devDependencies": {
@@ -76,7 +76,7 @@
76
76
  "@sanity/tsconfig": "^2.1.0",
77
77
  "@sanity/webhook": "4.0.4",
78
78
  "@types/js-yaml": "^4.0.9",
79
- "@types/node": "^24.10.7",
79
+ "@types/node": "^24.10.8",
80
80
  "@types/react": "^19.2.8",
81
81
  "@types/react-dom": "^19.2.3",
82
82
  "@vitejs/plugin-react": "^5.1.2",
@@ -97,7 +97,7 @@
97
97
  "next": "^16.0.0-0",
98
98
  "react": "^19.2.3",
99
99
  "react-dom": "^19.2.3",
100
- "sanity": "^5.2.0",
100
+ "sanity": "^5.3.0",
101
101
  "styled-components": "^6.1"
102
102
  },
103
103
  "browserslist": "extends @sanity/browserslist-config",