Socket
Socket
Sign inDemoInstall

@sanity/presentation

Package Overview
Dependencies
Maintainers
56
Versions
135
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@sanity/presentation - npm Package Compare versions

Comparing version 1.16.4-canary.1 to 1.16.4-canary.3

18

dist/_chunks-es/BroadcastDisplayedDocument.js

@@ -1,17 +0,1 @@

import { memo, useEffect } from 'react';
import { usePresentationParams } from './index.js';
import { useDisplayedDocumentBroadcaster } from './DisplayedDocumentBroadcaster.js';
function BroadcastDisplayedDocument(props) {
const setDisplayedDocument = useDisplayedDocumentBroadcaster();
const params = usePresentationParams(false);
useEffect(() => {
const timeout = setTimeout(() => setDisplayedDocument?.(props.value), 10);
return () => clearTimeout(timeout);
}, [params?.perspective, props.value, setDisplayedDocument]);
return null;
}
var BroadcastDisplayedDocument$1 = memo(BroadcastDisplayedDocument);
export { BroadcastDisplayedDocument$1 as default };
//# sourceMappingURL=BroadcastDisplayedDocument.js.map
import{memo as e,useEffect as r}from"react";import{d as t}from"./index.js";import{u as o}from"./DisplayedDocumentBroadcaster.js";var a=e((function(e){const a=o(),s=t(!1);return r((()=>{const r=setTimeout((()=>a?.(e.value)),10);return()=>clearTimeout(r)}),[s?.perspective,e.value,a]),null}));export{a as default};//# sourceMappingURL=BroadcastDisplayedDocument.js.map

@@ -1,26 +0,1 @@

import { jsx } from 'react/jsx-runtime';
import isEqual from 'fast-deep-equal';
import { createContext, useContext, useCallback, useEffect } from 'react';
const Context = createContext(null);
function DisplayedDocumentBroadcasterProvider(props) {
const { children, setDisplayedDocument, documentId } = props;
const context = useCallback(
(next) => setDisplayedDocument((prev) => isEqual(prev, next) ? prev : next),
[setDisplayedDocument]
);
useEffect(() => {
if (documentId) {
return;
}
const timeout = setTimeout(() => setDisplayedDocument(null));
return () => clearTimeout(timeout);
}, [documentId, setDisplayedDocument]);
return /* @__PURE__ */ jsx(Context.Provider, { value: context, children });
}
function useDisplayedDocumentBroadcaster() {
return useContext(Context);
}
export { DisplayedDocumentBroadcasterProvider, useDisplayedDocumentBroadcaster };
//# sourceMappingURL=DisplayedDocumentBroadcaster.js.map
import{jsx as e}from"react/jsx-runtime";import r from"fast-deep-equal";import{createContext as t,useContext as n,useCallback as o,useEffect as u}from"react";const i=t(null);function c(t){const{children:n,setDisplayedDocument:c,documentId:m}=t,l=o((e=>c((t=>r(t,e)?t:e))),[c]);return u((()=>{if(m)return;const e=setTimeout((()=>c(null)));return()=>clearTimeout(e)}),[m,c]),e(i.Provider,{value:l,children:n})}function m(){return n(i)}export{c as D,m as u};//# sourceMappingURL=DisplayedDocumentBroadcaster.js.map

@@ -1,566 +0,7 @@

import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useMemo, useEffect, createContext, useContext, useCallback, createElement, useRef, useLayoutEffect, lazy, Suspense } from 'react';
import { useDocumentStore, isRecord, isReference, defineLocaleResourceBundle, useTranslation, defineDocumentFieldAction, useWorkspace, pathToString, getPublishedId, definePlugin, isDocumentSchemaType } from 'sanity';
import { ComposeIcon, InfoOutlineIcon, ChevronRightIcon, DesktopIcon, WarningOutlineIcon, ErrorOutlineIcon, MasterDetailIcon } from '@sanity/icons';
import { Card, Flex, Box, Text, Spinner, Stack, rem } from '@sanity/ui';
import { styled } from 'styled-components';
import get from 'lodash.get';
import { Observable, switchMap, isObservable, from, map, of, combineLatest, mergeAll, scan } from 'rxjs';
import { useIntentLink, useRouter, encodeJsonParams, route } from 'sanity/router';
import { uuid } from '@sanity/uuid';
import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import{useState as r,useMemo as i,useEffect as o,createContext as s,useContext as c,useCallback as a,createElement as l,useRef as d,useLayoutEffect as p,lazy as u,Suspense as m}from"react";import{useDocumentStore as h,isRecord as f,isReference as y,defineLocaleResourceBundle as g,useTranslation as v,defineDocumentFieldAction as w,useWorkspace as b,pathToString as _,getPublishedId as P,definePlugin as j,isDocumentSchemaType as x}from"sanity";import{ComposeIcon as I,InfoOutlineIcon as T,ChevronRightIcon as S,DesktopIcon as O,WarningOutlineIcon as k,ErrorOutlineIcon as z,MasterDetailIcon as D}from"@sanity/icons";import{Card as A,Flex as E,Box as $,Text as C,Spinner as B,Stack as R,rem as U}from"@sanity/ui";import{styled as H}from"styled-components";import L from"lodash.get";import{Observable as N,switchMap as M,isObservable as Q,from as q,map as F,of as G,combineLatest as J,mergeAll as K,scan as V}from"rxjs";import{useIntentLink as W,useRouter as X,encodeJsonParams as Y,route as Z}from"sanity/router";import{uuid as ee}from"@sanity/uuid";const te=I,ne="presentation",re="Presentation",ie="sanity/structure/comments",oe="presentation",se=3e3,ce="2023-10-16",ae=1e3,le=100,de=2048;function pe(e,t,n){return{...e,[t]:n}}function ue(e={}){return t=>new N((e=>t.subscribe(e))).pipe(M((t=>{const n=(r=t,Object.keys(r)).map((e=>{const n=t[e];return Q(n)?q(n).pipe(F((t=>[e,t]))):G([e,n])}));var r;return e.wait?J(n).pipe(F((e=>e.reduce(((e,[t,n])=>pe(e,t,n)),{})))):q(n).pipe(K(),V(((e,[t,n])=>pe(e,t,n)),{}))})))}const me={locations:[]};function he(e,t,n){if(!e||"object"!=typeof e)return G(e);const r=function(e){return y(e)?e._ref:"_id"in e?e._id:void 0}(e),i=function(e,t){const n=e?{...t,_id:e}:{...t};return"reference"===n._type&&(delete n._type,delete n._ref,delete n._weak,delete n._dataset,delete n._projectId,delete n._strengthenOnPublish),n}(r,e),o=t.filter((e=>!(e[0]in i)));if(r&&o.length){return function(e,t,n){const r=`*[_id==$id][0]{${t.join(", ")}}`,i={id:e};return n.listenQuery(r,i,{perspective:"previewDrafts"})}(r,[...new Set(o.map((e=>e[0])))],n).pipe(M((e=>e?he(e,t,n):G(null))))}const s={};t.forEach((e=>{const[t,...n]=e;s[t]||(s[t]=[]),s[t].push(n)}));const c=Object.keys(s).reduce(((t,r)=>{const i=s[r].filter((e=>e.length>0));return 0===i.length?t[r]=f(e)?e[r]:void 0:t[r]=he(e[r],i,n),t}),i);return G(c).pipe(ue({wait:!0}))}function fe(e){const{id:t,resolvers:n,type:s}=e,c=h(),[a,l]=r(me),d=n&&("function"==typeof n?n:n[s]),[p,u]=r(d?"resolving":"empty"),m=i((()=>{if(d){if("function"==typeof d){const e=d({id:t,type:s},{documentStore:c});return Q(e)?e:G(e)}return"select"in d&&"resolve"in d?function(e,t,n){const{select:r}=t;return he({_type:"reference",_ref:e},Object.values(r).map((e=>String(e).split(".")))||[],n).pipe(F((e=>Object.keys(r).reduce(((t,n)=>(t[n]=L(e,r[n]),t)),{}))),F(t.resolve))}(t,d,c):G(d)}}),[c,t,d,s]);return o((()=>{const e=m?.subscribe((e=>{l(e||me),u(e?"resolved":"empty")}));return()=>e?.unsubscribe()}),[m]),{state:a,status:p}}const ye="presentation",ge=g({locale:"en-US",namespace:ye,resources:()=>import("./resources.js")}),ve=s(null);function we(){const e=c(ve);if(!e)throw new Error("Presentation context is missing");return e}const be={positive:T,caution:k,critical:z};function _e(i){const{documentId:o,isResolving:s,options:d,schemaType:p,showPresentationTitle:u}=i,{locations:m,message:h,tone:f}=i.state,y=m?.length||0,{t:g}=v(ye),w=c(ve),[b,_]=r(!1),P=a((()=>{y&&_((e=>!e))}),[y]),j=s?g("locations-banner.resolving.text"):h||g("locations-banner.locations-count",{count:y});return e(A,{padding:1,radius:2,border:!0,tone:f,children:t("div",{style:{margin:-1},children:[!m&&t(E,{align:"flex-start",gap:3,padding:3,children:[f&&e($,{flex:"none",children:e(C,{size:1,children:l(be[f])})}),e($,{flex:1,children:t(C,{size:1,weight:"medium",children:[u&&t(n,{children:[d.title||re," · "]}),j]})})]}),m&&t(n,{children:[e(A,{as:y?"button":void 0,onClick:P,padding:3,radius:1,tone:"inherit",children:t(E,{gap:3,children:[e($,{flex:"none",children:s?e(B,{size:1}):e(C,{size:1,children:0===y?e(T,{}):e(S,{style:{transform:`rotate(${b?"90deg":0})`,transition:"transform 100ms ease-in-out"}})})}),e($,{flex:1,children:t(C,{size:1,weight:"medium",children:[u&&t(n,{children:[d.title||re," · "]}),j]})})]})}),e(R,{hidden:!b,marginTop:1,space:1,children:m.map(((t,n)=>e(Pe,{active:(d.name||ne)===w?.name&&t.href===w?.params.preview,documentId:o,documentType:p.name,node:t,toolName:d.name||ne},n)))})]})]})})}function Pe(n){const{documentId:r,documentType:i,node:o,active:s,toolName:d}=n,p=c(ve),u=d===function(){try{return we().name}catch{return}}(),m=p?.navigate,h=W({intent:"edit",params:{id:r,type:i,mode:"presentation",presentation:d,...p?.structureParams,preview:o.href}}),f=a((()=>{m?.({},{preview:o.href})}),[o.href,m]);return l(A,{...u?{}:h,as:"a",key:o.href,onClick:u?f:h.onClick,padding:3,radius:1,pressed:s,tone:"inherit"},t(E,{gap:3,children:[e($,{flex:"none",children:e(C,{size:1,children:e(O,{})})}),t(R,{flex:1,space:2,children:[e(C,{size:1,weight:"medium",children:o.title}),e(C,{muted:!0,size:1,textOverflow:"ellipsis",children:o.href})]})]}))}const je=s(null),xe=H(R)`
min-height: ${U(42)};
const DEFAULT_TOOL_ICON = ComposeIcon;
const DEFAULT_TOOL_NAME = "presentation";
const DEFAULT_TOOL_TITLE = "Presentation";
const COMMENTS_INSPECTOR_NAME = "sanity/structure/comments";
const EDIT_INTENT_MODE = "presentation";
const MAX_TIME_TO_OVERLAYS_CONNECTION = 3e3;
const API_VERSION = "2023-10-16";
const MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL = 1e3;
const LIVE_QUERY_CACHE_BATCH_SIZE = 100;
const LIVE_QUERY_CACHE_SIZE = 2048;
function keysOf(value) {
return Object.keys(value);
}
function setKey(source, key, value) {
return {
...source,
[key]: value
};
}
function props(options = {}) {
return (source) => {
return new Observable((observer) => source.subscribe(observer)).pipe(
switchMap((object) => {
const keyObservables = keysOf(object).map((key) => {
const value = object[key];
return isObservable(value) ? from(value).pipe(map((val) => [key, val])) : of([key, value]);
});
return options.wait ? combineLatest(keyObservables).pipe(
map((pairs) => pairs.reduce((acc, [key, value]) => setKey(acc, key, value), {}))
) : from(keyObservables).pipe(
mergeAll(),
scan((acc, [key, value]) => setKey(acc, key, value), {})
);
})
);
};
}
const INITIAL_STATE = { locations: [] };
function getDocumentId(value) {
if (isReference(value)) {
return value._ref;
}
return "_id" in value ? value._id : void 0;
}
function cleanPreviewable(id, previewable) {
const clean = id ? { ...previewable, _id: id } : { ...previewable };
if (clean["_type"] === "reference") {
delete clean["_type"];
delete clean["_ref"];
delete clean["_weak"];
delete clean["_dataset"];
delete clean["_projectId"];
delete clean["_strengthenOnPublish"];
}
return clean;
}
function listen(id, fields, store) {
const projection = fields.join(", ");
const query = `*[_id==$id][0]{${projection}}`;
const params = { id };
return store.listenQuery(query, params, {
perspective: "previewDrafts"
});
}
function observeDocument(value, paths, store) {
if (!value || typeof value !== "object") {
return of(value);
}
const id = getDocumentId(value);
const currentValue = cleanPreviewable(id, value);
const headlessPaths = paths.filter((path) => !(path[0] in currentValue));
if (id && headlessPaths.length) {
const fields = [...new Set(headlessPaths.map((path) => path[0]))];
return listen(id, fields, store).pipe(
switchMap((snapshot) => {
if (snapshot) {
return observeDocument(snapshot, paths, store);
}
return of(null);
})
);
}
const leads = {};
paths.forEach((path) => {
const [head, ...tail] = path;
if (!leads[head]) {
leads[head] = [];
}
leads[head].push(tail);
});
const next = Object.keys(leads).reduce((res, head) => {
const tails = leads[head].filter((tail) => tail.length > 0);
if (tails.length === 0) {
res[head] = isRecord(value) ? value[head] : void 0;
} else {
res[head] = observeDocument(value[head], tails, store);
}
return res;
}, currentValue);
return of(next).pipe(props({ wait: true }));
}
function observeForLocations(documentId, resolver, documentStore) {
const { select } = resolver;
const paths = Object.values(select).map((value) => String(value).split(".")) || [];
const doc = { _type: "reference", _ref: documentId };
return observeDocument(doc, paths, documentStore).pipe(
map((doc2) => {
return Object.keys(select).reduce((acc, key) => {
acc[key] = get(doc2, select[key]);
return acc;
}, {});
}),
map(resolver.resolve)
);
}
function useDocumentLocations(props2) {
const { id, resolvers, type } = props2;
const documentStore = useDocumentStore();
const [locationsState, setLocationsState] = useState(INITIAL_STATE);
const resolver = resolvers && (typeof resolvers === "function" ? resolvers : resolvers[type]);
const [locationsStatus, setLocationsStatus] = useState(
resolver ? "resolving" : "empty"
);
const result = useMemo(() => {
if (!resolver) return void 0;
if (typeof resolver === "function") {
const params = { id, type };
const context = { documentStore };
const _result = resolver(params, context);
return isObservable(_result) ? _result : of(_result);
}
if ("select" in resolver && "resolve" in resolver) {
return observeForLocations(id, resolver, documentStore);
}
return of(resolver);
}, [documentStore, id, resolver, type]);
useEffect(() => {
const sub = result?.subscribe((state) => {
setLocationsState(state || INITIAL_STATE);
setLocationsStatus(state ? "resolved" : "empty");
});
return () => sub?.unsubscribe();
}, [result]);
return {
state: locationsState,
status: locationsStatus
};
}
const presentationLocaleNamespace = "presentation";
const presentationUsEnglishLocaleBundle = defineLocaleResourceBundle({
locale: "en-US",
namespace: presentationLocaleNamespace,
resources: () => import('./resources.js')
});
const PresentationContext = createContext(null);
function usePresentationTool() {
const presentation = useContext(PresentationContext);
if (!presentation) {
throw new Error("Presentation context is missing");
}
return presentation;
}
function useCurrentPresentationToolName() {
try {
return usePresentationTool().name;
} catch {
return void 0;
}
}
const TONE_ICONS = {
positive: InfoOutlineIcon,
caution: WarningOutlineIcon,
critical: ErrorOutlineIcon
};
function LocationsBanner(props) {
const { documentId, isResolving, options, schemaType, showPresentationTitle } = props;
const { locations, message, tone } = props.state;
const len = locations?.length || 0;
const { t } = useTranslation(presentationLocaleNamespace);
const presentation = useContext(PresentationContext);
const [expanded, setExpanded] = useState(false);
const toggle = useCallback(() => {
if (!len) return;
setExpanded((v) => !v);
}, [len]);
const title = isResolving ? t("locations-banner.resolving.text") : message || t("locations-banner.locations-count", { count: len });
return /* @__PURE__ */ jsx(Card, { padding: 1, radius: 2, border: true, tone, children: /* @__PURE__ */ jsxs("div", { style: { margin: -1 }, children: [
!locations && /* @__PURE__ */ jsxs(Flex, { align: "flex-start", gap: 3, padding: 3, children: [
tone && /* @__PURE__ */ jsx(Box, { flex: "none", children: /* @__PURE__ */ jsx(Text, { size: 1, children: createElement(TONE_ICONS[tone]) }) }),
/* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsxs(Text, { size: 1, weight: "medium", children: [
showPresentationTitle && /* @__PURE__ */ jsxs(Fragment, { children: [
options.title || DEFAULT_TOOL_TITLE,
" \xB7 "
] }),
title
] }) })
] }),
locations && /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(
Card,
{
as: len ? "button" : void 0,
onClick: toggle,
padding: 3,
radius: 1,
tone: "inherit",
children: /* @__PURE__ */ jsxs(Flex, { gap: 3, children: [
/* @__PURE__ */ jsx(Box, { flex: "none", children: isResolving ? /* @__PURE__ */ jsx(Spinner, { size: 1 }) : /* @__PURE__ */ jsx(Text, { size: 1, children: len === 0 ? /* @__PURE__ */ jsx(InfoOutlineIcon, {}) : /* @__PURE__ */ jsx(
ChevronRightIcon,
{
style: {
transform: `rotate(${expanded ? "90deg" : 0})`,
transition: "transform 100ms ease-in-out"
}
}
) }) }),
/* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsxs(Text, { size: 1, weight: "medium", children: [
showPresentationTitle && /* @__PURE__ */ jsxs(Fragment, { children: [
options.title || DEFAULT_TOOL_TITLE,
" \xB7 "
] }),
title
] }) })
] })
}
),
/* @__PURE__ */ jsx(Stack, { hidden: !expanded, marginTop: 1, space: 1, children: locations.map((l, index) => /* @__PURE__ */ jsx(
LocationItem,
{
active: (options.name || DEFAULT_TOOL_NAME) === presentation?.name && l.href === presentation?.params.preview,
documentId,
documentType: schemaType.name,
node: l,
toolName: options.name || DEFAULT_TOOL_NAME
},
index
)) })
] })
] }) });
}
function LocationItem(props) {
const { documentId, documentType, node, active, toolName } = props;
const presentation = useContext(PresentationContext);
const currentPresentationToolName = useCurrentPresentationToolName();
const isCurrentTool = toolName === currentPresentationToolName;
const navigate = presentation?.navigate;
const presentationLinkProps = useIntentLink({
intent: "edit",
params: {
id: documentId,
type: documentType,
mode: "presentation",
presentation: toolName,
...presentation?.structureParams,
preview: node.href
}
});
const handleCurrentToolClick = useCallback(() => {
navigate?.({}, { preview: node.href });
}, [node.href, navigate]);
return /* @__PURE__ */ createElement(
Card,
{
...isCurrentTool ? {} : presentationLinkProps,
as: "a",
key: node.href,
onClick: isCurrentTool ? handleCurrentToolClick : presentationLinkProps.onClick,
padding: 3,
radius: 1,
pressed: active,
tone: "inherit"
},
/* @__PURE__ */ jsxs(Flex, { gap: 3, children: [
/* @__PURE__ */ jsx(Box, { flex: "none", children: /* @__PURE__ */ jsx(Text, { size: 1, children: /* @__PURE__ */ jsx(DesktopIcon, {}) }) }),
/* @__PURE__ */ jsxs(Stack, { flex: 1, space: 2, children: [
/* @__PURE__ */ jsx(Text, { size: 1, weight: "medium", children: node.title }),
/* @__PURE__ */ jsx(Text, { muted: true, size: 1, textOverflow: "ellipsis", children: node.href })
] })
] })
);
}
const PresentationDocumentContext = createContext(
null
);
const LocationStack = styled(Stack)`
min-height: ${rem(42)};
& + &:empty {
display: none;
}
`;
function PresentationDocumentHeader(props) {
const { documentId, options, schemaType } = props;
const context = useContext(PresentationDocumentContext);
const { state, status } = useDocumentLocations({
id: documentId,
resolvers: options.resolve?.locations || options.locate,
type: schemaType.name
});
if (context && context.options[0] !== options || status === "empty") {
return null;
}
const contextOptions = context?.options || [];
return /* @__PURE__ */ jsx(LocationStack, { marginBottom: 5, space: 5, children: /* @__PURE__ */ jsx(Stack, { space: 2, children: contextOptions.map((options2, idx) => /* @__PURE__ */ jsx(
LocationsBanner,
{
documentId,
isResolving: status === "resolving",
options: options2,
schemaType,
showPresentationTitle: contextOptions.length > 1,
state
},
idx
)) }) });
}
function PresentationDocumentProvider(props) {
const { children, options } = props;
const parent = useContext(PresentationDocumentContext);
const parentRegister = parent?.register;
const [optionsArray, setOptionsArray] = useState(() => []);
const register = useCallback(
(options2) => {
if (parentRegister) {
return parentRegister(options2);
}
setOptionsArray((prev) => [options2].concat(prev));
return () => {
setOptionsArray((prev) => prev.filter((o) => o !== options2));
};
},
[parentRegister]
);
const registerRef = useRef(register);
registerRef.current = register;
const context = useMemo(
() => ({
options: parent?.options || optionsArray,
register
}),
[optionsArray, parent, register]
);
useLayoutEffect(() => registerRef.current(options), [options]);
return /* @__PURE__ */ jsx(PresentationDocumentContext.Provider, { value: context, children });
}
const openInStructure = defineDocumentFieldAction({
name: "presentation/openInStructure",
useAction({ documentId, documentType, path }) {
const workspace = useWorkspace();
const { navigateIntent } = useRouter();
const presentation = useContext(PresentationContext);
const defaultStructureTool = useMemo(
() => findStructureTool(workspace.tools, documentId, documentType),
[documentId, documentType, workspace.tools]
);
return {
type: "action",
hidden: !presentation || path.length > 0 || !defaultStructureTool,
icon: defaultStructureTool?.icon || MasterDetailIcon,
title: `Open in ${defaultStructureTool?.title || "Structure"}`,
onAction() {
navigateIntent("edit", {
id: documentId,
type: documentType,
mode: "structure",
path: pathToString(path)
});
},
renderAsButton: true
};
}
});
function findStructureTool(tools, documentId, documentType) {
const results = tools.map((t) => {
const match = t.canHandleIntent?.(
"edit",
{
id: documentId,
type: documentType,
mode: "structure"
},
{}
);
return { tool: t, match };
});
const modeMatches = results.filter((t) => isRecord(t.match) && t.match["mode"]);
if (modeMatches.length > 0) {
return modeMatches[0].tool;
}
const matches = results.filter((t) => t.match);
return matches[0]?.tool;
}
const preservedSearchParamKeys = [
"preview",
"perspective",
"viewport"
];
function getIntentState(intent, params, routerState, payload) {
const { id, mode, path, presentation, type, ...searchParams } = params;
const preservedSearchParams = (routerState?._searchParams || []).filter(([key]) => preservedSearchParamKeys.includes(key)).reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
const _searchParams = {
...preservedSearchParams,
...searchParams
};
if (intent === "edit" && id) {
return {
type: type || "*",
id: getPublishedId(id),
path,
_searchParams: Object.entries(_searchParams)
};
}
if (intent === "create") {
_searchParams["preview"] = _searchParams["preview"] || new URLSearchParams(window.location.search).get("preview") || "/";
if (payload && typeof payload === "object") {
_searchParams["templateParams"] = encodeJsonParams(payload);
}
return {
type: type || "*",
id: id || uuid(),
_searchParams: Object.entries(_searchParams)
};
}
return { intent, params, payload };
}
const router = route.create("/", { __unsafe_disableScopedSearchParams: true }, [
route.intents("/intent"),
route.create(":type", [route.create(":id", [route.create(":path")])])
]);
const PresentationTool = lazy(() => import('./PresentationTool.js'));
const BroadcastDisplayedDocument = lazy(() => import('./BroadcastDisplayedDocument.js'));
function defineLocations(resolver) {
return resolver;
}
function defineDocuments(resolvers) {
return resolvers;
}
const presentationTool = definePlugin((options) => {
const toolName = options.name || DEFAULT_TOOL_NAME;
if ("locate" in options) {
console.warn("Presentation\u2019s `locate` option is deprecated. Use `resolve.locations` instead.");
}
const hasLocationsResolver = !!(options.resolve?.locations || options.locate);
function PresentationDocumentInput(props) {
const value = props.value;
const documentId = value?._id ? getPublishedId(value?._id) : void 0;
if (isDocumentSchemaType(props.schemaType)) {
return /* @__PURE__ */ jsxs(PresentationDocumentProvider, { options, children: [
hasLocationsResolver && documentId && /* @__PURE__ */ jsx(
PresentationDocumentHeader,
{
documentId,
options,
schemaType: props.schemaType
}
),
props.renderDefault(props),
/* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(BroadcastDisplayedDocument, { value }, documentId) }, "broadcast-displayed-document")
] });
}
return props.renderDefault(props);
}
function canHandleCreateIntent(params) {
if (!("type" in params)) {
return false;
}
if ("presentation" in params && params["presentation"] !== toolName) {
return false;
}
return "template" in params ? { template: true } : true;
}
function canHandleEditIntent(params) {
if (!("type" in params) || !("id" in params)) {
return false;
}
if ("presentation" in params && params["presentation"] !== toolName) {
return false;
}
return "mode" in params ? { mode: params["mode"] === EDIT_INTENT_MODE } : true;
}
return {
i18n: {
bundles: [presentationUsEnglishLocaleBundle]
},
document: {
unstable_fieldActions: (prev) => {
return [
...prev.filter((a) => a.name !== openInStructure.name),
// prevent duplication
openInStructure
];
}
},
form: {
components: {
input: PresentationDocumentInput
}
},
tools: [
{
icon: options.icon || DEFAULT_TOOL_ICON,
name: toolName,
title: options.title,
component: PresentationTool,
options,
canHandleIntent(intent, params) {
if (intent === "create") return canHandleCreateIntent(params);
if (intent === "edit") return canHandleEditIntent(params);
return false;
},
getIntentState,
router
}
]
};
});
const PresentationNavigateContext = createContext(
null
);
function usePresentationNavigate() {
const navigate = useContext(PresentationNavigateContext);
if (!navigate) {
throw new Error("Presentation navigate context is missing");
}
return navigate;
}
const PresentationParamsContext = createContext(null);
function usePresentationParams(throwOnMissingContext = true) {
const params = useContext(PresentationParamsContext);
if (throwOnMissingContext && !params) {
throw new Error("Presentation params context is missing");
}
return params;
}
export { API_VERSION, COMMENTS_INSPECTOR_NAME, DEFAULT_TOOL_NAME, EDIT_INTENT_MODE, LIVE_QUERY_CACHE_BATCH_SIZE, LIVE_QUERY_CACHE_SIZE, MAX_TIME_TO_OVERLAYS_CONNECTION, MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL, PresentationContext, PresentationNavigateContext, PresentationParamsContext, defineDocuments, defineLocations, presentationLocaleNamespace, presentationTool, usePresentationNavigate, usePresentationParams, usePresentationTool };
//# sourceMappingURL=index.js.map
`;function Ie(t){const{documentId:n,options:r,schemaType:i}=t,o=c(je),{state:s,status:a}=fe({id:n,resolvers:r.resolve?.locations||r.locate,type:i.name});if(o&&o.options[0]!==r||"empty"===a)return null;const l=o?.options||[];return e(xe,{marginBottom:5,space:5,children:e(R,{space:2,children:l.map(((t,r)=>e(_e,{documentId:n,isResolving:"resolving"===a,options:t,schemaType:i,showPresentationTitle:l.length>1,state:s},r)))})})}function Te(t){const{children:n,options:o}=t,s=c(je),l=s?.register,[u,m]=r((()=>[])),h=a((e=>l?l(e):(m((t=>[e].concat(t))),()=>{m((t=>t.filter((t=>t!==e))))})),[l]),f=d(h);f.current=h;const y=i((()=>({options:s?.options||u,register:h})),[u,s,h]);return p((()=>f.current(o)),[o]),e(je.Provider,{value:y,children:n})}const Se=w({name:"presentation/openInStructure",useAction({documentId:e,documentType:t,path:n}){const r=b(),{navigateIntent:o}=X(),s=c(ve),a=i((()=>function(e,t,n){const r=e.map((e=>{const r=e.canHandleIntent?.("edit",{id:t,type:n,mode:"structure"},{});return{tool:e,match:r}})),i=r.filter((e=>f(e.match)&&e.match.mode));return i.length>0?i[0].tool:r.filter((e=>e.match))[0]?.tool}(r.tools,e,t)),[e,t,r.tools]);return{type:"action",hidden:!s||n.length>0||!a,icon:a?.icon||D,title:`Open in ${a?.title||"Structure"}`,onAction(){o("edit",{id:e,type:t,mode:"structure",path:_(n)})},renderAsButton:!0}}});const Oe=["preview","perspective","viewport"];function ke(e,t,n,r){const{id:i,mode:o,path:s,presentation:c,type:a,...l}=t,d={...(n?._searchParams||[]).filter((([e])=>Oe.includes(e))).reduce(((e,[t,n])=>({...e,[t]:n})),{}),...l};return"edit"===e&&i?{type:a||"*",id:P(i),path:s,_searchParams:Object.entries(d)}:"create"===e?(d.preview=d.preview||new URLSearchParams(window.location.search).get("preview")||"/",r&&"object"==typeof r&&(d.templateParams=Y(r)),{type:a||"*",id:i||ee(),_searchParams:Object.entries(d)}):{intent:e,params:t,payload:r}}const ze=Z.create("/",{__unsafe_disableScopedSearchParams:!0},[Z.intents("/intent"),Z.create(":type",[Z.create(":id",[Z.create(":path")])])]),De=u((()=>import("./PresentationTool.js"))),Ae=u((()=>import("./BroadcastDisplayedDocument.js")));function Ee(e){return e}function $e(e){return e}const Ce=j((n=>{const r=n.name||ne;"locate"in n&&console.warn("Presentation’s `locate` option is deprecated. Use `resolve.locations` instead.");const i=!(!n.resolve?.locations&&!n.locate);return{i18n:{bundles:[ge]},document:{unstable_fieldActions:e=>[...e.filter((e=>e.name!==Se.name)),Se]},form:{components:{input:function(r){const o=r.value,s=o?._id?P(o?._id):void 0;return x(r.schemaType)?t(Te,{options:n,children:[i&&s&&e(Ie,{documentId:s,options:n,schemaType:r.schemaType}),r.renderDefault(r),e(m,{children:e(Ae,{value:o},s)},"broadcast-displayed-document")]}):r.renderDefault(r)}}},tools:[{icon:n.icon||te,name:r,title:n.title,component:De,options:n,canHandleIntent:(e,t)=>"create"===e?function(e){return"type"in e&&(!("presentation"in e)||e.presentation===r)&&(!("template"in e)||{template:!0})}(t):"edit"===e&&function(e){return"type"in e&&"id"in e&&(!("presentation"in e)||e.presentation===r)&&(!("mode"in e)||{mode:e.mode===oe})}(t),getIntentState:ke,router:ze}]}})),Be=s(null);function Re(){const e=c(Be);if(!e)throw new Error("Presentation navigate context is missing");return e}const Ue=s(null);function He(e=!0){const t=c(Ue);if(e&&!t)throw new Error("Presentation params context is missing");return t}export{ce as A,ie as C,ne as D,oe as E,de as L,se as M,Be as P,Ue as a,ve as b,ae as c,He as d,le as e,Re as f,Ee as g,$e as h,Ce as i,ye as p,we as u};//# sourceMappingURL=index.js.map

@@ -1,374 +0,1 @@

import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
import { useMemo, useState, useCallback, useEffect, useSyncExternalStore, memo } from 'react';
import { applySourceDocuments, getPublishedId } from '@sanity/client/csm';
import { applyPatch } from 'mendoza';
import LRUCache from 'mnemonist/lru-cache-with-delete';
import { useClient } from 'sanity';
import { LIVE_QUERY_CACHE_SIZE, LIVE_QUERY_CACHE_BATCH_SIZE } from './index.js';
function useQueryParams(params) {
const stringifiedParams = useMemo(() => JSON.stringify(params || {}), [params]);
return useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams]);
}
function useRevalidate(props) {
const { refreshInterval } = props;
const shouldPause = useShouldPause();
const [state, setState] = useState("hit");
const startRefresh = useCallback(() => {
setState("inflight");
return () => setState("hit");
}, []);
useEffect(() => {
if (!refreshInterval || state !== "hit") {
return;
}
const timeout = setTimeout(() => setState("stale"), refreshInterval);
return () => clearTimeout(timeout);
}, [refreshInterval, state]);
useEffect(() => {
if (state !== "hit") {
return;
}
const onFocus = () => setState("stale");
window.addEventListener("focus", onFocus);
return () => window.removeEventListener("focus", onFocus);
}, [refreshInterval, state]);
useEffect(() => {
if (shouldPause && state === "hit") {
setState("stale");
}
if (!shouldPause && state === "stale") {
setState("refresh");
}
}, [shouldPause, state]);
return [state, startRefresh];
}
function useShouldPause() {
const [online, setOnline] = useState(false);
useEffect(() => {
setOnline(navigator.onLine);
const online2 = () => setOnline(true);
const offline = () => setOnline(false);
window.addEventListener("online", online2);
window.addEventListener("offline", offline);
return () => {
window.removeEventListener("online", online2);
window.removeEventListener("offline", offline);
};
}, []);
const visibilityState = useSyncExternalStore(
onVisibilityChange,
() => document.visibilityState,
() => "hidden"
);
if (!online) {
return true;
}
if (visibilityState === "hidden") {
return true;
}
return false;
}
function onVisibilityChange(onStoreChange) {
document.addEventListener("visibilitychange", onStoreChange);
return () => document.removeEventListener("visibilitychange", onStoreChange);
}
function LoaderQueries(props) {
const {
liveDocument,
channel,
perspective: activePerspective,
liveQueries,
documentsOnPage
} = props;
const [cache] = useState(() => new LRUCache(LIVE_QUERY_CACHE_SIZE));
const studioClient = useClient({ apiVersion: "2023-10-16" });
const clientConfig = useMemo(() => studioClient.config(), [studioClient]);
const client = useMemo(
() => studioClient.withConfig({
resultSourceMap: "withKeyArraySelector"
}),
[studioClient]
);
useEffect(() => {
if (channel) {
const { projectId, dataset } = clientConfig;
channel.send("loaders", "loader/perspective", {
projectId,
dataset,
perspective: activePerspective
});
}
}, [channel, clientConfig, activePerspective]);
const turboIds = useMemo(() => {
const documentsActuallyInUse = documentsOnPage.map(({ _id }) => _id);
const set = new Set(documentsActuallyInUse);
const ids = [...set];
const max = cache.capacity;
if (ids.length >= max) {
ids.length = max;
}
return ids;
}, [cache.capacity, documentsOnPage]);
const [documentsCacheLastUpdated, setDocumentsCacheLastUpdated] = useState(0);
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(
Turbo,
{
cache,
client,
turboIds,
setDocumentsCacheLastUpdated
}
),
Object.entries(liveQueries).map(([key, { query, params, perspective }]) => /* @__PURE__ */ jsx(
QuerySubscription,
{
cache,
projectId: clientConfig.projectId,
dataset: clientConfig.dataset,
perspective,
query,
params,
channel,
client,
refreshInterval: activePerspective ? 2e3 : 0,
liveDocument,
documentsCacheLastUpdated
},
`${key}${perspective}`
))
] });
}
const Turbo = memo(function Turbo2(props) {
const { cache, client, turboIds, setDocumentsCacheLastUpdated } = props;
const [batch, setBatch] = useState([]);
useEffect(() => {
const batchSet = new Set(batch.flat());
const nextBatch = /* @__PURE__ */ new Set();
for (const turboId of turboIds) {
if (!batchSet.has(turboId) && !cache.has(turboId)) {
nextBatch.add(turboId);
}
}
const nextBatchSlice = [...nextBatch].slice(0, LIVE_QUERY_CACHE_BATCH_SIZE);
if (nextBatchSlice.length === 0) return;
setBatch((prevBatch) => [...prevBatch.slice(-LIVE_QUERY_CACHE_BATCH_SIZE), nextBatchSlice]);
}, [batch, cache, turboIds]);
useEffect(() => {
const subscription = client.listen(
"*",
{},
{
events: ["mutation"],
effectFormat: "mendoza",
includePreviousRevision: false,
includeResult: false,
tag: "presentation-loader"
}
).subscribe((update) => {
if (update.type === "mutation" && update.transition === "disappear") {
if (cache.delete(update.documentId)) {
setDocumentsCacheLastUpdated(Date.now());
}
}
if (update.type !== "mutation" || !update.effects?.apply?.length) return;
const cachedDocument = cache.peek(update.documentId);
if (cachedDocument) {
const patchDoc = { ...cachedDocument };
delete patchDoc._rev;
const patchedDocument = applyPatch(patchDoc, update.effects.apply);
cache.set(update.documentId, patchedDocument);
setDocumentsCacheLastUpdated(Date.now());
}
});
return () => subscription.unsubscribe();
}, [cache, client, setDocumentsCacheLastUpdated]);
return /* @__PURE__ */ jsx(Fragment, { children: batch.map((ids) => /* @__PURE__ */ jsx(
GetDocuments,
{
cache,
client,
ids,
setDocumentsCacheLastUpdated
},
JSON.stringify(ids)
)) });
});
const GetDocuments = memo(function GetDocuments2(props) {
const { client, cache, ids, setDocumentsCacheLastUpdated } = props;
useEffect(() => {
const missingIds = ids.filter((id) => !cache.has(id));
if (missingIds.length === 0) return;
client.getDocuments(missingIds).then((documents) => {
for (const doc of documents) {
if (doc && doc?._id) {
cache.set(doc._id, doc);
setDocumentsCacheLastUpdated(Date.now());
}
}
}, console.error);
}, [cache, client, ids, setDocumentsCacheLastUpdated]);
return null;
});
GetDocuments.displayName = "GetDocuments";
function QuerySubscription(props) {
const {
cache,
projectId,
dataset,
perspective,
query,
client,
refreshInterval,
liveDocument,
channel,
documentsCacheLastUpdated
} = props;
const params = useQueryParams(props.params);
const data = useQuerySubscription({
cache,
client,
liveDocument,
params,
perspective,
query,
refreshInterval,
documentsCacheLastUpdated
});
const result = data?.result;
const resultSourceMap = data?.resultSourceMap;
useEffect(() => {
if (resultSourceMap) {
channel.send("loaders", "loader/query-change", {
projectId,
dataset,
perspective,
query,
params,
result,
resultSourceMap
});
}
}, [channel, dataset, params, perspective, projectId, query, result, resultSourceMap]);
return null;
}
function useQuerySubscription(props) {
const {
cache,
liveDocument,
client,
refreshInterval,
query,
params,
perspective,
documentsCacheLastUpdated
} = props;
const [snapshot, setSnapshot] = useState(null);
const { projectId, dataset } = useMemo(() => {
const { projectId: projectId2, dataset: dataset2 } = client.config();
return { projectId: projectId2, dataset: dataset2 };
}, [client]);
const [error, setError] = useState(null);
if (error) throw error;
const [revalidate, startRefresh] = useRevalidate({ refreshInterval });
const shouldRefetch = revalidate === "refresh" || revalidate === "inflight";
useEffect(() => {
if (!shouldRefetch) {
return;
}
let fulfilled = false;
let fetching = false;
const controller = new AbortController();
async function effect() {
const { signal } = controller;
fetching = true;
const { result, resultSourceMap } = await client.fetch(query, params, {
tag: "presentation-loader",
signal,
perspective,
filterResponse: false
});
fetching = false;
if (!signal.aborted) {
setSnapshot({ result, resultSourceMap });
fulfilled = true;
}
}
const onFinally = startRefresh();
effect().catch((error2) => {
fetching = false;
if (error2.name !== "AbortError") {
setError(error2);
}
}).finally(onFinally);
return () => {
if (!fulfilled && !fetching) {
controller.abort();
}
};
}, [
client,
dataset,
liveDocument,
params,
perspective,
projectId,
query,
shouldRefetch,
startRefresh
]);
return useMemo(() => {
if (documentsCacheLastUpdated && snapshot?.resultSourceMap) {
return {
result: turboChargeResultIfSourceMap(
cache,
liveDocument,
snapshot.result,
perspective,
snapshot.resultSourceMap
),
resultSourceMap: snapshot.resultSourceMap
};
}
return snapshot;
}, [cache, documentsCacheLastUpdated, liveDocument, perspective, snapshot]);
}
let warnedAboutCrossDatasetReference = false;
function turboChargeResultIfSourceMap(cache, liveDocument, result, perspective, resultSourceMap) {
if (perspective === "raw") {
throw new Error("turboChargeResultIfSourceMap does not support raw perspective");
}
return applySourceDocuments(
result,
resultSourceMap,
(sourceDocument) => {
if (sourceDocument._projectId) {
if (!warnedAboutCrossDatasetReference) {
console.warn(
"Cross dataset references are not supported yet, ignoring source document",
sourceDocument
);
warnedAboutCrossDatasetReference = true;
}
return void 0;
}
if (liveDocument?._id && getPublishedId(liveDocument._id) === getPublishedId(sourceDocument._id)) {
return liveDocument;
}
return cache.get(sourceDocument._id);
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(changedValue, { previousValue }) => {
if (typeof changedValue === "number" && typeof previousValue === "string") {
return `${changedValue}`;
}
return changedValue;
},
perspective
);
}
export { LoaderQueries as default, turboChargeResultIfSourceMap };
//# sourceMappingURL=LoaderQueries.js.map
import{jsxs as e,Fragment as t,jsx as n}from"react/jsx-runtime";import{useMemo as r,useState as s,useEffect as o,useSyncExternalStore as c,useCallback as a,memo as i}from"react";import{applySourceDocuments as u,getPublishedId as d}from"@sanity/client/csm";import{applyPatch as l}from"mendoza";import p from"mnemonist/lru-cache-with-delete";import{useClient as f}from"sanity";import{L as m,e as h}from"./index.js";function v(e){return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)}function w(c){const{liveDocument:a,channel:i,perspective:u,liveQueries:d,documentsOnPage:l}=c,[h]=s((()=>new p(m))),v=f({apiVersion:"2023-10-16"}),w=r((()=>v.config()),[v]),g=r((()=>v.withConfig({resultSourceMap:"withKeyArraySelector"})),[v]);o((()=>{if(i){const{projectId:e,dataset:t}=w;i.send("loaders","loader/perspective",{projectId:e,dataset:t,perspective:u})}}),[i,w,u]);const L=r((()=>{const e=l.map((({_id:e})=>e)),t=[...new Set(e)],n=h.capacity;return t.length>=n&&(t.length=n),t}),[h.capacity,l]),[S,b]=s(0);return e(t,{children:[n(y,{cache:h,client:g,turboIds:L,setDocumentsCacheLastUpdated:b}),Object.entries(d).map((([e,{query:t,params:r,perspective:s}])=>n(I,{cache:h,projectId:w.projectId,dataset:w.dataset,perspective:s,query:t,params:r,channel:i,client:g,refreshInterval:u?2e3:0,liveDocument:a,documentsCacheLastUpdated:S},`${e}${s}`)))]})}const y=i((function(e){const{cache:r,client:c,turboIds:a,setDocumentsCacheLastUpdated:i}=e,[u,d]=s([]);return o((()=>{const e=new Set(u.flat()),t=new Set;for(const n of a)!e.has(n)&&!r.has(n)&&t.add(n);const n=[...t].slice(0,h);0!==n.length&&d((e=>[...e.slice(-h),n]))}),[u,r,a]),o((()=>{const e=c.listen("*",{},{events:["mutation"],effectFormat:"mendoza",includePreviousRevision:!1,includeResult:!1,tag:"presentation-loader"}).subscribe((e=>{if("mutation"===e.type&&"disappear"===e.transition&&r.delete(e.documentId)&&i(Date.now()),"mutation"!==e.type||!e.effects?.apply?.length)return;const t=r.peek(e.documentId);if(t){const n={...t};delete n._rev;const s=l(n,e.effects.apply);r.set(e.documentId,s),i(Date.now())}}));return()=>e.unsubscribe()}),[r,c,i]),n(t,{children:u.map((e=>n(g,{cache:r,client:c,ids:e,setDocumentsCacheLastUpdated:i},JSON.stringify(e))))})})),g=i((function(e){const{client:t,cache:n,ids:r,setDocumentsCacheLastUpdated:s}=e;return o((()=>{const e=r.filter((e=>!n.has(e)));0!==e.length&&t.getDocuments(e).then((e=>{for(const t of e)t&&t?._id&&(n.set(t._id,t),s(Date.now()))}),console.error)}),[n,t,r,s]),null}));function I(e){const{cache:t,projectId:n,dataset:i,perspective:u,query:d,client:l,refreshInterval:p,liveDocument:f,channel:m,documentsCacheLastUpdated:h}=e,w=function(e){const t=r((()=>JSON.stringify(e||{})),[e]);return r((()=>JSON.parse(t)),[t])}(e.params),y=function(e){const{cache:t,liveDocument:n,client:i,refreshInterval:u,query:d,params:l,perspective:p,documentsCacheLastUpdated:f}=e,[m,h]=s(null),{projectId:w,dataset:y}=r((()=>{const{projectId:e,dataset:t}=i.config();return{projectId:e,dataset:t}}),[i]),[g,I]=s(null);if(g)throw g;const[L,b]=function(e){const{refreshInterval:t}=e,n=function(){const[e,t]=s(!1);o((()=>{t(navigator.onLine);const e=()=>t(!0),n=()=>t(!1);return window.addEventListener("online",e),window.addEventListener("offline",n),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",n)}}),[]);const n=c(v,(()=>document.visibilityState),(()=>"hidden"));return!e||"hidden"===n}(),[r,i]=s("hit"),u=a((()=>(i("inflight"),()=>i("hit"))),[]);return o((()=>{if(!t||"hit"!==r)return;const e=setTimeout((()=>i("stale")),t);return()=>clearTimeout(e)}),[t,r]),o((()=>{if("hit"!==r)return;const e=()=>i("stale");return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)}),[t,r]),o((()=>{n&&"hit"===r&&i("stale"),!n&&"stale"===r&&i("refresh")}),[n,r]),[r,u]}({refreshInterval:u}),D="refresh"===L||"inflight"===L;return o((()=>{if(!D)return;let e=!1,t=!1;const n=new AbortController;async function r(){const{signal:r}=n;t=!0;const{result:s,resultSourceMap:o}=await i.fetch(d,l,{tag:"presentation-loader",signal:r,perspective:p,filterResponse:!1});t=!1,r.aborted||(h({result:s,resultSourceMap:o}),e=!0)}const s=b();return r().catch((e=>{t=!1,"AbortError"!==e.name&&I(e)})).finally(s),()=>{!e&&!t&&n.abort()}}),[i,y,n,l,p,w,d,D,b]),r((()=>f&&m?.resultSourceMap?{result:S(t,n,m.result,p,m.resultSourceMap),resultSourceMap:m.resultSourceMap}:m),[t,f,n,p,m])}({cache:t,client:l,liveDocument:f,params:w,perspective:u,query:d,refreshInterval:p,documentsCacheLastUpdated:h}),g=y?.result,I=y?.resultSourceMap;return o((()=>{I&&m.send("loaders","loader/query-change",{projectId:n,dataset:i,perspective:u,query:d,params:w,result:g,resultSourceMap:I})}),[m,i,w,u,n,d,g,I]),null}g.displayName="GetDocuments";let L=!1;function S(e,t,n,r,s){if("raw"===r)throw new Error("turboChargeResultIfSourceMap does not support raw perspective");return u(n,s,(n=>{if(!n._projectId)return t?._id&&d(t._id)===d(n._id)?t:e.get(n._id);L||(console.warn("Cross dataset references are not supported yet, ignoring source document",n),L=!0)}),((e,{previousValue:t})=>"number"==typeof e&&"string"==typeof t?`${e}`:e),r)}export{w as default,S as turboChargeResultIfSourceMap};//# sourceMappingURL=LoaderQueries.js.map

@@ -1,59 +0,1 @@

import { jsx } from 'react/jsx-runtime';
import { memo, useMemo, useState, useEffect, startTransition } from 'react';
import { getPublishedId, useEditState } from 'sanity';
function PostMessageRefreshMutations(props) {
const { channel, type, previewKitConnection, loadersConnection } = props;
const id = useMemo(() => getPublishedId(props.id), [props.id]);
const { draft, published, ready } = useEditState(id, type, "low");
const livePreviewEnabled = previewKitConnection === "connected" || loadersConnection === "connected";
if (ready && draft || published) {
return /* @__PURE__ */ jsx(
PostMessageRefreshMutationsInner,
{
channel,
draft,
livePreviewEnabled,
published
},
id
);
}
return null;
}
function PostMessageRefreshMutationsInner(props) {
const { channel, draft, published, livePreviewEnabled } = props;
const [prevDraft, setPrevDraft] = useState(draft);
const [prevPublished, setPrevPublished] = useState(published);
useEffect(() => {
if (prevDraft?._rev !== draft?._rev) {
startTransition(() => setPrevDraft(draft));
if (draft) {
channel?.send("overlays", "presentation/refresh", {
source: "mutation",
livePreviewEnabled,
document: parseDocument(draft)
});
}
}
if (prevPublished?._rev !== published?._rev) {
startTransition(() => setPrevPublished(published));
if (published) {
channel?.send("overlays", "presentation/refresh", {
source: "mutation",
livePreviewEnabled,
document: parseDocument(published)
});
}
}
}, [channel, draft, livePreviewEnabled, prevDraft?._rev, prevPublished?._rev, published]);
return null;
}
function parseDocument(document) {
const { _id, _type, _rev, slug } = document;
return { _id, _type, _rev, slug };
}
var PostMessageRefreshMutations$1 = memo(PostMessageRefreshMutations);
export { PostMessageRefreshMutations$1 as default };
//# sourceMappingURL=PostMessageRefreshMutations.js.map
import{jsx as e}from"react/jsx-runtime";import{memo as n,useMemo as r,useState as t,useEffect as i,startTransition as o}from"react";import{getPublishedId as l,useEditState as a}from"sanity";function d(e){const{channel:n,draft:r,published:l,livePreviewEnabled:a}=e,[d,c]=t(r),[u,v]=t(l);return i((()=>{d?._rev!==r?._rev&&(o((()=>c(r))),r&&n?.send("overlays","presentation/refresh",{source:"mutation",livePreviewEnabled:a,document:s(r)})),u?._rev!==l?._rev&&(o((()=>v(l))),l&&n?.send("overlays","presentation/refresh",{source:"mutation",livePreviewEnabled:a,document:s(l)}))}),[n,r,a,d?._rev,u?._rev,l]),null}function s(e){const{_id:n,_type:r,_rev:t,slug:i}=e;return{_id:n,_type:r,_rev:t,slug:i}}var c=n((function(n){const{channel:t,type:i,previewKitConnection:o,loadersConnection:s}=n,c=r((()=>l(n.id)),[n.id]),{draft:u,published:v,ready:p}=a(c,i,"low");return p&&u||v?e(d,{channel:t,draft:u,livePreviewEnabled:"connected"===o||"connected"===s,published:v},c):null}));export{c as default};//# sourceMappingURL=PostMessageRefreshMutations.js.map

@@ -1,101 +0,1 @@

var resources = {
/** The title shown above the document list */
"document-list-pane.document-list.title": "Documents on this page",
/** The text shown if the document list is unable to render */
"document-list-pane.error.text": "Could not render the document list",
/** The status of the channel connection */
"channel.status_connected": "Connected",
/** The status of the channel connection */
"channel.status_connecting": "Connecting",
/** The status of the channel connection */
"channel.status_disconnected": "Disconnected",
/** The status of the channel connection */
"channel.status_reconnecting": "Reconnecting",
/** The text shown if the document editor is unable to render */
"document-pane.error.text": "Could not render the document editor",
/** The text shown on the button for bypassing after a connection has failed */
"error-card.continue-button.text": "Continue anyway",
/** The text shown on the button for retrying after a connection has failed */
"error-card.retry-button.text": "Retry",
/** The title on the card shown after a connection has failed */
"error-card.title": "An error occurred",
/** The text shown when the document is used in a single location */
"locations-banner.locations-count_one": "Used on one page",
/** The text shown when the document is used in multiple locations */
"locations-banner.locations-count_other": "Used on {{count}} pages",
/** The text shown when a resolver exists but the document is not used in any locations */
"locations-banner.locations-count_zero": "Not used on any pages",
/** The text shown whilst the locations resolver is executing */
"locations-banner.resolving.text": "Resolving locations...",
/** The label shown on a main document in the list pane */
"main-document.label": "Main document",
/** The warning message text shown when a defined resolver fails to return a main document */
"main-document.missing.text": "Missing a main document for <Code>{{path}}</Code>",
/** The label for a generic error message */
"presentation-error.label": "Error message",
/** The text shown when the preview frame cannot connect to Presentation */
"preview-frame.connection.error.text": "Could not connect to the preview",
/** The text shown on the button for dismissing the error overlay after a timeout */
"preview-frame.continue-button.text": "Continue anyway",
/** The label for the loader's connection status */
"preview-frame.loader.connection-status.label": "Loader connection status",
/** The `aria-label` for the navigator toggle button */
"preview-frame.navigator.toggle-button.aria-label": "Toggle navigator",
/** The tooltip text for the navigator toggle button */
"preview-frame.navigator.toggle-button.tooltip": "Toggle navigator",
/** The label for the overlay's connection status */
"preview-frame.overlay.connection-status.label": "Overlay connection status",
/** The text shown on the overlay toggle button */
"preview-frame.overlay.toggle-button.text": "Edit",
/** The text shown on the overlay toggle tooltip when overlays are enabled */
"preview-frame.overlay.toggle-button.tooltip_disable": "Disable edit overlay",
/** The text shown on the overlay toggle tooltip when overlays are disabled */
"preview-frame.overlay.toggle-button.tooltip_enable": "Enable edit overlay",
/** The text description for the previewDrafts perspective switcher menu item */
"preview-frame.perspective.previewDrafts.text": "View this page with latest draft content",
/** The title for the previewDrafts perspective switcher menu item */
"preview-frame.perspective.previewDrafts.title": "Drafts",
/** The text description for the published perspective switcher menu item */
"preview-frame.perspective.published.text": "View this page with published content",
/** The title for the published perspective switcher menu item */
"preview-frame.perspective.published.title": "Published",
/** The `aria-label` for the refresh button */
"preview-frame.refresh-button.aria-label": "Refresh preview",
/** The tooltip text for the refresh button */
"preview-frame.refresh-button.tooltip": "Refresh preview",
/** Text describing the current status of the preview frame */
"preview-frame.status_connecting": "Connecting.",
/** Text describing the current status of the preview frame */
"preview-frame.status_loading": "Loading.",
/** Text describing the current status of the preview frame */
"preview-frame.status_refreshing": "Refreshing.",
/** Text describing the current status of the preview frame */
"preview-frame.status_reloading": "Refreshing.",
/** Text describing the current status of the preview frame */
"preview-frame.status_timeout": "Unable to connect, check the browser console for more information.",
/** The `aria-label` for the button that switches viewport size */
"preview-frame.viewport-button.aria-label": "Toggle viewport size",
/** The viewport size button tooltip text when switching to a full width viewport */
"preview-frame.viewport-button.tooltip_full": "Switch to full viewport",
/** The viewport size button tooltip text when switching to a narrow viewport */
"preview-frame.viewport-button.tooltip_narrow": "Switch to narrow viewport",
/** The validation error message shown when the preview location input is missing an origin */
"preview-location-input.error_missing-origin": "URL must start with ${{origin}}",
/** The validation error message shown when the preview location input's base path matches that of the studio */
"preview-location-input.error_same-base-path": "URL can\u2019t have the same base path as the Studio {{basePath}}",
/** The status of the clipboard operation when copying a URL */
"share-url.clipboard.status_copying": "Copying URL to clipboard\u2026",
/** The status of the clipboard operation when copying a URL */
"share-url.clipboard.status_failed": "Copy failed",
/** The status of the clipboard operation when copying a URL */
"share-url.clipboard.status_success": "The URL is copied to the clipboard",
/** The status of the clipboard operation when copying a URL */
"share-url.clipboard.status_unsupported": "Clipboard not supported",
/** The share URL menu item text for copying a link */
"share-url.menu-item.copy.text": "Copy link",
/** The share URL menu item text for opening a preview window */
"share-url.menu-item.open.text": "Open preview"
};
export { resources as default };
//# sourceMappingURL=resources.js.map
var e={"document-list-pane.document-list.title":"Documents on this page","document-list-pane.error.text":"Could not render the document list","channel.status_connected":"Connected","channel.status_connecting":"Connecting","channel.status_disconnected":"Disconnected","channel.status_reconnecting":"Reconnecting","document-pane.error.text":"Could not render the document editor","error-card.continue-button.text":"Continue anyway","error-card.retry-button.text":"Retry","error-card.title":"An error occurred","locations-banner.locations-count_one":"Used on one page","locations-banner.locations-count_other":"Used on {{count}} pages","locations-banner.locations-count_zero":"Not used on any pages","locations-banner.resolving.text":"Resolving locations...","main-document.label":"Main document","main-document.missing.text":"Missing a main document for <Code>{{path}}</Code>","presentation-error.label":"Error message","preview-frame.connection.error.text":"Could not connect to the preview","preview-frame.continue-button.text":"Continue anyway","preview-frame.loader.connection-status.label":"Loader connection status","preview-frame.navigator.toggle-button.aria-label":"Toggle navigator","preview-frame.navigator.toggle-button.tooltip":"Toggle navigator","preview-frame.overlay.connection-status.label":"Overlay connection status","preview-frame.overlay.toggle-button.text":"Edit","preview-frame.overlay.toggle-button.tooltip_disable":"Disable edit overlay","preview-frame.overlay.toggle-button.tooltip_enable":"Enable edit overlay","preview-frame.perspective.previewDrafts.text":"View this page with latest draft content","preview-frame.perspective.previewDrafts.title":"Drafts","preview-frame.perspective.published.text":"View this page with published content","preview-frame.perspective.published.title":"Published","preview-frame.refresh-button.aria-label":"Refresh preview","preview-frame.refresh-button.tooltip":"Refresh preview","preview-frame.status_connecting":"Connecting.","preview-frame.status_loading":"Loading.","preview-frame.status_refreshing":"Refreshing.","preview-frame.status_reloading":"Refreshing.","preview-frame.status_timeout":"Unable to connect, check the browser console for more information.","preview-frame.viewport-button.aria-label":"Toggle viewport size","preview-frame.viewport-button.tooltip_full":"Switch to full viewport","preview-frame.viewport-button.tooltip_narrow":"Switch to narrow viewport","preview-location-input.error_missing-origin":"URL must start with ${{origin}}","preview-location-input.error_same-base-path":"URL can’t have the same base path as the Studio {{basePath}}","share-url.clipboard.status_copying":"Copying URL to clipboard…","share-url.clipboard.status_failed":"Copy failed","share-url.clipboard.status_success":"The URL is copied to the clipboard","share-url.clipboard.status_unsupported":"Clipboard not supported","share-url.menu-item.copy.text":"Copy link","share-url.menu-item.open.text":"Open preview"};export{e as default};//# sourceMappingURL=resources.js.map

3

dist/index.js

@@ -1,2 +0,1 @@

export { defineDocuments, defineLocations, presentationTool, usePresentationNavigate, usePresentationParams } from './_chunks-es/index.js';
//# sourceMappingURL=index.js.map
import{h as e,g as s,i as a,f as n,d as o}from"./_chunks-es/index.js";export{e as defineDocuments,s as defineLocations,a as presentationTool,n as usePresentationNavigate,o as usePresentationParams};//# sourceMappingURL=index.js.map
{
"name": "@sanity/presentation",
"version": "1.16.4-canary.1",
"version": "1.16.4-canary.3",
"homepage": "https://github.com/sanity-io/visual-editing/tree/main/packages/presentation#readme",

@@ -106,3 +106,3 @@ "bugs": {

"suspend-react": "0.1.3",
"@sanity/preview-url-secret": "^1.6.20-canary.1"
"@sanity/preview-url-secret": "^1.6.20-canary.3"
},

@@ -121,4 +121,4 @@ "devDependencies": {

"@repo/channels": "0.4.0",
"@repo/visual-editing-helpers": "0.6.20",
"@repo/package.config": "0.0.0"
"@repo/package.config": "0.0.0",
"@repo/visual-editing-helpers": "0.6.20"
},

@@ -125,0 +125,0 @@ "peerDependencies": {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc