@sanity/assist 1.0.1 → 1.0.3
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.js
CHANGED
|
@@ -2308,7 +2308,7 @@ 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=ui.useTheme();const line=React.useMemo(()=>mapConnectorToLine(options,{from,to}),[from,options,to]);return/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[/* @__PURE__ */jsxRuntime.jsx("path",{d:drawConnectorPath(options,line),stroke:theme.sanity.color.base.bg,strokeWidth:strokeWidth+4}),/* @__PURE__ */jsxRuntime.jsx("path",{d:drawConnectorPath(options,line),stroke:ui.rgba(theme.sanity.color.base.border,0.5),strokeWidth}),line.from.isAbove&&/* @__PURE__ */jsxRuntime.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__ */jsxRuntime.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]=React.useState(false);React.useEffect(()=>{setRedraw(true);},[]);return/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[/* @__PURE__ */jsxRuntime.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__ */jsxRuntime.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]=React.useState(NO_ASSIST_DOCS);const[contextDocs,setContextDocs]=React.useState(NO_CONTEXT_DOCS);const[staleStatusDocIds,setStaleStatusDocs]=React.useState(NO_IDS);const[error,setError]=React.useState(void 0);const[progress,setProgress]=React.useState(void 0);const toast=ui.useToast();const client=sanity.useClient({apiVersion:"2023-06-01"});React.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=React.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__ */jsxRuntime.jsx(ui.Dialog,{id:"outdated-assist-docs",header:pluginTitle,children:/* @__PURE__ */jsxRuntime.jsx(ui.Card,{padding:3,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:4,style:{maxWidth:500},children:[/* @__PURE__ */jsxRuntime.jsxs(ui.Text,{size:1,children:["It seems like this workspace contains documents from an"," ",/* @__PURE__ */jsxRuntime.jsxs("strong",{children:["older version of ",pluginTitle]}),"."]}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:"Cleanup is required."}),error?/* @__PURE__ */jsxRuntime.jsxs(ui.Card,{padding:2,tone:"critical",border:true,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:"An error occurred. See console for details."})," "]}):null,/* @__PURE__ */jsxRuntime.jsx(ui.Button,{icon:progress?/* @__PURE__ */jsxRuntime.jsx(ui.Box,{style:{marginTop:5},children:/* @__PURE__ */jsxRuntime.jsx(ui.Spinner,{})}):icons.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]=React.useState([]);const migrate=(_a=props.config.alphaMigration)!=null?_a:true;return/* @__PURE__ */jsxRuntime.jsxs(AiAssistanceConfigProvider,{config:props.config,children:[migrate?/* @__PURE__ */jsxRuntime.jsx(AlphaMigration,{}):null,/* @__PURE__ */jsxRuntime.jsx(RunInstructionProvider,{children:/* @__PURE__ */jsxRuntime.jsxs(ConnectorsProvider,{onConnectorsChange:setConnectors,children:[props.renderDefault(props),/* @__PURE__ */jsxRuntime.jsx(ui.ThemeProvider,{tone:"default",children:/* @__PURE__ */jsxRuntime.jsx(AssistConnectorsOverlay,{connectors})})]})})]});}const WrapPreCard=styled(ui.Card)(_templateObject9||(_templateObject9=_taggedTemplateLiteral(["\n & pre {\n white-space: pre-wrap !important;\n }\n"])));function SafeValueInput(props){return/* @__PURE__ */jsxRuntime.jsx(ErrorWrapper,{onChange:props.onChange,children:/* @__PURE__ */jsxRuntime.jsx(PteValueFixer,{...props})});}function ErrorWrapper(props){const{onChange}=props;const[error,setError]=React.useState();const catchError=React.useCallback(params=>{setError(params.error);},[setError]);const unsetValue=React.useCallback(()=>onChange(sanity.PatchEvent.from(sanity.unset())),[onChange]);const dismiss=React.useCallback(()=>setError(void 0),[]);const catcher=/* @__PURE__ */jsxRuntime.jsx(ui.ErrorBoundary,{onCatch:catchError,children:props.children});return error?/* @__PURE__ */jsxRuntime.jsx(ui.Card,{border:true,tone:"critical",padding:2,contentEditable:false,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,weight:"semibold",children:"An error occurred."}),/* @__PURE__ */jsxRuntime.jsx(WrapPreCard,{flex:1,padding:2,tone:"critical",border:true,children:catcher}),/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{width:"fill",flex:1,gap:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Button,{text:"Dismiss",onClick:dismiss,tone:"primary"})}),/* @__PURE__ */jsxRuntime.jsx(ui.Button,{text:"Unset value",onClick:unsetValue,tone:"critical"})]})]})}):catcher;}function PteValueFixer(props){const isPortableText=React.useMemo(()=>sanity.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}=sanity.useFormCallbacks();const key=props.value._key;const localOnChange=React.useCallback(patchEvent=>{if(!key){return;}onChange(sanity.PatchEvent.from(patchEvent).prefixAll({_key:key}));},[onChange,key]);return/* @__PURE__ */jsxRuntime.jsx(ErrorWrapper,{onChange:localOnChange,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",justify:"space-between",children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,children:props.renderDefault(props)}),presence.map(pre=>/* @__PURE__ */jsxRuntime.jsx(AiFieldPresence,{presence:pre},pre.lastActiveAt))]})});}function AssistItem(props){const{path}=props;const presence=useAssistPresence(path,true);return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",width:"fill",style:{position:"relative"},children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,children:props.renderDefault({...props})}),presence.map(pre=>/* @__PURE__ */jsxRuntime.jsx(ui.Box,{style:{position:"absolute",right:35},children:/* @__PURE__ */jsxRuntime.jsx(AiFieldPresence,{presence:pre})},pre.user.id))]});}function BackToInstructionListLink(){const{openInspector}=desk.useDocumentPane();const goBack=React.useCallback(()=>openInspector(aiInspectorId,{[instructionParam]:void 0}),[openInspector]);return/* @__PURE__ */jsxRuntime.jsx("div",{children:/* @__PURE__ */jsxRuntime.jsx(ui.Button,{as:"a",fontSize:1,icon:icons.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=React.useMemo(()=>{if(!id){return void 0;}return documentTypeFromAiDocumentId(id);},[id]);const{params,setParams}=useAiPaneRouter();const pathKey=params[fieldPathParam];const instruction=params[instructionParam];const activeKey=React.useMemo(()=>{var _a;return(_a=(fields!=null?fields:EMPTY_FIELDS).find(f=>f.path===pathKey))==null?void 0:_a._key;},[fields,pathKey]);const activePath=React.useMemo(()=>{if(!activeKey){return void 0;}const base=["fields",{_key:activeKey}];return instruction?[...base,"instructions",{_key:instruction}]:base;},[activeKey,instruction]);const schema=sanity.useSchema();const documentSchema=React.useMemo(()=>{if(!targetDocumentType){return void 0;}return schema.get(targetDocumentType);},[schema,targetDocumentType]);const fieldSchema=useSelectedSchema(pathKey,documentSchema);const context=React.useMemo(()=>({documentSchema,fieldSchema:fieldSchema!=null?fieldSchema:documentSchema}),[fieldSchema,documentSchema]);const title=value==null?void 0:value.title;React.useEffect(()=>{var _a;if(!title&&documentSchema&&!(id==null?void 0:id.startsWith("drafts."))){onChange(sanity.set((_a=documentSchema.title)!=null?_a:documentSchema.name,["title"]));}},[title,documentSchema,onChange,id]);React.useEffect(()=>{if(activePath||!pathKey){return;}onChange([sanity.setIfMissing([],["fields"]),sanity.insert([sanity.typed({_key:pathKey,_type:assistFieldTypeName,path:pathKey})],"after",["fields",-1])]);},[activePath,onChange,pathKey]);const{onPathOpen,...formCallbacks}=sanity.useFormCallbacks();const newCallbacks=React.useMemo(()=>({...formCallbacks,onPathOpen:path=>{var _a;if(!instruction&&path.length===4&&path[2]==="instructions"){setParams(sanity.typed({...params,[instructionParam]:(_a=path[3])==null?void 0:_a._key}));onPathOpen([]);}else{setTimeout(()=>onPathOpen(path),0);}}}),[formCallbacks,onPathOpen,params,setParams,instruction]);React.useEffect(()=>{if(activePath&&!instruction){onPathOpen([]);}},[activePath,instruction,onPathOpen]);return/* @__PURE__ */jsxRuntime.jsx(SelectedFieldContextProvider,{value:context,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:5,children:[instruction&&/* @__PURE__ */jsxRuntime.jsx(BackToInstructionListLink,{}),activePath&&/* @__PURE__ */jsxRuntime.jsx(sanity.FormCallbacksProvider,{...newCallbacks,children:/* @__PURE__ */jsxRuntime.jsx("div",{style:{lineHeight:"1.25em"},children:/* @__PURE__ */jsxRuntime.jsx(sanity.FormInput,{...props,absolutePath:activePath})})}),!activePath&&props.renderDefault(props)]})});}function useSelectedSchema(fieldPath,documentSchema){return React.useMemo(()=>{if(!fieldPath){return void 0;}if(fieldPath===documentRootKey){return documentSchema;}const path=sanity.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__ */jsxRuntime.jsxs(ui.Stack,{space:[4,4,4,5],children:[/* @__PURE__ */jsxRuntime.jsx(NameField,{...props}),/* @__PURE__ */jsxRuntime.jsx(ShareField,{...props}),/* @__PURE__ */jsxRuntime.jsx(PromptField,{...props})]});}function PromptField(props){const promptMember=findFieldMember(props.members,"prompt");return promptMember?/* @__PURE__ */jsxRuntime.jsx(sanity.ObjectInputMember,{...props,member:promptMember}):null;}const NONE=[];function NameField(props){var _a;const fieldsetMember=findFieldsetMember(props.members,"appearance");const titleId=React.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=React.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__ */jsxRuntime.jsx(ui.Stack,{space:5,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{gap:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{as:"label",weight:"semibold",size:1,htmlFor:titleId,children:"Name"})}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,children:"How this instruction appears in menus"}),/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",children:[iconMember&&/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:"none",children:/* @__PURE__ */jsxRuntime.jsx(sanity.ObjectInputMember,{...props,member:iconMember})}),moddedTitleMember&&/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,style:{marginLeft:-1},children:/* @__PURE__ */jsxRuntime.jsx(sanity.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__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children:visibilityMember&&/* @__PURE__ */jsxRuntime.jsx(sanity.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=sanity.useCurrentUser();const handleChange=React.useCallback(()=>{var _a;const newValue=value?"":(_a=user==null?void 0:user.id)!=null?_a:"";onChange(newValue?sanity.set(newValue):sanity.unset());},[onChange,user,value]);const id=React.useId();return/* @__PURE__ */jsxRuntime.jsx(ui.Card,{children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:2,align:"flex-start",children:[/* @__PURE__ */jsxRuntime.jsx("div",{style:{margin:"-3px 0"},children:/* @__PURE__ */jsxRuntime.jsx(ui.Switch,{...props.elementProps,id,value:"".concat(!value),checked:!value,onChange:handleChange,disabled:props.elementProps.readOnly})}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,weight:"medium",children:/* @__PURE__ */jsxRuntime.jsx("label",{htmlFor:id,children:"Make visible to all Studio members"})})]})});}function IconInput(props){const{value,onChange}=props;const id=React.useId();const items=React.useMemo(()=>Object.entries(icons.icons).map(_ref74=>{let[key,icon]=_ref74;return/* @__PURE__ */jsxRuntime.jsx(IconItem,{iconKey:key,icon,onChange},key);}),[onChange]);const selectedIcon=React.useMemo(()=>getIcon(value),[value]);return/* @__PURE__ */jsxRuntime.jsx(ui.MenuButton,{button:/* @__PURE__ */jsxRuntime.jsx(ui.Button,{icon:selectedIcon,title:"Select icon",padding:3,mode:"ghost",radius:1}),id,menu:/* @__PURE__ */jsxRuntime.jsx(ui.Menu,{style:{maxHeight:300},children:items}),popover:{portal:true}});}function IconItem(_ref75){let{icon,iconKey:key,onChange}=_ref75;const onClick=React.useCallback(()=>onChange(sanity.set(key)),[onChange,key]);return/* @__PURE__ */jsxRuntime.jsx(ui.MenuItem,{icon,title:key,text:key,onClick});}function getIcon(iconName){var _a,_b;return(_b=(_a=Object.entries(icons.icons).find(_ref76=>{let[key]=_ref76;return key===iconName;}))==null?void 0:_a[1])!=null?_b:icons.icons.sparkles;}function FieldAutocomplete(props){const{id,schemaType,fieldPath,onSelect,includeDocument}=props;const fieldNames=React.useMemo(()=>{if(includeDocument){return getFieldRefsWithDocument(schemaType);}return getFieldRefs(schemaType);},[schemaType,includeDocument]);const currentField=React.useMemo(()=>fieldNames.find(f=>f.key===fieldPath),[fieldPath,fieldNames]);const autocompleteOptions=React.useMemo(()=>fieldNames.map(field=>({value:field.key,field})),[fieldNames]);const renderOption=React.useCallback(option=>{const{value,field}=option;if(!value){return/* @__PURE__ */jsxRuntime.jsx(ui.Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{accent:true,size:1,children:option.value})});}if(isType(field.schemaType,"document")){return/* @__PURE__ */jsxRuntime.jsx(ui.Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,weight:"semibold",children:"The entire document"})});}const splitTitle=field.title.split("/");return/* @__PURE__ */jsxRuntime.jsx(ui.Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:React.createElement(field.icon)}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:"none",children:/* @__PURE__ */jsxRuntime.jsxs(ui.Breadcrumbs,{separator:/* @__PURE__ */jsxRuntime.jsx(ui.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
|
|
2311
|
+
},children:connectors.map(connector=>/* @__PURE__ */jsxRuntime.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]=React.useState(NO_ASSIST_DOCS);const[contextDocs,setContextDocs]=React.useState(NO_CONTEXT_DOCS);const[staleStatusDocIds,setStaleStatusDocs]=React.useState(NO_IDS);const[error,setError]=React.useState(void 0);const[progress,setProgress]=React.useState(void 0);const toast=ui.useToast();const client=sanity.useClient({apiVersion:"2023-06-01"});React.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=React.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__ */jsxRuntime.jsx(ui.Dialog,{id:"outdated-assist-docs",header:pluginTitle,children:/* @__PURE__ */jsxRuntime.jsx(ui.Card,{padding:3,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:4,style:{maxWidth:500},children:[/* @__PURE__ */jsxRuntime.jsxs(ui.Text,{size:1,children:["It seems like this workspace contains documents from an"," ",/* @__PURE__ */jsxRuntime.jsxs("strong",{children:["older version of ",pluginTitle]}),"."]}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:"Cleanup is required."}),error?/* @__PURE__ */jsxRuntime.jsxs(ui.Card,{padding:2,tone:"critical",border:true,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:"An error occurred. See console for details."})," "]}):null,/* @__PURE__ */jsxRuntime.jsx(ui.Button,{icon:progress?/* @__PURE__ */jsxRuntime.jsx(ui.Box,{style:{marginTop:5},children:/* @__PURE__ */jsxRuntime.jsx(ui.Spinner,{})}):icons.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]=React.useState([]);const migrate=(_a=props.config.alphaMigration)!=null?_a:true;return/* @__PURE__ */jsxRuntime.jsxs(AiAssistanceConfigProvider,{config:props.config,children:[migrate?/* @__PURE__ */jsxRuntime.jsx(AlphaMigration,{}):null,/* @__PURE__ */jsxRuntime.jsx(RunInstructionProvider,{children:/* @__PURE__ */jsxRuntime.jsxs(ConnectorsProvider,{onConnectorsChange:setConnectors,children:[props.renderDefault(props),/* @__PURE__ */jsxRuntime.jsx(ui.ThemeProvider,{tone:"default",children:/* @__PURE__ */jsxRuntime.jsx(AssistConnectorsOverlay,{connectors})})]})})]});}const WrapPreCard=styled(ui.Card)(_templateObject9||(_templateObject9=_taggedTemplateLiteral(["\n & pre {\n white-space: pre-wrap !important;\n }\n"])));function SafeValueInput(props){return/* @__PURE__ */jsxRuntime.jsx(ErrorWrapper,{onChange:props.onChange,children:/* @__PURE__ */jsxRuntime.jsx(PteValueFixer,{...props})});}function ErrorWrapper(props){const{onChange}=props;const[error,setError]=React.useState();const catchError=React.useCallback(params=>{setError(params.error);},[setError]);const unsetValue=React.useCallback(()=>onChange(sanity.PatchEvent.from(sanity.unset())),[onChange]);const dismiss=React.useCallback(()=>setError(void 0),[]);const catcher=/* @__PURE__ */jsxRuntime.jsx(ui.ErrorBoundary,{onCatch:catchError,children:props.children});return error?/* @__PURE__ */jsxRuntime.jsx(ui.Card,{border:true,tone:"critical",padding:2,contentEditable:false,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,weight:"semibold",children:"An error occurred."}),/* @__PURE__ */jsxRuntime.jsx(WrapPreCard,{flex:1,padding:2,tone:"critical",border:true,children:catcher}),/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{width:"fill",flex:1,gap:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Button,{text:"Dismiss",onClick:dismiss,tone:"primary"})}),/* @__PURE__ */jsxRuntime.jsx(ui.Button,{text:"Unset value",onClick:unsetValue,tone:"critical"})]})]})}):catcher;}function PteValueFixer(props){const isPortableText=React.useMemo(()=>sanity.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}=sanity.useFormCallbacks();const key=props.value._key;const localOnChange=React.useCallback(patchEvent=>{if(!key){return;}onChange(sanity.PatchEvent.from(patchEvent).prefixAll({_key:key}));},[onChange,key]);return/* @__PURE__ */jsxRuntime.jsx(ErrorWrapper,{onChange:localOnChange,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",justify:"space-between",children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,children:props.renderDefault(props)}),presence.map(pre=>/* @__PURE__ */jsxRuntime.jsx(AiFieldPresence,{presence:pre},pre.lastActiveAt))]})});}function AssistItem(props){const{path}=props;const presence=useAssistPresence(path,true);return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",width:"fill",style:{position:"relative"},children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,children:props.renderDefault({...props})}),presence.map(pre=>/* @__PURE__ */jsxRuntime.jsx(ui.Box,{style:{position:"absolute",right:35},children:/* @__PURE__ */jsxRuntime.jsx(AiFieldPresence,{presence:pre})},pre.user.id))]});}function BackToInstructionListLink(){const{openInspector}=desk.useDocumentPane();const goBack=React.useCallback(()=>openInspector(aiInspectorId,{[instructionParam]:void 0}),[openInspector]);return/* @__PURE__ */jsxRuntime.jsx("div",{children:/* @__PURE__ */jsxRuntime.jsx(ui.Button,{as:"a",fontSize:1,icon:icons.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=React.useRef(false);const targetDocumentType=React.useMemo(()=>{if(!id){return void 0;}return documentTypeFromAiDocumentId(id);},[id]);const{params,setParams}=useAiPaneRouter();const pathKey=params[fieldPathParam];const instruction=params[instructionParam];const activeKey=React.useMemo(()=>{var _a;return(_a=(fields!=null?fields:EMPTY_FIELDS).find(f=>f.path===pathKey))==null?void 0:_a._key;},[fields,pathKey]);const activePath=React.useMemo(()=>{if(!activeKey){return void 0;}const base=["fields",{_key:activeKey}];return instruction?[...base,"instructions",{_key:instruction}]:base;},[activeKey,instruction]);const schema=sanity.useSchema();const documentSchema=React.useMemo(()=>{if(!targetDocumentType){return void 0;}return schema.get(targetDocumentType);},[schema,targetDocumentType]);const fieldSchema=useSelectedSchema(pathKey,documentSchema);const context=React.useMemo(()=>({documentSchema,fieldSchema:fieldSchema!=null?fieldSchema:documentSchema}),[fieldSchema,documentSchema]);const title=value==null?void 0:value.title;React.useEffect(()=>{var _a;if(!title&&documentSchema&&!(id==null?void 0:id.startsWith("drafts."))){onChange(sanity.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);React.useEffect(()=>{if(onChangeCalled.current||fieldExists||activePath||!pathKey){return;}onChange([sanity.setIfMissing([],["fields"]),sanity.insert([sanity.typed({_key:pathKey,_type:assistFieldTypeName,path:pathKey})],"after",["fields",-1])]);onChangeCalled.current=true;},[activePath,onChange,pathKey,fieldExists]);const{onPathOpen,...formCallbacks}=sanity.useFormCallbacks();const newCallbacks=React.useMemo(()=>({...formCallbacks,onPathOpen:path=>{var _a;if(!instruction&&path.length===4&&path[2]==="instructions"){setParams(sanity.typed({...params,[instructionParam]:(_a=path[3])==null?void 0:_a._key}));onPathOpen([]);}else{setTimeout(()=>onPathOpen(path),0);}}}),[formCallbacks,onPathOpen,params,setParams,instruction]);React.useEffect(()=>{if(activePath&&!instruction){onPathOpen([]);}},[activePath,instruction,onPathOpen]);return/* @__PURE__ */jsxRuntime.jsx(SelectedFieldContextProvider,{value:context,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:5,children:[instruction&&/* @__PURE__ */jsxRuntime.jsx(BackToInstructionListLink,{}),activePath&&/* @__PURE__ */jsxRuntime.jsx(sanity.FormCallbacksProvider,{...newCallbacks,children:/* @__PURE__ */jsxRuntime.jsx("div",{style:{lineHeight:"1.25em"},children:/* @__PURE__ */jsxRuntime.jsx(sanity.FormInput,{...props,absolutePath:activePath})})}),!activePath&&props.renderDefault(props)]})});}function useSelectedSchema(fieldPath,documentSchema){return React.useMemo(()=>{if(!fieldPath){return void 0;}if(fieldPath===documentRootKey){return documentSchema;}const path=sanity.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__ */jsxRuntime.jsxs(ui.Stack,{space:[4,4,4,5],children:[/* @__PURE__ */jsxRuntime.jsx(NameField,{...props}),/* @__PURE__ */jsxRuntime.jsx(ShareField,{...props}),/* @__PURE__ */jsxRuntime.jsx(PromptField,{...props})]});}function PromptField(props){const promptMember=findFieldMember(props.members,"prompt");return promptMember?/* @__PURE__ */jsxRuntime.jsx(sanity.ObjectInputMember,{...props,member:promptMember}):null;}const NONE=[];function NameField(props){var _a;const fieldsetMember=findFieldsetMember(props.members,"appearance");const titleId=React.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=React.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__ */jsxRuntime.jsx(ui.Stack,{space:5,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{gap:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{as:"label",weight:"semibold",size:1,htmlFor:titleId,children:"Name"})}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,children:"How this instruction appears in menus"}),/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",children:[iconMember&&/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:"none",children:/* @__PURE__ */jsxRuntime.jsx(sanity.ObjectInputMember,{...props,member:iconMember})}),moddedTitleMember&&/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,style:{marginLeft:-1},children:/* @__PURE__ */jsxRuntime.jsx(sanity.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__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children:visibilityMember&&/* @__PURE__ */jsxRuntime.jsx(sanity.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=sanity.useCurrentUser();const handleChange=React.useCallback(()=>{var _a;const newValue=value?"":(_a=user==null?void 0:user.id)!=null?_a:"";onChange(newValue?sanity.set(newValue):sanity.unset());},[onChange,user,value]);const id=React.useId();return/* @__PURE__ */jsxRuntime.jsx(ui.Card,{children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:2,align:"flex-start",children:[/* @__PURE__ */jsxRuntime.jsx("div",{style:{margin:"-3px 0"},children:/* @__PURE__ */jsxRuntime.jsx(ui.Switch,{...props.elementProps,id,value:"".concat(!value),checked:!value,onChange:handleChange,disabled:props.elementProps.readOnly})}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,weight:"medium",children:/* @__PURE__ */jsxRuntime.jsx("label",{htmlFor:id,children:"Make visible to all Studio members"})})]})});}function IconInput(props){const{value,onChange}=props;const id=React.useId();const items=React.useMemo(()=>Object.entries(icons.icons).map(_ref74=>{let[key,icon]=_ref74;return/* @__PURE__ */jsxRuntime.jsx(IconItem,{iconKey:key,icon,onChange},key);}),[onChange]);const selectedIcon=React.useMemo(()=>getIcon(value),[value]);return/* @__PURE__ */jsxRuntime.jsx(ui.MenuButton,{button:/* @__PURE__ */jsxRuntime.jsx(ui.Button,{icon:selectedIcon,title:"Select icon",padding:3,mode:"ghost",radius:1}),id,menu:/* @__PURE__ */jsxRuntime.jsx(ui.Menu,{style:{maxHeight:300},children:items}),popover:{portal:true}});}function IconItem(_ref75){let{icon,iconKey:key,onChange}=_ref75;const onClick=React.useCallback(()=>onChange(sanity.set(key)),[onChange,key]);return/* @__PURE__ */jsxRuntime.jsx(ui.MenuItem,{icon,title:key,text:key,onClick});}function getIcon(iconName){var _a,_b;return(_b=(_a=Object.entries(icons.icons).find(_ref76=>{let[key]=_ref76;return key===iconName;}))==null?void 0:_a[1])!=null?_b:icons.icons.sparkles;}function FieldAutocomplete(props){const{id,schemaType,fieldPath,onSelect,includeDocument}=props;const fieldNames=React.useMemo(()=>{if(includeDocument){return getFieldRefsWithDocument(schemaType);}return getFieldRefs(schemaType);},[schemaType,includeDocument]);const currentField=React.useMemo(()=>fieldNames.find(f=>f.key===fieldPath),[fieldPath,fieldNames]);const autocompleteOptions=React.useMemo(()=>fieldNames.map(field=>({value:field.key,field})),[fieldNames]);const renderOption=React.useCallback(option=>{const{value,field}=option;if(!value){return/* @__PURE__ */jsxRuntime.jsx(ui.Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{accent:true,size:1,children:option.value})});}if(isType(field.schemaType,"document")){return/* @__PURE__ */jsxRuntime.jsx(ui.Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,weight:"semibold",children:"The entire document"})});}const splitTitle=field.title.split("/");return/* @__PURE__ */jsxRuntime.jsx(ui.Card,{as:"button",padding:3,radius:1,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:React.createElement(field.icon)}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:"none",children:/* @__PURE__ */jsxRuntime.jsxs(ui.Breadcrumbs,{separator:/* @__PURE__ */jsxRuntime.jsx(ui.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
2312
|
/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,children:pt.trim()},i)),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,weight:"medium",children:splitTitle[splitTitle.length-1]})]})})]})});},[]);const renderValue=React.useCallback((value,option)=>{var _a;return(_a=option==null?void 0:option.field.title)!=null?_a:value;},[]);const filterOption=React.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__ */jsxRuntime.jsx(ui.Autocomplete,{fontSize:1,icon:currentField?currentField.icon:icons.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=React.useContext(SelectedFieldContext))==null?void 0:_a.documentSchema;const ref=React.useRef(null);const id=React.useId();const{onChange}=props;React.useEffect(()=>{var _a2,_b;(_b=(_a2=ref.current)==null?void 0:_a2.querySelector("input"))==null?void 0:_b.focus();},[]);const onSelect=React.useCallback(path=>onChange(sanity.set(path)),[onChange]);if(!documentSchema){return props.renderDefault(props);}return/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,style:{minWidth:200},ref,children:/* @__PURE__ */jsxRuntime.jsx(FieldAutocomplete,{id,schemaType:documentSchema,onSelect,fieldPath:props.value})});}function InstructionsArrayInput(props){const user=sanity.useCurrentUser();const originalValue=props.value;const originalMembers=props.members;const value=React.useMemo(()=>(originalValue!=null?originalValue:[]).filter(v=>!v.userId||v.userId===(user==null?void 0:user.id)),[originalValue,user]);const members=React.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=React.createContext(void 0);function AssistInlineFormBlock(props){return/* @__PURE__ */jsxRuntime.jsx(InlineBlockValueContext.Provider,{value:props.value,children:/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,children:props.renderDefault(props)})});}function FieldRefPreview(props){var _a,_b,_c,_d;const documentSchema=(_a=React.useContext(SelectedFieldContext))==null?void 0:_a.documentSchema;const path=(_c=(_b=React.useContext(InlineBlockValueContext))==null?void 0:_b.path)!=null?_c:props.path;const selectedField=useSelectedField(documentSchema,path);return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:2,align:"center",style:{width:"100%"},children:[/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{flex:1,gap:2,align:"center",paddingY:3,paddingX:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Box,{children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,textOverflow:"ellipsis",children:(_d=selectedField==null?void 0:selectedField.title)!=null?_d:"Select field"})})}),/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children:props.actions})]});}function HideReferenceChangedBannerInput(props){const ref=React.useRef(null);React.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__ */jsxRuntime.jsx(ui.Box,{ref,children:props.renderDefault(props)});}const contextDocumentSchema=sanity.defineType({type:"document",name:contextDocumentTypeName,title:"AI context",liveEdit:true,icon:icons.TokenIcon,components:{input:HideReferenceChangedBannerInput},fields:[sanity.defineField({type:"string",name:"title",title:"Title"}),sanity.defineField({name:"context",type:"array",title:"Context",of:[sanity.defineArrayMember({type:"block",styles:[{title:"Normal",value:"normal"}],lists:[],marks:{decorators:[],annotations:[]}})]})],preview:{select:{title:"title",context:"context"},prepare(_ref77){let{title,context}=_ref77;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:icons.DocumentTextIcon};}}});// Strict ESM env, designed to run outside Node.js in envs that provide WebCrypto (deno, browsers, etc)
|
|
2313
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(ui.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__ */jsxRuntime.jsx(PteMods,{children:props.renderDefault(props)});}function useOnlyInlineBlocks(props){React.useEffect(()=>{var _a;let needsFix=false;const val=((_a=props.value)!=null?_a:[]).map(block=>{if(block._type==="block"){return block;}needsFix=true;return sanity.typed({_key:randomKey(12),_type:"block",level:0,markDefs:[],style:"normal",children:[block]});});if(needsFix){props.onChange(sanity.set(val));}},[]);}function InstructionsArrayField(props){return props.renderDefault({...props,title:void 0});}const fieldReference=sanity.defineType({type:"object",name:fieldReferenceTypeName,title:"Document field",icon:icons.ThListIcon,fields:[sanity.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(_ref78){let{path}=_ref78;return{title:path,path,icon:icons.CodeIcon};}},components:{preview:FieldRefPreview},options:{modal:{type:"popover"}}});const userInput=sanity.defineType({type:"object",name:userInputTypeName,title:"User input",icon:icons.ComposeIcon,fields:[sanity.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()}),sanity.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=sanity.defineType({type:"object",name:instructionContextTypeName,title:contextDocumentSchema.title,icon:contextDocumentSchema.icon,fields:[sanity.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__ */jsxRuntime.jsx(ui.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=sanity.defineType({type:"array",name:promptTypeName,title:"Prompt",of:[sanity.defineArrayMember({type:"block",styles:[{title:"Normal",value:"normal"}],lists:[],marks:{decorators:[],annotations:[]},of:[sanity.defineArrayMember({type:fieldReference.name}),sanity.defineArrayMember({type:promptContext.name}),sanity.defineArrayMember({type:userInput.name})]})/* defineArrayMember({
|
|
2314
2314
|
type: fieldReference.name,
|