@blinkk/root-cms 3.0.3 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/app.js +1 -1
  2. package/dist/{chunk-7Z5IRD2G.js → chunk-RLZFZT42.js} +2 -2
  3. package/dist/plugin.js +5 -5
  4. package/dist/ui/{AIPage-2LUC2PWC.js → AIPage-YI3RFK5F.js} +1 -1
  5. package/dist/ui/{AssetsPage-PODV4QAB.js → AssetsPage-4JNAOFYF.js} +1 -1
  6. package/dist/ui/{CollectionPage-4DMKW5YB.js → CollectionPage-JWHH5G55.js} +1 -1
  7. package/dist/ui/{ComparePage-JMJE5A5Y.js → ComparePage-YZE3EMU4.js} +1 -1
  8. package/dist/ui/{DataPage-MVLZT2BU.js → DataPage-VRCQSZZG.js} +1 -1
  9. package/dist/ui/{DataSourcePage-4RPBXRI2.js → DataSourcePage-WMSPBZ3W.js} +1 -1
  10. package/dist/ui/{DocTranslationsPage-XJSPKGVX.js → DocTranslationsPage-RY2LOZBX.js} +1 -1
  11. package/dist/ui/{DocumentPage-R2PVNG24.js → DocumentPage-EEGTJMIW.js} +1 -1
  12. package/dist/ui/{EditDataSourcePage-3SHAARNL.js → EditDataSourcePage-LLCX6K4J.js} +1 -1
  13. package/dist/ui/{EditReleasePage-G5VW2OGW.js → EditReleasePage-WQYXXMZQ.js} +1 -1
  14. package/dist/ui/{LogsPage-K6KYEG2P.js → LogsPage-IP2DKEYR.js} +1 -1
  15. package/dist/ui/{NewDataSourcePage-O2VQEOJG.js → NewDataSourcePage-RDYJC4DH.js} +1 -1
  16. package/dist/ui/{NewReleasePage-RSVS32RZ.js → NewReleasePage-DGMFU2JN.js} +1 -1
  17. package/dist/ui/{NotFoundPage-ZYD5ILG6.js → NotFoundPage-WDZ2K7EF.js} +1 -1
  18. package/dist/ui/{ProjectPage-X3YQBWL4.js → ProjectPage-HYJOQUWR.js} +1 -1
  19. package/dist/ui/{ReleasePage-FJHHXNNB.js → ReleasePage-2KSF23TK.js} +1 -1
  20. package/dist/ui/{ReleasesPage-VGWIBNEZ.js → ReleasesPage-NZIBBXU4.js} +1 -1
  21. package/dist/ui/{SettingsPage-C4RXOQ6T.js → SettingsPage-36XFWV62.js} +1 -1
  22. package/dist/ui/{SidebarToolsPage-ZBOKPEMP.js → SidebarToolsPage-5C6YBWJ7.js} +1 -1
  23. package/dist/ui/{TaskPage-BQ4OX5WN.js → TaskPage-SPIFPGPP.js} +1 -1
  24. package/dist/ui/{TasksPage-3IGQYVYS.js → TasksPage-ZOXRPBQV.js} +1 -1
  25. package/dist/ui/{TranslationsArbPage-GGHCWPQL.js → TranslationsArbPage-UHANA7JD.js} +1 -1
  26. package/dist/ui/{TranslationsEditPage-E2BCMKYV.js → TranslationsEditPage-PQY6W5YG.js} +1 -1
  27. package/dist/ui/{TranslationsPage-MC4O4ZNI.js → TranslationsPage-V2PQFCN5.js} +1 -1
  28. package/dist/ui/{chunk-UEON4JAT.js → chunk-FBJURT7Z.js} +1 -1
  29. package/dist/ui/{chunk-B6BLDN24.js → chunk-JT5L6GPZ.js} +57 -57
  30. package/dist/ui/chunk-P3NETZZP.js +1 -0
  31. package/dist/ui/chunk-TJBVMFNQ.js +1 -0
  32. package/dist/ui/ui.css +1 -1
  33. package/dist/ui/ui.js +1 -1
  34. package/package.json +3 -3
  35. package/dist/ui/chunk-6IFGKSIE.js +0 -1
  36. package/dist/ui/chunk-IU36W2TB.js +0 -1
  37. /package/dist/ui/{chunk-B6BLDN24.js.LEGAL.txt → chunk-JT5L6GPZ.js.LEGAL.txt} +0 -0
@@ -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{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};