@sanity/assist 1.0.3 → 1.0.4

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,7 +1,7 @@
1
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,FormCallbacksProvider,FormInput,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
- ...((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,_c,_d;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,values:type.jsonType==="string"&&((_c=type==null?void 0:type.options)==null?void 0:_c.list)?(_d=type==null?void 0:type.options)==null?void 0:_d.list.map(v=>{var _a2;return typeof v==="string"?v:(_a2=v.value)!=null?_a2:"".concat(v.title);}):void 0,of:"of"in type&&type.name==="array"?arrayOf(type,schema,options):void 0,to:"to"in type&&type.name==="reference"?refToTypeNames(type):void 0,fields:"fields"in type&&inlineTypes.includes(typeName)?serializeFields(schema,type,options):void 0});}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={};/**
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={};/**
5
5
  * @license React
6
6
  * react-is.production.min.js
7
7
  *