sanity 3.26.2-canary.52 → 3.26.2-canary.69

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.
Files changed (112) hide show
  1. package/lib/_chunks/{_internal-2CJ5wSKF.js → _internal-6Pl2wJGj.js} +422 -201
  2. package/lib/_chunks/_internal-6Pl2wJGj.js.map +1 -0
  3. package/lib/_chunks/{_internal-79flWvL8.js → _internal-yQwMw2ht.js} +419 -203
  4. package/lib/_chunks/_internal-yQwMw2ht.js.map +1 -0
  5. package/lib/_chunks/{_internalBrowser-QAFz3SKp.js → _internalBrowser-HWvRXvlU.js} +22 -22
  6. package/lib/_chunks/_internalBrowser-HWvRXvlU.js.map +1 -0
  7. package/lib/_chunks/{_internalBrowser-Y0qKZ-GA.js → _internalBrowser-TWIhitgI.js} +22 -22
  8. package/lib/_chunks/_internalBrowser-TWIhitgI.js.map +1 -0
  9. package/lib/_chunks/{deployApiAction-SHteit1G.js → deployApiAction-TZcCtXan.js} +2 -2
  10. package/lib/_chunks/{deployApiAction-SHteit1G.js.map → deployApiAction-TZcCtXan.js.map} +1 -1
  11. package/lib/_chunks/{deployApiAction-bRyJpGOS.js → deployApiAction-rVL67VYW.js} +2 -2
  12. package/lib/_chunks/{deployApiAction-bRyJpGOS.js.map → deployApiAction-rVL67VYW.js.map} +1 -1
  13. package/lib/_chunks/{getStudioConfig-JSkc4GE0.js → getStudioWorkspaces-HX9o9-hl.js} +20 -4
  14. package/lib/_chunks/getStudioWorkspaces-HX9o9-hl.js.map +1 -0
  15. package/lib/_chunks/{index-EO9iRnDS.js → index-2kSxso3r.js} +2 -2
  16. package/lib/_chunks/{index-EO9iRnDS.js.map → index-2kSxso3r.js.map} +1 -1
  17. package/lib/_chunks/{index-FQCCBbuC.js → index-751ZLh3z.js} +6 -6
  18. package/lib/_chunks/{index-FQCCBbuC.js.map → index-751ZLh3z.js.map} +1 -1
  19. package/lib/_chunks/{index-VNSHvpZr.js → index-HcF369ru.js} +2 -2
  20. package/lib/_chunks/{index-VNSHvpZr.js.map → index-HcF369ru.js.map} +1 -1
  21. package/lib/_chunks/{index-Xs2xnLUV.js → index-MAAxgUnl.js} +6 -6
  22. package/lib/_chunks/{index-Xs2xnLUV.js.map → index-MAAxgUnl.js.map} +1 -1
  23. package/lib/_chunks/{index-AaK2CidU.js → index-NweJPfGb.js} +2 -2
  24. package/lib/_chunks/{index-AaK2CidU.js.map → index-NweJPfGb.js.map} +1 -1
  25. package/lib/_chunks/{index-R7R6AyHF.js → index-zobOqko7.js} +2 -2
  26. package/lib/_chunks/{index-R7R6AyHF.js.map → index-zobOqko7.js.map} +1 -1
  27. package/lib/_chunks/{listApisAction-6lGkFZrU.js → listApisAction-IvKV4iAd.js} +2 -2
  28. package/lib/_chunks/{listApisAction-6lGkFZrU.js.map → listApisAction-IvKV4iAd.js.map} +1 -1
  29. package/lib/_chunks/{listApisAction-CqCkBz-F.js → listApisAction-oca2uykY.js} +2 -2
  30. package/lib/_chunks/{listApisAction-CqCkBz-F.js.map → listApisAction-oca2uykY.js.map} +1 -1
  31. package/lib/_chunks/pane-9HEeITpx.js +5 -0
  32. package/lib/_chunks/pane-9HEeITpx.js.map +1 -0
  33. package/lib/_chunks/pane-QyVrOLqS.js +2 -0
  34. package/lib/_chunks/pane-QyVrOLqS.js.map +1 -0
  35. package/lib/_chunks/pane-TXXUUvdc.js +5 -0
  36. package/lib/_chunks/pane-TXXUUvdc.js.map +1 -0
  37. package/lib/_chunks/pane-cQxQtBcL.js +2 -0
  38. package/lib/_chunks/pane-cQxQtBcL.js.map +1 -0
  39. package/lib/_chunks/{structure-qJLnDJXq.js → structure-iqIDIH7-.js} +3 -3
  40. package/lib/_chunks/structure-iqIDIH7-.js.map +1 -0
  41. package/lib/_chunks/{structure-588eAwLd.js → structure-o_wMXC_G.js} +3 -3
  42. package/lib/_chunks/structure-o_wMXC_G.js.map +1 -0
  43. package/lib/_chunks/validateAction-4Jl_y_iB.js +154 -0
  44. package/lib/_chunks/validateAction-4Jl_y_iB.js.map +1 -0
  45. package/lib/_chunks/{validateAction-GUvMkXiN.js → validateAction-6q8Sqwaz.js} +25 -73
  46. package/lib/_chunks/validateAction-6q8Sqwaz.js.map +1 -0
  47. package/lib/_chunks/validateAction-Bz67ApRP.js +143 -0
  48. package/lib/_chunks/validateAction-Bz67ApRP.js.map +1 -0
  49. package/lib/_chunks/{validateAction-NIrqtyYJ.js → validateAction-shi462sq.js} +27 -75
  50. package/lib/_chunks/validateAction-shi462sq.js.map +1 -0
  51. package/lib/_internal/cli/threads/getGraphQLAPIs.js +2 -2
  52. package/lib/_internal/cli/threads/getGraphQLAPIs.js.map +1 -1
  53. package/lib/_internal/cli/threads/validateDocuments.js +5 -3
  54. package/lib/_internal/cli/threads/validateDocuments.js.map +1 -1
  55. package/lib/_internal/cli/threads/validateSchema.js +55 -0
  56. package/lib/_internal/cli/threads/validateSchema.js.map +1 -0
  57. package/lib/_internal.esm.js +1 -1
  58. package/lib/_internal.js +1 -1
  59. package/lib/_internalBrowser.esm.js +1 -1
  60. package/lib/_internalBrowser.js +1 -1
  61. package/lib/desk.esm.js +1 -1
  62. package/lib/desk.js +1 -1
  63. package/lib/exports/index.d.ts +25 -0
  64. package/lib/index.cjs.mjs +1 -0
  65. package/lib/index.esm.js +2 -2
  66. package/lib/index.js +2 -1
  67. package/lib/index.js.map +1 -1
  68. package/lib/structure.esm.js +1 -1
  69. package/lib/structure.js +1 -1
  70. package/package.json +15 -15
  71. package/src/_internal/cli/actions/schema/formatSchemaValidation.ts +96 -0
  72. package/src/_internal/cli/actions/schema/validateAction.ts +120 -0
  73. package/src/_internal/cli/actions/validation/reporters/prettyReporter/formatDocumentValidation.ts +17 -95
  74. package/src/_internal/cli/commands/index.ts +2 -0
  75. package/src/_internal/cli/commands/migration/createMigrationCommand.ts +18 -10
  76. package/src/_internal/cli/commands/migration/listMigrationsCommand.ts +34 -31
  77. package/src/_internal/cli/commands/migration/prettyMutationFormatter.ts +214 -0
  78. package/src/_internal/cli/commands/migration/runMigrationCommand.ts +102 -58
  79. package/src/_internal/cli/commands/migration/templates/minimalAdvanced.ts +1 -1
  80. package/src/_internal/cli/commands/migration/templates/minimalSimple.ts +1 -1
  81. package/src/_internal/cli/commands/migration/templates/renameField.ts +3 -3
  82. package/src/_internal/cli/commands/migration/templates/renameType.ts +1 -1
  83. package/src/_internal/cli/commands/migration/templates/stringToPTE.ts +1 -1
  84. package/src/_internal/cli/commands/migration/utils/mutationFormatter.ts +1 -1
  85. package/src/_internal/cli/commands/schema/validateSchemaCommand.ts +35 -0
  86. package/src/_internal/cli/threads/getGraphQLAPIs.ts +2 -2
  87. package/src/_internal/cli/threads/validateDocuments.ts +6 -3
  88. package/src/_internal/cli/threads/validateSchema.ts +73 -0
  89. package/src/_internal/cli/util/{getStudioConfig.ts → getStudioWorkspaces.ts} +30 -8
  90. package/src/_internal/cli/util/tree.ts +110 -0
  91. package/src/core/config/index.ts +1 -0
  92. package/src/core/config/prepareConfig.ts +2 -5
  93. package/src/core/config/resolveSchemaTypes.ts +29 -0
  94. package/src/core/studio/screens/schemaErrors/SchemaProblemGroups.tsx +4 -2
  95. package/src/structure/comments/src/components/pte/blocks/MentionInlineBlock.tsx +13 -6
  96. package/lib/_chunks/_internal-2CJ5wSKF.js.map +0 -1
  97. package/lib/_chunks/_internal-79flWvL8.js.map +0 -1
  98. package/lib/_chunks/_internalBrowser-QAFz3SKp.js.map +0 -1
  99. package/lib/_chunks/_internalBrowser-Y0qKZ-GA.js.map +0 -1
  100. package/lib/_chunks/getStudioConfig-JSkc4GE0.js.map +0 -1
  101. package/lib/_chunks/pane-QmJb9ZTN.js +0 -2
  102. package/lib/_chunks/pane-QmJb9ZTN.js.map +0 -1
  103. package/lib/_chunks/pane-SK7FWNTJ.js +0 -2
  104. package/lib/_chunks/pane-SK7FWNTJ.js.map +0 -1
  105. package/lib/_chunks/pane-y4hpcKe1.js +0 -5
  106. package/lib/_chunks/pane-y4hpcKe1.js.map +0 -1
  107. package/lib/_chunks/pane-yQXBQyyI.js +0 -5
  108. package/lib/_chunks/pane-yQXBQyyI.js.map +0 -1
  109. package/lib/_chunks/structure-588eAwLd.js.map +0 -1
  110. package/lib/_chunks/structure-qJLnDJXq.js.map +0 -1
  111. package/lib/_chunks/validateAction-GUvMkXiN.js.map +0 -1
  112. package/lib/_chunks/validateAction-NIrqtyYJ.js.map +0 -1
@@ -15,7 +15,7 @@ pane.type==="documentList"&&pane.schemaTypeName===params.type&&pane.options.filt
15
15
  router$1.route.intents("/intent"),// Legacy fallback route, will be redirected to new format
16
16
  router$1.route.create("/edit/:type/:editDocumentId",[router$1.route.create({path:"/:params",transform:{params:{toState:legacyEditParamsToState,toPath:legacyEditParamsToPath}}})]),// The regular path - when the intent can be resolved to a specific pane
17
17
  router$1.route.create({path:"/:panes",// Legacy URLs, used to handle redirects
18
- children:[router$1.route.create("/:action",router$1.route.create("/:legacyEditDocumentId"))],transform:{panes:{toState,toPath}}})]);const panePattern=/^([.a-z0-9_-]+),?({.*?})?(?:(;|$))/i;const isParam=str=>/^[a-z0-9]+=[^=]+/i.test(str);const isPayloadLike=str=>/^[A-Za-z0-9\-_]+(?:={0,2})$/.test(str);const exclusiveParams=["view","since","rev","inspect","comment"];const isTruthy=Boolean;function parseChunks(chunks,initial){const sibling={...initial,params:EMPTY_PARAMS$1,payload:void 0};return chunks.reduce((pane,chunk)=>{if(isParam(chunk)){const key=chunk.slice(0,chunk.indexOf("="));const value=chunk.slice(key.length+1);pane.params={...pane.params,[decodeURIComponent(key)]:decodeURIComponent(value)};}else if(isPayloadLike(chunk)){pane.payload=tryParseBase64Payload(chunk);}else{console.warn("Unknown pane segment: %s - skipping",chunk);}return pane;},sibling);}function encodeChunks(pane,index,group){const{payload,params={},id}=pane;const[firstSibling]=group;const paneIsFirstSibling=pane===firstSibling;const sameAsFirst=index!==0&&id===firstSibling.id;const encodedPayload=typeof payload==="undefined"?void 0:router$1.encodeJsonParams(payload);const encodedParams=Object.entries(params).filter(entry=>{var _a;const[key,value]=entry;if(!value)return false;if(paneIsFirstSibling)return true;const valueFromFirstSibling=(_a=firstSibling.params)==null?void 0:_a[key];if(value===valueFromFirstSibling&&!exclusiveParams.includes(key))return false;return true;}).map(_ref28=>{let[key,value]=_ref28;return"".concat(encodeURIComponent(key),"=").concat(encodeURIComponent(value));});return[sameAsFirst?"":id].concat([encodedParams.length>0&&encodedParams,encodedPayload].filter(isTruthy).flat()).join(",")||",";}function parsePanesSegment(str){if(str.indexOf(",{")!==-1){return parseOldPanesSegment(str);}return str.split(";").map(group=>{const[firstSibling,...restOfSiblings]=group.split("|").map(segment=>{const[id,...chunks]=segment.split(",");return parseChunks(chunks,{id});});return[firstSibling,...restOfSiblings.map(sibling=>({...firstSibling,...sibling,id:sibling.id||firstSibling.id,params:{...omit__default.default(firstSibling.params,exclusiveParams),...sibling.params},payload:sibling.payload||firstSibling.payload}))];}).filter(group=>group.length>0);}function parseOldPanesSegment(str){const chunks=[];let buffer=str;while(buffer.length){const[match,id,payloadChunk]=buffer.match(panePattern)||[];if(!match){buffer=buffer.slice(1);continue;}const payload=payloadChunk&&tryParsePayload(payloadChunk);chunks.push({id,payload});buffer=buffer.slice(match.length);}return[chunks];}function tryParsePayload(json){try{return JSON.parse(json);}catch(err){console.warn("Failed to parse parameters: ".concat(err.message));return void 0;}}function tryParseBase64Payload(data){try{return data?router$1.decodeJsonParams(data):void 0;}catch(err){console.warn("Failed to parse parameters: ".concat(err.message));return void 0;}}const commentsLocaleNamespace="comments";const commentsUsEnglishLocaleBundle=sanity.defineLocaleResourceBundle({locale:"en-US",namespace:commentsLocaleNamespace,resources:()=>Promise.resolve().then(function(){return require('./resources-9GbvVlpz.js');})});const DOCUMENT_PANEL_MIN_WIDTH=320;const DOCUMENT_PANEL_INITIAL_MIN_WIDTH=600;const DOCUMENT_INSPECTOR_MIN_WIDTH=320;const DOCUMENT_INSPECTOR_MAX_WIDTH=540;const EMPTY_PARAMS={};const INSPECT_ACTION_PREFIX="inspect:";const DEFAULT_MENU_ITEM_GROUPS=[{id:"inspectors"},{id:"links"}];const HISTORY_INSPECTOR_NAME="sanity/structure/history";const VALIDATION_INSPECTOR_NAME="sanity/structure/validation";const COMMENTS_INSPECTOR_NAME="sanity/structure/comments";var __freeze$x=Object.freeze;var __defProp$x=Object.defineProperty;var __template$x=(cooked,raw)=>__freeze$x(__defProp$x(cooked,"raw",{value:__freeze$x(raw||cooked.slice())}));var _a$x;const StyledAvatar=styled__default.default(ui.Avatar)(_a$x||(_a$x=__template$x(["\n svg > ellipse {\n stroke: transparent;\n }\n"])));const SYMBOLS=/[^\p{Alpha}\p{White_Space}]/gu;const WHITESPACE=new RegExp("\\p{White_Space}+","u");function nameToInitials(fullName){const namesArray=fullName.replace(SYMBOLS,"").split(WHITESPACE);if(namesArray.length===1){return"".concat(namesArray[0].charAt(0)).toUpperCase();}return"".concat(namesArray[0].charAt(0)).concat(namesArray[namesArray.length-1].charAt(0));}function CommentsAvatar(props){const{user:userProp,...restProps}=props;const user=userProp;const initials=React.useMemo(()=>nameToInitials((user==null?void 0:user.displayName)||""),[user==null?void 0:user.displayName]);if(!user)return/* @__PURE__ */jsxRuntime.jsx(StyledAvatar,{...restProps});return/* @__PURE__ */jsxRuntime.jsx(StyledAvatar,{initials,src:user==null?void 0:user.imageUrl,title:user==null?void 0:user.displayName,...restProps});}const AVATAR_HEIGHT=25;const INLINE_STYLE$1={minWidth:AVATAR_HEIGHT};function SpacerAvatar(){return/* @__PURE__ */jsxRuntime.jsx("div",{style:INLINE_STYLE$1});}var __freeze$w=Object.freeze;var __defProp$w=Object.defineProperty;var __template$w=(cooked,raw)=>__freeze$w(__defProp$w(cooked,"raw",{value:__freeze$w(raw||cooked.slice())}));var _a$w;const Span$1=styled__default.default.span(_ref29=>{let{theme}=_ref29;var _a2,_b,_c;const{regular}=(_a2=theme.sanity.fonts)==null?void 0:_a2.text.weights;const{hovered}=(_b=theme.sanity.color)==null?void 0:_b.card;const{bg}=((_c=theme.sanity.color.selectable)==null?void 0:_c.caution.pressed)||{};return styled.css(_a$w||(_a$w=__template$w(["\n font-weight: ",";\n color: var(--card-link-fg-color);\n border-radius: 2px;\n background-color: ",";\n padding: 1px;\n box-sizing: border-box;\n\n &[data-active='true'] {\n background-color: ",";\n }\n "])),regular,hovered.bg,bg);});function MentionInlineBlock(props){const{selected,userId}=props;const[user,loading]=sanity.useUser(userId);const currentUser=sanity.useCurrentUser();sanity.useTranslation(commentsLocaleNamespace);if(!user||loading)return/* @__PURE__ */jsxRuntime.jsx(Span$1,{children:"@Loading"});return/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Tooltip,{portal:true,content:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",gap:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{children:/* @__PURE__ */jsxRuntime.jsx(CommentsAvatar,{user})}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:user.displayName})]}),children:/* @__PURE__ */jsxRuntime.jsxs(Span$1,{"data-selected":selected,"data-active":(currentUser==null?void 0:currentUser.id)===userId,children:["@",user.displayName]})});}var __freeze$v=Object.freeze;var __defProp$v=Object.defineProperty;var __template$v=(cooked,raw)=>__freeze$v(__defProp$v(cooked,"raw",{value:__freeze$v(raw||cooked.slice())}));var _a$v;const NormalText=styled__default.default(ui.Text)(_a$v||(_a$v=__template$v(["\n word-break: break-word;\n"])));function NormalBlock(props){const{children}=props;return/* @__PURE__ */jsxRuntime.jsx(NormalText,{size:1,children});}var __freeze$u=Object.freeze;var __defProp$u=Object.defineProperty;var __template$u=(cooked,raw)=>__freeze$u(__defProp$u(cooked,"raw",{value:__freeze$u(raw||cooked.slice())}));var _a$u;const PortableTextWrap=styled__default.default(ui.Stack)(()=>{return styled.css(_a$u||(_a$u=__template$u(["\n & > [data-ui='Text']:not(:first-child) {\n margin-top: 1em; // todo: improve\n }\n\n & > [data-ui='Text']:has(> span:empty) {\n display: none;\n }\n "])));});const EMPTY_ARRAY$9=[];const components={block:{normal:_ref30=>{let{children}=_ref30;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},// Since we do not offer any formatting options, we can just use the normal block for all of these.
18
+ children:[router$1.route.create("/:action",router$1.route.create("/:legacyEditDocumentId"))],transform:{panes:{toState,toPath}}})]);const panePattern=/^([.a-z0-9_-]+),?({.*?})?(?:(;|$))/i;const isParam=str=>/^[a-z0-9]+=[^=]+/i.test(str);const isPayloadLike=str=>/^[A-Za-z0-9\-_]+(?:={0,2})$/.test(str);const exclusiveParams=["view","since","rev","inspect","comment"];const isTruthy=Boolean;function parseChunks(chunks,initial){const sibling={...initial,params:EMPTY_PARAMS$1,payload:void 0};return chunks.reduce((pane,chunk)=>{if(isParam(chunk)){const key=chunk.slice(0,chunk.indexOf("="));const value=chunk.slice(key.length+1);pane.params={...pane.params,[decodeURIComponent(key)]:decodeURIComponent(value)};}else if(isPayloadLike(chunk)){pane.payload=tryParseBase64Payload(chunk);}else{console.warn("Unknown pane segment: %s - skipping",chunk);}return pane;},sibling);}function encodeChunks(pane,index,group){const{payload,params={},id}=pane;const[firstSibling]=group;const paneIsFirstSibling=pane===firstSibling;const sameAsFirst=index!==0&&id===firstSibling.id;const encodedPayload=typeof payload==="undefined"?void 0:router$1.encodeJsonParams(payload);const encodedParams=Object.entries(params).filter(entry=>{var _a;const[key,value]=entry;if(!value)return false;if(paneIsFirstSibling)return true;const valueFromFirstSibling=(_a=firstSibling.params)==null?void 0:_a[key];if(value===valueFromFirstSibling&&!exclusiveParams.includes(key))return false;return true;}).map(_ref28=>{let[key,value]=_ref28;return"".concat(encodeURIComponent(key),"=").concat(encodeURIComponent(value));});return[sameAsFirst?"":id].concat([encodedParams.length>0&&encodedParams,encodedPayload].filter(isTruthy).flat()).join(",")||",";}function parsePanesSegment(str){if(str.indexOf(",{")!==-1){return parseOldPanesSegment(str);}return str.split(";").map(group=>{const[firstSibling,...restOfSiblings]=group.split("|").map(segment=>{const[id,...chunks]=segment.split(",");return parseChunks(chunks,{id});});return[firstSibling,...restOfSiblings.map(sibling=>({...firstSibling,...sibling,id:sibling.id||firstSibling.id,params:{...omit__default.default(firstSibling.params,exclusiveParams),...sibling.params},payload:sibling.payload||firstSibling.payload}))];}).filter(group=>group.length>0);}function parseOldPanesSegment(str){const chunks=[];let buffer=str;while(buffer.length){const[match,id,payloadChunk]=buffer.match(panePattern)||[];if(!match){buffer=buffer.slice(1);continue;}const payload=payloadChunk&&tryParsePayload(payloadChunk);chunks.push({id,payload});buffer=buffer.slice(match.length);}return[chunks];}function tryParsePayload(json){try{return JSON.parse(json);}catch(err){console.warn("Failed to parse parameters: ".concat(err.message));return void 0;}}function tryParseBase64Payload(data){try{return data?router$1.decodeJsonParams(data):void 0;}catch(err){console.warn("Failed to parse parameters: ".concat(err.message));return void 0;}}const commentsLocaleNamespace="comments";const commentsUsEnglishLocaleBundle=sanity.defineLocaleResourceBundle({locale:"en-US",namespace:commentsLocaleNamespace,resources:()=>Promise.resolve().then(function(){return require('./resources-9GbvVlpz.js');})});const DOCUMENT_PANEL_MIN_WIDTH=320;const DOCUMENT_PANEL_INITIAL_MIN_WIDTH=600;const DOCUMENT_INSPECTOR_MIN_WIDTH=320;const DOCUMENT_INSPECTOR_MAX_WIDTH=540;const EMPTY_PARAMS={};const INSPECT_ACTION_PREFIX="inspect:";const DEFAULT_MENU_ITEM_GROUPS=[{id:"inspectors"},{id:"links"}];const HISTORY_INSPECTOR_NAME="sanity/structure/history";const VALIDATION_INSPECTOR_NAME="sanity/structure/validation";const COMMENTS_INSPECTOR_NAME="sanity/structure/comments";var __freeze$x=Object.freeze;var __defProp$x=Object.defineProperty;var __template$x=(cooked,raw)=>__freeze$x(__defProp$x(cooked,"raw",{value:__freeze$x(raw||cooked.slice())}));var _a$x;const StyledAvatar=styled__default.default(ui.Avatar)(_a$x||(_a$x=__template$x(["\n svg > ellipse {\n stroke: transparent;\n }\n"])));const SYMBOLS=/[^\p{Alpha}\p{White_Space}]/gu;const WHITESPACE=new RegExp("\\p{White_Space}+","u");function nameToInitials(fullName){const namesArray=fullName.replace(SYMBOLS,"").split(WHITESPACE);if(namesArray.length===1){return"".concat(namesArray[0].charAt(0)).toUpperCase();}return"".concat(namesArray[0].charAt(0)).concat(namesArray[namesArray.length-1].charAt(0));}function CommentsAvatar(props){const{user:userProp,...restProps}=props;const user=userProp;const initials=React.useMemo(()=>nameToInitials((user==null?void 0:user.displayName)||""),[user==null?void 0:user.displayName]);if(!user)return/* @__PURE__ */jsxRuntime.jsx(StyledAvatar,{...restProps});return/* @__PURE__ */jsxRuntime.jsx(StyledAvatar,{initials,src:user==null?void 0:user.imageUrl,title:user==null?void 0:user.displayName,...restProps});}const AVATAR_HEIGHT=25;const INLINE_STYLE$1={minWidth:AVATAR_HEIGHT};function SpacerAvatar(){return/* @__PURE__ */jsxRuntime.jsx("div",{style:INLINE_STYLE$1});}var __freeze$w=Object.freeze;var __defProp$w=Object.defineProperty;var __template$w=(cooked,raw)=>__freeze$w(__defProp$w(cooked,"raw",{value:__freeze$w(raw||cooked.slice())}));var _a$w;const Span$1=styled__default.default.span(_ref29=>{let{theme}=_ref29;var _a2,_b,_c;const{regular}=(_a2=theme.sanity.fonts)==null?void 0:_a2.text.weights;const{hovered}=(_b=theme.sanity.color)==null?void 0:_b.card;const{bg}=((_c=theme.sanity.color.selectable)==null?void 0:_c.caution.pressed)||{};return styled.css(_a$w||(_a$w=__template$w(["\n font-weight: ",";\n color: var(--card-link-fg-color);\n border-radius: 2px;\n background-color: ",";\n padding: 1px;\n box-sizing: border-box;\n\n &[data-active='true'] {\n background-color: ",";\n }\n "])),regular,hovered.bg,bg);});function MentionInlineBlock(props){const{selected,userId}=props;const[user,loading]=sanity.useUser(userId);const currentUser=sanity.useCurrentUser();if(!user||loading)return/* @__PURE__ */jsxRuntime.jsx(ui.TextSkeleton,{"data-testid":"comment-mentions-loading-skeleton",style:{width:"10ch"},size:0,muted:true,radius:1,animated:true});return/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Tooltip,{portal:true,content:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",gap:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{children:/* @__PURE__ */jsxRuntime.jsx(CommentsAvatar,{user})}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:user.displayName})]}),children:/* @__PURE__ */jsxRuntime.jsxs(Span$1,{"data-selected":selected,"data-active":(currentUser==null?void 0:currentUser.id)===userId,children:["@",user.displayName]})});}var __freeze$v=Object.freeze;var __defProp$v=Object.defineProperty;var __template$v=(cooked,raw)=>__freeze$v(__defProp$v(cooked,"raw",{value:__freeze$v(raw||cooked.slice())}));var _a$v;const NormalText=styled__default.default(ui.Text)(_a$v||(_a$v=__template$v(["\n word-break: break-word;\n"])));function NormalBlock(props){const{children}=props;return/* @__PURE__ */jsxRuntime.jsx(NormalText,{size:1,children});}var __freeze$u=Object.freeze;var __defProp$u=Object.defineProperty;var __template$u=(cooked,raw)=>__freeze$u(__defProp$u(cooked,"raw",{value:__freeze$u(raw||cooked.slice())}));var _a$u;const PortableTextWrap=styled__default.default(ui.Stack)(()=>{return styled.css(_a$u||(_a$u=__template$u(["\n & > [data-ui='Text']:not(:first-child) {\n margin-top: 1em; // todo: improve\n }\n\n & > [data-ui='Text']:has(> span:empty) {\n display: none;\n }\n "])));});const EMPTY_ARRAY$9=[];const components={block:{normal:_ref30=>{let{children}=_ref30;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},// Since we do not offer any formatting options, we can just use the normal block for all of these.
19
19
  h1:_ref31=>{let{children}=_ref31;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},h2:_ref32=>{let{children}=_ref32;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},h3:_ref33=>{let{children}=_ref33;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},h4:_ref34=>{let{children}=_ref34;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},h5:_ref35=>{let{children}=_ref35;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},h6:_ref36=>{let{children}=_ref36;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},blockquote:_ref37=>{let{children}=_ref37;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},code:_ref38=>{let{children}=_ref38;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});}},list:{bullet:_ref39=>{let{children}=_ref39;return children;},number:_ref40=>{let{children}=_ref40;return/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children});},checkmarks:_ref41=>{let{children}=_ref41;return/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children});}},listItem:{bullet:_ref42=>{let{children}=_ref42;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},number:_ref43=>{let{children}=_ref43;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});},checkmarks:_ref44=>{let{children}=_ref44;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});}},marks:{// Since we do not offer any formatting options, we can just use the normal block for all of these.
20
20
  strong:_ref45=>{let{children}=_ref45;return/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children});},em:_ref46=>{let{children}=_ref46;return/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children});},code:_ref47=>{let{children}=_ref47;return/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children});},underline:_ref48=>{let{children}=_ref48;return/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children});},strikeThrough:_ref49=>{let{children}=_ref49;return/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children});},link:_ref50=>{let{children}=_ref50;return/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children});}},types:{mention:props=>{var _a2;return/* @__PURE__ */jsxRuntime.jsx(MentionInlineBlock,{userId:(_a2=props==null?void 0:props.value)==null?void 0:_a2.userId,selected:false});}}};function CommentMessageSerializer(props){const{blocks}=props;return/* @__PURE__ */jsxRuntime.jsx(PortableTextWrap,{children:/* @__PURE__ */jsxRuntime.jsx(react$1.PortableText,{value:blocks||EMPTY_ARRAY$9,components})});}const mentionObject=types.defineField({name:"mention",type:"object",fields:[{name:"userId",type:"string"}]});const blockType=types.defineField({type:"block",name:"block",of:[mentionObject],marks:{annotations:[]},styles:[{title:"Normal",value:"normal"}],lists:[]});const portableTextType=types.defineArrayMember({type:"array",name:"body",of:[blockType]});const schema=schema$1.Schema.compile({name:"comments",types:[portableTextType]});const editorSchemaType=schema.get("body");const SendIcon=React.forwardRef(function Icon(props,ref){return/* @__PURE__ */jsxRuntime.jsx("svg",{"data-sanity-icon":"send",fill:"none",height:"1em",ref,viewBox:"0 0 25 25",width:"1em",xmlns:"http://www.w3.org/2000/svg",...props,children:/* @__PURE__ */jsxRuntime.jsx("path",{clipRule:"evenodd",d:"M21.1602 12.5L7.16016 19.5V14.8765L13.6656 12.4989L7.16016 9.97149L7.16016 5.5L21.1602 12.5Z",stroke:"currentColor",strokeWidth:1.2,strokeLinejoin:"round"})});});const MentionIcon=React.forwardRef(function Icon(props,ref){return/* @__PURE__ */jsxRuntime.jsxs("svg",{"data-sanity-icon":"mention",fill:"none",height:"1em",ref,viewBox:"0 0 25 25",width:"1em",xmlns:"http://www.w3.org/2000/svg",...props,children:[/* @__PURE__ */jsxRuntime.jsx("path",{d:"M16.6633 18.9383C15.539 19.6562 14.2034 20.0723 12.7705 20.0723C8.77022 20.0723 5.52734 16.8294 5.52734 12.8291C5.52734 8.82881 8.77022 5.58594 12.7705 5.58594C16.7708 5.58594 20.0137 8.82881 20.0137 12.8291C20.0137 13.6623 19.8249 14.7093 19.6141 15.2077C19.5578 15.3408 19.479 15.4845 19.3936 15.6238C19.0955 16.1106 18.5507 16.3721 17.9807 16.4018V16.4018C16.8271 16.462 15.8588 15.5428 15.8588 14.3877V9.27302",stroke:"currentColor",strokeWidth:1.2,strokeLinejoin:"round"}),/* @__PURE__ */jsxRuntime.jsx("circle",{cx:"12.5732",cy:"12.8291",r:"3.08691",stroke:"currentColor",strokeWidth:1.2})]});});const AddCommentIcon=React.forwardRef(function Icon(props,ref){return/* @__PURE__ */jsxRuntime.jsxs("svg",{"data-sanity-icon":"add-comment",fill:"none",height:"1em",ref,viewBox:"0 0 25 25",width:"1em",xmlns:"http://www.w3.org/2000/svg",...props,children:[/* @__PURE__ */jsxRuntime.jsx("path",{d:"M12.3368 5.97917H6.89453C5.78996 5.97917 4.89453 6.8746 4.89453 7.97917V13.4881C4.89453 14.5926 5.78996 15.4881 6.89453 15.4881H8.69808V19.2916L12.5016 15.4881H16.207C17.3115 15.4881 18.207 14.5926 18.207 13.4881V11.7158",stroke:"currentColor",strokeWidth:1.2,strokeLinejoin:"round"}),/* @__PURE__ */jsxRuntime.jsx("path",{d:"M18.2081 2.08333V9.87058M14.3145 5.97695H22.1017",stroke:"currentColor",strokeWidth:1.2,strokeLinejoin:"round"})]});});const CommentIcon=React.forwardRef(function Icon(props,ref){return/* @__PURE__ */jsxRuntime.jsx("svg",{"data-sanity-icon":"comment",width:"1em",height:"1em",ref,viewBox:"0 0 25 25",fill:"none",xmlns:"http://www.w3.org/2000/svg",...props,children:/* @__PURE__ */jsxRuntime.jsx("path",{d:"M7.5 15.5H9.5V19.5L13.5 15.5H17.5C18.6046 15.5 19.5 14.6046 19.5 13.5V7.5C19.5 6.39543 18.6046 5.5 17.5 5.5H7.5C6.39543 5.5 5.5 6.39543 5.5 7.5V13.5C5.5 14.6046 6.39543 15.5 7.5 15.5Z",stroke:"currentColor",strokeLinejoin:"round",strokeWidth:"1.2"})});});const ReactionIcon=React.forwardRef(function Icon(props,ref){return/* @__PURE__ */jsxRuntime.jsxs("svg",{"data-sanity-icon":"add-reaction",fill:"none",height:"1em",ref,viewBox:"0 0 25 25",width:"1em",xmlns:"http://www.w3.org/2000/svg",...props,children:[/* @__PURE__ */jsxRuntime.jsx("path",{d:"M10.1044 10.4011L10.1044 10.9972",stroke:"currentColor",strokeWidth:1.2,strokeLinecap:"square"}),/* @__PURE__ */jsxRuntime.jsx("path",{d:"M14.2393 10.4011L14.2393 10.9972",stroke:"currentColor",strokeWidth:1.2,strokeLinecap:"square"}),/* @__PURE__ */jsxRuntime.jsx("path",{d:"M7.12128 14.1151C7.70803 15.0226 9.66113 16.8377 11.7735 16.8377C13.8859 16.8377 15.6713 15.0226 16.4257 14.1151",stroke:"currentColor",strokeWidth:1.2,strokeLinecap:"square"}),/* @__PURE__ */jsxRuntime.jsx("path",{d:"M16.703 6.43905C15.3486 5.36511 13.6357 4.72374 11.773 4.72374C7.38731 4.72374 3.83203 8.27902 3.83203 12.6647C3.83203 17.0503 7.38731 20.6056 11.773 20.6056C16.0995 20.6056 19.618 17.1455 19.712 12.8415",stroke:"currentColor",strokeWidth:1.2}),/* @__PURE__ */jsxRuntime.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M19.1135 9.03425L19.1135 11.4903L20.3135 11.4903L20.3135 9.03425L22.7693 9.03425L22.7693 7.83425L20.3135 7.83425L20.3135 5.37941L19.1135 5.37941L19.1135 7.83425L16.6584 7.83425L16.6584 9.03425L19.1135 9.03425Z",fill:"currentColor"})]});});function useCommentHasChanged(message){const prevMessage=React.useRef(message);return React.useMemo(()=>!isEqual__default.default(prevMessage.current,message),[message]);}function hasCommentMessageValue(value){if(!value)return false;return value==null?void 0:value.some(block=>{var _a;return sanity.isPortableTextTextBlock(block)&&((_a=(block==null?void 0:block.children)||[])==null?void 0:_a.some(c=>sanity.isPortableTextSpan(c)?c.text:c.userId));});}const CommentInputContext=React__default.default.createContext(null);function CommentInputProvider(props){const{children,expandOnFocus=false,focused,focusOnMount=false,mentionOptions,onMentionMenuOpenChange,value,readOnly}=props;const editor=portableTextEditor.usePortableTextEditor();const[mentionsMenuOpen,setMentionsMenuOpen]=React.useState(false);const[mentionsSearchTerm,setMentionsSearchTerm]=React.useState("");const[selectionAtMentionInsert,setSelectionAtMentionInsert]=React.useState(null);const canSubmit=React.useMemo(()=>hasCommentMessageValue(value),[value]);const hasChanges=useCommentHasChanged(value);const focusEditor=React.useCallback(()=>{if(readOnly)return;portableTextEditor.PortableTextEditor.focus(editor);},[editor,readOnly]);const closeMentions=React.useCallback(()=>{setMentionsMenuOpen(false);setMentionsSearchTerm("");setSelectionAtMentionInsert(null);},[]);const openMentions=React.useCallback(()=>{setMentionsMenuOpen(true);setMentionsSearchTerm("");setMentionsMenuOpen(true);setSelectionAtMentionInsert(portableTextEditor.PortableTextEditor.getSelection(editor));},[editor]);const onBeforeInput=React.useCallback(event=>{const selection=portableTextEditor.PortableTextEditor.getSelection(editor);const cursorOffset=selection?selection.focus.offset:0;const focusChild=portableTextEditor.PortableTextEditor.focusChild(editor);const focusSpan=types.isPortableTextSpan(focusChild)&&focusChild||void 0;const isInsertText=event.inputType==="insertText";const isDeleteText=event.inputType==="deleteContentBackward";const isInsertingAtChar=isInsertText&&event.data==="@";const lastIndexOfAt=(focusSpan==null?void 0:focusSpan.text.substring(0,cursorOffset).lastIndexOf("@"))||0;const isWhitespaceCharBeforeCursorPosition=(focusSpan==null?void 0:focusSpan.text.substring(cursorOffset-1,cursorOffset))===" ";const filterStartsWithSpaceChar=isInsertText&&event.data===" "&&!mentionsSearchTerm;if(isInsertingAtChar&&(cursorOffset<1||isWhitespaceCharBeforeCursorPosition)){openMentions();return;}if(filterStartsWithSpaceChar||isDeleteText&&((focusSpan==null?void 0:focusSpan.text.length)===1||lastIndexOfAt===((focusSpan==null?void 0:focusSpan.text.length)||0)-1)){closeMentions();return;}if(types.isPortableTextSpan(focusChild)){let term=focusChild.text.substring(lastIndexOfAt+1,cursorOffset);if(isInsertText){term+=event.data;}if(isDeleteText){term=term.substring(0,term.length-1);}setMentionsSearchTerm(term);}},[closeMentions,editor,mentionsSearchTerm,openMentions]);const insertAtChar=React.useCallback(()=>{setMentionsMenuOpen(true);portableTextEditor.PortableTextEditor.focus(editor);portableTextEditor.PortableTextEditor.insertChild(editor,editor.schemaTypes.span,{text:"@"});setSelectionAtMentionInsert(portableTextEditor.PortableTextEditor.getSelection(editor));},[editor]);sanity.useDidUpdate(mentionsMenuOpen,()=>onMentionMenuOpenChange==null?void 0:onMentionMenuOpenChange(mentionsMenuOpen));const insertMention=React.useCallback(userId=>{var _a;const mentionSchemaType=editor.schemaTypes.inlineObjects.find(t=>t.name==="mention");const[span,spanPath]=selectionAtMentionInsert&&portableTextEditor.PortableTextEditor.findByPath(editor,selectionAtMentionInsert.focus.path)||[];if(span&&types.isPortableTextSpan(span)&&spanPath&&mentionSchemaType){portableTextEditor.PortableTextEditor.focus(editor);const offset=(_a=portableTextEditor.PortableTextEditor.getSelection(editor))==null?void 0:_a.focus.offset;if(typeof offset!=="undefined"){portableTextEditor.PortableTextEditor.delete(editor,{anchor:{path:spanPath,offset:span.text.lastIndexOf("@")},focus:{path:spanPath,offset}},{mode:"selected"});portableTextEditor.PortableTextEditor.insertChild(editor,mentionSchemaType,{userId});portableTextEditor.PortableTextEditor.insertChild(editor,editor.schemaTypes.span,{text:" "});}}},[editor,selectionAtMentionInsert]);const ctxValue=React.useMemo(()=>({canSubmit,closeMentions,editor,expandOnFocus,focused,focusEditor,focusOnMount,hasChanges,insertAtChar,insertMention,mentionOptions,mentionsMenuOpen,mentionsSearchTerm,onBeforeInput,openMentions,readOnly:Boolean(readOnly),value}),[canSubmit,closeMentions,editor,expandOnFocus,focused,focusEditor,focusOnMount,hasChanges,insertAtChar,insertMention,mentionOptions,mentionsMenuOpen,mentionsSearchTerm,onBeforeInput,openMentions,readOnly,value]);return/* @__PURE__ */jsxRuntime.jsx(CommentInputContext.Provider,{value:ctxValue,children});}function useCommentInput(){const ctx=React.useContext(CommentInputContext);if(!ctx){throw new Error("useCommentInputContext must be used within a CommentInputProvider");}return ctx;}var __freeze$t=Object.freeze;var __defProp$t=Object.defineProperty;var __template$t=(cooked,raw)=>__freeze$t(__defProp$t(cooked,"raw",{value:__freeze$t(raw||cooked.slice())}));var _a$t;const InnerFlex=styled__default.default(ui.Flex)(_a$t||(_a$t=__template$t([""])));const SKELETON_INLINE_STYLE$1={width:"50%"};function MentionsMenuItem(props){const{user,onSelect}=props;const[loadedUser]=sanity.useUser(user.id);const{t}=sanity.useTranslation(commentsLocaleNamespace);const avatar=/* @__PURE__ */jsxRuntime.jsx(CommentsAvatar,{user:loadedUser,status:user.canBeMentioned?void 0:"inactive"});const text=loadedUser?/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,textOverflow:"ellipsis",title:loadedUser.displayName,children:loadedUser.displayName}):/* @__PURE__ */jsxRuntime.jsx(ui.TextSkeleton,{size:1,style:SKELETON_INLINE_STYLE$1});const handleSelect=React.useCallback(()=>{onSelect(user.id);},[onSelect,user.id]);return/* @__PURE__ */jsxRuntime.jsx(ui.Card,{as:"button",disabled:!user.canBeMentioned,onClick:handleSelect,padding:2,radius:2,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",gap:3,children:[/* @__PURE__ */jsxRuntime.jsxs(InnerFlex,{align:"center",gap:2,flex:1,children:[avatar,/* @__PURE__ */jsxRuntime.jsx(ui.Box,{children:text})]}),!user.canBeMentioned&&/* @__PURE__ */jsxRuntime.jsx(ui.Badge,{fontSize:1,mode:"outline",children:t("comments.mentions-unauthorized")})]})});}const EMPTY_ARRAY$8=[];const Root$8=styled__default.default(ui.Stack)({maxWidth:"220px"// todo: improve
21
21
  });const ITEM_HEIGHT=41;const LIST_PADDING=4;const MAX_ITEMS=7;const FlexWrap=styled__default.default(ui.Flex)({maxHeight:ITEM_HEIGHT*MAX_ITEMS+LIST_PADDING*2+ITEM_HEIGHT/2});const MentionsMenu=React__default.default.forwardRef(function MentionsMenu2(props,ref){const{t}=sanity.useTranslation(commentsLocaleNamespace);const{loading,onSelect,options=[],inputElement}=props;const[searchTerm,setSearchTerm]=React.useState("");const commandListRef=React.useRef(null);React.useImperativeHandle(ref,()=>{return{setSearchTerm(term){setSearchTerm(term);}};},[]);const renderItem=React.useCallback(itemProps=>{return/* @__PURE__ */jsxRuntime.jsx(MentionsMenuItem,{user:itemProps,onSelect});},[onSelect]);const getItemDisabled=React.useCallback(index=>{var _a;return!((_a=options==null?void 0:options[index])==null?void 0:_a.canBeMentioned);},[options]);const filteredOptions=React.useMemo(()=>{var _a;if(!searchTerm)return options||EMPTY_ARRAY$8;const deburredSearchTerm=deburr__default.default(searchTerm).toLocaleLowerCase();const deburredOptions=options==null?void 0:options.map(option=>({...option,displayName:deburr__default.default(option.displayName||"").toLocaleLowerCase()}));const filtered=(_a=deburredOptions==null?void 0:deburredOptions.filter(option=>{var _a2;return(_a2=option==null?void 0:option.displayName)==null?void 0:_a2.includes(deburredSearchTerm);}))==null?void 0:_a.sort((a,b)=>{var _a2,_b;const matchA=(_a2=a.displayName)==null?void 0:_a2.startsWith(deburredSearchTerm);const matchB=(_b=b.displayName)==null?void 0:_b.startsWith(deburredSearchTerm);if(matchA&&!matchB)return-1;if(!matchA&&matchB)return 1;return 0;});return filtered||EMPTY_ARRAY$8;},[options,searchTerm]);if(loading){return/* @__PURE__ */jsxRuntime.jsx(Root$8,{children:/* @__PURE__ */jsxRuntime.jsx(sanity.LoadingBlock,{showText:true})});}const _inputElement=inputElement?inputElement:void 0;return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{direction:"column",height:"fill","data-testid":"comments-mentions-menu",children:[filteredOptions.length===0&&/* @__PURE__ */jsxRuntime.jsx(ui.Box,{padding:5,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{align:"center",size:1,muted:true,children:t("comments.mentions-not-found")})}),filteredOptions.length>0&&/* @__PURE__ */jsxRuntime.jsx(FlexWrap,{direction:"column",flex:1,overflow:"hidden",children:/* @__PURE__ */jsxRuntime.jsx(sanity.CommandList,{activeItemDataAttr:"data-hovered",ariaLabel:t("comments.mentions-user-list-aria-label"),fixedHeight:true,getItemDisabled,inputElement:_inputElement,itemHeight:41,items:filteredOptions,padding:1,ref:commandListRef,renderItem})})]});});const renderBlock=blockProps=>{const{children}=blockProps;return/* @__PURE__ */jsxRuntime.jsx(NormalBlock,{children});};const renderChild=childProps=>{const{children,value,selected}=childProps;const isMention=value._type==="mention"&&value.userId;if(isMention){return/* @__PURE__ */jsxRuntime.jsx(MentionInlineBlock,{selected,userId:value==null?void 0:value.userId});}return children;};const EVENT_LISTENER_OPTIONS={passive:true};function useCursorElement(opts){const{disabled,rootElement}=opts;const[cursorRect,setCursorRect]=React.useState(null);const cursorElement=React.useMemo(()=>{if(!cursorRect){return null;}return{getBoundingClientRect:()=>{return cursorRect;}};},[cursorRect]);const handleSelectionChange=React.useCallback(()=>{if(disabled){setCursorRect(null);return;}const sel=window.getSelection();if(!sel||!sel.isCollapsed||sel.rangeCount===0)return;const range=sel.getRangeAt(0);const isWithinRoot=rootElement==null?void 0:rootElement.contains(range.commonAncestorContainer);if(!isWithinRoot){setCursorRect(null);return;}const rect=range==null?void 0:range.getBoundingClientRect();if(rect){setCursorRect(rect);}},[disabled,rootElement]);React.useEffect(()=>{document.addEventListener("selectionchange",handleSelectionChange,EVENT_LISTENER_OPTIONS);return()=>{document.removeEventListener("selectionchange",handleSelectionChange);};},[handleSelectionChange]);return cursorElement;}var __freeze$s=Object.freeze;var __defProp$s=Object.defineProperty;var __template$s=(cooked,raw)=>__freeze$s(__defProp$s(cooked,"raw",{value:__freeze$s(raw||cooked.slice())}));var _a$s,_b$e;const POPOVER_FALLBACK_PLACEMENTS$2=["bottom","top"];const INLINE_STYLE={outline:"none"};const EMPTY_ARRAY$7=[];const PlaceholderWrapper=styled__default.default.span(()=>{return styled.css(_a$s||(_a$s=__template$s(["\n overflow: hidden;\n text-overflow: ellipsis;\n text-wrap: nowrap;\n display: block;\n "])));});const StyledPopover$1=styled__default.default(TooltipDelayGroupProvider.Popover)(_ref51=>{let{theme}=_ref51;const{space,radius}=theme.sanity;return styled.css(_b$e||(_b$e=__template$s(["\n &[data-placement='bottom'] {\n transform: translateY(","px);\n }\n\n &[data-placement='top'] {\n transform: translateY(-","px);\n }\n\n [data-ui='Popover__wrapper'] {\n border-radius: ","px;\n display: flex;\n flex-direction: column;\n overflow: clip;\n overflow: hidden;\n position: relative;\n width: 300px; // todo: improve\n }\n "])),space[1],space[1],radius[3]);});function Editable(props){const{focusLock,placeholder="Create a new comment",onFocus,onBlur,onKeyDown,onSubmit}=props;const[popoverElement,setPopoverElement]=React.useState(null);const rootElementRef=React.useRef(null);const editableRef=React.useRef(null);const mentionsMenuRef=React.useRef(null);const selection=portableTextEditor.usePortableTextEditorSelection();const{canSubmit,closeMentions,insertMention,mentionOptions,mentionsMenuOpen,mentionsSearchTerm,onBeforeInput,value}=useCommentInput();const cursorElement=useCursorElement({disabled:!mentionsMenuOpen,rootElement:rootElementRef.current});const renderPlaceholder=React.useCallback(()=>/* @__PURE__ */jsxRuntime.jsx(PlaceholderWrapper,{children:placeholder}),[placeholder]);const handleClickOutside=React.useCallback(()=>{if(mentionsMenuOpen){closeMentions();}},[closeMentions,mentionsMenuOpen]);ui.useClickOutside(handleClickOutside,[popoverElement]);const handleKeyDown=React.useCallback(event=>{switch(event.key){case"Enter":if(event.shiftKey){break;}event.preventDefault();event.stopPropagation();if(mentionsMenuOpen){closeMentions();break;}if(onSubmit&&canSubmit){onSubmit();}break;case"Escape":case"ArrowLeft":case"ArrowRight":if(mentionsMenuOpen){event.preventDefault();event.stopPropagation();closeMentions();}break;}if(onKeyDown)onKeyDown(event);},[canSubmit,closeMentions,mentionsMenuOpen,onKeyDown,onSubmit]);const initialSelectionAtEndOfContent=React.useMemo(()=>{if(selection){return void 0;}const lastBlock=(value||EMPTY_ARRAY$7).slice(-1)[0];const lastChild=types.isPortableTextTextBlock(lastBlock)?lastBlock.children.slice(-1)[0]:void 0;if(!lastChild){return void 0;}const point={path:[{_key:lastBlock._key},"children",{_key:lastChild._key}],offset:types.isPortableTextSpan(lastChild)?lastChild.text.length:0};return{focus:point,anchor:point};},[value,selection]);React.useEffect(()=>{var _a2;(_a2=mentionsMenuRef.current)==null?void 0:_a2.setSearchTerm(mentionsSearchTerm);},[mentionsSearchTerm]);React.useEffect(()=>{if(mentionsMenuOpen&&selection&&!isEqual__default.default(selection.anchor,selection.focus)){closeMentions();}},[mentionsMenuOpen,closeMentions,selection]);const popoverContent=/* @__PURE__ */jsxRuntime.jsx(MentionsMenu,{inputElement:editableRef.current,loading:mentionOptions.loading,onSelect:insertMention,options:mentionOptions.data||EMPTY_ARRAY$7,ref:mentionsMenuRef});return/* @__PURE__ */jsxRuntime.jsxs("div",{ref:rootElementRef,children:[/* @__PURE__ */jsxRuntime.jsx(StyledPopover$1,{arrow:false,constrainSize:true,content:popoverContent,disabled:!mentionsMenuOpen,fallbackPlacements:POPOVER_FALLBACK_PLACEMENTS$2,open:mentionsMenuOpen,placement:"bottom",ref:setPopoverElement,referenceElement:cursorElement}),/* @__PURE__ */jsxRuntime.jsx(portableTextEditor.PortableTextEditable,{"data-testid":"comment-input-editable","data-ui":"EditableElement",onBeforeInput,onBlur,onFocus,onKeyDown:handleKeyDown,ref:editableRef,renderBlock,renderChild,renderPlaceholder,selection:initialSelectionAtEndOfContent,style:INLINE_STYLE,tabIndex:focusLock?0:void 0})]});}var __freeze$r=Object.freeze;var __defProp$r=Object.defineProperty;var __template$r=(cooked,raw)=>__freeze$r(__defProp$r(cooked,"raw",{value:__freeze$r(raw||cooked.slice())}));var _a$r,_b$d;const EditableWrap=styled__default.default(ui.Box)(_a$r||(_a$r=__template$r(["\n max-height: 20vh;\n overflow-y: auto;\n"])));const ButtonDivider=styled__default.default(ui.MenuDivider)({height:20,width:1});const RootCard=styled__default.default(ui.Card)(_ref52=>{let{theme}=_ref52;const radii=theme.sanity.radius[2];return styled.css(_b$d||(_b$d=__template$r(["\n border-radius: ","px;\n\n &:not([data-expand-on-focus='false'], :focus-within) {\n background: transparent;\n box-shadow: unset;\n }\n\n &[data-focused='true']:focus-within {\n "," {\n min-height: 1em;\n }\n\n box-shadow: inset 0 0 0 1px var(--card-focus-ring-color);\n }\n\n &:focus-within {\n "," {\n min-height: 1em;\n }\n }\n\n &[data-expand-on-focus='false'] {\n "," {\n min-height: 1em;\n }\n }\n\n &[data-expand-on-focus='true'] {\n [data-ui='CommentInputActions']:not([hidden]) {\n display: none;\n }\n\n &:focus-within {\n [data-ui='CommentInputActions'] {\n display: flex;\n }\n }\n }\n "])),radii,EditableWrap,EditableWrap,EditableWrap);});function CommentInputInner(props){const{currentUser,focusLock,onBlur,onFocus,onKeyDown,onSubmit,placeholder,withAvatar}=props;const[user]=sanity.useUser(currentUser.id);const{canSubmit,expandOnFocus,focused,hasChanges,insertAtChar,openMentions,readOnly}=useCommentInput();const{t}=sanity.useTranslation(commentsLocaleNamespace);const avatar=withAvatar?/* @__PURE__ */jsxRuntime.jsx(CommentsAvatar,{user}):null;const handleMentionButtonClicked=React.useCallback(e=>{e.stopPropagation();insertAtChar();openMentions();},[insertAtChar,openMentions]);return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"flex-start",gap:2,children:[avatar,/* @__PURE__ */jsxRuntime.jsx(RootCard,{"data-expand-on-focus":expandOnFocus&&!canSubmit?"true":"false","data-focused":focused?"true":"false",flex:1,shadow:1,sizing:"border",tone:readOnly?"transparent":"default",children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{children:[/* @__PURE__ */jsxRuntime.jsx(EditableWrap,{paddingX:1,paddingY:2,sizing:"border",children:/* @__PURE__ */jsxRuntime.jsx(Editable,{focusLock,onBlur,onFocus,onKeyDown,onSubmit,placeholder})}),/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{align:"center","data-ui":"CommentInputActions",gap:1,justify:"flex-end",padding:1,children:/* @__PURE__ */jsxRuntime.jsxs(TooltipDelayGroupProvider.TooltipDelayGroupProvider,{children:[/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{"aria-label":t("comments.tooltip-mention-user-aria-label"),"data-testid":"comment-mention-button",disabled:readOnly,icon:MentionIcon,mode:"bleed",onClick:handleMentionButtonClicked,tooltipProps:{content:t("comments.tooltip-mention-user")}}),/* @__PURE__ */jsxRuntime.jsx(ButtonDivider,{}),/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{"aria-label":t("comments.tooltip-send-comment-aria-label"),disabled:!canSubmit||!hasChanges||readOnly,icon:SendIcon,mode:hasChanges&&canSubmit?"default":"bleed",onClick:onSubmit,tone:hasChanges&&canSubmit?"primary":"default",tooltipProps:{content:t("comments.tooltip-send-comment")}})]})})]})})]});}const Z_OFFSET=9999999;function CommentInputDiscardDialog(props){const{t}=sanity.useTranslation(commentsLocaleNamespace);const{onClose,onConfirm}=props;const handleCancelClick=React.useCallback(e=>{e.stopPropagation();onClose();},[onClose]);const handleConfirmClick=React.useCallback(e=>{e.stopPropagation();onConfirm();},[onConfirm]);return/* @__PURE__ */jsxRuntime.jsx(ui.ThemeColorProvider,{tone:"default",children:/* @__PURE__ */jsxRuntime.jsx(ui.DialogProvider,{zOffset:Z_OFFSET,children:/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Dialog,{header:t("comments.discard-header"),id:"discard-comment-dialog",onClose,width:0,onClickOutside:onClose,footer:{cancelButton:{onClick:handleCancelClick},confirmButton:{onClick:handleConfirmClick,text:t("comments.discard-button-confirm"),tone:"critical"}},children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:t("comments.discard-text")})})})});}const EMPTY_ARRAY$6=[];const SCROLL_INTO_VIEW_OPTIONS$2={behavior:"smooth",block:"center",inline:"center"};const CommentInput=React.forwardRef(function CommentInput2(props,ref){const{currentUser,expandOnFocus,focusLock=false,focusOnMount,mentionOptions,onBlur,onChange,onDiscardCancel,onDiscardConfirm,onFocus,onKeyDown,onMentionMenuOpenChange,onSubmit,placeholder,readOnly,value=EMPTY_ARRAY$6,withAvatar=true}=props;const[focused,setFocused]=React.useState(false);const editorRef=React.useRef(null);const editorContainerRef=React.useRef(null);const[showDiscardDialog,setShowDiscardDialog]=React.useState(false);const preDivRef=React.useRef(null);const postDivRef=React.useRef(null);const innerRef=React.useRef(null);const[editorInstanceKey,setEditorInstanceKey]=React.useState(portableTextEditor.keyGenerator());const requestFocus=React.useCallback(()=>{requestAnimationFrame(()=>{if(!editorRef.current)return;portableTextEditor.PortableTextEditor.focus(editorRef.current);});},[]);const resetEditorInstance=React.useCallback(()=>{setEditorInstanceKey(portableTextEditor.keyGenerator());},[]);const handleChange=React.useCallback(change=>{if(change.type==="ready"){if(focusOnMount){requestFocus();}}if(change.type==="focus"){setFocused(true);}if(change.type==="blur"){setFocused(false);}if(change.type==="patch"&&editorRef.current){const editorStateValue=portableTextEditor.PortableTextEditor.getValue(editorRef.current);onChange(editorStateValue||EMPTY_ARRAY$6);}},[focusOnMount,onChange,requestFocus]);const scrollToEditor=React.useCallback(()=>{var _a;(_a=editorContainerRef.current)==null?void 0:_a.scrollIntoView(SCROLL_INTO_VIEW_OPTIONS$2);},[]);const handleSubmit=React.useCallback(()=>{onSubmit();resetEditorInstance();requestFocus();scrollToEditor();},[onSubmit,requestFocus,resetEditorInstance,scrollToEditor]);const handleDiscardConfirm=React.useCallback(()=>{onDiscardConfirm();resetEditorInstance();},[onDiscardConfirm,resetEditorInstance]);const discardDialogController=React.useMemo(()=>{return{open:()=>{setShowDiscardDialog(true);},close:()=>{setShowDiscardDialog(false);requestFocus();}};},[requestFocus]);React.useImperativeHandle(ref,()=>{return{focus:requestFocus,blur(){if(editorRef.current){portableTextEditor.PortableTextEditor.blur(editorRef.current);}},scrollTo:scrollToEditor,reset:resetEditorInstance,discardDialogController};},[discardDialogController,requestFocus,resetEditorInstance,scrollToEditor]);const handleFocus=React.useCallback(event=>{if(!focusLock)return;const target=event.target;const innerEl=innerRef.current;if(innerEl&&target===preDivRef.current){ui.focusLastDescendant(innerEl);return;}if(innerEl&&target===postDivRef.current){ui.focusFirstDescendant(innerEl);}},[focusLock]);return/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[showDiscardDialog&&/* @__PURE__ */jsxRuntime.jsx(CommentInputDiscardDialog,{onClose:onDiscardCancel,onConfirm:handleDiscardConfirm}),/* @__PURE__ */jsxRuntime.jsx(ui.Stack,{ref:editorContainerRef,"data-testid":"comment-input",onFocus:handleFocus,children:/* @__PURE__ */jsxRuntime.jsx(portableTextEditor.PortableTextEditor,{onChange:handleChange,readOnly,ref:editorRef,schemaType:editorSchemaType,value:value||EMPTY_ARRAY$6,children:/* @__PURE__ */jsxRuntime.jsxs(CommentInputProvider,{expandOnFocus,focused,focusOnMount,mentionOptions,onMentionMenuOpenChange,readOnly,value,children:[focusLock&&/* @__PURE__ */jsxRuntime.jsx("div",{ref:preDivRef,tabIndex:0}),/* @__PURE__ */jsxRuntime.jsx(ui.Stack,{ref:innerRef,children:/* @__PURE__ */jsxRuntime.jsx(CommentInputInner,{currentUser,focusLock,onBlur,onFocus,onKeyDown,onSubmit:handleSubmit,placeholder,withAvatar})}),focusLock&&/* @__PURE__ */jsxRuntime.jsx("div",{ref:postDivRef,tabIndex:0})]})},editorInstanceKey)})]});});const FLEX_GAP=3;const COMMENT_REACTION_OPTIONS=[{shortName:":+1:",title:"Thumbs up"},{shortName:":-1:",title:"Thumbs down"},{shortName:":heart:",title:"Heart"},{shortName:":rocket:",title:"Rocket"},{shortName:":heavy_plus_sign:",title:"Heavy plus sign"},{shortName:":eyes:",title:"Eyes"}];const COMMENT_REACTION_EMOJIS={":-1:":"\u{1F44E}",":+1:":"\u{1F44D}",":eyes:":"\u{1F440}",":heart:":"\u2764\uFE0F",":heavy_plus_sign:":"\u2795",":rocket:":"\u{1F680}"};var __freeze$q=Object.freeze;var __defProp$q=Object.defineProperty;var __template$q=(cooked,raw)=>__freeze$q(__defProp$q(cooked,"raw",{value:__freeze$q(raw||cooked.slice())}));var _a$q;const EmojiText=styled__default.default(ui.Text)(_a$q||(_a$q=__template$q(["\n font-family: 'Twemoji Mozilla', 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',\n 'Noto Color Emoji', 'EmojiOne Color', 'Android Emoji', sans-serif;\n"])));const GRID_COLUMNS=6;function CommentReactionsMenu(props){const{options,onSelect}=props;const{t}=sanity.useTranslation(commentsLocaleNamespace);const[focusableElements,setFocusableElements]=React.useState([]);const[rootElement,setRootElement]=React.useState(null);const[focusedIndex,setFocusedIndex]=React.useState(0);const handleRootKeyDown=React.useCallback(event=>{const focusableLen=focusableElements.length;if(event.key==="ArrowRight"){setFocusedIndex(prev=>(prev+1)%focusableLen);}if(event.key==="ArrowLeft"){setFocusedIndex(prev=>(prev-1+focusableLen)%focusableLen);}},[focusableElements.length]);const handleOptionClick=React.useCallback(event=>{const index=focusableElements.indexOf(event.currentTarget);setFocusedIndex(index);onSelect(options[index]);},[focusableElements,onSelect,options]);React.useEffect(()=>{if(rootElement){const buttons=rootElement.querySelectorAll("button");setFocusableElements(Array.from(buttons));}},[rootElement]);React.useEffect(()=>{if(focusableElements.length>0){focusableElements[focusedIndex].focus();}},[focusableElements,focusedIndex]);return/* @__PURE__ */jsxRuntime.jsx(ui.Grid,{columns:GRID_COLUMNS,gap:1,onKeyDown:handleRootKeyDown,ref:setRootElement,role:"menu",children:options.map(o=>{const emoji=COMMENT_REACTION_EMOJIS[o.shortName];return/* @__PURE__ */jsxRuntime.jsx(ui.Button,{"aria-label":t("comments.reactions-menu-button-aria-label",{reaction:o.title||o.shortName}),mode:"bleed",onClick:handleOptionClick,padding:2,role:"menuitem",tabIndex:-1,children:/* @__PURE__ */jsxRuntime.jsx(EmojiText,{align:"center",size:2,children:emoji})},o.shortName);})});}const POPOVER_FALLBACK_PLACEMENTS$1=["top","bottom"];function CommentReactionsMenuButton(props){const{onMenuClose,onMenuOpen,onSelect,options,readOnly,renderMenuButton}=props;const[buttonElement,setButtonElement]=React.useState(null);const[popoverElement,setPopoverElement]=React.useState(null);const[open,setOpen]=React.useState(false);const{t}=sanity.useTranslation(commentsLocaleNamespace);const handleClick=React.useCallback(()=>{const next=!open;setOpen(next);if(next){onMenuOpen==null?void 0:onMenuOpen();}else{onMenuClose==null?void 0:onMenuClose();}},[onMenuClose,onMenuOpen,open]);const handleClose=React.useCallback(()=>{if(!open)return;setOpen(false);onMenuClose==null?void 0:onMenuClose();buttonElement==null?void 0:buttonElement.focus();},[buttonElement,onMenuClose,open]);const handleClickOutside=React.useCallback(handleClose,[handleClose]);const handleKeyDown=React.useCallback(event=>{const{key,shiftKey}=event;if(shiftKey&&key==="Tab"||key==="Escape"||key==="Tab"){handleClose();}},[handleClose]);ui.useClickOutside(handleClickOutside,[popoverElement,buttonElement]);const handleSelect=React.useCallback(option=>{onSelect(option);handleClose();},[handleClose,onSelect]);const button=React.useMemo(()=>{const btn=renderMenuButton({open,t});return React.cloneElement(btn,{"aria-expanded":open,"aria-haspopup":"true",disabled:readOnly,id:"reactions-menu-button",onClick:handleClick,ref:setButtonElement,t});},[handleClick,open,readOnly,renderMenuButton,t]);const popoverContent=/* @__PURE__ */jsxRuntime.jsx(ui.Card,{"aria-labelledby":"reactions-menu-button",onKeyDown:handleKeyDown,padding:1,radius:3,tone:"default",children:/* @__PURE__ */jsxRuntime.jsx(CommentReactionsMenu,{onSelect:handleSelect,options})});return/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Popover,{constrainSize:true,content:popoverContent,fallbackPlacements:POPOVER_FALLBACK_PLACEMENTS$1,open,placement:"bottom",portal:true,ref:setPopoverElement,tone:"default",children:button});}var __freeze$p=Object.freeze;var __defProp$p=Object.defineProperty;var __template$p=(cooked,raw)=>__freeze$p(__defProp$p(cooked,"raw",{value:__freeze$p(raw||cooked.slice())}));var _a$p,_b$c,_c$6;const TEXT_SIZE=1;const ContentStack$1=styled__default.default(ui.Stack)(_a$p||(_a$p=__template$p(["\n max-width: 180px;\n"])));const InlineText=styled__default.default(ui.Text).attrs({size:TEXT_SIZE})(_b$c||(_b$c=__template$p(["\n display: inline-block !important;\n"])));const TextBox=styled__default.default(ui.Box)(_c$6||(_c$6=__template$p(["\n line-height: 1;\n text-align: center;\n"])));function UserDisplayName(props){var _a2;const{currentUserId,isFirst,userId,separator}=props;const[user]=sanity.useUser(userId);const{t}=sanity.useTranslation(commentsLocaleNamespace);const isCurrentUser=currentUserId===userId;const you=isFirst?t("comments.reaction-user-you"):t("comments.reaction-user-you-lowercase");const content=isCurrentUser?you:(_a2=user==null?void 0:user.displayName)!=null?_a2:t("comments.reaction-unknown-user");const text=separator?"".concat(content,", "):content;return/* @__PURE__ */jsxRuntime.jsxs(InlineText,{weight:"medium",children:[" ",text," "]});}function CommentReactionsUsersTooltip(props){const{children,...restProps}=props;return/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Tooltip,{content:/* @__PURE__ */jsxRuntime.jsx(CommentReactionsUsersTooltipContent,{...restProps}),placement:"bottom",portal:true,children:/* @__PURE__ */jsxRuntime.jsx("div",{children})});}function CommentReactionsUsersTooltipContent(props){const{currentUser,reactionName,userIds}=props;const{t}=sanity.useTranslation(commentsLocaleNamespace);const content=React.useMemo(()=>{const len=userIds.length;if(len===0||!currentUser)return null;return userIds.map((id,index)=>{const separator=index<userIds.length-1&&len>2&&index!==userIds.length-2;const showAnd=index===len-1&&len>1;return/* @__PURE__ */jsxRuntime.jsxs(React.Fragment,{children:[showAnd&&/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[/* @__PURE__ */jsxRuntime.jsxs(InlineText,{children:[t("comments.reaction-separator")," "]})," "]}),/* @__PURE__ */jsxRuntime.jsx(UserDisplayName,{currentUserId:currentUser.id,isFirst:index===0,separator,userId:id})," "]},id);});},[currentUser,userIds,t]);return/* @__PURE__ */jsxRuntime.jsxs(ContentStack$1,{padding:1,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{justify:"center",paddingBottom:2,paddingTop:1,children:/* @__PURE__ */jsxRuntime.jsx(EmojiText,{size:4,children:COMMENT_REACTION_EMOJIS[reactionName]})}),/* @__PURE__ */jsxRuntime.jsx(TextBox,{children:/* @__PURE__ */jsxRuntime.jsx(sanity.Translate,{t,i18nKey:"comments.user-reacted-with",values:{reactionName},components:{Content:()=>/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children:content}),Text:_ref53=>{let{children}=_ref53;return/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[/* @__PURE__ */jsxRuntime.jsx(InlineText,{muted:true,children})," ",/* @__PURE__ */jsxRuntime.jsx("wbr",{})," "]});},ReactionName:_ref54=>{let{children}=_ref54;return/* @__PURE__ */jsxRuntime.jsx(InlineText,{muted:true,children});}}})})]});}var __freeze$o=Object.freeze;var __defProp$o=Object.defineProperty;var __template$o=(cooked,raw)=>__freeze$o(__defProp$o(cooked,"raw",{value:__freeze$o(raw||cooked.slice())}));var _a$o;const TransparentCard=styled__default.default(ui.Card)(_a$o||(_a$o=__template$o(["\n background: none;\n"])));function groupReactionsByName(reactions){const grouped=reactions.reduce((acc,reaction)=>{const{shortName}=reaction;if(!acc[shortName]){acc[shortName]=[];}acc[shortName].push(reaction);return acc;},{});const sorted=Object.entries(grouped).sort((_ref55,_ref56)=>{let[nameA]=_ref55;let[nameB]=_ref56;const indexA=reactions.findIndex(r=>r.shortName===nameA);const indexB=reactions.findIndex(r=>r.shortName===nameB);return indexA-indexB;});return sorted;}const renderMenuButton$1=_ref57=>{let{open,t}=_ref57;return/* @__PURE__ */jsxRuntime.jsx(ui.Button,{fontSize:1,mode:"ghost",padding:0,radius:"full",selected:open,children:/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{paddingX:3,paddingY:2,children:/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Tooltip,{animate:true,content:t("comments.reaction-bar-tooltip"),disabled:open,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:/* @__PURE__ */jsxRuntime.jsx(ReactionIcon,{})})})})});};const CommentReactionsBar=React__default.default.memo(function CommentReactionsBar2(props){const{currentUser,onSelect,reactions,readOnly}=props;const handleSelect=React.useCallback(name=>{const option=COMMENT_REACTION_OPTIONS.find(o=>o.shortName===name);if(option){onSelect(option);}},[onSelect]);const currentUserReactionNames=React.useMemo(()=>{return reactions.filter(r=>r.userId===(currentUser==null?void 0:currentUser.id)).map(r=>r.shortName);},[currentUser==null?void 0:currentUser.id,reactions]);const groupedReactions=React.useMemo(()=>{const grouped=groupReactionsByName(reactions);return grouped.filter(_ref58=>{let[name]=_ref58;return COMMENT_REACTION_EMOJIS[name];});},[reactions]);const sortOrder=React.useRef(Object.keys(Object.fromEntries(groupedReactions)));const sortedReactions=React.useMemo(()=>{const sorted=groupedReactions.sort((_ref59,_ref60)=>{let[nameA]=_ref59;let[nameB]=_ref60;const indexA=sortOrder.current.indexOf(nameA);const indexB=sortOrder.current.indexOf(nameB);if(indexA===-1){return 1;}if(indexB===-1){return-1;}return indexA-indexB;});sortOrder.current=sorted.map(_ref61=>{let[name]=_ref61;return name;});return sorted;},[groupedReactions]);return/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{align:"center",gap:1,wrap:"wrap",children:/* @__PURE__ */jsxRuntime.jsxs(TooltipDelayGroupProvider.TooltipDelayGroupProvider,{children:[sortedReactions.map(_ref62=>{let[name,reactionsList]=_ref62;const hasReacted=currentUserReactionNames.includes(name);const userIds=reactionsList.map(r=>r.userId);const emoji=COMMENT_REACTION_EMOJIS[name];return/* @__PURE__ */jsxRuntime.jsx(CommentReactionsUsersTooltip,{currentUser,reactionName:name,userIds,children:/* @__PURE__ */jsxRuntime.jsx(TransparentCard,{tone:"default",children:/* @__PURE__ */jsxRuntime.jsx(ui.Button,{disabled:readOnly,mode:"ghost",onClick:()=>handleSelect(name),padding:2,radius:"full",selected:hasReacted,tone:hasReacted?"primary":"default",children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",gap:1,children:[/* @__PURE__ */jsxRuntime.jsx(EmojiText,{size:1,children:emoji}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:0,weight:hasReacted?"semibold":"medium",children:reactionsList==null?void 0:reactionsList.length})]})})})},name);}),/* @__PURE__ */jsxRuntime.jsx(TransparentCard,{tone:"default",children:/* @__PURE__ */jsxRuntime.jsx(CommentReactionsMenuButton,{onSelect:o=>handleSelect(o.shortName),options:COMMENT_REACTION_OPTIONS,readOnly,renderMenuButton:renderMenuButton$1})})]})});});var __freeze$n=Object.freeze;var __defProp$n=Object.defineProperty;var __template$n=(cooked,raw)=>__freeze$n(__defProp$n(cooked,"raw",{value:__freeze$n(raw||cooked.slice())}));var _a$n;const renderMenuButton=_ref63=>{let{open,t}=_ref63;return/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{"aria-label":t("comments.list-item-context-menu-add-reaction-aria-label"),icon:ReactionIcon,mode:"bleed",selected:open,tooltipProps:{content:t("comments.list-item-context-menu-add-reaction")}});};const POPOVER_PROPS={placement:"bottom-end"};const FloatingCard=styled__default.default(ui.Card)(_a$n||(_a$n=__template$n(["\n &:empty {\n display: none;\n }\n"])));function CommentsListItemContextMenu(props){const{canDelete,canEdit,isParent,onCopyLink,onDeleteStart,onEditStart,onMenuClose,onMenuOpen,onReactionSelect,onStatusChange,readOnly,status}=props;const showMenuButton=Boolean(onCopyLink||onDeleteStart||onEditStart);const{t}=sanity.useTranslation(commentsLocaleNamespace);return/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.TooltipDelayGroupProvider,{children:/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{children:/* @__PURE__ */jsxRuntime.jsxs(FloatingCard,{display:"flex",shadow:2,padding:1,radius:2,sizing:"border",children:[onReactionSelect&&/* @__PURE__ */jsxRuntime.jsx(CommentReactionsMenuButton,{onMenuClose,onMenuOpen,onSelect:onReactionSelect,options:COMMENT_REACTION_OPTIONS,readOnly,renderMenuButton}),isParent&&/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{"aria-label":status==="open"?t("comments.list-item-resolved-tooltip-aria-label"):t("comments.list-item-re-open-resolved-aria-label"),disabled:readOnly,icon:status==="open"?icons.CheckmarkCircleIcon:icons.UndoIcon,mode:"bleed",onClick:onStatusChange,tooltipProps:{content:status==="open"?t("comments.list-item-resolved-tooltip-content"):t("comments.list-item-re-open-resolved")}}),/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.MenuButton,{id:"comment-actions-menu",button:/* @__PURE__ */jsxRuntime.jsx(sanity.ContextMenuButton,{"aria-label":t("comments.list-item-open-menu-aria-label"),disabled:readOnly,hidden:!showMenuButton}),onOpen:onMenuOpen,onClose:onMenuClose,menu:/* @__PURE__ */jsxRuntime.jsxs(ui.Menu,{children:[/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.MenuItem,{hidden:!canEdit,icon:icons.EditIcon,onClick:onEditStart,text:t("comments.list-item-edit-comment")}),/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.MenuItem,{hidden:!canDelete,icon:icons.TrashIcon,onClick:onDeleteStart,text:t("comments.list-item-delete-comment"),tone:"critical"}),/* @__PURE__ */jsxRuntime.jsx(ui.MenuDivider,{hidden:!canDelete&&!canEdit}),/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.MenuItem,{hidden:!onCopyLink,icon:icons.LinkIcon,onClick:onCopyLink,text:t("comments.list-item-copy-link")})]}),popover:POPOVER_PROPS})]})})});}var __freeze$m=Object.freeze;var __defProp$m=Object.defineProperty;var __template$m=(cooked,raw)=>__freeze$m(__defProp$m(cooked,"raw",{value:__freeze$m(raw||cooked.slice())}));var _a$m,_b$b,_c$5,_d$2,_e$1,_f$1;const stopPropagation=e=>e.stopPropagation();const ContextMenuBox=styled__default.default(ui.Box)(_a$m||(_a$m=__template$m([""])));const SKELETON_INLINE_STYLE={width:"50%"};const EMPTY_ARRAY$5=[];const TimeText=styled__default.default(ui.Text)(_ref64=>{let{theme}=_ref64;const isDark=theme.sanity.color.dark;const fg=color.hues.gray[isDark?200:800].hex;return styled.css(_b$b||(_b$b=__template$m(["\n min-width: max-content;\n --card-fg-color: ",";\n color: var(--card-fg-color);\n "])),fg);});const InnerStack=styled__default.default(ui.Stack)(_c$5||(_c$5=__template$m(["\n transition: opacity 200ms ease;\n\n &[data-muted='true'] {\n transition: unset;\n opacity: 0.5;\n }\n"])));const ErrorFlex=styled__default.default(ui.Flex)(_d$2||(_d$2=__template$m(["\n min-height: ","px;\n"])),AVATAR_HEIGHT);const RetryCardButton=styled__default.default(ui.Card)(_e$1||(_e$1=__template$m(["\n // Add not on hover\n &:not(:hover) {\n background-color: transparent;\n }\n"])));const RootStack=styled__default.default(ui.Stack)(_ref65=>{let{theme}=_ref65;const{space}=theme.sanity;return styled.css(_f$1||(_f$1=__template$m(["\n position: relative;\n\n // Only show the floating layer on hover when hover is supported.\n // Else, the layer is always visible.\n @media (hover: hover) {\n "," {\n opacity: 0;\n position: absolute;\n right: 0;\n top: 0;\n transform: translate(","px, -","px);\n }\n\n "," {\n &:focus-within {\n opacity: 1;\n }\n }\n\n &:hover {\n "," {\n opacity: 1;\n }\n }\n }\n\n &[data-menu-open='true'] {\n "," {\n opacity: 1;\n }\n }\n "])),ContextMenuBox,space[1],space[1],ContextMenuBox,ContextMenuBox,ContextMenuBox);});const TIME_AGO_OPTS={agoSuffix:true};function CommentsListItemLayout(props){const{canDelete,canEdit,comment,currentUser,hasError,isParent,isRetrying,mentionOptions,onCopyLink,onCreateRetry,onDelete,onEdit,onInputKeyDown,onReactionSelect,onStatusChange,readOnly}=props;const{_createdAt,authorId,message,_id,lastEditedAt}=comment;const[user]=sanity.useUser(authorId);const{t}=sanity.useTranslation(commentsLocaleNamespace);const[value,setValue]=React.useState(message);const[isEditing,setIsEditing]=React.useState(false);const[rootElement,setRootElement]=React.useState(null);const startMessage=React.useRef(message);const[menuOpen,setMenuOpen]=React.useState(false);const hasChanges=useCommentHasChanged(value);const hasValue=React.useMemo(()=>hasCommentMessageValue(value),[value]);const reactions=React.useMemo(()=>{var _a2;return(((_a2=comment==null?void 0:comment.reactions)==null?void 0:_a2.filter(r=>(r==null?void 0:r._optimisticState)!=="removed"))||EMPTY_ARRAY$5).filter(r=>{return"userId"in r&&"shortName"in r;});},[comment==null?void 0:comment.reactions]);const hasReactions=Boolean(reactions==null?void 0:reactions.length);const commentInputRef=React.useRef(null);const createdDate=_createdAt?new Date(_createdAt):/* @__PURE__ */new Date();const createdTimeAgo=sanity.useTimeAgo(createdDate,TIME_AGO_OPTS);const formattedCreatedAt=dateFns.format(createdDate,"PPPPp");const formattedLastEditAt=lastEditedAt?dateFns.format(new Date(lastEditedAt),"PPPPp"):null;const displayError=hasError||isRetrying;const handleMenuOpen=React.useCallback(()=>setMenuOpen(true),[]);const handleMenuClose=React.useCallback(()=>setMenuOpen(false),[]);const handleCopyLink=React.useCallback(()=>onCopyLink==null?void 0:onCopyLink(_id),[_id,onCopyLink]);const handleCreateRetry=React.useCallback(e=>{e.stopPropagation();onCreateRetry==null?void 0:onCreateRetry(_id);},[_id,onCreateRetry]);const handleDelete=React.useCallback(()=>onDelete(_id),[_id,onDelete]);const cancelEdit=React.useCallback(()=>{setIsEditing(false);setValue(startMessage.current);},[]);const startDiscard=React.useCallback(()=>{var _a2;if(!hasValue||!hasChanges){cancelEdit();return;}(_a2=commentInputRef.current)==null?void 0:_a2.discardDialogController.open();},[cancelEdit,hasChanges,hasValue]);const handleInputKeyDown=React.useCallback(event=>{if(event.isDefaultPrevented()){return;}if(event.key==="Escape"){event.preventDefault();event.stopPropagation();startDiscard();}if(onInputKeyDown)onInputKeyDown(event);},[onInputKeyDown,startDiscard]);const cancelDiscard=React.useCallback(()=>{var _a2;(_a2=commentInputRef.current)==null?void 0:_a2.discardDialogController.close();},[]);const confirmDiscard=React.useCallback(()=>{var _a2;(_a2=commentInputRef.current)==null?void 0:_a2.discardDialogController.close();cancelEdit();},[cancelEdit]);const handleReactionSelect=React.useCallback(reaction=>{onReactionSelect==null?void 0:onReactionSelect(_id,reaction);},[_id,onReactionSelect]);const handleEditSubmit=React.useCallback(()=>{onEdit(_id,{message:value});setIsEditing(false);},[_id,onEdit,value]);const handleOpenStatusChange=React.useCallback(()=>{onStatusChange==null?void 0:onStatusChange(_id,comment.status==="open"?"resolved":"open");},[_id,comment.status,onStatusChange]);const toggleEdit=React.useCallback(()=>{setIsEditing(v=>!v);},[]);const handleCloseMenu=React.useCallback(()=>setMenuOpen(false),[]);const handleClickOutside=React.useCallback(()=>{if(!hasChanges){cancelEdit();}},[cancelEdit,hasChanges]);const handleRootKeyDown=React.useCallback(event=>{if(event.key==="Escape"&&!hasChanges){cancelEdit();}},[cancelEdit,hasChanges]);sanity.useDidUpdate(isEditing,handleCloseMenu);ui.useClickOutside(handleClickOutside,[rootElement]);const name=(user==null?void 0:user.displayName)?/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,weight:"medium",textOverflow:"ellipsis",title:user.displayName,children:user.displayName}):/* @__PURE__ */jsxRuntime.jsx(ui.TextSkeleton,{size:1,style:SKELETON_INLINE_STYLE});return/* @__PURE__ */jsxRuntime.jsxs(RootStack,{"data-menu-open":menuOpen?"true":"false",onKeyDown:handleRootKeyDown,ref:setRootElement,space:4,children:[/* @__PURE__ */jsxRuntime.jsxs(InnerStack,{space:1,"data-muted":displayError,children:[/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",gap:FLEX_GAP,flex:1,children:[/* @__PURE__ */jsxRuntime.jsx(CommentsAvatar,{user}),/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{align:"center",paddingBottom:1,sizing:"border",flex:1,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"flex-end",gap:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,children:name}),!displayError&&/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",gap:1,children:[/* @__PURE__ */jsxRuntime.jsx(TimeText,{muted:true,size:0,title:formattedCreatedAt,children:createdTimeAgo}),formattedLastEditAt&&/* @__PURE__ */jsxRuntime.jsxs(TimeText,{muted:true,size:0,title:formattedLastEditAt,children:["(",t("comments.list-item-layout-edited"),")"]})]})]})}),!isEditing&&!displayError&&/* @__PURE__ */jsxRuntime.jsx(ContextMenuBox,{"data-root-menu":isParent?"true":"false",onClick:stopPropagation,children:/* @__PURE__ */jsxRuntime.jsx(CommentsListItemContextMenu,{canDelete,canEdit,isParent,onCopyLink:handleCopyLink,onDeleteStart:handleDelete,onEditStart:toggleEdit,onMenuClose:handleMenuClose,onMenuOpen:handleMenuOpen,onReactionSelect:handleReactionSelect,onStatusChange:handleOpenStatusChange,readOnly,status:comment.status})})]}),isEditing&&/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"flex-start",gap:2,children:[/* @__PURE__ */jsxRuntime.jsx(SpacerAvatar,{}),/* @__PURE__ */jsxRuntime.jsx(ui.Stack,{flex:1,children:/* @__PURE__ */jsxRuntime.jsx(CommentInput,{currentUser,focusOnMount:true,mentionOptions,onChange:setValue,onDiscardCancel:cancelDiscard,onDiscardConfirm:confirmDiscard,onKeyDown:handleInputKeyDown,onSubmit:handleEditSubmit,readOnly,ref:commentInputRef,value,withAvatar:false})})]}),!isEditing&&/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:FLEX_GAP,children:[/* @__PURE__ */jsxRuntime.jsx(SpacerAvatar,{}),/* @__PURE__ */jsxRuntime.jsx(CommentMessageSerializer,{blocks:message})]}),hasReactions&&/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:FLEX_GAP,marginTop:2,children:[/* @__PURE__ */jsxRuntime.jsx(SpacerAvatar,{}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{onClick:stopPropagation,children:/* @__PURE__ */jsxRuntime.jsx(CommentReactionsBar,{currentUser,onSelect:handleReactionSelect,reactions,readOnly})})]})]}),displayError&&/* @__PURE__ */jsxRuntime.jsxs(ErrorFlex,{gap:FLEX_GAP,children:[/* @__PURE__ */jsxRuntime.jsx(SpacerAvatar,{}),/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",gap:1,flex:1,children:[/* @__PURE__ */jsxRuntime.jsxs(ui.Text,{muted:true,size:1,children:[hasError&&t("comments.list-item-layout-failed-sent"),isRetrying&&t("comments.list-item-layout-posting")]}),/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{hidden:isRetrying,children:/* @__PURE__ */jsxRuntime.jsx(RetryCardButton,{__unstable_focusRing:true,display:"flex",forwardedAs:"button",onClick:handleCreateRetry,padding:1,radius:2,tone:"primary",children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,muted:true,children:t("comments.list-item-layout-retry")})})})]})]})]});}var __freeze$l=Object.freeze;var __defProp$l=Object.defineProperty;var __template$l=(cooked,raw)=>__freeze$l(__defProp$l(cooked,"raw",{value:__freeze$l(raw||cooked.slice())}));var _a$l;const ThreadCard=styled__default.default(ui.Card).attrs(_ref66=>{let{tone}=_ref66;return{padding:3,radius:3,sizing:"border",tone:tone||"transparent"};})(_a$l||(_a$l=__template$l(["\n // ...\n"])));var __freeze$k=Object.freeze;var __defProp$k=Object.defineProperty;var __template$k=(cooked,raw)=>__freeze$k(__defProp$k(cooked,"raw",{value:__freeze$k(raw||cooked.slice())}));var _a$k,_b$a,_c$4;const EMPTY_ARRAY$4=[];const MAX_COLLAPSED_REPLIES=5;const StyledThreadCard=styled__default.default(ThreadCard)(_ref67=>{let{theme}=_ref67;const{hovered}=theme.sanity.color.button.bleed.default;return styled.css(_a$k||(_a$k=__template$k(["\n position: relative;\n\n &:has(> [data-ui='GhostButton']:focus:focus-visible) {\n box-shadow:\n inset 0 0 0 1px var(--card-border-color),\n 0 0 0 1px var(--card-bg-color),\n 0 0 0 2px var(--card-focus-ring-color);\n }\n\n // When the comment is not selected, we want to apply hover styles.\n // The hover styles is managed with the [data-hovered] attribute instead of the :hover pseudo class\n // since we want to show the hover styles when hovering over the menu items in the context menu as well.\n // The context menu is rendered using a portal, so the :hover pseudo class won't work when hovering over\n // the menu items.\n &:not([data-active='true']) {\n @media (hover: hover) {\n &[data-hovered='true'] {\n --card-bg-color: ",";\n\n [data-root-menu='true'] {\n opacity: 1;\n }\n }\n }\n }\n "])),hovered.bg2);});const ExpandButton=styled__default.default(TooltipDelayGroupProvider.Button)(_ref68=>{let{theme}=_ref68;const{medium}=theme.sanity.fonts.text.weights;return styled.css(_b$a||(_b$a=__template$k(["\n font-weight: ",";\n "])),medium);});const GhostButton=styled__default.default.button(_c$4||(_c$4=__template$k(["\n opacity: 0;\n position: absolute;\n right: 0;\n top: 0;\n bottom: 0;\n left: 0;\n"])));const CommentsListItem=React__default.default.memo(function CommentsListItem2(props){var _a2,_b2;const{canReply,currentUser,isSelected,mentionOptions,onCopyLink,onCreateRetry,onDelete,onEdit,onKeyDown,onPathSelect,onReactionSelect,onReply,onStatusChange,parentComment,readOnly,replies=EMPTY_ARRAY$4}=props;const{t}=sanity.useTranslation(commentsLocaleNamespace);const[value,setValue]=React.useState(EMPTY_ARRAY$4);const[collapsed,setCollapsed]=React.useState(true);const didExpand=React.useRef(false);const replyInputRef=React.useRef(null);const{isTopLayer}=ui.useLayer();const hasValue=React.useMemo(()=>hasCommentMessageValue(value),[value]);const[mouseOver,setMouseOver]=React.useState(false);const handleMouseEnter=React.useCallback(()=>setMouseOver(true),[]);const handleMouseLeave=React.useCallback(()=>setMouseOver(false),[]);const handleReplySubmit=React.useCallback(()=>{const nextComment={fieldPath:parentComment.target.path.field,message:value,parentCommentId:parentComment._id,status:(parentComment==null?void 0:parentComment.status)||"open",// Since this is a reply to an existing comment, we use the same thread ID as the parent
@@ -40,7 +40,7 @@ runSetup,// The following callbacks runs when the comment operation are executed
40
40
  // event from the real time listener.
41
41
  onCreate:handleOnCreate,onCreateError:handleOnCreateError,onEdit:handleOnEdit,onUpdate:handleOnUpdate}),[client,currentUser,dataset,publishedId,documentType,projectId,schemaType,workspaceName,getThreadLength,getComment,runSetup,handleOnCreate,handleOnCreateError,handleOnEdit,handleOnUpdate]));const ctxValue=React.useMemo(()=>({isRunningSetup,status,setStatus,getComment,isCommentsOpen,onCommentsOpen,comments:{data:threadItemsByStatus,error,loading:loading||isRunningSetup},operation:{create:operation.create,edit:operation.edit,react:operation.react,remove:operation.remove,update:operation.update},mentionOptions}),[error,getComment,isCommentsOpen,isRunningSetup,loading,mentionOptions,onCommentsOpen,operation.create,operation.edit,operation.react,operation.remove,operation.update,status,threadItemsByStatus]);return/* @__PURE__ */jsxRuntime.jsx(CommentsContext.Provider,{value:ctxValue,children});});const CommentsSetupContext=React.createContext(null);const API_VERSION="v2023-11-13";function CommentsSetupProvider(props){const{children}=props;const{dataset,projectId}=sanity.useWorkspace();const originalClient=sanity.useClient(sanity.DEFAULT_STUDIO_CLIENT_OPTIONS);const[addonDatasetClient,setAddonDatasetClient]=React.useState(null);const[isRunningSetup,setIsRunningSetup]=React.useState(false);const getAddonDatasetName=React.useCallback(async()=>{var _a;const res=await originalClient.withConfig({apiVersion:API_VERSION}).request({uri:"/projects/".concat(projectId,"/datasets?datasetProfile=comments&addonFor=").concat(dataset),tag:"sanity.studio"});return(_a=res==null?void 0:res[0])==null?void 0:_a.name;},[dataset,originalClient,projectId]);const handleCreateClient=React.useCallback(addonDatasetName=>{const client=originalClient.withConfig({apiVersion:API_VERSION,dataset:addonDatasetName,projectId,requestTagPrefix:"sanity.studio",useCdn:false,withCredentials:true});return client;},[originalClient,projectId]);const handleRunSetup=React.useCallback(async comment=>{setIsRunningSetup(true);try{const addonDatasetName=await getAddonDatasetName();if(addonDatasetName){const client=handleCreateClient(addonDatasetName);setAddonDatasetClient(client);await client.create(comment);setIsRunningSetup(false);return;}}catch(_){}try{const res=await originalClient.withConfig({apiVersion:API_VERSION}).request({uri:"/comments/".concat(dataset,"/setup"),method:"POST"});const datasetName=res==null?void 0:res.datasetName;if(!datasetName){setIsRunningSetup(false);return;}const client=handleCreateClient(datasetName);setAddonDatasetClient(client);await client.create(comment);}catch(err){throw err;}finally{setIsRunningSetup(false);}},[dataset,getAddonDatasetName,handleCreateClient,originalClient]);React.useEffect(()=>{getAddonDatasetName().then(addonDatasetName=>{if(!addonDatasetName)return;const client=handleCreateClient(addonDatasetName);setAddonDatasetClient(client);});},[getAddonDatasetName,handleCreateClient]);const ctxValue=React.useMemo(()=>({client:addonDatasetClient,runSetup:handleRunSetup,isRunningSetup}),[addonDatasetClient,handleRunSetup,isRunningSetup]);return/* @__PURE__ */jsxRuntime.jsx(CommentsSetupContext.Provider,{value:ctxValue,children});}const CommentsSelectedPathContext=React.createContext(null);const CommentsSelectedPathProvider=React__default.default.memo(function CommentsSelectedPathProvider2(props){const{children}=props;const[selectedPath,setSelectedPath]=React.useState(null);const handleSelectPath=React.useCallback(nextPath=>{setSelectedPath(nextPath);},[]);const ctxValue=React.useMemo(()=>({selectedPath,setSelectedPath:handleSelectPath}),[selectedPath,handleSelectPath]);return/* @__PURE__ */jsxRuntime.jsx(CommentsSelectedPathContext.Provider,{value:ctxValue,children});});const Root$6=styled__default.default(ui.Card)({position:"relative",zIndex:1,lineHeight:0});const CommentsInspectorHeader=React.forwardRef(function CommentsInspectorHeader2(props,ref){const{t}=sanity.useTranslation(commentsLocaleNamespace);const{onClose,onViewChange,view}=props;const handleSetOpenView=React.useCallback(()=>onViewChange("open"),[onViewChange]);const handleSetResolvedView=React.useCallback(()=>onViewChange("resolved"),[onViewChange]);return/* @__PURE__ */jsxRuntime.jsx(Root$6,{ref,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{padding:2,children:[/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",flex:1,gap:2,paddingY:2,padding:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Text,{as:"h1",size:1,weight:"medium",children:t("comments.header-title")}),/* @__PURE__ */jsxRuntime.jsx(sanity.BetaBadge,{})]}),/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{flex:"none",padding:1,gap:2,children:[/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.MenuButton,{id:"comment-status-menu-button",button:/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{text:view==="open"?t("comments.dropdown-title-open"):t("comments.dropdown-title-resolved"),mode:"bleed",iconRight:icons.ChevronDownIcon}),menu:/* @__PURE__ */jsxRuntime.jsxs(ui.Menu,{style:{width:"180px"},children:[/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.MenuItem,{iconRight:view==="open"?icons.CheckmarkIcon:void 0,onClick:handleSetOpenView,text:t("comments.dropdown-item-open")}),/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.MenuItem,{iconRight:view==="resolved"?icons.CheckmarkIcon:void 0,onClick:handleSetResolvedView,text:t("comments.dropdown-item-resolved")})]}),popover:{placement:"bottom-end"}}),/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{"aria-label":t("comments.button-close-pane-text-aria-label"),icon:icons.DoubleChevronRightIcon,mode:"bleed",onClick:onClose,tooltipProps:{content:t("comments.button-close-pane-text")}})]})]})});});var __freeze$h=Object.freeze;var __defProp$h=Object.defineProperty;var __template$h=(cooked,raw)=>__freeze$h(__defProp$h(cooked,"raw",{value:__freeze$h(raw||cooked.slice())}));var _a$h,_b$7;const FEEDBACK_FORM_LINK="https://snty.link/comments-beta-feedback";const Span=styled__default.default.span(_a$h||(_a$h=__template$h(["\n margin-right: 0.2em;\n"])));const Link=styled__default.default.a(_b$7||(_b$7=__template$h(["\n white-space: nowrap;\n"])));const FooterCard=styled__default.default(ui.Card)({position:"relative",zIndex:1});function CommentsInspectorFeedbackFooter(){const{t}=sanity.useTranslation(commentsLocaleNamespace);return/* @__PURE__ */jsxRuntime.jsx(FooterCard,{padding:4,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Text,{muted:true,size:1,children:[t("comments.feedback-footer-title")," ",/* @__PURE__ */jsxRuntime.jsxs(Link,{href:FEEDBACK_FORM_LINK,target:"_blank",rel:"noreferrer",children:[/* @__PURE__ */jsxRuntime.jsxs(Span,{children:[t("comments.feedback-footer-link")," "]})," ",/* @__PURE__ */jsxRuntime.jsx(icons.LaunchIcon,{})]})]})});}var __freeze$g=Object.freeze;var __defProp$g=Object.defineProperty;var __template$g=(cooked,raw)=>__freeze$g(__defProp$g(cooked,"raw",{value:__freeze$g(raw||cooked.slice())}));var _a$g;const RootLayer=styled__default.default(ui.Layer)(_a$g||(_a$g=__template$g(["\n display: flex;\n flex-direction: column;\n height: 100%;\n overflow: hidden;\n"])));function CommentsInspector(props){const isEnabled=useCommentsEnabled();if(!isEnabled)return null;return/* @__PURE__ */jsxRuntime.jsx(RootLayer,{children:/* @__PURE__ */jsxRuntime.jsx(CommentsInspectorInner,{...props})});}function CommentsInspectorInner(props){const{t}=sanity.useTranslation(commentsLocaleNamespace);const{onClose}=props;const[showDeleteDialog,setShowDeleteDialog]=React.useState(false);const[commentToDelete,setCommentToDelete]=React.useState(null);const[deleteLoading,setDeleteLoading]=React.useState(false);const[deleteError,setDeleteError]=React.useState(null);const commentsListHandleRef=React.useRef(null);const rootRef=React.useRef(null);const currentUser=sanity.useCurrentUser();const{params,createPathWithParams,setParams}=usePaneRouter();const uniqueParams=sanity.useUnique(params)||EMPTY_PARAMS$2;const commentIdParamRef=React.useRef(uniqueParams==null?void 0:uniqueParams.comment);const didScrollToCommentFromParam=React.useRef(false);const pushToast=ui.useToast().push;const{onPathOpen,ready}=useDocumentPane();const{isDismissed,setDismissed}=useCommentsOnboarding();const{comments,getComment,isRunningSetup,mentionOptions,setStatus,status,operation}=useComments();const{isTopLayer}=ui.useLayer();const currentComments=React.useMemo(()=>comments.data[status],[comments,status]);const loading=React.useMemo(()=>{return comments.loading||!ready;},[comments.loading,ready]);const{selectedPath,setSelectedPath}=useCommentsSelectedPath();const handleChangeView=React.useCallback(nextView=>{setStatus(nextView);setSelectedPath(null);},[setSelectedPath,setStatus]);const handleCloseInspector=React.useCallback(()=>{onClose();setSelectedPath(null);},[onClose,setSelectedPath]);const handleCopyLink=React.useCallback(id=>{const path=createPathWithParams({...params,comment:id});const url="".concat(window.location.origin).concat(path);navigator.clipboard.writeText(url).then(()=>{pushToast({closable:true,status:"info",title:t("comments.copy-link-success-message")});}).catch(()=>{pushToast({closable:true,status:"error",title:t("comments.copy-link-error-message")});});},[createPathWithParams,params,pushToast,t]);const handleCreateRetry=React.useCallback(id=>{const comment=getComment(id);if(!comment)return;operation.create({fieldPath:comment.target.path.field,id:comment._id,message:comment.message,parentCommentId:comment.parentCommentId,reactions:comment.reactions||[],status:comment.status,threadId:comment.threadId});},[getComment,operation]);const closeDeleteDialog=React.useCallback(()=>{if(deleteLoading)return;setShowDeleteDialog(false);setCommentToDelete(null);},[deleteLoading]);const handlePathSelect=React.useCallback(nextPath=>{setSelectedPath(nextPath);if(nextPath==null?void 0:nextPath.fieldPath){const path=PathUtils__namespace.fromString(nextPath.fieldPath);onPathOpen(path);}},[onPathOpen,setSelectedPath]);const handleNewThreadCreate=React.useCallback(payload=>{operation.create(payload);setSelectedPath({fieldPath:payload.fieldPath,origin:"inspector",threadId:payload.threadId});},[operation,setSelectedPath]);const handleReply=React.useCallback(payload=>{operation.create(payload);},[operation]);const handleEdit=React.useCallback((id,payload)=>{operation.edit(id,payload);},[operation]);const onDeleteStart=React.useCallback(id=>{var _a2;const parent=currentComments.find(c=>{var _a3;return((_a3=c.parentComment)==null?void 0:_a3._id)===id;});const isParent=Boolean(parent&&((_a2=parent==null?void 0:parent.replies)==null?void 0:_a2.length)>0);setShowDeleteDialog(true);setCommentToDelete({commentId:id,isParent});},[currentComments]);const handleDeleteConfirm=React.useCallback(async id=>{try{setDeleteLoading(true);await operation.remove(id);closeDeleteDialog();}catch(err){setDeleteError(err);}finally{setDeleteLoading(false);}},[closeDeleteDialog,operation]);const handleScrollToComment=React.useCallback((id,origin)=>{const comment=getComment(id);if(comment){setSelectedPath({fieldPath:comment.target.path.field||null,origin:origin||"inspector",threadId:comment.threadId||null});setTimeout(()=>{var _a2;(_a2=commentsListHandleRef.current)==null?void 0:_a2.scrollToComment(id);});}},[getComment,setSelectedPath]);const handleStatusChange=React.useCallback((id,nextStatus)=>{operation.update(id,{status:nextStatus});if(nextStatus==="open"){setStatus("open");handleScrollToComment(id);}},[handleScrollToComment,operation,setStatus]);const handleReactionSelect=React.useCallback((id,reaction)=>{operation.react(id,reaction);},[operation]);const handleDeselectPath=React.useCallback(()=>{if(selectedPath&&isTopLayer){setSelectedPath(null);}},[isTopLayer,selectedPath,setSelectedPath]);ui.useClickOutside(handleDeselectPath,[rootRef.current]);React.useEffect(()=>{const commentToScrollTo=getComment(commentIdParamRef.current||"");if(!loading&&commentToScrollTo&&didScrollToCommentFromParam.current===false){setStatus(commentToScrollTo.status||"open");handleScrollToComment(commentToScrollTo._id,"url");didScrollToCommentFromParam.current=true;commentIdParamRef.current=void 0;setParams({...params,comment:void 0});}},[getComment,handleScrollToComment,loading,params,setParams,setStatus]);return/* @__PURE__ */jsxRuntime.jsxs(React.Fragment,{children:[commentToDelete&&showDeleteDialog&&/* @__PURE__ */jsxRuntime.jsx(CommentDeleteDialog,{...commentToDelete,error:deleteError,loading:deleteLoading,onClose:closeDeleteDialog,onConfirm:handleDeleteConfirm}),/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{direction:"column",flex:1,height:"fill",onClick:handleDeselectPath,overflow:"hidden",ref:rootRef,children:[/* @__PURE__ */jsxRuntime.jsx(CommentsOnboardingPopover,{onDismiss:setDismissed,open:!isDismissed,placement:"left-start",children:/* @__PURE__ */jsxRuntime.jsx(CommentsInspectorHeader,{onClose:handleCloseInspector,onViewChange:handleChangeView,view:status})}),currentUser&&/* @__PURE__ */jsxRuntime.jsx(CommentsList,{comments:currentComments,currentUser,error:comments.error,loading,mentionOptions,onCopyLink:handleCopyLink,onCreateRetry:handleCreateRetry,onDelete:onDeleteStart,onEdit:handleEdit,onNewThreadCreate:handleNewThreadCreate,onPathSelect:handlePathSelect,onReactionSelect:handleReactionSelect,onReply:handleReply,onStatusChange:handleStatusChange,readOnly:isRunningSetup,ref:commentsListHandleRef,selectedPath,status}),/* @__PURE__ */jsxRuntime.jsx(CommentsInspectorFeedbackFooter,{})]})]});}function useMenuItem$1(){const isEnabled=useCommentsEnabled();const{t}=sanity.useTranslation(commentsLocaleNamespace);return{hidden:!isEnabled,icon:icons.CommentIcon,showAsAction:true,title:t("comments.document-inspector-title")};}const commentsInspector=sanity.defineDocumentInspector({name:COMMENTS_INSPECTOR_NAME,component:CommentsInspector,useMenuItem:useMenuItem$1});var __freeze$f=Object.freeze;var __defProp$f=Object.defineProperty;var __template$f=(cooked,raw)=>__freeze$f(__defProp$f(cooked,"raw",{value:__freeze$f(raw||cooked.slice())}));var _a$f;const ContentStack=styled__default.default(ui.Stack)(_a$f||(_a$f=__template$f(["\n width: 320px;\n"])));function CommentsFieldButton(props){const{count,currentUser,fieldTitle,isRunningSetup,mentionOptions,onChange,onClick,onCommentAdd,onDiscard,onInputKeyDown,open,setOpen,value}=props;const{t}=sanity.useTranslation(commentsLocaleNamespace);const[popoverElement,setPopoverElement]=React.useState(null);const[addCommentButtonElement,setAddCommentButtonElement]=React.useState(null);const commentInputHandle=React.useRef(null);const hasComments=Boolean(count>0);const closePopover=React.useCallback(()=>{if(!open)return;setOpen(false);addCommentButtonElement==null?void 0:addCommentButtonElement.focus();},[addCommentButtonElement,open,setOpen]);const handleSubmit=React.useCallback(()=>{onCommentAdd();closePopover();},[closePopover,onCommentAdd]);const hasValue=React.useMemo(()=>hasCommentMessageValue(value),[value]);const startDiscard=React.useCallback(()=>{var _a2;if(!hasValue){closePopover();return;}(_a2=commentInputHandle.current)==null?void 0:_a2.discardDialogController.open();},[closePopover,hasValue]);const handleInputKeyDown=React.useCallback(event=>{if(event.isDefaultPrevented()){return;}if(onInputKeyDown)onInputKeyDown(event);},[onInputKeyDown]);const handleDiscardCancel=React.useCallback(()=>{var _a2;(_a2=commentInputHandle.current)==null?void 0:_a2.discardDialogController.close();},[]);const handleDiscardConfirm=React.useCallback(()=>{var _a2;(_a2=commentInputHandle.current)==null?void 0:_a2.discardDialogController.close();closePopover();onDiscard();},[closePopover,onDiscard]);const handlePopoverKeyDown=React.useCallback(event=>{if(event.key==="Escape"){event.preventDefault();event.stopPropagation();startDiscard();}},[startDiscard]);const handleClickOutside=React.useCallback(()=>{if(!open)return;startDiscard();},[open,startDiscard]);ui.useClickOutside(handleClickOutside,[popoverElement]);if(!hasComments){const placeholder=/* @__PURE__ */jsxRuntime.jsx(sanity.Translate,{t,i18nKey:"comments.placeholder-add-comment-field-title",components:{Strong:()=>/* @__PURE__ */jsxRuntime.jsx("b",{children:fieldTitle})}});const content=/* @__PURE__ */jsxRuntime.jsx(ContentStack,{padding:2,space:4,children:/* @__PURE__ */jsxRuntime.jsx(CommentInput,{currentUser,focusLock:true,focusOnMount:true,mentionOptions,onChange,onDiscardCancel:handleDiscardCancel,onDiscardConfirm:handleDiscardConfirm,onKeyDown:handleInputKeyDown,onSubmit:handleSubmit,placeholder,readOnly:isRunningSetup,ref:commentInputHandle,value})});return/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Popover,{constrainSize:true,content,fallbackPlacements:["bottom-end"],open,placement:"right-start",portal:true,ref:setPopoverElement,onKeyDown:handlePopoverKeyDown,children:/* @__PURE__ */jsxRuntime.jsx("div",{children:/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{"aria-label":t("comments.field-button-aria-label-add"),disabled:isRunningSetup,icon:AddCommentIcon,mode:"bleed",onClick,ref:setAddCommentButtonElement,selected:open,tooltipProps:{content:t("comments.field-button-title"),placement:"top"}})})});}return/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Tooltip,{portal:true,placement:"top",content:t("comments.field-button-content",{count}),children:/* @__PURE__ */jsxRuntime.jsx(ui.Button,{"aria-label":t("comments.field-button-aria-label-open"),mode:"bleed",onClick,padding:2,space:2,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"center",gap:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:/* @__PURE__ */jsxRuntime.jsx(CommentIcon,{})}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:0,children:count>9?"9+":count})]})})});}var __freeze$e=Object.freeze;var __defProp$e=Object.defineProperty;var __template$e=(cooked,raw)=>__freeze$e(__defProp$e(cooked,"raw",{value:__freeze$e(raw||cooked.slice())}));var _a$e,_b$6;const HIGHLIGHT_BLOCK_VARIANTS={initial:{opacity:0},animate:{opacity:1},exit:{opacity:0}};function CommentsField(props){const isEnabled=useCommentsEnabled();if(!isEnabled){return props.renderDefault(props);}return/* @__PURE__ */jsxRuntime.jsx(CommentFieldInner,{...props});}const SCROLL_INTO_VIEW_OPTIONS={behavior:"smooth",block:"start"};const HighlightDiv=styled__default.default(framerMotion.motion.div)(_ref74=>{let{theme}=_ref74;const{radius,space,color:color$1}=theme.sanity;const bg=color.hues.yellow[color$1.dark?900:50].hex;return styled.css(_a$e||(_a$e=__template$e(["\n mix-blend-mode: ",";\n border-radius: ","px;\n top: -","px;\n left: -","px;\n bottom: -","px;\n right: -","px;\n pointer-events: none;\n position: absolute;\n z-index: 1;\n width: calc(100% + ","px);\n height: calc(100% + ","px);\n background-color: ",";\n "])),color$1.dark?"screen":"multiply",radius[3],space[2],space[2],space[2],space[2],space[2]*2,space[2]*2,bg);});const FieldStack=styled__default.default(ui.Stack)(_b$6||(_b$6=__template$e(["\n position: relative;\n"])));function CommentFieldInner(props){const[open,setOpen]=React.useState(false);const[value,setValue]=React.useState(null);const rootElementRef=React.useRef(null);const[threadIdToScrollTo,setThreadIdToScrollTo]=React.useState(null);const{element:boundaryElement}=ui.useBoundaryElement();const currentUser=sanity.useCurrentUser();const{comments,isCommentsOpen,isRunningSetup,mentionOptions,onCommentsOpen,operation,setStatus,status}=useComments();const{selectedPath,setSelectedPath}=useCommentsSelectedPath();const fieldTitle=React.useMemo(()=>sanity.getSchemaTypeTitle(props.schemaType),[props.schemaType]);const isSelected=React.useMemo(()=>{if(!isCommentsOpen)return false;if((selectedPath==null?void 0:selectedPath.origin)==="form"||(selectedPath==null?void 0:selectedPath.origin)==="url")return false;return(selectedPath==null?void 0:selectedPath.fieldPath)===PathUtils__namespace.toString(props.path);},[isCommentsOpen,props.path,selectedPath==null?void 0:selectedPath.fieldPath,selectedPath==null?void 0:selectedPath.origin]);const count=React.useMemo(()=>{const stringPath=PathUtils__namespace.toString(props.path);const commentsCount=comments.data.open.map(c=>c.fieldPath===stringPath?c.commentsCount:0).reduce((acc,val)=>acc+val,0);return commentsCount||0;},[comments.data.open,props.path]);const hasComments=Boolean(count>0);const handleSetThreadToScrollTo=React.useCallback(threadId=>{setSelectedPath({threadId,origin:"form",fieldPath:PathUtils__namespace.toString(props.path)});setThreadIdToScrollTo(threadId);},[props.path,setSelectedPath]);const handleClick=React.useCallback(()=>{var _a2;if(hasComments){if(status==="resolved"){setStatus("open");}setOpen(false);onCommentsOpen==null?void 0:onCommentsOpen();const scrollToThreadId=(_a2=comments.data.open.find(c=>c.fieldPath===PathUtils__namespace.toString(props.path)))==null?void 0:_a2.threadId;if(scrollToThreadId){handleSetThreadToScrollTo(scrollToThreadId);}return;}setOpen(v=>!v);},[hasComments,status,onCommentsOpen,comments.data.open,setStatus,props.path,handleSetThreadToScrollTo]);const handleCommentAdd=React.useCallback(()=>{if(value){const newThreadId=uuid.uuid();const nextComment={fieldPath:PathUtils__namespace.toString(props.path),message:value,parentCommentId:void 0,status:"open",threadId:newThreadId,// New comments have no reactions
42
42
  reactions:[]};operation.create(nextComment);onCommentsOpen==null?void 0:onCommentsOpen();if(status==="resolved"){setStatus("open");}setValue(null);handleSetThreadToScrollTo(newThreadId);}},[handleSetThreadToScrollTo,onCommentsOpen,operation,props.path,setStatus,status,value]);const handleDiscard=React.useCallback(()=>setValue(null),[]);const scrollIntoViewIfNeededOpts=React.useMemo(()=>({...SCROLL_INTO_VIEW_OPTIONS,boundary:boundaryElement,scrollMode:"if-needed",block:"start"}),[boundaryElement]);React.useEffect(()=>{if(isSelected&&rootElementRef.current&&isCommentsOpen){scrollIntoView__default.default(rootElementRef.current,scrollIntoViewIfNeededOpts);}},[boundaryElement,isCommentsOpen,isSelected,props.path,scrollIntoViewIfNeededOpts]);React.useEffect(()=>{if(isCommentsOpen&&threadIdToScrollTo){const node=document.querySelector('[data-group-id="'.concat(threadIdToScrollTo,'"]'));if(node){node.scrollIntoView(SCROLL_INTO_VIEW_OPTIONS);setThreadIdToScrollTo(null);}}},[isCommentsOpen,threadIdToScrollTo]);const internalComments=React.useMemo(()=>({button:currentUser&&/* @__PURE__ */jsxRuntime.jsx(CommentsFieldButton,{count:Number(count),currentUser,fieldTitle,isRunningSetup,mentionOptions,onChange:setValue,onClick:handleClick,onCommentAdd:handleCommentAdd,onDiscard:handleDiscard,open,setOpen,value}),hasComments,isAddingComment:open}),[currentUser,count,fieldTitle,mentionOptions,handleClick,handleCommentAdd,handleDiscard,open,value,isRunningSetup,hasComments]);return/* @__PURE__ */jsxRuntime.jsxs(FieldStack,{ref:rootElementRef,children:[props.renderDefault({...props,// eslint-disable-next-line camelcase
43
- __internal_comments:internalComments}),/* @__PURE__ */jsxRuntime.jsx(framerMotion.AnimatePresence,{children:isSelected&&/* @__PURE__ */jsxRuntime.jsx(HighlightDiv,{animate:"animate",exit:"exit",initial:"initial",variants:HIGHLIGHT_BLOCK_VARIANTS})})]});}function CommentsDocumentLayout(props){const{documentId,documentType}=props;return/* @__PURE__ */jsxRuntime.jsx(CommentsEnabledProvider,{documentId,documentType,children:/* @__PURE__ */jsxRuntime.jsx(CommentsDocumentLayoutInner,{...props})});}function CommentsDocumentLayoutInner(props){const{documentId,documentType}=props;const commentsEnabled=useCommentsEnabled();const{openInspector,inspector}=useDocumentPane();const handleOpenCommentsInspector=React.useCallback(()=>{if((inspector==null?void 0:inspector.name)===COMMENTS_INSPECTOR_NAME)return;openInspector(COMMENTS_INSPECTOR_NAME);},[inspector==null?void 0:inspector.name,openInspector]);if(!commentsEnabled){return props.renderDefault(props);}return/* @__PURE__ */jsxRuntime.jsx(CommentsProvider,{documentId,documentType,isCommentsOpen:(inspector==null?void 0:inspector.name)===COMMENTS_INSPECTOR_NAME,onCommentsOpen:handleOpenCommentsInspector,children:/* @__PURE__ */jsxRuntime.jsx(CommentsSelectedPathProvider,{children:props.renderDefault(props)})});}function CommentsStudioLayout(props){return/* @__PURE__ */jsxRuntime.jsx(CommentsSetupProvider,{children:/* @__PURE__ */jsxRuntime.jsx(CommentsOnboardingProvider,{children:props.renderDefault(props)})});}const comments=sanity.definePlugin({name:"sanity/structure/comments",document:{inspectors:[commentsInspector],components:{unstable_layout:CommentsDocumentLayout}},form:{components:{field:CommentsField}},studio:{components:{layout:CommentsStudioLayout}},i18n:{bundles:[commentsUsEnglishLocaleBundle]}});const StructureToolContext=React.createContext(null);function useStructureTool(){const structureTool=React.useContext(StructureToolContext);if(!structureTool)throw new Error("StructureTool: missing context value");return structureTool;}const TIMELINE_ICON_COMPONENTS={create:icons.AddCircleIcon,delete:icons.TrashIcon,discardDraft:icons.CloseIcon,initial:icons.AddCircleIcon,editDraft:icons.EditIcon,editLive:icons.EditIcon,publish:icons.PublishIcon,unpublish:icons.UnpublishIcon};function getTimelineEventIconComponent(type){return TIMELINE_ICON_COMPONENTS[type];}function UserAvatarStack(_ref75){let{maxLength,userIds}=_ref75;return/* @__PURE__ */jsxRuntime.jsx(ui.AvatarStack,{maxLength,children:userIds.map(userId=>/* @__PURE__ */jsxRuntime.jsx(sanity.UserAvatar,{user:userId,withTooltip:true},userId))});}var __freeze$d=Object.freeze;var __defProp$d=Object.defineProperty;var __template$d=(cooked,raw)=>__freeze$d(__defProp$d(cooked,"raw",{value:__freeze$d(raw||cooked.slice())}));var _a$d,_b$5,_c$2,_d$1,_e,_f;const IconWrapper=styled__default.default(ui.Flex)(_ref76=>{let{theme}=_ref76;var _a2;const borderColor=(_a2=theme.sanity.color.base.skeleton)==null?void 0:_a2.from;return styled.css(_a$d||(_a$d=__template$d(["\n --timeline-hairline-width: 1px;\n position: relative;\n z-index: 2;\n margin: 0;\n padding: 0;\n\n &::before {\n position: absolute;\n content: '';\n height: 100%;\n width: var(--timeline-hairline-width);\n background: ",";\n top: 0;\n left: calc((100% - var(--timeline-hairline-width)) / 2);\n z-index: 1;\n }\n "])),borderColor);});const Root$5=styled__default.default(ui.Button)(_ref77=>{let{$selected,$disabled}=_ref77;return styled.css(_d$1||(_d$1=__template$d(["\n position: relative;\n width: 100%;\n\n /* Line styling */\n &[data-first] ","::before {\n height: 50%;\n top: unset;\n bottom: 0;\n }\n\n &[data-last] ","::before {\n height: 50%;\n }\n\n ","\n\n ","\n "])),IconWrapper,IconWrapper,$selected&&styled.css(_b$5||(_b$5=__template$d(["\n ","::before {\n background: transparent;\n }\n "])),IconWrapper),$disabled&&styled.css(_c$2||(_c$2=__template$d(["\n cursor: not-allowed;\n "]))));});const IconBox=styled__default.default(ui.Box)(_e||(_e=__template$d(["\n background: var(--card-bg-color);\n border-radius: 50px;\n position: relative;\n z-index: 2;\n"])));const TimestampBox=styled__default.default(ui.Box)(_f||(_f=__template$d(["\n min-width: 1rem;\n margin-left: ",";\n"])),_ref78=>{let{theme}=_ref78;return"-".concat(ui.rem(theme.sanity.space[1]));});const TIMELINE_ITEM_I18N_KEY_MAPPING={initial:"timeline.operation.created-initial",create:"timeline.operation.created",publish:"timeline.operation.published",editLive:"timeline.operation.edited-live",editDraft:"timeline.operation.edited-draft",unpublish:"timeline.operation.unpublished",discardDraft:"timeline.operation.draft-discarded",delete:"timeline.operation.deleted"};const TIMELINE_ITEM_EVENT_TONE={initial:"primary",create:"primary",publish:"positive",editLive:"caution",editDraft:"caution",unpublish:"critical",discardDraft:"critical",delete:"critical",withinSelection:"primary"};function TimelineItem(_ref79){let{chunk,isFirst,isLast,isLatest,isSelected,onSelect,timestamp,type}=_ref79;const{t}=sanity.useTranslation("studio");const iconComponent=getTimelineEventIconComponent(type);const authorUserIds=Array.from(chunk.authors);const isSelectable=type!=="delete";const dateFormat=sanity.useDateTimeFormat({dateStyle:"medium",timeStyle:"short"});const formattedTimestamp=React.useMemo(()=>{const parsedDate=new Date(timestamp);const formattedDate=dateFormat.format(parsedDate);return formattedDate;},[timestamp,dateFormat]);const handleClick=React.useCallback(evt=>{evt.preventDefault();evt.stopPropagation();if(isSelectable){onSelect(chunk);}},[onSelect,chunk,isSelectable]);return/* @__PURE__ */jsxRuntime.jsx(Root$5,{$selected:isSelected,$disabled:!isSelectable,"data-chunk-id":chunk.id,"data-first":isFirst?true:void 0,"data-last":isLast?true:void 0,"data-ui":"timelineItem",mode:isSelected?"default":"bleed",onClick:handleClick,padding:0,radius:2,tone:isSelected?"primary":TIMELINE_ITEM_EVENT_TONE[chunk.type],children:/* @__PURE__ */jsxRuntime.jsx(ui.Box,{paddingX:2,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"stretch",children:[/* @__PURE__ */jsxRuntime.jsx(IconWrapper,{align:"center",children:/* @__PURE__ */jsxRuntime.jsx(IconBox,{padding:2,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:2,children:iconComponent&&React.createElement(iconComponent)})})}),/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:2,margin:2,children:[isLatest&&/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{children:/* @__PURE__ */jsxRuntime.jsx(ui.Card,{padding:1,radius:2,shadow:1,tone:isSelected?"primary":TIMELINE_ITEM_EVENT_TONE[chunk.type],children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:0,weight:"medium",children:t("timeline.latest")})})}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,weight:"medium",children:t(TIMELINE_ITEM_I18N_KEY_MAPPING[type])||/* @__PURE__ */jsxRuntime.jsx("code",{children:type})})}),/* @__PURE__ */jsxRuntime.jsx(TimestampBox,{paddingX:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{as:"time",size:0,muted:true,dateTime:timestamp,children:formattedTimestamp})})]}),/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{flex:1,justify:"flex-end",align:"center",children:/* @__PURE__ */jsxRuntime.jsx(UserAvatarStack,{maxLength:3,userIds:authorUserIds})})]})})});}var __freeze$c=Object.freeze;var __defProp$c=Object.defineProperty;var __template$c=(cooked,raw)=>__freeze$c(__defProp$c(cooked,"raw",{value:__freeze$c(raw||cooked.slice())}));var _a$c,_b$4,_c$1,_d;const StackWrapper=styled__default.default(ui.Stack)(_a$c||(_a$c=__template$c(["\n max-width: 200px;\n"])));const ListWrapper=styled__default.default(ui.Flex)(_b$4||(_b$4=__template$c(["\n max-height: calc(100vh - 198px);\n min-width: 244px;\n"])));const Root$4=styled__default.default(ui.Box)(_ref80=>{let{$visible}=_ref80;return styled.css(_d||(_d=__template$c(["\n opacity: 0;\n pointer-events: none;\n\n ","\n "])),$visible&&styled.css(_c$1||(_c$1=__template$c(["\n opacity: 1;\n pointer-events: auto;\n "]))));});const Timeline=_ref81=>{let{chunks,disabledBeforeFirstChunk,hasMoreChunks,lastChunk,onLoadMore,onSelect,firstChunk}=_ref81;const[mounted,setMounted]=React.useState(false);const{t}=sanity.useTranslation("studio");const filteredChunks=React.useMemo(()=>{return chunks.filter(c=>{if(disabledBeforeFirstChunk&&firstChunk){return c.index<firstChunk.index;}return true;});},[chunks,disabledBeforeFirstChunk,firstChunk]);const selectedIndex=React.useMemo(()=>(lastChunk==null?void 0:lastChunk.id)?filteredChunks.findIndex(c=>c.id===lastChunk.id):-1,[lastChunk==null?void 0:lastChunk.id,filteredChunks]);const renderItem=React.useCallback((chunk,_ref82)=>{let{activeIndex}=_ref82;const isFirst=activeIndex===0;const isLast=filteredChunks&&activeIndex===filteredChunks.length-1||false;return/* @__PURE__ */jsxRuntime.jsxs(ui.Box,{paddingBottom:isLast?1:0,paddingTop:isFirst?1:0,paddingX:1,children:[/* @__PURE__ */jsxRuntime.jsx(TimelineItem,{chunk,isFirst,isLast,isLatest:activeIndex===0&&!disabledBeforeFirstChunk,isSelected:activeIndex===selectedIndex,onSelect,timestamp:chunk.endTimestamp,type:chunk.type}),activeIndex===filteredChunks.length-1&&hasMoreChunks&&/* @__PURE__ */jsxRuntime.jsx(sanity.LoadingBlock,{})]});},[disabledBeforeFirstChunk,filteredChunks,hasMoreChunks,onSelect,selectedIndex]);React.useEffect(()=>setMounted(true),[]);return/* @__PURE__ */jsxRuntime.jsxs(Root$4,{$visible:!selectedIndex||mounted,"data-ui":"timeline",children:[filteredChunks.length===0&&/* @__PURE__ */jsxRuntime.jsxs(StackWrapper,{padding:3,space:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,weight:"medium",children:t("timeline.error.no-document-history-title")}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,children:t("timeline.error.no-document-history-description")})]}),filteredChunks.length>0&&/* @__PURE__ */jsxRuntime.jsx(ListWrapper,{direction:"column",children:/* @__PURE__ */jsxRuntime.jsx(sanity.CommandList,{activeItemDataAttr:"data-hovered",ariaLabel:t("timeline.list.aria-label"),autoFocus:"list",initialIndex:selectedIndex,initialScrollAlign:"center",itemHeight:40,items:filteredChunks,onEndReached:onLoadMore,onEndReachedIndexOffset:20,overscan:5,renderItem,wrapAround:false})})]});};Timeline.displayName="Timeline";function TimelineError(){const{t}=sanity.useTranslation("studio");return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"flex-start",gap:3,padding:4,children:[/* @__PURE__ */jsxRuntime.jsx(sanity.TextWithTone,{tone:"critical",children:/* @__PURE__ */jsxRuntime.jsx(icons.ErrorOutlineIcon,{})}),/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:4,children:[/* @__PURE__ */jsxRuntime.jsx(sanity.TextWithTone,{size:1,tone:"critical",weight:"medium",children:t("timeline.error.load-document-changes-title")}),/* @__PURE__ */jsxRuntime.jsx(sanity.TextWithTone,{size:1,tone:"critical",children:t("timeline.error.load-document-changes-description")})]})]});}var __freeze$b=Object.freeze;var __defProp$b=Object.defineProperty;var __template$b=(cooked,raw)=>__freeze$b(__defProp$b(cooked,"raw",{value:__freeze$b(raw||cooked.slice())}));var _a$b;const Root$3=styled__default.default(TooltipDelayGroupProvider.Popover)(_a$b||(_a$b=__template$b(["\n overflow: hidden;\n overflow: clip;\n"])));function TimelineMenu(_ref83){let{chunk,mode,placement}=_ref83;const{setTimelineRange,setTimelineMode,timelineError,ready,timelineStore}=useDocumentPane();const[open,setOpen]=React.useState(false);const[button,setButton]=React.useState(null);const[popover,setPopover]=React.useState(null);const toast=ui.useToast();const chunks=sanity.useTimelineSelector(timelineStore,state=>state.chunks);const loading=sanity.useTimelineSelector(timelineStore,state=>state.isLoading);const hasMoreChunks=sanity.useTimelineSelector(timelineStore,state=>state.hasMoreChunks);const realRevChunk=sanity.useTimelineSelector(timelineStore,state=>state.realRevChunk);const sinceTime=sanity.useTimelineSelector(timelineStore,state=>state.sinceTime);const{t}=sanity.useTranslation("studio");const handleOpen=React.useCallback(()=>{setTimelineMode(mode);setOpen(true);},[mode,setTimelineMode]);const handleClose=React.useCallback(()=>{setTimelineMode("closed");setOpen(false);},[setTimelineMode]);const handleClickOutside=React.useCallback(()=>{if(open){handleClose();}},[handleClose,open]);const handleGlobalKeyDown=React.useCallback(event=>{if(open&&(event.key==="Escape"||event.key==="Tab")){handleClose();button==null?void 0:button.focus();}},[button,handleClose,open]);ui.useClickOutside(handleClickOutside,[button,popover]);ui.useGlobalKeyDown(handleGlobalKeyDown);const selectRev=React.useCallback(revChunk=>{try{const[sinceId,revId]=timelineStore.findRangeForRev(revChunk);setTimelineMode("closed");setTimelineRange(sinceId,revId);}catch(err){toast.push({closable:true,description:err.message,status:"error",title:t("timeline.error.unable-to-load-revision")});}},[setTimelineMode,setTimelineRange,t,timelineStore,toast]);const selectSince=React.useCallback(sinceChunk=>{try{const[sinceId,revId]=timelineStore.findRangeForSince(sinceChunk);setTimelineMode("closed");setTimelineRange(sinceId,revId);}catch(err){toast.push({closable:true,description:err.message,status:"error",title:t("timeline.error.unable-to-load-revision")});}},[setTimelineMode,setTimelineRange,t,timelineStore,toast]);const handleLoadMore=React.useCallback(()=>{if(!loading){timelineStore.loadMore();}},[loading,timelineStore]);const content=timelineError?/* @__PURE__ */jsxRuntime.jsx(TimelineError,{}):/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[mode==="rev"&&/* @__PURE__ */jsxRuntime.jsx(Timeline,{chunks,firstChunk:realRevChunk,hasMoreChunks,lastChunk:realRevChunk,onLoadMore:handleLoadMore,onSelect:selectRev}),mode==="since"&&/* @__PURE__ */jsxRuntime.jsx(Timeline,{chunks,disabledBeforeFirstChunk:true,firstChunk:realRevChunk,hasMoreChunks,lastChunk:sinceTime,onLoadMore:handleLoadMore,onSelect:selectSince})]});const formatParams={timestamp:{dateStyle:"medium",timeStyle:"short"}};const revLabel=chunk?t(TIMELINE_ITEM_I18N_KEY_MAPPING[chunk.type],{context:"timestamp",timestamp:new Date(chunk==null?void 0:chunk.endTimestamp),formatParams}):t("timeline.latest-version");const sinceLabel=chunk?t("timeline.since",{timestamp:new Date(chunk==null?void 0:chunk.endTimestamp),formatParams}):t("timeline.since-version-missing");const buttonLabel=mode==="rev"?revLabel:sinceLabel;return/* @__PURE__ */jsxRuntime.jsx(Root$3,{constrainSize:true,content:open&&content,"data-ui":"versionMenu",open,placement,portal:true,ref:setPopover,children:/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{disabled:!ready,mode:"bleed",iconRight:icons.ChevronDownIcon,onClick:open?handleClose:handleOpen,ref:setButton,selected:open,style:{maxWidth:"100%"},text:ready?buttonLabel:t("timeline.loading-history")})});}const Root$2=styled__default.default(ui.Card)({position:"relative",zIndex:1,lineHeight:0});function DocumentInspectorHeader(props){const{as:forwardedAs,children,closeButtonLabel,onClose,title,...restProps}=props;const{t}=sanity.useTranslation(structureLocaleNamespace);return/* @__PURE__ */jsxRuntime.jsxs(Root$2,{...restProps,as:forwardedAs,children:[/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{padding:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,padding:3,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{as:"h1",size:1,weight:"medium",children:title})}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:"none",padding:1,children:/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{"aria-label":closeButtonLabel,icon:icons.CloseIcon,mode:"bleed",onClick:onClose,tooltipProps:{content:t("document-inspector.close-button.tooltip")}})})]}),children]});}var __freeze$a=Object.freeze;var __defProp$a=Object.defineProperty;var __template$a=(cooked,raw)=>__freeze$a(__defProp$a(cooked,"raw",{value:__freeze$a(raw||cooked.slice())}));var _a$a;const Root$1=styled__default.default.div(_a$a||(_a$a=__template$a(["\n position: absolute;\n top: 0;\n left: -4px;\n bottom: 0;\n width: 9px;\n z-index: 201;\n cursor: ew-resize;\n\n /* Border */\n & > span:nth-child(1) {\n display: block;\n border-left: 1px solid var(--card-border-color);\n position: absolute;\n top: 0;\n left: 4px;\n bottom: 0;\n transition: opacity 200ms;\n }\n\n /* Hover effect */\n & > span:nth-child(2) {\n display: block;\n position: absolute;\n top: 0;\n left: 0;\n width: 9px;\n bottom: 0;\n background-color: var(--card-border-color);\n opacity: 0;\n transition: opacity 150ms;\n }\n\n @media (hover: hover) {\n &:hover > span:nth-child(2) {\n opacity: 0.2;\n }\n }\n"])));function Resizer(props){const{onResize,onResizeStart}=props;const mouseXRef=React.useRef(0);const handleMouseDown=React.useCallback(event=>{event.preventDefault();mouseXRef.current=event.pageX;onResizeStart();const handleMouseMove=e=>{e.preventDefault();onResize(e.pageX-mouseXRef.current);};const handleMouseUp=()=>{window.removeEventListener("mousemove",handleMouseMove);window.removeEventListener("mouseup",handleMouseUp);};window.addEventListener("mousemove",handleMouseMove);window.addEventListener("mouseup",handleMouseUp);},[onResize,onResizeStart]);return/* @__PURE__ */jsxRuntime.jsxs(Root$1,{onMouseDown:handleMouseDown,children:[/* @__PURE__ */jsxRuntime.jsx("span",{}),/* @__PURE__ */jsxRuntime.jsx("span",{})]});}var __freeze$9=Object.freeze;var __defProp$9=Object.defineProperty;var __template$9=(cooked,raw)=>__freeze$9(__defProp$9(cooked,"raw",{value:__freeze$9(raw||cooked.slice())}));var _a$9;const Root=styled__default.default(ui.Box)(_a$9||(_a$9=__template$9(["\n position: relative;\n flex: 1;\n padding-left: 1px;\n"])));function Resizable(props){const{as:forwardedAs,children,minWidth,maxWidth,...restProps}=props;const[element,setElement]=React.useState(null);const elementWidthRef=React.useRef();const[targetWidth,setTargetWidth]=React.useState();const handleResizeStart=React.useCallback(()=>{elementWidthRef.current=element==null?void 0:element.offsetWidth;},[element]);const handleResize=React.useCallback(deltaX=>{const w=elementWidthRef.current;if(!w)return;setTargetWidth(Math.min(Math.max(w-deltaX,minWidth),maxWidth));},[minWidth,maxWidth]);const style=React.useMemo(()=>targetWidth?{flex:"none",width:targetWidth}:{minWidth,maxWidth},[minWidth,maxWidth,targetWidth]);return/* @__PURE__ */jsxRuntime.jsxs(Root,{as:forwardedAs,...restProps,ref:setElement,style,children:[children,/* @__PURE__ */jsxRuntime.jsx(Resizer,{onResize:handleResize,onResizeStart:handleResizeStart})]});}function DocumentInspectorPanel(props){const{documentId,documentType,flex}=props;const{collapsed}=usePane();const{closeInspector,inspector}=useDocumentPane();const{features}=useStructureTool();const handleClose=React.useCallback(()=>{if(inspector)closeInspector(inspector.name);},[closeInspector,inspector]);if(collapsed||!inspector)return null;const element=React.createElement(inspector.component,{onClose:handleClose,documentId,documentType});if(features.resizablePanes){return/* @__PURE__ */jsxRuntime.jsx(Resizable,{as:"aside","data-ui":"DocumentInspectorPanel",flex,maxWidth:DOCUMENT_INSPECTOR_MAX_WIDTH,minWidth:DOCUMENT_INSPECTOR_MIN_WIDTH,children:element});}return/* @__PURE__ */jsxRuntime.jsx(ui.Box,{as:"aside","data-ui":"DocumentInspectorPanel",flex,children:element});}function collectLatestAuthorAnnotations(diff){const authorMap=/* @__PURE__ */new Map();sanity.visitDiff(diff,child=>{if(child.action==="unchanged"||!("annotation"in child)||!child.annotation){return true;}const{author,timestamp}=child.annotation;const previous=authorMap.get(author);if(!previous||previous.timestamp<timestamp){authorMap.set(author,child.annotation);}return true;});return Array.from(authorMap.values()).sort((a,b)=>a.timestamp<b.timestamp?1:-1);}var __freeze$8=Object.freeze;var __defProp$8=Object.defineProperty;var __template$8=(cooked,raw)=>__freeze$8(__defProp$8(cooked,"raw",{value:__freeze$8(raw||cooked.slice())}));var _a$8;const Scroller$1=styled__default.default(sanity.ScrollContainer)(_a$8||(_a$8=__template$8(["\n height: 100%;\n overflow: auto;\n position: relative;\n scroll-behavior: smooth;\n"])));function ChangesInspector(props){const{onClose}=props;const{documentId,schemaType,timelineError,timelineStore,value}=useDocumentPane();const scrollRef=React.useRef(null);const diff=sanity.useTimelineSelector(timelineStore,state=>state.diff);const onOlderRevision=sanity.useTimelineSelector(timelineStore,state=>state.onOlderRevision);const selectionState=sanity.useTimelineSelector(timelineStore,state=>state.selectionState);const sinceTime=sanity.useTimelineSelector(timelineStore,state=>state.sinceTime);const loading=selectionState==="loading";const isComparingCurrent=!onOlderRevision;const{t}=sanity.useTranslation("studio");const documentContext=React__default.default.useMemo(()=>({documentId,schemaType,FieldWrapper:sanity.ChangeFieldWrapper,rootDiff:diff,isComparingCurrent,value}),[documentId,diff,isComparingCurrent,schemaType,value]);const changeAnnotations=React__default.default.useMemo(()=>diff?collectLatestAuthorAnnotations(diff):[],[diff]);return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{"data-testid":"review-changes-pane",direction:"column",height:"fill",overflow:"hidden",children:[/* @__PURE__ */jsxRuntime.jsx(DocumentInspectorHeader,{as:"header",closeButtonLabel:t("changes.action.close-label"),flex:"none",onClose,title:t("changes.title"),children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:1,padding:3,paddingTop:0,paddingBottom:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,children:/* @__PURE__ */jsxRuntime.jsx(TimelineMenu,{mode:"since",chunk:sinceTime,placement:"bottom-start"})}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:"none",children:/* @__PURE__ */jsxRuntime.jsx(sanity.DiffTooltip,{annotations:changeAnnotations,description:t("changes.changes-by-author"),portal:true,children:/* @__PURE__ */jsxRuntime.jsx(ui.AvatarStack,{maxLength:4,"aria-label":t("changes.changes-by-author"),children:changeAnnotations.map(_ref84=>{let{author}=_ref84;return/* @__PURE__ */jsxRuntime.jsx(sanity.UserAvatar,{user:author},author);})})})})]})}),/* @__PURE__ */jsxRuntime.jsx(ui.Card,{flex:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.BoundaryElementProvider,{element:scrollRef.current,children:/* @__PURE__ */jsxRuntime.jsx(Scroller$1,{"data-ui":"Scroller",ref:scrollRef,children:/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,padding:4,children:/* @__PURE__ */jsxRuntime.jsx(Content$1,{diff,documentContext,error:timelineError,loading,schemaType})})})})})]});}function Content$1(_ref85){let{error,diff,documentContext,loading,schemaType}=_ref85;if(error){return/* @__PURE__ */jsxRuntime.jsx(sanity.NoChanges,{});}if(loading){return/* @__PURE__ */jsxRuntime.jsx(sanity.LoadingBlock,{showText:true});}if(!diff){return/* @__PURE__ */jsxRuntime.jsx(sanity.NoChanges,{});}return/* @__PURE__ */jsxRuntime.jsx(sanity.DocumentChangeContext.Provider,{value:documentContext,children:/* @__PURE__ */jsxRuntime.jsx(sanity.ChangeList,{diff,schemaType})});}const changesInspector={name:HISTORY_INSPECTOR_NAME,useMenuItem:()=>{const{features}=useStructureTool();const{t}=sanity.useTranslation();return{hidden:!features.reviewChanges,icon:icons.RestoreIcon,title:t("changes.title")};},component:ChangesInspector,onClose:_ref86=>{let{params}=_ref86;return{params:{...params,since:void 0}};},onOpen:_ref87=>{let{params}=_ref87;return{params:{...params,since:"@lastPublished"}};}};function getPathTitles(options){const{path,schemaType,value}=options;const result=[];let s=schemaType;let v=value;for(const segment of path){if(typeof segment==="string"){if(!sanity.isRecord(v)&&v!==void 0){throw new Error("Parent value is not an object, cannot get path segment: .".concat(segment));}if(s.jsonType!=="object"){throw new Error("Parent type is not an object schema type, cannot get path segment: .".concat(segment));}v=v==null?void 0:v[segment];const field=s.fields.find(f=>f.name===segment);if(!field){result.push({name:segment});return result;}s=field.type;result.push(s);continue;}if(typeof segment==="number"){if(!sanity.isArray(v)&&v!==void 0){throw new Error("Parent value is not an array, cannot get path segment: [".concat(segment,"]"));}if(s.jsonType!=="array"){throw new Error("Parent type is not an array schema type, cannot get path segment: [".concat(segment,"]"));}v=v==null?void 0:v[segment];const itemType=s.of.find(ofType=>{if(typeof v==="string"){return ofType.jsonType==="string";}if(typeof v==="number"){return ofType.jsonType==="number";}if(typeof v==="boolean"){return ofType.jsonType==="boolean";}if(sanity.isRecord(v)){return ofType.name===(v==null?void 0:v._type);}return false;});if(!itemType){throw new Error("Item type not found: [".concat(segment,"]"));}s=itemType;result.push(s);continue;}if(sanity.isRecord(segment)&&segment._key){if(!sanity.isArray(v)){throw new Error("Parent value is not an array, cannot get path segment: [_key == ".concat(segment,"]"));}if(s.jsonType!=="array"){throw new Error("Parent type is not an array schema type, cannot get path segment: .".concat(segment));}const values=v!=null?v:[];v=values.find(i=>sanity.isRecord(i)&&i._key===segment._key);if(!sanity.isRecord(v)){throw new Error("Array item not found: [_key == ".concat(segment._key,"]"));}const ofType=s.of.find(i=>sanity.isRecord(v)&&i.name===(v==null?void 0:v._type));if(!ofType){throw new Error("Array item type not found: .".concat(v==null?void 0:v._type));}s=ofType;result.push(s);continue;}throw new Error("Invalid path segment: ".concat(JSON.stringify(segment)));}return result;}const MARKER_ICON={error:icons.ErrorOutlineIcon,warning:icons.WarningOutlineIcon,info:icons.InfoOutlineIcon};const MARKER_TONE={error:"critical",warning:"caution",info:"primary"};function ValidationInspector(props){const{onClose}=props;const{onFocus,onPathOpen,schemaType,validation,value}=useDocumentPane();const{t}=sanity.useTranslation("validation");const handleOpen=React.useCallback(path=>{onPathOpen(path);onFocus(path);},[onFocus,onPathOpen]);return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{direction:"column",height:"fill",overflow:"hidden",children:[/* @__PURE__ */jsxRuntime.jsx(DocumentInspectorHeader,{as:"header",closeButtonLabel:t("panel.close-button-aria-label"),flex:"none",onClose,title:t("panel.title")}),/* @__PURE__ */jsxRuntime.jsxs(ui.Card,{flex:1,overflow:"auto",padding:3,children:[validation.length===0&&/* @__PURE__ */jsxRuntime.jsx(ui.Box,{padding:2,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,children:t("panel.no-errors-message")})}),validation.length>0&&/* @__PURE__ */jsxRuntime.jsx(ui.Stack,{space:2,children:validation.map((marker,i)=>/* @__PURE__ */jsxRuntime.jsx(ValidationCard,{marker,onOpen:handleOpen,schemaType,value},i))})]})]});}function ValidationCard(props){const{marker,onOpen,schemaType,value}=props;const handleOpen=React.useCallback(()=>onOpen(marker.path),[marker,onOpen]);const[errorInfo,setErrorInfo]=React.useState(null);return/* @__PURE__ */jsxRuntime.jsxs(ui.ErrorBoundary,{onCatch:setErrorInfo,children:[errorInfo&&/* @__PURE__ */jsxRuntime.jsx(ui.Card,{padding:3,radius:2,tone:"critical",children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:errorInfo.error.message})}),!errorInfo&&/* @__PURE__ */jsxRuntime.jsx(ui.Card,{__unstable_focusRing:true,as:"button",onClick:handleOpen,padding:3,radius:2,tone:MARKER_TONE[marker.level],children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"flex-start",gap:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:"none",children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:React.createElement(MARKER_ICON[marker.level])})}),/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{flex:1,space:2,children:[/* @__PURE__ */jsxRuntime.jsx(DocumentNodePathBreadcrumbs,{path:marker.path,schemaType,value}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,children:marker.message})]})]})})]});}function DocumentNodePathBreadcrumbs(props){const{path,schemaType,value}=props;const pathTitles=React.useMemo(()=>getPathTitles({path,schemaType,value}),[path,schemaType,value]);if(!pathTitles.length)return null;return/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:pathTitles.map((t,i)=>/* @__PURE__ */jsxRuntime.jsxs(React.Fragment,{children:[i>0&&/* @__PURE__ */jsxRuntime.jsx("span",{style:{color:"var(--card-muted-fg-color)",opacity:0.5},children:" / "}),/* @__PURE__ */jsxRuntime.jsx("span",{style:{fontWeight:500},children:t.title||t.name})]},i))});}function useMenuItem(props){const{documentId,documentType}=props;const{t}=sanity.useTranslation("validation");const{validation:validationMarkers}=sanity.useValidationStatus(documentId,documentType);const validation=React.useMemo(()=>validationMarkers.map(item=>({level:item.level,message:item.message,path:item.path})),[validationMarkers]);const hasErrors=validation.some(sanity.isValidationError);const hasWarnings=validation.some(sanity.isValidationWarning);const icon=React.useMemo(()=>{if(hasErrors)return icons.ErrorOutlineIcon;if(hasWarnings)return icons.WarningOutlineIcon;return icons.CheckmarkCircleIcon;},[hasErrors,hasWarnings]);const tone=React.useMemo(()=>{if(hasErrors)return"critical";if(hasWarnings)return"caution";return"positive";},[hasErrors,hasWarnings]);return{hidden:validation.length===0,icon,title:t("panel.title"),tone,showAsAction:true};}const validationInspector={name:VALIDATION_INSPECTOR_NAME,component:ValidationInspector,useMenuItem};const documentActions=[PublishAction,UnpublishAction,DiscardChangesAction,DuplicateAction,DeleteAction,HistoryRestoreAction];const documentBadges=[LiveEditBadge];const inspectors=[validationInspector,changesInspector];const structureTool=sanity.definePlugin(options=>{const icon=(options==null?void 0:options.icon)||icons.MasterDetailIcon;return{name:"sanity/structure",document:{actions:prevActions=>{return Array.from(/* @__PURE__ */new Set([...prevActions,...documentActions]));},badges:prevBadges=>{return Array.from(/* @__PURE__ */new Set([...prevBadges,...documentBadges]));},inspectors:prevInspectors=>{return Array.from(/* @__PURE__ */new Set([...prevInspectors,...inspectors]));}},plugins:[comments()],tools:[{name:(options==null?void 0:options.name)||"structure",title:(options==null?void 0:options.title)||"Structure",icon,component:React.lazy(()=>Promise.resolve().then(function(){return require('./index-FQCCBbuC.js');})),canHandleIntent:(intent,params)=>{if(intent==="create")return canHandleCreateIntent(params);if(intent==="edit")return canHandleEditIntent(params);return false;},getIntentState,// Controlled by sanity/src/structure/components/structureTool/StructureTitle.tsx
43
+ __internal_comments:internalComments}),/* @__PURE__ */jsxRuntime.jsx(framerMotion.AnimatePresence,{children:isSelected&&/* @__PURE__ */jsxRuntime.jsx(HighlightDiv,{animate:"animate",exit:"exit",initial:"initial",variants:HIGHLIGHT_BLOCK_VARIANTS})})]});}function CommentsDocumentLayout(props){const{documentId,documentType}=props;return/* @__PURE__ */jsxRuntime.jsx(CommentsEnabledProvider,{documentId,documentType,children:/* @__PURE__ */jsxRuntime.jsx(CommentsDocumentLayoutInner,{...props})});}function CommentsDocumentLayoutInner(props){const{documentId,documentType}=props;const commentsEnabled=useCommentsEnabled();const{openInspector,inspector}=useDocumentPane();const handleOpenCommentsInspector=React.useCallback(()=>{if((inspector==null?void 0:inspector.name)===COMMENTS_INSPECTOR_NAME)return;openInspector(COMMENTS_INSPECTOR_NAME);},[inspector==null?void 0:inspector.name,openInspector]);if(!commentsEnabled){return props.renderDefault(props);}return/* @__PURE__ */jsxRuntime.jsx(CommentsProvider,{documentId,documentType,isCommentsOpen:(inspector==null?void 0:inspector.name)===COMMENTS_INSPECTOR_NAME,onCommentsOpen:handleOpenCommentsInspector,children:/* @__PURE__ */jsxRuntime.jsx(CommentsSelectedPathProvider,{children:props.renderDefault(props)})});}function CommentsStudioLayout(props){return/* @__PURE__ */jsxRuntime.jsx(CommentsSetupProvider,{children:/* @__PURE__ */jsxRuntime.jsx(CommentsOnboardingProvider,{children:props.renderDefault(props)})});}const comments=sanity.definePlugin({name:"sanity/structure/comments",document:{inspectors:[commentsInspector],components:{unstable_layout:CommentsDocumentLayout}},form:{components:{field:CommentsField}},studio:{components:{layout:CommentsStudioLayout}},i18n:{bundles:[commentsUsEnglishLocaleBundle]}});const StructureToolContext=React.createContext(null);function useStructureTool(){const structureTool=React.useContext(StructureToolContext);if(!structureTool)throw new Error("StructureTool: missing context value");return structureTool;}const TIMELINE_ICON_COMPONENTS={create:icons.AddCircleIcon,delete:icons.TrashIcon,discardDraft:icons.CloseIcon,initial:icons.AddCircleIcon,editDraft:icons.EditIcon,editLive:icons.EditIcon,publish:icons.PublishIcon,unpublish:icons.UnpublishIcon};function getTimelineEventIconComponent(type){return TIMELINE_ICON_COMPONENTS[type];}function UserAvatarStack(_ref75){let{maxLength,userIds}=_ref75;return/* @__PURE__ */jsxRuntime.jsx(ui.AvatarStack,{maxLength,children:userIds.map(userId=>/* @__PURE__ */jsxRuntime.jsx(sanity.UserAvatar,{user:userId,withTooltip:true},userId))});}var __freeze$d=Object.freeze;var __defProp$d=Object.defineProperty;var __template$d=(cooked,raw)=>__freeze$d(__defProp$d(cooked,"raw",{value:__freeze$d(raw||cooked.slice())}));var _a$d,_b$5,_c$2,_d$1,_e,_f;const IconWrapper=styled__default.default(ui.Flex)(_ref76=>{let{theme}=_ref76;var _a2;const borderColor=(_a2=theme.sanity.color.base.skeleton)==null?void 0:_a2.from;return styled.css(_a$d||(_a$d=__template$d(["\n --timeline-hairline-width: 1px;\n position: relative;\n z-index: 2;\n margin: 0;\n padding: 0;\n\n &::before {\n position: absolute;\n content: '';\n height: 100%;\n width: var(--timeline-hairline-width);\n background: ",";\n top: 0;\n left: calc((100% - var(--timeline-hairline-width)) / 2);\n z-index: 1;\n }\n "])),borderColor);});const Root$5=styled__default.default(ui.Button)(_ref77=>{let{$selected,$disabled}=_ref77;return styled.css(_d$1||(_d$1=__template$d(["\n position: relative;\n width: 100%;\n\n /* Line styling */\n &[data-first] ","::before {\n height: 50%;\n top: unset;\n bottom: 0;\n }\n\n &[data-last] ","::before {\n height: 50%;\n }\n\n ","\n\n ","\n "])),IconWrapper,IconWrapper,$selected&&styled.css(_b$5||(_b$5=__template$d(["\n ","::before {\n background: transparent;\n }\n "])),IconWrapper),$disabled&&styled.css(_c$2||(_c$2=__template$d(["\n cursor: not-allowed;\n "]))));});const IconBox=styled__default.default(ui.Box)(_e||(_e=__template$d(["\n background: var(--card-bg-color);\n border-radius: 50px;\n position: relative;\n z-index: 2;\n"])));const TimestampBox=styled__default.default(ui.Box)(_f||(_f=__template$d(["\n min-width: 1rem;\n margin-left: ",";\n"])),_ref78=>{let{theme}=_ref78;return"-".concat(ui.rem(theme.sanity.space[1]));});const TIMELINE_ITEM_I18N_KEY_MAPPING={initial:"timeline.operation.created-initial",create:"timeline.operation.created",publish:"timeline.operation.published",editLive:"timeline.operation.edited-live",editDraft:"timeline.operation.edited-draft",unpublish:"timeline.operation.unpublished",discardDraft:"timeline.operation.draft-discarded",delete:"timeline.operation.deleted"};const TIMELINE_ITEM_EVENT_TONE={initial:"primary",create:"primary",publish:"positive",editLive:"caution",editDraft:"caution",unpublish:"critical",discardDraft:"critical",delete:"critical",withinSelection:"primary"};function TimelineItem(_ref79){let{chunk,isFirst,isLast,isLatest,isSelected,onSelect,timestamp,type}=_ref79;const{t}=sanity.useTranslation("studio");const iconComponent=getTimelineEventIconComponent(type);const authorUserIds=Array.from(chunk.authors);const isSelectable=type!=="delete";const dateFormat=sanity.useDateTimeFormat({dateStyle:"medium",timeStyle:"short"});const formattedTimestamp=React.useMemo(()=>{const parsedDate=new Date(timestamp);const formattedDate=dateFormat.format(parsedDate);return formattedDate;},[timestamp,dateFormat]);const handleClick=React.useCallback(evt=>{evt.preventDefault();evt.stopPropagation();if(isSelectable){onSelect(chunk);}},[onSelect,chunk,isSelectable]);return/* @__PURE__ */jsxRuntime.jsx(Root$5,{$selected:isSelected,$disabled:!isSelectable,"data-chunk-id":chunk.id,"data-first":isFirst?true:void 0,"data-last":isLast?true:void 0,"data-ui":"timelineItem",mode:isSelected?"default":"bleed",onClick:handleClick,padding:0,radius:2,tone:isSelected?"primary":TIMELINE_ITEM_EVENT_TONE[chunk.type],children:/* @__PURE__ */jsxRuntime.jsx(ui.Box,{paddingX:2,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"stretch",children:[/* @__PURE__ */jsxRuntime.jsx(IconWrapper,{align:"center",children:/* @__PURE__ */jsxRuntime.jsx(IconBox,{padding:2,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:2,children:iconComponent&&React.createElement(iconComponent)})})}),/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:2,margin:2,children:[isLatest&&/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{children:/* @__PURE__ */jsxRuntime.jsx(ui.Card,{padding:1,radius:2,shadow:1,tone:isSelected?"primary":TIMELINE_ITEM_EVENT_TONE[chunk.type],children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:0,weight:"medium",children:t("timeline.latest")})})}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,weight:"medium",children:t(TIMELINE_ITEM_I18N_KEY_MAPPING[type])||/* @__PURE__ */jsxRuntime.jsx("code",{children:type})})}),/* @__PURE__ */jsxRuntime.jsx(TimestampBox,{paddingX:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{as:"time",size:0,muted:true,dateTime:timestamp,children:formattedTimestamp})})]}),/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{flex:1,justify:"flex-end",align:"center",children:/* @__PURE__ */jsxRuntime.jsx(UserAvatarStack,{maxLength:3,userIds:authorUserIds})})]})})});}var __freeze$c=Object.freeze;var __defProp$c=Object.defineProperty;var __template$c=(cooked,raw)=>__freeze$c(__defProp$c(cooked,"raw",{value:__freeze$c(raw||cooked.slice())}));var _a$c,_b$4,_c$1,_d;const StackWrapper=styled__default.default(ui.Stack)(_a$c||(_a$c=__template$c(["\n max-width: 200px;\n"])));const ListWrapper=styled__default.default(ui.Flex)(_b$4||(_b$4=__template$c(["\n max-height: calc(100vh - 198px);\n min-width: 244px;\n"])));const Root$4=styled__default.default(ui.Box)(_ref80=>{let{$visible}=_ref80;return styled.css(_d||(_d=__template$c(["\n opacity: 0;\n pointer-events: none;\n\n ","\n "])),$visible&&styled.css(_c$1||(_c$1=__template$c(["\n opacity: 1;\n pointer-events: auto;\n "]))));});const Timeline=_ref81=>{let{chunks,disabledBeforeFirstChunk,hasMoreChunks,lastChunk,onLoadMore,onSelect,firstChunk}=_ref81;const[mounted,setMounted]=React.useState(false);const{t}=sanity.useTranslation("studio");const filteredChunks=React.useMemo(()=>{return chunks.filter(c=>{if(disabledBeforeFirstChunk&&firstChunk){return c.index<firstChunk.index;}return true;});},[chunks,disabledBeforeFirstChunk,firstChunk]);const selectedIndex=React.useMemo(()=>(lastChunk==null?void 0:lastChunk.id)?filteredChunks.findIndex(c=>c.id===lastChunk.id):-1,[lastChunk==null?void 0:lastChunk.id,filteredChunks]);const renderItem=React.useCallback((chunk,_ref82)=>{let{activeIndex}=_ref82;const isFirst=activeIndex===0;const isLast=filteredChunks&&activeIndex===filteredChunks.length-1||false;return/* @__PURE__ */jsxRuntime.jsxs(ui.Box,{paddingBottom:isLast?1:0,paddingTop:isFirst?1:0,paddingX:1,children:[/* @__PURE__ */jsxRuntime.jsx(TimelineItem,{chunk,isFirst,isLast,isLatest:activeIndex===0&&!disabledBeforeFirstChunk,isSelected:activeIndex===selectedIndex,onSelect,timestamp:chunk.endTimestamp,type:chunk.type}),activeIndex===filteredChunks.length-1&&hasMoreChunks&&/* @__PURE__ */jsxRuntime.jsx(sanity.LoadingBlock,{})]});},[disabledBeforeFirstChunk,filteredChunks,hasMoreChunks,onSelect,selectedIndex]);React.useEffect(()=>setMounted(true),[]);return/* @__PURE__ */jsxRuntime.jsxs(Root$4,{$visible:!selectedIndex||mounted,"data-ui":"timeline",children:[filteredChunks.length===0&&/* @__PURE__ */jsxRuntime.jsxs(StackWrapper,{padding:3,space:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,weight:"medium",children:t("timeline.error.no-document-history-title")}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,children:t("timeline.error.no-document-history-description")})]}),filteredChunks.length>0&&/* @__PURE__ */jsxRuntime.jsx(ListWrapper,{direction:"column",children:/* @__PURE__ */jsxRuntime.jsx(sanity.CommandList,{activeItemDataAttr:"data-hovered",ariaLabel:t("timeline.list.aria-label"),autoFocus:"list",initialIndex:selectedIndex,initialScrollAlign:"center",itemHeight:40,items:filteredChunks,onEndReached:onLoadMore,onEndReachedIndexOffset:20,overscan:5,renderItem,wrapAround:false})})]});};Timeline.displayName="Timeline";function TimelineError(){const{t}=sanity.useTranslation("studio");return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"flex-start",gap:3,padding:4,children:[/* @__PURE__ */jsxRuntime.jsx(sanity.TextWithTone,{tone:"critical",children:/* @__PURE__ */jsxRuntime.jsx(icons.ErrorOutlineIcon,{})}),/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:4,children:[/* @__PURE__ */jsxRuntime.jsx(sanity.TextWithTone,{size:1,tone:"critical",weight:"medium",children:t("timeline.error.load-document-changes-title")}),/* @__PURE__ */jsxRuntime.jsx(sanity.TextWithTone,{size:1,tone:"critical",children:t("timeline.error.load-document-changes-description")})]})]});}var __freeze$b=Object.freeze;var __defProp$b=Object.defineProperty;var __template$b=(cooked,raw)=>__freeze$b(__defProp$b(cooked,"raw",{value:__freeze$b(raw||cooked.slice())}));var _a$b;const Root$3=styled__default.default(TooltipDelayGroupProvider.Popover)(_a$b||(_a$b=__template$b(["\n overflow: hidden;\n overflow: clip;\n"])));function TimelineMenu(_ref83){let{chunk,mode,placement}=_ref83;const{setTimelineRange,setTimelineMode,timelineError,ready,timelineStore}=useDocumentPane();const[open,setOpen]=React.useState(false);const[button,setButton]=React.useState(null);const[popover,setPopover]=React.useState(null);const toast=ui.useToast();const chunks=sanity.useTimelineSelector(timelineStore,state=>state.chunks);const loading=sanity.useTimelineSelector(timelineStore,state=>state.isLoading);const hasMoreChunks=sanity.useTimelineSelector(timelineStore,state=>state.hasMoreChunks);const realRevChunk=sanity.useTimelineSelector(timelineStore,state=>state.realRevChunk);const sinceTime=sanity.useTimelineSelector(timelineStore,state=>state.sinceTime);const{t}=sanity.useTranslation("studio");const handleOpen=React.useCallback(()=>{setTimelineMode(mode);setOpen(true);},[mode,setTimelineMode]);const handleClose=React.useCallback(()=>{setTimelineMode("closed");setOpen(false);},[setTimelineMode]);const handleClickOutside=React.useCallback(()=>{if(open){handleClose();}},[handleClose,open]);const handleGlobalKeyDown=React.useCallback(event=>{if(open&&(event.key==="Escape"||event.key==="Tab")){handleClose();button==null?void 0:button.focus();}},[button,handleClose,open]);ui.useClickOutside(handleClickOutside,[button,popover]);ui.useGlobalKeyDown(handleGlobalKeyDown);const selectRev=React.useCallback(revChunk=>{try{const[sinceId,revId]=timelineStore.findRangeForRev(revChunk);setTimelineMode("closed");setTimelineRange(sinceId,revId);}catch(err){toast.push({closable:true,description:err.message,status:"error",title:t("timeline.error.unable-to-load-revision")});}},[setTimelineMode,setTimelineRange,t,timelineStore,toast]);const selectSince=React.useCallback(sinceChunk=>{try{const[sinceId,revId]=timelineStore.findRangeForSince(sinceChunk);setTimelineMode("closed");setTimelineRange(sinceId,revId);}catch(err){toast.push({closable:true,description:err.message,status:"error",title:t("timeline.error.unable-to-load-revision")});}},[setTimelineMode,setTimelineRange,t,timelineStore,toast]);const handleLoadMore=React.useCallback(()=>{if(!loading){timelineStore.loadMore();}},[loading,timelineStore]);const content=timelineError?/* @__PURE__ */jsxRuntime.jsx(TimelineError,{}):/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[mode==="rev"&&/* @__PURE__ */jsxRuntime.jsx(Timeline,{chunks,firstChunk:realRevChunk,hasMoreChunks,lastChunk:realRevChunk,onLoadMore:handleLoadMore,onSelect:selectRev}),mode==="since"&&/* @__PURE__ */jsxRuntime.jsx(Timeline,{chunks,disabledBeforeFirstChunk:true,firstChunk:realRevChunk,hasMoreChunks,lastChunk:sinceTime,onLoadMore:handleLoadMore,onSelect:selectSince})]});const formatParams={timestamp:{dateStyle:"medium",timeStyle:"short"}};const revLabel=chunk?t(TIMELINE_ITEM_I18N_KEY_MAPPING[chunk.type],{context:"timestamp",timestamp:new Date(chunk==null?void 0:chunk.endTimestamp),formatParams}):t("timeline.latest-version");const sinceLabel=chunk?t("timeline.since",{timestamp:new Date(chunk==null?void 0:chunk.endTimestamp),formatParams}):t("timeline.since-version-missing");const buttonLabel=mode==="rev"?revLabel:sinceLabel;return/* @__PURE__ */jsxRuntime.jsx(Root$3,{constrainSize:true,content:open&&content,"data-ui":"versionMenu",open,placement,portal:true,ref:setPopover,children:/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{disabled:!ready,mode:"bleed",iconRight:icons.ChevronDownIcon,onClick:open?handleClose:handleOpen,ref:setButton,selected:open,style:{maxWidth:"100%"},text:ready?buttonLabel:t("timeline.loading-history")})});}const Root$2=styled__default.default(ui.Card)({position:"relative",zIndex:1,lineHeight:0});function DocumentInspectorHeader(props){const{as:forwardedAs,children,closeButtonLabel,onClose,title,...restProps}=props;const{t}=sanity.useTranslation(structureLocaleNamespace);return/* @__PURE__ */jsxRuntime.jsxs(Root$2,{...restProps,as:forwardedAs,children:[/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{padding:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,padding:3,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{as:"h1",size:1,weight:"medium",children:title})}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:"none",padding:1,children:/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{"aria-label":closeButtonLabel,icon:icons.CloseIcon,mode:"bleed",onClick:onClose,tooltipProps:{content:t("document-inspector.close-button.tooltip")}})})]}),children]});}var __freeze$a=Object.freeze;var __defProp$a=Object.defineProperty;var __template$a=(cooked,raw)=>__freeze$a(__defProp$a(cooked,"raw",{value:__freeze$a(raw||cooked.slice())}));var _a$a;const Root$1=styled__default.default.div(_a$a||(_a$a=__template$a(["\n position: absolute;\n top: 0;\n left: -4px;\n bottom: 0;\n width: 9px;\n z-index: 201;\n cursor: ew-resize;\n\n /* Border */\n & > span:nth-child(1) {\n display: block;\n border-left: 1px solid var(--card-border-color);\n position: absolute;\n top: 0;\n left: 4px;\n bottom: 0;\n transition: opacity 200ms;\n }\n\n /* Hover effect */\n & > span:nth-child(2) {\n display: block;\n position: absolute;\n top: 0;\n left: 0;\n width: 9px;\n bottom: 0;\n background-color: var(--card-border-color);\n opacity: 0;\n transition: opacity 150ms;\n }\n\n @media (hover: hover) {\n &:hover > span:nth-child(2) {\n opacity: 0.2;\n }\n }\n"])));function Resizer(props){const{onResize,onResizeStart}=props;const mouseXRef=React.useRef(0);const handleMouseDown=React.useCallback(event=>{event.preventDefault();mouseXRef.current=event.pageX;onResizeStart();const handleMouseMove=e=>{e.preventDefault();onResize(e.pageX-mouseXRef.current);};const handleMouseUp=()=>{window.removeEventListener("mousemove",handleMouseMove);window.removeEventListener("mouseup",handleMouseUp);};window.addEventListener("mousemove",handleMouseMove);window.addEventListener("mouseup",handleMouseUp);},[onResize,onResizeStart]);return/* @__PURE__ */jsxRuntime.jsxs(Root$1,{onMouseDown:handleMouseDown,children:[/* @__PURE__ */jsxRuntime.jsx("span",{}),/* @__PURE__ */jsxRuntime.jsx("span",{})]});}var __freeze$9=Object.freeze;var __defProp$9=Object.defineProperty;var __template$9=(cooked,raw)=>__freeze$9(__defProp$9(cooked,"raw",{value:__freeze$9(raw||cooked.slice())}));var _a$9;const Root=styled__default.default(ui.Box)(_a$9||(_a$9=__template$9(["\n position: relative;\n flex: 1;\n padding-left: 1px;\n"])));function Resizable(props){const{as:forwardedAs,children,minWidth,maxWidth,...restProps}=props;const[element,setElement]=React.useState(null);const elementWidthRef=React.useRef();const[targetWidth,setTargetWidth]=React.useState();const handleResizeStart=React.useCallback(()=>{elementWidthRef.current=element==null?void 0:element.offsetWidth;},[element]);const handleResize=React.useCallback(deltaX=>{const w=elementWidthRef.current;if(!w)return;setTargetWidth(Math.min(Math.max(w-deltaX,minWidth),maxWidth));},[minWidth,maxWidth]);const style=React.useMemo(()=>targetWidth?{flex:"none",width:targetWidth}:{minWidth,maxWidth},[minWidth,maxWidth,targetWidth]);return/* @__PURE__ */jsxRuntime.jsxs(Root,{as:forwardedAs,...restProps,ref:setElement,style,children:[children,/* @__PURE__ */jsxRuntime.jsx(Resizer,{onResize:handleResize,onResizeStart:handleResizeStart})]});}function DocumentInspectorPanel(props){const{documentId,documentType,flex}=props;const{collapsed}=usePane();const{closeInspector,inspector}=useDocumentPane();const{features}=useStructureTool();const handleClose=React.useCallback(()=>{if(inspector)closeInspector(inspector.name);},[closeInspector,inspector]);if(collapsed||!inspector)return null;const element=React.createElement(inspector.component,{onClose:handleClose,documentId,documentType});if(features.resizablePanes){return/* @__PURE__ */jsxRuntime.jsx(Resizable,{as:"aside","data-ui":"DocumentInspectorPanel",flex,maxWidth:DOCUMENT_INSPECTOR_MAX_WIDTH,minWidth:DOCUMENT_INSPECTOR_MIN_WIDTH,children:element});}return/* @__PURE__ */jsxRuntime.jsx(ui.Box,{as:"aside","data-ui":"DocumentInspectorPanel",flex,children:element});}function collectLatestAuthorAnnotations(diff){const authorMap=/* @__PURE__ */new Map();sanity.visitDiff(diff,child=>{if(child.action==="unchanged"||!("annotation"in child)||!child.annotation){return true;}const{author,timestamp}=child.annotation;const previous=authorMap.get(author);if(!previous||previous.timestamp<timestamp){authorMap.set(author,child.annotation);}return true;});return Array.from(authorMap.values()).sort((a,b)=>a.timestamp<b.timestamp?1:-1);}var __freeze$8=Object.freeze;var __defProp$8=Object.defineProperty;var __template$8=(cooked,raw)=>__freeze$8(__defProp$8(cooked,"raw",{value:__freeze$8(raw||cooked.slice())}));var _a$8;const Scroller$1=styled__default.default(sanity.ScrollContainer)(_a$8||(_a$8=__template$8(["\n height: 100%;\n overflow: auto;\n position: relative;\n scroll-behavior: smooth;\n"])));function ChangesInspector(props){const{onClose}=props;const{documentId,schemaType,timelineError,timelineStore,value}=useDocumentPane();const scrollRef=React.useRef(null);const diff=sanity.useTimelineSelector(timelineStore,state=>state.diff);const onOlderRevision=sanity.useTimelineSelector(timelineStore,state=>state.onOlderRevision);const selectionState=sanity.useTimelineSelector(timelineStore,state=>state.selectionState);const sinceTime=sanity.useTimelineSelector(timelineStore,state=>state.sinceTime);const loading=selectionState==="loading";const isComparingCurrent=!onOlderRevision;const{t}=sanity.useTranslation("studio");const documentContext=React__default.default.useMemo(()=>({documentId,schemaType,FieldWrapper:sanity.ChangeFieldWrapper,rootDiff:diff,isComparingCurrent,value}),[documentId,diff,isComparingCurrent,schemaType,value]);const changeAnnotations=React__default.default.useMemo(()=>diff?collectLatestAuthorAnnotations(diff):[],[diff]);return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{"data-testid":"review-changes-pane",direction:"column",height:"fill",overflow:"hidden",children:[/* @__PURE__ */jsxRuntime.jsx(DocumentInspectorHeader,{as:"header",closeButtonLabel:t("changes.action.close-label"),flex:"none",onClose,title:t("changes.title"),children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:1,padding:3,paddingTop:0,paddingBottom:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,children:/* @__PURE__ */jsxRuntime.jsx(TimelineMenu,{mode:"since",chunk:sinceTime,placement:"bottom-start"})}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:"none",children:/* @__PURE__ */jsxRuntime.jsx(sanity.DiffTooltip,{annotations:changeAnnotations,description:t("changes.changes-by-author"),portal:true,children:/* @__PURE__ */jsxRuntime.jsx(ui.AvatarStack,{maxLength:4,"aria-label":t("changes.changes-by-author"),children:changeAnnotations.map(_ref84=>{let{author}=_ref84;return/* @__PURE__ */jsxRuntime.jsx(sanity.UserAvatar,{user:author},author);})})})})]})}),/* @__PURE__ */jsxRuntime.jsx(ui.Card,{flex:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.BoundaryElementProvider,{element:scrollRef.current,children:/* @__PURE__ */jsxRuntime.jsx(Scroller$1,{"data-ui":"Scroller",ref:scrollRef,children:/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:1,padding:4,children:/* @__PURE__ */jsxRuntime.jsx(Content$1,{diff,documentContext,error:timelineError,loading,schemaType})})})})})]});}function Content$1(_ref85){let{error,diff,documentContext,loading,schemaType}=_ref85;if(error){return/* @__PURE__ */jsxRuntime.jsx(sanity.NoChanges,{});}if(loading){return/* @__PURE__ */jsxRuntime.jsx(sanity.LoadingBlock,{showText:true});}if(!diff){return/* @__PURE__ */jsxRuntime.jsx(sanity.NoChanges,{});}return/* @__PURE__ */jsxRuntime.jsx(sanity.DocumentChangeContext.Provider,{value:documentContext,children:/* @__PURE__ */jsxRuntime.jsx(sanity.ChangeList,{diff,schemaType})});}const changesInspector={name:HISTORY_INSPECTOR_NAME,useMenuItem:()=>{const{features}=useStructureTool();const{t}=sanity.useTranslation();return{hidden:!features.reviewChanges,icon:icons.RestoreIcon,title:t("changes.title")};},component:ChangesInspector,onClose:_ref86=>{let{params}=_ref86;return{params:{...params,since:void 0}};},onOpen:_ref87=>{let{params}=_ref87;return{params:{...params,since:"@lastPublished"}};}};function getPathTitles(options){const{path,schemaType,value}=options;const result=[];let s=schemaType;let v=value;for(const segment of path){if(typeof segment==="string"){if(!sanity.isRecord(v)&&v!==void 0){throw new Error("Parent value is not an object, cannot get path segment: .".concat(segment));}if(s.jsonType!=="object"){throw new Error("Parent type is not an object schema type, cannot get path segment: .".concat(segment));}v=v==null?void 0:v[segment];const field=s.fields.find(f=>f.name===segment);if(!field){result.push({name:segment});return result;}s=field.type;result.push(s);continue;}if(typeof segment==="number"){if(!sanity.isArray(v)&&v!==void 0){throw new Error("Parent value is not an array, cannot get path segment: [".concat(segment,"]"));}if(s.jsonType!=="array"){throw new Error("Parent type is not an array schema type, cannot get path segment: [".concat(segment,"]"));}v=v==null?void 0:v[segment];const itemType=s.of.find(ofType=>{if(typeof v==="string"){return ofType.jsonType==="string";}if(typeof v==="number"){return ofType.jsonType==="number";}if(typeof v==="boolean"){return ofType.jsonType==="boolean";}if(sanity.isRecord(v)){return ofType.name===(v==null?void 0:v._type);}return false;});if(!itemType){throw new Error("Item type not found: [".concat(segment,"]"));}s=itemType;result.push(s);continue;}if(sanity.isRecord(segment)&&segment._key){if(!sanity.isArray(v)){throw new Error("Parent value is not an array, cannot get path segment: [_key == ".concat(segment,"]"));}if(s.jsonType!=="array"){throw new Error("Parent type is not an array schema type, cannot get path segment: .".concat(segment));}const values=v!=null?v:[];v=values.find(i=>sanity.isRecord(i)&&i._key===segment._key);if(!sanity.isRecord(v)){throw new Error("Array item not found: [_key == ".concat(segment._key,"]"));}const ofType=s.of.find(i=>sanity.isRecord(v)&&i.name===(v==null?void 0:v._type));if(!ofType){throw new Error("Array item type not found: .".concat(v==null?void 0:v._type));}s=ofType;result.push(s);continue;}throw new Error("Invalid path segment: ".concat(JSON.stringify(segment)));}return result;}const MARKER_ICON={error:icons.ErrorOutlineIcon,warning:icons.WarningOutlineIcon,info:icons.InfoOutlineIcon};const MARKER_TONE={error:"critical",warning:"caution",info:"primary"};function ValidationInspector(props){const{onClose}=props;const{onFocus,onPathOpen,schemaType,validation,value}=useDocumentPane();const{t}=sanity.useTranslation("validation");const handleOpen=React.useCallback(path=>{onPathOpen(path);onFocus(path);},[onFocus,onPathOpen]);return/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{direction:"column",height:"fill",overflow:"hidden",children:[/* @__PURE__ */jsxRuntime.jsx(DocumentInspectorHeader,{as:"header",closeButtonLabel:t("panel.close-button-aria-label"),flex:"none",onClose,title:t("panel.title")}),/* @__PURE__ */jsxRuntime.jsxs(ui.Card,{flex:1,overflow:"auto",padding:3,children:[validation.length===0&&/* @__PURE__ */jsxRuntime.jsx(ui.Box,{padding:2,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,children:t("panel.no-errors-message")})}),validation.length>0&&/* @__PURE__ */jsxRuntime.jsx(ui.Stack,{space:2,children:validation.map((marker,i)=>/* @__PURE__ */jsxRuntime.jsx(ValidationCard,{marker,onOpen:handleOpen,schemaType,value},i))})]})]});}function ValidationCard(props){const{marker,onOpen,schemaType,value}=props;const handleOpen=React.useCallback(()=>onOpen(marker.path),[marker,onOpen]);const[errorInfo,setErrorInfo]=React.useState(null);return/* @__PURE__ */jsxRuntime.jsxs(ui.ErrorBoundary,{onCatch:setErrorInfo,children:[errorInfo&&/* @__PURE__ */jsxRuntime.jsx(ui.Card,{padding:3,radius:2,tone:"critical",children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:errorInfo.error.message})}),!errorInfo&&/* @__PURE__ */jsxRuntime.jsx(ui.Card,{__unstable_focusRing:true,as:"button",onClick:handleOpen,padding:3,radius:2,tone:MARKER_TONE[marker.level],children:/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{align:"flex-start",gap:3,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{flex:"none",children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:React.createElement(MARKER_ICON[marker.level])})}),/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{flex:1,space:2,children:[/* @__PURE__ */jsxRuntime.jsx(DocumentNodePathBreadcrumbs,{path:marker.path,schemaType,value}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{muted:true,size:1,children:marker.message})]})]})})]});}function DocumentNodePathBreadcrumbs(props){const{path,schemaType,value}=props;const pathTitles=React.useMemo(()=>getPathTitles({path,schemaType,value}),[path,schemaType,value]);if(!pathTitles.length)return null;return/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:pathTitles.map((t,i)=>/* @__PURE__ */jsxRuntime.jsxs(React.Fragment,{children:[i>0&&/* @__PURE__ */jsxRuntime.jsx("span",{style:{color:"var(--card-muted-fg-color)",opacity:0.5},children:" / "}),/* @__PURE__ */jsxRuntime.jsx("span",{style:{fontWeight:500},children:t.title||t.name})]},i))});}function useMenuItem(props){const{documentId,documentType}=props;const{t}=sanity.useTranslation("validation");const{validation:validationMarkers}=sanity.useValidationStatus(documentId,documentType);const validation=React.useMemo(()=>validationMarkers.map(item=>({level:item.level,message:item.message,path:item.path})),[validationMarkers]);const hasErrors=validation.some(sanity.isValidationError);const hasWarnings=validation.some(sanity.isValidationWarning);const icon=React.useMemo(()=>{if(hasErrors)return icons.ErrorOutlineIcon;if(hasWarnings)return icons.WarningOutlineIcon;return icons.CheckmarkCircleIcon;},[hasErrors,hasWarnings]);const tone=React.useMemo(()=>{if(hasErrors)return"critical";if(hasWarnings)return"caution";return"positive";},[hasErrors,hasWarnings]);return{hidden:validation.length===0,icon,title:t("panel.title"),tone,showAsAction:true};}const validationInspector={name:VALIDATION_INSPECTOR_NAME,component:ValidationInspector,useMenuItem};const documentActions=[PublishAction,UnpublishAction,DiscardChangesAction,DuplicateAction,DeleteAction,HistoryRestoreAction];const documentBadges=[LiveEditBadge];const inspectors=[validationInspector,changesInspector];const structureTool=sanity.definePlugin(options=>{const icon=(options==null?void 0:options.icon)||icons.MasterDetailIcon;return{name:"sanity/structure",document:{actions:prevActions=>{return Array.from(/* @__PURE__ */new Set([...prevActions,...documentActions]));},badges:prevBadges=>{return Array.from(/* @__PURE__ */new Set([...prevBadges,...documentBadges]));},inspectors:prevInspectors=>{return Array.from(/* @__PURE__ */new Set([...prevInspectors,...inspectors]));}},plugins:[comments()],tools:[{name:(options==null?void 0:options.name)||"structure",title:(options==null?void 0:options.title)||"Structure",icon,component:React.lazy(()=>Promise.resolve().then(function(){return require('./index-751ZLh3z.js');})),canHandleIntent:(intent,params)=>{if(intent==="create")return canHandleCreateIntent(params);if(intent==="edit")return canHandleEditIntent(params);return false;},getIntentState,// Controlled by sanity/src/structure/components/structureTool/StructureTitle.tsx
44
44
  controlsDocumentTitle:true,options,router}],i18n:{bundles:[structureUsEnglishLocaleBundle]}};});function canHandleCreateIntent(params){if(!("type"in params)){return false;}return"template"in params?{template:true}:true;}function canHandleEditIntent(params){if(!("id"in params)){return false;}return"mode"in params?{mode:params.mode==="structure"}:true;}class SerializeError extends Error{constructor(message,parentPath,pathSegment,hint){super(message);const segment=typeof pathSegment==="undefined"?"<unknown>":"".concat(pathSegment);this.path=(parentPath||[]).concat(hint?"".concat(segment," (").concat(hint,")"):segment);}withHelpUrl(id){this.helpId=id;return this;}}var HELP_URL=/* @__PURE__ */(HELP_URL2=>{HELP_URL2["ID_REQUIRED"]="structure-node-id-required";HELP_URL2["TITLE_REQUIRED"]="structure-title-required";HELP_URL2["FILTER_REQUIRED"]="structure-filter-required";HELP_URL2["INVALID_LIST_ITEM"]="structure-invalid-list-item";HELP_URL2["COMPONENT_REQUIRED"]="structure-view-component-required";HELP_URL2["DOCUMENT_ID_REQUIRED"]="structure-document-id-required";HELP_URL2["DOCUMENT_TYPE_REQUIRED"]="structure-document-type-required";HELP_URL2["SCHEMA_TYPE_REQUIRED"]="structure-schema-type-required";HELP_URL2["SCHEMA_TYPE_NOT_FOUND"]="structure-schema-type-not-found";HELP_URL2["LIST_ITEMS_MUST_BE_ARRAY"]="structure-list-items-must-be-array";HELP_URL2["QUERY_PROVIDED_FOR_FILTER"]="structure-query-provided-for-filter";HELP_URL2["ACTION_OR_INTENT_REQUIRED"]="structure-action-or-intent-required";HELP_URL2["LIST_ITEM_IDS_MUST_BE_UNIQUE"]="structure-list-item-ids-must-be-unique";HELP_URL2["ACTION_AND_INTENT_MUTUALLY_EXCLUSIVE"]="structure-action-and-intent-mutually-exclusive";HELP_URL2["API_VERSION_REQUIRED_FOR_CUSTOM_FILTER"]="structure-api-version-required-for-custom-filter";return HELP_URL2;})(HELP_URL||{});const IMPLICIT_FIELDS=["_id","_type","_createdAt","_updatedAt","_rev"];function joinReferences(schemaType,path){const[head,...tail]=path;if(!("fields"in schemaType)){return"";}const schemaField=schemaType.fields.find(field=>field.name===head);if(!schemaField){if(!IMPLICIT_FIELDS.includes(head)){console.warn('The current ordering config targeted the nonexistent field "%s" on schema type "%s". It should be one of %o',head,schemaType.name,schemaType.fields.map(field=>field.name));}return"";}if("to"in schemaField.type&&schemaField.type.name==="reference"){const refTypes=schemaField.type.to;return"".concat(head,"->{").concat(refTypes.map(refType=>joinReferences(refType,tail)).join(","),"}");}const tailFields=tail.length>0&&joinReferences(schemaField.type,tail);const tailWrapper=tailFields?"{".concat(tailFields,"}"):"";return tail.length>0?"".concat(head).concat(tailWrapper):head;}function getExtendedProjection(schemaType,orderBy){return orderBy.map(ordering=>joinReferences(schemaType,ordering.field.split("."))).join(", ");}const ORDER_BY_UPDATED_AT={title:"Last edited",i18n:{title:{key:"menu-items.sort-by.last-edited",ns:structureLocaleNamespace}},name:"lastEditedDesc",by:[{field:"_updatedAt",direction:"desc"}]};const ORDER_BY_CREATED_AT={title:"Created",i18n:{title:{key:"menu-items.sort-by.created",ns:structureLocaleNamespace}},name:"lastCreatedDesc",by:[{field:"_createdAt",direction:"desc"}]};const DEFAULT_SELECTED_ORDERING_OPTION=ORDER_BY_UPDATED_AT;const DEFAULT_ORDERING_OPTIONS=[ORDER_BY_UPDATED_AT,// _updatedAt
45
45
  ORDER_BY_CREATED_AT// _createdAt
46
46
  ];function maybeSerializeMenuItem(item,index,path){return item instanceof MenuItemBuilder?item.serialize({path,index}):item;}class MenuItemBuilder{constructor(_context,spec){this._context=_context;this.spec=spec?spec:{};}/**
@@ -505,4 +505,4 @@ getInspectItem(params),...items];}function DocumentLayoutError(props){const{docu
505
505
  "absolute"];const StyledChangeConnectorRoot=styled__default.default(sanity.ChangeConnectorRoot)(_a$2||(_a$2=__template$2(["\n flex: 1;\n display: flex;\n flex-direction: column;\n min-height: 0;\n min-width: 0;\n"])));function DocumentLayout(){const{changesOpen,documentId,documentType,fieldActions,inspectOpen,inspector,inspectors,onFocus,onHistoryOpen,onMenuAction,onPathOpen,paneKey,schemaType,value}=useDocumentPane();const{features}=useStructureTool();const{t}=reactI18next.useTranslation(structureLocaleNamespace);const{collapsed:layoutCollapsed}=usePaneLayout();const zOffsets=sanity.useZIndex();const previewUrl=usePreviewUrl(value);const[rootElement,setRootElement]=React.useState(null);const[footerElement,setFooterElement]=React.useState(null);const[headerElement,setHeaderElement]=React.useState(null);const[actionsBoxElement,setActionsBoxElement]=React.useState(null);const[documentPanelPortalElement,setDocumentPanelPortalElement]=React.useState(null);const[inspectorMenuItems,setInspectorMenuItems]=React.useState([]);const[rootFieldActionNodes,setRootFieldActionNodes]=React.useState([]);const footerRect=ui.useElementRect(footerElement);const headerRect=ui.useElementRect(headerElement);const footerHeight=footerRect==null?void 0:footerRect.height;const headerHeight=headerRect==null?void 0:headerRect.height;const currentMinWidth=DOCUMENT_PANEL_INITIAL_MIN_WIDTH+(inspector?DOCUMENT_INSPECTOR_MIN_WIDTH:0);const minWidth=DOCUMENT_PANEL_MIN_WIDTH+(inspector?DOCUMENT_INSPECTOR_MIN_WIDTH:0);const currentInspector=React.useMemo(()=>inspectors==null?void 0:inspectors.find(i=>i.name===(inspector==null?void 0:inspector.name)),[inspectors,inspector==null?void 0:inspector.name]);const hasValue=Boolean(value);const menuItems=React.useMemo(()=>getMenuItems({currentInspector,features,hasValue,inspectorMenuItems,inspectors,previewUrl,t}),[currentInspector,features,hasValue,inspectorMenuItems,inspectors,previewUrl,t]);const handleKeyUp=React.useCallback(event=>{for(const item of menuItems){if(item.shortcut){if(isHotkey__default.default(item.shortcut,event)){event.preventDefault();event.stopPropagation();onMenuAction(item);return;}}}},[onMenuAction,menuItems]);const onConnectorSetFocus=React.useCallback(path=>{onPathOpen(path);onFocus(path);},[onPathOpen,onFocus]);if(!schemaType){return/* @__PURE__ */jsxRuntime.jsx(DocumentLayoutError,{currentMinWidth,documentType,minWidth,paneKey,value});}return/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[inspectors.length>0&&/* @__PURE__ */jsxRuntime.jsx(DocumentInspectorMenuItemsResolver,{documentId,documentType,inspectors,onMenuItems:setInspectorMenuItems}),fieldActions.length>0&&schemaType&&/* @__PURE__ */jsxRuntime.jsx(sanity.FieldActionsResolver,{actions:fieldActions,documentId,documentType,onActions:setRootFieldActionNodes,path:EMPTY_ARRAY$2,schemaType}),/* @__PURE__ */jsxRuntime.jsx(sanity.FieldActionsProvider,{actions:rootFieldActionNodes,path:EMPTY_ARRAY$2,children:/* @__PURE__ */jsxRuntime.jsxs(DocumentActionShortcuts,{actionsBoxElement,as:Pane,currentMinWidth,"data-testid":"document-pane",flex:2.5,id:paneKey,minWidth,onKeyUp:handleKeyUp,rootRef:setRootElement,children:[/* @__PURE__ */jsxRuntime.jsx(DocumentPanelHeader,{ref:setHeaderElement,menuItems}),/* @__PURE__ */jsxRuntime.jsx(ui.DialogProvider,{position:DIALOG_PROVIDER_POSITION,zOffset:zOffsets.portal,children:/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{direction:"column",flex:1,height:layoutCollapsed?void 0:"fill",children:/* @__PURE__ */jsxRuntime.jsx(StyledChangeConnectorRoot,{"data-testid":"change-connector-root",isReviewChangesOpen:changesOpen,onOpenReviewChanges:onHistoryOpen,onSetFocus:onConnectorSetFocus,children:/* @__PURE__ */jsxRuntime.jsx(DocumentPanel,{footerHeight:footerHeight||null,headerHeight:headerHeight||null,isInspectOpen:inspectOpen,rootElement,setDocumentPanelPortalElement})})})}),/* @__PURE__ */jsxRuntime.jsx(ui.PortalProvider,{__unstable_elements:{[DOCUMENT_PANEL_PORTAL_ELEMENT]:documentPanelPortalElement},children:/* @__PURE__ */jsxRuntime.jsx(ui.DialogProvider,{position:DIALOG_PROVIDER_POSITION,zOffset:zOffsets.portal,children:/* @__PURE__ */jsxRuntime.jsx(PaneFooter,{ref:setFooterElement,children:/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.TooltipDelayGroupProvider,{children:/* @__PURE__ */jsxRuntime.jsx(DocumentStatusBar,{actionsBoxRef:setActionsBoxElement})})})})}),/* @__PURE__ */jsxRuntime.jsx(DocumentOperationResults,{})]})})]});}function pick(plugin){var _a,_b;return(_b=(_a=plugin.document)==null?void 0:_a.components)==null?void 0:_b.unstable_layout;}function useDocumentLayoutComponent(){return sanity.useMiddlewareComponents({pick,defaultComponent:DocumentLayout});}const DocumentPane=React.memo(function DocumentPane2(props){const{name:parentSourceName}=sanity.useSource();return/* @__PURE__ */jsxRuntime.jsx(sanity.SourceProvider,{name:props.pane.source||parentSourceName,children:/* @__PURE__ */jsxRuntime.jsx(DocumentPaneInner,{...props})});});function DocumentPaneInner(props){var _a;const{pane,paneKey}=props;const{resolveNewDocumentOptions}=sanity.useSource().document;const paneRouter=usePaneRouter();const options=usePaneOptions(pane.options,paneRouter.params);const{documentType,isLoaded:isDocumentLoaded}=sanity.useDocumentType(options.id,options.type);const DocumentLayout=useDocumentLayoutComponent();const templateItems=React.useMemo(()=>{return resolveNewDocumentOptions({type:"document",documentId:options.id,schemaType:options.type});},[options.id,options.type,resolveNewDocumentOptions]);const[templatePermissions,isTemplatePermissionsLoading]=sanity.useTemplatePermissions({templateItems});const isLoaded=isDocumentLoaded&&!isTemplatePermissionsLoading;const providerProps=React.useMemo(()=>{return isLoaded&&documentType&&options.type!==documentType?mergeDocumentType(props,options,documentType):props;},[props,documentType,isLoaded,options]);const{ReferenceChildLink,handleEditReference,groupIndex,routerPanesState}=paneRouter;const childParams=((_a=routerPanesState[groupIndex+1])==null?void 0:_a[0].params)||{};const routerPanesStateLength=routerPanesState.length;const{parentRefPath}=childParams;const activePath=React.useMemo(()=>{return parentRefPath?{path:PathUtils.fromString(parentRefPath),state:// eslint-disable-next-line no-nested-ternary
506
506
  groupIndex>=routerPanesStateLength-1?"none":groupIndex>=routerPanesStateLength-2?"selected":"pressed"}:{path:[],state:"none"};},[parentRefPath,groupIndex,routerPanesStateLength]);const{t}=sanity.useTranslation(structureLocaleNamespace);if(options.type==="*"&&!isLoaded){return/* @__PURE__ */jsxRuntime.jsx(LoadingPane,{flex:2.5,minWidth:320,paneKey,title:t("panes.document-pane.document-not-found.loading")});}if(!documentType){return/* @__PURE__ */jsxRuntime.jsx(ErrorPane,{flex:2.5,minWidth:320,paneKey,title:t("panes.document-pane.document-not-found.title"),children:/* @__PURE__ */jsxRuntime.jsx(ui.Stack,{space:4,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{as:"p",children:/* @__PURE__ */jsxRuntime.jsx(sanity.Translate,{t,i18nKey:"panes.document-pane.document-not-found.text",values:{id:options.id}})})})});}return/* @__PURE__ */jsxRuntime.jsx(DocumentPaneProvider,{...providerProps,children:/* @__PURE__ */jsxRuntime.jsx(sanity.ReferenceInputOptionsProvider,{EditReferenceLinkComponent:ReferenceChildLink,onEditReference:handleEditReference,initialValueTemplateItems:templatePermissions,activePath,children:/* @__PURE__ */jsxRuntime.jsx(DocumentLayout,{documentId:options.id,documentType:options.type})})},"".concat(documentType,"-").concat(options.id));}function usePaneOptions(options){let params=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const templates=sanity.useTemplates();return React.useMemo(()=>{if(options.type&&options.type!=="*"){return options;}const templateName=options.template||params.template;const template=templateName?templates.find(t=>t.id===templateName):void 0;const documentType=template==null?void 0:template.schemaType;if(!documentType){return options;}return{...options,type:documentType};},[options,params.template,templates]);}function mergeDocumentType(props,options,documentType){return{...props,pane:{...props.pane,options:{...options,type:documentType}}};}const PARTIAL_PAGE_LIMIT=100;const FULL_LIST_LIMIT=2e3;const DEFAULT_ORDERING={by:[{field:"_updatedAt",direction:"desc"}]};const EMPTY_RECORD={};function removePublishedWithDrafts(documents){return sanity.collate(documents).map(entry=>{const doc=entry.draft||entry.published;return{...doc,hasPublished:!!entry.published,hasDraft:!!entry.draft};});}const RE_TYPE_NAME_IN_FILTER=/\b_type\s*==\s*(['"].*?['"]|\$.*?(?:\s|$))|\B(['"].*?['"]|\$.*?(?:\s|$))\s*==\s*_type\b/;function getTypeNameFromSingleTypeFilter(filter){let params=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const matches=filter.match(RE_TYPE_NAME_IN_FILTER);if(!matches){return null;}const match=(matches[1]||matches[2]).trim().replace(/^["']|["']$/g,"");if(match[0]==="$"){const k=match.slice(1);const v=params[k];return typeof v==="string"?v:null;}return match;}function isSimpleTypeFilter(filter){return /^_type\s*==\s*['"$]\w+['"]?\s*$/.test(filter.trim());}function applyOrderingFunctions(order,schemaType){const orderBy=order.by.map(by=>{if(by.mapWith){return by;}const fieldType=tryResolveSchemaTypeForPath(schemaType,by.field);if(!fieldType){return by;}if(fieldExtendsType(fieldType,"datetime")){return{...by,mapWith:"dateTime"};}if(fieldType.jsonType==="string"){return{...by,mapWith:"lower"};}return by;});return orderBy.every((item,index)=>item===order.by[index])?order:{...order,by:orderBy};}function tryResolveSchemaTypeForPath(baseType,path){const pathSegments=PathUtils__namespace.fromString(path);let current=baseType;for(const segment of pathSegments){if(!current){return void 0;}if(typeof segment==="string"){current=getFieldTypeByName(current,segment);continue;}const isArrayAccessor=types.isKeySegment(segment)||types.isIndexSegment(segment);if(!isArrayAccessor||current.jsonType!=="array"){return void 0;}const[memberType,otherType]=current.of||[];if(otherType||!memberType){return void 0;}if(!types.isReferenceSchemaType(memberType)){current=memberType;continue;}const[refType,otherRefType]=memberType.to||[];if(otherRefType||!refType){return void 0;}current=refType;}return current;}function getFieldTypeByName(type,fieldName){if(!("fields"in type)){return void 0;}const fieldType=type.fields.find(field=>field.name===fieldName);return fieldType?fieldType.type:void 0;}function fieldExtendsType(field,ofType){let current=field.type;while(current){if(current.name===ofType){return true;}if(!current.type&&current.jsonType===ofType){return true;}current=current.type;}return false;}var __freeze$1=Object.freeze;var __defProp$1=Object.defineProperty;var __template$1=(cooked,raw)=>__freeze$1(__defProp$1(cooked,"raw",{value:__freeze$1(raw||cooked.slice())}));var _a$1,_b$1;const RootBox=styled__default.default(ui.Box)(_a$1||(_a$1=__template$1(["\n position: relative;\n"])));const CommandListBox=styled__default.default(ui.Box)(_b$1||(_b$1=__template$1(["\n position: absolute;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n"])));const SKELETON_ITEMS=[...Array(30).keys()];function LoadingView(props){const{layout}=props;return/* @__PURE__ */jsxRuntime.jsx(ui.Stack,{paddingX:3,paddingY:2,paddingTop:0,space:1,children:SKELETON_ITEMS.map(num=>/* @__PURE__ */jsxRuntime.jsx(sanity.SanityDefaultPreview,{isPlaceholder:true,layout},num))});}function DocumentListPaneContent(props){const{childItemId,error,filterIsSimpleTypeConstraint,hasMaxItems,hasSearchQuery,isActive,isLazyLoading,isLoading,items,layout,loadingVariant,onListChange,onRetry,paneTitle,searchInputElement,showIcons}=props;const schema=sanity.useSchema();const{collapsed:layoutCollapsed}=usePaneLayout();const{collapsed,index}=usePane();const[shouldRender,setShouldRender]=React.useState(false);const{t}=sanity.useTranslation(structureLocaleNamespace);const handleEndReached=React.useCallback(()=>{if(isLoading||isLazyLoading||!shouldRender)return;onListChange();},[isLazyLoading,isLoading,onListChange,shouldRender]);React.useEffect(()=>{if(collapsed)return void 0;const timer=setTimeout(()=>{setShouldRender(true);},0);return()=>{clearTimeout(timer);};},[collapsed,items]);const renderItem=React.useCallback((item,_ref115)=>{let{activeIndex}=_ref115;const publishedId=sanity.getPublishedId(item._id);const isSelected=childItemId===publishedId;const pressed=!isActive&&isSelected;const selected=isActive&&isSelected;const isLastItem=activeIndex===items.length-1;const showSpinner=isLastItem&&isLazyLoading;const showMaxItemsMessage=isLastItem&&hasMaxItems;return/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[/* @__PURE__ */jsxRuntime.jsx(PaneItem,{icon:showIcons===false?false:void 0,id:publishedId,layout,marginBottom:1,pressed,schemaType:schema.get(item._type),selected,value:item}),showSpinner&&/* @__PURE__ */jsxRuntime.jsx(sanity.LoadingBlock,{}),showMaxItemsMessage&&/* @__PURE__ */jsxRuntime.jsx(ui.Box,{marginY:1,paddingX:3,paddingY:4,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{align:"center",muted:true,size:1,children:t("panes.document-list-pane.max-items.text",{limit:FULL_LIST_LIMIT})})})]});},[childItemId,isActive,items.length,layout,schema,showIcons,hasMaxItems,isLazyLoading,t]);const noDocumentsContent=React.useMemo(()=>{if(hasSearchQuery){return/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{align:"center",direction:"column",height:"fill",justify:"center",children:/* @__PURE__ */jsxRuntime.jsx(ui.Container,{width:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Box,{paddingX:4,paddingY:5,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{align:"center",muted:true,children:t("panes.document-list-pane.no-documents.text")})})})});}return/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{align:"center",direction:"column",height:"fill",justify:"center",children:/* @__PURE__ */jsxRuntime.jsx(ui.Container,{width:1,children:/* @__PURE__ */jsxRuntime.jsx(ui.Box,{paddingX:4,paddingY:5,children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{align:"center",muted:true,children:filterIsSimpleTypeConstraint?t("panes.document-list-pane.no-documents-of-type.text"):t("panes.document-list-pane.no-matching-documents.text")})})})});},[filterIsSimpleTypeConstraint,hasSearchQuery,t]);const mainContent=React.useMemo(()=>{if(!shouldRender){return null;}if(error){return/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{align:"center",direction:"column",height:"fill",justify:"center",children:/* @__PURE__ */jsxRuntime.jsx(ui.Container,{width:1,children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{paddingX:4,paddingY:5,space:4,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Heading,{as:"h3",children:t("panes.document-list-pane.error.title")}),/* @__PURE__ */jsxRuntime.jsx(ui.Text,{as:"p",children:/* @__PURE__ */jsxRuntime.jsx(sanity.Translate,{t,i18nKey:"panes.document-list-pane.error.text",values:{error:error.message},components:{Code:_ref116=>{let{children}=_ref116;return/* @__PURE__ */jsxRuntime.jsx("code",{children});}}})}),onRetry&&/* @__PURE__ */jsxRuntime.jsx(ui.Box,{children:/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{icon:icons.SyncIcon,onClick:onRetry,text:t("panes.document-list-pane.error.retry-button.text"),tone:"primary"})})]})})});}if(!isLoading&&items.length===0){return noDocumentsContent;}if(loadingVariant==="initial"&&isLoading){return/* @__PURE__ */jsxRuntime.jsx(Delay,{ms:300,children:/* @__PURE__ */jsxRuntime.jsx(LoadingView,{layout})});}if(loadingVariant==="spinner"&&isLoading){return null;}const key="".concat(index,"-").concat(collapsed);return/* @__PURE__ */jsxRuntime.jsx(RootBox,{overflow:"hidden",height:"fill",children:/* @__PURE__ */jsxRuntime.jsx(CommandListBox,{children:/* @__PURE__ */jsxRuntime.jsx(sanity.CommandList,{activeItemDataAttr:"data-hovered",ariaLabel:paneTitle,canReceiveFocus:true,inputElement:searchInputElement,itemHeight:51,items,onEndReached:handleEndReached,onlyShowSelectionWhenActive:true,overscan:10,paddingBottom:1,paddingX:3,renderItem,wrapAround:false},key)})});},[collapsed,error,handleEndReached,index,isLoading,items,layout,loadingVariant,// noDocumentsContent,
507
507
  onRetry,renderItem,searchInputElement,shouldRender]);return/* @__PURE__ */jsxRuntime.jsx(PaneContent,{overflow:layoutCollapsed||loadingVariant==="initial"?"hidden":"auto",children:mainContent});}const DocumentListPaneHeader=React.memo(_ref117=>{let{contentAfter,index,initialValueTemplates=[],menuItemGroups=[],menuItems=[],setLayout,setSortOrder,title}=_ref117;const{features}=useStructureTool();const{collapsed,isLast}=usePane();const tabIndex=isLast&&!collapsed?-1:0;const actionHandlers=React.useMemo(()=>{return{setLayout:_ref118=>{let{layout:value}=_ref118;setLayout(value);},setSortOrder:sort=>{setSortOrder(sort);}};},[setLayout,setSortOrder]);return/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.TooltipDelayGroupProvider,{children:/* @__PURE__ */jsxRuntime.jsx(PaneHeader,{actions:/* @__PURE__ */jsxRuntime.jsx(PaneHeaderActions,{initialValueTemplateItems:initialValueTemplates,actionHandlers,menuItemGroups,menuItems}),backButton:features.backButton&&index>0&&/* @__PURE__ */jsxRuntime.jsx(TooltipDelayGroupProvider.Button,{as:BackLink,"data-as":"a",icon:icons.ArrowLeftIcon,mode:"bleed",tooltipProps:{content:"Back"}}),contentAfter,tabIndex,title})});});DocumentListPaneHeader.displayName="DocumentListPaneHeader";function listenSearchQuery(options){const{client,schema,sort,limit,params,filter,searchQuery,staticTypeNames,maxFieldDepth}=options;const sortBy=sort.by;const extendedProjection=sort==null?void 0:sort.extendedProjection;const events$=rxjs.defer(()=>{return client.listen("*[".concat(filter,"]"),params,{events:["welcome","mutation","reconnect"],includeResult:false,visibility:"query"});}).pipe(rxjs.mergeMap((ev,i)=>{const isFirst=i===0;if(isFirst&&ev.type!=="welcome"){return rxjs.throwError(()=>new Error(ev.type==="reconnect"?"Could not establish EventSource connection":'Received unexpected type of first event "'.concat(ev.type,'"')));}return rxjs.of(ev);}),rxjs.share());const[welcome$,mutationAndReconnect$]=rxjs.partition(events$,ev=>ev.type==="welcome");return rxjs.merge(welcome$.pipe(rxjs.take(1)),mutationAndReconnect$.pipe(rxjs.throttleTime(1e3,rxjs.asyncScheduler,{leading:true,trailing:true}))).pipe(rxjsExhaustmapWithTrailing.exhaustMapWithTrailing(event=>{const typeNames$=staticTypeNames?rxjs.of(staticTypeNames):client.observable.fetch("array::unique(*[".concat(filter,"][]._type)"),params);return typeNames$.pipe(rxjs.mergeMap(typeNames=>{const types=_internalBrowser.getSearchTypesWithMaxDepth(_internalBrowser.getSearchableTypes(schema).filter(type=>{return typeNames.includes(type.name);}),maxFieldDepth);const searchTerms={filter,query:searchQuery||"",types};const searchOptions={__unstable_extendedProjection:extendedProjection,comments:["findability-source: ".concat(searchQuery?"list-query":"list")],limit,params,sort:sortBy};const{query:createdQuery,params:createdParams}=sanity.createSearchQuery(searchTerms,searchOptions);const doFetch=()=>client.observable.fetch(createdQuery,createdParams);if(event.type==="mutation"&&event.visibility!=="query"){return rxjs.timer(1200).pipe(rxjs.mergeMap(doFetch));}return doFetch();}));}));}const EMPTY_ARRAY$1=[];const INITIAL_STATE={error:null,onRetry:void 0,result:null};const INITIAL_QUERY_RESULTS={result:null,error:null};function useDocumentList(opts){const{filter,params:paramsProp,sortOrder,searchQuery,apiVersion}=opts;const client=sanity.useClient({...sanity.DEFAULT_STUDIO_CLIENT_OPTIONS,apiVersion:apiVersion||sanity.DEFAULT_STUDIO_CLIENT_OPTIONS.apiVersion});const schema=sanity.useSchema();const maxFieldDepth=_internalBrowser.useSearchMaxFieldDepth();const[resultState,setResult]=React.useState(INITIAL_STATE);const{onRetry,error,result}=resultState;const documents=result==null?void 0:result.documents;const items=React.useMemo(()=>documents?removePublishedWithDrafts(documents):EMPTY_ARRAY$1,[documents]);const[isLazyLoading,setIsLazyLoading]=React.useState(false);const[hasFullList,setHasFullList]=React.useState(false);const[shouldFetchFullList,setShouldFetchFullList]=React.useState(false);const typeNameFromFilter=React.useMemo(()=>getTypeNameFromSingleTypeFilter(filter,paramsProp),[filter,paramsProp]);const isLoading=result===null&&!error;const hasMaxItems=(documents==null?void 0:documents.length)===FULL_LIST_LIMIT;const onListChange=React.useCallback(()=>{if(isLoading||hasFullList||shouldFetchFullList)return;setShouldFetchFullList(true);},[isLoading,hasFullList,shouldFetchFullList]);const handleSetResult=React.useCallback(res=>{var _a,_b;if(res.error){setResult(res);return;}const documentsLength=((_b=(_a=res.result)==null?void 0:_a.documents)==null?void 0:_b.length)||0;const isLoadingMoreItems=!res.error&&(res==null?void 0:res.result)===null&&shouldFetchFullList;if(isLoadingMoreItems){setIsLazyLoading(true);return;}if(documentsLength<PARTIAL_PAGE_LIMIT&&documentsLength!==0&&!shouldFetchFullList){setHasFullList(true);}if((res==null?void 0:res.result)===null){setResult(prev=>({...(prev.error?res:prev)}));return;}setIsLazyLoading(false);setResult(res);},[shouldFetchFullList]);const queryResults$=React.useMemo(()=>{const onRetry$=new rxjs.Subject();const _onRetry=()=>onRetry$.next();const limit=shouldFetchFullList?FULL_LIST_LIMIT:PARTIAL_PAGE_LIMIT;const sort=sortOrder||DEFAULT_ORDERING;return listenSearchQuery({client,filter,limit,params:paramsProp,schema,searchQuery:searchQuery||"",sort,staticTypeNames:typeNameFromFilter?[typeNameFromFilter]:void 0,maxFieldDepth}).pipe(operators.map(results=>({result:{documents:results},error:null})),operators.startWith(INITIAL_QUERY_RESULTS),operators.catchError(err=>{if(err instanceof ProgressEvent){return rxjs.throwError(()=>new Error("Request error"));}return rxjs.throwError(()=>err);}),operators.catchError((err,caught$)=>{return rxjs.concat(rxjs.of({result:null,error:err}),rxjs.merge(rxjs.fromEvent(window,"online"),onRetry$).pipe(operators.take(1),operators.mergeMap(()=>caught$)));}),operators.scan((prev,next)=>({...prev,...next,onRetry:_onRetry})));},[client,filter,paramsProp,schema,searchQuery,shouldFetchFullList,sortOrder,typeNameFromFilter,maxFieldDepth]);React.useEffect(()=>{const sub=queryResults$.subscribe(handleSetResult);return()=>{sub.unsubscribe();};},[handleSetResult,queryResults$]);const reset=React.useCallback(()=>{setHasFullList(false);setIsLazyLoading(false);setResult(INITIAL_STATE);setShouldFetchFullList(false);},[]);React.useEffect(()=>{reset();},[reset,filter,paramsProp,sortOrder,searchQuery]);return{error,hasMaxItems,isLazyLoading,isLoading,isSearchReady:!error,items,onListChange,onRetry};}var __freeze=Object.freeze;var __defProp=Object.defineProperty;var __template=(cooked,raw)=>__freeze(__defProp(cooked,"raw",{value:__freeze(raw||cooked.slice())}));var _a,_b;const EMPTY_ARRAY=[];const rotate=styled.keyframes(_a||(_a=__template(["\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n"])));const AnimatedSpinnerIcon=styled__default.default(icons.SpinnerIcon)(_b||(_b=__template(["\n animation: "," 500ms linear infinite;\n"])),rotate);function useShallowUnique(value){const valueRef=React.useRef(value);if(!shallowEquals__default.default(valueRef.current,value)){valueRef.current=value;}return valueRef.current;}const addSelectedStateToMenuItems=options=>{const{menuItems,sortOrderRaw,layout}=options;return menuItems==null?void 0:menuItems.map(item=>{var _a2,_b2,_c,_d;if((_a2=item.params)==null?void 0:_a2.layout){return{...item,selected:layout===((_b2=item.params)==null?void 0:_b2.layout)};}if((_c=item==null?void 0:item.params)==null?void 0:_c.by){return{...item,selected:isEqual__default.default(sortOrderRaw==null?void 0:sortOrderRaw.by,((_d=item==null?void 0:item.params)==null?void 0:_d.by)||EMPTY_ARRAY)};}return{...item,selected:false};});};const DocumentListPane=React.memo(function DocumentListPane2(props){const{childItemId,index,isActive,isSelected,pane,paneKey}=props;const schema=sanity.useSchema();const{name:parentSourceName}=sanity.useSource();const{defaultLayout="default",displayOptions,initialValueTemplates=EMPTY_ARRAY,menuItemGroups,menuItems,options}=pane;const{apiVersion,defaultOrdering=EMPTY_ARRAY,filter}=options;const params=useShallowUnique(options.params||EMPTY_RECORD);const sourceName=pane.source;const typeName=React.useMemo(()=>getTypeNameFromSingleTypeFilter(filter,params),[filter,params]);const showIcons=(displayOptions==null?void 0:displayOptions.showIcons)!==false;const[layout,setLayout]=useStructureToolSetting(typeName,"layout",defaultLayout);const{t}=sanity.useTranslation(structureLocaleNamespace);const{title}=sanity.useI18nText(pane);const[searchQuery,setSearchQuery]=React.useState("");const[searchInputValue,setSearchInputValue]=React.useState("");const[searchInputElement,setSearchInputElement]=React.useState(null);const showSearchLoadingRef=React.useRef(false);const defaultSortOrder=React.useMemo(()=>{return(defaultOrdering==null?void 0:defaultOrdering.length)>0?{by:defaultOrdering}:DEFAULT_ORDERING;},[defaultOrdering]);const[sortOrderRaw,setSortOrder]=useStructureToolSetting(typeName,"sortOrder",defaultSortOrder);const sortWithOrderingFn=typeName&&sortOrderRaw?applyOrderingFunctions(sortOrderRaw,schema.get(typeName)):sortOrderRaw;const sortOrder=sanity.useUnique(sortWithOrderingFn);const filterIsSimpleTypeConstraint=isSimpleTypeFilter(filter);const{error,hasMaxItems,isLazyLoading,isLoading,isSearchReady,items,onListChange,onRetry}=useDocumentList({apiVersion,filter,params,searchQuery:searchQuery==null?void 0:searchQuery.trim(),sortOrder});const menuItemsWithSelectedState=React.useMemo(()=>addSelectedStateToMenuItems({menuItems,sortOrderRaw,layout}),[layout,menuItems,sortOrderRaw]);const handleQueryChange=reactRx.useObservableCallback(event$=>{return event$.pipe(rxjs.map(event=>event.target.value),rxjs.tap(setSearchInputValue),rxjs.debounce(value=>value===""?rxjs.of(""):rxjs.timer(300)),rxjs.tap(setSearchQuery));},[]);const handleClearSearch=React.useCallback(()=>{setSearchQuery("");setSearchInputValue("");},[]);const handleSearchKeyDown=React.useCallback(event=>{if(event.key==="Escape"){handleClearSearch();}},[handleClearSearch]);React.useEffect(()=>{if(showSearchLoadingRef.current===false&&!isLoading){showSearchLoadingRef.current=true;}return()=>{showSearchLoadingRef.current=false;};},[isLoading]);React.useEffect(()=>{handleClearSearch();showSearchLoadingRef.current=false;},[paneKey,handleClearSearch]);const loadingVariant=React.useMemo(()=>{const showSpinner=isLoading&&items.length===0&&showSearchLoadingRef.current;if(showSpinner)return"spinner";return"initial";},[isLoading,items.length]);const searchInput=/* @__PURE__ */jsxRuntime.jsx(ui.Box,{paddingX:3,paddingBottom:3,children:/* @__PURE__ */jsxRuntime.jsx(ui.TextInput,{"aria-label":t("panes.document-list-pane.search-input.aria-label"),autoComplete:"off",border:false,clearButton:Boolean(searchQuery),disabled:!isSearchReady,fontSize:[2,2,1],icon:loadingVariant==="spinner"?AnimatedSpinnerIcon:icons.SearchIcon,onChange:handleQueryChange,onClear:handleClearSearch,onKeyDown:handleSearchKeyDown,padding:2,placeholder:t("panes.document-list-pane.search-input.placeholder"),radius:2,ref:setSearchInputElement,spellCheck:false,value:searchInputValue})});return/* @__PURE__ */jsxRuntime.jsx(sanity.SourceProvider,{name:sourceName||parentSourceName,children:/* @__PURE__ */jsxRuntime.jsxs(Pane,{currentMaxWidth:350,"data-ui":"DocumentListPane",id:paneKey,maxWidth:640,minWidth:320,selected:isSelected,children:[_DEBUG,/* @__PURE__ */jsxRuntime.jsx(DocumentListPaneHeader,{contentAfter:searchInput,index,initialValueTemplates,menuItemGroups,menuItems:menuItemsWithSelectedState,setLayout,setSortOrder,title}),/* @__PURE__ */jsxRuntime.jsx(DocumentListPaneContent,{childItemId,error,filterIsSimpleTypeConstraint,hasMaxItems,hasSearchQuery:Boolean(searchQuery),isActive,isLazyLoading,isLoading,items,layout,loadingVariant,onListChange,onRetry,paneTitle:title,searchInputElement,showIcons},paneKey)]})});});exports.BackLink=BackLink;exports.ChildLink=ChildLink;exports.ComponentBuilder=ComponentBuilder;exports.ComponentViewBuilder=ComponentViewBuilder;exports.ConfirmDeleteDialogContainer=ConfirmDeleteDialogContainer;exports.DEFAULT_INTENT_HANDLER=DEFAULT_INTENT_HANDLER;exports.DocumentBuilder=DocumentBuilder;exports.DocumentInspectorHeader=DocumentInspectorHeader;exports.DocumentListBuilder=DocumentListBuilder;exports.DocumentListItemBuilder=DocumentListItemBuilder;exports.DocumentListPane=DocumentListPane;exports.DocumentPane=DocumentPane;exports.DocumentPaneProvider=DocumentPaneProvider;exports.DocumentTypeListBuilder=DocumentTypeListBuilder;exports.FormViewBuilder=FormViewBuilder;exports.GenericListBuilder=GenericListBuilder;exports.GenericViewBuilder=GenericViewBuilder;exports.HELP_URL=HELP_URL;exports.InitialValueTemplateItemBuilder=InitialValueTemplateItemBuilder;exports.LOADING_PANE=LOADING_PANE;exports.ListBuilder=ListBuilder;exports.ListItemBuilder=ListItemBuilder;exports.LoadingPane=LoadingPane;exports.MenuItemBuilder=MenuItemBuilder;exports.MenuItemGroupBuilder=MenuItemGroupBuilder;exports.Pane=Pane;exports.PaneContent=PaneContent;exports.PaneHeader=PaneHeader;exports.PaneHeaderActions=PaneHeaderActions;exports.PaneItem=PaneItem;exports.PaneLayout=PaneLayout;exports.PaneRouterContext=PaneRouterContext;exports.ParameterizedLink=ParameterizedLink;exports.ReferenceChildLink=ReferenceChildLink;exports.SerializeError=SerializeError;exports.StructureToolProvider=StructureToolProvider;exports._DEBUG=_DEBUG;exports.component=component;exports.createStructureBuilder=createStructureBuilder;exports.defaultInitialValueTemplateItems=defaultInitialValueTemplateItems;exports.defaultIntentChecker=defaultIntentChecker;exports.documentFromEditor=documentFromEditor;exports.documentFromEditorWithInitialValue=documentFromEditorWithInitialValue;exports.form=form;exports.getOrderingMenuItem=getOrderingMenuItem;exports.getOrderingMenuItemsForSchemaType=getOrderingMenuItemsForSchemaType;exports.getTypeNamesFromFilter=getTypeNamesFromFilter;exports.isDocumentListItem=isDocumentListItem;exports.maybeSerializeInitialValueTemplateItem=maybeSerializeInitialValueTemplateItem;exports.maybeSerializeMenuItem=maybeSerializeMenuItem;exports.maybeSerializeMenuItemGroup=maybeSerializeMenuItemGroup;exports.maybeSerializeView=maybeSerializeView;exports.menuItemsFromInitialValueTemplateItems=menuItemsFromInitialValueTemplateItems;exports.setActivePanes=setActivePanes;exports.shallowIntentChecker=shallowIntentChecker;exports.structureLocaleNamespace=structureLocaleNamespace;exports.structureTool=structureTool;exports.useDocumentPane=useDocumentPane;exports.useDocumentTitle=useDocumentTitle;exports.usePane=usePane;exports.usePaneLayout=usePaneLayout;exports.usePaneRouter=usePaneRouter;exports.useStructureTool=useStructureTool;
508
- //# sourceMappingURL=structure-588eAwLd.js.map
508
+ //# sourceMappingURL=structure-o_wMXC_G.js.map