@blinkk/root-cms 3.0.3 → 3.0.5

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 (47) hide show
  1. package/dist/app.js +2 -1
  2. package/dist/{chunk-7Z5IRD2G.js → chunk-VSPPZPMP.js} +2 -2
  3. package/dist/core/schema.d.ts +20 -0
  4. package/dist/plugin.js +5 -5
  5. package/dist/shared/auto-slug-words.d.ts +7 -0
  6. package/dist/shared/auto-slug.d.ts +14 -0
  7. package/dist/ui/{AIPage-2LUC2PWC.js → AIPage-F3NNYM5E.js} +1 -1
  8. package/dist/ui/{AssetsPage-PODV4QAB.js → AssetsPage-DZQHAENZ.js} +1 -1
  9. package/dist/ui/{CollectionPage-4DMKW5YB.js → CollectionPage-WVVG62NR.js} +1 -1
  10. package/dist/ui/{ComparePage-JMJE5A5Y.js → ComparePage-CRDHP45W.js} +1 -1
  11. package/dist/ui/{DataPage-MVLZT2BU.js → DataPage-WMLBCPGF.js} +1 -1
  12. package/dist/ui/{DataSourcePage-4RPBXRI2.js → DataSourcePage-POZAQFPU.js} +1 -1
  13. package/dist/ui/{DocTranslationsPage-XJSPKGVX.js → DocTranslationsPage-UR5D2RF2.js} +1 -1
  14. package/dist/ui/DocumentPage-SQ7ROBMC.js +1 -0
  15. package/dist/ui/{EditDataSourcePage-3SHAARNL.js → EditDataSourcePage-PUA2AJ4C.js} +1 -1
  16. package/dist/ui/{EditReleasePage-G5VW2OGW.js → EditReleasePage-CENP46EO.js} +1 -1
  17. package/dist/ui/{LogsPage-K6KYEG2P.js → LogsPage-FZRN6MBJ.js} +1 -1
  18. package/dist/ui/{NewDataSourcePage-O2VQEOJG.js → NewDataSourcePage-FTILYFJY.js} +1 -1
  19. package/dist/ui/{NewReleasePage-RSVS32RZ.js → NewReleasePage-MHJC66KK.js} +1 -1
  20. package/dist/ui/{NotFoundPage-ZYD5ILG6.js → NotFoundPage-EP2OE4JV.js} +1 -1
  21. package/dist/ui/{ProjectPage-X3YQBWL4.js → ProjectPage-6J7QCG75.js} +1 -1
  22. package/dist/ui/{ReleasePage-FJHHXNNB.js → ReleasePage-IZ3DNGT4.js} +1 -1
  23. package/dist/ui/{ReleasesPage-VGWIBNEZ.js → ReleasesPage-RWFOJ5VG.js} +1 -1
  24. package/dist/ui/SettingsPage-M4SIDBTI.js +1 -0
  25. package/dist/ui/{SidebarToolsPage-ZBOKPEMP.js → SidebarToolsPage-GAX3XJ7W.js} +1 -1
  26. package/dist/ui/{TaskPage-BQ4OX5WN.js → TaskPage-UCATTNZ5.js} +1 -1
  27. package/dist/ui/{TasksPage-3IGQYVYS.js → TasksPage-4AQLQ4IT.js} +1 -1
  28. package/dist/ui/{TranslationsArbPage-GGHCWPQL.js → TranslationsArbPage-JGQGATCS.js} +1 -1
  29. package/dist/ui/{TranslationsEditPage-E2BCMKYV.js → TranslationsEditPage-7AGZGHKS.js} +1 -1
  30. package/dist/ui/{TranslationsPage-MC4O4ZNI.js → TranslationsPage-WIDVSTYF.js} +1 -1
  31. package/dist/ui/{chunk-UEON4JAT.js → chunk-7MTDTPYB.js} +1 -1
  32. package/dist/ui/{chunk-GXSAEPU3.js → chunk-7UIUAHC4.js} +1 -1
  33. package/dist/ui/{chunk-B6BLDN24.js → chunk-AEWL2RWR.js} +57 -57
  34. package/dist/ui/{chunk-MDUBCXU2.js → chunk-JKCZGT6B.js} +1 -1
  35. package/dist/ui/chunk-P3NETZZP.js +1 -0
  36. package/dist/ui/chunk-P4U2LUTF.js +1 -0
  37. package/dist/ui/{chunk-V7S4IAGB.js → chunk-QGBR3J2Y.js} +1 -1
  38. package/dist/ui/chunk-TJBVMFNQ.js +1 -0
  39. package/dist/ui/ui.css +1 -1
  40. package/dist/ui/ui.js +1 -1
  41. package/package.json +3 -3
  42. package/dist/ui/DocumentPage-R2PVNG24.js +0 -1
  43. package/dist/ui/SettingsPage-C4RXOQ6T.js +0 -1
  44. package/dist/ui/chunk-6IFGKSIE.js +0 -1
  45. package/dist/ui/chunk-IU36W2TB.js +0 -1
  46. package/dist/ui/chunk-NXQVLOTK.js +0 -1
  47. /package/dist/ui/{chunk-B6BLDN24.js.LEGAL.txt → chunk-AEWL2RWR.js.LEGAL.txt} +0 -0
@@ -1 +1 @@
1
- import{a as $}from"./chunk-JHBAMPGB.js";import{a as W}from"./chunk-V7S4IAGB.js";import{f as U}from"./chunk-3IYZCUPI.js";import{a as B,c as L,d as O,i as A}from"./chunk-RSVO46S3.js";import{a as j,c as q}from"./chunk-ONTGW2VA.js";import{a as H}from"./chunk-L4RHGQUG.js";import{a as T}from"./chunk-JDW4UORS.js";import{b as M}from"./chunk-62UWGWON.js";import{a as v}from"./chunk-I6ICVKEC.js";import{d as k}from"./chunk-AL3TN2KI.js";import{Ga as I,Ha as e,Pc as F,Ra as V,W as p,a as c,aa as D,c as N,e as P,ea as f,j as ie,oa as y,qa as z,va as E}from"./chunk-NZHF733K.js";ie();function R(s){let{route:i}=k(),S=P(null),[Y,d]=c(!1),[w,g]=c(""),[G,h]=c(!!s.releaseId),[J,C]=c(null),[m,x]=c([]),[_,b]=c([]),K=W(),Q=$(),{roles:X}=H(),Z=window.firebase.user.email||"",n=j(X,Z);async function ee(r){console.log(r),await M(async()=>{let t=await L(r);C(t),x(t?.docIds||[]),b(t?.dataSourceIds||[])}),h(!1)}N(()=>{s.releaseId&&(h(!0),ee(s.releaseId))},[s.releaseId]);async function oe(){g("");let r=S.current;function t(l){let u=r.elements[l];return u?u.value.trim():""}let o=s.releaseId||t("id");if(!o){g("missing id");return}if(!T(o)){g("id is invalid (alphanumeric characters and dashes only)");return}let a={id:o,description:t("description"),docIds:m,dataSourceIds:_};try{C(a),d(!0),s.releaseId?(await O(s.releaseId,a),v({title:"Saved release",message:`Updated ${o}`,autoClose:5e3}),d(!1)):(await B(o,a),v({title:"Added release",message:`Successfully added ${o}`,autoClose:5e3}),d(!1)),i(`/cms/releases/${o}`)}catch(l){console.error(l),v({title:"Failed to save release",message:String(l),color:"red",autoClose:!1}),d(!1)}}function ae(){K.open({multiSelect:!0,selectedDocIds:m,onChangeMulti:(r,t)=>{x(o=>{let a=[...o];if(t)a.push(r);else{let l=a.findIndex(u=>u===r);l>-1&&a.splice(l,1)}return console.log(a),a.sort()})}})}function se(){Q.open({selectedDataSourceIds:_,onChange:(r,t)=>{b(o=>{let a=[...o];if(t)a.push(r);else{let l=a.indexOf(r);l>-1&&a.splice(l,1)}return a.sort()})}})}function re(r){console.log("onRemoveDoc()",r),x(t=>{let o=[...t],a=o.indexOf(r);return a!==-1&&o.splice(a,1),console.log(o),o})}function te(r){b(t=>{let o=[...t],a=o.indexOf(r);return a!==-1&&o.splice(a,1),o})}return e("form",{className:"ReleaseForm",ref:S,onSubmit:r=>{r.preventDefault(),oe()},children:[e(z,{visible:G}),e(E,{className:"ReleaseForm__input",name:"id",label:"ID",description:"Unique identifier for the release. Use alphanumeric characters and dashes only, e.g. grogus-favorite-meals",size:"xs",radius:0,defaultValue:s.releaseId||A(),disabled:!!s.releaseId}),e(y,{className:"ReleaseForm__input",name:"description",label:"Description",description:"Optional.",size:"xs",radius:0,value:J?.description,disabled:!n}),e(D,{className:"ReleaseForm__input",label:"Docs",description:"Select one or more docs to add to the release. Note: you can add or edit this list at a later time, if needed.",size:"xs",children:[m.length>0&&e(R.DocPreviewCards,{docIds:m,onRemoveDoc:re,canEdit:n}),e(f,{className:"ReleaseForm__docSelectButton",color:"dark",size:"xs",onClick:()=>ae(),disabled:!n,children:"Select"})]}),e(D,{className:"ReleaseForm__input",label:"Data Sources",description:"Optional. Data sources to publish with the release.",size:"xs",children:[_.length>0&&e(R.DataSourceIds,{ids:_,onRemove:te,canEdit:n}),e(f,{className:"ReleaseForm__docSelectButton",color:"dark",size:"xs",onClick:()=>se(),disabled:!n,children:"Select"})]}),e("div",{className:"ReleaseForm__submit__buttons",children:e(q,{label:"You don't have access to create or edit releases",condition:!n,children:e("span",{children:e(f,{className:"ReleaseForm__submit",color:"blue",size:"xs",type:"submit",loading:Y,disabled:!n,children:s.buttonLabel||"Save"})})})}),w&&e("div",{className:"ReleaseForm__error",children:["Error: ",w]})]})}R.DocPreviewCards=s=>e("div",{className:"ReleaseForm__DocPreviewCards",children:s.docIds.map(i=>e("div",{className:"ReleaseForm__DocPreviewCards__card",children:[e(U,{className:"ReleaseForm__DocPreviewCards__card__preview",docId:i}),e("div",{className:"ReleaseForm__DocPreviewCards__card__controls",children:[s.canEdit&&e("div",{className:"ReleaseForm__DocPreviewCards__card__controls__remove",children:e(I,{label:"Remove",children:e(p,{className:"ReleaseForm__DocPreviewCards__card__controls__remove__icon",onClick:()=>s.onRemoveDoc(i),children:e(F,{size:16})})})}),e("div",{className:"ReleaseForm__DocPreviewCards__card__controls__open",children:e(I,{label:"Open",children:e(p,{component:"a",className:"ReleaseForm__DocPreviewCards__card__controls__open__icon",href:`/cms/content/${i}`,target:"_blank",children:e(V,{size:16})})})})]})]},i))});R.DataSourceIds=s=>e("div",{className:"ReleaseForm__DataSourceIds",children:s.ids.map(i=>e("div",{className:"ReleaseForm__DataSourceIds__item",children:[e("span",{className:"ReleaseForm__DataSourceIds__item__id",children:i}),s.canEdit&&e(p,{className:"ReleaseForm__DataSourceIds__item__remove",onClick:()=>s.onRemove(i),children:e(F,{size:16})})]},i))});export{R as a};
1
+ import{a as $}from"./chunk-JHBAMPGB.js";import{a as W}from"./chunk-QGBR3J2Y.js";import{f as U}from"./chunk-3IYZCUPI.js";import{a as B,c as L,d as O,i as A}from"./chunk-RSVO46S3.js";import{a as j,c as q}from"./chunk-ONTGW2VA.js";import{a as H}from"./chunk-L4RHGQUG.js";import{a as T}from"./chunk-JDW4UORS.js";import{b as M}from"./chunk-62UWGWON.js";import{a as v}from"./chunk-I6ICVKEC.js";import{d as k}from"./chunk-AL3TN2KI.js";import{Ga as I,Ha as e,Pc as F,Ra as V,W as p,a as c,aa as D,c as N,e as P,ea as f,j as ie,oa as y,qa as z,va as E}from"./chunk-NZHF733K.js";ie();function R(s){let{route:i}=k(),S=P(null),[Y,d]=c(!1),[w,g]=c(""),[G,h]=c(!!s.releaseId),[J,C]=c(null),[m,x]=c([]),[_,b]=c([]),K=W(),Q=$(),{roles:X}=H(),Z=window.firebase.user.email||"",n=j(X,Z);async function ee(r){console.log(r),await M(async()=>{let t=await L(r);C(t),x(t?.docIds||[]),b(t?.dataSourceIds||[])}),h(!1)}N(()=>{s.releaseId&&(h(!0),ee(s.releaseId))},[s.releaseId]);async function oe(){g("");let r=S.current;function t(l){let u=r.elements[l];return u?u.value.trim():""}let o=s.releaseId||t("id");if(!o){g("missing id");return}if(!T(o)){g("id is invalid (alphanumeric characters and dashes only)");return}let a={id:o,description:t("description"),docIds:m,dataSourceIds:_};try{C(a),d(!0),s.releaseId?(await O(s.releaseId,a),v({title:"Saved release",message:`Updated ${o}`,autoClose:5e3}),d(!1)):(await B(o,a),v({title:"Added release",message:`Successfully added ${o}`,autoClose:5e3}),d(!1)),i(`/cms/releases/${o}`)}catch(l){console.error(l),v({title:"Failed to save release",message:String(l),color:"red",autoClose:!1}),d(!1)}}function ae(){K.open({multiSelect:!0,selectedDocIds:m,onChangeMulti:(r,t)=>{x(o=>{let a=[...o];if(t)a.push(r);else{let l=a.findIndex(u=>u===r);l>-1&&a.splice(l,1)}return console.log(a),a.sort()})}})}function se(){Q.open({selectedDataSourceIds:_,onChange:(r,t)=>{b(o=>{let a=[...o];if(t)a.push(r);else{let l=a.indexOf(r);l>-1&&a.splice(l,1)}return a.sort()})}})}function re(r){console.log("onRemoveDoc()",r),x(t=>{let o=[...t],a=o.indexOf(r);return a!==-1&&o.splice(a,1),console.log(o),o})}function te(r){b(t=>{let o=[...t],a=o.indexOf(r);return a!==-1&&o.splice(a,1),o})}return e("form",{className:"ReleaseForm",ref:S,onSubmit:r=>{r.preventDefault(),oe()},children:[e(z,{visible:G}),e(E,{className:"ReleaseForm__input",name:"id",label:"ID",description:"Unique identifier for the release. Use alphanumeric characters and dashes only, e.g. grogus-favorite-meals",size:"xs",radius:0,defaultValue:s.releaseId||A(),disabled:!!s.releaseId}),e(y,{className:"ReleaseForm__input",name:"description",label:"Description",description:"Optional.",size:"xs",radius:0,value:J?.description,disabled:!n}),e(D,{className:"ReleaseForm__input",label:"Docs",description:"Select one or more docs to add to the release. Note: you can add or edit this list at a later time, if needed.",size:"xs",children:[m.length>0&&e(R.DocPreviewCards,{docIds:m,onRemoveDoc:re,canEdit:n}),e(f,{className:"ReleaseForm__docSelectButton",color:"dark",size:"xs",onClick:()=>ae(),disabled:!n,children:"Select"})]}),e(D,{className:"ReleaseForm__input",label:"Data Sources",description:"Optional. Data sources to publish with the release.",size:"xs",children:[_.length>0&&e(R.DataSourceIds,{ids:_,onRemove:te,canEdit:n}),e(f,{className:"ReleaseForm__docSelectButton",color:"dark",size:"xs",onClick:()=>se(),disabled:!n,children:"Select"})]}),e("div",{className:"ReleaseForm__submit__buttons",children:e(q,{label:"You don't have access to create or edit releases",condition:!n,children:e("span",{children:e(f,{className:"ReleaseForm__submit",color:"blue",size:"xs",type:"submit",loading:Y,disabled:!n,children:s.buttonLabel||"Save"})})})}),w&&e("div",{className:"ReleaseForm__error",children:["Error: ",w]})]})}R.DocPreviewCards=s=>e("div",{className:"ReleaseForm__DocPreviewCards",children:s.docIds.map(i=>e("div",{className:"ReleaseForm__DocPreviewCards__card",children:[e(U,{className:"ReleaseForm__DocPreviewCards__card__preview",docId:i}),e("div",{className:"ReleaseForm__DocPreviewCards__card__controls",children:[s.canEdit&&e("div",{className:"ReleaseForm__DocPreviewCards__card__controls__remove",children:e(I,{label:"Remove",children:e(p,{className:"ReleaseForm__DocPreviewCards__card__controls__remove__icon",onClick:()=>s.onRemoveDoc(i),children:e(F,{size:16})})})}),e("div",{className:"ReleaseForm__DocPreviewCards__card__controls__open",children:e(I,{label:"Open",children:e(p,{component:"a",className:"ReleaseForm__DocPreviewCards__card__controls__open__icon",href:`/cms/content/${i}`,target:"_blank",children:e(V,{size:16})})})})]})]},i))});R.DataSourceIds=s=>e("div",{className:"ReleaseForm__DataSourceIds",children:s.ids.map(i=>e("div",{className:"ReleaseForm__DataSourceIds__item",children:[e("span",{className:"ReleaseForm__DataSourceIds__item__id",children:i}),s.canEdit&&e(p,{className:"ReleaseForm__DataSourceIds__item__remove",onClick:()=>s.onRemove(i),children:e(F,{size:16})})]},i))});export{R as a};
@@ -0,0 +1 @@
1
+ import{a as h}from"./chunk-YDO2EDVY.js";import{g as y}from"./chunk-XOQ3KDSR.js";import{a as x}from"./chunk-5MV6XVGA.js";import{c as f,n as g}from"./chunk-EGEB6N4J.js";async function b(e){let t=window.firebase.db,r=window.__ROOT_CTX.rootConfig.projectId,[o,a]=e.split("/",2),i=await h(o),n=f(t,"Projects",r,"Collections",o,"Drafts",a),c=(await g(n)).data()||{},p=new Set;return m(p,i.fields,c.fields||{},i.types||{}),Array.from(p)}async function C(e){let t=window.firebase.db,r=window.__ROOT_CTX.rootConfig.projectId,[o,a]=e.split("/",2),i=await h(o),n=f(t,"Projects",r,"Collections",o,"Drafts",a),c=(await g(n)).data()||{},p=new Map;return d(p,i.fields,c.fields||{},i.types||{}),p}function m(e,t,r,o={}){t.forEach(a=>{if(!a.id)return;let i=r[a.id],n=`@${a.id}`,s=r[n];s?.translate===!1||s?.disableTranslations||R(e,a,i,o,s)})}function d(e,t,r,o={}){t.forEach(a=>{if(!a.id)return;let i=r[a.id],n=`@${a.id}`,s=r[n];if(s?.translate===!1||s?.disableTranslations)return;let c=s?.description;S(e,a,i,o,c,s)})}function R(e,t,r,o={},a){if(!r)return;function i(n){let s=y(n);s&&e.add(s)}if(t.type==="object")m(e,t.fields||[],r,o);else if(t.type==="array"){let n=r._array||[];for(let s of n)R(e,t.of,r[s],o)}else if(t.type==="string"||t.type==="select")t.translate&&i(r);else if(t.type==="image")t.translate&&r&&r.alt&&t.alt!==!1&&a?.alt!==!1&&i(r.alt);else if(t.type==="multiselect"){if(t.translate&&Array.isArray(r))for(let n of r)i(n)}else if(t.type==="oneof"){let n=t.types||[],s;typeof n[0]=="string"?n.includes(r._type)&&(s=o[r._type]):s=n.find(c=>c.name===r._type),s&&m(e,s.fields||[],r,o)}else t.type==="richtext"?t.translate&&T(e,r):console.log(`extract: ignoring field, id=${t.id}, type=${t.type}`)}function S(e,t,r,o={},a,i){if(!r)return;function n(s){let c=y(s);if(c){let p=e.get(c);(!p||!p.description)&&e.set(c,{description:a})}}if(t.type==="object")d(e,t.fields||[],r,o);else if(t.type==="array"){let s=r._array||[];for(let c of s)S(e,t.of,r[c],o,a)}else if(t.type==="string"||t.type==="select")t.translate&&n(r);else if(t.type==="image")t.translate&&r&&r.alt&&t.alt!==!1&&i?.alt!==!1&&n(r.alt);else if(t.type==="multiselect"){if(t.translate&&Array.isArray(r))for(let s of r)n(s)}else if(t.type==="oneof"){let s=t.types||[],c;typeof s[0]=="string"?s.includes(r._type)&&(c=o[r._type]):c=s.find(p=>p.name===r._type),c&&d(e,c.fields||[],r,o)}else if(t.type==="richtext"&&t.translate){let s=new Set;T(s,r),s.forEach(c=>n(c))}}function T(e,t){(t?.blocks||[]).forEach(o=>{l(e,o)})}function l(e,t){if(!t?.type)return;function r(n){if(!n)return;let s=y(n);s&&e.add(s)}function o(n){n&&Object.values(n).forEach(s=>{a(s)})}function a(n){if(typeof n=="string"){r(n);return}if(Array.isArray(n)){n.forEach(s=>a(s));return}x(n)&&Object.values(n).forEach(s=>a(s))}function i(n){n&&n.forEach(s=>{r(s.content),o(s.components),i(s.items)})}t.type==="heading"||t.type==="paragraph"?(r(t.data?.text),o(t.data?.components)):t.type==="orderedList"||t.type==="unorderedList"?i(t.data?.items):t.type==="html"?r(t.data?.html):t.type==="table"&&(t.data?.rows||[]).forEach(s=>{(s.cells||[]).forEach(p=>{(p.blocks||[]).forEach(w=>{l(e,w)})})})}export{b as a,C as b,R as c};
@@ -0,0 +1 @@
1
+ import{b as se}from"./chunk-54DVDYU6.js";import{a as te,b as R,c as k}from"./chunk-JDW4UORS.js";import{a as ie}from"./chunk-YDO2EDVY.js";import{c as ne,s as re}from"./chunk-AFWBSIPL.js";import{b as oe}from"./chunk-62UWGWON.js";import{a as U}from"./chunk-I6ICVKEC.js";import{a as P}from"./chunk-HLMBCVRX.js";import{a as z}from"./chunk-5MV6XVGA.js";import{b as K,f as H,g as E,i as C,o as Z}from"./chunk-EGEB6N4J.js";import{d as ee,f as ae}from"./chunk-AL3TN2KI.js";import{A as W,Aa as Q,Ha as g,a as p,c as v,e as S,ea as j,g as X,h as N,i as B,j as D,sa as G,va as J}from"./chunk-NZHF733K.js";import{j as q,k as Ee}from"./chunk-KUCVLANF.js";function $(e){let t=window.__ROOT_CTX.collections[e.collectionId];if(!t)throw new Error(`collection not found: ${e.collectionId}`);if(!t.url)return"";let n=t.domain||window.__ROOT_CTX.rootConfig.domain||"https://example.com",r=Ce(e);return`${n}${r}`}function Ce(e){let o=window.__ROOT_CTX.collections,{collectionId:t,slug:n,locale:r}=e,a=o[t];if(!a)throw new Error(`collection not found: ${t}`);if(!a.url)return"";let s=window.__ROOT_CTX.rootConfig,f=s.base||"/",l="/[base]/[path]";r&&(l=s.i18n.urlFormat||"/[locale]/[base]/[path]");let d="",u=a?.url;if(u)if(n){let c=u.replace(/\[.*slug\]/,n).replaceAll("--","/").replace(/\/+/g,"/");c==="/index"&&(c="/"),d=c}else d=u;return le(l,{base:f,path:d,locale:r||"",slug:n})}function ze(e){let o=window.__ROOT_CTX.collections,{collectionId:t,slug:n,locale:r}=e,a=o[t];if(!a)throw new Error(`collection not found: ${t}`);let s=window.__ROOT_CTX.rootConfig,f=s.base||"/",l="/[base]/[path]";r&&(l=s.i18n.urlFormat||"/[locale]/[base]/[path]");let d="",u=a?.previewUrl||a?.url;if(u)if(n){let c=u.replace(/\[.*slug\]/,n).replaceAll("--","/").replace(/\/+/g,"/");c==="/index"&&(c="/"),d=c}else d=u;return le(l,{base:f,path:d,locale:r||"",slug:n})}function le(e,o){let t=e.replaceAll(/\[\[?(\.\.\.)?([\w\-_]*)\]?\]/g,(n,r,a)=>o[a]??n);return ke(t,{trailingSlash:window.__ROOT_CTX.rootConfig.server.trailingSlash})}function ke(e,o){return e=e.replace(/\/+/g,"/"),o?.trailingSlash===!1&&e!=="/"&&e.endsWith("/")&&(e=e.replace(/\/*$/g,"")),(e.endsWith("/index")||e.endsWith("/index/"))&&(e=e.slice(0,-6)),e.startsWith("/")||(e=`/${e}`),o?.trailingSlash&&!e.endsWith("/")&&(e=`${e}/`),e}D();function $e(e,o){let[t,n]=p([]),[r,a]=p(!0),f=se().db,l=window.__ROOT_CTX.rootConfig.projectId||"default",d=o.includeArchived??!1,u=async()=>{a(!0);let c=K(f,"Projects",l,"Collections",e,"Drafts"),i=c,m=o.orderBy;if(m==="modifiedAt")i=E(c,C("sys.modifiedAt","desc"));else if(m==="newest")i=E(c,C("sys.createdAt","desc"));else if(m==="oldest")i=E(c,C("sys.createdAt"));else if(m==="slug")i=E(c,C(H()));else if(m==="slugDesc")i=E(c,C(H(),"desc"));else{let y=window.__ROOT_CTX.collections[e]?.sortOptions?.find(w=>w.id===m);y&&(i=y.direction==="desc"?E(c,C(y.field,"desc")):E(c,C(y.field)))}await oe(async()=>{let h=await Z(i),y=[];h.docs.forEach(w=>{let L=w.data(),b=w.id,_=`${e}/${b}`,x={...L,id:_,slug:b};ne(_,x),!(!d&&x?.sys?.archivedAt)&&y.push(x)}),n(y)}),a(!1)};return v(()=>{a(!0),u()},[e,o.orderBy,d]),[r,u,t]}Ee();D();var O={CONNECTED:"connected",SCHEMA_CHANGED:"schemaChanged"};function ce(e){let t=new URLSearchParams(window.location.search).get("e");return t?t.split(",").includes(e):!1}var _e="/cms/api/sse.connect",I=ce("EnableVerboseLogging"),ue=window.location.hostname==="localhost",F=class{constructor(){this.map=new Map}on(o,t){return this.map.has(o)||this.map.set(o,new Set),this.map.get(o).add(t),()=>{this.map.get(o)?.delete(t)}}emit(o,t,n){this.map.get(o)?.forEach(r=>r(t,n)),this.map.get("*")?.forEach(r=>r({type:o,data:t},n))}},ge=q(null);function Qe(e){let t=S(new F).current,n=S(null),r=S(!1),a=S({attempt:0,timer:0}),s=S(""),f=()=>{n.current&&(n.current.close(),n.current=null)},l=N(()=>{I&&console.log("[sse] connecting..."),f();let u=new EventSource(_e);n.current=u,u.addEventListener(O.CONNECTED,i=>{if(I&&console.log("[sse] connected"),r.current=!1,a.current.attempt=0,ue){let h=de(i.data)?.serverVersion||"";s.current?s.current!==h&&(console.log(`server version changed: ${s.current} -> ${h}`),console.log("reloading..."),window.location.reload()):s.current=h}});let c=i=>{if(!i||!i.type)return;let m=de(i.data);I&&console.log("[sse] event:",i.type,m),t.emit(i.type,m,i)};Object.values(O).forEach(i=>{u.addEventListener(i,c)}),u.addEventListener("error",()=>{I&&console.log("[sse] disconnected"),u.readyState===EventSource.CLOSED&&!r.current&&(r.current=!0,(()=>{let m=++a.current.attempt,h=Math.min(3e4,Math.pow(2,m)*500),y=Math.random()*.3*h,w=h+y;window.clearTimeout(a.current.timer),a.current.timer=window.setTimeout(()=>{r.current=!1,l()},w)})())})},[t]);v(()=>{if(!ue)return;l();let u=()=>{document.visibilityState==="visible"&&n.current?.readyState!==EventSource.OPEN&&l()};return document.addEventListener("visibilitychange",u),()=>{document.removeEventListener("visibilitychange",u),window.clearTimeout(a.current.timer),f()}},[l]);let d=X(()=>({emitter:t}),[t]);return g(ge.Provider,{value:d,children:e.children})}function de(e){try{return JSON.parse(e)}catch{return e}}function fe(e,o){let t=B(ge);if(!t)throw new Error("useSSE() must be used within an <SSEProvider>");let n=S(o);v(()=>{n.current=o},[o]),v(()=>t.emitter.on(e,(r,a)=>n.current(r,a)),[t,e])}D();var me=["agile","amber","amused","ancient","autumn","azure","balmy","beige","big","bitter","black","blue","bold","brave","breezy","bright","brisk","broad","bronze","brown","bubbly","busy","calm","candid","careful","caring","cheerful","cherry","chilly","classic","clean","clear","clever","cloudy","cobalt","cold","cool","cosmic","cosy","cozy","crimson","crisp","cuddly","curious","daring","dark","dawn","dazzling","dear","deep","delicate","dewy","dizzy","dreamy","dry","dusky","dusty","eager","early","earnest","easy","electric","elegant","emerald","empty","epic","even","every","faint","fair","falling","famous","fancy","fast","feisty","fierce","fiery","fine","firm","flat","fluffy","foggy","fond","forest","fragrant","fresh","friendly","frosty","funky","funny","fuzzy","gentle","giant","glad","gleaming","glossy","gold","golden","good","graceful","grand","grassy","gray","green","groovy","happy","hardy","hazy","hearty","heavy","helpful","hidden","high","holy","honest","hopeful","humble","humming","icy","ideal","idle","indigo","inky","iron","ivory","jade","jazzy","jolly","jovial","joyful","juicy","jumpy","keen","kind","lacy","late","lazy","lemon","light","lime","linen","little","lively","lone","long","loud","lovely","loyal","lucid","lucky","lush","magenta","magic","mango","marble","maroon","massive","mauve","mellow","merry","mighty","mild","milky","mindful","minty","misty","mocha","modest","morning","mossy","muddy","mysterious","narrow","navy","neat","neon","new","nimble","noble","noisy","noon","nosy","oaken","odd","old","olive","onyx","opal","open","orange","pale","patient","peach","peachy","pearly","peppy","perky","pink","placid","plain","playful","plucky","plum","plush","polite","proud","pure","purple","quaint","quick","quiet","quirky","rapid","rare","raven","ready","red","restless","rich","rosy","rough","round","royal","ruby","rugged","rustic","sable","safe","sage","salty","sandy","sapphire","savvy","scarlet","secret","sepia","serene","shaggy","sharp","shiny","short","shrewd","shy","silent","silky","silly","silver","simple","sleek","sleepy","slim","slow","small","smart","smoky","smooth","snappy","snowy","soft","solar","solid","spicy","spiffy","spry","square","steady","steel","sticky","still","stony","stormy","strong","sturdy","sunny","super","swank","sweet","swift","tame","tan","tart","teal","tender","thin","thirsty","tidy","tiny","tireless","topaz","tough","tranquil","trim","true","twinkly","umber","upbeat","urban","useful","vast","velvet","vibrant","vintage","violet","vivid","warm","watchful","wavy","wee","whimsical","whispering","white","wild","windy","winter","wise","witty","woody","wool","yellow","young","youthful","zealous","zen","zesty","zippy"],pe=["acorn","alpaca","anchor","apple","apricot","arrow","autumn","badger","bagel","bamboo","banana","bay","beach","bear","bee","beetle","bell","berry","bird","biscuit","blossom","boat","book","boot","bottle","boulder","branch","brass","breeze","bridge","brook","broom","brunch","bubble","bucket","bud","buffalo","bug","bunny","burrow","butter","button","cabin","cactus","cake","camel","candle","canyon","cape","cardinal","carrot","cat","cave","cedar","chair","cherry","chestnut","chickpea","cliff","cloud","clove","clover","cocoa","comet","compass","cookie","coral","cottage","cotton","cove","crane","crayon","creek","cricket","crow","crumpet","crystal","cup","cupcake","currant","cypress","daffodil","dahlia","daisy","dawn","deer","desert","dew","diamond","dingo","dock","dolphin","donut","dove","dragon","drizzle","drum","duck","dumpling","dune","eagle","echo","eel","egg","elder","elephant","elk","ember","ermine","estuary","falcon","fawn","feather","fern","field","fig","finch","fir","firefly","fish","flame","flamingo","flask","flax","fleece","flower","flute","fog","forest","fountain","fox","frog","frost","galaxy","garden","gecko","gem","ginger","glacier","globe","glow","goat","goose","gorge","grape","grass","grove","gull","hammock","hare","harp","harvest","hat","hawk","haystack","hazel","heather","hedge","heron","hill","honey","horizon","horse","iceberg","iris","island","ivy","jacket","jade","jaguar","jam","jar","jasmine","jay","jelly","juniper","kayak","kelp","kettle","key","kingfisher","kite","kitten","koala","ladybug","lagoon","lake","lamp","lantern","lark","lava","leaf","lemon","lemur","leopard","lighthouse","lilac","lily","lime","lion","llama","lobster","log","lotus","lynx","magnet","mango","maple","marble","marlin","meadow","melody","melon","mermaid","meteor","mint","mist","mitten","mole","monkey","moon","moose","morel","moss","moth","mountain","mouse","muffin","mushroom","mussel","nectar","needle","nest","newt","nimbus","noodle","north","note","oak","oasis","oats","ocean","octopus","olive","onion","opal","orange","orchid","otter","owl","oyster","paddle","palm","panda","pansy","panther","paper","parrot","partridge","pasture","path","peach","peacock","pear","pebble","pelican","penguin","peony","pepper","petal","phoenix","pie","pigeon","pine","pineapple","planet","plover","plum","pond","pony","poppy","pouch","prairie","puffin","pumpkin","quail","quartz","queen","quill","rabbit","raccoon","radish","rain","rainbow","raven","reef","reel","reindeer","rhino","ribbon","ridge","river","road","robin","rock","rose","rowan","sage","salmon","sand","sapphire","satellite","scarf","sea","seagull","seal","seed","shark","shell","shore","shrimp","silk","silo","sky","sleet","snail","snake","snow","sock","spark","sparrow","spider","spire","spoon","spring","spruce","squirrel","star","starling","stone","stork","storm","stream","summer","sun","sundial","swan","swift","tadpole","tea","teal","thicket","thistle","thrush","thunder","tide","tiger","toad","tooth","topaz","tortoise","totem","tower","tractor","trail","tree","truffle","tulip","tundra","turtle","twig","twilight","umbrella","unicorn","urchin","valley","vine","violet","volcano","vulture","wagon","walnut","walrus","wasp","water","wave","whale","wheat","whisker","wildcat","willow","wind","window","winter","wolf","wombat","wood","wren","yak","yam","zebra","zinnia"];var he="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",xe="YYYYMMDD";function be(e,o){let t=o?.now??new Date,n=o?.random??Math.random,r=e.replace(/\{([^{}]+?)\}/g,(a,s)=>{let[f,l]=De(s);switch(f){case"date":return Me(t,l||xe);case"adjective":return ye(me,n);case"noun":return ye(pe,n);case"random":return Te(Oe(l,6),n);default:return a}});return k(r.toLowerCase())}function De(e){let o=e.indexOf(":");return o===-1?[e.trim(),void 0]:[e.slice(0,o).trim(),e.slice(o+1)]}function Oe(e,o){if(!e)return o;let t=parseInt(e,10);return Number.isFinite(t)&&t>0?t:o}function ye(e,o){return e[Math.floor(o()*e.length)]}function Te(e,o){let t=[];for(let n=0;n<e;n++)t.push(he.charAt(Math.floor(o()*he.length)));return t.join("")}function Me(e,o){let t={YYYY:String(e.getFullYear()),YY:String(e.getFullYear()).slice(-2),MM:T(e.getMonth()+1),DD:T(e.getDate()),HH:T(e.getHours()),mm:T(e.getMinutes()),ss:T(e.getSeconds())};return o.replace(/YYYY|YY|MM|DD|HH|mm|ss/g,n=>t[n]??n)}function T(e){return e<10?`0${e}`:String(e)}D();function we(e){let[o,t]=p(!0),[n,r]=p(null),a=N(async()=>{try{let s=await ie(e);r(s)}catch(s){console.error(s),U({title:`Failed to load collection: ${e}`,message:String(s),color:"red",autoClose:!1})}t(!1)},[e]);return v(()=>{a()},[e]),fe(O.SCHEMA_CHANGED,async s=>{await a();let f=s.file?`Applied updates from changes to ${s.file}.`:"Applied updates from changes to a .schema.ts file.";U({title:"Updated schema!",message:f})}),{loading:o,schema:n}}function Y(e){let o={_array:[]};return e.forEach(t=>{let n=Ne();o._array.push(n),o[n]=t}),o}function Ne(){let e=[],o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=o.length;for(let n=0;n<6;n++)e.push(o.charAt(Math.floor(Math.random()*t)));return e.join("")}function V(e){let o={};return e.fields.forEach(t=>{t.id&&(t.type==="array"&&t.default&&Array.isArray(t.default)?o[t.id]=Y(t.default):t.default?o[t.id]=t.default:t.type==="object"&&(o[t.id]=V(t)))}),o}function A(e,o,t){let n={...o};return e.fields.forEach(r=>{if(!r.id)return;let a=n[r.id];if(a!=null){if(r.type==="array"&&Array.isArray(a)){let s=a.map(f=>Re(r.of,f,t));n[r.id]=Y(s)}else if(r.type==="object"&&z(a))n[r.id]=A(r,a,t);else if(r.type==="oneof"&&z(a)&&typeof a._type=="string"&&t){let s=t[a._type];s&&(n[r.id]=A(s,a,t))}}}),n}function Re(e,o,t){if(!z(o))return o;if(e.type==="object")return A(e,o,t);if(e.type==="oneof"&&typeof o._type=="string"&&t){let n=t[o._type];if(n)return A(n,o,t)}return o}D();function Se(e){let[o,t]=p(e.collectionId||""),n=S(null),[r,a]=p(e.initialSlug||""),s=window.__ROOT_CTX.collections[o],f=[];e.collectionId&&e.collectionDisabled?f.push({value:e.collectionId,label:e.collectionId}):Object.keys(window.__ROOT_CTX.collections).forEach(i=>{f.push({value:i,label:i})});let l="",d="";if(s?.url){if(r){let i=k(r),m=s?.slugRegex;te(i,m)?l=$({collectionId:o,slug:i}):d=R(i,m)}else l=$({collectionId:o,slug:"[slug]"});l.endsWith("/index")&&(l=l.replace(/\/index$/,"/"))}function u(i){t(i),e.onChange&&e.onChange({collectionId:i,slug:r})}function c(i){a(i),e.onChange&&e.onChange({collectionId:o,slug:i})}return g("div",{className:ae(e.className,"SlugInput"),children:[g("div",{className:"SlugInput__inputs",children:[g(Q,{className:"SlugInput__collection",placeholder:"Collection",size:"xs",data:f,onChange:i=>u(i),value:o,disabled:!!e.collectionDisabled}),g("div",{className:"SlugInput__divider",children:"/"}),g(J,{className:"SlugInput__slug",name:"slug",ref:n,value:r,onChange:i=>{c(i.currentTarget.value)},placeholder:"slug",autoComplete:"off",size:"xs"})]}),l&&g(P,{className:"SlugInput__urlHelp",size:"body-sm",children:l}),d&&g(P,{className:"SlugInput__slugError",size:"body-sm",children:d})]})}function Ut(e){let{route:o}=ee(),t=W(),n=e.collection,r=window.__ROOT_CTX.collections[n];if(!r)throw new Error(`collection not found: ${n}`);let[a]=p(()=>r.autoSlug?be(r.autoSlug):""),[s,f]=p(a),[l,d]=p(!1),[u,c]=p(()=>y(a)),[i,m]=p(""),h=we(n);function y(b){let _=k(b);return _?R(_,r.slugRegex):""}function w(){e.onClose&&e.onClose()}async function L(b){if(b.preventDefault(),d(!0),c(""),y(s)){d(!1);return}let x=k(s),ve=`${n}/${x}`;try{let M={};!h.loading&&h.schema&&(M=await V(h.schema)),await re(ve,{fields:M})}catch(M){m(String(M)),d(!1);return}d(!1),e.skipNavigation?w():o(`/cms/content/${e.collection}/${x}`)}return g(G,{className:"NewDocModal",opened:e.opened||!1,onClose:()=>w(),title:"New",size:"500px",overlayColor:t.colorScheme==="dark"?t.colors.dark[9]:t.colors.gray[2],children:[g("div",{className:"NewDocModal__body",children:"Enter a slug for the new doc. The slug is the ID of the page and is what's used in the URL. Use only lowercase letters, numbers, and dashes."}),g("form",{onSubmit:b=>L(b),children:[g(Se,{className:"NewDocModal__slug",collectionId:n,initialSlug:a,onChange:b=>{f(b.slug),c(y(b.slug)),m("")}}),i&&g("div",{className:"NewDocModal__slugError",children:i}),g("div",{className:"NewDocModal__buttons",children:[g(j,{variant:"outline",onClick:()=>w(),type:"button",size:"xs",color:"dark",children:"Cancel"}),g(j,{variant:"filled",type:"submit",size:"xs",color:"dark",loading:h.loading||l,disabled:!!u||!!i,children:"Submit"})]})]})]})}export{$ as a,Ce as b,ze as c,Se as d,$e as e,Qe as f,we as g,V as h,A as i,Ut as j};
@@ -1 +1 @@
1
- import{e as z,j as I}from"./chunk-NXQVLOTK.js";import{c as N,e as L}from"./chunk-3IYZCUPI.js";import{a as C}from"./chunk-X2WHBGTP.js";import{a as w,c as y}from"./chunk-HRGYNHZ3.js";import{b as v}from"./chunk-5MV6XVGA.js";import{Aa as f,Ac as B,Ha as e,V as P,a as g,ea as p,g as M,j as x,va as S}from"./chunk-NZHF733K.js";x();x();function O(o,t){return M(()=>{if(!t.trim())return o;let l=t.toLowerCase();return o.filter(c=>{let[a,u]=c.id.split("/"),r=c.fields||{},n=window.__ROOT_CTX.collections[a],s=v(r,n.preview?.title||"meta.title")||"";return c.id.toLowerCase().includes(l)||s.toLowerCase().includes(l)||u.toLowerCase().includes(l)})},[o,t])}var h="DocPickerModal";function ee(){let o=w(),t=y();return{open:l=>{o.openContextModal(h,{...t,innerProps:l,size:"700px",overflow:"inside"})},close:()=>{o.closeModal(h)}}}function k(o){let{innerProps:t}=o,l=Object.keys(window.__ROOT_CTX.collections);t.collections?.length&&(l=l.filter(i=>t.collections?.includes(i)));let c=[{value:"",label:"Select"}];l.forEach(i=>{c.push({value:i,label:i})});let[a,u]=C("DocPickerModal.lastSelectedCollection",""),r=()=>t.initialCollection?t.initialCollection:a&&l.includes(a)?a:l.length===1?l[0]:"",[n,D]=g(r()),s=i=>{D(i),u(i)};function m(i){t.multiSelect&&t.onChangeMulti?t.onChangeMulti(i.id,!0):t.onChange&&t.onChange(i.id)}function b(i){t.multiSelect&&t.onChangeMulti&&t.onChangeMulti(i.id,!1)}return e("div",{className:"DocPickerModal",children:[l.length===0&&e("div",{className:"DocPickerModal__noCollections",children:"No collections matching schema field definition."}),l.length>0&&e(k.DocsList,{collection:n,onDocSelected:m,onDocUnselected:b,onCollectionChange:s,multiSelect:t.multiSelect,selectedDocIds:t.selectedDocIds,options:{enableSearch:t.enableSearch??!0,enableSort:t.enableSort??!0,enableCreate:t.enableCreate??!0,enableStatusBadges:t.enableStatusBadges??!0,showCollectionSelect:l.length>1,collectionSelectValue:n,collectionSelectOptions:c}})]})}k.DocsList=o=>{let[t,l]=g(""),[c,a]=C(`root::DocPickerModal:${o.collection}:sortBy`,"modifiedAt"),[u,r]=g(!1),[n,D,s]=z(o.collection||"",{orderBy:c}),m=O(s,t),b=[{value:"modifiedAt",label:"Last Modified"},{value:"slug",label:"A-Z"},{value:"slugDesc",label:"Z-A"},{value:"newest",label:"Newest"},{value:"oldest",label:"Oldest"}],i=o.selectedDocIds||[],d=o.options||{};return e("div",{className:"DocPickerModal__DocsList",children:[e("div",{className:"DocPickerModal__DocsList__stickyHeader",children:[d.showCollectionSelect&&e("div",{className:"DocPickerModal__collection__select",children:[e("div",{className:"DocPickerModal__collection__select__label",children:"Content Type:"}),e(f,{data:d.collectionSelectOptions||[],value:d.collectionSelectValue,placeholder:"Select",onChange:_=>{o.onCollectionChange?.(_||"")},size:"xs",radius:0,searchable:!0,autoFocus:!0,dropdownComponent:"div"}),d.collectionSelectValue&&e(p,{variant:"outline",color:"dark",size:"xs",onClick:()=>r(!0),children:"New"})]}),d.enableSearch&&d.collectionSelectValue&&e("div",{className:"DocPickerModal__DocsList__controls",children:[e(S,{placeholder:"Search documents...",value:t,onChange:_=>l(_.target.value),icon:e(B,{size:16}),size:"xs",className:"DocPickerModal__DocsList__controls__search"}),d.enableSort&&e(f,{data:b,value:c,onChange:_=>a(_||"modifiedAt"),size:"xs",className:"DocPickerModal__DocsList__controls__sort"})]}),!n&&s.length>0&&e("div",{className:"DocPickerModal__DocsList__count",children:["Showing ",m.length," of ",s.length," documents"]})]}),e("div",{className:"DocPickerModal__DocsList__docsContainer",children:o.collection?n?e("div",{className:"DocPickerModal__DocsList__loading",children:e(P,{color:"gray",size:"xl"})}):m.length===0?e("div",{className:"DocPickerModal__DocsList__empty",children:s.length===0?"Collection is empty.":"No documents match your search."}):e("div",{className:"DocPickerModal__DocsList__docs",children:m.map(_=>e(k.DocCard,{doc:_,onDocSelected:o.onDocSelected,onDocUnselected:o.onDocUnselected,multiSelect:o.multiSelect,selected:i.includes(_.id),enableStatusBadges:d.enableStatusBadges},_.id))}):e("div",{className:"DocPickerModal__DocsList__empty",children:"Select a content type to view documents"})}),d.collectionSelectValue&&e(I,{collection:d.collectionSelectValue,opened:u,skipNavigation:!0,onClose:()=>{r(!1),D()}})]})};k.DocCard=o=>{let[t,l]=g(!!o.selected),c=o.doc,[a,u]=c.id.split("/"),r=c.fields||{},n=window.__ROOT_CTX.collections[a],D=`/cms/content/${a}/${u}`,s=v(r,n.preview?.title||"meta.title"),m=v(r,n.preview?.image||"meta.image")||n.preview?.defaultImage;return e("div",{className:"DocPickerModal__DocCard",children:[e("div",{className:"DocPickerModal__DocCard__image",onClick:()=>window.open(D,"_blank"),children:e(L,{file:m,width:120,height:90,withPlaceholder:!m?.src})}),e("div",{className:"DocPickerModal__DocCard__content",children:[e("div",{className:"DocPickerModal__DocCard__content__header",children:e("div",{className:"DocPickerModal__DocCard__content__header__docId",onClick:()=>window.open(D,"_blank"),children:c.id})}),e("div",{className:"DocPickerModal__DocCard__content__title",children:e("div",{className:"DocPickerModal__DocCard__content__link",onClick:()=>window.open(D,"_blank"),children:s||"[UNTITLED]"})}),o.enableStatusBadges&&e("div",{className:"DocPickerModal__DocCard__content__badges",children:e(N,{doc:c})})]}),e("div",{className:"DocPickerModal__DocCard__controls",children:e("div",{className:"DocPickerModal__DocCard__controls__buttons",children:o.multiSelect?t?e(p,{variant:"light",color:"blue",size:"xs",onClick:()=>{l(!1),o.onDocUnselected(o.doc)},children:"Unselect"}):e(p,{variant:"filled",color:"blue",size:"xs",onClick:()=>{l(!0),o.onDocSelected(o.doc)},children:"Select"}):e(p,{color:"blue",size:"xs",onClick:()=>o.onDocSelected(o.doc),children:"Select"})})})]})};k.id=h;export{ee as a,k as b};
1
+ import{e as z,j as I}from"./chunk-P4U2LUTF.js";import{c as N,e as L}from"./chunk-3IYZCUPI.js";import{a as C}from"./chunk-X2WHBGTP.js";import{a as w,c as y}from"./chunk-HRGYNHZ3.js";import{b as v}from"./chunk-5MV6XVGA.js";import{Aa as f,Ac as B,Ha as e,V as P,a as g,ea as p,g as M,j as x,va as S}from"./chunk-NZHF733K.js";x();x();function O(o,t){return M(()=>{if(!t.trim())return o;let l=t.toLowerCase();return o.filter(c=>{let[a,u]=c.id.split("/"),r=c.fields||{},n=window.__ROOT_CTX.collections[a],s=v(r,n.preview?.title||"meta.title")||"";return c.id.toLowerCase().includes(l)||s.toLowerCase().includes(l)||u.toLowerCase().includes(l)})},[o,t])}var h="DocPickerModal";function ee(){let o=w(),t=y();return{open:l=>{o.openContextModal(h,{...t,innerProps:l,size:"700px",overflow:"inside"})},close:()=>{o.closeModal(h)}}}function k(o){let{innerProps:t}=o,l=Object.keys(window.__ROOT_CTX.collections);t.collections?.length&&(l=l.filter(i=>t.collections?.includes(i)));let c=[{value:"",label:"Select"}];l.forEach(i=>{c.push({value:i,label:i})});let[a,u]=C("DocPickerModal.lastSelectedCollection",""),r=()=>t.initialCollection?t.initialCollection:a&&l.includes(a)?a:l.length===1?l[0]:"",[n,D]=g(r()),s=i=>{D(i),u(i)};function m(i){t.multiSelect&&t.onChangeMulti?t.onChangeMulti(i.id,!0):t.onChange&&t.onChange(i.id)}function b(i){t.multiSelect&&t.onChangeMulti&&t.onChangeMulti(i.id,!1)}return e("div",{className:"DocPickerModal",children:[l.length===0&&e("div",{className:"DocPickerModal__noCollections",children:"No collections matching schema field definition."}),l.length>0&&e(k.DocsList,{collection:n,onDocSelected:m,onDocUnselected:b,onCollectionChange:s,multiSelect:t.multiSelect,selectedDocIds:t.selectedDocIds,options:{enableSearch:t.enableSearch??!0,enableSort:t.enableSort??!0,enableCreate:t.enableCreate??!0,enableStatusBadges:t.enableStatusBadges??!0,showCollectionSelect:l.length>1,collectionSelectValue:n,collectionSelectOptions:c}})]})}k.DocsList=o=>{let[t,l]=g(""),[c,a]=C(`root::DocPickerModal:${o.collection}:sortBy`,"modifiedAt"),[u,r]=g(!1),[n,D,s]=z(o.collection||"",{orderBy:c}),m=O(s,t),b=[{value:"modifiedAt",label:"Last Modified"},{value:"slug",label:"A-Z"},{value:"slugDesc",label:"Z-A"},{value:"newest",label:"Newest"},{value:"oldest",label:"Oldest"}],i=o.selectedDocIds||[],d=o.options||{};return e("div",{className:"DocPickerModal__DocsList",children:[e("div",{className:"DocPickerModal__DocsList__stickyHeader",children:[d.showCollectionSelect&&e("div",{className:"DocPickerModal__collection__select",children:[e("div",{className:"DocPickerModal__collection__select__label",children:"Content Type:"}),e(f,{data:d.collectionSelectOptions||[],value:d.collectionSelectValue,placeholder:"Select",onChange:_=>{o.onCollectionChange?.(_||"")},size:"xs",radius:0,searchable:!0,autoFocus:!0,dropdownComponent:"div"}),d.collectionSelectValue&&e(p,{variant:"outline",color:"dark",size:"xs",onClick:()=>r(!0),children:"New"})]}),d.enableSearch&&d.collectionSelectValue&&e("div",{className:"DocPickerModal__DocsList__controls",children:[e(S,{placeholder:"Search documents...",value:t,onChange:_=>l(_.target.value),icon:e(B,{size:16}),size:"xs",className:"DocPickerModal__DocsList__controls__search"}),d.enableSort&&e(f,{data:b,value:c,onChange:_=>a(_||"modifiedAt"),size:"xs",className:"DocPickerModal__DocsList__controls__sort"})]}),!n&&s.length>0&&e("div",{className:"DocPickerModal__DocsList__count",children:["Showing ",m.length," of ",s.length," documents"]})]}),e("div",{className:"DocPickerModal__DocsList__docsContainer",children:o.collection?n?e("div",{className:"DocPickerModal__DocsList__loading",children:e(P,{color:"gray",size:"xl"})}):m.length===0?e("div",{className:"DocPickerModal__DocsList__empty",children:s.length===0?"Collection is empty.":"No documents match your search."}):e("div",{className:"DocPickerModal__DocsList__docs",children:m.map(_=>e(k.DocCard,{doc:_,onDocSelected:o.onDocSelected,onDocUnselected:o.onDocUnselected,multiSelect:o.multiSelect,selected:i.includes(_.id),enableStatusBadges:d.enableStatusBadges},_.id))}):e("div",{className:"DocPickerModal__DocsList__empty",children:"Select a content type to view documents"})}),d.collectionSelectValue&&e(I,{collection:d.collectionSelectValue,opened:u,skipNavigation:!0,onClose:()=>{r(!1),D()}})]})};k.DocCard=o=>{let[t,l]=g(!!o.selected),c=o.doc,[a,u]=c.id.split("/"),r=c.fields||{},n=window.__ROOT_CTX.collections[a],D=`/cms/content/${a}/${u}`,s=v(r,n.preview?.title||"meta.title"),m=v(r,n.preview?.image||"meta.image")||n.preview?.defaultImage;return e("div",{className:"DocPickerModal__DocCard",children:[e("div",{className:"DocPickerModal__DocCard__image",onClick:()=>window.open(D,"_blank"),children:e(L,{file:m,width:120,height:90,withPlaceholder:!m?.src})}),e("div",{className:"DocPickerModal__DocCard__content",children:[e("div",{className:"DocPickerModal__DocCard__content__header",children:e("div",{className:"DocPickerModal__DocCard__content__header__docId",onClick:()=>window.open(D,"_blank"),children:c.id})}),e("div",{className:"DocPickerModal__DocCard__content__title",children:e("div",{className:"DocPickerModal__DocCard__content__link",onClick:()=>window.open(D,"_blank"),children:s||"[UNTITLED]"})}),o.enableStatusBadges&&e("div",{className:"DocPickerModal__DocCard__content__badges",children:e(N,{doc:c})})]}),e("div",{className:"DocPickerModal__DocCard__controls",children:e("div",{className:"DocPickerModal__DocCard__controls__buttons",children:o.multiSelect?t?e(p,{variant:"light",color:"blue",size:"xs",onClick:()=>{l(!1),o.onDocUnselected(o.doc)},children:"Unselect"}):e(p,{variant:"filled",color:"blue",size:"xs",onClick:()=>{l(!0),o.onDocSelected(o.doc)},children:"Select"}):e(p,{color:"blue",size:"xs",onClick:()=>o.onDocSelected(o.doc),children:"Select"})})})]})};k.id=h;export{ee as a,k as b};
@@ -0,0 +1 @@
1
+ import{a as bt}from"./chunk-CGCKJFL4.js";import{f as ft,g as ht,h as mt,i as ke,j as R,k as Ae,l as Q,m as vt}from"./chunk-SKEP5WYH.js";import{c as nt}from"./chunk-AFWBSIPL.js";import{a as at}from"./chunk-62UWGWON.js";import{a as w,c as we}from"./chunk-I6ICVKEC.js";import{a as ce,f as ot}from"./chunk-ORXEMIQC.js";import{a as N,d as Se}from"./chunk-5MV6XVGA.js";import{c as et,q as tt,r as it,t as de,u as xe}from"./chunk-EGEB6N4J.js";import{f as j}from"./chunk-AL3TN2KI.js";import{$ as Fe,A as qe,Aa as le,Ab as Ce,Ca as se,Ea as Qe,Ec as Y,Fc as Ie,Ga as re,Ha as i,Ob as ut,Pc as gt,R as $e,V as We,W as X,Wc as Ee,Y as G,a as g,c as z,e as ve,ea as A,fa as Ke,g as J,ga as B,ha as Je,i as oe,j as be,jc as pt,lc as De,m as _e,ma as Xe,mb as lt,mc as Te,o as Ve,oa as Z,ob as st,p as He,qa as Ze,ra as T,sa as ye,ub as rt,va as ne,w as je,wb as dt,xb as ct,za as Ye}from"./chunk-NZHF733K.js";import{d as M,j as ae,k as Le}from"./chunk-KUCVLANF.js";Le();be();function _t(e,l){let t;return(...a)=>{window.clearTimeout(t),t=window.setTimeout(()=>{e(...a)},l)}}function Ft(e){e||(e=6);let l=[],t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=t.length;for(let o=0;o<e;o++)l.push(t.charAt(Math.floor(Math.random()*a)));return l.join("")}var q=class{constructor(){this.events=new Map}on(l,t){let a=Ft(6),o=this.events.get(l);return o||(o=new Map,this.events.set(l,o)),o.set(a,t),()=>{this.off(l,a)}}off(l,t){let a=this.events.get(l);a&&(a.delete(t),a.size===0&&this.events.delete(l))}dispatch(l,...t){let a=this.events.get(l);a&&a.forEach(o=>o(...t))}dispose(){this.events.clear()}};var ue=class{constructor(){this.subscribers=new Set;this.subtreeSubscribers=new Set;this.children=new Map}},pe=class extends q{constructor(t){super();this.root=new ue;this.data=t||{}}get(t){return this.getValueFromPath(t,this.data)}set(t,a){if(t===""){N(a)&&this.setData(a);return}this.update({[t]:a})}update(t){let a=new Map,o=(s,r,d)=>{if(a.set(s,d),!N(r)&&!N(d))return;let u=N(r)?Object.keys(r):[],m=N(d)?Object.keys(d):[];new Set([...u,...m]).forEach(h=>{let p=N(r)?r[h]:void 0,b=N(d)?d[h]:void 0;Se(p,b)||o(`${s}.${h}`,p,b)})};Object.entries(t).forEach(([s,r])=>{let d=this.data,u=s.split("."),m=u.pop();for(let h of u)d[h]||(d[h]={}),d=d[h];let F=d[m];d[m]=r,this.dispatch("VALUE_CHANGE",s,r),o(s,F,r)});let n=new Map;a.forEach((s,r)=>{this.collectSubtreeNotifications(r,n)}),a.forEach((s,r)=>{let d=this.getTrieNode(r);d&&d.subscribers.size>0&&d.subscribers.forEach(u=>u(s))}),n.forEach((s,r)=>{let d=this.get(r);s.subtreeSubscribers.forEach(u=>u(d))}),this.dispatch("CHANGE",this.data)}setData(t){let a=this.data;this.notifyOnUpdate(this.root,"",a,t),this.data=t,this.dispatch("CHANGE",this.data)}subscribe(t,a){let o=this.getTrieNode(t,!0);return o.subscribers.add(a),window.setTimeout(()=>{let n=this.get(t);n!==void 0&&a(n)}),()=>{o.subscribers.delete(a)}}subscribeSubtree(t,a){let o=this.getTrieNode(t,!0);return o.subtreeSubscribers.add(a),window.setTimeout(()=>{let n=this.get(t);n!==void 0&&a(n)}),()=>{o.subtreeSubscribers.delete(a)}}getDataSnapshot(){return this.data}dispose(){super.dispose(),this.data={},this.root.subscribers.clear(),this.root.subtreeSubscribers.clear(),this.root.children.clear()}notifyOnUpdate(t,a,o,n){let s=this.getValueFromPath(a,o),r=this.getValueFromPath(a,n);Se(s,r)||(t.subscribers.forEach(d=>d(r)),t.subtreeSubscribers.forEach(d=>d(r))),t.children.forEach((d,u)=>{let m=a?`${a}.${u}`:u;this.notifyOnUpdate(d,m,o,n)})}collectSubtreeNotifications(t,a){let o=this.root;if(o.subtreeSubscribers.size>0&&a.set("",o),!t)return;let n="";for(let s of t.split(".")){if(o=o.children.get(s),!o)return;n=n?`${n}.${s}`:s,o.subtreeSubscribers.size>0&&a.set(n,o)}}getValueFromPath(t,a){if(!t)return a;let o=t.split("."),n=a;for(let s of o){if(n===null||typeof n!="object"||!(s in n))return;n=n[s]}return n}getTrieNode(t,a=!1){if(!t)return this.root;let o=t.split("."),n=this.root;for(let s of o){if(!n.children.has(s))if(a)n.children.set(s,new ue);else return;n=n.children.get(s)}return n}};var yt=3*ce.second,kt=5*ce.minute;var At=30*ce.second,Pe=class extends q{constructor(t){super();this.pendingUpdates=new Map;this.saveState="NO_CHANGES";this.autolock=!1;this.autolockReason="autolock";this.autolockApplied=!1;this.readOnly=!1;this.autoSave=!0;this.flushOnStop=!0;this.started=!1;this.queueChanges=_t(()=>this.flush(),yt);this.projectId=window.__ROOT_CTX.rootConfig.projectId;let[a,o]=t.split("/");this.docId=t,this.collectionId=a,this.slug=o,this.db=window.firebase.db,this.docRef=et(this.db,"Projects",this.projectId,"Collections",a,"Drafts",o),this.store=new pe({id:this.docId,collection:this.collectionId,slug:this.slug,sys:{}}),this.store.on("CHANGE",s=>{this.dispatch("CHANGE",s)}),this.store.on("VALUE_CHANGE",(s,r)=>{this.dispatch("VALUE_CHANGE",s,r)});let n=window.__ROOT_CTX.collections[a];n&&(this.autolock=!!n.autolock,n.autolockReason&&(this.autolockReason=n.autolockReason))}async start(){this.started||(this.started=!0,this.dbUnsubscribe=it(this.docRef,t=>{if(t.metadata.hasPendingWrites)return;let a=t.data()||{};this.pendingUpdates.size>0&&wt(a,Object.fromEntries(this.pendingUpdates)),this.store.setData(a)}))}stop(){this.started&&(this.dbUnsubscribe&&this.dbUnsubscribe(),this.flushOnStop&&this.flush(),this.started=!1)}onChange(t){return this.on("CHANGE",t)}onSaveStateChange(t){return this.on("SAVE_STATE_CHANGE",t)}onFlush(t){return this.on("FLUSH",t)}subscribe(t,a){return this.store.subscribe(t,a)}subscribeSubtree(t,a){return this.store.subscribeSubtree(t,a)}getData(){return this.store.getDataSnapshot()}getValue(t){return this.store.get(t)}async updateKey(t,a){this.readOnly||(a===void 0?this.setPendingUpdate(t,de()):this.setPendingUpdate(t,a),this.store.set(t,a),this.setSaveState("UPDATE_PENDING"),this.autoSave&&this.queueChanges())}async updateKeys(t){if(!this.readOnly){for(let a in t){let o=t[a];o==null?this.setPendingUpdate(a,de()):this.setPendingUpdate(a,o)}this.store.update(t),this.setSaveState("UPDATE_PENDING"),this.autoSave&&this.queueChanges()}}async removeKey(t){this.readOnly||(this.setPendingUpdate(t,de()),this.store.set(t,void 0),this.setSaveState("UPDATE_PENDING"),this.autoSave&&this.queueChanges())}setPendingUpdate(t,a){for(let o of this.pendingUpdates.keys())Ut(o,t)&&this.pendingUpdates.delete(o);this.pendingUpdates.set(t,a)}getPendingUpdates(){return Nt(Object.fromEntries(this.pendingUpdates))}setSaveState(t){let a=this.saveState;t==="SAVED"&&a!=="SAVING"||(this.saveState=t,t==="SAVED"&&window.setTimeout(()=>{this.saveState==="SAVED"&&this.setSaveState("NO_CHANGES")},yt),this.dispatch("SAVE_STATE_CHANGE",t))}removePublishingLock(){this.autolockApplied=!0,this.removeKey("sys.publishingLocked"),this.flush()}async flush(t){if(this.readOnly||this.pendingUpdates.size===0)return;let a=this.getPendingUpdates();a["sys.modifiedAt"]=xe(),a["sys.modifiedBy"]=window.firebase.user.email,this.autolock&&!this.autolockApplied&&!this.store.get("sys.publishingLocked")&&(this.autolockApplied=!0,a["sys.publishingLocked"]={lockedAt:xe(),lockedBy:window.firebase.user.email,reason:this.autolockReason}),this.pendingUpdates.clear();try{this.setSaveState("SAVING"),await tt(this.docRef,a),this.setSaveState("SAVED"),t?.quiet||this.dispatch("FLUSH"),ot("doc.save",{metadata:{docId:this.docId},throttle:kt,throttleId:this.docId})}catch(o){console.error("failed to update doc:",o),this.setSaveState("ERROR");let n=at(o);w({title:`Failed to save ${this.slug}`,message:n||`Something went wrong while saving ${this.slug}`,color:"red",autoClose:!1});for(let s in a)s.startsWith("sys.")||this.pendingUpdates.has(s)||(this.pendingUpdates.set(s,a[s]),this.queueChanges(),console.log("re-queued updates"),console.log(this.pendingUpdates))}}getLocales(){let t=this.store.get("sys.locales");return t||["en"]}setLocales(t){this.updateKey("sys.locales",t)}async dispose(){super.dispose(),this.stop()}};function wt(e,l){for(let t in l){let a=l[t];if(t.includes(".")){let[o,n]=Pt(t);e[o]??={},wt(e[o],{[n]:a})}else typeof a>"u"?delete e[t]:e[t]=a}}function Pt(e){let l=e.indexOf("."),t=e.substring(0,l),a=e.substring(l+1);return[t,a]}function Nt(e){let l={...e};for(let t in l)Ot(t,l)&&delete l[t];return l}function Ot(e,l){let t=e.split(".");for(let a=1;a<t.length;a++)if(t.slice(0,a).join(".")in l)return!0;return!1}function Ut(e,l){return e.startsWith(`${l}.`)}var Ne=ae(null);function hi(e){let[l,t]=g(!0),a=J(()=>new Pe(e.docId),[e.docId]);a.readOnly=e.readOnly??!1,a.autoSave=e.autoSave??!0,a.flushOnStop=e.flushOnStop??!0,z(()=>(t(!0),a.onChange(n=>{t(!1),nt(n.id,n)}),a.start(),()=>a.dispose()),[a]),z(()=>{let n,s=()=>{document.hidden||document.visibilityState!=="visible"?n=window.setTimeout(()=>{a.stop()},At):(n&&(clearTimeout(n),n=void 0),a.started||a.start())};return document.addEventListener("visibilitychange",s),()=>{document.removeEventListener("visibilitychange",s),n&&clearTimeout(n)}},[a]);let o=J(()=>({loading:l,controller:a}),[l,a]);return i(Ne.Provider,{value:o,children:e.children})}function mi(e){return i(Ne.Provider,{value:e.value,children:e.children})}function ge(){let e=oe(Ne);if(!e)throw new Error("useDraftDoc() should be used within a <DraftDocProvider>");return e}function vi(e){let{controller:l}=ge();z(()=>l.onSaveStateChange(e),[l])}function bi(e){let{controller:l}=ge();z(()=>l.onChange(e),[l])}function _i(e,l){let{controller:t}=ge();z(()=>t.subscribe(e,l),[t])}function Oe(e,l){let{controller:t}=ge(),[a,o]=g(t.getValue(e)??l);return z(()=>t.subscribe(e,s=>{o(s)}),[t]),[a,s=>{o(s),s==null?t.removeKey(e):t.updateKey(e,s)}]}Le();je();je();be();var Mt=["drive.google.com","docs.google.com"];function fe(e){try{let l=new URL(e);if(!Mt.includes(l.hostname))return null;if(l.searchParams.has("id"))return l.searchParams.get("id");let t=l.pathname.split("/"),a=t.findIndex(o=>o==="d");if(a!==-1&&a<t.length-1)return t[a+1]}catch{return null}return null}async function xt(e,l){let t="https://www.googleapis.com/auth/drive.readonly";(!e.isLoggedIn()||!e.hasScope(t))&&await e.login({scopes:[t]});let a=window.gapi;if(!a||!a.client||!a.client.drive)throw new Error("Google Drive API not loaded");let o=a.auth.getToken()?.access_token;if(!o)throw new Error("No Google Drive access token found");let[n,s]=await Promise.all([a.client.drive.files.get({fileId:l,fields:"name,mimeType,size",supportsAllDrives:!0}),fetch(`https://www.googleapis.com/drive/v3/files/${l}?alt=media&supportsAllDrives=true`,{headers:{Authorization:`Bearer ${o}`}})]),r=n.result;if(!s.ok)throw new Error(`Failed to download file from Drive: ${s.statusText}`);let d=await s.blob();return new File([d],r.name,{type:r.mimeType})}be();var zt=["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"],Gt=["#25262b","#868e96","#fa5252","#e64980","#be4bdb","#7950f2","#4c6ef5","#228be6","#15aabf","#12b886","#40c057","#82c91e","#fab005","#fd7e14"];function St(e){let[l,t]=g("simple"),[a,o]=g(!1),[n,s]=g(!1),[r,d]=g(null),[u,m]=g(""),[F,h]=g(e.initialWidth||1600),[p,b]=g(e.initialHeight||900),[S,$]=g("16:9"),W=!!(window.__ROOT_CTX?.experiments||{}).ai;async function L(){if(!u){w({title:"Prompt required",message:"Please enter a prompt to generate an image.",color:"red"});return}o(!0);try{let _=await(await fetch("/cms/api/ai.generate_image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:u,aspectRatio:S})})).json();if(_.success&&_.image)d(_.image);else throw new Error(_.error||"Failed to generate image")}catch(f){console.error(f),w({title:"Generation failed",message:f.message||"Unknown error",color:"red"})}finally{o(!1)}}function te(f){f.preventDefault();let _=new FormData(f.target),y=parseInt(_.get("width"),10),D=parseInt(_.get("height"),10),V=_.get("backgroundColor"),O=_.get("label")||`${y}x${D}`,E=[];if(E.push(`<svg xmlns="http://www.w3.org/2000/svg" width="${y}" height="${D}" viewBox="0 0 ${y} ${D}"><rect width="${y}" height="${D}" fill="${V}" />`),O){let me=y*.5/(O.length*.6);E.push(`<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="sans-serif" font-size="${me}" fill="#fff">${O}</text>`)}E.push("</svg>");let H=E.join(""),U=new TextEncoder().encode(H),he={src:`data:image/svg+xml;base64,${btoa(String.fromCharCode(...U))}`,filename:"placeholder.svg",width:y,height:D,alt:""};e.onSubmit(he)}async function K(){if(r){s(!0);try{let _=await(await fetch(r)).blob(),y=new File([_],"generated-image.png",{type:"image/png"}),{uploadFileToGCS:D}=await import("./gcs-L33FIRZU.js"),V=await D(y),[O,E]=S.split(":").map(Number),H=1600,ie=Math.round(H*E/O),U={...V,width:H,height:ie,alt:u};e.onSubmit(U)}catch(f){console.error(f),w({title:"Save failed",message:f.message||"Failed to upload image",color:"red"})}finally{s(!1)}}}return i(se,{gap:"md",children:[W&&i(Ye,{value:l,onChange:f=>t(f),data:[{label:"Simple",value:"simple"},{label:i(B,{gap:5,children:[i(Y,{size:16}),i("span",{children:"Generate with AI"})]}),value:"ai"}],fullWidth:!0}),l==="simple"?i("form",{onSubmit:te,children:[i(se,{gap:"xs",children:[i(ne,{label:"Width",name:"width",type:"number",value:F,onChange:f=>h(parseInt(f.currentTarget.value,10)),"data-autofocus":!0}),i(ne,{label:"Height",name:"height",type:"number",value:p,onChange:f=>b(parseInt(f.currentTarget.value,10))}),i(ne,{name:"label",label:"Label",defaultValue:""}),i(Je,{name:"backgroundColor",label:"Background color",format:"hex",defaultValue:"#868e96",swatches:Gt})]}),i(B,{justify:"flex-end",mt:"md",children:i(A,{variant:"filled",type:"submit",children:"Create"})})]}):i(se,{gap:"xs",children:[i(le,{label:"Aspect Ratio",data:zt,value:S,onChange:f=>$(f)}),i(Z,{label:"Prompt",placeholder:"Describe the image you want to generate...",minRows:3,value:u,onChange:f=>m(f.currentTarget.value),"data-autofocus":!0,required:!0}),r&&i(Xe,{src:r,alt:"Generated preview",height:200,fit:"contain"}),i(B,{justify:"flex-end",mt:"md",children:[i(A,{variant:"light",onClick:L,loading:a,disabled:n||!u,leftIcon:i(Y,{size:16}),children:a?"Generating...":"Preview"}),i(A,{variant:"filled",onClick:K,loading:n,disabled:!r||a,children:n?"Saving...":"Save"})]})]})]})}var Bt=["image/gif","image/jpeg","image/png","image/svg+xml","image/webp"],Ct=ae(null),Rt=He(()=>import("./ImageEditorDialog-4H665KK2.js").then(e=>({default:e.ImageEditorDialog})));function ee(){let e=oe(Ct);if(!e)throw new Error("useFileField() should be called within a <FileFieldContext.Provider>");return e}function Lt(e){let{field:l,value:t,setValue:a,loadingState:o,setLoadingState:n}=e,s=qe(),r=ve(null),[d,u]=g(!1),[m,F]=g(!1),[h,p]=g(!1),b=bt(),S=e.allowEditing!==!1,[$,Ue]=g("hash"),[W,L]=g(null),[te,K]=g(!1),[f,_]=g(null),y=e.accept??l.exts??(e.variant==="image"?Bt:[]),D=t?.alt||"",V=e.altDisabledByMetadata===!0,O=l.alt!==!1&&!V;async function E(c,C,v){try{n("loading");let P=v?.namingMode||(l.preserveFilename?"clean":"hash"),k=l.cacheControl||(P==="clean"?"no-cache":void 0),x=await ft(c,{namingMode:P,checkExists:v?.checkExists??!1,cacheControl:k});!x.alt&&Dt(x.filename)&&D&&(x.alt=D),C&&(x.originalSrc=C),a(x),n("complete"),L(null),_(null)}catch(P){console.error("upload failed"),console.error(P),n("error"),w({title:"Upload failed",message:"Failed to upload: "+String(P),color:"red",autoClose:!1})}}async function H(){n("loading");try{let c=t?.gcsPath||t?.src;c&&await ht(c),a(null),n(null),w({message:"File deleted from GCS",color:"green"})}catch(c){console.error(c),n("error"),w({title:"Delete failed",message:String(c),color:"red"})}finally{F(!1)}}function ie(){if(!S&&t?.src){F(!0);return}a(null)}async function U(c,C){if(!c)return;if(L(null),_(null),K(!1),typeof c=="string"&&!C?.as){let k=fe(c);if(k){try{if(!b.enabled){console.warn("Google API integration is not enabled for this project. Specify the `gapi` config in your root.config.ts to enable pasting from Google Drive URLs.");return}n("loading"),w({message:"Downloading from Google Drive...",loading:!0,autoClose:!1,id:"gdrive-download"});let x=await xt(b,k);we("gdrive-download"),U(x)}catch(x){console.error(x),n("error"),we("gdrive-download"),w({title:"Google Drive import failed",message:x.message||"Failed to download",color:"red"})}return}}C?.as==="svg"&&typeof c=="string"&&(c=new File([new Blob([c],{type:"image/svg+xml"})],"untitled.svg",{type:"image/svg+xml"}));let v=c,P=ke(v.name);if(y.length>0&&!y.some(k=>k.endsWith(P)||k===`*/${P}`||k==="*/*"||k===v.type)){w({title:"Invalid file type",message:`File type ${P} is not allowed.`,color:"red",autoClose:!0});return}if($==="clean"&&e.showNamingOptions){n("loading");let x=`${window.__ROOT_CTX.rootConfig.projectId}/uploads/${v.name}`;try{if(await mt(x)){L(v),_(`https://storage.googleapis.com/${window.firebase.storage.app.options.storageBucket}/${x}`),n(null);return}}catch(Re){console.warn("Failed to check file existence",Re)}}E(v,void 0,{namingMode:$})}function Me(){r.current?.focus()}function he(){if(t?.src)if(Ae(t.src)){let c=document.createElement("a");c.href=vt(t.src),t.filename&&(c.download=t.filename),document.body.appendChild(c),c.click(),document.body.removeChild(c)}else window.open(t.src,"_blank")}function ze(){let c=document.createElement("input");c.type="file",y.length>0&&(c.accept=y.join(",")),c.onchange=C=>{let v=C.target;v.files&&v.files.length>0&&U(v.files[0])},c.click(),c.remove()}function Ge(){u(!0)}function me(){p(!0)}function Be(c){t?.src&&a({...t,alt:c||""})}async function Et(){let c=t;if(c?.src){n("loading");try{let C=await window.fetch("/cms/api/ai.generate_alt_text",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({imageUrl:c.src})}),v=await C.json();if(!C.ok||!v.success)throw new Error(v.error||"Failed to generate alt text");v.altText&&Be(v.altText)}catch(C){w({title:"Sorry, something went wrong.",message:C.message||"Unknown error",color:"red",autoClose:!0})}finally{n("complete")}}}return i(Ct.Provider,{value:{field:l,variant:e.variant,value:t,setValue:a,loadingState:o,removeFile:ie,acceptedFileTypes:y,handleFile:U,focusDropZone:Me,requestGenerateAltText:Et,requestFileUpload:ze,requestFileDownload:he,requestPlaceholderModalOpen:Ge,requestImageEditorOpen:me,showAltText:O,altText:D,setAltText:Be,altDisabledByMetadata:V,setAltDisabledByMetadata:e.setAltDisabledByMetadata,allowEditing:S},children:[i(ye,{size:"sm",opened:d,onClose:()=>u(!1),title:"Placeholder image",centered:!0,overlayColor:s.colorScheme==="dark"?s.colors.dark[9]:s.colors.gray[2],children:i(St,{onSubmit:c=>{a(c),u(!1)}})}),i(ye,{size:"sm",opened:m,onClose:()=>F(!1),title:"Delete file?",centered:!0,overlayColor:s.colorScheme==="dark"?s.colors.dark[9]:s.colors.gray[2],children:[i(G,{size:"sm",mb:"lg",children:"Are you sure you want to delete this file from GCS? This action cannot be undone."}),i(B,{grow:!0,spacing:"xs",children:[i(A,{variant:"default",onClick:()=>F(!1),disabled:o==="loading",children:"Cancel"}),i(A,{color:"red",onClick:H,loading:o==="loading",children:"Delete"})]})]}),h&&t?.src&&i(Ve,{fallback:null,children:i(Rt,{opened:h,onClose:()=>p(!1),src:t.src,originalSrc:t.originalSrc,filename:t.filename,initialWidth:parseInt(t.width),initialHeight:parseInt(t.height),onSave:c=>{E(c,t.originalSrc||t.src),p(!1)}},t.src)}),W?i("div",{className:"FileField__overwriteWarning",children:[i("div",{className:"FileField__overwriteWarning__header",children:i(G,{size:"sm",color:"red",weight:700,children:"File already exists"})}),i(G,{size:"sm",children:["A file named ",i("strong",{children:W.name})," already exists."]}),f&&i(G,{size:"sm",className:"FileField__overwriteWarning__link",children:i("a",{href:f,target:"_blank",rel:"noopener noreferrer",children:["View existing file ",i(ct,{size:12})]})}),i("div",{className:"FileField__overwriteWarning__checkbox",children:i(Ke,{label:"Confirm overwrite",checked:te,onChange:c=>K(c.currentTarget.checked)})}),i(B,{grow:!0,spacing:"xs",className:"FileField__overwriteWarning__actions",children:[i(A,{variant:"default",onClick:()=>{L(null),_(null),K(!1)},disabled:o==="loading",children:"Cancel"}),i(A,{disabled:!te,onClick:()=>E(W,void 0,{namingMode:"clean"}),color:"red",loading:o==="loading",children:"Overwrite"})]})]}):i(M,{children:[i("div",{className:j("FileField",e.showNamingOptions&&"FileField--withOptions"),children:[i(I.Dropzone,{ref:r}),t?.src?i(I.Preview,{}):i(I.InvisibleDropzone,{children:i(I.Empty,{})})]}),e.showNamingOptions&&!t&&i("div",{className:"FileField__settings",style:{marginTop:8},children:i(le,{label:"File name options",size:"xs",itemComponent:Vt,data:[{value:"hash",label:"Hash the file name",description:"The filename will be hashed so the file's original name won't be exposed."},{value:"hash-path",label:"Use a hashed path with the original file name",description:"Use the original file name, but put it inside a hashed directory."},{value:"clean",label:"Use the original file name only",description:"The file will be uploaded to the bucket as-is, without a hashed directory."}],value:$,onChange:c=>Ue(c||"hash"),disabled:o==="loading"||!!t})})]})]})}function I(e){let l=e.field,[t,a]=Oe(e.deepKey),[o,n]=g(null),s=jt(e.deepKey),[r,d]=Oe(s),u=r?.alt===!1,m=F=>{let h={...r||{}};F?h.alt=!1:delete h.alt,d(Object.keys(h).length===0?null:h)};return i(Lt,{field:l,value:t,setValue:a,loadingState:o,setLoadingState:n,variant:e.variant,allowEditing:e.allowEditing,altDisabledByMetadata:u,setAltDisabledByMetadata:e.variant==="image"&&l.alt!==!1?m:void 0})}I.Preview=()=>{let e=ee(),[l,t]=g(!1),[a,o]=g(!1),n=window.__ROOT_CTX.experiments||{},s=!!e.value?.width&&!!e.value?.height&&Number(e.value.width)>0&&Number(e.value.height)>0,r=e.value?.filename||"",d=Q(r),u=R(r)||d&&s,[m,F]=g(!u),h=ve(e.value?.src);if(e.value?.src!==h.current){h.current=e.value?.src;let p=e.value?.filename||"",b=R(p)||Q(p)&&s;!b&&!m?F(!0):b&&m&&F(!1)}return e.value?.src?i("div",{className:"FileField__Preview",children:[i("div",{className:"FileField__Preview__InfoButton",children:[u&&i(re,{label:"Toggle file info",position:"top",withArrow:!0,children:i(X,{onClick:()=>F(p=>!p),size:"sm",variant:"outline",className:"FileField__Preview__InfoButton__Icon","aria-label":"Toggle file info",children:i(ut,{size:16})})}),i(T,{shadow:"sm",control:i(X,{variant:"outline",size:"sm",radius:"sm",c:"black",className:"FileField__Preview__InfoButton__Icon",children:i(rt,{size:16})}),children:[e.allowEditing&&i(M,{children:[i(T.Label,{size:"sm",children:"REPLACE"}),i(T.Item,{icon:e.variant==="image"?i(Te,{size:16}):i(Ce,{size:16}),onClick:()=>e.requestFileUpload(),children:["Upload ",e.variant==="image"?"image":"file"]}),Tt(e.acceptedFileTypes)&&i(T.Item,{disabled:!e.value?.src,icon:i(De,{size:16}),onClick:()=>{e.requestPlaceholderModalOpen()},children:"Placeholder image"}),R(e.value?.src)&&!e.value?.src?.endsWith(".svg")&&i(T.Item,{disabled:!e.value?.src,icon:i(st,{size:16}),closeMenuOnClick:!0,onClick:()=>{e.requestImageEditorOpen()},children:"Edit image"}),i(Fe,{})]}),i(T.Item,{disabled:e.value?.src?.startsWith("data:"),onClick:()=>{e?.requestFileDownload()},icon:i(dt,{size:16}),children:"Download file"}),i(T.Item,{closeOnItemClick:!1,icon:i(lt,{size:16}),onClick:()=>{o(!1);let p=e.value?.src||"";Ae(p)&&(p=p.split("=")[0]+"=s0"),navigator.clipboard.writeText(p).then(()=>o(!0)).finally(()=>setTimeout(()=>{o(!1)},2e3))},children:a?"Copied!":"Copy URL"}),e.allowEditing&&R(e.value?.src||"")&&e.value?.canvasBgColor&&i(T.Item,{icon:e.value?.canvasBgColor==="dark"?i(Ee,{size:16}):i(Ie,{size:16,style:{opacity:.25}}),closeOnItemClick:!1,onClick:()=>{let p=e.value?.canvasBgColor==="dark"?"light":"dark";e.value&&e.setValue({...e.value,canvasBgColor:p})},children:"Use dark canvas"}),e.allowEditing&&e.setAltDisabledByMetadata&&i(T.Item,{icon:e.altDisabledByMetadata?i(Ee,{size:16}):i(Ie,{size:16,style:{opacity:.25}}),closeOnItemClick:!1,onClick:()=>{e.setAltDisabledByMetadata?.(!e.altDisabledByMetadata)},children:"Disable alt text"}),i(Fe,{}),i(T.Item,{color:"red",onClick:()=>{e?.removeFile()},icon:i(gt,{size:16}),children:"Remove file"})]})]}),i("div",{className:j("FileField__Canvas",m&&"FileField__Canvas--infoOpened",l&&"dragging"),style:Ht(e.value),onDragOver:p=>{p.preventDefault(),t(!0)},onDragLeave:p=>{p.preventDefault(),t(!1)},onDrop:p=>{p.preventDefault(),t(!1);let b=p.dataTransfer?.files[0];b&&e&&e.handleFile(b)},onPaste:p=>{p.preventDefault();let b=p.clipboardData?.files[0];if(b){e.handleFile(b);return}let S=p.clipboardData?.getData("text/plain");if(S){if(fe(S)){e.handleFile(S);return}if(It(S)){e.handleFile(S,{as:"svg"});return}}},children:[i(Ze,{visible:e.loadingState==="loading"}),m?i("div",{className:"FileField__Canvas__Info",children:[i(pt,{size:16,className:"FileField__Canvas__Info__Icon"}),i(Qe,{className:"FileField__Canvas__Info__Table",verticalSpacing:"xs",fontSize:"xs",children:i("tbody",{children:[e.value?.filename&&i("tr",{children:[i("td",{children:i("b",{children:"Name"})}),i("td",{children:e.value.filename})]}),e.value?.uploadedAt&&i("tr",{children:[i("td",{children:i("b",{children:"Uploaded"})}),i("td",{children:[new Date(parseInt(e.value.uploadedAt,10)).toLocaleString(),e.value.uploadedBy&&i(M,{children:[" by ",e.value.uploadedBy]})]})]}),!!(e.value?.width&&e.value?.height)&&i("tr",{children:[i("td",{children:i("b",{children:"Dimensions"})}),i("td",{children:[e.value.width,"x",e.value.height]})]}),i("tr",{children:[i("td",{children:i("b",{children:"URL"})}),i("td",{children:i(Z,{readOnly:!0,value:e.value?.src,size:"xs",radius:0,autosize:!0,maxRows:10})})]})]})})]}):i(M,{children:[!!(e.value?.width&&e.value?.height)&&i($e,{radius:"sm",className:"FileField__Preview__Info",children:[e.value.width,"x",e.value.height]}),R(e.value?.src)&&i("img",{onClick:()=>{e?.focusDropZone()},onDblClick:()=>{e.allowEditing&&e?.requestFileUpload()},src:e.value.src,alt:e.value.alt||"Uploaded file preview",className:"FileField__Preview__Image"}),Q(e.value?.src)&&i(M,{children:i("video",{className:"FileField__Preview__Image",controls:!0,muted:!0,preload:"metadata",children:i("source",{src:e.value.src,type:`video/${ke(e.value.src)}`})})})]}),e.allowEditing&&i("div",{className:"FileField__reupload",children:i(I.UploadButton,{className:"FileField__reupload__button",compact:!0})})]}),e.allowEditing&&e.showAltText&&(e.altText||Dt(e.value?.filename)||e.variant==="image")&&i("div",{className:"DocEditor__ImageField__imagePreview__Image__Alt",children:[i(Z,{radius:0,className:"DocEditor__ImageField__imagePreview__Image__Alt__Textarea",value:e.altText,placeholder:"Alt text",size:"xs",autosize:!0,disabled:e.loadingState==="loading",onChange:p=>{e?.setAltText(p.currentTarget.value)}}),n.ai&&!e.altText&&e.value?.src?.startsWith("http")&&i(re,{label:"Generate alt text with AI",position:"top",withArrow:!0,children:i(X,{className:"DocEditor__ImageField__imagePreview__Image__Alt__AiButton",onClick:()=>{e.requestGenerateAltText()},disabled:e.loadingState==="loading",children:i(Y,{size:20,stroke:"1.75"})})})]})]}):null};I.UploadButton=e=>{let l=ee(),t=l.loadingState==="loading",a=e.compact?14:16;return i(A,{color:"black",variant:"default",disabled:t,size:e.compact?"compact-xs":"compact-md",className:j("FileField__FileUploadButton",e.compact&&"FileField__FileUploadButton--compact"),onClick:()=>{l.requestFileUpload()},leftIcon:i(M,{children:t&&!e.compact?i(We,{size:a}):l?.variant==="image"?i(Te,{size:a}):i(Ce,{size:a})}),children:t&&!e.compact?"Uploading...":l.value?.src?"Upload":"Paste, drop, or click to upload"})};I.InvisibleDropzone=e=>{let[l,t]=g(!1),a=ee();return i("div",{className:j("FileField__InvisibleDropzone",l&&"dragging"),onDragOver:o=>{o.preventDefault(),o.stopPropagation(),t(!0)},onDragLeave:o=>{o.preventDefault(),o.stopPropagation(),t(!1)},onDrop:o=>{o.preventDefault(),o.stopPropagation(),t(!1);let n=o.dataTransfer?.files[0];n&&a.handleFile(n)},children:e.children})};I.Empty=()=>{let e=ee(),l=J(()=>{if(e.acceptedFileTypes.length===0)return"";let t=e.acceptedFileTypes.filter(a=>a!=="*/*"&&a!=="*");return t.length===0?"":t.map(a=>a.split("/").pop().split("+")[0].replaceAll(".","")).sort().join(", ")},[e.acceptedFileTypes]);return i("div",{className:"FileField__Empty",children:[i("div",{className:"FileField__Empty__Label",children:[i(I.UploadButton,{}),Tt(e.acceptedFileTypes)&&i("div",{children:i(re,{label:"Create placeholder image",children:i(X,{className:"FileField__Empty__Label__PlaceholderButton",onClick:()=>{e.requestPlaceholderModalOpen()},title:"Create placeholder image",children:i(De,{size:16})})})})]}),l&&i("div",{children:i("div",{className:"FileField__Empty__AcceptTypes",children:["Allowed file types: ",l]})})]})};I.Dropzone=_e((e,l)=>{let[t,a]=g(!1),o=ee();return i("button",{ref:l,className:j("FileField__Dropzone",t&&"dragging"),onDblClick:()=>{o?.requestFileUpload()},onCopy:n=>{o.value?.src&&(n.preventDefault(),n.clipboardData?.setData("text/plain",o.value.src),n.clipboardData?.setData("application/json",JSON.stringify(o.value)))},onKeyDown:n=>{((n.metaKey||n.ctrlKey)&&n.key==="Backspace"||n.key==="Delete")&&(n.preventDefault(),o.value?.src&&o.removeFile())},onDragOver:n=>{n.preventDefault(),a(!0)},onDragLeave:n=>{n.preventDefault(),a(!1)},onDrop:n=>{n.preventDefault(),a(!1);let s=n.dataTransfer?.files[0];s&&o&&o.handleFile(s)},onPaste:n=>{if(n.preventDefault(),!o)return;let s=n.clipboardData?.getData("application/json");if(s)try{let u=JSON.parse(s);if(u&&u.src&&u.filename&&o){console.log("Parsed JSON file:",u),o.setValue(u);return}}catch(u){console.error("error parsing json",u)}let r=n.clipboardData?.files[0];if(r){o.handleFile(r);return}let d=n.clipboardData?.getData("text/plain");if(d){if(fe(d)){o.handleFile(d);return}if(It(d)){o.handleFile(d,{as:"svg"});return}}},title:"Drop or paste to upload a file"})});var Vt=_e(e=>{let{label:l,description:t,...a}=e;return i("div",{className:"FileField__NamingModeItem",...a,children:[i(G,{size:"sm",weight:500,children:l}),i(G,{size:"xs",color:"dimmed",children:t})]})});function Dt(e){return e?R(e)||Q(e):!1}function Tt(e){return e.some(l=>l.startsWith("image/"))||e.length===0}function Ht(e){let l={};if(e.width&&e.height){l["--canvas-aspect-ratio"]=`${e.width} / ${e.height}`,l["--canvas-asset-width"]=`${e.width}px`;let t=Math.min(e.height,280);t<80&&(t=80),l["--canvas-max-height"]=`${t}px`}return e.canvasBgColor==="dark"&&(l["--canvas-bg-color"]="#000"),l}function jt(e){let l=e.split("."),t=l.pop();return[...l,`@${t}`].join(".")}function It(e){return/^(?:\uFEFF)?\s*(?:<!--[\s\S]*?-->\s*)*(?:<\?xml[\s\S]*?\?>\s*)?(?:<!DOCTYPE\s+svg[\s\S]*?>\s*)?<svg\b[^>]*?(?:\/>|>[\s\S]*?<\/svg>)\s*$/.test(e)}export{_t as a,Ft as b,q as c,hi as d,mi as e,ge as f,vi as g,bi as h,_i as i,Oe as j,Lt as k,I as l};