@sanity/assist
Version:
You create the instructions; Sanity AI Assist does the rest.
1,130 lines (1,129 loc) • 220 kB
JavaScript
import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { pathToString, isVersionId, getVersionFromId, getPublishedId, useEditState, useCurrentUser, useClient, typed, isObjectSchemaType, stringToPath, isKeySegment, FormFieldHeaderText, PatchEvent, unset, useSchema, usePerspective, getVersionId, getDraftId, useColorSchemeValue, isArraySchemaType, useFormCallbacks, useDocumentStore, useDocumentPresence, createPatchChannel, FormBuilder, fromMutationPatches, StatusButton, PresenceOverlay, VirtualizerScrollInstanceProvider, PerspectiveProvider, isDocumentSchemaType, isRecord, useSyncState, set, useWorkspaceSchemaId, MemberFieldError, FormCallbacksProvider, FormInput, setIfMissing, insert, ObjectInputMember, isArrayOfObjectsSchemaType, defineType, defineField, defineArrayMember, definePlugin } from "sanity";
import { c } from "react/compiler-runtime";
import { useToast, useLayer, Dialog, Stack, Flex, Tooltip, Text, Button, TextArea, Card, Box, ErrorBoundary, focusFirstDescendant, Spinner, Container, Autocomplete, Breadcrumbs, useClickOutside, Popover, useGlobalKeyDown, useTheme, rgba, Checkbox, Radio, ThemeProvider, MenuButton, MenuItem, Menu, Switch, Label } from "@sanity/ui";
import { useDocumentPane, usePaneRouter, DocumentPaneProvider, DocumentInspectorHeader } from "sanity/structure";
import { useRef, useState, useEffect, createContext, useContext, useCallback, useId, forwardRef, useMemo, useEffectEvent, useReducer } from "react";
import { minutesToMilliseconds, isAfter, addSeconds, formatDistanceToNow } from "date-fns";
import { DocumentIcon, LinkIcon, ImageIcon, BlockContentIcon, OlistIcon, BlockquoteIcon, StringIcon, PlayIcon, SparklesIcon, SearchIcon, SyncIcon, ErrorOutlineIcon, CheckmarkCircleIcon, ClockIcon, CloseCircleIcon, ArrowRightIcon, RetryIcon, CloseIcon, icons, TranslateIcon, LockIcon, ControlsIcon, ArrowLeftIcon, TokenIcon, DocumentTextIcon, ThListIcon, CodeIcon, ComposeIcon } from "@sanity/icons";
import { extractWithPath } from "@sanity/mutator";
import { keyframes, styled } from "styled-components";
import { purple } from "@sanity/color";
import { tap, mergeMap, share, take, filter, distinctUntilChanged, catchError } from "rxjs/operators";
import get from "lodash-es/get.js";
import isEqual from "react-fast-compare";
import { throwError, of, partition, merge, switchMap, delay, defer } from "rxjs";
import { exhaustMapToWithTrailing } from "rxjs-exhaustmap-with-trailing";
function hasOverflowScroll(el) {
const overflow = getComputedStyle(el).overflow;
return overflow.includes("auto") || overflow.includes("hidden") || overflow.includes("scroll");
}
function useRegionRects() {
const $ = c(13), ref = useRef(null), [relativeBoundsRect, setRelativeBoundsRect] = useState(null), [relativeElementRect, setRelativeElementRect] = useState(null);
let t0;
$[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {
x: 0,
y: 0
}, $[0] = t0) : t0 = $[0];
const [boundsScroll, setBoundsScroll] = useState(t0);
let t1;
$[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = {
x: 0,
y: 0
}, $[1] = t1) : t1 = $[1];
const [scroll, setScroll] = useState(t1), boundsScrollXRef = useRef(0), boundsScrollYRef = useRef(0), elementScrollXRef = useRef(0), elementScrollYRef = useRef(0);
let t2, t3;
$[2] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = () => {
const el = ref.current;
if (!el)
return;
const scrollParents = [];
let parent = el.parentElement;
for (; parent && parent !== document.body; )
hasOverflowScroll(parent) && scrollParents.push(parent), parent = parent.parentElement;
const handleResize = function() {
const boundsRect = scrollParents[0]?.getBoundingClientRect() || {
x: 0,
y: 0,
width: window.innerWidth,
height: window.innerHeight
}, domRect = el.getBoundingClientRect();
setRelativeBoundsRect({
x: boundsRect.x + boundsScrollXRef.current,
y: boundsRect.y + boundsScrollYRef.current,
w: boundsRect.width,
h: boundsRect.height
}), setRelativeElementRect({
x: domRect.x + elementScrollXRef.current,
y: domRect.y + elementScrollYRef.current,
w: domRect.width,
h: domRect.height
});
}, handleScroll = function() {
let scrollX = window.scrollX, scrollY = window.scrollY;
for (const scrollParent_0 of scrollParents)
scrollX = scrollX + scrollParent_0.scrollLeft, scrollY = scrollY + scrollParent_0.scrollTop;
const scrollParent_1 = scrollParents[0];
boundsScrollXRef.current = scrollX - (scrollParent_1?.scrollLeft || window.scrollX), boundsScrollYRef.current = scrollY - (scrollParent_1?.scrollTop || window.scrollY), setBoundsScroll({
x: boundsScrollXRef.current,
y: boundsScrollYRef.current
}), elementScrollXRef.current = scrollX, elementScrollYRef.current = scrollY, setScroll({
x: scrollX,
y: scrollY
});
};
window.addEventListener("scroll", handleScroll, {
passive: !0
});
const ro = new ResizeObserver(handleResize);
ro.observe(el);
for (const scrollParent_2 of scrollParents)
scrollParent_2.addEventListener("scroll", handleScroll, {
passive: !0
}), ro.observe(scrollParent_2);
return handleScroll(), () => {
ro.unobserve(el);
for (const scrollParent_3 of scrollParents)
ro.unobserve(scrollParent_3), scrollParent_3.removeEventListener("scroll", handleScroll);
ro.disconnect(), window.removeEventListener("scroll", handleScroll);
};
}, t3 = [], $[2] = t2, $[3] = t3) : (t2 = $[2], t3 = $[3]), useEffect(t2, t3);
let t4;
$[4] !== boundsScroll || $[5] !== relativeBoundsRect ? (t4 = relativeBoundsRect && {
x: relativeBoundsRect.x - boundsScroll.x,
y: relativeBoundsRect.y - boundsScroll.y,
w: relativeBoundsRect.w,
h: relativeBoundsRect.h
}, $[4] = boundsScroll, $[5] = relativeBoundsRect, $[6] = t4) : t4 = $[6];
const bounds = t4;
let t5;
$[7] !== relativeElementRect || $[8] !== scroll ? (t5 = relativeElementRect && {
x: relativeElementRect.x - scroll.x,
y: relativeElementRect.y - scroll.y,
w: relativeElementRect.w,
h: relativeElementRect.h
}, $[7] = relativeElementRect, $[8] = scroll, $[9] = t5) : t5 = $[9];
const element = t5;
let t6;
return $[10] !== bounds || $[11] !== element ? (t6 = {
bounds,
element,
ref
}, $[10] = bounds, $[11] = element, $[12] = t6) : t6 = $[12], t6;
}
function ConnectorRegion(props) {
const $ = c(13);
let children, onRectsChange, restProps;
$[0] !== props ? ({
children,
onRectsChange,
...restProps
} = props, $[0] = props, $[1] = children, $[2] = onRectsChange, $[3] = restProps) : (children = $[1], onRectsChange = $[2], restProps = $[3]);
const {
bounds,
element,
ref
} = useRegionRects();
let t0, t1;
$[4] !== bounds || $[5] !== element || $[6] !== onRectsChange ? (t0 = () => {
onRectsChange?.(bounds && element ? {
bounds,
element
} : null);
}, t1 = [bounds, element, onRectsChange], $[4] = bounds, $[5] = element, $[6] = onRectsChange, $[7] = t0, $[8] = t1) : (t0 = $[7], t1 = $[8]), useEffect(t0, t1);
let t2;
return $[9] !== children || $[10] !== ref || $[11] !== restProps ? (t2 = /* @__PURE__ */ jsx("div", { ...restProps, ref, children }), $[9] = children, $[10] = ref, $[11] = restProps, $[12] = t2) : t2 = $[12], t2;
}
const ConnectorsStoreContext = createContext(null);
function useConnectorsStore() {
const store = useContext(ConnectorsStoreContext);
if (!store)
throw new Error("Missing connectors store context");
return store;
}
function ConnectFromRegion(props) {
const $ = c(24);
let children, key, restProps, zIndex;
$[0] !== props ? ({
children,
_key: key,
zIndex,
...restProps
} = props, $[0] = props, $[1] = children, $[2] = key, $[3] = restProps, $[4] = zIndex) : (children = $[1], key = $[2], restProps = $[3], zIndex = $[4]);
const store = useConnectorsStore(), [rects, setRects] = useState(null);
let t0;
$[5] !== key || $[6] !== store.from || $[7] !== zIndex ? (t0 = () => store.from.subscribe(key, {
zIndex
}), $[5] = key, $[6] = store.from, $[7] = zIndex, $[8] = t0) : t0 = $[8];
let t1;
$[9] !== key || $[10] !== store || $[11] !== zIndex ? (t1 = [key, store, zIndex], $[9] = key, $[10] = store, $[11] = zIndex, $[12] = t1) : t1 = $[12], useEffect(t0, t1);
let t2;
$[13] !== key || $[14] !== rects || $[15] !== store.from ? (t2 = () => {
rects && store.from.next(key, rects);
}, $[13] = key, $[14] = rects, $[15] = store.from, $[16] = t2) : t2 = $[16];
let t3;
$[17] !== key || $[18] !== rects || $[19] !== store ? (t3 = [key, rects, store], $[17] = key, $[18] = rects, $[19] = store, $[20] = t3) : t3 = $[20], useEffect(t2, t3);
let t4;
return $[21] !== children || $[22] !== restProps ? (t4 = /* @__PURE__ */ jsx(ConnectorRegion, { ...restProps, onRectsChange: setRects, children }), $[21] = children, $[22] = restProps, $[23] = t4) : t4 = $[23], t4;
}
function createConnectorsStore() {
const configKeys = [], fieldKeys = [], channels = {
from: /* @__PURE__ */ new Map(),
to: /* @__PURE__ */ new Map()
}, payloads = {
from: /* @__PURE__ */ new Map(),
to: /* @__PURE__ */ new Map()
}, observers = [];
function notifyObservers() {
const connectors = [];
for (const key of configKeys) {
const toRects = channels.to.get(key), toPayload = payloads.from.get(key), fromRects = channels.from.get(key), fromPayload = payloads.from.get(key);
toRects && fromRects && connectors.push({
key,
from: {
...fromRects,
payload: fromPayload
},
to: {
...toRects,
payload: toPayload
}
});
}
for (const observer of observers)
observer(connectors);
}
return {
to: {
subscribe(key, payload) {
return channels.to.set(key, null), payloads.to.set(key, payload), configKeys.push(key), () => {
channels.to.delete(key), payloads.to.delete(key);
const idx = configKeys.indexOf(key);
idx > -1 && configKeys.splice(idx, 1), notifyObservers();
};
},
next(key, rects) {
channels.to.set(key, rects), fieldKeys.includes(key) && notifyObservers();
}
},
connectors: {
subscribe(observer) {
return observers.push(observer), () => {
const idx = observers.indexOf(observer);
idx > -1 && observers.splice(idx, 1);
};
}
},
from: {
subscribe(key, payload) {
return channels.from.set(key, null), payloads.from.set(key, payload), fieldKeys.push(key), () => {
channels.from.delete(key), payloads.from.delete(key);
const idx = fieldKeys.indexOf(key);
idx > -1 && fieldKeys.splice(idx, 1), notifyObservers();
};
},
next(key, rects) {
channels.from.set(key, rects), configKeys.includes(key) && notifyObservers();
}
}
};
}
function ConnectorsProvider(props) {
const $ = c(6), {
children,
onConnectorsChange
} = props;
let t0;
$[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = createConnectorsStore(), $[0] = t0) : t0 = $[0];
const store = t0;
let t1, t2;
$[1] !== onConnectorsChange ? (t1 = () => onConnectorsChange && store.connectors.subscribe(onConnectorsChange), t2 = [onConnectorsChange, store], $[1] = onConnectorsChange, $[2] = t1, $[3] = t2) : (t1 = $[2], t2 = $[3]), useEffect(t1, t2);
let t3;
return $[4] !== children ? (t3 = /* @__PURE__ */ jsx(ConnectorsStoreContext.Provider, { value: store, children }), $[4] = children, $[5] = t3) : t3 = $[5], t3;
}
function getConnectorLinePoint(options2, rect, bounds) {
const centerY = rect.y + rect.h / 2, isAbove = rect.y + rect.h < bounds.y + options2.arrow.marginY, isBelow = rect.y > bounds.y + bounds.h - options2.arrow.marginY;
return {
bounds,
x: rect.x,
y: centerY,
centerY,
startY: rect.y + options2.path.marginY,
endY: rect.y + rect.h - options2.path.marginY,
isAbove,
isBelow,
outOfBounds: isAbove || isBelow
};
}
function mapConnectorToLine(options2, connector) {
const fromBounds = {
y: connector.from.bounds.y + options2.arrow.threshold,
// bottom: connector.from.bounds.y + connector.from.bounds.h - options.arrow.threshold,
x: connector.from.bounds.x,
// right: connector.from.bounds.x + connector.from.bounds.w,
w: connector.from.bounds.w,
h: connector.from.bounds.h - options2.arrow.threshold * 2
}, from = getConnectorLinePoint(options2, connector.from.element, fromBounds);
from.x = connector.from.element.x + connector.from.element.w;
const fromBottom = fromBounds.y + fromBounds.h, toBounds = {
y: connector.to.bounds.y + options2.arrow.threshold,
// bottom: connector.to.bounds.y + connector.to.bounds.h - options.arrow.threshold,
x: connector.to.bounds.x,
// right: connector.to.bounds.x + connector.to.bounds.w,
w: connector.to.bounds.w,
h: connector.to.bounds.h - options2.arrow.threshold * 2
}, toBottom = toBounds.y + toBounds.h, to = getConnectorLinePoint(options2, connector.to.element, toBounds), maxStartY = Math.max(to.startY, from.startY);
return from.y = Math.min(maxStartY, from.endY), from.y < toBounds.y ? from.y = Math.min(toBounds.y, from.endY) : from.y > toBottom && (from.y = Math.max(toBottom, from.startY)), to.y = Math.min(maxStartY, to.endY), to.y < fromBounds.y ? to.y = Math.min(fromBounds.y, to.endY) : to.y > fromBottom && (to.y = Math.max(fromBottom, to.startY)), from.y = Math.min(Math.max(from.y, fromBounds.y), fromBottom), to.y = Math.min(Math.max(to.y, toBounds.y), toBottom), {
from,
to
};
}
const assistFormId = "assist", assistDocumentIdPrefix = "sanity.assist.schemaType.", assistDocumentStatusIdPrefix = "sanity.assist.status.", assistSchemaIdPrefix = "sanity.assist.schema.", assistDocumentTypeName = "sanity.assist.schemaType.annotations", assistFieldTypeName = "sanity.assist.schemaType.field", instructionTypeName = "sanity.assist.instruction", promptTypeName = "sanity.assist.instruction.prompt", userInputTypeName = "sanity.assist.instruction.userInput", instructionContextTypeName = "sanity.assist.instruction.context", fieldReferenceTypeName = "sanity.assist.instruction.fieldRef", contextDocumentTypeName = "assist.instruction.context", assistTasksStatusTypeName = "sanity.assist.task.status", instructionTaskTypeName = "sanity.assist.instructionTask", fieldPresenceTypeName = "sanity.assist.instructionTask.presence", assistSerializedTypeName = "sanity.assist.serialized.type", assistSerializedFieldTypeName = "sanity.assist.serialized.field", outputFieldTypeName = "sanity.assist.output.field", outputTypeTypeName = "sanity.assist.output.type", fieldPathParam = "pathKey", instructionParam = "instruction", documentRootKey = "<document>";
function usePathKey(path) {
const $ = c(2);
let t0;
return $[0] !== path ? (t0 = getPathKey(path), $[0] = path, $[1] = t0) : t0 = $[1], t0;
}
function getPathKey(path) {
return path.length ? Array.isArray(path) ? pathToString(path) : path : documentRootKey;
}
function getInstructionTitle(instruction2) {
return instruction2?.title ?? "Untitled";
}
function isDefined(t) {
return t != null;
}
function isPortableTextArray(type) {
return type.of.find((t) => isType(t, "block"));
}
function isType(schemaType, typeName) {
return schemaType.name === typeName ? !0 : schemaType.type ? isType(schemaType.type, typeName) : !1;
}
function isImage(schemaType) {
return isType(schemaType, "image");
}
function getDescriptionFieldOption(schemaType) {
if (!schemaType)
return;
const descriptionField = schemaType.options?.aiAssist?.imageDescriptionField;
return typeof descriptionField == "string" ? {
path: descriptionField,
updateOnImageChange: !0
} : descriptionField ? {
path: descriptionField.path,
updateOnImageChange: descriptionField.updateOnImageChange ?? !0
} : getDescriptionFieldOption(schemaType.type);
}
function getImageInstructionFieldOption(schemaType) {
return schemaType ? schemaType.options?.aiAssist?.imageInstructionField || getImageInstructionFieldOption(schemaType.type) : void 0;
}
function isSchemaAssistEnabled(type) {
return !type.options?.aiAssist?.exclude;
}
function isAssistSupported(type) {
return !isSchemaAssistEnabled(type) || isDisabled(type) ? !1 : type.jsonType === "array" ? !type.of.every((t) => isDisabled(t)) : type.jsonType === "object" ? !type.fields.every((field) => isDisabled(field.type)) || /* to allow attaching custom actions on fieldless images */
isType(type, "image") : !0;
}
function isDisabled(type) {
return !isSchemaAssistEnabled(type) || isUnsupportedType(type);
}
function isUnsupportedType(type) {
return type.name === "sanity.imageCrop" || type.name === "sanity.imageHotspot" || isType(type, "globalDocumentReference") || isType(type, "reference") && // oxlint-disable-next-line no-unsafe-type-assertion
!type?.options?.aiAssist?.embeddingsIndex || isType(type, "crossDatasetReference") || isType(type, "file");
}
const FirstAssistedPathContext = createContext(void 0);
function FirstAssistedPathProvider(props) {
const $ = c(5), {
members
} = props;
let t0;
if ($[0] !== members) {
const firstAssisted = members.find(_temp$f);
t0 = firstAssisted?.field.path ? pathToString(firstAssisted?.field.path) : void 0, $[0] = members, $[1] = t0;
} else
t0 = $[1];
const firstAssistedPath = t0;
let t1;
return $[2] !== firstAssistedPath || $[3] !== props.children ? (t1 = /* @__PURE__ */ jsx(FirstAssistedPathContext.Provider, { value: firstAssistedPath, children: props.children }), $[2] = firstAssistedPath, $[3] = props.children, $[4] = t1) : t1 = $[4], t1;
}
function _temp$f(member) {
return member.kind === "field" && isAssistSupported(member.field.schemaType);
}
const releaseAnnouncementUrl = "https://www.sanity.io/blog/sanity-ai-assist-announcement?utm_source=sanity-assist-plugin&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=", instructionGuideUrl = "https://sanity.io/guides/getting-started-with-ai-assist-instructions?utm_source=sanity-assist-plugin&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=", giveFeedbackUrl = "https://forms.gle/Kwz7CThxGeA2GiEU8", salesUrl = "https://www.sanity.io/contact/sales?utm_source=sanity-assist-plugin&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=", packageName = "@sanity/assist", pluginTitle = "Sanity AI Assist", pluginTitleShort = "AI Assist", maxHistoryVisibilityMs = minutesToMilliseconds(30), illegalIdChars = /[^a-zA-Z0-9._-]/g;
function assistDocumentId(documentType) {
return `${assistDocumentIdPrefix}${documentType}`.replace(illegalIdChars, "_");
}
function assistTasksStatusId(documentId) {
return isVersionId(documentId) ? `${assistDocumentStatusIdPrefix}${getVersionFromId(documentId)}.${getPublishedId(documentId)}` : `${assistDocumentStatusIdPrefix}${getPublishedId(documentId)}`;
}
function useDocumentState(id, docType) {
const state = useEditState(id, docType);
return state.draft || state.published;
}
function useStudioAssistDocument(t0) {
const $ = c(15), {
documentId,
schemaType,
initDoc
} = t0, documentTypeName = schemaType.name, currentUser = useCurrentUser();
let t1;
$[0] !== documentTypeName ? (t1 = assistDocumentId(documentTypeName), $[0] = documentTypeName, $[1] = t1) : t1 = $[1];
const assistDocument = useDocumentState(t1, assistDocumentTypeName), t2 = documentId ?? "";
let t3;
$[2] !== t2 ? (t3 = assistTasksStatusId(t2), $[2] = t2, $[3] = t3) : t3 = $[3];
const assistTasksStatus = useDocumentState(t3, assistTasksStatusTypeName);
let t4;
$[4] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t4 = {
apiVersion: "2023-01-01"
}, $[4] = t4) : t4 = $[4];
const client = useClient(t4);
let t5, t6;
$[5] !== assistDocument || $[6] !== client || $[7] !== documentTypeName || $[8] !== initDoc ? (t5 = () => {
!assistDocument && initDoc && client.createIfNotExists({
_id: assistDocumentId(documentTypeName),
_type: assistDocumentTypeName
}).catch(_temp$e);
}, t6 = [client, assistDocument, documentTypeName, initDoc], $[5] = assistDocument, $[6] = client, $[7] = documentTypeName, $[8] = initDoc, $[9] = t5, $[10] = t6) : (t5 = $[9], t6 = $[10]), useEffect(t5, t6);
let t7;
bb0: {
if (!assistDocument) {
t7 = void 0;
break bb0;
}
let t8;
if ($[11] !== assistDocument || $[12] !== assistTasksStatus?.tasks || $[13] !== currentUser?.id) {
const tasks = assistTasksStatus?.tasks ?? [], fields = (assistDocument?.fields ?? []).map((assistField) => ({
...assistField,
tasks: tasks.filter((task) => task.path === assistField.path),
instructions: assistField.instructions?.filter((p) => !p.userId || p.userId === currentUser?.id).map((instruction2) => asStudioInstruction(instruction2, tasks))
}));
t8 = typed({
...assistDocument,
tasks: tasks?.map((task_0) => {
const instruction_0 = fields.find((f) => f.path === task_0.path)?.instructions?.find((i) => i._key === task_0.instructionKey);
return {
...task_0,
instruction: instruction_0
};
}),
fields
}), $[11] = assistDocument, $[12] = assistTasksStatus?.tasks, $[13] = currentUser?.id, $[14] = t8;
} else
t8 = $[14];
t7 = t8;
}
return t7;
}
function _temp$e() {
}
function asStudioInstruction(instruction2, run) {
return {
...instruction2,
tasks: run.filter((task) => task.instructionKey === instruction2._key).filter((task) => task.started && (/* @__PURE__ */ new Date()).getTime() - new Date(task.started).getTime() < maxHistoryVisibilityMs)
};
}
const NO_TASKS = [];
function useInstructionToaster(documentId, documentSchemaType) {
const $ = c(13);
let t0;
$[0] !== documentId || $[1] !== documentSchemaType ? (t0 = {
documentId,
schemaType: documentSchemaType
}, $[0] = documentId, $[1] = documentSchemaType, $[2] = t0) : t0 = $[2];
const assistDocument = useStudioAssistDocument(t0), assistDocLoaded = !!assistDocument, currentUser = useCurrentUser(), toast = useToast(), tasks = assistDocument?.tasks, previousTasks = useRef("initial");
let t1;
$[3] !== assistDocLoaded || $[4] !== currentUser?.id || $[5] !== tasks || $[6] !== toast ? (t1 = () => {
if (assistDocLoaded) {
if (previousTasks.current !== "initial") {
const prevTaskByKey = Object.fromEntries((previousTasks.current ?? NO_TASKS).map(_temp$d));
tasks?.filter((task) => task.startedByUserId === currentUser?.id).filter((task_0) => {
const prevTask = prevTaskByKey[task_0._key];
return !prevTask && task_0.ended || !prevTask?.ended && task_0.ended;
}).filter(_temp2$7)?.forEach((task_2) => {
const title = task_2.title ?? getInstructionTitle(task_2.instruction);
task_2.reason === "error" ? toast.push({
title: `Failed: ${title}`,
status: "error",
description: `Instruction failed. ${task_2.message ?? ""}`,
closable: !0,
duration: 1e4
}) : task_2.reason === "timeout" ? toast.push({
title: `Timeout: ${title}`,
status: "error",
description: "Instruction timed out.",
closable: !0
}) : task_2.reason === "success" ? toast.push({
title: `Success: ${title}`,
status: "success",
description: "Instruction completed.",
closable: !0
}) : task_2.reason === "aborted" && toast.push({
title: `Canceled: ${title}`,
status: "warning",
description: "Instruction canceled.",
closable: !0
});
});
}
previousTasks.current = tasks;
}
}, $[3] = assistDocLoaded, $[4] = currentUser?.id, $[5] = tasks, $[6] = toast, $[7] = t1) : t1 = $[7];
let t2;
$[8] !== assistDocLoaded || $[9] !== currentUser || $[10] !== tasks || $[11] !== toast ? (t2 = [tasks, previousTasks, toast, currentUser, assistDocLoaded], $[8] = assistDocLoaded, $[9] = currentUser, $[10] = tasks, $[11] = toast, $[12] = t2) : t2 = $[12], useEffect(t1, t2);
}
function _temp2$7(task_1) {
return task_1.ended && isAfter(addSeconds(new Date(task_1.ended), 30), /* @__PURE__ */ new Date());
}
function _temp$d(run) {
return [run._key, run];
}
function AssistDocumentInputWrapper(props) {
const $ = c(7);
if (!isType(props.schemaType, "document") && props.id !== "root" && props.id !== assistFormId) {
let t02;
return $[0] !== props ? (t02 = /* @__PURE__ */ jsx(AssistInput, { ...props }), $[0] = props, $[1] = t02) : t02 = $[1], t02;
}
const documentId = props.value?._id;
if (!documentId) {
let t02;
return $[2] !== props ? (t02 = props.renderDefault(props), $[2] = props, $[3] = t02) : t02 = $[3], t02;
}
const t0 = props;
let t1;
return $[4] !== documentId || $[5] !== t0 ? (t1 = /* @__PURE__ */ jsx(AssistDocumentInput, { ...t0, documentId }), $[4] = documentId, $[5] = t0, $[6] = t1) : t1 = $[6], t1;
}
function AssistDocumentInput(t0) {
const $ = c(14);
let documentId, props;
$[0] !== t0 ? ({
documentId,
...props
} = t0, $[0] = t0, $[1] = documentId, $[2] = props) : (documentId = $[1], props = $[2]), useInstructionToaster(documentId, props.schemaType);
let t1;
bb0: {
if (props.schemaType.name !== assistDocumentTypeName) {
t1 = props.schemaType;
break bb0;
}
let t22;
$[3] !== props.schemaType.type ? (t22 = {
...props.schemaType.type,
name: "document"
}, $[3] = props.schemaType.type, $[4] = t22) : t22 = $[4];
let t32;
$[5] !== props.schemaType || $[6] !== t22 ? (t32 = {
...props.schemaType,
type: t22
}, $[5] = props.schemaType, $[6] = t22, $[7] = t32) : t32 = $[7], t1 = t32;
}
const schemaType = t1, t2 = props.members;
let t3;
$[8] !== props || $[9] !== schemaType ? (t3 = props.renderDefault({
...props,
schemaType
}), $[8] = props, $[9] = schemaType, $[10] = t3) : t3 = $[10];
let t4;
return $[11] !== props.members || $[12] !== t3 ? (t4 = /* @__PURE__ */ jsx(FirstAssistedPathProvider, { members: t2, children: t3 }), $[11] = props.members, $[12] = t3, $[13] = t4) : t4 = $[13], t4;
}
function AssistInput(props) {
const $ = c(7), {
zIndex
} = useLayer(), {
paneKey
} = useDocumentPane(), pathKey = usePathKey(props.path), t0 = `${paneKey}_${pathKey}`;
let t1;
$[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = {
minWidth: 0
}, $[0] = t1) : t1 = $[0];
let t2;
$[1] !== props ? (t2 = props.renderDefault(props), $[1] = props, $[2] = t2) : t2 = $[2];
let t3;
return $[3] !== t0 || $[4] !== t2 || $[5] !== zIndex ? (t3 = /* @__PURE__ */ jsx(ConnectFromRegion, { _key: t0, zIndex, style: t1, children: t2 }), $[3] = t0, $[4] = t2, $[5] = zIndex, $[6] = t3) : t3 = $[6], t3;
}
const AssistDocumentContext = createContext(void 0);
function useAssistDocumentContext() {
const context = useContext(AssistDocumentContext);
if (!context)
throw new Error("AssistDocumentContext value is missing");
return context;
}
const AiAssistanceConfigContext = createContext({});
function useAiAssistanceConfig() {
const context = useContext(AiAssistanceConfigContext);
if (!context)
throw new Error("Missing AiAssistanceConfigContext");
return context;
}
function useSerializedTypes() {
return useAiAssistanceConfig().serializedTypes;
}
const maxDepth = 6;
function getTypeIcon(schemaType) {
let t = schemaType;
for (; t; ) {
if (t.icon) return t.icon;
t = t.type;
}
return isType(schemaType, "slug") ? LinkIcon : isType(schemaType, "image") ? ImageIcon : schemaType.jsonType === "array" && isPortableTextArray(schemaType) ? BlockContentIcon : schemaType.jsonType === "array" ? OlistIcon : schemaType.jsonType === "object" ? BlockquoteIcon : schemaType.jsonType === "string" ? StringIcon : DocumentIcon;
}
function asFieldRefsByTypePath(fieldRefs) {
return fieldRefs.reduce((acc, ref) => ({
...acc,
[ref.key]: ref
}), {});
}
function getDocumentFieldRef(schemaType) {
return {
key: documentRootKey,
icon: schemaType.icon ?? DocumentIcon,
title: "The entire document",
path: [],
schemaType
};
}
function getFieldRefs(schemaType, parent, depth = 0) {
return depth >= maxDepth ? [] : schemaType.fields.filter((f) => !f.name.startsWith("_")).flatMap((field) => {
const path = parent ? [...parent.path, field.name] : [field.name], title = field.type.title ?? field.name, fieldRef = {
key: patchableKey(pathToString(path)),
path,
title: parent ? [parent.title, title].join(" / ") : title,
schemaType: field.type,
icon: getTypeIcon(field.type)
}, fields = field.type.jsonType === "object" ? getFieldRefs(field.type, fieldRef, depth + 1) : [], syntheticFields = field.type.jsonType === "array" ? getSyntheticFields(field.type, fieldRef, depth + 1) : [];
return isAssistSupported(field.type) ? [fieldRef, ...fields, ...syntheticFields] : [...fields, ...syntheticFields];
});
}
function getSyntheticFields(schemaType, parent, depth = 0) {
return depth >= maxDepth ? [] : schemaType.of.filter((itemType) => !isType(itemType, "block")).flatMap((itemType) => {
const segment = {
_key: itemType.name
}, title = itemType.title ?? itemType.name, path = parent ? [...parent.path, segment] : [segment], fieldRef = {
key: patchableKey(pathToString(path)),
path,
title: parent ? [parent.title, title].join(" / ") : title,
schemaType: itemType,
icon: getTypeIcon(itemType),
synthetic: !0
}, fields = itemType.jsonType === "object" ? getFieldRefs(itemType, fieldRef, depth + 1) : [];
return isAssistSupported(itemType) ? [fieldRef, ...fields] : fields;
});
}
function getTypePath(doc, pathString) {
if (!pathString)
return;
const path = stringToPath(pathString), currentPath = [];
let valid = !0;
const syntheticPath = path.map((segment) => {
if (currentPath.push(segment), isKeySegment(segment)) {
const match = extractWithPath(pathToString(currentPath), doc)[0], value = match?.value;
if (match && value && typeof value == "object" && "_type" in value)
return {
_key: value._type
};
valid = !1;
}
return segment;
});
return valid ? patchableKey(pathToString(syntheticPath)) : void 0;
}
function patchableKey(pathKey) {
return pathKey.replace(/[=]=/g, ":").replace(/[[\]]/g, "|").replace(/"/g, "");
}
function useTypePath(doc, pathString) {
const $ = c(3);
let t0;
return $[0] !== doc || $[1] !== pathString ? (t0 = getTypePath(doc, pathString), $[0] = doc, $[1] = pathString, $[2] = t0) : t0 = $[2], t0;
}
function useSelectedField(documentSchemaType, path) {
const $ = c(6), {
getFieldRefs: getFieldRefs2
} = useAiAssistanceConfig();
let t0;
$[0] !== documentSchemaType || $[1] !== getFieldRefs2 ? (t0 = documentSchemaType && isObjectSchemaType(documentSchemaType) ? [getDocumentFieldRef(documentSchemaType), ...getFieldRefs2(documentSchemaType.name)] : [], $[0] = documentSchemaType, $[1] = getFieldRefs2, $[2] = t0) : t0 = $[2];
const selectableFields = t0;
let t1;
return $[3] !== path || $[4] !== selectableFields ? (t1 = path ? selectableFields?.find((f) => f.key === path) : void 0, $[3] = path, $[4] = selectableFields, $[5] = t1) : t1 = $[5], t1;
}
function getFieldTitle(field) {
const schemaType = field?.schemaType;
return field?.title ?? schemaType?.title ?? schemaType?.name ?? "Untitled";
}
function useAiPaneRouter() {
const $ = c(5), paneRouter = usePaneRouter();
let t0;
$[0] !== paneRouter.params ? (t0 = paneRouter.params ?? {}, $[0] = paneRouter.params, $[1] = t0) : t0 = $[1];
let t1;
return $[2] !== paneRouter || $[3] !== t0 ? (t1 = {
...paneRouter,
params: t0
}, $[2] = paneRouter, $[3] = t0, $[4] = t1) : t1 = $[4], t1;
}
const basePath = "/assist/tasks/instruction", API_VERSION_WITH_EXTENDED_TYPES = "2025-04-01";
function canUseAssist(status) {
return status?.enabled && status.initialized && status.validToken;
}
function useApiClient(customApiClient) {
const $ = c(4);
let t0;
$[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {
apiVersion: API_VERSION_WITH_EXTENDED_TYPES
}, $[0] = t0) : t0 = $[0];
const client = useClient(t0);
let t1;
return $[1] !== client || $[2] !== customApiClient ? (t1 = customApiClient ? customApiClient(client) : client, $[1] = client, $[2] = customApiClient, $[3] = t1) : t1 = $[3], t1;
}
function useTranslate(apiClient) {
const $ = c(8), [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), toast = useToast();
let t0;
$[0] !== apiClient || $[1] !== toast || $[2] !== types || $[3] !== user?.id ? (t0 = (t12) => {
const {
documentId,
languagePath,
styleguide,
translatePath,
fieldLanguageMap,
conditionalMembers
} = t12;
return setLoading(!0), (async function() {
return apiClient.request({
method: "POST",
url: `/assist/tasks/translate/${apiClient.config().dataset}?projectId=${apiClient.config().projectId}`,
body: {
documentId,
types,
languagePath,
userStyleguide: await styleguide(),
fieldLanguageMap,
conditionalMembers,
translatePath: translatePath.length === 0 ? documentRootKey : pathToString(translatePath),
userId: user?.id
}
});
})().catch((e) => {
throw toast.push({
status: "error",
title: "Translate failed",
description: e.message
}), setLoading(!1), e;
}).finally(() => {
setTimeout(() => {
setLoading(!1);
}, 2e3);
});
}, $[0] = apiClient, $[1] = toast, $[2] = types, $[3] = user?.id, $[4] = t0) : t0 = $[4];
const translate = t0;
let t1;
return $[5] !== loading || $[6] !== translate ? (t1 = {
translate,
loading
}, $[5] = loading, $[6] = translate, $[7] = t1) : t1 = $[7], t1;
}
function useGenerateCaption(apiClient) {
const $ = c(8), [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), toast = useToast();
let t0;
$[0] !== apiClient || $[1] !== toast || $[2] !== types || $[3] !== user?.id ? (t0 = (t12) => {
const {
path,
documentId
} = t12;
return setLoading(!0), apiClient.request({
method: "POST",
url: `/assist/tasks/generate-caption/${apiClient.config().dataset}?projectId=${apiClient.config().projectId}`,
body: {
path,
documentId,
types,
userId: user?.id
}
}).catch((e) => {
throw toast.push({
status: "error",
title: "Generate image description failed",
description: e.message
}), setLoading(!1), e;
}).finally(() => {
setTimeout(() => {
setLoading(!1);
}, 2e3);
});
}, $[0] = apiClient, $[1] = toast, $[2] = types, $[3] = user?.id, $[4] = t0) : t0 = $[4];
const generateCaption = t0;
let t1;
return $[5] !== generateCaption || $[6] !== loading ? (t1 = {
generateCaption,
loading
}, $[5] = generateCaption, $[6] = loading, $[7] = t1) : t1 = $[7], t1;
}
function useGenerateImage(apiClient) {
const $ = c(8), [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), toast = useToast();
let t0;
$[0] !== apiClient || $[1] !== toast || $[2] !== types || $[3] !== user?.id ? (t0 = (t12) => {
const {
path,
documentId
} = t12;
return setLoading(!0), apiClient.request({
method: "POST",
url: `/assist/tasks/generate-image/${apiClient.config().dataset}?projectId=${apiClient.config().projectId}`,
body: {
path,
documentId,
types,
userId: user?.id
}
}).catch((e) => {
throw toast.push({
status: "error",
title: "Generate image from prompt failed",
description: e.message
}), setLoading(!1), e;
}).finally(() => {
setTimeout(() => {
setLoading(!1);
}, 2e3);
});
}, $[0] = apiClient, $[1] = toast, $[2] = types, $[3] = user?.id, $[4] = t0) : t0 = $[4];
const generateImage = t0;
let t1;
return $[5] !== generateImage || $[6] !== loading ? (t1 = {
generateImage,
loading
}, $[5] = generateImage, $[6] = loading, $[7] = t1) : t1 = $[7], t1;
}
function useGetInstructStatus(apiClient) {
const [loading, setLoading] = useState(!0), getInstructStatus = useCallback(async () => {
setLoading(!0);
const projectId = apiClient.config().projectId;
try {
return await apiClient.request({
method: "GET",
url: `${basePath}/${apiClient.config().dataset}/status?projectId=${projectId}`
});
} finally {
setLoading(!1);
}
}, [setLoading, apiClient]);
return {
loading,
getInstructStatus
};
}
function useInitInstruct(apiClient) {
const $ = c(5), [loading, setLoading] = useState(!1);
let t0;
$[0] !== apiClient ? (t0 = () => (setLoading(!0), apiClient.request({
method: "GET",
url: `${basePath}/${apiClient.config().dataset}/init?projectId=${apiClient.config().projectId}`
}).finally(() => {
setLoading(!1);
})), $[0] = apiClient, $[1] = t0) : t0 = $[1];
const initInstruct = t0;
let t1;
return $[2] !== initInstruct || $[3] !== loading ? (t1 = {
loading,
initInstruct
}, $[2] = initInstruct, $[3] = loading, $[4] = t1) : t1 = $[4], t1;
}
function useRunInstructionApi(apiClient) {
const $ = c(9), toast = useToast(), [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), {
config: t0
} = useAiAssistanceConfig(), {
assist: assistConfig
} = t0;
let t1;
$[0] !== apiClient || $[1] !== assistConfig || $[2] !== toast || $[3] !== types || $[4] !== user ? (t1 = (request) => {
if (!user) {
toast.push({
status: "error",
title: "Unable to get user for instruction."
});
return;
}
setLoading(!0);
const {
timeZone,
locale
} = Intl.DateTimeFormat().resolvedOptions(), defaultLocaleSettings = {
timeZone,
locale
}, localeSettings = assistConfig?.localeSettings?.({
user,
defaultSettings: defaultLocaleSettings
}) ?? defaultLocaleSettings;
return apiClient.request({
method: "POST",
url: `${basePath}/${apiClient.config().dataset}?projectId=${apiClient.config().projectId}`,
body: {
...request,
types,
userId: user?.id,
localeSettings,
maxPathDepth: assistConfig?.maxPathDepth
}
}).catch((e) => {
throw toast.push({
status: "error",
title: "Instruction failed",
description: e.message
}), e;
}).finally(() => {
setLoading(!1);
});
}, $[0] = apiClient, $[1] = assistConfig, $[2] = toast, $[3] = types, $[4] = user, $[5] = t1) : t1 = $[5];
const runInstruction = t1;
let t2;
return $[6] !== loading || $[7] !== runInstruction ? (t2 = {
runInstruction,
loading
}, $[6] = loading, $[7] = runInstruction, $[8] = t2) : t2 = $[8], t2;
}
const NO_INPUT = {}, RunInstructionContext = createContext({
runInstruction: () => {
},
getUserInput: async () => {
},
instructionLoading: !1
});
function useRunInstruction() {
return useContext(RunInstructionContext);
}
function isUserInputBlock(block) {
return block._type === userInputTypeName;
}
function RunInstructionProvider(props) {
const $ = c(33), {
config
} = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), {
runInstruction: runInstructionRequest,
loading
} = useRunInstructionApi(apiClient), id = useId(), [inputs, setInputs] = useState(NO_INPUT), [runRequest, setRunRequest] = useState(), [resolveUserInput, setResolveUserInput] = useState();
let t0;
$[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = async (t12) => {
const {
title,
inputs: inputs_0
} = t12, userInputBlocks = inputs_0.map(_temp$c);
if (userInputBlocks.length)
return setRunRequest({
dialogTitle: title,
userInputBlocks
}), new Promise((resolve) => {
setResolveUserInput(() => resolve);
});
}, $[0] = t0) : t0 = $[0];
const getUserInput = t0;
let t1;
$[1] !== loading || $[2] !== runInstructionRequest ? (t1 = (req) => {
if (loading)
return;
const {
instruction: instruction2,
...request
} = req, instructionKey = instruction2._key, userInputBlocks_0 = instruction2?.prompt?.flatMap(_temp2$6).filter(isUserInputBlock);
if (!userInputBlocks_0?.length) {
runInstructionRequest({
...request,
instructionKey,
userTexts: void 0
});
return;
}
setRunRequest({
...req,
userInputBlocks: userInputBlocks_0
});
}, $[1] = loading, $[2] = runInstructionRequest, $[3] = t1) : t1 = $[3];
const runInstruction = t1;
let t2;
$[4] !== resolveUserInput ? (t2 = () => {
setRunRequest(void 0), setInputs(NO_INPUT), resolveUserInput && resolveUserInput(void 0), setResolveUserInput(void 0);
}, $[4] = resolveUserInput, $[5] = t2) : t2 = $[5];
const close = t2;
let t3;
$[6] !== close || $[7] !== inputs || $[8] !== resolveUserInput || $[9] !== runInstructionRequest || $[10] !== runRequest ? (t3 = () => {
if (runRequest)
if ("instruction" in runRequest) {
const {
instruction: instruction_0,
userInputBlocks: _,
...request_0
} = runRequest;
runInstructionRequest({
...request_0,
instructionKey: instruction_0._key,
userTexts: Object.entries(inputs).map(_temp3$4)
});
} else {
const userInputs = Object.values(inputs).map((input_0, i_0) => {
const userInputBlock = runRequest.userInputBlocks[i_0];
return {
input: {
id: userInputBlock._key,
title: userInputBlock.message ?? "",
description: userInputBlock.description
},
result: input_0
};
});
resolveUserInput?.(userInputs), setResolveUserInput(void 0);
}
close();
}, $[6] = close, $[7] = inputs, $[8] = resolveUserInput, $[9] = runInstructionRequest, $[10] = runRequest, $[11] = t3) : t3 = $[11];
const runWithInput = t3, open = !!runRequest;
let t4;
$[12] !== inputs ? (t4 = Object.entries(inputs).filter(_temp4$2), $[12] = inputs, $[13] = t4) : t4 = $[13];
const runDisabled = (runRequest?.userInputBlocks?.length ?? 0) > t4.length;
let t5;
$[14] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t5 = {
width: "100%"
}, $[14] = t5) : t5 = $[14];
let t6;
$[15] !== runDisabled || $[16] !== runWithInput ? (t6 = /* @__PURE__ */ jsx(Button, { text: "Run instruction", onClick: runWithInput, tone: "primary", icon: PlayIcon, style: t5, disabled: runDisabled }), $[15] = runDisabled, $[16] = runWithInput, $[17] = t6) : t6 = $[17];
const runButton = t6;
let t7;
$[18] !== loading || $[19] !== runInstruction ? (t7 = {
runInstruction,
getUserInput,
instructionLoading: loading
}, $[18] = loading, $[19] = runInstruction, $[20] = t7) : t7 = $[20];
const contextValue = t7;
let t8;
$[21] !== close || $[22] !== id || $[23] !== inputs || $[24] !== open || $[25] !== runButton || $[26] !== runDisabled || $[27] !== runRequest ? (t8 = open ? /* @__PURE__ */ jsx(Dialog, { id, open, onClose: close, width: 1, header: "dialogTitle" in runRequest ? runRequest.dialogTitle : getInstructionTitle(runRequest?.instruction), footer: /* @__PURE__ */ jsx(Flex, { justify: "space-between", padding: 2, flex: 1, children: runDisabled ? /* @__PURE__ */ jsx(Tooltip, { content: /* @__PURE__ */ jsx(Flex, { padding: 2, children: /* @__PURE__ */ jsx(Text, { children: "Unable to run instruction. All fields must have a value." }) }), placement: "top", children: /* @__PURE__ */ jsx(Flex, { flex: 1, children: runButton }) }) : runButton }), children: /* @__PURE__ */ jsx(Stack, { padding: 4, gap: 2, children: runRequest?.userInputBlocks?.map((block_0, i_1) => /* @__PURE__ */ jsx(UserInput, { block: block_0, autoFocus: i_1 === 0, inputs, setInputs }, block_0._key)) }) }) : null, $[21] = close, $[22] = id, $[23] = inputs, $[24] = open, $[25] = runButton, $[26] = runDisabled, $[27] = runRequest, $[28] = t8) : t8 = $[28];
let t9;
return $[29] !== contextValue || $[30] !== props.children || $[31] !== t8 ? (t9 = /* @__PURE__ */ jsxs(RunInstructionContext.Provider, { value: contextValue, children: [
t8,
props.children
] }), $[29] = contextValue, $[30] = props.children, $[31] = t8, $[32] = t9) : t9 = $[32], t9;
}
function _temp4$2(t0) {
const [, value_0] = t0;
return !!value_0;
}
function _temp3$4(t0) {
const [key, value] = t0;
return {
blockKey: key,
userInput: value
};
}
function _temp2$6(block) {
return block._type === "block" ? block.children.filter(isUserInputBlock) : [block];
}
function _temp$c(input, i) {
return {
_type: userInputTypeName,
_key: input.id ?? `${i}`,
message: input.title,
description: input.description
};
}
function UserInput(props) {
const $ = c(16), {
block,
autoFocus,
setInputs,
inputs
} = props, key = block._key, textAreaRef = useRef(null);
let t0;
$[0] !== key || $[1] !== setInputs ? (t0 = (e) => {
setInputs((current) => ({
...current,
[key]: (e.currentTarget ?? e.target).value
}));
}, $[0] = key, $[1] = setInputs, $[2] = t0) : t0 = $[2];
const onChange = t0, value = inputs[key];
let t1, t2;
$[3] !== autoFocus ? (t1 = () => {
autoFocus && setTimeout(() => textAreaRef.current?.focus(), 0);
}, t2 = [autoFocus], $[3] = autoFocus, $[4] = t1, $[5] = t2) : (t1 = $[4], t2 = $[5]), useEffect(t1, t2);
const t3 = block?.message ?? "Provide more context";
let t4;
$[6] !== block.description || $[7] !== t3 ? (t4 = /* @__PURE__ */ jsx(FormFieldHeaderText, { title: t3, description: block.description }), $[6] = block.description, $[7] = t3, $[8] = t4) : t4 = $[8];
let t5;
$[9] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t5 = {
resize: "vertical"
}, $[9] = t5) : t5 = $[9];
let t6;
$[10] !== onChange || $[11] !== value ? (t6 = /* @__PURE__ */ jsx(TextArea, { ref: textAreaRef, rows: 4, value, onChange, style: t5 }), $[10] = onChange, $[11] = value, $[12] = t6) : t6 = $[12];
let t7;
return $[13] !== t4 || $[14] !== t6 ? (t7 = /* @__PURE__ */ jsxs(Stack, { padding: 2, gap: 3, children: [
t4,
t6
] }), $[13] = t4, $[14] = t6, $[15] = t7) : t7 = $[15], t7;
}
function isDocAssistable(documentSchemaType, published, draft) {
return !!(documentSchemaType.liveEdit ? published : draft);
}
function useRequestRunInstruction(args) {
const $ = c(6), {
runInstruction,
instructionLoading
} = useRunInstruction();
let t0;
$[0] !== args || $[1] !== runInstruction ? (t0 = {
...args,
task: runInstruction
}, $[0] = args, $[1] = runInstruction, $[2] = t0) : t0 = $[2];
const requestRunInstruction = useDraftDelayedTask(t0);
let t1;
return $[3] !== instructionLoading || $[4] !== requestRunInstruction ? (t1 = {
instructionLoading,
requestRunInstruction
}, $[3] = instructionLoading, $[4] = requestRunInstruction, $[5] = t1) : t1 = $[5], t1;
}
function useDraftDelayedTask(args) {
const $ = c(7), {
documentOnChange,
isDocAssistable: isDocAssistable2,
task
} = args, [queuedArgs, setQueuedArgs] = useState(void 0);
let t0, t1;
$[0] !== isDocAssistable2 || $[1] !== queuedArgs || $[2] !== task ? (t0 = () => {
queuedArgs && isDocAssistable2 && (task(queuedArgs), setQueuedArgs(void 0));
}, t1 = [queuedArgs, isDocAssistable2, task], $[0] = isDocAssistable2, $[1] = queuedArgs, $[2] = task, $[3] = t0, $[4] = t1) : (t0 = $[3], t1 = $[4]), useEffect(t0, t1);
let t2;
return $[5] !== documentOnChange ? (t2 = (taskArgs) => {
documentOnChange(PatchEvent.from([unset(["_force_document_creation"])])), setQueuedArgs(taskArgs);
}, $[5] = documentOnChange, $[6] = t2) : t2 = $[6], t2;
}
function useAssistDocumentContextValue(documentId, documentType) {
const $ = c(47), schema = useSchema(), {
getFieldRefs: getFieldRefs2,
getFieldRefsByTypePath
} = useAiAssistanceConfig();
let t0, t1;
$[0] !== documentType || $[1] !== schema ? (t1 = schema.get(documentType), $[0] = documentType, $[1] = schema, $[2] = t1) : t1 = $[2];
const schemaType = t1;
if (!schemaType)
throw new Error(`Schema type "${documentType}" not found`);
t0 = schemaType;
const documentSchemaType = t0;
let t2;
$[3] !== documentType || $[4] !== getFieldRefs2 ? (t2 = getFieldRefs2(documentType), $[3] = documentType, $[4] = getFieldRefs2, $[5] = t2) : t2 = $[5];
let t3;
$[6] !== documentType || $[7] !== getFieldRefsByTypePath ? (t3 = getFieldRefsByTypePath(documentType), $[6] = documentType, $[7] = getFieldRefsByTypePath, $[8] = t3) : t3 = $[8];
let t4;
$[9] !== t2 || $[10] !== t3 ? (t4 = {
fieldRefs: t2,
fieldRefsByTypePath: t3
}, $[9] = t2, $[10] = t3, $[11] = t4) : t4 = $[11];
const {
fieldRefs,
fieldRefsByTypePath
} = t4, {
openInspector,
closeInspector,
inspector,
onChange: documentOnChange,
editState
} = useDocumentPane(), {
selectedReleaseId
} = usePerspective();
let t5;
$[12] !== editState ? (t5 = editState || {}, $[12] = editState, $[13] = t5) : t5 = $[13];
const {
draft,
published,
version
} = t5;
let t6;