@sanity/assist 1.0.5 → 1.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var _templateObject,_templateObject2,_templateObject3,_templateObject4,_templateObject5,_templateObject6,_templateObject7,_templateObject8,_templateObject9,_templateObject10;function _taggedTemplateLiteral(strings,raw){if(!raw){raw=strings.slice(0);}return Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}));}import{jsx,jsxs,Fragment}from'react/jsx-runtime';import{useClient,typed,useSchema,useDocumentStore,useDocumentPresence,createPatchChannel,FormBuilder,fromMutationPatches,pathToString,isObjectSchemaType,useEditState,useCurrentUser,useValidationStatus,StatusButton,FormFieldHeaderText,PatchEvent,unset,PresenceOverlay,VirtualizerScrollInstanceProvider,stringToPath,isKeySegment,useColorSchemeValue,isArraySchemaType,useFormCallbacks,set,setIfMissing,insert,
|
|
1
|
+
var _templateObject,_templateObject2,_templateObject3,_templateObject4,_templateObject5,_templateObject6,_templateObject7,_templateObject8,_templateObject9,_templateObject10;function _taggedTemplateLiteral(strings,raw){if(!raw){raw=strings.slice(0);}return Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}));}import{jsx,jsxs,Fragment}from'react/jsx-runtime';import{useClient,typed,useSchema,useDocumentStore,useDocumentPresence,createPatchChannel,FormBuilder,fromMutationPatches,pathToString,isObjectSchemaType,useEditState,useCurrentUser,useValidationStatus,StatusButton,FormFieldHeaderText,PatchEvent,unset,PresenceOverlay,VirtualizerScrollInstanceProvider,stringToPath,isKeySegment,useColorSchemeValue,isArraySchemaType,useFormCallbacks,set,FormCallbacksProvider,FormInput,setIfMissing,insert,ObjectInputMember,defineType,defineField,defineArrayMember,getPublishedId,definePlugin}from'sanity';import{Card,Stack,Box,Button,Spinner,Flex,Label,focusFirstDescendant,Text,useClickOutside,Popover,useLayer,useGlobalKeyDown,useToast,Dialog,Tooltip,TextArea,Container,Badge,useTheme,rgba as rgba$1,ThemeProvider,ErrorBoundary,Switch,MenuButton,Menu,MenuItem,Breadcrumbs,Autocomplete}from'@sanity/ui';import*as React from'react';import React__default,{useState,useRef,useEffect,useMemo,useCallback,createContext,useContext,createElement,useReducer,forwardRef,useId,useLayoutEffect,useInsertionEffect}from'react';import{SyncIcon,DocumentIcon,LinkIcon,ImageIcon,BlockContentIcon,OlistIcon,BlockquoteIcon,StringIcon,ErrorOutlineIcon,CheckmarkCircleIcon,CloseCircleIcon,ClockIcon,PlayIcon,SparklesIcon,RetryIcon,ArrowRightIcon,CloseIcon,CheckmarkIcon,ArrowLeftIcon,icons,SearchIcon,TokenIcon,DocumentTextIcon,ThListIcon,CodeIcon,ComposeIcon,LockIcon,ControlsIcon}from'@sanity/icons';import{mergeMap,share,take,filter as filter$1,distinctUntilChanged,catchError,tap}from'rxjs/operators';import isEqual from'react-fast-compare';import{throwError,of,partition,merge,switchMap,delay as delay$1,defer}from'rxjs';import{exhaustMapToWithTrailing}from'rxjs-exhaustmap-with-trailing';import{useDocumentPane,usePaneRouter,DocumentInspectorHeader,DocumentPaneProvider}from'sanity/desk';const assistDocumentIdPrefix="sanity.assist.schemaType.";const assistDocumentStatusIdPrefix="sanity.assist.status.";const assistSchemaIdPrefix="sanity.assist.schema.";const assistDocumentTypeName="sanity.assist.schemaType.annotations";const assistFieldTypeName="sanity.assist.schemaType.field";const instructionTypeName="sanity.assist.instruction";const promptTypeName="sanity.assist.instruction.prompt";const userInputTypeName="sanity.assist.instruction.userInput";const instructionContextTypeName="sanity.assist.instruction.context";const fieldReferenceTypeName="sanity.assist.instruction.fieldRef";const contextDocumentTypeName="assist.instruction.context";const assistTasksStatusTypeName="sanity.assist.task.status";const instructionTaskTypeName="sanity.assist.instructionTask";const fieldPresenceTypeName="sanity.assist.instructionTask.presence";const assistSerializedTypeName="sanity.assist.serialized.type";const assistSerializedFieldTypeName="sanity.assist.serialized.field";const fieldPathParam="pathKey";const instructionParam="instruction";const documentRootKey="<document>";const fetch=(client,query,params,options)=>defer(()=>// getVersionedClient(options.apiVersion)
|
|
2
2
|
client.observable.fetch(query,params,{tag:options.tag,filterResponse:true}));const listen=(client,query,params,options)=>defer(()=>// getVersionedClient(options.apiVersion)
|
|
3
3
|
client.listen(query,params,{events:["welcome","mutation","reconnect"],includeResult:false,visibility:"query",tag:options.tag}));function isWelcomeEvent(event){return event.type==="welcome";}const listenQuery=function(client,query){let params=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};let options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};const fetchQuery=typeof query==="string"?query:query.fetch;const listenerQuery=typeof query==="string"?query:query.listen;const fetchOnce$=fetch(client,fetchQuery,params,options);const events$=listen(client,listenerQuery,params,options).pipe(mergeMap((ev,i)=>{const isFirst=i===0;if(isFirst&&!isWelcomeEvent(ev)){return throwError(new Error(ev.type==="reconnect"?"Could not establish EventSource connection":"Received unexpected type of first event \"".concat(ev.type,"\"")));}return of(ev);}),share());const[welcome$,mutationAndReconnect$]=partition(events$,isWelcomeEvent);const isRelevantEvent=event=>{if(!options.transitions||event.type!=="mutation"){return true;}return options.transitions.includes(event.transition);};return merge(welcome$.pipe(take(1)),mutationAndReconnect$.pipe(filter$1(isRelevantEvent),switchMap(event=>merge(of(event),of(event).pipe(delay$1(options.throttleTime||1e3)))))).pipe(exhaustMapToWithTrailing(fetchOnce$));};const DEFAULT_PARAMS={};const DEFAULT_OPTIONS={apiVersion:"v2022-05-09"};function useListeningQuery(query){let params=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_PARAMS;let options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEFAULT_OPTIONS;const[loading,setLoading]=useState(true);const[error,setError]=useState(false);const[data,setData]=useState(null);const subscription=useRef(null);const client=useClient({apiVersion:"v2022-05-09"});useEffect(()=>{if(query){subscription.current=listenQuery(client,query,params,options).pipe(distinctUntilChanged(isEqual),catchError(err=>{console.error(err);setError(err);setLoading(false);setData(null);return err;})).subscribe(documents=>{setData(current=>isEqual(current,documents)?current:documents);setLoading(false);setError(false);});}return()=>{return subscription.current?subscription.current.unsubscribe():void 0;};},[query,params,options,client]);return{loading,error,data};}const hiddenTypes=["any","array","block","boolean","crossDatasetReference","date","datetime","document","email","file","image","number","object","reference","span","string","text","url","slug","geopoint","sanity.assetSourceData","sanity.imageAsset","sanity.fileAsset","sanity.imageCrop","sanity.imageHotspot","sanity.imageMetadata","sanity.imageDimensions","sanity.imagePalette","sanity.imagePaletteSwatch",assistSerializedTypeName,assistSerializedFieldTypeName,"sanity-agent.job.document"];function isPortableTextArray(type){return type.of.find(t=>isType(t,"block"));}function isType(schemaType,typeName){if(schemaType.name===typeName){return true;}if(!schemaType.type){return false;}return isType(schemaType.type,typeName);}function isSchemaAssistEnabled(type){var _a,_b;return!((_b=(_a=type.options)==null?void 0:_a.aiWritingAssistance)==null?void 0:_b.exclude);}function isAssistSupported(type){if(!isSchemaAssistEnabled(type)){return false;}if(isUnsupportedType(type)){return false;}if(type.jsonType==="array"){const unsupportedArray=type.of.every(t=>isUnsupportedType(t));return!unsupportedArray;}if(type.jsonType==="object"){const unsupportedObject=type.fields.every(field=>isUnsupportedType(field.type));return!unsupportedObject;}return true;}function isUnsupportedType(type){return!isSchemaAssistEnabled(type)||type.jsonType==="number"||type.name==="sanity.imageCrop"||type.name==="sanity.imageHotspot"||isType(type,"reference")||isType(type,"crossDatasetReference")||isType(type,"slug")||isType(type,"url")||isType(type,"date")||isType(type,"datetime")||isType(type,"file");}const inlineTypes=["document","object","image","file"];function serializeSchema(schema,options){const list=schema.getTypeNames().filter(t=>!(hiddenTypes.includes(t)||t.startsWith("sanity."))).map(t=>schema.get(t)).filter(t=>!!t).map(t=>getSchemaStub(t,schema,options)).filter(t=>{if("to"in t&&t.to&&!t.to.length){return false;}if("of"in t&&t.of&&!t.of.length){return false;}if("fields"in t&&t.fields&&!t.fields.length){return false;}return true;});list.sort((a,b)=>{var _a,_b;return((_a=a==null?void 0:a.name)!=null?_a:"").localeCompare((_b=b==null?void 0:b.name)!=null?_b:"");});return list;}function getSchemaStub(schemaType,schema,options){var _a;if(!((_a=schemaType.type)==null?void 0:_a.name)){console.error("Missing type name",schemaType.type);throw new Error("Type is missing name!");}const baseSchema={// we dont need type or id when we send using POST, so leave these out to save bandwidth
|
|
4
4
|
...((options==null?void 0:options.leanFormat)?{}:{_id:"".concat(assistSchemaIdPrefix).concat(schemaType.name),_type:assistSerializedTypeName}),name:schemaType.name,title:schemaType.title,type:schemaType.type.name,...getBaseFields(schema,schemaType,schemaType.type.name,options)};return removeUndef(baseSchema);}function getBaseFields(schema,type,typeName,options){var _a,_b,_c;const imagePromptField=(_a=type.options)==null?void 0:_a.imagePromptField;return removeUndef({options:imagePromptField?{imagePromptField}:void 0,values:type.jsonType==="string"&&((_b=type==null?void 0:type.options)==null?void 0:_b.list)?(_c=type==null?void 0:type.options)==null?void 0:_c.list.map(v=>{var _a2;return typeof v==="string"?v:(_a2=v.value)!=null?_a2:"".concat(v.title);}):void 0,of:"of"in type&&typeName==="array"?arrayOf(type,schema,options):void 0,to:"to"in type&&typeName==="reference"?refToTypeNames(type):void 0,fields:"fields"in type&&inlineTypes.includes(typeName)?serializeFields(schema,type,options):void 0});}function serializeFields(schema,schemaType,options){return schemaType.fields.filter(f=>{var _a,_b;return!["sanity.imageHotspot","sanity.imageCrop"].includes((_b=(_a=f.type)==null?void 0:_a.name)!=null?_b:"");}).filter(f=>isAssistSupported(f.type)).map(field=>serializeMember(schema,field.type,field.name,options));}function serializeMember(schema,type,name,options){var _a,_b;const typeNameExists=!!schema.get(type==null?void 0:type.name);const typeName=typeNameExists?type.name:(_b=(_a=type.type)==null?void 0:_a.name)!=null?_b:"";return removeUndef({...((options==null?void 0:options.leanFormat)?{}:{_type:assistSerializedFieldTypeName}),name,type:typeName,title:type.title,...getBaseFields(schema,type,typeName,options)});}function arrayOf(arrayType,schema,options){return arrayType.of.filter(type=>isAssistSupported(type)).map(t=>{return serializeMember(schema,t,t.name,options);});}function refToTypeNames(type){return type.to.map(t=>({type:typed(t.name)}));}function removeUndef(obj){Object.keys(obj).forEach(key=>obj[key]===void 0?delete obj[key]:{});return obj;}const NO_DATA=[];const defaultTitle="Sync schema";function SchemaTypeTool(){const schema=useSchema();const client=useClient({apiVersion:"2023-01-01"});const[saving,setSaving]=useState(false);const[syncTitle,setSyncTitle]=useState(defaultTitle);const{data}=useListeningQuery("*[_type==$type] | order(_type)",{type:assistSerializedTypeName});const types=useMemo(()=>{return serializeSchema(schema);},[schema]);const storeTypes=useCallback(()=>{setSaving(true);let canSave=true;async function store(){setSyncTitle("Syncing 0/".concat(types.length));const transaction=client.transaction();for(let i=0;i<types.length;i++){if(!canSave){break;}const type=types[i];await transaction.createOrReplace(type);if(i>0&&i%50===0){await transaction.commit();transaction.reset();setSyncTitle("Syncing ".concat(i,"/").concat(types.length));}}await transaction.commit();}store().catch(console.error).finally(()=>{setSaving(false);setSyncTitle(defaultTitle);});return()=>{canSave=false;setSaving(false);setSyncTitle(defaultTitle);};},[types,client,setSaving,setSyncTitle]);return/* @__PURE__ */jsx(Card,{padding:4,overflow:"auto",style:{height:"calc(100vh - 81px)"},children:/* @__PURE__ */jsxs(Stack,{space:4,children:[/* @__PURE__ */jsx(Box,{children:/* @__PURE__ */jsx(Button,{icon:saving?/* @__PURE__ */jsx(Spinner,{style:{marginTop:5}}):SyncIcon,text:syncTitle,disabled:saving,onClick:storeTypes})}),/* @__PURE__ */jsxs(Flex,{gap:2,children:[/* @__PURE__ */jsxs(Stack,{space:2,children:[/* @__PURE__ */jsx(Label,{children:"Studio schema"}),/* @__PURE__ */jsx("ul",{children:types.map(type=>/* @__PURE__ */jsx("li",{children:/* @__PURE__ */jsx(SchemaEntry,{schemaStub:type})},type.name))})]}),/* @__PURE__ */jsxs(Stack,{space:2,children:[/* @__PURE__ */jsx(Label,{children:"Stored schema"}),/* @__PURE__ */jsx("ul",{children:(data!=null?data:NO_DATA).map(type=>/* @__PURE__ */jsx("li",{children:/* @__PURE__ */jsx(SchemaEntry,{schemaStub:type})},type.name))})]})]})]})});}function SchemaEntry(_ref2){let{schemaStub}=_ref2;const out=useMemo(()=>JSON.stringify(schemaStub,null,2),[schemaStub]);return/* @__PURE__ */jsx("pre",{children:out});}const aiInspectorId="ai-assistance";const preventDefault=ev=>ev.preventDefault();function DocumentForm(props){var _a;const{collapsedFieldSets,collapsedPaths,displayed:value,documentId,documentType,editState,formState,onBlur,onChange,onFocus,onPathOpen,onSetActiveFieldGroup,onSetCollapsedFieldSet,onSetCollapsedPath,ready,validation}=useDocumentPane();const documentStore=useDocumentStore();const presence=useDocumentPresence(documentId);const patchChannel=useMemo(()=>createPatchChannel(),[]);const isLocked=(_a=editState==null?void 0:editState.transactionSyncLock)==null?void 0:_a.enabled;useEffect(()=>{const sub=documentStore.pair.documentEvents(documentId,documentType).pipe(tap(event=>{if(event.type==="mutation"){patchChannel.publish(prepareMutationEvent(event));}if(event.type==="rebase"){patchChannel.publish(prepareRebaseEvent(event));}})).subscribe();return()=>{sub.unsubscribe();};},[documentId,documentStore,documentType,patchChannel]);const hasRev=Boolean(value==null?void 0:value._rev);useEffect(()=>{if(hasRev){patchChannel.publish({type:"mutation",patches:[],snapshot:value});}},[hasRev]);const formRef=useRef(null);useEffect(()=>{focusFirstDescendant(formRef.current);},[]);if(isLocked){return/* @__PURE__ */jsx(Box,{as:"form",...props,ref:formRef,children:/* @__PURE__ */jsx(Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:/* @__PURE__ */jsx(Text,{size:1,children:"Please hold tight while the document is synced. This usually happens right after the document has been published, and it shouldn\u2019t take more than a few seconds"})})});}return/* @__PURE__ */jsx(Box,{as:"form",...props,onSubmit:preventDefault,ref:formRef,children:ready?formState===null?/* @__PURE__ */jsx(Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:/* @__PURE__ */jsx(Text,{size:1,children:"This form is hidden"})}):/* @__PURE__ */jsx(FormBuilder,{__internal_patchChannel:patchChannel,collapsedFieldSets,collapsedPaths,focusPath:formState.focusPath,changed:formState.changed,focused:formState.focused,groups:formState.groups,id:"root",members:formState.members,onChange,onFieldGroupSelect:onSetActiveFieldGroup,onPathBlur:onBlur,onPathFocus:onFocus,onPathOpen,onSetFieldSetCollapsed:onSetCollapsedFieldSet,onSetPathCollapsed:onSetCollapsedPath,presence,readOnly:formState.readOnly,schemaType:formState.schemaType,validation,value:formState.value}):/* @__PURE__ */jsxs(Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:[/* @__PURE__ */jsx(Spinner,{muted:true}),/* @__PURE__ */jsx(Box,{marginTop:3,children:/* @__PURE__ */jsx(Text,{align:"center",muted:true,size:1,children:"Loading document"})})]})});}function prepareMutationEvent(event){const patches=event.mutations.map(mut=>mut.patch).filter(Boolean);return{type:"mutation",snapshot:event.document,patches:fromMutationPatches(event.origin,patches)};}function prepareRebaseEvent(event){const remotePatches=event.remoteMutations.map(mut=>mut.patch).filter(Boolean);const localPatches=event.localMutations.map(mut=>mut.patch).filter(Boolean);return{type:"rebase",snapshot:event.document,patches:fromMutationPatches("remote",remotePatches).concat(fromMutationPatches("local",localPatches))};}const SelectedFieldContext=createContext(void 0);const SelectedFieldContextProvider=SelectedFieldContext.Provider;function getTypeIcon(schemaType){let t=schemaType;while(t){if(t.icon)return t.icon;t=t.type;}if(isType(schemaType,"slug"))return LinkIcon;if(isType(schemaType,"image"))return ImageIcon;if(schemaType.jsonType==="array"&&isPortableTextArray(schemaType))return BlockContentIcon;if(schemaType.jsonType==="array")return OlistIcon;if(schemaType.jsonType==="object")return BlockquoteIcon;if(schemaType.jsonType==="string")return StringIcon;return DocumentIcon;}function getFieldRefsWithDocument(schemaType){var _a;const fields=getFieldRefs(schemaType);return[{key:documentRootKey,icon:(_a=schemaType.icon)!=null?_a:DocumentIcon,title:"The entire document",path:[],schemaType},...fields];}function getFieldRefs(schemaType,parent){return schemaType.fields.filter(f=>!f.name.startsWith("_")).flatMap(field=>{var _a;const path=parent?[...parent.path,field.name]:[field.name];const title=(_a=field.type.title)!=null?_a:field.name;const fieldRef={key:pathToString(path),path,title:parent?[parent.title,title].join(" / "):title,schemaType:field.type,icon:getTypeIcon(field.type)};const fields=field.type.jsonType==="object"?getFieldRefs(field.type,fieldRef):[];if(!isAssistSupported(field.type)){return fields;}return[fieldRef,...fields];});}function useSelectedField(documentSchemaType,path){const selectableFields=useMemo(()=>documentSchemaType&&isObjectSchemaType(documentSchemaType)?getFieldRefsWithDocument(documentSchemaType):[],[documentSchemaType]);return useMemo(()=>{return path?selectableFields==null?void 0:selectableFields.find(f=>f.key===path):void 0;},[selectableFields,path]);}function getFieldTitle(field){var _a,_b;const schemaType=field==null?void 0:field.schemaType;return(_b=(_a=schemaType==null?void 0:schemaType.title)!=null?_a:schemaType==null?void 0:schemaType.name)!=null?_b:"Untitled";}function useAiPaneRouter(){const paneRouter=usePaneRouter();return useMemo(()=>{var _a;return{...paneRouter,params:(_a=paneRouter.params)!=null?_a:{}};},[paneRouter]);}function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,'default')?x['default']:x;}var reactIs$2={exports:{}};var reactIs_production_min$1={};/**
|
|
@@ -2308,9 +2308,9 @@ x:connector.from.bounds.x,// right: connector.from.bounds.x + connector.from.bou
|
|
|
2308
2308
|
w:connector.from.bounds.w,h:connector.from.bounds.h-options.arrow.threshold*2};const from=getConnectorLinePoint(options,connector.from.element,fromBounds);from.x=connector.from.element.x+connector.from.element.w;const fromBottom=fromBounds.y+fromBounds.h;const toBounds={y:connector.to.bounds.y+options.arrow.threshold,// bottom: connector.to.bounds.y + connector.to.bounds.h - options.arrow.threshold,
|
|
2309
2309
|
x:connector.to.bounds.x,// right: connector.to.bounds.x + connector.to.bounds.w,
|
|
2310
2310
|
w:connector.to.bounds.w,h:connector.to.bounds.h-options.arrow.threshold*2};const toBottom=toBounds.y+toBounds.h;const to=getConnectorLinePoint(options,connector.to.element,toBounds);const maxStartY=Math.max(to.startY,from.startY);from.y=Math.min(maxStartY,from.endY);if(from.y<toBounds.y){from.y=Math.min(toBounds.y,from.endY);}else if(from.y>toBottom){from.y=Math.max(toBottom,from.startY);}to.y=Math.min(maxStartY,to.endY);if(to.y<fromBounds.y){to.y=Math.min(fromBounds.y,to.endY);}else if(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);return{from,to};}function arrowPath(options,x,y,dir){return["M ".concat(x-options.arrow.size," ").concat(y-options.arrow.size*dir," "),"L ".concat(x," ").concat(y),"L ".concat(x+options.arrow.size," ").concat(y-options.arrow.size*dir)].join("");}function moveTo(x,y){return"M".concat(x," ").concat(y);}function lineTo(x,y){return"L".concat(x," ").concat(y);}function join(strings){let delim=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"";return strings.join(delim);}function quadCurve(x1,y1,x,y){return"Q".concat(x1," ").concat(y1," ").concat(x," ").concat(y);}function drawConnectorPath(options,line){const{cornerRadius}=options.path;const{from,to}=line;const{x:fromX,y:fromY}=from;const{x:_toX,y:toY}=to;const toX=_toX-1;const dividerX=to.bounds.x+options.divider.offsetX;const fromPathX=from.isAbove||from.isBelow?fromX+options.arrow.marginX:fromX;const r0=Math.min(cornerRadius,Math.abs(fromPathX-dividerX)/2);const r1=Math.min(cornerRadius,Math.abs(fromY-toY)/2);const cmds=[];if(from.isAbove){cmds.push(moveTo(fromX+options.arrow.marginX,fromY-options.arrow.threshold+options.arrow.marginY),lineTo(fromX+options.arrow.marginX,fromY-r0),quadCurve(fromX+options.arrow.marginX,fromY,fromX+options.arrow.marginX+r0,fromY));}else if(from.isBelow){cmds.push(moveTo(fromX+options.arrow.marginX,fromY+options.arrow.threshold-options.arrow.marginY),lineTo(fromX+options.arrow.marginX,fromY+r0),quadCurve(fromX+options.arrow.marginX,fromY,fromX+options.arrow.marginX+r0,fromY));}else{cmds.push(moveTo(fromX,fromY));}if(to.isAbove){if(fromY<to.bounds.y){cmds.push(lineTo(dividerX-r1,fromY),quadCurve(dividerX,fromY,dividerX,fromY+r1),lineTo(dividerX,toY-r1),quadCurve(dividerX,toY,dividerX+r1,toY),lineTo(dividerX-cornerRadius,toY),quadCurve(dividerX,toY,dividerX,toY-cornerRadius),lineTo(dividerX,toY-options.arrow.threshold+options.arrow.marginY));}else{cmds.push(lineTo(dividerX-cornerRadius,fromY),quadCurve(dividerX,fromY,dividerX,fromY-cornerRadius),lineTo(dividerX,toY-options.arrow.threshold+options.arrow.marginY));}}else if(to.isBelow){if(fromY>to.bounds.y+to.bounds.h){cmds.push(lineTo(dividerX-options.arrow.marginX-r1,fromY),quadCurve(dividerX-options.arrow.marginX,fromY,dividerX-options.arrow.marginX,fromY-r1),lineTo(dividerX-options.arrow.marginX,toY+r1),quadCurve(dividerX-options.arrow.marginX,toY,dividerX-options.arrow.marginX+r1,toY),lineTo(dividerX-cornerRadius,toY),quadCurve(dividerX,toY,dividerX,toY+cornerRadius),lineTo(dividerX,toY+options.arrow.threshold-options.arrow.marginY));}else{cmds.push(lineTo(dividerX-cornerRadius,fromY),quadCurve(dividerX,fromY,dividerX,fromY+cornerRadius),lineTo(dividerX,toY+options.arrow.threshold-options.arrow.marginY));}}else if(fromY<toY){cmds.push(lineTo(dividerX-r0,fromY),quadCurve(dividerX,fromY,dividerX,fromY+r1),lineTo(dividerX,toY-r1),quadCurve(dividerX,toY,dividerX+r1,toY),lineTo(toX,toY));}else{cmds.push(lineTo(dividerX-Math.min(r0,r1),fromY),quadCurve(dividerX,fromY,dividerX,fromY-Math.min(r0,r1)),lineTo(dividerX,toY+r1),quadCurve(dividerX,toY,dividerX+r1,toY),lineTo(toX,toY));}return join(cmds);}function ConnectorPath(props){const{from,options,to}=props;const{strokeWidth}=options.path;const theme=useTheme();const line=useMemo(()=>mapConnectorToLine(options,{from,to}),[from,options,to]);return/* @__PURE__ */jsxs(Fragment,{children:[/* @__PURE__ */jsx("path",{d:drawConnectorPath(options,line),stroke:theme.sanity.color.base.bg,strokeWidth:strokeWidth+4}),/* @__PURE__ */jsx("path",{d:drawConnectorPath(options,line),stroke:rgba$1(theme.sanity.color.base.border,0.5),strokeWidth}),line.from.isAbove&&/* @__PURE__ */jsx("path",{d:arrowPath(options,line.from.x+options.arrow.marginX,line.from.bounds.y-options.arrow.threshold+options.arrow.marginY,-1),stroke:theme.sanity.color.base.border,strokeWidth}),line.from.isBelow&&/* @__PURE__ */jsx("path",{d:arrowPath(options,line.from.x+options.arrow.marginX,line.from.bounds.y+line.from.bounds.h+options.arrow.threshold-options.arrow.marginY,1),stroke:theme.sanity.color.base.border,strokeWidth})]});}const DEBUG=false;const options={arrow:{marginX:10.5,marginY:5,size:4,threshold:16.5},divider:{offsetX:-10.5},path:{cornerRadius:3,marginY:10.5,strokeWidth:1}};function AssistConnectorsOverlay(props){const{connectors}=props;const[,setRedraw]=useState(false);useEffect(()=>{setRedraw(true);},[]);return/* @__PURE__ */jsxs(Fragment,{children:[/* @__PURE__ */jsx("svg",{fill:"none",width:window.innerWidth,height:window.innerHeight,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:150// zIndex,
|
|
2311
|
-
},children:connectors.map(connector=>/* @__PURE__ */jsx(ConnectorPath,{from:connector.from,options,to:connector.to},connector.key))}),DEBUG]});}const legacyAssistDocumentIdPrefix="sanity.ai.";const legacyAssistDocumentTypeName="sanity.ai.docType";const legacyContextDocumentTypeName="ai.instruction.context";const legacyAssistStatusDocumentTypeName="sanity.ai.instructionStatus";const NO_ASSIST_DOCS=[];const NO_CONTEXT_DOCS=[];const NO_IDS=[];function AlphaMigration(){const[alphaAssistDocs,setAlphaAssistDocs]=useState(NO_ASSIST_DOCS);const[contextDocs,setContextDocs]=useState(NO_CONTEXT_DOCS);const[staleStatusDocIds,setStaleStatusDocs]=useState(NO_IDS);const[error,setError]=useState(void 0);const[progress,setProgress]=useState(void 0);const toast=useToast();const client=useClient({apiVersion:"2023-06-01"});useEffect(()=>{let canUpdate=true;client.fetch("\n {\n \"assistDocs\": *[_type==\"".concat(legacyAssistDocumentTypeName,"\"],\n \"staleStatusDocIds\": *[_type==\"").concat(legacyAssistStatusDocumentTypeName,"\"]._id,\n \"contextDocs\": *[_type==\"").concat(legacyContextDocumentTypeName,"\"],\n }\n ")).then(result=>{var _a,_b,_c;if(!canUpdate||!result){return;}setAlphaAssistDocs((_a=result==null?void 0:result.assistDocs)!=null?_a:NO_ASSIST_DOCS);setStaleStatusDocs((_b=result==null?void 0:result.staleStatusDocIds)!=null?_b:NO_IDS);setContextDocs((_c=result==null?void 0:result.contextDocs)!=null?_c:NO_CONTEXT_DOCS);});return()=>{canUpdate=false;};},[client,setAlphaAssistDocs,setStaleStatusDocs,setContextDocs]);const convert=useCallback(async()=>{try{setProgress(1e-4);const tasks=[()=>convertContextDocs(client,contextDocs),subtaskProgress=>deleteDocs(client,staleStatusDocIds,subtaskProgress),subtaskProgress=>convertDocs(client,alphaAssistDocs,subtaskProgress),subtaskProgress=>deleteDocs(client,contextDocs.map(d=>d._id),subtaskProgress)];const taskSize=1/tasks.length;for(let i=0;i<tasks.length;i++){const startProgress=i/tasks.length;await tasks[i](subProgress=>setProgress(startProgress+subProgress*taskSize));setProgress((i+1)/tasks.length);}setProgress(1);setAlphaAssistDocs(NO_ASSIST_DOCS);setContextDocs(NO_CONTEXT_DOCS);setStaleStatusDocs(NO_IDS);toast.push({title:"Converted instructions to new format.",status:"success",description:"Pending feature name",closable:true});}catch(e){console.error(e);toast.push({title:"An error occured",status:"error",closable:true});setError(e);setProgress(void 0);}},[contextDocs,client,alphaAssistDocs,staleStatusDocIds,setProgress,toast]);if((alphaAssistDocs.length||staleStatusDocIds.length||contextDocs.length)&&(!progress||progress<1)){return/* @__PURE__ */jsx(Dialog,{id:"outdated-assist-docs",header:pluginTitle,children:/* @__PURE__ */jsx(Card,{padding:3,children:/* @__PURE__ */jsxs(Stack,{space:4,style:{maxWidth:500},children:[/* @__PURE__ */jsxs(Text,{size:1,children:["It seems like this workspace contains documents from an"," ",/* @__PURE__ */jsxs("strong",{children:["older version of ",pluginTitle]}),"."]}),/* @__PURE__ */jsx(Text,{size:1,children:"Cleanup is required."}),error?/* @__PURE__ */jsxs(Card,{padding:2,tone:"critical",border:true,children:[/* @__PURE__ */jsx(Text,{size:1,children:"An error occurred. See console for details."})," "]}):null,/* @__PURE__ */jsx(Button,{icon:progress?/* @__PURE__ */jsx(Box,{style:{marginTop:5},children:/* @__PURE__ */jsx(Spinner,{})}):CheckmarkIcon,disabled:!!progress,text:progress?"".concat(Math.floor(progress*100),"%"):"Ok, convert to new format!",tone:"primary",onClick:convert})]})})});}return null;}async function deleteDocs(client,ids,updateProgress){const chunkSize=50;for(let i=0;i<ids.length;i+=chunkSize){const progressCount=Math.min(ids.length,i+chunkSize);const chunk=ids.slice(i,progressCount);const trans=client.transaction();chunk.forEach(id=>trans.delete(id));await trans.commit();updateProgress(progressCount/ids.length);}}async function convertContextDocs(client,docs){const trans=client.transaction();for(const doc of docs){const{_id,_type,...rest}=doc;trans.createOrReplace({...rest,_id:"port.".concat(_id),_alphaId:_id,_type:contextDocumentTypeName});}await trans.commit();}async function convertDocs(client,docs,updateProgress){const chunkSize=10;for(let i=0;i<docs.length;i+=chunkSize){const progressCount=Math.min(docs.length,i+chunkSize);const chunk=docs.slice(i,progressCount);const trans=client.transaction();const contextDocs=await client.fetch("*[_type==\"".concat(contextDocumentTypeName,"\" && _alphaId != null]{_id, _alphaId}"));chunk.forEach(oldDoc=>{var _a;const documentType=oldDoc._id.replace(new RegExp("^(".concat(legacyAssistDocumentIdPrefix,"|").concat(assistDocumentIdPrefix,")")),"");const id=assistDocumentId(documentType);const fields=((_a=oldDoc.fields)!=null?_a:[]).filter(field=>{var _a2;return(_a2=field.instructions)==null?void 0:_a2.length;}).map(oldField=>{var _a2;const instructions=((_a2=oldField.instructions)!=null?_a2:[]).map(inst=>{var _a3;const prompt=((_a3=inst.prompt)!=null?_a3:[]).map(block=>{return mapBlock(block,contextDocs);});return{...inst,_type:instructionTypeName,prompt};});return{...oldField,_type:assistFieldTypeName,instructions};});if(fields.length){trans.createOrReplace({_id:id,_type:assistDocumentTypeName,fields});}trans.delete(oldDoc._id);});await trans.commit();updateProgress(progressCount/docs.length);}}function isFieldRef(block){return block._type==="sanity.ai.prompt.fieldRef";}function isContext(block){return block._type==="sanity.ai.prompt.context";}function isUserInput(block){return block._type==="sanity.ai.prompt.userInput";}function isSpan(block){return block._type==="span";}function mapBlock(block,migratedContexts){var _a,_b,_c,_d;if(isFieldRef(block)){return{...block,_type:fieldReferenceTypeName};}if(isUserInput(block)){return{...block,_type:userInputTypeName};}if(isContext(block)){const newBlock={...block,_type:instructionContextTypeName,reference:{_type:"reference",_ref:(_c=(_a=migratedContexts.find(c=>{var _a2;return c._alphaId===((_a2=block.reference)==null?void 0:_a2._ref);}))==null?void 0:_a._id)!=null?_c:(_b=block.reference)==null?void 0:_b._ref}};return newBlock;}if(isSpan(block)){return block;}const textBlock=block;return{...textBlock,children:((_d=textBlock.children)!=null?_d:[]).map(child=>mapBlock(child,migratedContexts))};}function AssistLayout(props){var _a;const[connectors,setConnectors]=useState([]);const migrate=(_a=props.config.alphaMigration)!=null?_a:true;return/* @__PURE__ */jsxs(AiAssistanceConfigProvider,{config:props.config,children:[migrate?/* @__PURE__ */jsx(AlphaMigration,{}):null,/* @__PURE__ */jsx(RunInstructionProvider,{children:/* @__PURE__ */jsxs(ConnectorsProvider,{onConnectorsChange:setConnectors,children:[props.renderDefault(props),/* @__PURE__ */jsx(ThemeProvider,{tone:"default",children:/* @__PURE__ */jsx(AssistConnectorsOverlay,{connectors})})]})})]});}const WrapPreCard=styled(Card)(_templateObject9||(_templateObject9=_taggedTemplateLiteral(["\n & pre {\n white-space: pre-wrap !important;\n }\n"])));function SafeValueInput(props){return/* @__PURE__ */jsx(ErrorWrapper,{onChange:props.onChange,children:/* @__PURE__ */jsx(PteValueFixer,{...props})});}function ErrorWrapper(props){const{onChange}=props;const[error,setError]=useState();const catchError=useCallback(params=>{setError(params.error);},[setError]);const unsetValue=useCallback(()=>onChange(PatchEvent.from(unset())),[onChange]);const dismiss=useCallback(()=>setError(void 0),[]);const catcher=/* @__PURE__ */jsx(ErrorBoundary,{onCatch:catchError,children:props.children});return error?/* @__PURE__ */jsx(Card,{border:true,tone:"critical",padding:2,contentEditable:false,children:/* @__PURE__ */jsxs(Stack,{space:3,children:[/* @__PURE__ */jsx(Text,{muted:true,weight:"semibold",children:"An error occurred."}),/* @__PURE__ */jsx(WrapPreCard,{flex:1,padding:2,tone:"critical",border:true,children:catcher}),/* @__PURE__ */jsxs(Flex,{width:"fill",flex:1,gap:3,children:[/* @__PURE__ */jsx(Box,{flex:1,children:/* @__PURE__ */jsx(Button,{text:"Dismiss",onClick:dismiss,tone:"primary"})}),/* @__PURE__ */jsx(Button,{text:"Unset value",onClick:unsetValue,tone:"critical"})]})]})}):catcher;}function PteValueFixer(props){const isPortableText=useMemo(()=>isArraySchemaType(props.schemaType)&&isPortableTextArray(props.schemaType),[props.schemaType]);const value=props.value;if(isPortableText&&value&&!value.length){return props.renderDefault({...props,value:void 0});}return props.renderDefault(props);}function AssistFormBlock(props){const presence=useAssistPresence(props.path,true);const{onChange}=useFormCallbacks();const key=props.value._key;const localOnChange=useCallback(patchEvent=>{if(!key){return;}onChange(PatchEvent.from(patchEvent).prefixAll({_key:key}));},[onChange,key]);return/* @__PURE__ */jsx(ErrorWrapper,{onChange:localOnChange,children:/* @__PURE__ */jsxs(Flex,{align:"center",justify:"space-between",children:[/* @__PURE__ */jsx(Box,{flex:1,children:props.renderDefault(props)}),presence.map(pre=>/* @__PURE__ */jsx(AiFieldPresence,{presence:pre},pre.lastActiveAt))]})});}function AssistItem(props){const{path}=props;const presence=useAssistPresence(path,true);return/* @__PURE__ */jsxs(Flex,{align:"center",width:"fill",style:{position:"relative"},children:[/* @__PURE__ */jsx(Box,{flex:1,children:props.renderDefault({...props})}),presence.map(pre=>/* @__PURE__ */jsx(Box,{style:{position:"absolute",right:35},children:/* @__PURE__ */jsx(AiFieldPresence,{presence:pre})},pre.user.id))]});}function BackToInstructionListLink(){const{openInspector}=useDocumentPane();const goBack=useCallback(()=>openInspector(aiInspectorId,{[instructionParam]:void 0}),[openInspector]);return/* @__PURE__ */jsx("div",{children:/* @__PURE__ */jsx(Button,{as:"a",fontSize:1,icon:ArrowLeftIcon,mode:"bleed",padding:1,space:2,onClick:goBack,text:" Instructions",textAlign:"left"})});}const EMPTY_FIELDS=[];function AssistDocumentForm(props){const{onChange}=props;const value=props.value;const id=value==null?void 0:value._id;const fields=value==null?void 0:value.fields;const onChangeCalled=useRef(false);const targetDocumentType=useMemo(()=>{if(!id){return void 0;}return documentTypeFromAiDocumentId(id);},[id]);const{params,setParams}=useAiPaneRouter();const pathKey=params[fieldPathParam];const instruction=params[instructionParam];const activeKey=useMemo(()=>{var _a;return(_a=(fields!=null?fields:EMPTY_FIELDS).find(f=>f.path===pathKey))==null?void 0:_a._key;},[fields,pathKey]);const activePath=useMemo(()=>{if(!activeKey){return void 0;}const base=["fields",{_key:activeKey}];return instruction?[...base,"instructions",{_key:instruction}]:base;},[activeKey,instruction]);const schema=useSchema();const documentSchema=useMemo(()=>{if(!targetDocumentType){return void 0;}return schema.get(targetDocumentType);},[schema,targetDocumentType]);const fieldSchema=useSelectedSchema(pathKey,documentSchema);const context=useMemo(()=>({documentSchema,fieldSchema:fieldSchema!=null?fieldSchema:documentSchema}),[fieldSchema,documentSchema]);const title=value==null?void 0:value.title;useEffect(()=>{var _a;if(!title&&documentSchema&&!(id==null?void 0:id.startsWith("drafts."))){onChange(set((_a=documentSchema.title)!=null?_a:documentSchema.name,["title"]));}},[title,documentSchema,onChange,id]);const fieldExists=fields==null?void 0:fields.some(f=>f._key===pathKey);useEffect(()=>{if(onChangeCalled.current||fieldExists||activePath||!pathKey){return;}onChange([setIfMissing([],["fields"]),insert([typed({_key:pathKey,_type:assistFieldTypeName,path:pathKey})],"after",["fields",-1])]);onChangeCalled.current=true;},[activePath,onChange,pathKey,fieldExists]);const{onPathOpen,...formCallbacks}=useFormCallbacks();const newCallbacks=useMemo(()=>({...formCallbacks,onPathOpen:path=>{var _a;if(!instruction&&path.length===4&&path[2]==="instructions"){setParams(typed({...params,[instructionParam]:(_a=path[3])==null?void 0:_a._key}));onPathOpen([]);}else{setTimeout(()=>onPathOpen(path),0);}}}),[formCallbacks,onPathOpen,params,setParams,instruction]);useEffect(()=>{if(activePath&&!instruction){onPathOpen([]);}},[activePath,instruction,onPathOpen]);return/* @__PURE__ */jsx(SelectedFieldContextProvider,{value:context,children:/* @__PURE__ */jsxs(Stack,{space:5,children:[instruction&&/* @__PURE__ */jsx(BackToInstructionListLink,{}),activePath&&/* @__PURE__ */jsx(FormCallbacksProvider,{...newCallbacks,children:/* @__PURE__ */jsx("div",{style:{lineHeight:"1.25em"},children:/* @__PURE__ */jsx(FormInput,{...props,absolutePath:activePath})})}),!activePath&&props.renderDefault(props)]})});}function useSelectedSchema(fieldPath,documentSchema){return useMemo(()=>{if(!fieldPath){return void 0;}if(fieldPath===documentRootKey){return documentSchema;}const path=stringToPath(fieldPath);let currentSchema=documentSchema;for(let i=0;i<path.length;i++){const segment=path[i];const field=currentSchema==null?void 0:currentSchema.fields.find(f=>f.name===segment);if(!field){return void 0;}if(i===path.length-1){return field.type;}if(field.type.jsonType!=="object"){return void 0;}currentSchema=field.type;}return currentSchema;},[documentSchema,fieldPath]);}function findFieldMember(members,fieldName){return members.find(m=>m.kind==="field"&&m.name===fieldName||m.kind==="error"&&m.fieldName===fieldName);}function findFieldsetMember(members,fieldsetName){return members.find(m=>m.kind==="fieldSet"&&m.fieldSet.name===fieldsetName);}function InstructionInput(props){return/* @__PURE__ */jsxs(Stack,{space:[4,4,4,5],children:[/* @__PURE__ */jsx(NameField,{...props}),/* @__PURE__ */jsx(ShareField,{...props}),/* @__PURE__ */jsx(PromptField,{...props})]});}function PromptField(props){const promptMember=findFieldMember(props.members,"prompt");return promptMember?/* @__PURE__ */jsx(ObjectInputMember,{...props,member:promptMember}):null;}const NONE=[];function NameField(props){var _a;const fieldsetMember=findFieldsetMember(props.members,"appearance");const titleId=useId();const members=(_a=fieldsetMember==null?void 0:fieldsetMember.fieldSet.members)!=null?_a:NONE;const iconMember=findFieldMember(members,"icon");const titleMember=findFieldMember(members,"title");const titlePlaceholder="Untitled";const moddedTitleMember=useMemo(()=>{if(!titleMember){return void 0;}if(titleMember.kind==="error"){return titleMember;}return{...titleMember,field:{...(titleMember==null?void 0:titleMember.field),schemaType:{...(titleMember==null?void 0:titleMember.field.schemaType),placeholder:titlePlaceholder}}};},[titleMember,titlePlaceholder]);return/* @__PURE__ */jsx(Stack,{space:5,children:/* @__PURE__ */jsxs(Stack,{space:2,children:[/* @__PURE__ */jsx(Flex,{gap:1,children:/* @__PURE__ */jsx(Text,{as:"label",weight:"semibold",size:1,htmlFor:titleId,children:"Name"})}),/* @__PURE__ */jsx(Text,{muted:true,size:1,children:"How this instruction appears in menus"}),/* @__PURE__ */jsxs(Flex,{align:"center",children:[iconMember&&/* @__PURE__ */jsx(Box,{flex:"none",children:/* @__PURE__ */jsx(ObjectInputMember,{...props,member:iconMember})}),moddedTitleMember&&/* @__PURE__ */jsx(Box,{flex:1,style:{marginLeft:-1},children:/* @__PURE__ */jsx(ObjectInputMember,{...props,member:moddedTitleMember})})]})]})});}function ShareField(props){var _a;const fieldsetMember=findFieldsetMember(props.members,"appearance");const members=(_a=fieldsetMember==null?void 0:fieldsetMember.fieldSet.members)!=null?_a:NONE;const visibilityMember=findFieldMember(members,"userId");return/* @__PURE__ */jsx(Fragment,{children:visibilityMember&&/* @__PURE__ */jsx(ObjectInputMember,{...props,member:visibilityMember})});}function HiddenFieldTitle(props){return props.renderDefault({...props,title:"",level:props.level-2,changed:false});}function InstructionVisibility(props){const{value,onChange}=props;const user=useCurrentUser();const handleChange=useCallback(()=>{var _a;const newValue=value?"":(_a=user==null?void 0:user.id)!=null?_a:"";onChange(newValue?set(newValue):unset());},[onChange,user,value]);const id=useId();return/* @__PURE__ */jsx(Card,{children:/* @__PURE__ */jsxs(Flex,{gap:2,align:"flex-start",children:[/* @__PURE__ */jsx("div",{style:{margin:"-3px 0"},children:/* @__PURE__ */jsx(Switch,{...props.elementProps,id,value:"".concat(!value),checked:!value,onChange:handleChange,disabled:props.elementProps.readOnly})}),/* @__PURE__ */jsx(Text,{muted:true,size:1,weight:"medium",children:/* @__PURE__ */jsx("label",{htmlFor:id,children:"Make visible to all Studio members"})})]})});}function IconInput(props){const{value,onChange}=props;const id=useId();const items=useMemo(()=>Object.entries(icons).map(_ref74=>{let[key,icon]=_ref74;return/* @__PURE__ */jsx(IconItem,{iconKey:key,icon,onChange},key);}),[onChange]);const selectedIcon=useMemo(()=>getIcon(value),[value]);return/* @__PURE__ */jsx(MenuButton,{button:/* @__PURE__ */jsx(Button,{icon:selectedIcon,title:"Select icon",padding:3,mode:"ghost",radius:1}),id,menu:/* @__PURE__ */jsx(Menu,{style:{maxHeight:300},children:items}),popover:{portal:true}});}function IconItem(_ref75){let{icon,iconKey:key,onChange}=_ref75;const onClick=useCallback(()=>onChange(set(key)),[onChange,key]);return/* @__PURE__ */jsx(MenuItem,{icon,title:key,text:key,onClick});}function getIcon(iconName){var _a,_b;return(_b=(_a=Object.entries(icons).find(_ref76=>{let[key]=_ref76;return key===iconName;}))==null?void 0:_a[1])!=null?_b:icons.sparkles;}function FieldAutocomplete(props){const{id,schemaType,fieldPath,onSelect,includeDocument}=props;const fieldNames=useMemo(()=>{if(includeDocument){return getFieldRefsWithDocument(schemaType);}return getFieldRefs(schemaType);},[schemaType,includeDocument]);const currentField=useMemo(()=>fieldNames.find(f=>f.key===fieldPath),[fieldPath,fieldNames]);const autocompleteOptions=useMemo(()=>fieldNames.map(field=>({value:field.key,field})),[fieldNames]);const renderOption=useCallback(option=>{const{value,field}=option;if(!value){return/* @__PURE__ */jsx(Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsx(Text,{accent:true,size:1,children:option.value})});}if(isType(field.schemaType,"document")){return/* @__PURE__ */jsx(Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsx(Text,{size:1,weight:"semibold",children:"The entire document"})});}const splitTitle=field.title.split("/");return/* @__PURE__ */jsx(Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsxs(Flex,{gap:3,children:[/* @__PURE__ */jsx(Text,{size:1,children:createElement(field.icon)}),/* @__PURE__ */jsx(Box,{flex:"none",children:/* @__PURE__ */jsxs(Breadcrumbs,{separator:/* @__PURE__ */jsx(Text,{muted:true,size:1,children:"/"}),space:1,children:[splitTitle.slice(0,splitTitle.length-1).map((pt,i)=>// eslint-disable-next-line react/no-array-index-key
|
|
2312
|
-
/* @__PURE__ */jsx(Text,{muted:true,size:1,children:pt.trim()},i)),/* @__PURE__ */jsx(Text,{size:1,weight:"medium",children:splitTitle[splitTitle.length-1]})]})})]})});},[]);const renderValue=useCallback((value,option)=>{var _a;return(_a=option==null?void 0:option.field.title)!=null?_a:value;},[]);const filterOption=useCallback((query,option)=>{var _a,_b,_c;const lQuery=query.toLowerCase();return((_a=option==null?void 0:option.value)==null?void 0:_a.toLowerCase().includes(lQuery))||((_c=(_b=option==null?void 0:option.field)==null?void 0:_b.title)==null?void 0:_c.toLowerCase().includes(lQuery));},[]);return/* @__PURE__ */jsx(Autocomplete,{fontSize:1,icon:currentField?currentField.icon:SearchIcon,onChange:onSelect,openButton:true,id,options:autocompleteOptions,placeholder:"Search for a field",radius:2,renderOption,renderValue,value:currentField==null?void 0:currentField.key,filterOption});}function FieldRefPathInput(props){var _a;const documentSchema=(_a=useContext(SelectedFieldContext))==null?void 0:_a.documentSchema;const ref=useRef(null);const id=useId();const{onChange}=props;useEffect(()=>{var _a2,_b;(_b=(_a2=ref.current)==null?void 0:_a2.querySelector("input"))==null?void 0:_b.focus();},[]);const onSelect=useCallback(path=>onChange(set(path)),[onChange]);if(!documentSchema){return props.renderDefault(props);}return/* @__PURE__ */jsx(Box,{flex:1,style:{minWidth:200},ref,children:/* @__PURE__ */jsx(FieldAutocomplete,{id,schemaType:documentSchema,onSelect,fieldPath:props.value})});}function InstructionsArrayInput(props){const user=useCurrentUser();const originalValue=props.value;const originalMembers=props.members;const value=useMemo(()=>(originalValue!=null?originalValue:[]).filter(v=>!v.userId||v.userId===(user==null?void 0:user.id)),[originalValue,user]);const members=useMemo(()=>(originalMembers!=null?originalMembers:[]).filter(v=>{var _a;if(v.kind==="error"){return true;}const value2=(_a=v==null?void 0:v.item)==null?void 0:_a.value;return!value2.userId||value2.userId===(user==null?void 0:user.id);}),[originalMembers,user]);return props.renderDefault({...props,value,members});}const InlineBlockValueContext=createContext(void 0);function AssistInlineFormBlock(props){return/* @__PURE__ */jsx(InlineBlockValueContext.Provider,{value:props.value,children:/* @__PURE__ */jsx(Box,{flex:1,children:props.renderDefault(props)})});}function FieldRefPreview(props){var _a,_b,_c,_d;const documentSchema=(_a=useContext(SelectedFieldContext))==null?void 0:_a.documentSchema;const path=(_c=(_b=useContext(InlineBlockValueContext))==null?void 0:_b.path)!=null?_c:props.path;const selectedField=useSelectedField(documentSchema,path);return/* @__PURE__ */jsxs(Flex,{gap:2,align:"center",style:{width:"100%"},children:[/* @__PURE__ */jsx(Flex,{flex:1,gap:2,align:"center",paddingY:3,paddingX:1,children:/* @__PURE__ */jsx(Box,{children:/* @__PURE__ */jsx(Text,{size:1,textOverflow:"ellipsis",children:(_d=selectedField==null?void 0:selectedField.title)!=null?_d:"Select field"})})}),/* @__PURE__ */jsx(Fragment,{children:props.actions})]});}function HideReferenceChangedBannerInput(props){const ref=useRef(null);useEffect(()=>{var _a;const parent=(_a=ref.current)==null?void 0:_a.closest('[data-testid="pane-content"]');if(!parent){return;}const style=document.createElement("style");const parentId="id-".concat(Math.random()).replace(".","-");parent.id=parentId;style.innerText="\n #".concat(parentId," [data-testid=\"reference-changed-banner\"] { display: none; }\n ");parent.prepend(style);},[ref]);return/* @__PURE__ */jsx(Box,{ref,children:props.renderDefault(props)});}const contextDocumentSchema=defineType({type:"document",name:contextDocumentTypeName,title:"AI context",liveEdit:true,icon:TokenIcon,components:{input:HideReferenceChangedBannerInput},fields:[defineField({type:"string",name:"title",title:"Title"}),defineField({name:"context",type:"array",title:"Context",of:[defineArrayMember({type:"block",styles:[{title:"Normal",value:"normal"}],lists:[],marks:{decorators:[],annotations:[]}})]})],preview:{select:{title:"title",context:"context"},prepare(
|
|
2313
|
-
function getRandomValues(typedArray){return window.crypto.getRandomValues(typedArray);}function whatwgRNG(){let length=arguments.length>0&&arguments[0]!==undefined?arguments[0]:16;const rnds8=new Uint8Array(length);getRandomValues(rnds8);return rnds8;}const getByteHexTable=(()=>{let table;return()=>{if(table){return table;}table=[];for(let i=0;i<256;++i){table[i]=(i+256).toString(16).substring(1);}return table;};})();function randomKey(length){const table=getByteHexTable();return whatwgRNG(length).reduce((str,n)=>str+table[n],"").slice(0,length);}const PteMods=styled(Box)(_templateObject10||(_templateObject10=_taggedTemplateLiteral(["\n & [data-testid='pt-editor__toolbar-card'] > div > div:last-child {\n display: none;\n }\n & [data-testid='pt-editor'] {\n min-height: 300px;\n }\n & [data-testid='pt-editor'] .pt-inline-object * {\n max-width: 400px;\n }\n"])));function PromptInput(props){useOnlyInlineBlocks(props);return/* @__PURE__ */jsx(PteMods,{children:props.renderDefault(props)});}function useOnlyInlineBlocks(props){useEffect(()=>{var _a;let needsFix=false;const val=((_a=props.value)!=null?_a:[]).map(block=>{if(block._type==="block"){return block;}needsFix=true;return typed({_key:randomKey(12),_type:"block",level:0,markDefs:[],style:"normal",children:[block]});});if(needsFix){props.onChange(set(val));}},[]);}function InstructionsArrayField(props){return props.renderDefault({...props,title:void 0});}const fieldReference=defineType({type:"object",name:fieldReferenceTypeName,title:"Document field",icon:ThListIcon,fields:[defineField({type:"string",name:"path",title:"Field",components:{input:FieldRefPathInput},validation:rule=>rule.custom((value,context)=>{var _a;if(!value){return"Please select a field";}try{const docId=(_a=context.document)==null?void 0:_a._id;if(!docId){return"Field reference cannot be used outside document inspector context. Could not resolve document id.";}const targetDocType=docId.replace(new RegExp("^".concat(assistDocumentIdPrefix)),"");const schema=context.schema.get(targetDocType);if(!schema){return"Field reference cannot be used outside document inspector context. Could not resolve schema: ".concat(targetDocType);}const refs=getFieldRefsWithDocument(schema);const fieldRef=refs.find(r=>r.key===value);if(!fieldRef){return"Field with path \"".concat(value,"\" does not exist in the schema.");}return true;}catch(e){console.error("Failed to resolve field reference",e);return"Invalid field reference.";}})})],preview:{select:{path:"path"},prepare(
|
|
2311
|
+
},children:connectors.map(connector=>/* @__PURE__ */jsx(ConnectorPath,{from:connector.from,options,to:connector.to},connector.key))}),DEBUG]});}const legacyAssistDocumentIdPrefix="sanity.ai.";const legacyAssistDocumentTypeName="sanity.ai.docType";const legacyContextDocumentTypeName="ai.instruction.context";const legacyAssistStatusDocumentTypeName="sanity.ai.instructionStatus";const NO_ASSIST_DOCS=[];const NO_CONTEXT_DOCS=[];const NO_IDS=[];function AlphaMigration(){const[alphaAssistDocs,setAlphaAssistDocs]=useState(NO_ASSIST_DOCS);const[contextDocs,setContextDocs]=useState(NO_CONTEXT_DOCS);const[staleStatusDocIds,setStaleStatusDocs]=useState(NO_IDS);const[error,setError]=useState(void 0);const[progress,setProgress]=useState(void 0);const toast=useToast();const client=useClient({apiVersion:"2023-06-01"});useEffect(()=>{let canUpdate=true;client.fetch("\n {\n \"assistDocs\": *[_type==\"".concat(legacyAssistDocumentTypeName,"\"],\n \"staleStatusDocIds\": *[_type==\"").concat(legacyAssistStatusDocumentTypeName,"\"]._id,\n \"contextDocs\": *[_type==\"").concat(legacyContextDocumentTypeName,"\"],\n }\n ")).then(result=>{var _a,_b,_c;if(!canUpdate||!result){return;}setAlphaAssistDocs((_a=result==null?void 0:result.assistDocs)!=null?_a:NO_ASSIST_DOCS);setStaleStatusDocs((_b=result==null?void 0:result.staleStatusDocIds)!=null?_b:NO_IDS);setContextDocs((_c=result==null?void 0:result.contextDocs)!=null?_c:NO_CONTEXT_DOCS);});return()=>{canUpdate=false;};},[client,setAlphaAssistDocs,setStaleStatusDocs,setContextDocs]);const convert=useCallback(async()=>{try{setProgress(1e-4);const tasks=[()=>convertContextDocs(client,contextDocs),subtaskProgress=>deleteDocs(client,staleStatusDocIds,subtaskProgress),subtaskProgress=>convertDocs(client,alphaAssistDocs,subtaskProgress),subtaskProgress=>deleteDocs(client,contextDocs.map(d=>d._id),subtaskProgress)];const taskSize=1/tasks.length;for(let i=0;i<tasks.length;i++){const startProgress=i/tasks.length;await tasks[i](subProgress=>setProgress(startProgress+subProgress*taskSize));setProgress((i+1)/tasks.length);}setProgress(1);setAlphaAssistDocs(NO_ASSIST_DOCS);setContextDocs(NO_CONTEXT_DOCS);setStaleStatusDocs(NO_IDS);toast.push({title:"Converted instructions to new format.",status:"success",closable:true});}catch(e){console.error(e);toast.push({title:"An error occurred",status:"error",closable:true});setError(e);setProgress(void 0);}},[contextDocs,client,alphaAssistDocs,staleStatusDocIds,setProgress,toast]);if((alphaAssistDocs.length||staleStatusDocIds.length||contextDocs.length)&&(!progress||progress<1)){return/* @__PURE__ */jsx(Dialog,{id:"outdated-assist-docs",header:pluginTitle,children:/* @__PURE__ */jsx(Card,{padding:3,children:/* @__PURE__ */jsxs(Stack,{space:4,style:{maxWidth:500},children:[/* @__PURE__ */jsxs(Text,{size:1,children:["It seems like this workspace contains documents from an"," ",/* @__PURE__ */jsxs("strong",{children:["older version of ",pluginTitle]}),"."]}),/* @__PURE__ */jsx(Text,{size:1,children:"Cleanup is required."}),error?/* @__PURE__ */jsxs(Card,{padding:2,tone:"critical",border:true,children:[/* @__PURE__ */jsx(Text,{size:1,children:"An error occurred. See console for details."})," "]}):null,/* @__PURE__ */jsx(Button,{icon:progress?/* @__PURE__ */jsx(Box,{style:{marginTop:5},children:/* @__PURE__ */jsx(Spinner,{})}):CheckmarkIcon,disabled:!!progress,text:progress?"".concat(Math.floor(progress*100),"%"):"Ok, convert to new format!",tone:"primary",onClick:convert})]})})});}return null;}async function deleteDocs(client,ids,updateProgress){const chunkSize=50;for(let i=0;i<ids.length;i+=chunkSize){const progressCount=Math.min(ids.length,i+chunkSize);const chunk=ids.slice(i,progressCount);const trans=client.transaction();chunk.forEach(id=>trans.delete(id));await trans.commit();updateProgress(progressCount/ids.length);}}async function convertContextDocs(client,docs){const trans=client.transaction();for(const doc of docs){const{_id,_type,...rest}=doc;trans.createOrReplace({...rest,_id:"port.".concat(_id),_alphaId:_id,_type:contextDocumentTypeName});}await trans.commit();}async function convertDocs(client,docs,updateProgress){const chunkSize=10;for(let i=0;i<docs.length;i+=chunkSize){const progressCount=Math.min(docs.length,i+chunkSize);const chunk=docs.slice(i,progressCount);const trans=client.transaction();const contextDocs=await client.fetch("*[_type==\"".concat(contextDocumentTypeName,"\" && _alphaId != null]{_id, _alphaId}"));chunk.forEach(oldDoc=>{var _a;const documentType=oldDoc._id.replace(new RegExp("^(".concat(legacyAssistDocumentIdPrefix,"|").concat(assistDocumentIdPrefix,")")),"");const id=assistDocumentId(documentType);const fields=((_a=oldDoc.fields)!=null?_a:[]).filter(field=>{var _a2;return(_a2=field.instructions)==null?void 0:_a2.length;}).map(oldField=>{var _a2;const instructions=((_a2=oldField.instructions)!=null?_a2:[]).map(inst=>{var _a3;const prompt=((_a3=inst.prompt)!=null?_a3:[]).map(block=>{return mapBlock(block,contextDocs);});return{...inst,_type:instructionTypeName,prompt};});return{...oldField,_type:assistFieldTypeName,instructions};});if(fields.length){trans.createOrReplace({_id:id,_type:assistDocumentTypeName,fields});}trans.delete(oldDoc._id);});await trans.commit();updateProgress(progressCount/docs.length);}}function isFieldRef(block){return block._type==="sanity.ai.prompt.fieldRef";}function isContext(block){return block._type==="sanity.ai.prompt.context";}function isUserInput(block){return block._type==="sanity.ai.prompt.userInput";}function isSpan(block){return block._type==="span";}function mapBlock(block,migratedContexts){var _a,_b,_c,_d;if(isFieldRef(block)){return{...block,_type:fieldReferenceTypeName};}if(isUserInput(block)){return{...block,_type:userInputTypeName};}if(isContext(block)){const newBlock={...block,_type:instructionContextTypeName,reference:{_type:"reference",_ref:(_c=(_a=migratedContexts.find(c=>{var _a2;return c._alphaId===((_a2=block.reference)==null?void 0:_a2._ref);}))==null?void 0:_a._id)!=null?_c:(_b=block.reference)==null?void 0:_b._ref}};return newBlock;}if(isSpan(block)){return block;}const textBlock=block;return{...textBlock,children:((_d=textBlock.children)!=null?_d:[]).map(child=>mapBlock(child,migratedContexts))};}function AssistLayout(props){var _a;const[connectors,setConnectors]=useState([]);const migrate=(_a=props.config.alphaMigration)!=null?_a:true;return/* @__PURE__ */jsxs(AiAssistanceConfigProvider,{config:props.config,children:[migrate?/* @__PURE__ */jsx(AlphaMigration,{}):null,/* @__PURE__ */jsx(RunInstructionProvider,{children:/* @__PURE__ */jsxs(ConnectorsProvider,{onConnectorsChange:setConnectors,children:[props.renderDefault(props),/* @__PURE__ */jsx(ThemeProvider,{tone:"default",children:/* @__PURE__ */jsx(AssistConnectorsOverlay,{connectors})})]})})]});}const WrapPreCard=styled(Card)(_templateObject9||(_templateObject9=_taggedTemplateLiteral(["\n & pre {\n white-space: pre-wrap !important;\n }\n"])));function SafeValueInput(props){return/* @__PURE__ */jsx(ErrorWrapper,{onChange:props.onChange,children:/* @__PURE__ */jsx(PteValueFixer,{...props})});}function ErrorWrapper(props){const{onChange}=props;const[error,setError]=useState();const catchError=useCallback(params=>{setError(params.error);},[setError]);const unsetValue=useCallback(()=>onChange(PatchEvent.from(unset())),[onChange]);const dismiss=useCallback(()=>setError(void 0),[]);const catcher=/* @__PURE__ */jsx(ErrorBoundary,{onCatch:catchError,children:props.children});return error?/* @__PURE__ */jsx(Card,{border:true,tone:"critical",padding:2,contentEditable:false,children:/* @__PURE__ */jsxs(Stack,{space:3,children:[/* @__PURE__ */jsx(Text,{muted:true,weight:"semibold",children:"An error occurred."}),/* @__PURE__ */jsx(WrapPreCard,{flex:1,padding:2,tone:"critical",border:true,children:catcher}),/* @__PURE__ */jsxs(Flex,{width:"fill",flex:1,gap:3,children:[/* @__PURE__ */jsx(Box,{flex:1,children:/* @__PURE__ */jsx(Button,{text:"Dismiss",onClick:dismiss,tone:"primary"})}),/* @__PURE__ */jsx(Button,{text:"Unset value",onClick:unsetValue,tone:"critical"})]})]})}):catcher;}function PteValueFixer(props){const isPortableText=useMemo(()=>isArraySchemaType(props.schemaType)&&isPortableTextArray(props.schemaType),[props.schemaType]);const value=props.value;if(isPortableText&&value&&!value.length){return props.renderDefault({...props,value:void 0});}return props.renderDefault(props);}function AssistFormBlock(props){const presence=useAssistPresence(props.path,true);const{onChange}=useFormCallbacks();const key=props.value._key;const localOnChange=useCallback(patchEvent=>{if(!key){return;}onChange(PatchEvent.from(patchEvent).prefixAll({_key:key}));},[onChange,key]);return/* @__PURE__ */jsx(ErrorWrapper,{onChange:localOnChange,children:/* @__PURE__ */jsxs(Flex,{align:"center",justify:"space-between",children:[/* @__PURE__ */jsx(Box,{flex:1,children:props.renderDefault(props)}),presence.map(pre=>/* @__PURE__ */jsx(AiFieldPresence,{presence:pre},pre.lastActiveAt))]})});}function AssistItem(props){const{path}=props;const presence=useAssistPresence(path,true);return/* @__PURE__ */jsxs(Flex,{align:"center",width:"fill",style:{position:"relative"},children:[/* @__PURE__ */jsx(Box,{flex:1,children:props.renderDefault({...props})}),presence.map(pre=>/* @__PURE__ */jsx(Box,{style:{position:"absolute",right:35},children:/* @__PURE__ */jsx(AiFieldPresence,{presence:pre})},pre.user.id))]});}function BackToInstructionListLink(){const{openInspector}=useDocumentPane();const goBack=useCallback(()=>openInspector(aiInspectorId,{[instructionParam]:void 0}),[openInspector]);return/* @__PURE__ */jsx("div",{children:/* @__PURE__ */jsx(Button,{as:"a",fontSize:1,icon:ArrowLeftIcon,mode:"bleed",padding:1,space:2,onClick:goBack,text:" Instructions",textAlign:"left"})});}const EMPTY_FIELDS=[];function AssistDocumentForm(props){const{onChange}=props;const value=props.value;const id=value==null?void 0:value._id;const fields=value==null?void 0:value.fields;const targetDocumentType=useMemo(()=>{if(!id){return void 0;}return documentTypeFromAiDocumentId(id);},[id]);const{params,setParams}=useAiPaneRouter();const pathKey=params[fieldPathParam];const instruction=params[instructionParam];const activeKey=useMemo(()=>{var _a;return(_a=(fields!=null?fields:EMPTY_FIELDS).find(f=>f.path===pathKey))==null?void 0:_a._key;},[fields,pathKey]);const activePath=useMemo(()=>{if(!activeKey){return void 0;}const base=["fields",{_key:activeKey}];return instruction?[...base,"instructions",{_key:instruction}]:base;},[activeKey,instruction]);const schema=useSchema();const documentSchema=useMemo(()=>{if(!targetDocumentType){return void 0;}return schema.get(targetDocumentType);},[schema,targetDocumentType]);const fieldSchema=useSelectedSchema(pathKey,documentSchema);const context=useMemo(()=>({documentSchema,fieldSchema:fieldSchema!=null?fieldSchema:documentSchema}),[fieldSchema,documentSchema]);const title=value==null?void 0:value.title;useEffect(()=>{var _a;if(!title&&documentSchema&&!(id==null?void 0:id.startsWith("drafts."))){onChange(set((_a=documentSchema.title)!=null?_a:documentSchema.name,["title"]));}},[title,documentSchema,onChange,id]);const fieldExists=!!(fields==null?void 0:fields.some(f=>f._key===pathKey));const{onPathOpen,...formCallbacks}=useFormCallbacks();const newCallbacks=useMemo(()=>({...formCallbacks,onPathOpen:path=>{var _a;if(!instruction&&path.length===4&&path[2]==="instructions"){setParams(typed({...params,[instructionParam]:(_a=path[3])==null?void 0:_a._key}));onPathOpen([]);}else{setTimeout(()=>onPathOpen(path),0);}}}),[formCallbacks,onPathOpen,params,setParams,instruction]);useEffect(()=>{if(activePath&&!instruction){onPathOpen([]);}},[activePath,instruction,onPathOpen]);return/* @__PURE__ */jsx(SelectedFieldContextProvider,{value:context,children:/* @__PURE__ */jsxs(Stack,{space:5,children:[/* @__PURE__ */jsx(FieldsInitializer,{pathKey,activePath,fieldExists,onChange},pathKey),instruction&&/* @__PURE__ */jsx(BackToInstructionListLink,{}),activePath&&/* @__PURE__ */jsx(FormCallbacksProvider,{...newCallbacks,children:/* @__PURE__ */jsx("div",{style:{lineHeight:"1.25em"},children:/* @__PURE__ */jsx(FormInput,{...props,absolutePath:activePath})})}),!activePath&&props.renderDefault(props)]})});}function useSelectedSchema(fieldPath,documentSchema){return useMemo(()=>{if(!fieldPath){return void 0;}if(fieldPath===documentRootKey){return documentSchema;}const path=stringToPath(fieldPath);let currentSchema=documentSchema;for(let i=0;i<path.length;i++){const segment=path[i];const field=currentSchema==null?void 0:currentSchema.fields.find(f=>f.name===segment);if(!field){return void 0;}if(i===path.length-1){return field.type;}if(field.type.jsonType!=="object"){return void 0;}currentSchema=field.type;}return currentSchema;},[documentSchema,fieldPath]);}function FieldsInitializer(_ref74){let{pathKey,activePath,fieldExists,onChange}=_ref74;const initialized=useRef(false);useEffect(()=>{if(initialized.current||fieldExists||activePath||!pathKey){return;}onChange([setIfMissing([],["fields"]),insert([typed({_key:pathKey,_type:assistFieldTypeName,path:pathKey})],"after",["fields",-1])]);initialized.current=true;},[activePath,onChange,pathKey,fieldExists]);return null;}function findFieldMember(members,fieldName){return members.find(m=>m.kind==="field"&&m.name===fieldName||m.kind==="error"&&m.fieldName===fieldName);}function findFieldsetMember(members,fieldsetName){return members.find(m=>m.kind==="fieldSet"&&m.fieldSet.name===fieldsetName);}function InstructionInput(props){return/* @__PURE__ */jsxs(Stack,{space:[4,4,4,5],children:[/* @__PURE__ */jsx(NameField,{...props}),/* @__PURE__ */jsx(ShareField,{...props}),/* @__PURE__ */jsx(PromptField,{...props})]});}function PromptField(props){const promptMember=findFieldMember(props.members,"prompt");return promptMember?/* @__PURE__ */jsx(ObjectInputMember,{...props,member:promptMember}):null;}const NONE=[];function NameField(props){var _a;const fieldsetMember=findFieldsetMember(props.members,"appearance");const titleId=useId();const members=(_a=fieldsetMember==null?void 0:fieldsetMember.fieldSet.members)!=null?_a:NONE;const iconMember=findFieldMember(members,"icon");const titleMember=findFieldMember(members,"title");const titlePlaceholder="Untitled";const moddedTitleMember=useMemo(()=>{if(!titleMember){return void 0;}if(titleMember.kind==="error"){return titleMember;}return{...titleMember,field:{...(titleMember==null?void 0:titleMember.field),schemaType:{...(titleMember==null?void 0:titleMember.field.schemaType),placeholder:titlePlaceholder}}};},[titleMember,titlePlaceholder]);return/* @__PURE__ */jsx(Stack,{space:5,children:/* @__PURE__ */jsxs(Stack,{space:2,children:[/* @__PURE__ */jsx(Flex,{gap:1,children:/* @__PURE__ */jsx(Text,{as:"label",weight:"semibold",size:1,htmlFor:titleId,children:"Name"})}),/* @__PURE__ */jsx(Text,{muted:true,size:1,children:"How this instruction appears in menus"}),/* @__PURE__ */jsxs(Flex,{align:"center",children:[iconMember&&/* @__PURE__ */jsx(Box,{flex:"none",children:/* @__PURE__ */jsx(ObjectInputMember,{...props,member:iconMember})}),moddedTitleMember&&/* @__PURE__ */jsx(Box,{flex:1,style:{marginLeft:-1},children:/* @__PURE__ */jsx(ObjectInputMember,{...props,member:moddedTitleMember})})]})]})});}function ShareField(props){var _a;const fieldsetMember=findFieldsetMember(props.members,"appearance");const members=(_a=fieldsetMember==null?void 0:fieldsetMember.fieldSet.members)!=null?_a:NONE;const visibilityMember=findFieldMember(members,"userId");return/* @__PURE__ */jsx(Fragment,{children:visibilityMember&&/* @__PURE__ */jsx(ObjectInputMember,{...props,member:visibilityMember})});}function HiddenFieldTitle(props){return props.renderDefault({...props,title:"",level:props.level-2,changed:false});}function InstructionVisibility(props){const{value,onChange}=props;const user=useCurrentUser();const handleChange=useCallback(()=>{var _a;const newValue=value?"":(_a=user==null?void 0:user.id)!=null?_a:"";onChange(newValue?set(newValue):unset());},[onChange,user,value]);const id=useId();return/* @__PURE__ */jsx(Card,{children:/* @__PURE__ */jsxs(Flex,{gap:2,align:"flex-start",children:[/* @__PURE__ */jsx("div",{style:{margin:"-3px 0"},children:/* @__PURE__ */jsx(Switch,{...props.elementProps,id,value:"".concat(!value),checked:!value,onChange:handleChange,disabled:props.elementProps.readOnly})}),/* @__PURE__ */jsx(Text,{muted:true,size:1,weight:"medium",children:/* @__PURE__ */jsx("label",{htmlFor:id,children:"Make visible to all Studio members"})})]})});}function IconInput(props){const{value,onChange}=props;const id=useId();const items=useMemo(()=>Object.entries(icons).map(_ref75=>{let[key,icon]=_ref75;return/* @__PURE__ */jsx(IconItem,{iconKey:key,icon,onChange},key);}),[onChange]);const selectedIcon=useMemo(()=>getIcon(value),[value]);return/* @__PURE__ */jsx(MenuButton,{button:/* @__PURE__ */jsx(Button,{icon:selectedIcon,title:"Select icon",padding:3,mode:"ghost",radius:1}),id,menu:/* @__PURE__ */jsx(Menu,{style:{maxHeight:300},children:items}),popover:{portal:true}});}function IconItem(_ref76){let{icon,iconKey:key,onChange}=_ref76;const onClick=useCallback(()=>onChange(set(key)),[onChange,key]);return/* @__PURE__ */jsx(MenuItem,{icon,title:key,text:key,onClick});}function getIcon(iconName){var _a,_b;return(_b=(_a=Object.entries(icons).find(_ref77=>{let[key]=_ref77;return key===iconName;}))==null?void 0:_a[1])!=null?_b:icons.sparkles;}function FieldAutocomplete(props){const{id,schemaType,fieldPath,onSelect,includeDocument}=props;const fieldNames=useMemo(()=>{if(includeDocument){return getFieldRefsWithDocument(schemaType);}return getFieldRefs(schemaType);},[schemaType,includeDocument]);const currentField=useMemo(()=>fieldNames.find(f=>f.key===fieldPath),[fieldPath,fieldNames]);const autocompleteOptions=useMemo(()=>fieldNames.map(field=>({value:field.key,field})),[fieldNames]);const renderOption=useCallback(option=>{const{value,field}=option;if(!value){return/* @__PURE__ */jsx(Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsx(Text,{accent:true,size:1,children:option.value})});}if(isType(field.schemaType,"document")){return/* @__PURE__ */jsx(Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsx(Text,{size:1,weight:"semibold",children:"The entire document"})});}const splitTitle=field.title.split("/");return/* @__PURE__ */jsx(Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsxs(Flex,{gap:3,children:[/* @__PURE__ */jsx(Text,{size:1,children:createElement(field.icon)}),/* @__PURE__ */jsx(Box,{flex:"none",children:/* @__PURE__ */jsxs(Breadcrumbs,{separator:/* @__PURE__ */jsx(Text,{muted:true,size:1,children:"/"}),space:1,children:[splitTitle.slice(0,splitTitle.length-1).map((pt,i)=>// eslint-disable-next-line react/no-array-index-key
|
|
2312
|
+
/* @__PURE__ */jsx(Text,{muted:true,size:1,children:pt.trim()},i)),/* @__PURE__ */jsx(Text,{size:1,weight:"medium",children:splitTitle[splitTitle.length-1]})]})})]})});},[]);const renderValue=useCallback((value,option)=>{var _a;return(_a=option==null?void 0:option.field.title)!=null?_a:value;},[]);const filterOption=useCallback((query,option)=>{var _a,_b,_c;const lQuery=query.toLowerCase();return((_a=option==null?void 0:option.value)==null?void 0:_a.toLowerCase().includes(lQuery))||((_c=(_b=option==null?void 0:option.field)==null?void 0:_b.title)==null?void 0:_c.toLowerCase().includes(lQuery));},[]);return/* @__PURE__ */jsx(Autocomplete,{fontSize:1,icon:currentField?currentField.icon:SearchIcon,onChange:onSelect,openButton:true,id,options:autocompleteOptions,placeholder:"Search for a field",radius:2,renderOption,renderValue,value:currentField==null?void 0:currentField.key,filterOption});}function FieldRefPathInput(props){var _a;const documentSchema=(_a=useContext(SelectedFieldContext))==null?void 0:_a.documentSchema;const ref=useRef(null);const id=useId();const{onChange}=props;useEffect(()=>{var _a2,_b;(_b=(_a2=ref.current)==null?void 0:_a2.querySelector("input"))==null?void 0:_b.focus();},[]);const onSelect=useCallback(path=>onChange(set(path)),[onChange]);if(!documentSchema){return props.renderDefault(props);}return/* @__PURE__ */jsx(Box,{flex:1,style:{minWidth:200},ref,children:/* @__PURE__ */jsx(FieldAutocomplete,{id,schemaType:documentSchema,onSelect,fieldPath:props.value})});}function InstructionsArrayInput(props){const user=useCurrentUser();const originalValue=props.value;const originalMembers=props.members;const value=useMemo(()=>(originalValue!=null?originalValue:[]).filter(v=>!v.userId||v.userId===(user==null?void 0:user.id)),[originalValue,user]);const members=useMemo(()=>(originalMembers!=null?originalMembers:[]).filter(v=>{var _a;if(v.kind==="error"){return true;}const value2=(_a=v==null?void 0:v.item)==null?void 0:_a.value;return!value2.userId||value2.userId===(user==null?void 0:user.id);}),[originalMembers,user]);return props.renderDefault({...props,value,members});}const InlineBlockValueContext=createContext(void 0);function AssistInlineFormBlock(props){return/* @__PURE__ */jsx(InlineBlockValueContext.Provider,{value:props.value,children:/* @__PURE__ */jsx(Box,{flex:1,children:props.renderDefault(props)})});}function FieldRefPreview(props){var _a,_b,_c,_d;const documentSchema=(_a=useContext(SelectedFieldContext))==null?void 0:_a.documentSchema;const path=(_c=(_b=useContext(InlineBlockValueContext))==null?void 0:_b.path)!=null?_c:props.path;const selectedField=useSelectedField(documentSchema,path);return/* @__PURE__ */jsxs(Flex,{gap:2,align:"center",style:{width:"100%"},children:[/* @__PURE__ */jsx(Flex,{flex:1,gap:2,align:"center",paddingY:3,paddingX:1,children:/* @__PURE__ */jsx(Box,{children:/* @__PURE__ */jsx(Text,{size:1,textOverflow:"ellipsis",children:(_d=selectedField==null?void 0:selectedField.title)!=null?_d:"Select field"})})}),/* @__PURE__ */jsx(Fragment,{children:props.actions})]});}function HideReferenceChangedBannerInput(props){const ref=useRef(null);useEffect(()=>{var _a;const parent=(_a=ref.current)==null?void 0:_a.closest('[data-testid="pane-content"]');if(!parent){return;}const style=document.createElement("style");const parentId="id-".concat(Math.random()).replace(".","-");parent.id=parentId;style.innerText="\n #".concat(parentId," [data-testid=\"reference-changed-banner\"] { display: none; }\n ");parent.prepend(style);},[ref]);return/* @__PURE__ */jsx(Box,{ref,children:props.renderDefault(props)});}const contextDocumentSchema=defineType({type:"document",name:contextDocumentTypeName,title:"AI context",liveEdit:true,icon:TokenIcon,components:{input:HideReferenceChangedBannerInput},fields:[defineField({type:"string",name:"title",title:"Title"}),defineField({name:"context",type:"array",title:"Context",of:[defineArrayMember({type:"block",styles:[{title:"Normal",value:"normal"}],lists:[],marks:{decorators:[],annotations:[]}})]})],preview:{select:{title:"title",context:"context"},prepare(_ref78){let{title,context}=_ref78;var _a;const text=context==null?void 0:context.flatMap(block=>block==null?void 0:block.children).flatMap(child=>{var _a2;return(_a2=child==null?void 0:child.text)==null?void 0:_a2.split(" ");}).filter(Boolean);const words=(_a=text==null?void 0:text.length)!=null?_a:0;return{title,subtitle:"Words: ".concat(words),media:DocumentTextIcon};}}});// Strict ESM env, designed to run outside Node.js in envs that provide WebCrypto (deno, browsers, etc)
|
|
2313
|
+
function getRandomValues(typedArray){return window.crypto.getRandomValues(typedArray);}function whatwgRNG(){let length=arguments.length>0&&arguments[0]!==undefined?arguments[0]:16;const rnds8=new Uint8Array(length);getRandomValues(rnds8);return rnds8;}const getByteHexTable=(()=>{let table;return()=>{if(table){return table;}table=[];for(let i=0;i<256;++i){table[i]=(i+256).toString(16).substring(1);}return table;};})();function randomKey(length){const table=getByteHexTable();return whatwgRNG(length).reduce((str,n)=>str+table[n],"").slice(0,length);}const PteMods=styled(Box)(_templateObject10||(_templateObject10=_taggedTemplateLiteral(["\n & [data-testid='pt-editor__toolbar-card'] > div > div:last-child {\n display: none;\n }\n & [data-testid='pt-editor'] {\n min-height: 300px;\n }\n & [data-testid='pt-editor'] .pt-inline-object * {\n max-width: 400px;\n }\n"])));function PromptInput(props){useOnlyInlineBlocks(props);return/* @__PURE__ */jsx(PteMods,{children:props.renderDefault(props)});}function useOnlyInlineBlocks(props){useEffect(()=>{var _a;let needsFix=false;const val=((_a=props.value)!=null?_a:[]).map(block=>{if(block._type==="block"){return block;}needsFix=true;return typed({_key:randomKey(12),_type:"block",level:0,markDefs:[],style:"normal",children:[block]});});if(needsFix){props.onChange(set(val));}},[]);}function InstructionsArrayField(props){return props.renderDefault({...props,title:void 0});}const fieldReference=defineType({type:"object",name:fieldReferenceTypeName,title:"Document field",icon:ThListIcon,fields:[defineField({type:"string",name:"path",title:"Field",components:{input:FieldRefPathInput},validation:rule=>rule.custom((value,context)=>{var _a;if(!value){return"Please select a field";}try{const docId=(_a=context.document)==null?void 0:_a._id;if(!docId){return"Field reference cannot be used outside document inspector context. Could not resolve document id.";}const targetDocType=docId.replace(new RegExp("^".concat(assistDocumentIdPrefix)),"");const schema=context.schema.get(targetDocType);if(!schema){return"Field reference cannot be used outside document inspector context. Could not resolve schema: ".concat(targetDocType);}const refs=getFieldRefsWithDocument(schema);const fieldRef=refs.find(r=>r.key===value);if(!fieldRef){return"Field with path \"".concat(value,"\" does not exist in the schema.");}return true;}catch(e){console.error("Failed to resolve field reference",e);return"Invalid field reference.";}})})],preview:{select:{path:"path"},prepare(_ref79){let{path}=_ref79;return{title:path,path,icon:CodeIcon};}},components:{preview:FieldRefPreview},options:{modal:{type:"popover"}}});const userInput=defineType({type:"object",name:userInputTypeName,title:"User input",icon:ComposeIcon,fields:[defineField({type:"string",name:"message",title:"User input title",placeholder:"Provide instruction text",description:"The header above the user input text field",validation:rule=>rule.required()}),defineField({type:"text",rows:3,name:"description",title:"User input description",description:"The description above the user input text field"})],preview:{select:{title:"message"}},options:{modal:{type:"popover",width:1}}});const promptContext=defineType({type:"object",name:instructionContextTypeName,title:contextDocumentSchema.title,icon:contextDocumentSchema.icon,fields:[defineField({type:"reference",name:"reference",to:[{type:contextDocumentSchema.name}],title:"Context",description:"The referenced context will be inserted into the instruction",validation:rule=>rule.required(),components:{input:function Fix(props){return/* @__PURE__ */jsx(Box,{style:{maxWidth:300},children:props.renderDefault(props)});}}})],preview:{select:{ref:"reference._ref",title:"reference.title",context:"reference.context"},prepare(select){var _a,_b,_c,_d;return select.ref?(_d=(_c=(_b=(_a=contextDocumentSchema)==null?void 0:_a.preview)==null?void 0:_b.prepare)==null?void 0:_c.call(_b,select))!=null?_d:select:{title:"No reference selected",media:contextDocumentSchema.icon};}},options:{modal:{type:"popover",width:"auto"}}});const prompt=defineType({type:"array",name:promptTypeName,title:"Prompt",of:[defineArrayMember({type:"block",styles:[{title:"Normal",value:"normal"}],lists:[],marks:{decorators:[],annotations:[]},of:[defineArrayMember({type:fieldReference.name}),defineArrayMember({type:promptContext.name}),defineArrayMember({type:userInput.name})]})/* defineArrayMember({
|
|
2314
2314
|
type: fieldReference.name,
|
|
2315
2315
|
}),
|
|
2316
2316
|
defineArrayMember({
|
|
@@ -2318,7 +2318,7 @@ function getRandomValues(typedArray){return window.crypto.getRandomValues(typedA
|
|
|
2318
2318
|
}),
|
|
2319
2319
|
defineArrayMember({
|
|
2320
2320
|
type: userInput.name,
|
|
2321
|
-
}),*/]});const instruction=defineType({type:"object",name:instructionTypeName,title:"Instruction",fieldsets:[{name:"appearance",title:"Appearance",options:{collapsible:true,collapsed:true}}],preview:{select:{icon:"icon",title:"title",userId:"userId"},prepare:
|
|
2321
|
+
}),*/]});const instruction=defineType({type:"object",name:instructionTypeName,title:"Instruction",fieldsets:[{name:"appearance",title:"Appearance",options:{collapsible:true,collapsed:true}}],preview:{select:{icon:"icon",title:"title",userId:"userId"},prepare:_ref80=>{let{icon,title,userId}=_ref80;return{title,icon:icon?icons[icon]:SparklesIcon,userId};}},components:{input:InstructionInput,preview:props=>{return/* @__PURE__ */jsxs(Flex,{gap:3,align:"center",padding:2,children:[props.icon&&/* @__PURE__ */jsx(Box,{flex:"none",children:/* @__PURE__ */jsx(Text,{size:1,children:createElement(props.icon)})}),/* @__PURE__ */jsx(Stack,{flex:1,space:2,children:/* @__PURE__ */jsx(Text,{size:1,textOverflow:"ellipsis",weight:"medium",children:getInstructionTitle(props)})}),props.userId&&/* @__PURE__ */jsx(Text,{size:1,children:/* @__PURE__ */jsx(Tooltip,{content:/* @__PURE__ */jsx(Text,{size:1,children:"Only visible to you"}),padding:2,placement:"top",portal:true,children:/* @__PURE__ */jsx(LockIcon,{})})})]});}},fields:[defineField({type:prompt.name,name:"prompt",title:"Instruction",description:/* @__PURE__ */jsxs(Fragment,{children:["Learn from"," ",/* @__PURE__ */jsxs("a",{href:instructionGuideUrl,target:"_blank",rel:"noreferrer",children:["our instruction guide ",/* @__PURE__ */jsx(ArrowRightIcon,{})]})]}),components:{input:PromptInput}}),defineField({type:"string",name:"icon",title:"Icon",fieldset:"appearance",components:{field:HiddenFieldTitle,input:IconInput}}),defineField({type:"string",name:"title",title:"Title",fieldset:"appearance",components:{field:HiddenFieldTitle}}),defineField({type:"string",name:"userId",title:"Visibility",fieldset:"appearance",components:{field:HiddenFieldTitle,input:InstructionVisibility},initialValue:(params,context)=>{var _a,_b;return(_b=(_a=context.currentUser)==null?void 0:_a.id)!=null?_b:"";},readOnly:context=>{var _a,_b,_c;return Boolean(((_a=context.parent)==null?void 0:_a.createdById)&&((_b=context.parent)==null?void 0:_b.createdById)!==((_c=context.currentUser)==null?void 0:_c.id));}}),defineField({type:"string",name:"createdById",title:"Created by",hidden:true,fieldset:"appearance",initialValue:(params,context)=>{var _a,_b;return(_b=(_a=context.currentUser)==null?void 0:_a.id)!=null?_b:"";}})]});const fieldInstructions=defineType({type:"object",name:assistFieldTypeName,title:"Field prompt",/* components: {
|
|
2322
2322
|
input: FieldPromptInput,
|
|
2323
2323
|
},*/fields:[defineField({type:"string",name:"path",title:"Path",readOnly:true,hidden:true}),defineField({type:"array",name:"instructions",title:"Instructions",of:[{type:instruction.name}],components:{field:InstructionsArrayField,input:InstructionsArrayInput}})],preview:{select:{title:"path"}}});const assistDocumentSchema=defineType({//NOTE: this is a document type. Using object here ensures it does not appear in structure menus
|
|
2324
2324
|
type:"object",//workaround for using object and not document
|
|
@@ -2337,5 +2337,5 @@ useAssistDocumentContext();const currentUser=useCurrentUser();const isHidden=!as
|
|
|
2337
2337
|
status: 'warning',
|
|
2338
2338
|
onAction: () => {},
|
|
2339
2339
|
},*/manageInstructionsItem].filter(c=>!!c),expanded:false,renderAsButton:true,hidden:!assistSupported}),[//documentIsNew,
|
|
2340
|
-
runInstructionsGroup,manageInstructionsItem,assistSupported]);const emptyAction=useMemo(()=>node({type:"action",hidden:!assistSupported,icon:SparklesIcon,onAction:manageInstructions,renderAsButton:true,title:pluginTitleShort,selected:isSelected}),[assistSupported,manageInstructions,isSelected]);if(instructionsLength===0){return emptyAction;}return group;}};function instructionItem(props){const{hidden,isPrivate,onInstructionAction,assistSupported,instruction}=props;return node({type:"action",icon:getIcon(instruction.icon),iconRight:isPrivate?PrivateIcon:void 0,title:getInstructionTitle(instruction),onAction:()=>onInstructionAction(instruction),disabled:assistSupported?false:{reason:"".concat(pluginTitle," is not supported for this field")},hidden});}function AssistDocumentContextProvider(props){const{documentId,schemaType}=props;const value=useAssistDocumentContextValue(documentId,schemaType);return/* @__PURE__ */jsx(AssistDocumentContext.Provider,{value,children:props.children});}const NO_TASKS=[];function useInstructionToaster(documentId,documentSchemaType){const assistDocument=useStudioAssistDocument({documentId,schemaType:documentSchemaType});const assistDocLoaded=!!assistDocument;const currentUser=useCurrentUser();const toast=useToast();const tasks=assistDocument==null?void 0:assistDocument.tasks;const previousTasks=useRef("initial");useEffect(()=>{var _a;if(!assistDocLoaded){return;}if(previousTasks.current!=="initial"){const prevTaskByKey=Object.fromEntries(((_a=previousTasks.current)!=null?_a:NO_TASKS).map(run=>[run._key,run]));const endedTasks=tasks==null?void 0:tasks.filter(task=>task.startedByUserId===(currentUser==null?void 0:currentUser.id)).filter(task=>{const prevTask=prevTaskByKey[task._key];return!prevTask&&task.ended||!(prevTask==null?void 0:prevTask.ended)&&task.ended;}).filter(task=>task.ended&&isAfter(addSeconds(new Date(task.ended),30),/* @__PURE__ */new Date()));endedTasks==null?void 0:endedTasks.forEach(task=>{var _a2;const title=getInstructionTitle(task.instruction);if(task.reason==="error"){toast.push({title:"Failed: ".concat(title),status:"error",description:"Instruction failed. ".concat((_a2=task.message)!=null?_a2:""),closable:true,duration:1e4});}else if(task.reason==="timeout"){toast.push({title:"Timeout: ".concat(title),status:"error",description:"Instruction timed out.",closable:true});}else if(task.reason==="success"){toast.push({title:"Success: ".concat(title),status:"success",description:"Instruction completed.",closable:true});}else if(task.reason==="aborted"){toast.push({title:"Canceled: ".concat(title),status:"warning",description:"Instruction canceled.",closable:true});}});}previousTasks.current=tasks;},[tasks,previousTasks,toast,currentUser,assistDocLoaded]);}function AssistDocumentInputWrapper(props){var _a;if(!isType(props.schemaType,"document")&&props.id!=="root"){return/* @__PURE__ */jsx(AssistInput,{...props});}const documentId=(_a=props.value)==null?void 0:_a._id;if(!documentId){return props.renderDefault(props);}return/* @__PURE__ */jsx(AssistDocumentInput,{...props,documentId});}function AssistDocumentInput(
|
|
2340
|
+
runInstructionsGroup,manageInstructionsItem,assistSupported]);const emptyAction=useMemo(()=>node({type:"action",hidden:!assistSupported,icon:SparklesIcon,onAction:manageInstructions,renderAsButton:true,title:pluginTitleShort,selected:isSelected}),[assistSupported,manageInstructions,isSelected]);if(instructionsLength===0){return emptyAction;}return group;}};function instructionItem(props){const{hidden,isPrivate,onInstructionAction,assistSupported,instruction}=props;return node({type:"action",icon:getIcon(instruction.icon),iconRight:isPrivate?PrivateIcon:void 0,title:getInstructionTitle(instruction),onAction:()=>onInstructionAction(instruction),disabled:assistSupported?false:{reason:"".concat(pluginTitle," is not supported for this field")},hidden});}function AssistDocumentContextProvider(props){const{documentId,schemaType}=props;const value=useAssistDocumentContextValue(documentId,schemaType);return/* @__PURE__ */jsx(AssistDocumentContext.Provider,{value,children:props.children});}const NO_TASKS=[];function useInstructionToaster(documentId,documentSchemaType){const assistDocument=useStudioAssistDocument({documentId,schemaType:documentSchemaType});const assistDocLoaded=!!assistDocument;const currentUser=useCurrentUser();const toast=useToast();const tasks=assistDocument==null?void 0:assistDocument.tasks;const previousTasks=useRef("initial");useEffect(()=>{var _a;if(!assistDocLoaded){return;}if(previousTasks.current!=="initial"){const prevTaskByKey=Object.fromEntries(((_a=previousTasks.current)!=null?_a:NO_TASKS).map(run=>[run._key,run]));const endedTasks=tasks==null?void 0:tasks.filter(task=>task.startedByUserId===(currentUser==null?void 0:currentUser.id)).filter(task=>{const prevTask=prevTaskByKey[task._key];return!prevTask&&task.ended||!(prevTask==null?void 0:prevTask.ended)&&task.ended;}).filter(task=>task.ended&&isAfter(addSeconds(new Date(task.ended),30),/* @__PURE__ */new Date()));endedTasks==null?void 0:endedTasks.forEach(task=>{var _a2;const title=getInstructionTitle(task.instruction);if(task.reason==="error"){toast.push({title:"Failed: ".concat(title),status:"error",description:"Instruction failed. ".concat((_a2=task.message)!=null?_a2:""),closable:true,duration:1e4});}else if(task.reason==="timeout"){toast.push({title:"Timeout: ".concat(title),status:"error",description:"Instruction timed out.",closable:true});}else if(task.reason==="success"){toast.push({title:"Success: ".concat(title),status:"success",description:"Instruction completed.",closable:true});}else if(task.reason==="aborted"){toast.push({title:"Canceled: ".concat(title),status:"warning",description:"Instruction canceled.",closable:true});}});}previousTasks.current=tasks;},[tasks,previousTasks,toast,currentUser,assistDocLoaded]);}function AssistDocumentInputWrapper(props){var _a;if(!isType(props.schemaType,"document")&&props.id!=="root"){return/* @__PURE__ */jsx(AssistInput,{...props});}const documentId=(_a=props.value)==null?void 0:_a._id;if(!documentId){return props.renderDefault(props);}return/* @__PURE__ */jsx(AssistDocumentInput,{...props,documentId});}function AssistDocumentInput(_ref81){let{documentId,...props}=_ref81;useInstructionToaster(documentId,props.schemaType);return/* @__PURE__ */jsx(FirstAssistedPathProvider,{members:props.members,children:/* @__PURE__ */jsx(AssistDocumentContextProvider,{schemaType:props.schemaType,documentId,children:props.renderDefault(props)})});}function AssistInput(props){const{zIndex}=useLayer();const{paneKey}=useDocumentPane();const pathKey=usePathKey(props.path);return/* @__PURE__ */jsx(ConnectFromRegion,{_key:"".concat(paneKey,"_").concat(pathKey),zIndex,style:{minWidth:0},children:props.renderDefault(props)});}function createAssistDocumentPresence(documentId,schemaType){return function AssistDocumentPresenceWrapper(){return documentId?/* @__PURE__ */jsx(AssistDocumentPresence,{documentId,schemaType}):null;};}function AssistDocumentPresence(props){const{assistDocument}=useAssistDocumentContextValue(props.documentId,props.schemaType);const anyPresence=useMemo(()=>{var _a,_b,_c,_d;const anyPresence2=(_b=(_a=assistDocument==null?void 0:assistDocument.tasks)==null?void 0:_a.filter(run=>!run.ended&&!run.reason))==null?void 0:_b.flatMap(run=>{var _a2;return(_a2=run.presence)!=null?_a2:[];}).find(f=>f.started&&/* @__PURE__ */new Date().getTime()-new Date(f.started).getTime()<3e4);if(anyPresence2){return aiPresence(anyPresence2,[]);}const anyRun=(_d=(_c=assistDocument==null?void 0:assistDocument.tasks)==null?void 0:_c.filter(run=>!run.ended&&!run.reason))==null?void 0:_d.find(f=>f.started&&/* @__PURE__ */new Date().getTime()-new Date(f.started).getTime()<3e4);return anyRun?aiPresence({started:anyRun.started,path:documentRootKey,_key:anyRun._key,_type:fieldPresenceTypeName},[]):void 0;},[assistDocument==null?void 0:assistDocument.tasks]);return/* @__PURE__ */jsx(Card,{children:/* @__PURE__ */jsx(Flex,{flex:1,justify:"flex-end",children:/* @__PURE__ */jsx(Flex,{gap:2,align:"center",children:anyPresence&&/* @__PURE__ */jsx(AiFieldPresence,{presence:anyPresence})})})});}const assist=definePlugin(config=>{const configWithDefaults=config!=null?config:{};return{name:packageName,schema:{types:schemaTypes},document:{inspectors:(prev,context)=>{const docSchema=context.schema.get(context.documentType);if(docSchema&&isSchemaAssistEnabled(docSchema)){return[...prev,assistInspector];}return prev;},unstable_fieldActions:prev=>{return[...prev,assistFieldActions];},unstable_languageFilter:(prev,_ref82)=>{let{documentId,schema,schemaType}=_ref82;const docSchema=schema.get(schemaType);return[...prev,createAssistDocumentPresence(documentId,docSchema)];}},studio:{components:{layout:function Layout(props){return/* @__PURE__ */jsx(AssistLayout,{...props,config:configWithDefaults});}}},form:{components:{input:AssistDocumentInputWrapper,field:AssistFieldWrapper,item:AssistItem,block:AssistFormBlock,inlineBlock:AssistInlineFormBlock}},plugins:[definePlugin({name:"".concat(packageName,"/safe-value-input"),form:{components:{input:SafeValueInput}}})()]};});export{SchemaTypeTool,assist,contextDocumentTypeName};
|
|
2341
2341
|
//# sourceMappingURL=index.esm.js.map
|