@sanity/presentation
Advanced tools
Comparing version 1.18.5 to 1.19.0
@@ -0,1 +1,2 @@ | ||
import { c } from "react-compiler-runtime"; | ||
import { memo, useEffect } from "react"; | ||
@@ -5,7 +6,11 @@ import { usePresentationParams } from "./index.js"; | ||
function BroadcastDisplayedDocument(props) { | ||
const setDisplayedDocument = useDisplayedDocumentBroadcaster(), params = usePresentationParams(!1); | ||
return useEffect(() => { | ||
const $ = c(7), setDisplayedDocument = useDisplayedDocumentBroadcaster(), params = usePresentationParams(!1); | ||
let t0; | ||
$[0] !== props.value || $[1] !== setDisplayedDocument ? (t0 = () => { | ||
const timeout = setTimeout(() => setDisplayedDocument?.(props.value), 10); | ||
return () => clearTimeout(timeout); | ||
}, [params?.perspective, props.value, setDisplayedDocument]), null; | ||
}, $[0] = props.value, $[1] = setDisplayedDocument, $[2] = t0) : t0 = $[2]; | ||
const t1 = params?.perspective; | ||
let t2; | ||
return $[3] !== props.value || $[4] !== setDisplayedDocument || $[5] !== t1 ? (t2 = [t1, props.value, setDisplayedDocument], $[3] = props.value, $[4] = setDisplayedDocument, $[5] = t1, $[6] = t2) : t2 = $[6], useEffect(t0, t2), null; | ||
} | ||
@@ -12,0 +17,0 @@ var BroadcastDisplayedDocument$1 = memo(BroadcastDisplayedDocument); |
import { jsx } from "react/jsx-runtime"; | ||
import { c } from "react-compiler-runtime"; | ||
import isEqual from "fast-deep-equal"; | ||
import { createContext, useContext, useCallback, useEffect } from "react"; | ||
import { createContext, useContext, useEffect } from "react"; | ||
const Context = createContext(null); | ||
function DisplayedDocumentBroadcasterProvider(props) { | ||
const { children, setDisplayedDocument, documentId } = props, context = useCallback( | ||
(next) => setDisplayedDocument((prev) => isEqual(prev, next) ? prev : next), | ||
[setDisplayedDocument] | ||
); | ||
return useEffect(() => { | ||
const $ = c(9), { | ||
children, | ||
setDisplayedDocument, | ||
documentId | ||
} = props; | ||
let t0; | ||
$[0] !== setDisplayedDocument ? (t0 = (next) => setDisplayedDocument((prev) => isEqual(prev, next) ? prev : next), $[0] = setDisplayedDocument, $[1] = t0) : t0 = $[1]; | ||
const context = t0; | ||
let t1, t2; | ||
$[2] !== documentId || $[3] !== setDisplayedDocument ? (t1 = () => { | ||
if (documentId) | ||
@@ -15,3 +21,5 @@ return; | ||
return () => clearTimeout(timeout); | ||
}, [documentId, setDisplayedDocument]), /* @__PURE__ */ jsx(Context.Provider, { value: context, children }); | ||
}, t2 = [documentId, setDisplayedDocument], $[2] = documentId, $[3] = setDisplayedDocument, $[4] = t1, $[5] = t2) : (t1 = $[4], t2 = $[5]), useEffect(t1, t2); | ||
let t3; | ||
return $[6] !== children || $[7] !== context ? (t3 = /* @__PURE__ */ jsx(Context.Provider, { value: context, children }), $[6] = children, $[7] = context, $[8] = t3) : t3 = $[8], t3; | ||
} | ||
@@ -18,0 +26,0 @@ function useDisplayedDocumentBroadcaster() { |
@@ -0,1 +1,2 @@ | ||
import { c } from "react-compiler-runtime"; | ||
import { useMemo, useState, useCallback, useEffect, useSyncExternalStore } from "react"; | ||
@@ -7,11 +8,11 @@ function useQueryParams(params) { | ||
function useRevalidate(props) { | ||
const { refreshInterval } = props, shouldPause = useShouldPause(), [state, setState] = useState("hit"), startRefresh = useCallback(() => (setState("inflight"), () => setState("hit")), []); | ||
const { | ||
refreshInterval | ||
} = props, shouldPause = useShouldPause(), [state, setState] = useState("hit"), startRefresh = useCallback(() => (setState("inflight"), () => setState("hit")), []); | ||
return useEffect(() => { | ||
if (!refreshInterval || state !== "hit") | ||
return; | ||
if (!refreshInterval || state !== "hit") return; | ||
const timeout = setTimeout(() => setState("stale"), refreshInterval); | ||
return () => clearTimeout(timeout); | ||
}, [refreshInterval, state]), useEffect(() => { | ||
if (state !== "hit") | ||
return; | ||
if (state !== "hit") return; | ||
const onFocus = () => setState("stale"); | ||
@@ -24,4 +25,5 @@ return window.addEventListener("focus", onFocus), () => window.removeEventListener("focus", onFocus); | ||
function useShouldPause() { | ||
const [online, setOnline] = useState(!1); | ||
useEffect(() => { | ||
const $ = c(2), [online, setOnline] = useState(!1); | ||
let t0, t1; | ||
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = () => { | ||
setOnline(navigator.onLine); | ||
@@ -32,10 +34,12 @@ const online2 = () => setOnline(!0), offline = () => setOnline(!1); | ||
}; | ||
}, []); | ||
const visibilityState = useSyncExternalStore( | ||
onVisibilityChange, | ||
() => document.visibilityState, | ||
() => "hidden" | ||
); | ||
}, t1 = [], $[0] = t0, $[1] = t1) : (t0 = $[0], t1 = $[1]), useEffect(t0, t1); | ||
const visibilityState = useSyncExternalStore(onVisibilityChange, _temp, _temp2); | ||
return !online || visibilityState === "hidden"; | ||
} | ||
function _temp2() { | ||
return "hidden"; | ||
} | ||
function _temp() { | ||
return document.visibilityState; | ||
} | ||
function onVisibilityChange(onStoreChange) { | ||
@@ -42,0 +46,0 @@ return document.addEventListener("visibilitychange", onStoreChange), () => document.removeEventListener("visibilitychange", onStoreChange); |
import { jsx, jsxs, Fragment } from "react/jsx-runtime"; | ||
import { useState, useMemo, useEffect, createContext, useContext, useCallback, createElement, useRef, useLayoutEffect, lazy, Suspense } from "react"; | ||
import { c } from "react-compiler-runtime"; | ||
import { useState, useEffect, createContext, useContext, useCallback, createElement, useLayoutEffect, useMemo, 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 { ComposeIcon, InfoOutlineIcon, ChevronRightIcon, WarningOutlineIcon, ErrorOutlineIcon, DesktopIcon, MasterDetailIcon } from "@sanity/icons"; | ||
import { Card, Flex, Box, Text, Spinner, Stack, rem } from "@sanity/ui"; | ||
@@ -10,2 +11,3 @@ import { styled } from "styled-components"; | ||
import { useIntentLink, useRouter, encodeJsonParams, route } from "sanity/router"; | ||
import { useEffectEvent } from "use-effect-event"; | ||
import { uuid } from "@sanity/uuid"; | ||
@@ -23,18 +25,13 @@ const DEFAULT_TOOL_ICON = ComposeIcon, DEFAULT_TOOL_NAME = "presentation", DEFAULT_TOOL_TITLE = "Presentation", COMMENTS_INSPECTOR_NAME = "sanity/structure/comments", EDIT_INTENT_MODE = "presentation", MAX_TIME_TO_OVERLAYS_CONNECTION = 3e3, API_VERSION = "2023-10-16", MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL = 1e3, LIVE_QUERY_CACHE_BATCH_SIZE = 100, LIVE_QUERY_CACHE_SIZE = 2048, POPUP_CHECK_INTERVAL = 1e3; | ||
function props(options = {}) { | ||
return (source) => new Observable((observer) => source.subscribe(observer)).pipe( | ||
switchMap((object2) => { | ||
const keyObservables = keysOf(object2).map((key) => { | ||
const value = object2[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), {}) | ||
); | ||
}) | ||
); | ||
return (source) => new Observable((observer) => source.subscribe(observer)).pipe(switchMap((object2) => { | ||
const keyObservables = keysOf(object2).map((key) => { | ||
const value = object2[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: [] }; | ||
const INITIAL_STATE = { | ||
locations: [] | ||
}; | ||
function getDocumentId(value) { | ||
@@ -44,7 +41,14 @@ return isReference(value) ? value._ref : "_id" in value ? value._id : void 0; | ||
function cleanPreviewable(id, previewable) { | ||
const clean = id ? { ...previewable, _id: id } : { ...previewable }; | ||
const clean = id ? { | ||
...previewable, | ||
_id: id | ||
} : { | ||
...previewable | ||
}; | ||
return clean._type === "reference" && (delete clean._type, delete clean._ref, delete clean._weak, delete clean._dataset, delete clean._projectId, delete clean._strengthenOnPublish), clean; | ||
} | ||
function listen(id, fields, store5) { | ||
const query = `*[_id==$id][0]{${fields.join(", ")}}`, params = { id }; | ||
const query = `*[_id==$id][0]{${fields.join(", ")}}`, params = { | ||
id | ||
}; | ||
return store5.listenQuery(query, params, { | ||
@@ -60,5 +64,3 @@ perspective: "previewDrafts" | ||
const fields = [...new Set(headlessPaths.map((path) => path[0]))]; | ||
return listen(id, fields, store5).pipe( | ||
switchMap((snapshot) => snapshot ? observeDocument(snapshot, paths, store5) : of(null)) | ||
); | ||
return listen(id, fields, store5).pipe(switchMap((snapshot) => snapshot ? observeDocument(snapshot, paths, store5) : of(null))); | ||
} | ||
@@ -74,24 +76,53 @@ const leads = {}; | ||
}, currentValue); | ||
return of(next).pipe(props({ wait: !0 })); | ||
return of(next).pipe(props({ | ||
wait: !0 | ||
})); | ||
} | ||
function observeForLocations(documentId, resolver, documentStore) { | ||
const { select } = resolver, paths = Object.values(select).map((value) => String(value).split(".")) || []; | ||
return observeDocument({ _type: "reference", _ref: documentId }, paths, documentStore).pipe( | ||
map((doc2) => Object.keys(select).reduce((acc, key) => (acc[key] = get(doc2, select[key]), acc), {})), | ||
map(resolver.resolve) | ||
); | ||
const { | ||
select | ||
} = resolver, paths = Object.values(select).map((value) => String(value).split(".")) || []; | ||
return observeDocument({ | ||
_type: "reference", | ||
_ref: documentId | ||
}, paths, documentStore).pipe(map((doc2) => Object.keys(select).reduce((acc, key) => (acc[key] = get(doc2, select[key]), acc), {})), map(resolver.resolve)); | ||
} | ||
function useDocumentLocations(props2) { | ||
const { id, resolvers, type } = props2, documentStore = useDocumentStore(), [locationsState, setLocationsState] = useState(INITIAL_STATE), resolver = resolvers && (typeof resolvers == "function" ? resolvers : resolvers[type]), [locationsStatus, setLocationsStatus] = useState( | ||
resolver ? "resolving" : "empty" | ||
), result = useMemo(() => { | ||
if (resolver) { | ||
if (typeof resolver == "function") { | ||
const _result = resolver({ id, type }, { documentStore }); | ||
return isObservable(_result) ? _result : of(_result); | ||
} | ||
return "select" in resolver && "resolve" in resolver ? observeForLocations(id, resolver, documentStore) : of(resolver); | ||
const $ = c(17), { | ||
id, | ||
resolvers, | ||
type | ||
} = props2, documentStore = useDocumentStore(), [locationsState, setLocationsState] = useState(INITIAL_STATE), resolver = resolvers && (typeof resolvers == "function" ? resolvers : resolvers[type]), [locationsStatus, setLocationsStatus] = useState(resolver ? "resolving" : "empty"); | ||
let t0; | ||
bb0: { | ||
if (!resolver) { | ||
t0 = void 0; | ||
break bb0; | ||
} | ||
}, [documentStore, id, resolver, type]); | ||
return useEffect(() => { | ||
if (typeof resolver == "function") { | ||
let t13; | ||
if ($[0] !== documentStore || $[1] !== id || $[2] !== resolver || $[3] !== type) { | ||
const _result = resolver({ | ||
id, | ||
type | ||
}, { | ||
documentStore | ||
}); | ||
t13 = isObservable(_result) ? _result : of(_result), $[0] = documentStore, $[1] = id, $[2] = resolver, $[3] = type, $[4] = t13; | ||
} else | ||
t13 = $[4]; | ||
t0 = t13; | ||
break bb0; | ||
} | ||
if ("select" in resolver && "resolve" in resolver) { | ||
let t13; | ||
$[5] !== documentStore || $[6] !== id || $[7] !== resolver ? (t13 = observeForLocations(id, resolver, documentStore), $[5] = documentStore, $[6] = id, $[7] = resolver, $[8] = t13) : t13 = $[8], t0 = t13; | ||
break bb0; | ||
} | ||
let t12; | ||
$[9] !== resolver ? (t12 = of(resolver), $[9] = resolver, $[10] = t12) : t12 = $[10], t0 = t12; | ||
} | ||
const result = t0; | ||
let t1, t2; | ||
$[11] !== result ? (t1 = () => { | ||
const sub = result?.subscribe((state) => { | ||
@@ -101,6 +132,8 @@ setLocationsState(state || INITIAL_STATE), setLocationsStatus(state ? "resolved" : "empty"); | ||
return () => sub?.unsubscribe(); | ||
}, [result]), { | ||
}, t2 = [result], $[11] = result, $[12] = t1, $[13] = t2) : (t1 = $[12], t2 = $[13]), useEffect(t1, t2); | ||
let t3; | ||
return $[14] !== locationsState || $[15] !== locationsStatus ? (t3 = { | ||
state: locationsState, | ||
status: locationsStatus | ||
}; | ||
}, $[14] = locationsState, $[15] = locationsStatus, $[16] = t3) : t3 = $[16], t3; | ||
} | ||
@@ -112,5 +145,5 @@ const presentationLocaleNamespace = "presentation", presentationUsEnglishLocaleBundle = defineLocaleResourceBundle({ | ||
}), PresentationContext = createContext(null); | ||
function usePresentationTool() { | ||
const presentation = useContext(PresentationContext); | ||
if (!presentation) | ||
function usePresentationTool(t0) { | ||
const throwOnMissingContext = t0 === void 0 ? !0 : t0, presentation = useContext(PresentationContext); | ||
if (throwOnMissingContext && !presentation) | ||
throw new Error("Presentation context is missing"); | ||
@@ -120,7 +153,3 @@ return presentation; | ||
function useCurrentPresentationToolName() { | ||
try { | ||
return usePresentationTool().name; | ||
} catch { | ||
return; | ||
} | ||
return usePresentationTool(!1)?.name ?? void 0; | ||
} | ||
@@ -133,6 +162,22 @@ const TONE_ICONS = { | ||
function LocationsBanner(props2) { | ||
const { documentId, isResolving, options, schemaType, showPresentationTitle } = props2, { locations, message, tone } = props2.state, len = locations?.length || 0, { t } = useTranslation(presentationLocaleNamespace), presentation = useContext(PresentationContext), [expanded, setExpanded] = useState(!1), toggle = useCallback(() => { | ||
const { | ||
documentId, | ||
isResolving, | ||
options, | ||
schemaType, | ||
showPresentationTitle | ||
} = props2, { | ||
locations, | ||
message, | ||
tone | ||
} = props2.state, len = locations?.length || 0, { | ||
t | ||
} = useTranslation(presentationLocaleNamespace), presentation = useContext(PresentationContext), [expanded, setExpanded] = useState(!1), toggle = useCallback(() => { | ||
len && setExpanded((v) => !v); | ||
}, [len]), title = isResolving ? t("locations-banner.resolving.text") : message || t("locations-banner.locations-count", { count: len }); | ||
return /* @__PURE__ */ jsx(Card, { padding: 1, radius: 2, border: !0, tone, children: /* @__PURE__ */ jsxs("div", { style: { margin: -1 }, children: [ | ||
}, [len]), title = isResolving ? t("locations-banner.resolving.text") : message || t("locations-banner.locations-count", { | ||
count: len | ||
}); | ||
return /* @__PURE__ */ jsx(Card, { padding: 1, radius: 2, border: !0, tone, children: /* @__PURE__ */ jsxs("div", { style: { | ||
margin: -1 | ||
}, children: [ | ||
!locations && /* @__PURE__ */ jsxs(Flex, { align: "flex-start", gap: 3, padding: 3, children: [ | ||
@@ -149,41 +194,16 @@ tone && /* @__PURE__ */ jsx(Box, { flex: "none", children: /* @__PURE__ */ jsx(Text, { size: 1, children: createElement(TONE_ICONS[tone]) }) }), | ||
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 | ||
)) }) | ||
/* @__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)) }) | ||
] }) | ||
@@ -193,3 +213,11 @@ ] }) }); | ||
function LocationItem(props2) { | ||
const { documentId, documentType, node, active, toolName } = props2, presentation = useContext(PresentationContext), currentPresentationToolName = useCurrentPresentationToolName(), isCurrentTool = toolName === currentPresentationToolName, navigate = presentation?.navigate, presentationLinkProps = useIntentLink({ | ||
const $ = c(26), { | ||
documentId, | ||
documentType, | ||
node, | ||
active, | ||
toolName | ||
} = props2, presentation = useContext(PresentationContext), currentPresentationToolName = useCurrentPresentationToolName(), isCurrentTool = toolName === currentPresentationToolName, navigate = presentation?.navigate, t0 = presentation?.structureParams; | ||
let t1; | ||
$[0] !== documentId || $[1] !== documentType || $[2] !== node.href || $[3] !== t0 || $[4] !== toolName ? (t1 = { | ||
intent: "edit", | ||
@@ -201,32 +229,35 @@ params: { | ||
presentation: toolName, | ||
...presentation?.structureParams, | ||
...t0, | ||
preview: node.href | ||
} | ||
}), 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: !0, size: 1, textOverflow: "ellipsis", children: node.href }) | ||
] }) | ||
}, $[0] = documentId, $[1] = documentType, $[2] = node.href, $[3] = t0, $[4] = toolName, $[5] = t1) : t1 = $[5]; | ||
const presentationLinkProps = useIntentLink(t1); | ||
let t2; | ||
$[6] !== navigate || $[7] !== node.href ? (t2 = () => { | ||
navigate?.({}, { | ||
preview: node.href | ||
}); | ||
}, $[6] = navigate, $[7] = node.href, $[8] = t2) : t2 = $[8]; | ||
const handleCurrentToolClick = t2; | ||
let t3; | ||
$[9] !== isCurrentTool || $[10] !== presentationLinkProps ? (t3 = isCurrentTool ? {} : presentationLinkProps, $[9] = isCurrentTool, $[10] = presentationLinkProps, $[11] = t3) : t3 = $[11]; | ||
const t4 = isCurrentTool ? handleCurrentToolClick : presentationLinkProps.onClick; | ||
let t5; | ||
$[12] === Symbol.for("react.memo_cache_sentinel") ? (t5 = /* @__PURE__ */ jsx(Box, { flex: "none", children: /* @__PURE__ */ jsx(Text, { size: 1, children: /* @__PURE__ */ jsx(DesktopIcon, {}) }) }), $[12] = t5) : t5 = $[12]; | ||
let t6; | ||
$[13] !== node.title ? (t6 = /* @__PURE__ */ jsx(Text, { size: 1, weight: "medium", children: node.title }), $[13] = node.title, $[14] = t6) : t6 = $[14]; | ||
let t7; | ||
$[15] !== node.href ? (t7 = /* @__PURE__ */ jsx(Text, { muted: !0, size: 1, textOverflow: "ellipsis", children: node.href }), $[15] = node.href, $[16] = t7) : t7 = $[16]; | ||
let t8; | ||
$[17] !== t6 || $[18] !== t7 ? (t8 = /* @__PURE__ */ jsxs(Flex, { gap: 3, children: [ | ||
t5, | ||
/* @__PURE__ */ jsxs(Stack, { flex: 1, space: 2, children: [ | ||
t6, | ||
t7 | ||
] }) | ||
); | ||
] }), $[17] = t6, $[18] = t7, $[19] = t8) : t8 = $[19]; | ||
let t9; | ||
return $[20] !== active || $[21] !== node.href || $[22] !== t3 || $[23] !== t4 || $[24] !== t8 ? (t9 = /* @__PURE__ */ createElement(Card, { ...t3, as: "a", key: node.href, onClick: t4, padding: 3, radius: 1, pressed: active, tone: "inherit" }, t8), $[20] = active, $[21] = node.href, $[22] = t3, $[23] = t4, $[24] = t8, $[25] = t9) : t9 = $[25], t9; | ||
} | ||
const PresentationDocumentContext = createContext( | ||
null | ||
), LocationStack = styled(Stack)` | ||
const PresentationDocumentContext = createContext(null), LocationStack = styled(Stack)` | ||
min-height: ${rem(42)}; | ||
@@ -239,47 +270,70 @@ | ||
function PresentationDocumentHeader(props2) { | ||
const { documentId, options, schemaType } = props2, context = useContext(PresentationDocumentContext), { state, status } = useDocumentLocations({ | ||
const $ = c(20), { | ||
documentId, | ||
options, | ||
schemaType | ||
} = props2, context = useContext(PresentationDocumentContext), t0 = options.resolve?.locations || options.locate; | ||
let t1; | ||
$[0] !== documentId || $[1] !== schemaType.name || $[2] !== t0 ? (t1 = { | ||
id: documentId, | ||
resolvers: options.resolve?.locations || options.locate, | ||
resolvers: t0, | ||
type: schemaType.name | ||
}); | ||
}, $[0] = documentId, $[1] = schemaType.name, $[2] = t0, $[3] = t1) : t1 = $[3]; | ||
const { | ||
state, | ||
status | ||
} = useDocumentLocations(t1); | ||
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 | ||
)) }) }); | ||
let t2; | ||
$[4] !== context?.options ? (t2 = context?.options || [], $[4] = context?.options, $[5] = t2) : t2 = $[5]; | ||
const contextOptions = t2; | ||
let t3; | ||
if ($[6] !== contextOptions || $[7] !== documentId || $[8] !== schemaType || $[9] !== state || $[10] !== status) { | ||
let t42; | ||
$[12] !== contextOptions.length || $[13] !== documentId || $[14] !== schemaType || $[15] !== state || $[16] !== status ? (t42 = (options_0, idx) => /* @__PURE__ */ jsx(LocationsBanner, { documentId, isResolving: status === "resolving", options: options_0, schemaType, showPresentationTitle: contextOptions.length > 1, state }, idx), $[12] = contextOptions.length, $[13] = documentId, $[14] = schemaType, $[15] = state, $[16] = status, $[17] = t42) : t42 = $[17], t3 = contextOptions.map(t42), $[6] = contextOptions, $[7] = documentId, $[8] = schemaType, $[9] = state, $[10] = status, $[11] = t3; | ||
} else | ||
t3 = $[11]; | ||
let t4; | ||
return $[18] !== t3 ? (t4 = /* @__PURE__ */ jsx(LocationStack, { marginBottom: 5, space: 5, children: /* @__PURE__ */ jsx(Stack, { space: 2, children: t3 }) }), $[18] = t3, $[19] = t4) : t4 = $[19], t4; | ||
} | ||
function PresentationDocumentProvider(props2) { | ||
const { children, options } = props2, parent = useContext(PresentationDocumentContext), parentRegister = parent?.register, [optionsArray, setOptionsArray] = useState(() => []), register = useCallback( | ||
(options2) => parentRegister ? parentRegister(options2) : (setOptionsArray((prev) => [options2].concat(prev)), () => { | ||
setOptionsArray((prev) => prev.filter((o) => o !== options2)); | ||
}), | ||
[parentRegister] | ||
), registerRef = useRef(register); | ||
registerRef.current = register; | ||
const context = useMemo( | ||
() => ({ | ||
options: parent?.options || optionsArray, | ||
register | ||
}), | ||
[optionsArray, parent, register] | ||
); | ||
return useLayoutEffect(() => registerRef.current(options), [options]), /* @__PURE__ */ jsx(PresentationDocumentContext.Provider, { value: context, children }); | ||
const $ = c(14), { | ||
children, | ||
options | ||
} = props2, parent = useContext(PresentationDocumentContext), parentRegister = parent?.register, [optionsArray, setOptionsArray] = useState(_temp); | ||
let t0; | ||
$[0] !== parentRegister ? (t0 = (options_0) => parentRegister ? parentRegister(options_0) : (setOptionsArray((prev) => [options_0].concat(prev)), () => { | ||
setOptionsArray((prev_0) => prev_0.filter((o) => o !== options_0)); | ||
}), $[0] = parentRegister, $[1] = t0) : t0 = $[1]; | ||
const register = t0; | ||
let t1; | ||
const t2 = parent?.options || optionsArray; | ||
let t3; | ||
$[2] !== register || $[3] !== t2 ? (t3 = { | ||
options: t2, | ||
register | ||
}, $[2] = register, $[3] = t2, $[4] = t3) : t3 = $[4], t1 = t3; | ||
const context = t1; | ||
let t4; | ||
$[5] !== register ? (t4 = (options_1) => register(options_1), $[5] = register, $[6] = t4) : t4 = $[6]; | ||
const registerEffectEvent = useEffectEvent(t4); | ||
let t5, t6; | ||
$[7] !== options || $[8] !== registerEffectEvent ? (t5 = () => registerEffectEvent(options), t6 = [registerEffectEvent, options], $[7] = options, $[8] = registerEffectEvent, $[9] = t5, $[10] = t6) : (t5 = $[9], t6 = $[10]), useLayoutEffect(t5, t6); | ||
let t7; | ||
return $[11] !== children || $[12] !== context ? (t7 = /* @__PURE__ */ jsx(PresentationDocumentContext.Provider, { value: context, children }), $[11] = children, $[12] = context, $[13] = t7) : t7 = $[13], t7; | ||
} | ||
function _temp() { | ||
return []; | ||
} | ||
const openInStructure = defineDocumentFieldAction({ | ||
name: "presentation/openInStructure", | ||
useAction({ documentId, documentType, path }) { | ||
const workspace = useWorkspace(), { navigateIntent } = useRouter(), presentation = useContext(PresentationContext), defaultStructureTool = useMemo( | ||
() => findStructureTool(workspace.tools, documentId, documentType), | ||
[documentId, documentType, workspace.tools] | ||
); | ||
useAction({ | ||
documentId, | ||
documentType, | ||
path | ||
}) { | ||
const workspace = useWorkspace(), { | ||
navigateIntent | ||
} = useRouter(), presentation = useContext(PresentationContext), defaultStructureTool = useMemo(() => findStructureTool(workspace.tools, documentId, documentType), [documentId, documentType, workspace.tools]); | ||
return { | ||
@@ -304,24 +358,29 @@ type: "action", | ||
const results = tools.map((t) => { | ||
const match = t.canHandleIntent?.( | ||
"edit", | ||
{ | ||
id: documentId, | ||
type: documentType, | ||
mode: "structure" | ||
}, | ||
{} | ||
); | ||
return { tool: t, match }; | ||
const match = t.canHandleIntent?.("edit", { | ||
id: documentId, | ||
type: documentType, | ||
mode: "structure" | ||
}, {}); | ||
return { | ||
tool: t, | ||
match | ||
}; | ||
}), modeMatches = results.filter((t) => isRecord(t.match) && t.match.mode); | ||
return modeMatches.length > 0 ? modeMatches[0].tool : results.filter((t) => t.match)[0]?.tool; | ||
} | ||
const preservedSearchParamKeys = [ | ||
"preview", | ||
"perspective", | ||
"viewport" | ||
]; | ||
const preservedSearchParamKeys = ["preview", "perspective", "viewport"]; | ||
function getIntentState(intent, params, routerState, payload) { | ||
const { id, mode, path, presentation, type, ...searchParams } = params, _searchParams = { | ||
...(routerState?._searchParams || []).filter(([key]) => preservedSearchParamKeys.includes(key)).reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {}), | ||
const { | ||
id, | ||
mode, | ||
path, | ||
presentation, | ||
type, | ||
...searchParams | ||
} = params, _searchParams = { | ||
...(routerState?._searchParams || []).filter(([key]) => preservedSearchParamKeys.includes(key)).reduce((acc, [key, value]) => ({ | ||
...acc, | ||
[key]: value | ||
}), {}), | ||
...searchParams | ||
}; | ||
@@ -337,11 +396,18 @@ return intent === "edit" && id ? (_searchParams.preview = _searchParams.preview || new URLSearchParams(window.location.search).get("preview") || "/", { | ||
_searchParams: Object.entries(_searchParams) | ||
}) : { intent, params, payload }; | ||
}) : { | ||
intent, | ||
params, | ||
payload | ||
}; | ||
} | ||
function PresentationSpinner() { | ||
return /* @__PURE__ */ jsx(Flex, { align: "center", direction: "column", height: "fill", justify: "center", style: { width: "100%" }, children: /* @__PURE__ */ jsx(Spinner, {}) }); | ||
const $ = c(1); | ||
let t0; | ||
return $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = /* @__PURE__ */ jsx(Flex, { align: "center", direction: "column", height: "fill", justify: "center", style: { | ||
width: "100%" | ||
}, children: /* @__PURE__ */ jsx(Spinner, {}) }), $[0] = t0) : t0 = $[0], t0; | ||
} | ||
const router = route.create("/", { __unsafe_disableScopedSearchParams: !0 }, [ | ||
route.intents("/intent"), | ||
route.create(":type", [route.create(":id", [route.create(":path")])]) | ||
]), PresentationTool = lazy(() => import("./PresentationToolGrantsCheck.js").then(function(n) { | ||
const router = route.create("/", { | ||
__unsafe_disableScopedSearchParams: !0 | ||
}, [route.intents("/intent"), route.create(":type", [route.create(":id", [route.create(":path")])])]), PresentationTool = lazy(() => import("./PresentationToolGrantsCheck.js").then(function(n) { | ||
return n.PresentationToolGrantsCheck; | ||
@@ -360,21 +426,36 @@ })), BroadcastDisplayedDocument = lazy(() => import("./BroadcastDisplayedDocument.js")); | ||
function PresentationDocumentInput(props2) { | ||
const value = props2.value, documentId = value?._id ? getPublishedId(value?._id) : void 0; | ||
return isDocumentSchemaType(props2.schemaType) ? /* @__PURE__ */ jsxs(PresentationDocumentProvider, { options, children: [ | ||
hasLocationsResolver && documentId && /* @__PURE__ */ jsx( | ||
PresentationDocumentHeader, | ||
{ | ||
documentId, | ||
options, | ||
schemaType: props2.schemaType | ||
} | ||
), | ||
/* @__PURE__ */ jsx(Suspense, { fallback: /* @__PURE__ */ jsx(PresentationSpinner, {}), children: props2.renderDefault(props2) }), | ||
/* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(BroadcastDisplayedDocument, { value }, documentId) }, "broadcast-displayed-document") | ||
] }) : props2.renderDefault(props2); | ||
const $ = c(19), value = props2.value; | ||
let t0; | ||
$[0] !== value?._id ? (t0 = value?._id ? getPublishedId(value?._id) : void 0, $[0] = value?._id, $[1] = t0) : t0 = $[1]; | ||
const documentId = t0; | ||
if (isDocumentSchemaType(props2.schemaType)) { | ||
let t12; | ||
$[2] !== documentId || $[3] !== props2.schemaType ? (t12 = hasLocationsResolver && documentId && /* @__PURE__ */ jsx(PresentationDocumentHeader, { documentId, options, schemaType: props2.schemaType }), $[2] = documentId, $[3] = props2.schemaType, $[4] = t12) : t12 = $[4]; | ||
let t2; | ||
$[5] === Symbol.for("react.memo_cache_sentinel") ? (t2 = /* @__PURE__ */ jsx(PresentationSpinner, {}), $[5] = t2) : t2 = $[5]; | ||
let t3; | ||
$[6] !== props2 ? (t3 = props2.renderDefault(props2), $[6] = props2, $[7] = t3) : t3 = $[7]; | ||
let t4; | ||
$[8] !== t3 ? (t4 = /* @__PURE__ */ jsx(Suspense, { fallback: t2, children: t3 }), $[8] = t3, $[9] = t4) : t4 = $[9]; | ||
let t5; | ||
$[10] !== documentId || $[11] !== value ? (t5 = /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(BroadcastDisplayedDocument, { value }, documentId) }, "broadcast-displayed-document"), $[10] = documentId, $[11] = value, $[12] = t5) : t5 = $[12]; | ||
let t6; | ||
return $[13] !== t12 || $[14] !== t4 || $[15] !== t5 ? (t6 = /* @__PURE__ */ jsxs(PresentationDocumentProvider, { options, children: [ | ||
t12, | ||
t4, | ||
t5 | ||
] }), $[13] = t12, $[14] = t4, $[15] = t5, $[16] = t6) : t6 = $[16], t6; | ||
} | ||
let t1; | ||
return $[17] !== props2 ? (t1 = props2.renderDefault(props2), $[17] = props2, $[18] = t1) : t1 = $[18], t1; | ||
} | ||
function canHandleCreateIntent(params) { | ||
return !("type" in params) || "presentation" in params && params.presentation !== toolName ? !1 : "template" in params ? { template: !0 } : !0; | ||
return !("type" in params) || "presentation" in params && params.presentation !== toolName ? !1 : "template" in params ? { | ||
template: !0 | ||
} : !0; | ||
} | ||
function canHandleEditIntent(params) { | ||
return !("type" in params) || !("id" in params) || "presentation" in params && params.presentation !== toolName ? !1 : "mode" in params ? { mode: params.mode === EDIT_INTENT_MODE } : !0; | ||
return !("type" in params) || !("id" in params) || "presentation" in params && params.presentation !== toolName ? !1 : "mode" in params ? { | ||
mode: params.mode === EDIT_INTENT_MODE | ||
} : !0; | ||
} | ||
@@ -397,20 +478,16 @@ return { | ||
}, | ||
tools: [ | ||
{ | ||
icon: options.icon || DEFAULT_TOOL_ICON, | ||
name: toolName, | ||
title: options.title, | ||
component: PresentationTool, | ||
options, | ||
canHandleIntent(intent, params) { | ||
return intent === "create" ? canHandleCreateIntent(params) : intent === "edit" ? canHandleEditIntent(params) : !1; | ||
}, | ||
getIntentState, | ||
router | ||
} | ||
] | ||
tools: [{ | ||
icon: options.icon || DEFAULT_TOOL_ICON, | ||
name: toolName, | ||
title: options.title, | ||
component: PresentationTool, | ||
options, | ||
canHandleIntent(intent, params) { | ||
return intent === "create" ? canHandleCreateIntent(params) : intent === "edit" ? canHandleEditIntent(params) : !1; | ||
}, | ||
getIntentState, | ||
router | ||
}] | ||
}; | ||
}), PresentationNavigateContext = createContext( | ||
null | ||
); | ||
}), PresentationNavigateContext = createContext(null); | ||
function usePresentationNavigate() { | ||
@@ -423,4 +500,4 @@ const navigate = useContext(PresentationNavigateContext); | ||
const PresentationParamsContext = createContext(null); | ||
function usePresentationParams(throwOnMissingContext = !0) { | ||
const params = useContext(PresentationParamsContext); | ||
function usePresentationParams(t0) { | ||
const throwOnMissingContext = t0 === void 0 ? !0 : t0, params = useContext(PresentationParamsContext); | ||
if (throwOnMissingContext && !params) | ||
@@ -431,9 +508,12 @@ throw new Error("Presentation params context is missing"); | ||
const SharedStateContext = createContext(null), useSharedState = (key, value) => { | ||
const context = useContext(SharedStateContext); | ||
const $ = c(5), context = useContext(SharedStateContext); | ||
if (!context) | ||
throw new Error("Preview Snapshots context is missing"); | ||
const { setValue } = context; | ||
useEffect(() => { | ||
const { | ||
setValue | ||
} = context; | ||
let t0, t1; | ||
$[0] !== key || $[1] !== setValue || $[2] !== value ? (t0 = () => { | ||
setValue(key, value); | ||
}, [key, value, setValue]); | ||
}, t1 = [key, value, setValue], $[0] = key, $[1] = setValue, $[2] = value, $[3] = t0, $[4] = t1) : (t0 = $[3], t1 = $[4]), useEffect(t0, t1); | ||
}; | ||
@@ -535,3 +615,6 @@ var store; | ||
_run(dataset, config2) { | ||
return schema._run(dataset, config2), dataset.issues ? { typed: !0, value: getFallback(this, dataset, config2) } : dataset; | ||
return schema._run(dataset, config2), dataset.issues ? { | ||
typed: !0, | ||
value: getFallback(this, dataset, config2) | ||
} : dataset; | ||
} | ||
@@ -576,6 +659,6 @@ }; | ||
for (const key in this.entries) { | ||
const value2 = input[key], valueDataset = this.entries[key]._run( | ||
{ typed: !1, value: value2 }, | ||
config2 | ||
); | ||
const value2 = input[key], valueDataset = this.entries[key]._run({ | ||
typed: !1, | ||
value: value2 | ||
}, config2); | ||
if (valueDataset.issues) { | ||
@@ -613,7 +696,3 @@ const pathItem = { | ||
_run(dataset, config2) { | ||
return dataset.value === void 0 && ("default" in this && (dataset.value = getDefault( | ||
this, | ||
dataset, | ||
config2 | ||
)), dataset.value === void 0) ? (dataset.typed = !0, dataset) : this.wrapped._run(dataset, config2); | ||
return dataset.value === void 0 && ("default" in this && (dataset.value = getDefault(this, dataset, config2)), dataset.value === void 0) ? (dataset.typed = !0, dataset) : this.wrapped._run(dataset, config2); | ||
} | ||
@@ -653,6 +732,6 @@ }; | ||
if (_isAllowedObjectKey(entryKey)) { | ||
const entryValue = input[entryKey], keyDataset = this.key._run( | ||
{ typed: !1, value: entryKey }, | ||
config2 | ||
); | ||
const entryValue = input[entryKey], keyDataset = this.key._run({ | ||
typed: !1, | ||
value: entryKey | ||
}, config2); | ||
if (keyDataset.issues) { | ||
@@ -673,6 +752,6 @@ const pathItem = { | ||
} | ||
const valueDataset = this.value._run( | ||
{ typed: !1, value: entryValue }, | ||
config2 | ||
); | ||
const valueDataset = this.value._run({ | ||
typed: !1, | ||
value: entryValue | ||
}, config2); | ||
if (valueDataset.issues) { | ||
@@ -727,6 +806,6 @@ const pathItem = { | ||
function parse(schema, input, config2) { | ||
const dataset = schema._run( | ||
{ typed: !1, value: input }, | ||
getGlobalConfig(config2) | ||
); | ||
const dataset = schema._run({ | ||
typed: !1, | ||
value: input | ||
}, getGlobalConfig(config2)); | ||
if (dataset.issues) | ||
@@ -796,3 +875,5 @@ throw new ValiError(dataset.issues); | ||
}), | ||
visualEditing: object({ overlaysEnabled: boolean() }) | ||
visualEditing: object({ | ||
overlaysEnabled: boolean() | ||
}) | ||
}), INITIAL_PRESENTATION_STATE = { | ||
@@ -808,3 +889,6 @@ mainDocument: !1, | ||
function presentationReducerInit(state) { | ||
return parse(initStateSchema, { ...INITIAL_PRESENTATION_STATE, ...state }); | ||
return parse(initStateSchema, { | ||
...INITIAL_PRESENTATION_STATE, | ||
...state | ||
}); | ||
} | ||
@@ -811,0 +895,0 @@ export { |
import { jsx, Fragment } from "react/jsx-runtime"; | ||
import { c } from "react-compiler-runtime"; | ||
import { createCompatibilityActors, getQueryCacheKey } from "./PresentationToolGrantsCheck.js"; | ||
@@ -21,32 +22,24 @@ import { useQueryParams, useRevalidate } from "./hooks.js"; | ||
useEffect(() => { | ||
const interval = setInterval( | ||
() => setLiveQueries((liveQueries2) => { | ||
if (Object.keys(liveQueries2).length < 1) | ||
return liveQueries2; | ||
const now = Date.now(); | ||
if (!Object.values(liveQueries2).some( | ||
(liveQuery) => liveQuery.heartbeat !== !1 && now > liveQuery.receivedAt + liveQuery.heartbeat | ||
)) | ||
return liveQueries2; | ||
const next = {}; | ||
for (const [key, value] of Object.entries(liveQueries2)) | ||
value.heartbeat !== !1 && now > value.receivedAt + value.heartbeat || (next[key] = value); | ||
return next; | ||
}), | ||
MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL | ||
); | ||
const interval = setInterval(() => setLiveQueries((liveQueries_0) => { | ||
if (Object.keys(liveQueries_0).length < 1) | ||
return liveQueries_0; | ||
const now = Date.now(); | ||
if (!Object.values(liveQueries_0).some((liveQuery) => liveQuery.heartbeat !== !1 && now > liveQuery.receivedAt + liveQuery.heartbeat)) | ||
return liveQueries_0; | ||
const next = {}; | ||
for (const [key, value] of Object.entries(liveQueries_0)) | ||
value.heartbeat !== !1 && now > value.receivedAt + value.heartbeat || (next[key] = value); | ||
return next; | ||
}), MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL); | ||
return () => clearInterval(interval); | ||
}, []), useEffect(() => { | ||
if (controller) { | ||
const comlink2 = controller.createConnection( | ||
{ | ||
name: "presentation", | ||
connectTo: "loaders", | ||
heartbeat: !0 | ||
}, | ||
createChannelMachine().provide({ | ||
actors: createCompatibilityActors() | ||
}) | ||
); | ||
return setComlink(comlink2), comlink2.onStatus(onLoadersConnection), comlink2.on("loader/documents", (data) => { | ||
const comlink_0 = controller.createConnection({ | ||
name: "presentation", | ||
connectTo: "loaders", | ||
heartbeat: !0 | ||
}, createChannelMachine().provide({ | ||
actors: createCompatibilityActors() | ||
})); | ||
return setComlink(comlink_0), comlink_0.onStatus(onLoadersConnection), comlink_0.on("loader/documents", (data) => { | ||
data.projectId === projectId && data.dataset === dataset && onDocumentsOnPage( | ||
@@ -58,36 +51,36 @@ "loaders", | ||
); | ||
}), comlink2.on("loader/query-listen", (data) => { | ||
if (data.projectId === projectId && data.dataset === dataset) { | ||
if (typeof data.heartbeat == "number" && data.heartbeat < MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL) | ||
throw new Error( | ||
`Loader query listen heartbeat interval must be at least ${MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL}ms` | ||
); | ||
}), comlink_0.on("loader/query-listen", (data_0) => { | ||
if (data_0.projectId === projectId && data_0.dataset === dataset) { | ||
if (typeof data_0.heartbeat == "number" && data_0.heartbeat < MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL) | ||
throw new Error(`Loader query listen heartbeat interval must be at least ${MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL}ms`); | ||
setLiveQueries((prev) => ({ | ||
...prev, | ||
[getQueryCacheKey(data.query, data.params)]: { | ||
perspective: data.perspective, | ||
query: data.query, | ||
params: data.params, | ||
[getQueryCacheKey(data_0.query, data_0.params)]: { | ||
perspective: data_0.perspective, | ||
query: data_0.query, | ||
params: data_0.params, | ||
receivedAt: Date.now(), | ||
heartbeat: data.heartbeat ?? !1 | ||
heartbeat: data_0.heartbeat ?? !1 | ||
} | ||
})); | ||
} | ||
}), comlink2.start(); | ||
}), comlink_0.start(); | ||
} | ||
}, [controller, dataset, onDocumentsOnPage, onLoadersConnection, projectId]); | ||
const [syncTagsInUse] = useState(() => /* @__PURE__ */ new Set()), [lastLiveEventId, setLastLiveEventId] = useState(null), studioClient = useClient({ apiVersion: "2023-10-16" }), clientConfig = useMemo(() => studioClient.config(), [studioClient]), client = useMemo( | ||
() => studioClient.withConfig({ | ||
resultSourceMap: "withKeyArraySelector" | ||
}), | ||
[studioClient] | ||
); | ||
const [syncTagsInUse] = useState(() => /* @__PURE__ */ new Set()), [lastLiveEventId, setLastLiveEventId] = useState(null), studioClient = useClient({ | ||
apiVersion: "2023-10-16" | ||
}), clientConfig = useMemo(() => studioClient.config(), [studioClient]), client = useMemo(() => studioClient.withConfig({ | ||
resultSourceMap: "withKeyArraySelector" | ||
}), [studioClient]); | ||
useEffect(() => { | ||
if (comlink) { | ||
const { projectId: projectId2, dataset: dataset2 } = clientConfig; | ||
const { | ||
projectId: projectId_0, | ||
dataset: dataset_0 | ||
} = clientConfig; | ||
comlink.post({ | ||
type: "loader/perspective", | ||
data: { | ||
projectId: projectId2, | ||
dataset: dataset2, | ||
projectId: projectId_0, | ||
dataset: dataset_0, | ||
perspective: activePerspective | ||
@@ -100,3 +93,5 @@ } | ||
const flattenedSyncTags = Array.from(syncTagsInUse).flat(); | ||
event.tags.some((tag) => flattenedSyncTags.includes(tag)) ? setLastLiveEventId(event.id) : console.log("No matching tags found", event.tags, { flattenedSyncTags }); | ||
event.tags.some((tag) => flattenedSyncTags.includes(tag)) ? setLastLiveEventId(event.id) : console.log("No matching tags found", event.tags, { | ||
flattenedSyncTags | ||
}); | ||
}); | ||
@@ -107,5 +102,8 @@ useEffect(() => { | ||
apiVersion: "vX" | ||
}).live.events({ includeDrafts: !0, tag: "presentation-loader" }).subscribe({ | ||
next: (event) => { | ||
event.type === "message" ? handleSyncTags(event) : event.type === "restart" ? setLastLiveEventId(event.id) : event.type === "reconnect" && setLastLiveEventId(null); | ||
}).live.events({ | ||
includeDrafts: !0, | ||
tag: "presentation-loader" | ||
}).subscribe({ | ||
next: (event_0) => { | ||
event_0.type === "message" ? handleSyncTags(event_0) : event_0.type === "restart" ? setLastLiveEventId(event_0.id) : event_0.type === "reconnect" && setLastLiveEventId(null); | ||
}, | ||
@@ -118,21 +116,10 @@ // eslint-disable-next-line no-console | ||
const liveDocument = useDeferredValue(_liveDocument); | ||
return /* @__PURE__ */ jsx(Fragment, { children: Object.entries(liveQueries).map(([key, { query, params, perspective }]) => /* @__PURE__ */ jsx( | ||
QuerySubscription, | ||
{ | ||
projectId: clientConfig.projectId, | ||
dataset: clientConfig.dataset, | ||
perspective, | ||
query, | ||
params, | ||
comlink, | ||
client, | ||
liveDocument, | ||
lastLiveEventId, | ||
syncTagsInUse | ||
}, | ||
`${key}${perspective}` | ||
)) }); | ||
return /* @__PURE__ */ jsx(Fragment, { children: Object.entries(liveQueries).map(([key_0, { | ||
query, | ||
params, | ||
perspective | ||
}]) => /* @__PURE__ */ jsx(QuerySubscription, { projectId: clientConfig.projectId, dataset: clientConfig.dataset, perspective, query, params, comlink, client, liveDocument, lastLiveEventId, syncTagsInUse }, `${key_0}${perspective}`)) }); | ||
} | ||
function QuerySubscriptionComponent(props) { | ||
const { | ||
const $ = c(14), { | ||
projectId, | ||
@@ -158,20 +145,22 @@ dataset, | ||
lastLiveEventId | ||
}) || {}, handleQueryChange = useEffectEvent( | ||
(comlink2, perspective2, query2, params2, result2, resultSourceMap2, tags2) => { | ||
comlink2?.post({ | ||
type: "loader/query-change", | ||
data: { | ||
projectId, | ||
dataset, | ||
perspective: perspective2, | ||
query: query2, | ||
params: params2, | ||
result: result2, | ||
resultSourceMap: resultSourceMap2, | ||
tags: tags2 | ||
} | ||
}); | ||
} | ||
); | ||
return useEffect(() => { | ||
}) || {}; | ||
let t0; | ||
$[0] !== dataset || $[1] !== projectId ? (t0 = (comlink_0, perspective_0, query_0, params_0, result_0, resultSourceMap_0, tags_0) => { | ||
comlink_0?.post({ | ||
type: "loader/query-change", | ||
data: { | ||
projectId, | ||
dataset, | ||
perspective: perspective_0, | ||
query: query_0, | ||
params: params_0, | ||
result: result_0, | ||
resultSourceMap: resultSourceMap_0, | ||
tags: tags_0 | ||
} | ||
}); | ||
}, $[0] = dataset, $[1] = projectId, $[2] = t0) : t0 = $[2]; | ||
const handleQueryChange = useEffectEvent(t0); | ||
let t1, t2; | ||
return $[3] !== comlink || $[4] !== handleQueryChange || $[5] !== params || $[6] !== perspective || $[7] !== query || $[8] !== result || $[9] !== resultSourceMap || $[10] !== syncTagsInUse || $[11] !== tags ? (t1 = () => { | ||
if (resultSourceMap && handleQueryChange(comlink, perspective, query, params, result, resultSourceMap, tags), Array.isArray(tags)) | ||
@@ -181,13 +170,3 @@ return syncTagsInUse.add(tags), () => { | ||
}; | ||
}, [ | ||
comlink, | ||
handleQueryChange, | ||
params, | ||
perspective, | ||
query, | ||
result, | ||
resultSourceMap, | ||
syncTagsInUse, | ||
tags | ||
]), null; | ||
}, t2 = [comlink, handleQueryChange, params, perspective, query, result, resultSourceMap, syncTagsInUse, tags], $[3] = comlink, $[4] = handleQueryChange, $[5] = params, $[6] = perspective, $[7] = query, $[8] = result, $[9] = resultSourceMap, $[10] = syncTagsInUse, $[11] = tags, $[12] = t1, $[13] = t2) : (t1 = $[12], t2 = $[13]), useEffect(t1, t2), null; | ||
} | ||
@@ -197,17 +176,35 @@ const QuerySubscription = memo(QuerySubscriptionComponent); | ||
function useQuerySubscription(props) { | ||
const { liveDocument, client, query, params, perspective, lastLiveEventId } = props, [snapshot, setSnapshot] = useState(null), [error, setError] = useState(null); | ||
if (error) throw error; | ||
const [revalidate, startRefresh] = useRevalidate({ | ||
// Refresh interval is set to zero as we're using the Live Draft Content API to revalidate queries | ||
const $ = c(25), { | ||
liveDocument, | ||
client, | ||
query, | ||
params, | ||
perspective, | ||
lastLiveEventId | ||
} = props, [snapshot, setSnapshot] = useState(null), [error, setError] = useState(null); | ||
if (error) | ||
throw error; | ||
let t0; | ||
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = { | ||
refreshInterval: 0 | ||
}), shouldRefetch = revalidate === "refresh" || revalidate === "inflight" || lastLiveEventId !== snapshot?.lastLiveEventId; | ||
useEffect(() => { | ||
}, $[0] = t0) : t0 = $[0]; | ||
const [revalidate, startRefresh] = useRevalidate(t0), shouldRefetch = revalidate === "refresh" || revalidate === "inflight" || lastLiveEventId !== snapshot?.lastLiveEventId; | ||
let t1, t2; | ||
$[1] !== client || $[2] !== lastLiveEventId || $[3] !== params || $[4] !== perspective || $[5] !== query || $[6] !== shouldRefetch || $[7] !== startRefresh ? (t1 = () => { | ||
if (!shouldRefetch) | ||
return; | ||
let fulfilled = !1, fetching = !1; | ||
const controller = new AbortController(); | ||
async function effect() { | ||
const { signal } = controller; | ||
let fulfilled; | ||
fulfilled = !1; | ||
let fetching; | ||
fetching = !1; | ||
const controller = new AbortController(), effect = async function() { | ||
const { | ||
signal | ||
} = controller; | ||
fetching = !0; | ||
const { result: result2, resultSourceMap: resultSourceMap2, syncTags: syncTags2 } = await client.fetch(query, params, { | ||
const { | ||
result, | ||
resultSourceMap, | ||
syncTags | ||
} = await client.fetch(query, params, { | ||
lastLiveEventId, | ||
@@ -221,21 +218,42 @@ tag: "presentation-loader", | ||
fetching = !1, signal.aborted || (setSnapshot((prev) => ({ | ||
result: isEqual(prev?.result, result2) ? prev?.result : result2, | ||
resultSourceMap: isEqual(prev?.resultSourceMap, resultSourceMap2) ? prev?.resultSourceMap : resultSourceMap2, | ||
syncTags: isEqual(prev?.syncTags, syncTags2) ? prev?.syncTags : syncTags2, | ||
result: isEqual(prev?.result, result) ? prev?.result : result, | ||
resultSourceMap: isEqual(prev?.resultSourceMap, resultSourceMap) ? prev?.resultSourceMap : resultSourceMap, | ||
syncTags: isEqual(prev?.syncTags, syncTags) ? prev?.syncTags : syncTags, | ||
lastLiveEventId | ||
})), fulfilled = !0); | ||
} | ||
const onFinally = startRefresh(); | ||
return effect().catch((error2) => { | ||
fetching = !1, error2.name !== "AbortError" && setError(error2); | ||
}, onFinally = startRefresh(); | ||
return effect().catch((error_0) => { | ||
fetching = !1, error_0.name !== "AbortError" && setError(error_0); | ||
}).finally(onFinally), () => { | ||
!fulfilled && !fetching && controller.abort(); | ||
}; | ||
}, [client, lastLiveEventId, params, perspective, query, shouldRefetch, startRefresh]); | ||
const { result, resultSourceMap, syncTags } = snapshot ?? {}; | ||
return useMemo(() => liveDocument && resultSourceMap ? { | ||
result: turboChargeResultIfSourceMap(liveDocument, result, perspective, resultSourceMap), | ||
resultSourceMap, | ||
syncTags | ||
} : { result, resultSourceMap, syncTags }, [liveDocument, perspective, result, resultSourceMap, syncTags]); | ||
}, t2 = [client, lastLiveEventId, params, perspective, query, shouldRefetch, startRefresh], $[1] = client, $[2] = lastLiveEventId, $[3] = params, $[4] = perspective, $[5] = query, $[6] = shouldRefetch, $[7] = startRefresh, $[8] = t1, $[9] = t2) : (t1 = $[8], t2 = $[9]), useEffect(t1, t2); | ||
let t3; | ||
$[10] !== snapshot ? (t3 = snapshot ?? {}, $[10] = snapshot, $[11] = t3) : t3 = $[11]; | ||
const { | ||
result: result_0, | ||
resultSourceMap: resultSourceMap_0, | ||
syncTags: syncTags_0 | ||
} = t3; | ||
let t4; | ||
bb0: { | ||
if (liveDocument && resultSourceMap_0) { | ||
let t52; | ||
$[12] !== liveDocument || $[13] !== perspective || $[14] !== resultSourceMap_0 || $[15] !== result_0 ? (t52 = turboChargeResultIfSourceMap(liveDocument, result_0, perspective, resultSourceMap_0), $[12] = liveDocument, $[13] = perspective, $[14] = resultSourceMap_0, $[15] = result_0, $[16] = t52) : t52 = $[16]; | ||
let t6; | ||
$[17] !== resultSourceMap_0 || $[18] !== syncTags_0 || $[19] !== t52 ? (t6 = { | ||
result: t52, | ||
resultSourceMap: resultSourceMap_0, | ||
syncTags: syncTags_0 | ||
}, $[17] = resultSourceMap_0, $[18] = syncTags_0, $[19] = t52, $[20] = t6) : t6 = $[20], t4 = t6; | ||
break bb0; | ||
} | ||
let t5; | ||
$[21] !== resultSourceMap_0 || $[22] !== result_0 || $[23] !== syncTags_0 ? (t5 = { | ||
result: result_0, | ||
resultSourceMap: resultSourceMap_0, | ||
syncTags: syncTags_0 | ||
}, $[21] = resultSourceMap_0, $[22] = result_0, $[23] = syncTags_0, $[24] = t5) : t5 = $[24], t4 = t5; | ||
} | ||
return t4; | ||
} | ||
@@ -256,3 +274,5 @@ function turboChargeResultIfSourceMap(liveDocument, result, perspective, resultSourceMap) { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
(changedValue, { previousValue }) => typeof changedValue == "number" && typeof previousValue == "string" ? `${changedValue}` : changedValue, | ||
(changedValue, { | ||
previousValue | ||
}) => typeof changedValue == "number" && typeof previousValue == "string" ? `${changedValue}` : changedValue, | ||
perspective | ||
@@ -259,0 +279,0 @@ ); |
import { jsxs, Fragment, jsx } from "react/jsx-runtime"; | ||
import { c } from "react-compiler-runtime"; | ||
import { createCompatibilityActors, getQueryCacheKey } from "./PresentationToolGrantsCheck.js"; | ||
@@ -21,32 +22,24 @@ import { useQueryParams, useRevalidate } from "./hooks.js"; | ||
useEffect(() => { | ||
const interval = setInterval( | ||
() => setLiveQueries((liveQueries2) => { | ||
if (Object.keys(liveQueries2).length < 1) | ||
return liveQueries2; | ||
const now = Date.now(); | ||
if (!Object.values(liveQueries2).some( | ||
(liveQuery) => liveQuery.heartbeat !== !1 && now > liveQuery.receivedAt + liveQuery.heartbeat | ||
)) | ||
return liveQueries2; | ||
const next = {}; | ||
for (const [key, value] of Object.entries(liveQueries2)) | ||
value.heartbeat !== !1 && now > value.receivedAt + value.heartbeat || (next[key] = value); | ||
return next; | ||
}), | ||
MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL | ||
); | ||
const interval = setInterval(() => setLiveQueries((liveQueries_0) => { | ||
if (Object.keys(liveQueries_0).length < 1) | ||
return liveQueries_0; | ||
const now = Date.now(); | ||
if (!Object.values(liveQueries_0).some((liveQuery) => liveQuery.heartbeat !== !1 && now > liveQuery.receivedAt + liveQuery.heartbeat)) | ||
return liveQueries_0; | ||
const next = {}; | ||
for (const [key, value] of Object.entries(liveQueries_0)) | ||
value.heartbeat !== !1 && now > value.receivedAt + value.heartbeat || (next[key] = value); | ||
return next; | ||
}), MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL); | ||
return () => clearInterval(interval); | ||
}, []), useEffect(() => { | ||
if (controller) { | ||
const comlink2 = controller.createConnection( | ||
{ | ||
name: "presentation", | ||
connectTo: "loaders", | ||
heartbeat: !0 | ||
}, | ||
createChannelMachine().provide({ | ||
actors: createCompatibilityActors() | ||
}) | ||
); | ||
return setComlink(comlink2), comlink2.onStatus(onLoadersConnection), comlink2.on("loader/documents", (data) => { | ||
const comlink_0 = controller.createConnection({ | ||
name: "presentation", | ||
connectTo: "loaders", | ||
heartbeat: !0 | ||
}, createChannelMachine().provide({ | ||
actors: createCompatibilityActors() | ||
})); | ||
return setComlink(comlink_0), comlink_0.onStatus(onLoadersConnection), comlink_0.on("loader/documents", (data) => { | ||
data.projectId === projectId && data.dataset === dataset && onDocumentsOnPage( | ||
@@ -58,36 +51,36 @@ "loaders", | ||
); | ||
}), comlink2.on("loader/query-listen", (data) => { | ||
if (data.projectId === projectId && data.dataset === dataset) { | ||
if (typeof data.heartbeat == "number" && data.heartbeat < MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL) | ||
throw new Error( | ||
`Loader query listen heartbeat interval must be at least ${MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL}ms` | ||
); | ||
}), comlink_0.on("loader/query-listen", (data_0) => { | ||
if (data_0.projectId === projectId && data_0.dataset === dataset) { | ||
if (typeof data_0.heartbeat == "number" && data_0.heartbeat < MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL) | ||
throw new Error(`Loader query listen heartbeat interval must be at least ${MIN_LOADER_QUERY_LISTEN_HEARTBEAT_INTERVAL}ms`); | ||
setLiveQueries((prev) => ({ | ||
...prev, | ||
[getQueryCacheKey(data.query, data.params)]: { | ||
perspective: data.perspective, | ||
query: data.query, | ||
params: data.params, | ||
[getQueryCacheKey(data_0.query, data_0.params)]: { | ||
perspective: data_0.perspective, | ||
query: data_0.query, | ||
params: data_0.params, | ||
receivedAt: Date.now(), | ||
heartbeat: data.heartbeat ?? !1 | ||
heartbeat: data_0.heartbeat ?? !1 | ||
} | ||
})); | ||
} | ||
}), comlink2.start(); | ||
}), comlink_0.start(); | ||
} | ||
}, [controller, dataset, onDocumentsOnPage, onLoadersConnection, projectId]); | ||
const [cache] = useState(() => new LRUCache(LIVE_QUERY_CACHE_SIZE)), studioClient = useClient({ apiVersion: "2023-10-16" }), clientConfig = useMemo(() => studioClient.config(), [studioClient]), client = useMemo( | ||
() => studioClient.withConfig({ | ||
resultSourceMap: "withKeyArraySelector" | ||
}), | ||
[studioClient] | ||
); | ||
const [cache] = useState(() => new LRUCache(LIVE_QUERY_CACHE_SIZE)), studioClient = useClient({ | ||
apiVersion: "2023-10-16" | ||
}), clientConfig = useMemo(() => studioClient.config(), [studioClient]), client = useMemo(() => studioClient.withConfig({ | ||
resultSourceMap: "withKeyArraySelector" | ||
}), [studioClient]); | ||
useEffect(() => { | ||
if (comlink) { | ||
const { projectId: projectId2, dataset: dataset2 } = clientConfig; | ||
const { | ||
projectId: projectId_0, | ||
dataset: dataset_0 | ||
} = clientConfig; | ||
comlink.post({ | ||
type: "loader/perspective", | ||
data: { | ||
projectId: projectId2, | ||
dataset: dataset2, | ||
projectId: projectId_0, | ||
dataset: dataset_0, | ||
perspective: activePerspective | ||
@@ -99,37 +92,28 @@ } | ||
const turboIds = useMemo(() => { | ||
const documentsActuallyInUse = documentsOnPage.map(({ _id }) => _id), ids = [...new Set(documentsActuallyInUse)], max = cache.capacity; | ||
const documentsActuallyInUse = documentsOnPage.map(({ | ||
_id | ||
}) => _id), ids = [...new Set(documentsActuallyInUse)], max = cache.capacity; | ||
return ids.length >= max && (ids.length = max), ids; | ||
}, [cache.capacity, documentsOnPage]), [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, | ||
comlink, | ||
client, | ||
refreshInterval: activePerspective ? 2e3 : 0, | ||
liveDocument, | ||
documentsCacheLastUpdated | ||
}, | ||
`${key}${perspective}` | ||
)) | ||
/* @__PURE__ */ jsx(Turbo, { cache, client, turboIds, setDocumentsCacheLastUpdated }), | ||
Object.entries(liveQueries).map(([key_0, { | ||
query, | ||
params, | ||
perspective | ||
}]) => /* @__PURE__ */ jsx(QuerySubscription, { cache, projectId: clientConfig.projectId, dataset: clientConfig.dataset, perspective, query, params, comlink, client, refreshInterval: activePerspective ? 2e3 : 0, liveDocument, documentsCacheLastUpdated }, `${key_0}${perspective}`)) | ||
] }); | ||
} | ||
const Turbo = memo(function(props) { | ||
const { cache, client, turboIds, setDocumentsCacheLastUpdated } = props, [batch, setBatch] = useState([]); | ||
return useEffect(() => { | ||
const $ = c(22), { | ||
cache, | ||
client, | ||
turboIds, | ||
setDocumentsCacheLastUpdated | ||
} = props; | ||
let t0; | ||
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = [], $[0] = t0) : t0 = $[0]; | ||
const [batch, setBatch] = useState(t0); | ||
let t1, t2; | ||
$[1] !== batch || $[2] !== cache || $[3] !== turboIds ? (t1 = () => { | ||
const batchSet = new Set(batch.flat()), nextBatch = /* @__PURE__ */ new Set(); | ||
@@ -140,18 +124,19 @@ for (const turboId of turboIds) | ||
nextBatchSlice.length !== 0 && setBatch((prevBatch) => [...prevBatch.slice(-LIVE_QUERY_CACHE_BATCH_SIZE), nextBatchSlice]); | ||
}, [batch, cache, turboIds]), useEffect(() => { | ||
const subscription = client.listen( | ||
"*", | ||
{}, | ||
{ | ||
events: ["mutation"], | ||
effectFormat: "mendoza", | ||
includePreviousRevision: !1, | ||
includeResult: !1, | ||
tag: "presentation-loader" | ||
} | ||
).subscribe((update) => { | ||
if (update.type === "mutation" && update.transition === "disappear" && cache.delete(update.documentId) && setDocumentsCacheLastUpdated(Date.now()), update.type !== "mutation" || !update.effects?.apply?.length) return; | ||
}, t2 = [batch, cache, turboIds], $[1] = batch, $[2] = cache, $[3] = turboIds, $[4] = t1, $[5] = t2) : (t1 = $[4], t2 = $[5]), useEffect(t1, t2); | ||
let t3, t4; | ||
$[6] !== cache || $[7] !== client || $[8] !== setDocumentsCacheLastUpdated ? (t3 = () => { | ||
const subscription = client.listen("*", {}, { | ||
events: ["mutation"], | ||
effectFormat: "mendoza", | ||
includePreviousRevision: !1, | ||
includeResult: !1, | ||
tag: "presentation-loader" | ||
}).subscribe((update) => { | ||
if (update.type === "mutation" && update.transition === "disappear" && cache.delete(update.documentId) && setDocumentsCacheLastUpdated(Date.now()), update.type !== "mutation" || !update.effects?.apply?.length) | ||
return; | ||
const cachedDocument = cache.peek(update.documentId); | ||
if (cachedDocument) { | ||
const patchDoc = { ...cachedDocument }; | ||
const patchDoc = { | ||
...cachedDocument | ||
}; | ||
delete patchDoc._rev; | ||
@@ -163,15 +148,20 @@ const patchedDocument = applyPatch(patchDoc, update.effects.apply); | ||
return () => subscription.unsubscribe(); | ||
}, [cache, client, setDocumentsCacheLastUpdated]), /* @__PURE__ */ jsx(Fragment, { children: batch.map((ids) => /* @__PURE__ */ jsx( | ||
GetDocuments, | ||
{ | ||
cache, | ||
client, | ||
ids, | ||
setDocumentsCacheLastUpdated | ||
}, | ||
JSON.stringify(ids) | ||
)) }); | ||
}, t4 = [cache, client, setDocumentsCacheLastUpdated], $[6] = cache, $[7] = client, $[8] = setDocumentsCacheLastUpdated, $[9] = t3, $[10] = t4) : (t3 = $[9], t4 = $[10]), useEffect(t3, t4); | ||
let t5; | ||
if ($[11] !== batch || $[12] !== cache || $[13] !== client || $[14] !== setDocumentsCacheLastUpdated) { | ||
let t62; | ||
$[16] !== cache || $[17] !== client || $[18] !== setDocumentsCacheLastUpdated ? (t62 = (ids) => /* @__PURE__ */ jsx(GetDocuments, { cache, client, ids, setDocumentsCacheLastUpdated }, JSON.stringify(ids)), $[16] = cache, $[17] = client, $[18] = setDocumentsCacheLastUpdated, $[19] = t62) : t62 = $[19], t5 = batch.map(t62), $[11] = batch, $[12] = cache, $[13] = client, $[14] = setDocumentsCacheLastUpdated, $[15] = t5; | ||
} else | ||
t5 = $[15]; | ||
let t6; | ||
return $[20] !== t5 ? (t6 = /* @__PURE__ */ jsx(Fragment, { children: t5 }), $[20] = t5, $[21] = t6) : t6 = $[21], t6; | ||
}), GetDocuments = memo(function(props) { | ||
const { client, cache, ids, setDocumentsCacheLastUpdated } = props; | ||
return useEffect(() => { | ||
const $ = c(6), { | ||
client, | ||
cache, | ||
ids, | ||
setDocumentsCacheLastUpdated | ||
} = props; | ||
let t0, t1; | ||
return $[0] !== cache || $[1] !== client || $[2] !== ids || $[3] !== setDocumentsCacheLastUpdated ? (t0 = () => { | ||
const missingIds = ids.filter((id) => !cache.has(id)); | ||
@@ -182,7 +172,7 @@ missingIds.length !== 0 && client.getDocuments(missingIds).then((documents) => { | ||
}, console.error); | ||
}, [cache, client, ids, setDocumentsCacheLastUpdated]), null; | ||
}, t1 = [cache, client, ids, setDocumentsCacheLastUpdated], $[0] = cache, $[1] = client, $[2] = ids, $[3] = setDocumentsCacheLastUpdated, $[4] = t0, $[5] = t1) : (t0 = $[4], t1 = $[5]), useEffect(t0, t1), null; | ||
}); | ||
GetDocuments.displayName = "GetDocuments"; | ||
function QuerySubscription(props) { | ||
const { | ||
const $ = c(20), { | ||
cache, | ||
@@ -198,3 +188,5 @@ projectId, | ||
documentsCacheLastUpdated | ||
} = props, params = useQueryParams(props.params), data = useQuerySubscription({ | ||
} = props, params = useQueryParams(props.params); | ||
let t0; | ||
$[0] !== cache || $[1] !== client || $[2] !== documentsCacheLastUpdated || $[3] !== liveDocument || $[4] !== params || $[5] !== perspective || $[6] !== query || $[7] !== refreshInterval ? (t0 = { | ||
cache, | ||
@@ -208,4 +200,6 @@ client, | ||
documentsCacheLastUpdated | ||
}), result = data?.result, resultSourceMap = data?.resultSourceMap, tags = data?.tags; | ||
return useEffect(() => { | ||
}, $[0] = cache, $[1] = client, $[2] = documentsCacheLastUpdated, $[3] = liveDocument, $[4] = params, $[5] = perspective, $[6] = query, $[7] = refreshInterval, $[8] = t0) : t0 = $[8]; | ||
const data = useQuerySubscription(t0), result = data?.result, resultSourceMap = data?.resultSourceMap, tags = data?.tags; | ||
let t1, t2; | ||
return $[9] !== comlink || $[10] !== dataset || $[11] !== params || $[12] !== perspective || $[13] !== projectId || $[14] !== query || $[15] !== result || $[16] !== resultSourceMap || $[17] !== tags ? (t1 = () => { | ||
resultSourceMap && comlink?.post({ | ||
@@ -224,3 +218,3 @@ type: "loader/query-change", | ||
}); | ||
}, [comlink, dataset, params, perspective, projectId, query, result, resultSourceMap, tags]), null; | ||
}, t2 = [comlink, dataset, params, perspective, projectId, query, result, resultSourceMap, tags], $[9] = comlink, $[10] = dataset, $[11] = params, $[12] = perspective, $[13] = projectId, $[14] = query, $[15] = result, $[16] = resultSourceMap, $[17] = tags, $[18] = t1, $[19] = t2) : (t1 = $[18], t2 = $[19]), useEffect(t1, t2), null; | ||
} | ||
@@ -237,8 +231,19 @@ function useQuerySubscription(props) { | ||
documentsCacheLastUpdated | ||
} = props, [snapshot, setSnapshot] = useState(null), { projectId, dataset } = useMemo(() => { | ||
const { projectId: projectId2, dataset: dataset2 } = client.config(); | ||
return { projectId: projectId2, dataset: dataset2 }; | ||
} = props, [snapshot, setSnapshot] = useState(null), { | ||
projectId: projectId_0, | ||
dataset: dataset_0 | ||
} = useMemo(() => { | ||
const { | ||
projectId, | ||
dataset | ||
} = client.config(); | ||
return { | ||
projectId, | ||
dataset | ||
}; | ||
}, [client]), [error, setError] = useState(null); | ||
if (error) throw error; | ||
const [revalidate, startRefresh] = useRevalidate({ refreshInterval }), shouldRefetch = revalidate === "refresh" || revalidate === "inflight"; | ||
const [revalidate, startRefresh] = useRevalidate({ | ||
refreshInterval | ||
}), shouldRefetch = revalidate === "refresh" || revalidate === "inflight"; | ||
return useEffect(() => { | ||
@@ -250,5 +255,11 @@ if (!shouldRefetch) | ||
async function effect() { | ||
const { signal } = controller; | ||
const { | ||
signal | ||
} = controller; | ||
fetching = !0; | ||
const { result, resultSourceMap, syncTags } = await client.fetch(query, params, { | ||
const { | ||
result, | ||
resultSourceMap, | ||
syncTags | ||
} = await client.fetch(query, params, { | ||
tag: "presentation-loader", | ||
@@ -259,28 +270,16 @@ signal, | ||
}); | ||
fetching = !1, signal.aborted || (setSnapshot({ result, resultSourceMap, tags: syncTags }), fulfilled = !0); | ||
fetching = !1, signal.aborted || (setSnapshot({ | ||
result, | ||
resultSourceMap, | ||
tags: syncTags | ||
}), fulfilled = !0); | ||
} | ||
const onFinally = startRefresh(); | ||
return effect().catch((error2) => { | ||
fetching = !1, error2.name !== "AbortError" && setError(error2); | ||
return effect().catch((error_0) => { | ||
fetching = !1, error_0.name !== "AbortError" && setError(error_0); | ||
}).finally(onFinally), () => { | ||
!fulfilled && !fetching && controller.abort(); | ||
}; | ||
}, [ | ||
client, | ||
dataset, | ||
liveDocument, | ||
params, | ||
perspective, | ||
projectId, | ||
query, | ||
shouldRefetch, | ||
startRefresh | ||
]), useMemo(() => documentsCacheLastUpdated && snapshot?.resultSourceMap ? { | ||
result: turboChargeResultIfSourceMap( | ||
cache, | ||
liveDocument, | ||
snapshot.result, | ||
perspective, | ||
snapshot.resultSourceMap | ||
), | ||
}, [client, dataset_0, liveDocument, params, perspective, projectId_0, query, shouldRefetch, startRefresh]), useMemo(() => documentsCacheLastUpdated && snapshot?.resultSourceMap ? { | ||
result: turboChargeResultIfSourceMap(cache, liveDocument, snapshot.result, perspective, snapshot.resultSourceMap), | ||
resultSourceMap: snapshot.resultSourceMap | ||
@@ -298,6 +297,3 @@ } : snapshot, [cache, documentsCacheLastUpdated, liveDocument, perspective, snapshot]); | ||
if (sourceDocument._projectId) { | ||
warnedAboutCrossDatasetReference || (console.warn( | ||
"Cross dataset references are not supported yet, ignoring source document", | ||
sourceDocument | ||
), warnedAboutCrossDatasetReference = !0); | ||
warnedAboutCrossDatasetReference || (console.warn("Cross dataset references are not supported yet, ignoring source document", sourceDocument), warnedAboutCrossDatasetReference = !0); | ||
return; | ||
@@ -308,3 +304,5 @@ } | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
(changedValue, { previousValue }) => typeof changedValue == "number" && typeof previousValue == "string" ? `${changedValue}` : changedValue, | ||
(changedValue, { | ||
previousValue | ||
}) => typeof changedValue == "number" && typeof previousValue == "string" ? `${changedValue}` : changedValue, | ||
perspective | ||
@@ -311,0 +309,0 @@ ); |
@@ -0,1 +1,2 @@ | ||
import { c } from "react-compiler-runtime"; | ||
import { memo, useEffect } from "react"; | ||
@@ -6,39 +7,35 @@ import { filter, shareReplay, first, merge } from "rxjs"; | ||
const PostMessageDocuments = (props) => { | ||
const { comlink } = props, client = useClient({ apiVersion: API_VERSION }); | ||
return useEffect(() => { | ||
const listener = client.listen( | ||
'*[!(_id in path("_.**"))]', | ||
{}, | ||
{ | ||
effectFormat: "mendoza", | ||
events: ["welcome", "mutation", "reconnect"], | ||
includePreviousRevision: !1, | ||
includeResult: !1, | ||
tag: "presentation-documents", | ||
visibility: "transaction" | ||
} | ||
).pipe( | ||
filter( | ||
(event) => event.type === "welcome" || event.type === "reconnect" || event.type === "mutation" | ||
) | ||
), welcome = listener.pipe( | ||
filter((event) => event.type === "welcome"), | ||
shareReplay({ bufferSize: 1, refCount: !1 }) | ||
), unsubscribe = comlink.on("visual-editing/snapshot-welcome", async () => ({ event: await new Promise((resolve) => { | ||
welcome.pipe(first()).subscribe((event2) => { | ||
resolve(event2); | ||
const $ = c(13), { | ||
comlink | ||
} = props; | ||
let t0; | ||
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = { | ||
apiVersion: API_VERSION | ||
}, $[0] = t0) : t0 = $[0]; | ||
const client = useClient(t0); | ||
let t1, t2; | ||
$[1] !== client || $[2] !== comlink ? (t1 = () => { | ||
const listener = client.listen('*[!(_id in path("_.**"))]', {}, { | ||
effectFormat: "mendoza", | ||
events: ["welcome", "mutation", "reconnect"], | ||
includePreviousRevision: !1, | ||
includeResult: !1, | ||
tag: "presentation-documents", | ||
visibility: "transaction" | ||
}).pipe(filter(_temp)), welcome = listener.pipe(filter(_temp2), shareReplay({ | ||
bufferSize: 1, | ||
refCount: !1 | ||
})), unsubscribe = comlink.on("visual-editing/snapshot-welcome", async () => ({ | ||
event: await new Promise((resolve) => { | ||
welcome.pipe(first()).subscribe((event_1) => { | ||
resolve(event_1); | ||
}); | ||
}) | ||
})), reconnect = listener.pipe(filter(_temp3)), mutations = listener.pipe(filter(_temp4)), events = merge(welcome, mutations, reconnect).subscribe((event_5) => { | ||
comlink.post({ | ||
type: "presentation/snapshot-event", | ||
data: { | ||
event: event_5 | ||
} | ||
}); | ||
}) })), reconnect = listener.pipe( | ||
filter((event) => event.type === "reconnect") | ||
), mutations = listener.pipe( | ||
filter((event) => event.type === "mutation") | ||
), events = merge( | ||
/** | ||
* @deprecated remove 'welcome' here and switch to explict welcome message fetching at next major | ||
*/ | ||
welcome, | ||
mutations, | ||
reconnect | ||
).subscribe((event) => { | ||
comlink.post({ type: "presentation/snapshot-event", data: { event } }); | ||
}); | ||
@@ -48,10 +45,28 @@ return () => { | ||
}; | ||
}, [client, comlink]), useEffect(() => comlink.on("visual-editing/fetch-snapshot", async (data) => ({ snapshot: await client.getDocument(data.documentId, { | ||
tag: "document.snapshots" | ||
}) })), [client, comlink]), useEffect(() => comlink.on("visual-editing/mutate", async (data) => client.dataRequest("mutate", data, { | ||
}, t2 = [client, comlink], $[1] = client, $[2] = comlink, $[3] = t1, $[4] = t2) : (t1 = $[3], t2 = $[4]), useEffect(t1, t2); | ||
let t3, t4; | ||
$[5] !== client || $[6] !== comlink ? (t3 = () => comlink.on("visual-editing/fetch-snapshot", async (data) => ({ | ||
snapshot: await client.getDocument(data.documentId, { | ||
tag: "document.snapshots" | ||
}) | ||
})), t4 = [client, comlink], $[5] = client, $[6] = comlink, $[7] = t3, $[8] = t4) : (t3 = $[7], t4 = $[8]), useEffect(t3, t4); | ||
let t5, t6; | ||
return $[9] !== client || $[10] !== comlink ? (t5 = () => comlink.on("visual-editing/mutate", async (data_0) => client.dataRequest("mutate", data_0, { | ||
visibility: "async", | ||
returnDocuments: !0 | ||
})), [client, comlink]), null; | ||
})), t6 = [client, comlink], $[9] = client, $[10] = comlink, $[11] = t5, $[12] = t6) : (t5 = $[11], t6 = $[12]), useEffect(t5, t6), null; | ||
}; | ||
var PostMessageDocuments$1 = memo(PostMessageDocuments); | ||
function _temp(event) { | ||
return event.type === "welcome" || event.type === "reconnect" || event.type === "mutation"; | ||
} | ||
function _temp2(event_0) { | ||
return event_0.type === "welcome"; | ||
} | ||
function _temp3(event_3) { | ||
return event_3.type === "reconnect"; | ||
} | ||
function _temp4(event_4) { | ||
return event_4.type === "mutation"; | ||
} | ||
export { | ||
@@ -58,0 +73,0 @@ PostMessageDocuments$1 as default |
@@ -0,11 +1,18 @@ | ||
import { c } from "react-compiler-runtime"; | ||
import { memo, useEffect } from "react"; | ||
const PostMessageFeatures = (props) => { | ||
const { comlink } = props; | ||
return useEffect(() => comlink.on("visual-editing/features", () => ({ | ||
const $ = c(3), { | ||
comlink | ||
} = props; | ||
let t0, t1; | ||
return $[0] !== comlink ? (t0 = () => comlink.on("visual-editing/features", _temp), t1 = [comlink], $[0] = comlink, $[1] = t0, $[2] = t1) : (t0 = $[1], t1 = $[2]), useEffect(t0, t1), null; | ||
}; | ||
var PostMessageFeatures$1 = memo(PostMessageFeatures); | ||
function _temp() { | ||
return { | ||
features: { | ||
optimistic: !0 | ||
} | ||
})), [comlink]), null; | ||
}; | ||
var PostMessageFeatures$1 = memo(PostMessageFeatures); | ||
}; | ||
} | ||
export { | ||
@@ -12,0 +19,0 @@ PostMessageFeatures$1 as default |
@@ -0,12 +1,21 @@ | ||
import { c } from "react-compiler-runtime"; | ||
import { memo, useEffect } from "react"; | ||
const PostMessagePerspective = (props) => { | ||
const { comlink, perspective } = props; | ||
return useEffect(() => comlink.on("visual-editing/fetch-perspective", () => ({ | ||
const $ = c(8), { | ||
comlink, | ||
perspective | ||
})), [comlink, perspective]), useEffect(() => { | ||
} = props; | ||
let t0, t1; | ||
$[0] !== comlink || $[1] !== perspective ? (t0 = () => comlink.on("visual-editing/fetch-perspective", () => ({ | ||
perspective | ||
})), t1 = [comlink, perspective], $[0] = comlink, $[1] = perspective, $[2] = t0, $[3] = t1) : (t0 = $[2], t1 = $[3]), useEffect(t0, t1); | ||
let t2, t3; | ||
return $[4] !== comlink || $[5] !== perspective ? (t2 = () => { | ||
comlink.post({ | ||
type: "presentation/perspective", | ||
data: { perspective } | ||
data: { | ||
perspective | ||
} | ||
}); | ||
}, [comlink, perspective]), null; | ||
}, t3 = [comlink, perspective], $[4] = comlink, $[5] = perspective, $[6] = t2, $[7] = t3) : (t2 = $[6], t3 = $[7]), useEffect(t2, t3), null; | ||
}; | ||
@@ -13,0 +22,0 @@ var PostMessagePerspective$1 = memo(PostMessagePerspective); |
@@ -5,34 +5,33 @@ import { memo, useMemo, useEffect } from "react"; | ||
const PostMessagePreviews = (props) => { | ||
const { comlink, refs, perspective } = props, documentPreviewStore = useDocumentPreviewStore(), schema = useSchema(), refsSubject = useMemo(() => new Subject(), []), previews$ = useMemo(() => refsSubject.asObservable().pipe( | ||
switchMap((refs2) => combineLatest( | ||
refs2.map((ref) => { | ||
const draftRef = { ...ref, _id: getDraftId(ref._id) }, draft$ = perspective === "previewDrafts" ? documentPreviewStore.observeForPreview(draftRef, schema.get(draftRef._type)).pipe( | ||
// Share to prevent double subscribe in the merge | ||
share(), | ||
// Don't emit if no snapshot is returned | ||
skipWhile((p) => p.snapshot === null) | ||
) : ( | ||
// Don't emit if not displaying drafts | ||
NEVER | ||
), publishedRef = { ...ref, _id: getPublishedId(ref._id) }, published$ = documentPreviewStore.observeForPreview( | ||
publishedRef, | ||
schema.get(publishedRef._type) | ||
); | ||
return merge(published$.pipe(takeUntil(draft$)), draft$).pipe( | ||
filter((p) => !!p.snapshot), | ||
map((p) => { | ||
const snapshot = p.snapshot; | ||
return { | ||
_id: getPublishedId(snapshot._id), | ||
title: snapshot.title, | ||
subtitle: snapshot.subtitle, | ||
description: snapshot.description, | ||
imageUrl: snapshot.imageUrl | ||
}; | ||
}) | ||
); | ||
}) | ||
)), | ||
debounceTime(0) | ||
), [documentPreviewStore, refsSubject, schema, perspective]); | ||
const { | ||
comlink, | ||
refs, | ||
perspective | ||
} = props, documentPreviewStore = useDocumentPreviewStore(), schema = useSchema(), refsSubject = useMemo(() => new Subject(), []), previews$ = useMemo(() => refsSubject.asObservable().pipe(switchMap((refs_0) => combineLatest(refs_0.map((ref) => { | ||
const draftRef = { | ||
...ref, | ||
_id: getDraftId(ref._id) | ||
}, draft$ = perspective === "previewDrafts" ? documentPreviewStore.observeForPreview(draftRef, schema.get(draftRef._type)).pipe( | ||
// Share to prevent double subscribe in the merge | ||
share(), | ||
// Don't emit if no snapshot is returned | ||
skipWhile((p) => p.snapshot === null) | ||
) : ( | ||
// Don't emit if not displaying drafts | ||
NEVER | ||
), publishedRef = { | ||
...ref, | ||
_id: getPublishedId(ref._id) | ||
}, published$ = documentPreviewStore.observeForPreview(publishedRef, schema.get(publishedRef._type)); | ||
return merge(published$.pipe(takeUntil(draft$)), draft$).pipe(filter((p_0) => !!p_0.snapshot), map((p_1) => { | ||
const snapshot = p_1.snapshot; | ||
return { | ||
_id: getPublishedId(snapshot._id), | ||
title: snapshot.title, | ||
subtitle: snapshot.subtitle, | ||
description: snapshot.description, | ||
imageUrl: snapshot.imageUrl | ||
}; | ||
})); | ||
}))), debounceTime(0)), [documentPreviewStore, refsSubject, schema, perspective]); | ||
return useEffect(() => { | ||
@@ -42,3 +41,5 @@ const sub = previews$.subscribe((snapshots) => { | ||
type: "presentation/preview-snapshots", | ||
data: { snapshots } | ||
data: { | ||
snapshots | ||
} | ||
}); | ||
@@ -45,0 +46,0 @@ }); |
import { jsx } from "react/jsx-runtime"; | ||
import { memo, useMemo, useState, useEffect, startTransition } from "react"; | ||
import { c } from "react-compiler-runtime"; | ||
import { memo, useState, useEffect, startTransition } from "react"; | ||
import { getPublishedId, useEditState } from "sanity"; | ||
function PostMessageRefreshMutations(props) { | ||
const { comlink, type, previewKitConnection, loadersConnection } = props, id = useMemo(() => getPublishedId(props.id), [props.id]), { draft, published, ready } = useEditState(id, type, "low"); | ||
return ready && draft || published ? /* @__PURE__ */ jsx( | ||
PostMessageRefreshMutationsInner, | ||
{ | ||
comlink, | ||
draft, | ||
livePreviewEnabled: previewKitConnection === "connected" || loadersConnection === "connected", | ||
published | ||
}, | ||
id | ||
) : null; | ||
const $ = c(8), { | ||
comlink, | ||
type, | ||
previewKitConnection, | ||
loadersConnection | ||
} = props; | ||
let t0, t1; | ||
$[0] !== props.id ? (t1 = getPublishedId(props.id), $[0] = props.id, $[1] = t1) : t1 = $[1], t0 = t1; | ||
const id = t0, { | ||
draft, | ||
published, | ||
ready | ||
} = useEditState(id, type, "low"), livePreviewEnabled = previewKitConnection === "connected" || loadersConnection === "connected"; | ||
if (ready && draft || published) { | ||
let t2; | ||
return $[2] !== comlink || $[3] !== draft || $[4] !== id || $[5] !== livePreviewEnabled || $[6] !== published ? (t2 = /* @__PURE__ */ jsx(PostMessageRefreshMutationsInner, { comlink, draft, livePreviewEnabled, published }, id), $[2] = comlink, $[3] = draft, $[4] = id, $[5] = livePreviewEnabled, $[6] = published, $[7] = t2) : t2 = $[7], t2; | ||
} | ||
return null; | ||
} | ||
function PostMessageRefreshMutationsInner(props) { | ||
const { comlink, draft, published, livePreviewEnabled } = props, [prevDraft, setPrevDraft] = useState(draft), [prevPublished, setPrevPublished] = useState(published); | ||
return useEffect(() => { | ||
const $ = c(14), { | ||
comlink, | ||
draft, | ||
published, | ||
livePreviewEnabled | ||
} = props, [prevDraft, setPrevDraft] = useState(draft), [prevPublished, setPrevPublished] = useState(published); | ||
let t0; | ||
$[0] !== comlink || $[1] !== draft || $[2] !== livePreviewEnabled || $[3] !== prevDraft?._rev || $[4] !== prevPublished?._rev || $[5] !== published ? (t0 = () => { | ||
prevDraft?._rev !== draft?._rev && (startTransition(() => setPrevDraft(draft)), draft && comlink?.post({ | ||
@@ -35,7 +49,20 @@ type: "presentation/refresh", | ||
})); | ||
}, [comlink, draft, livePreviewEnabled, prevDraft?._rev, prevPublished?._rev, published]), null; | ||
}, $[0] = comlink, $[1] = draft, $[2] = livePreviewEnabled, $[3] = prevDraft?._rev, $[4] = prevPublished?._rev, $[5] = published, $[6] = t0) : t0 = $[6]; | ||
const t1 = prevDraft?._rev, t2 = prevPublished?._rev; | ||
let t3; | ||
return $[7] !== comlink || $[8] !== draft || $[9] !== livePreviewEnabled || $[10] !== published || $[11] !== t1 || $[12] !== t2 ? (t3 = [comlink, draft, livePreviewEnabled, t1, t2, published], $[7] = comlink, $[8] = draft, $[9] = livePreviewEnabled, $[10] = published, $[11] = t1, $[12] = t2, $[13] = t3) : t3 = $[13], useEffect(t0, t3), null; | ||
} | ||
function parseDocument(document) { | ||
const { _id, _type, _rev, slug } = document; | ||
return { _id, _type, _rev, slug }; | ||
const { | ||
_id, | ||
_type, | ||
_rev, | ||
slug | ||
} = document; | ||
return { | ||
_id, | ||
_type, | ||
_rev, | ||
slug | ||
}; | ||
} | ||
@@ -42,0 +69,0 @@ var PostMessageRefreshMutations$1 = memo(PostMessageRefreshMutations); |
@@ -0,1 +1,2 @@ | ||
import { c } from "react-compiler-runtime"; | ||
import { ThemeProvider, useRootTheme } from "@sanity/ui"; | ||
@@ -9,3 +10,5 @@ import { createElement, memo, useEffect } from "react"; | ||
function isFieldRequired(field) { | ||
const { validation } = field.type; | ||
const { | ||
validation | ||
} = field.type; | ||
if (!validation) | ||
@@ -16,8 +19,5 @@ return !1; | ||
let required = !1; | ||
const proxy = new Proxy( | ||
{}, | ||
{ | ||
get: (target, methodName) => () => (methodName === "required" && (required = !0), proxy) | ||
} | ||
); | ||
const proxy = new Proxy({}, { | ||
get: (target, methodName) => () => (methodName === "required" && (required = !0), proxy) | ||
}); | ||
if (typeof rule == "function" && (rule(proxy), required) || typeof rule == "object" && rule !== null && "_required" in rule && rule._required === "required") | ||
@@ -105,5 +105,16 @@ return !0; | ||
} | ||
const SchemaIcon = function({ schemaType, theme: themeContext }) { | ||
const { theme, scheme, tone } = themeContext, sheet = new ServerStyleSheet(); | ||
return schemaType.icon ? /* @__PURE__ */ jsx(StyleSheetManager, { sheet: sheet.instance, children: /* @__PURE__ */ jsx(ThemeProvider, { theme, scheme, tone, children: createElement(schemaType.icon) }) }) : null; | ||
const SchemaIcon = function(t0) { | ||
const $ = c(6), { | ||
schemaType, | ||
theme: themeContext | ||
} = t0, { | ||
theme, | ||
scheme, | ||
tone | ||
} = themeContext; | ||
let t1; | ||
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t1 = new ServerStyleSheet(), $[0] = t1) : t1 = $[0]; | ||
const sheet = t1; | ||
let t2; | ||
return $[1] !== schemaType.icon || $[2] !== scheme || $[3] !== theme || $[4] !== tone ? (t2 = schemaType.icon ? /* @__PURE__ */ jsx(StyleSheetManager, { sheet: sheet.instance, children: /* @__PURE__ */ jsx(ThemeProvider, { theme, scheme, tone, children: createElement(schemaType.icon) }) }) : null, $[1] = schemaType.icon, $[2] = scheme, $[3] = theme, $[4] = tone, $[5] = t2) : t2 = $[5], t2; | ||
}, documentDefaultFields = (typeName) => ({ | ||
@@ -228,12 +239,20 @@ _id: { | ||
} | ||
const typesMap = /* @__PURE__ */ new Map([ | ||
["text", { type: "string" }], | ||
["url", { type: "string" }], | ||
["datetime", { type: "string" }], | ||
["date", { type: "string" }], | ||
["boolean", { type: "boolean" }], | ||
["email", { type: "string" }] | ||
]); | ||
const typesMap = /* @__PURE__ */ new Map([["text", { | ||
type: "string" | ||
}], ["url", { | ||
type: "string" | ||
}], ["datetime", { | ||
type: "string" | ||
}], ["date", { | ||
type: "string" | ||
}], ["boolean", { | ||
type: "boolean" | ||
}], ["email", { | ||
type: "string" | ||
}]]); | ||
function extractSchema(workspace, theme) { | ||
const inlineFields = /* @__PURE__ */ new Set(), { schema: schemaDef, basePath } = workspace; | ||
const inlineFields = /* @__PURE__ */ new Set(), { | ||
schema: schemaDef, | ||
basePath | ||
} = workspace; | ||
return sortByDependencies(schemaDef).map((typeName) => { | ||
@@ -249,3 +268,6 @@ const schemaType = schemaDef.get(typeName); | ||
if (schemaType.icon) | ||
return renderToString(createElement(SchemaIcon, { schemaType, theme })); | ||
return renderToString(createElement(SchemaIcon, { | ||
schemaType, | ||
theme | ||
})); | ||
} | ||
@@ -313,5 +335,11 @@ function convertBaseType(schemaType) { | ||
if (inlineFields.has(schemaType.type)) | ||
return { type: "inline", name: schemaType.type.name }; | ||
return { | ||
type: "inline", | ||
name: schemaType.type.name | ||
}; | ||
if (schemaType.type?.type?.name === "object") | ||
return { type: "inline", name: schemaType.type.name }; | ||
return { | ||
type: "inline", | ||
name: schemaType.type.name | ||
}; | ||
if (isStringType(schemaType)) | ||
@@ -327,3 +355,5 @@ return createStringNodeDefintion(schemaType); | ||
if (isCrossDatasetReferenceType(schemaType)) | ||
return { type: "unknown" }; | ||
return { | ||
type: "unknown" | ||
}; | ||
if (isReferenceType(schemaType)) | ||
@@ -338,3 +368,5 @@ return createReferenceNodeDefintion(schemaType); | ||
function createUnionNodeOptions(schemaType, of) { | ||
const { options } = schemaType; | ||
const { | ||
options | ||
} = schemaType; | ||
if (!options) return; | ||
@@ -346,23 +378,17 @@ const opts = { | ||
...options.insertMenu, | ||
views: options.insertMenu.views?.map( | ||
(view) => view.name === "grid" ? { | ||
name: "grid", | ||
previewImageUrls: view.previewImageUrl ? of.reduce( | ||
(acc, { name }) => { | ||
const url = view.previewImageUrl?.(name); | ||
if (!url) return acc; | ||
try { | ||
new URL(url), acc[name] = url; | ||
} catch { | ||
acc[name] = new URL( | ||
url, | ||
`${window.location.origin}${basePath ? `${basePath}/` : ""}` | ||
).toString(); | ||
} | ||
return acc; | ||
}, | ||
{} | ||
) : void 0 | ||
} : view | ||
) | ||
views: options.insertMenu.views?.map((view) => view.name === "grid" ? { | ||
name: "grid", | ||
previewImageUrls: view.previewImageUrl ? of.reduce((acc, { | ||
name | ||
}) => { | ||
const url = view.previewImageUrl?.(name); | ||
if (!url) return acc; | ||
try { | ||
new URL(url), acc[name] = url; | ||
} catch { | ||
acc[name] = new URL(url, `${window.location.origin}${basePath ? `${basePath}/` : ""}`).toString(); | ||
} | ||
return acc; | ||
}, {}) : void 0 | ||
} : view) | ||
}), opts; | ||
@@ -395,3 +421,5 @@ } | ||
if (of.length === 0) | ||
return { type: "null" }; | ||
return { | ||
type: "null" | ||
}; | ||
if (of.length > 1) | ||
@@ -403,3 +431,7 @@ return { | ||
}; | ||
const { name, title, value } = of[0]; | ||
const { | ||
name, | ||
title, | ||
value | ||
} = of[0]; | ||
return { | ||
@@ -426,27 +458,64 @@ type: "array", | ||
function getDocumentPathArray(paths) { | ||
const documentPathMap = paths.reduce( | ||
(acc, { id, path }) => (acc[id] ? acc[id].add(path) : acc[id] = /* @__PURE__ */ new Set([path]), acc), | ||
{} | ||
); | ||
const documentPathMap = paths.reduce((acc, { | ||
id, | ||
path | ||
}) => (acc[id] ? acc[id].add(path) : acc[id] = /* @__PURE__ */ new Set([path]), acc), {}); | ||
return Object.entries(documentPathMap); | ||
} | ||
function PostMessageSchema(props) { | ||
const { comlink, perspective } = props, workspace = useWorkspace(), theme = useRootTheme(); | ||
useEffect(() => { | ||
const $ = c(11), { | ||
comlink, | ||
perspective | ||
} = props, workspace = useWorkspace(), theme = useRootTheme(); | ||
let t0, t1; | ||
$[0] !== comlink || $[1] !== theme || $[2] !== workspace ? (t0 = () => { | ||
const schema = extractSchema(workspace, theme); | ||
return comlink.post({ type: "presentation/schema", data: { schema } }), comlink.on("visual-editing/schema", () => ({ schema })); | ||
}, [comlink, theme, workspace]); | ||
const client = useClient({ apiVersion: API_VERSION }); | ||
return useEffect(() => comlink.on("visual-editing/schema-union-types", async (data) => { | ||
const documentPathArray = getDocumentPathArray(data.paths), unionTypes = await Promise.all( | ||
documentPathArray.map(async ([id, paths]) => { | ||
const arr = Array.from(paths), query = `*[_id == $id][0]{${arr.map((path, i) => `"${i}": ${path}[0]._type`).join(",")}}`, result = await client.fetch(query, { id }, { perspective, tag: "presentation-schema" }), mapped = arr.map((path, i) => ({ path, type: result[i] })); | ||
return { id, paths: mapped }; | ||
}) | ||
), newState = /* @__PURE__ */ new Map(); | ||
return comlink.post({ | ||
type: "presentation/schema", | ||
data: { | ||
schema | ||
} | ||
}), comlink.on("visual-editing/schema", () => ({ | ||
schema | ||
})); | ||
}, t1 = [comlink, theme, workspace], $[0] = comlink, $[1] = theme, $[2] = workspace, $[3] = t0, $[4] = t1) : (t0 = $[3], t1 = $[4]), useEffect(t0, t1); | ||
let t2; | ||
$[5] === Symbol.for("react.memo_cache_sentinel") ? (t2 = { | ||
apiVersion: API_VERSION | ||
}, $[5] = t2) : t2 = $[5]; | ||
const client = useClient(t2); | ||
let t3, t4; | ||
return $[6] !== client || $[7] !== comlink || $[8] !== perspective ? (t3 = () => comlink.on("visual-editing/schema-union-types", async (data) => { | ||
const documentPathArray = getDocumentPathArray(data.paths), unionTypes = await Promise.all(documentPathArray.map(async (t5) => { | ||
const [id, paths] = t5, arr = Array.from(paths), query = `*[_id == $id][0]{${arr.map(_temp).join(",")}}`, result = await client.fetch(query, { | ||
id | ||
}, { | ||
perspective, | ||
tag: "presentation-schema" | ||
}), mapped = arr.map((path_0, i_0) => ({ | ||
path: path_0, | ||
type: result[i_0] | ||
})); | ||
return { | ||
id, | ||
paths: mapped | ||
}; | ||
})), newState = /* @__PURE__ */ new Map(); | ||
return unionTypes.forEach((action) => { | ||
newState.set(action.id, new Map(action.paths.map(({ path, type }) => [path, type]))); | ||
}), { types: newState }; | ||
}), [comlink, client, perspective]), null; | ||
newState.set(action.id, new Map(action.paths.map(_temp2))); | ||
}), { | ||
types: newState | ||
}; | ||
}), t4 = [comlink, client, perspective], $[6] = client, $[7] = comlink, $[8] = perspective, $[9] = t3, $[10] = t4) : (t3 = $[9], t4 = $[10]), useEffect(t3, t4), null; | ||
} | ||
function _temp2(t0) { | ||
const { | ||
path: path_1, | ||
type | ||
} = t0; | ||
return [path_1, type]; | ||
} | ||
function _temp(path, i) { | ||
return `"${i}": ${path}[0]._type`; | ||
} | ||
var PostMessageSchema$1 = memo(PostMessageSchema); | ||
@@ -453,0 +522,0 @@ export { |
@@ -10,28 +10,2 @@ import { jsxs, jsx } from "react/jsx-runtime"; | ||
class QrCode { | ||
/*-- Constructor (low level) and fields --*/ | ||
// Creates a new QR Code with the given version number, | ||
// error correction level, data codeword bytes, and mask number. | ||
// This is a low-level API that most users should not use directly. | ||
// A mid-level API is the encodeSegments() function. | ||
constructor(version, errorCorrectionLevel, dataCodewords, msk) { | ||
if (this.version = version, this.errorCorrectionLevel = errorCorrectionLevel, version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) | ||
throw new RangeError("Version value out of range"); | ||
if (msk < -1 || msk > 7) throw new RangeError("Mask value out of range"); | ||
this.size = version * 4 + 17; | ||
const row = []; | ||
for (let i = 0; i < this.size; i++) row.push(!1); | ||
for (let i = 0; i < this.size; i++) | ||
this.modules.push(row.slice()), this.isFunction.push(row.slice()); | ||
this.drawFunctionPatterns(); | ||
const allCodewords = this.addEccAndInterleave(dataCodewords); | ||
if (this.drawCodewords(allCodewords), msk == -1) { | ||
let minPenalty = 1e9; | ||
for (let i = 0; i < 8; i++) { | ||
this.applyMask(i), this.drawFormatBits(i); | ||
const penalty = this.getPenaltyScore(); | ||
penalty < minPenalty && (msk = i, minPenalty = penalty), this.applyMask(i); | ||
} | ||
} | ||
assert(0 <= msk && msk <= 7), this.mask = msk, this.applyMask(msk), this.drawFormatBits(msk), this.isFunction = []; | ||
} | ||
/*-- Static factory functions (high level) --*/ | ||
@@ -66,4 +40,3 @@ // Returns a QR Code representing the given Unicode text string at the given error correction level. | ||
static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = !0) { | ||
if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION) || mask < -1 || mask > 7) | ||
throw new RangeError("Invalid value"); | ||
if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION) || mask < -1 || mask > 7) throw new RangeError("Invalid value"); | ||
let version, dataUsedBits; | ||
@@ -89,4 +62,3 @@ for (version = minVersion; ; version++) { | ||
assert(bb.length <= dataCapacityBits), appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb), appendBits(0, (8 - bb.length % 8) % 8, bb), assert(bb.length % 8 == 0); | ||
for (let padByte = 236; bb.length < dataCapacityBits; padByte ^= 253) | ||
appendBits(padByte, 8, bb); | ||
for (let padByte = 236; bb.length < dataCapacityBits; padByte ^= 253) appendBits(padByte, 8, bb); | ||
const dataCodewords = []; | ||
@@ -99,7 +71,5 @@ for (; dataCodewords.length * 8 < bb.length; ) dataCodewords.push(0); | ||
// 21 and 177 (inclusive). This is equal to version * 4 + 17. | ||
size; | ||
// The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). | ||
// Even if a QR Code is created with automatic masking requested (mask = -1), | ||
// the resulting object still has a mask value between 0 and 7. | ||
mask; | ||
// The modules of this QR Code (false = light, true = dark). | ||
@@ -110,2 +80,27 @@ // Immutable after constructor finishes. Accessed through getModule(). | ||
isFunction = []; | ||
/*-- Constructor (low level) and fields --*/ | ||
// Creates a new QR Code with the given version number, | ||
// error correction level, data codeword bytes, and mask number. | ||
// This is a low-level API that most users should not use directly. | ||
// A mid-level API is the encodeSegments() function. | ||
constructor(version, errorCorrectionLevel, dataCodewords, msk) { | ||
if (this.version = version, this.errorCorrectionLevel = errorCorrectionLevel, version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) throw new RangeError("Version value out of range"); | ||
if (msk < -1 || msk > 7) throw new RangeError("Mask value out of range"); | ||
this.size = version * 4 + 17; | ||
const row = []; | ||
for (let i = 0; i < this.size; i++) row.push(!1); | ||
for (let i = 0; i < this.size; i++) | ||
this.modules.push(row.slice()), this.isFunction.push(row.slice()); | ||
this.drawFunctionPatterns(); | ||
const allCodewords = this.addEccAndInterleave(dataCodewords); | ||
if (this.drawCodewords(allCodewords), msk == -1) { | ||
let minPenalty = 1e9; | ||
for (let i = 0; i < 8; i++) { | ||
this.applyMask(i), this.drawFormatBits(i); | ||
const penalty = this.getPenaltyScore(); | ||
penalty < minPenalty && (msk = i, minPenalty = penalty), this.applyMask(i); | ||
} | ||
} | ||
assert(0 <= msk && msk <= 7), this.mask = msk, this.applyMask(msk), this.drawFormatBits(msk), this.isFunction = []; | ||
} | ||
/*-- Accessor methods --*/ | ||
@@ -175,4 +170,3 @@ // Returns the color of the module (pixel) at the given coordinates, which is false | ||
for (let dy = -2; dy <= 2; dy++) | ||
for (let dx = -2; dx <= 2; dx++) | ||
this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1); | ||
for (let dx = -2; dx <= 2; dx++) this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1); | ||
} | ||
@@ -189,10 +183,6 @@ // Sets the color of a module and marks it as a function module. | ||
const ver = this.version, ecl = this.errorCorrectionLevel; | ||
if (data.length != QrCode.getNumDataCodewords(ver, ecl)) | ||
throw new RangeError("Invalid argument"); | ||
if (data.length != QrCode.getNumDataCodewords(ver, ecl)) throw new RangeError("Invalid argument"); | ||
const numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver], blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver], rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8), numShortBlocks = numBlocks - rawCodewords % numBlocks, shortBlockLen = Math.floor(rawCodewords / numBlocks), blocks = [], rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen); | ||
for (let i = 0, k = 0; i < numBlocks; i++) { | ||
const dat = data.slice( | ||
k, | ||
k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1) | ||
); | ||
const dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); | ||
k += dat.length; | ||
@@ -212,4 +202,3 @@ const ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv); | ||
drawCodewords(data) { | ||
if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8)) | ||
throw new RangeError("Invalid argument"); | ||
if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8)) throw new RangeError("Invalid argument"); | ||
let i = 0; | ||
@@ -311,4 +300,3 @@ for (let right = this.size - 1; right >= 1; right -= 2) { | ||
static getNumRawDataModules(ver) { | ||
if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) | ||
throw new RangeError("Version number out of range"); | ||
if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) throw new RangeError("Version number out of range"); | ||
let result = (16 * ver + 128) * ver + 64; | ||
@@ -389,177 +377,9 @@ if (ver >= 2) { | ||
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level | ||
[ | ||
-1, | ||
7, | ||
10, | ||
15, | ||
20, | ||
26, | ||
18, | ||
20, | ||
24, | ||
30, | ||
18, | ||
20, | ||
24, | ||
26, | ||
30, | ||
22, | ||
24, | ||
28, | ||
30, | ||
28, | ||
28, | ||
28, | ||
28, | ||
30, | ||
30, | ||
26, | ||
28, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30 | ||
], | ||
[-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], | ||
// Low | ||
[ | ||
-1, | ||
10, | ||
16, | ||
26, | ||
18, | ||
24, | ||
16, | ||
18, | ||
22, | ||
22, | ||
26, | ||
30, | ||
22, | ||
22, | ||
24, | ||
24, | ||
28, | ||
28, | ||
26, | ||
26, | ||
26, | ||
26, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28, | ||
28 | ||
], | ||
[-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], | ||
// Medium | ||
[ | ||
-1, | ||
13, | ||
22, | ||
18, | ||
26, | ||
18, | ||
24, | ||
18, | ||
22, | ||
20, | ||
24, | ||
28, | ||
26, | ||
24, | ||
20, | ||
30, | ||
24, | ||
28, | ||
28, | ||
26, | ||
30, | ||
28, | ||
30, | ||
30, | ||
30, | ||
30, | ||
28, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30 | ||
], | ||
[-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], | ||
// Quartile | ||
[ | ||
-1, | ||
17, | ||
28, | ||
22, | ||
16, | ||
22, | ||
28, | ||
26, | ||
26, | ||
24, | ||
28, | ||
24, | ||
28, | ||
22, | ||
24, | ||
24, | ||
30, | ||
28, | ||
28, | ||
26, | ||
28, | ||
30, | ||
24, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30, | ||
30 | ||
] | ||
[-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30] | ||
// High | ||
@@ -570,177 +390,9 @@ ]; | ||
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level | ||
[ | ||
-1, | ||
1, | ||
1, | ||
1, | ||
1, | ||
1, | ||
2, | ||
2, | ||
2, | ||
2, | ||
4, | ||
4, | ||
4, | ||
4, | ||
4, | ||
6, | ||
6, | ||
6, | ||
6, | ||
7, | ||
8, | ||
8, | ||
9, | ||
9, | ||
10, | ||
12, | ||
12, | ||
12, | ||
13, | ||
14, | ||
15, | ||
16, | ||
17, | ||
18, | ||
19, | ||
19, | ||
20, | ||
21, | ||
22, | ||
24, | ||
25 | ||
], | ||
[-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], | ||
// Low | ||
[ | ||
-1, | ||
1, | ||
1, | ||
1, | ||
2, | ||
2, | ||
4, | ||
4, | ||
4, | ||
5, | ||
5, | ||
5, | ||
8, | ||
9, | ||
9, | ||
10, | ||
10, | ||
11, | ||
13, | ||
14, | ||
16, | ||
17, | ||
17, | ||
18, | ||
20, | ||
21, | ||
23, | ||
25, | ||
26, | ||
28, | ||
29, | ||
31, | ||
33, | ||
35, | ||
37, | ||
38, | ||
40, | ||
43, | ||
45, | ||
47, | ||
49 | ||
], | ||
[-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], | ||
// Medium | ||
[ | ||
-1, | ||
1, | ||
1, | ||
2, | ||
2, | ||
4, | ||
4, | ||
6, | ||
6, | ||
8, | ||
8, | ||
8, | ||
10, | ||
12, | ||
16, | ||
12, | ||
17, | ||
16, | ||
18, | ||
21, | ||
20, | ||
23, | ||
23, | ||
25, | ||
27, | ||
29, | ||
34, | ||
34, | ||
35, | ||
38, | ||
40, | ||
43, | ||
45, | ||
48, | ||
51, | ||
53, | ||
56, | ||
59, | ||
62, | ||
65, | ||
68 | ||
], | ||
[-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], | ||
// Quartile | ||
[ | ||
-1, | ||
1, | ||
1, | ||
2, | ||
4, | ||
4, | ||
4, | ||
5, | ||
6, | ||
8, | ||
8, | ||
11, | ||
11, | ||
16, | ||
16, | ||
18, | ||
16, | ||
19, | ||
21, | ||
25, | ||
25, | ||
25, | ||
34, | ||
30, | ||
32, | ||
35, | ||
37, | ||
40, | ||
42, | ||
45, | ||
48, | ||
51, | ||
54, | ||
57, | ||
60, | ||
63, | ||
66, | ||
70, | ||
74, | ||
77, | ||
81 | ||
] | ||
[-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81] | ||
// High | ||
@@ -751,4 +403,3 @@ ]; | ||
if (len < 0 || len > 31 || val >>> len) throw new RangeError("Value out of range"); | ||
for (let i = len - 1; i >= 0; i--) | ||
bb.push(val >>> i & 1); | ||
for (let i = len - 1; i >= 0; i--) bb.push(val >>> i & 1); | ||
} | ||
@@ -762,10 +413,2 @@ function getBit(x, i) { | ||
class QrSegment { | ||
/*-- Constructor (low level) and fields --*/ | ||
// Creates a new QR Code segment with the given attributes and data. | ||
// The character count (numChars) must agree with the mode and the bit buffer length, | ||
// but the constraint isn't checked. The given bit buffer is cloned and stored. | ||
constructor(mode, numChars, bitData) { | ||
if (this.mode = mode, this.numChars = numChars, this.bitData = bitData, numChars < 0) throw new RangeError("Invalid argument"); | ||
this.bitData = bitData.slice(); | ||
} | ||
/*-- Static factory functions (mid level) --*/ | ||
@@ -794,4 +437,3 @@ // Returns a segment representing the given binary data encoded in | ||
static makeAlphanumeric(text) { | ||
if (!QrSegment.isAlphanumeric(text)) | ||
throw new RangeError("String contains unencodable characters in alphanumeric mode"); | ||
if (!QrSegment.isAlphanumeric(text)) throw new RangeError("String contains unencodable characters in alphanumeric mode"); | ||
const bb = []; | ||
@@ -834,2 +476,10 @@ let i; | ||
} | ||
/*-- Constructor (low level) and fields --*/ | ||
// Creates a new QR Code segment with the given attributes and data. | ||
// The character count (numChars) must agree with the mode and the bit buffer length, | ||
// but the constraint isn't checked. The given bit buffer is cloned and stored. | ||
constructor(mode, numChars, bitData) { | ||
if (this.mode = mode, this.numChars = numChars, this.bitData = bitData, numChars < 0) throw new RangeError("Invalid argument"); | ||
this.bitData = bitData.slice(); | ||
} | ||
/*-- Methods --*/ | ||
@@ -869,7 +519,2 @@ // Returns a new copy of the data bits of this segment. | ||
class Ecc { | ||
// The QR Code can tolerate about 30% erroneous codewords | ||
/*-- Constructor and fields --*/ | ||
constructor(ordinal, formatBits) { | ||
this.ordinal = ordinal, this.formatBits = formatBits; | ||
} | ||
/*-- Constants --*/ | ||
@@ -883,8 +528,9 @@ static LOW = new Ecc(0, 1); | ||
static HIGH = new Ecc(3, 2); | ||
// The QR Code can tolerate about 30% erroneous codewords | ||
/*-- Constructor and fields --*/ | ||
constructor(ordinal, formatBits) { | ||
this.ordinal = ordinal, this.formatBits = formatBits; | ||
} | ||
} | ||
class Mode { | ||
/*-- Constructor and fields --*/ | ||
constructor(modeBits, numBitsCharCount) { | ||
this.modeBits = modeBits, this.numBitsCharCount = numBitsCharCount; | ||
} | ||
/*-- Constants --*/ | ||
@@ -896,2 +542,6 @@ static NUMERIC = new Mode(1, [10, 12, 14]); | ||
static ECI = new Mode(7, [0, 0, 0]); | ||
/*-- Constructor and fields --*/ | ||
constructor(modeBits, numBitsCharCount) { | ||
this.modeBits = modeBits, this.numBitsCharCount = numBitsCharCount; | ||
} | ||
/*-- Method --*/ | ||
@@ -936,3 +586,14 @@ // (Package-private) Returns the bit width of the character count field for a segment in | ||
const scale = (cells.length + margin * 2) / size, w = logoSize * scale, h = logoSize * scale, x = cells.length / 2 - w / 2, y = cells.length / 2 - h / 2, floorX = Math.floor(x), floorY = Math.floor(y), ceilW = Math.ceil(w + x - floorX), ceilH = Math.ceil(h + y - floorY); | ||
return { x, y, h, w, excavation: { x: floorX, y: floorY, w: ceilW, h: ceilH } }; | ||
return { | ||
x, | ||
y, | ||
h, | ||
w, | ||
excavation: { | ||
x: floorX, | ||
y: floorY, | ||
w: ceilW, | ||
h: ceilH | ||
} | ||
}; | ||
} | ||
@@ -954,9 +615,14 @@ function getMarginSize(includeMargin, marginSize) { | ||
return QrCode.encodeSegments(segments, ERROR_LEVEL_MAP[level], minVersion); | ||
}, [value, level, minVersion]), { cells, margin, numCells, calculatedImageSettings } = useMemo(() => { | ||
const cells2 = qrcode.getModules(), margin2 = getMarginSize(includeMargin, marginSize), numCells2 = cells2.length + margin2 * 2, calculatedImageSettings2 = getImageSettings(cells2, size, margin2, logoSize); | ||
}, [value, level, minVersion]), { | ||
cells: cells_0, | ||
margin: margin_0, | ||
numCells: numCells_0, | ||
calculatedImageSettings: calculatedImageSettings_0 | ||
} = useMemo(() => { | ||
const cells = qrcode.getModules(), margin = getMarginSize(includeMargin, marginSize), numCells = cells.length + margin * 2, calculatedImageSettings = getImageSettings(cells, size, margin, logoSize); | ||
return { | ||
cells: cells2, | ||
margin: margin2, | ||
numCells: numCells2, | ||
calculatedImageSettings: calculatedImageSettings2 | ||
cells, | ||
margin, | ||
numCells, | ||
calculatedImageSettings | ||
}; | ||
@@ -966,6 +632,6 @@ }, [qrcode, size, logoSize, includeMargin, marginSize]); | ||
qrcode, | ||
margin, | ||
cells, | ||
numCells, | ||
calculatedImageSettings | ||
margin: margin_0, | ||
cells: cells_0, | ||
numCells: numCells_0, | ||
calculatedImageSettings: calculatedImageSettings_0 | ||
}; | ||
@@ -982,3 +648,8 @@ } | ||
logoSize | ||
} = props, marginSize = void 0, { margin, cells, numCells, calculatedImageSettings } = useQRCode({ | ||
} = props, marginSize = void 0, { | ||
margin, | ||
cells, | ||
numCells, | ||
calculatedImageSettings | ||
} = useQRCode({ | ||
value, | ||
@@ -991,19 +662,12 @@ level, | ||
size | ||
}), cellsToDraw = useMemo( | ||
() => logoSize && calculatedImageSettings?.excavation ? excavateModules(cells, calculatedImageSettings.excavation) : cells, | ||
[calculatedImageSettings?.excavation, cells, logoSize] | ||
), fgPath = generatePath(cellsToDraw, margin); | ||
}), cellsToDraw = useMemo(() => logoSize && calculatedImageSettings?.excavation ? excavateModules(cells, calculatedImageSettings.excavation) : cells, [calculatedImageSettings?.excavation, cells, logoSize]), fgPath = generatePath(cellsToDraw, margin); | ||
return /* @__PURE__ */ jsxs("svg", { height: size, width: size, viewBox: `0 0 ${numCells} ${numCells}`, role: "img", children: [ | ||
!!title && /* @__PURE__ */ jsx("title", { children: title }), | ||
/* @__PURE__ */ jsx( | ||
motion.path, | ||
{ | ||
fill: color, | ||
d: fgPath, | ||
shapeRendering: "crispEdges", | ||
initial: { opacity: 0 }, | ||
animate: { opacity: 2 }, | ||
exit: { opacity: -1 } | ||
} | ||
) | ||
/* @__PURE__ */ jsx(motion.path, { fill: color, d: fgPath, shapeRendering: "crispEdges", initial: { | ||
opacity: 0 | ||
}, animate: { | ||
opacity: 2 | ||
}, exit: { | ||
opacity: -1 | ||
} }) | ||
] }); | ||
@@ -1010,0 +674,0 @@ } |
{ | ||
"name": "@sanity/presentation", | ||
"version": "1.18.5", | ||
"version": "1.19.0", | ||
"homepage": "https://github.com/sanity-io/visual-editing/tree/main/packages/presentation#readme", | ||
@@ -55,12 +55,14 @@ "bugs": { | ||
"path-to-regexp": "^6.3.0", | ||
"react-compiler-runtime": "19.0.0-beta-df7b47d-20241124", | ||
"rxjs": "^7.8.1", | ||
"suspend-react": "0.1.3", | ||
"use-effect-event": "^1.0.2", | ||
"@sanity/comlink": "1.1.4", | ||
"@sanity/preview-url-secret": "2.0.4" | ||
"@sanity/preview-url-secret": "2.0.4", | ||
"@sanity/comlink": "1.1.4" | ||
}, | ||
"devDependencies": { | ||
"@sanity/client": "^6.22.5", | ||
"@sanity/pkg-utils": "6.11.12", | ||
"@sanity/pkg-utils": "6.11.13", | ||
"@types/lodash.get": "^4.4.9", | ||
"babel-plugin-react-compiler": "19.0.0-beta-df7b47d-20241124", | ||
"eslint": "^8.57.1", | ||
@@ -70,10 +72,10 @@ "happy-dom": "^15.11.6", | ||
"react-dom": "^18.3.1", | ||
"sanity": "^3.64.2", | ||
"sanity": "^3.65.0", | ||
"styled-components": "6.1.13", | ||
"typescript": "5.6.3", | ||
"vitest": "^2.1.5", | ||
"@repo/eslint-config": "0.0.0", | ||
"@repo/package.config": "0.0.0", | ||
"@repo/prettier-config": "0.0.0", | ||
"@repo/visual-editing-helpers": "0.7.4", | ||
"@repo/eslint-config": "0.0.0" | ||
"@repo/visual-editing-helpers": "0.7.4" | ||
}, | ||
@@ -80,0 +82,0 @@ "peerDependencies": { |
import {usePresentationTool} from '../usePresentationTool' | ||
export function useCurrentPresentationToolName(): string | undefined { | ||
try { | ||
return usePresentationTool().name | ||
} catch { | ||
return undefined | ||
} | ||
return usePresentationTool(false)?.name ?? undefined | ||
} |
@@ -1,7 +0,7 @@ | ||
import {useRef} from 'react' | ||
import {useState} from 'react' | ||
import {v4 as uuid} from 'uuid' | ||
export function usePanelId(id?: string): string { | ||
const idRef = useRef(id || uuid()) | ||
return idRef.current | ||
const [panelId] = useState(() => id || uuid()) | ||
return panelId | ||
} |
@@ -5,2 +5,3 @@ import type {ClientPerspective} from '@sanity/client' | ||
import type {FrameState, PresentationPerspective} from './types' | ||
import {defineWarnOnce} from './util/warnOnce' | ||
@@ -15,3 +16,3 @@ export type DocumentOnPage = { | ||
let warnedAboutCrossDatasetReference = false | ||
const warnOnceAboutCrossDatasetReference = defineWarnOnce() | ||
@@ -42,10 +43,7 @@ export function useDocumentsOnPage( | ||
// @TODO Handle cross dataset references | ||
if (!warnedAboutCrossDatasetReference) { | ||
// eslint-disable-next-line no-console | ||
console.warn( | ||
'Cross dataset references are not supported yet, ignoring source document', | ||
sourceDocument, | ||
) | ||
warnedAboutCrossDatasetReference = true | ||
} | ||
warnOnceAboutCrossDatasetReference( | ||
'Cross dataset references are not supported yet, ignoring source document', | ||
sourceDocument, | ||
) | ||
return false | ||
@@ -52,0 +50,0 @@ } |
import {useContext} from 'react' | ||
import {PresentationContext, type PresentationContextValue} from './PresentationContext' | ||
export function usePresentationTool(): PresentationContextValue { | ||
export function usePresentationTool(throwOnMissingContext?: true): PresentationContextValue | ||
export function usePresentationTool(throwOnMissingContext: false): PresentationContextValue | null | ||
export function usePresentationTool(throwOnMissingContext = true): PresentationContextValue | null { | ||
const presentation = useContext(PresentationContext) | ||
if (!presentation) { | ||
if (throwOnMissingContext && !presentation) { | ||
throw new Error('Presentation context is missing') | ||
@@ -9,0 +11,0 @@ } |
@@ -1,2 +0,3 @@ | ||
import {useCallback, useEffect, useRef, type DependencyList} from 'react' | ||
import {useEffect, useRef} from 'react' | ||
import {useEffectEvent} from 'use-effect-event' | ||
@@ -7,3 +8,2 @@ /** | ||
* @param callback - The callback to execute when the value changes. | ||
* @param dependencies - The callback dependencies. | ||
* @param initialValue - An optional initial value to compare against. | ||
@@ -15,4 +15,3 @@ * @param comparator - An optional comparator function for determining changes, useful if the value is non-primitive. Should return true if the callback should be executed. | ||
value: T, | ||
callback: (value: T, prevValue: T | undefined) => void | (() => void), | ||
dependencies: DependencyList, | ||
_callback: (value: T, prevValue: T | undefined) => void | (() => void), | ||
initialValue?: T, | ||
@@ -22,6 +21,4 @@ comparator?: (a: T, b?: T) => boolean | undefined, | ||
const previousValueRef = useRef<T | undefined>(initialValue) | ||
const callback = useEffectEvent(_callback) | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
const _callback = useCallback(callback, dependencies) | ||
useEffect(() => { | ||
@@ -31,5 +28,5 @@ const prev = previousValueRef.current | ||
if (comparator ? comparator(value, prev) : value !== prev) { | ||
return _callback(value, prev) | ||
return callback(value, prev) | ||
} | ||
}, [_callback, comparator, value]) | ||
}, [callback, comparator, value]) | ||
} |
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
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 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
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
2405779
159
22113
19
16
+ Addedreact-compiler-runtime@19.0.0-beta-df7b47d-20241124(transitive)
- Removedreact-compiler-runtime@19.0.0-beta-201e55d-20241215(transitive)