ngx-xtroedge-cms 1.3.7 → 1.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.global.js +10 -8
- package/dist/index.js +28 -23
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +28 -23
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.global.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var XtroedgeCMSLib=(()=>{var x=Object.defineProperty;var
|
|
1
|
+
"use strict";var XtroedgeCMSLib=(()=>{var x=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var L=Object.prototype.hasOwnProperty;var k=(g,t)=>{for(var e in t)x(g,e,{get:t[e],enumerable:!0})},I=(g,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of C(t))!L.call(g,s)&&s!==e&&x(g,s,{get:()=>t[s],enumerable:!(i=M(t,s))||i.enumerable});return g};var H=g=>I(x({},"__esModule",{value:!0}),g);var O={};k(O,{XtroedgeCMS:()=>v});var w=`
|
|
2
2
|
/* ===== XTROEDGE CMS ===== */
|
|
3
3
|
|
|
4
4
|
/* LOADER */
|
|
@@ -130,10 +130,12 @@
|
|
|
130
130
|
.lcms-toggle input:checked + .lcms-toggle-slider::after { transform: translateX(16px); background: white; }
|
|
131
131
|
.lcms-toggle-label { font-size: 12px; font-weight: 700; color: rgba(255,255,255,0.5); letter-spacing: 0.5px; transition: color 0.25s; }
|
|
132
132
|
.lcms-toggle input:checked ~ .lcms-toggle-label { color: rgba(var(--lcms-primary-rgb, 0,200,83),0.75); }
|
|
133
|
-
.lcms-lang-switch {
|
|
134
|
-
.lcms-lang-
|
|
135
|
-
.lcms-lang-
|
|
136
|
-
.lcms-lang-
|
|
133
|
+
.lcms-lang-switch { margin-left: auto; position: relative; }
|
|
134
|
+
.lcms-lang-select { background: rgba(var(--lcms-primary-rgb, 0,200,83),0.15); border: 1px solid rgba(var(--lcms-primary-rgb, 0,200,83),0.4); border-radius: 6px; color: white; padding: 3px 24px 3px 8px; font-size: 11px; font-weight: 600; cursor: pointer; appearance: none; -webkit-appearance: none; outline: none; transition: all 0.2s; }
|
|
135
|
+
.lcms-lang-select:hover { background: rgba(var(--lcms-primary-rgb, 0,200,83),0.3); }
|
|
136
|
+
.lcms-lang-select:focus { border-color: var(--lcms-primary, #00C853); }
|
|
137
|
+
.lcms-lang-select option { background: #1a1a2e; color: white; }
|
|
138
|
+
.lcms-lang-arrow { position: absolute; right: 6px; top: 50%; transform: translateY(-50%); pointer-events: none; color: rgba(255,255,255,0.6); font-size: 10px; }
|
|
137
139
|
.lcms-close-btn { background: transparent; border: none; color: rgba(255,255,255,0.4); cursor: pointer; padding: 2px; display: flex; transition: color 0.2s; }
|
|
138
140
|
.lcms-close-btn:hover { color: white; }
|
|
139
141
|
.lcms-changes-info { font-size: 12px; color: rgba(var(--lcms-primary-rgb, 0,200,83),0.75); margin-bottom: 10px; padding-left: 2px; }
|
|
@@ -290,7 +292,7 @@
|
|
|
290
292
|
|
|
291
293
|
/* HIDDEN ELEMENTS */
|
|
292
294
|
.lcms-hidden { display: none !important; }
|
|
293
|
-
`;var p={edit:'<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>',close:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',undo:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>',redo:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.13-9.36L23 10"/></svg>',history:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',save:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>',publish:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/></svg>',image:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',check:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>',error:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>'},
|
|
295
|
+
`;var p={edit:'<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>',close:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',undo:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>',redo:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.13-9.36L23 10"/></svg>',history:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',save:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>',publish:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/></svg>',image:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',check:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>',error:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>'},P="xtroedge_cms_history",b="history",B=["h1","h2","h3","h4","h5","h6","p","span","b","strong","i","em","a","button","li","label","small","blockquote","td","th","div","header","footer"],v=class g{constructor(t){this.brandingEl=null;this.siteIdentifier="";this.siteIdEl=null;this.loginModalEl=null;this.pendingEditMode=!1;this.editMode=!1;this.currentLang="en";this.pageTexts={};this.pageImages={};this.originalTexts={};this.originalImages={};this.unsavedChanges=0;this.isSaving=!1;this.isPublishing=!1;this.loading=!1;this.canUndo=!1;this.canRedo=!1;this.showHistory=!1;this.historyList=[];this.isOpen=!1;this.isEditAllowed=!1;this.imageUploading=!1;this.toastMessage="";this.toastType="success";this.undoStack=[];this.redoStack=[];this.dirtyKeys=new Set;this.dirtyImageKeys=new Set;this.registeredKeys=new Set;this.managedElements=new Map;this.managedImages=new Map;this.autoDetectedElements=new Set;this.observer=null;this.scanTimeout=null;this.activeImageEl=null;this.imageCtxMenu=null;this.currentSlug="";this.currentTitle="";this.origPushState=null;this.origReplaceState=null;this.styleEl=null;this.rootEl=null;this.loaderEl=null;this.toastEl=null;this.fabEl=null;this.fabBtn=null;this.badgeEl=null;this.panelEl=null;this.editToggle=null;this.langSwitchEl=null;this.changesInfoEl=null;this.undoBtn=null;this.redoBtn=null;this.historyBtnEl=null;this.historyPanelEl=null;this.historyListEl=null;this.saveBtn=null;this.publishBtn=null;this.cancelBtn=null;this.actionsEl=null;this.editModeContent=null;this.fileInput=null;this.imgOverlay=null;this.posX=20;this.posY=20;this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.startPosX=0;this.startPosY=0;this.hasMoved=!1;this.toastTimer=null;this.db=null;this.translationCache=new Map;this.config=t||{},this.containerSelector=this.config.containerSelector||"",this.editableTags=(this.config.editableTags||B).map(i=>i.toLowerCase()),this.languages=this.config.languages||["en"],this.defaultLanguage=this.config.defaultLanguage||this.languages[0]||"en",this.highlightColor=this.config.highlightColor||"#00C853",this.historyRetentionMs=(this.config.historyRetentionDays||7)*24*60*60*1e3,this.currentLang=this.defaultLanguage,this.siteIdentifier=this.resolveSiteIdentifier();let e=localStorage.getItem("xtroedge_theme_color");e&&(this.highlightColor=e),this.boundMouseMove=i=>this.onDragMove(i),this.boundMouseUp=()=>this.onDragEnd(),this.boundTouchMove=i=>this.onTouchMove(i),this.boundTouchEnd=()=>this.onTouchEnd(),this.boundPopState=()=>this.handleNavigation(),this.boundHashChange=()=>this.handleNavigation()}init(){this.posY=window.innerHeight-72,this.injectStyles(),this.applyThemeColor(this.highlightColor),this.buildUI(),this.interceptNavigation(),this.observer=new MutationObserver(()=>{this.rootEl&&!document.contains(this.rootEl)&&document.body.appendChild(this.rootEl),this.styleEl&&!document.contains(this.styleEl)&&document.head.appendChild(this.styleEl),this.scanTimeout&&clearTimeout(this.scanTimeout),this.scanTimeout=setTimeout(()=>this.autoDetectAndScan(),150)}),this.observer.observe(document.body,{childList:!0,subtree:!0}),window.addEventListener("popstate",this.boundPopState),window.addEventListener("hashchange",this.boundHashChange),this.handleNavigation()}destroy(){this.cleanupManagedElements(),this.styleEl?.remove(),this.rootEl?.remove(),window.removeEventListener("popstate",this.boundPopState),window.removeEventListener("hashchange",this.boundHashChange),document.removeEventListener("mousemove",this.boundMouseMove),document.removeEventListener("mouseup",this.boundMouseUp),document.removeEventListener("touchmove",this.boundTouchMove),document.removeEventListener("touchend",this.boundTouchEnd),this.origPushState&&(history.pushState=this.origPushState),this.origReplaceState&&(history.replaceState=this.origReplaceState),this.observer?.disconnect(),this.scanTimeout&&clearTimeout(this.scanTimeout),this.toastTimer&&clearTimeout(this.toastTimer),this.db?.close()}injectStyles(){document.getElementById("xtroedge-cms-styles")||(this.styleEl=document.createElement("style"),this.styleEl.id="xtroedge-cms-styles",this.styleEl.textContent=w,document.head.appendChild(this.styleEl))}interceptNavigation(){this.origPushState=history.pushState.bind(history),this.origReplaceState=history.replaceState.bind(history);let t=this;history.pushState=function(...e){t.origPushState(...e),setTimeout(()=>t.handleNavigation(),0)},history.replaceState=function(...e){t.origReplaceState(...e),setTimeout(()=>t.handleNavigation(),0)}}handleNavigation(){let t=window.location.href,e=window.location.pathname||"/",i=window.location.hash||"",s,n;if(i.startsWith("#/")||i.startsWith("#!")){let h=i.replace(/^#[!/]*/,""),u=h.indexOf("?");s=u>=0?h.substring(0,u):h,n=u>=0?h.substring(u):""}else s=e.replace(/^\//,"")||"home",n=window.location.search;let a="/"+(s.replace(/^\//,"")||"home"),r=new URLSearchParams(n).get("edit")==="true";this.isEditAllowed=r||sessionStorage.getItem("builder_edit_mode")==="true",a!==this.currentSlug&&(this.cleanupManagedElements(),this.currentSlug=a,this.currentTitle=(s.replace(/^\//,"")||"home").replace(/-/g," ").replace(/\b\w/g,h=>h.toUpperCase())+" Page",this.resetAll());let d=sessionStorage.getItem("builder_edit_mode")==="true",c=r||d;if(c){if(!localStorage.getItem("builder_token")){this.pendingEditMode=!0,this.currentLang=this.detectCurrentLanguage(),this.setLoading(!0),setTimeout(()=>{this.loadTranslationsAndInit(!1),this.showLoginModal()},300);return}this.editMode=!0}this.currentLang=this.detectCurrentLanguage(),this.setLoading(!0);let m=c;setTimeout(()=>{this.loadTranslationsAndInit(m)},300)}buildUI(){this.rootEl=document.createElement("div"),this.rootEl.id="xtroedge-cms-root",this.loaderEl=this.createElement("div","lcms-loader-overlay lcms-hidden"),this.loaderEl.innerHTML=`<div class="lcms-loader-content">
|
|
294
296
|
<div class="lcms-orbit-loader">
|
|
295
297
|
<div class="lcms-orbit lcms-orbit-1"><span class="lcms-particle"></span></div>
|
|
296
298
|
<div class="lcms-orbit lcms-orbit-2"><span class="lcms-particle"></span></div>
|
|
@@ -299,7 +301,7 @@
|
|
|
299
301
|
<div class="lcms-core"></div>
|
|
300
302
|
</div>
|
|
301
303
|
<span class="lcms-loader-text">Loading</span>
|
|
302
|
-
</div>`,this.rootEl.appendChild(this.loaderEl),this.toastEl=this.createElement("div","lcms-toast lcms-hidden"),this.rootEl.appendChild(this.toastEl),this.fabEl=this.createElement("div","lcms-fab"),this.fabEl.style.left=this.posX+"px",this.fabEl.style.top=this.posY+"px",this.fabEl.addEventListener("mousedown",t=>this.onDragStart(t)),this.fabEl.addEventListener("touchstart",t=>this.onTouchStart(t),{passive:!0}),this.fabBtn=document.createElement("button"),this.fabBtn.className="lcms-fab-btn",this.fabBtn.innerHTML=p.edit,this.fabBtn.addEventListener("click",t=>this.onFabClick(t)),this.badgeEl=this.createElement("span","lcms-badge lcms-hidden"),this.fabBtn.appendChild(this.badgeEl),this.fabEl.appendChild(this.fabBtn),this.panelEl=this.createElement("div","lcms-panel lcms-hidden"),this.buildPanel(),this.fabEl.appendChild(this.panelEl),this.rootEl.appendChild(this.fabEl),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/*",this.fileInput.style.display="none",this.fileInput.addEventListener("change",t=>this.onImageFileSelected(t)),this.rootEl.appendChild(this.fileInput),this.imgOverlay=this.createElement("div","lcms-img-upload-overlay lcms-hidden"),this.imgOverlay.innerHTML='<div class="lcms-img-upload-content"><div class="lcms-spinner-lg"></div><span>Uploading image...</span></div>',this.rootEl.appendChild(this.imgOverlay),document.body.appendChild(this.rootEl)}buildPanel(){if(!this.panelEl)return;let t=this.createElement("div","lcms-panel-header"),e=this.createElement("label","lcms-toggle");e.addEventListener("click",l=>l.stopPropagation()),this.editToggle=document.createElement("input"),this.editToggle.type="checkbox",this.editToggle.checked=this.editMode,this.editToggle.addEventListener("change",l=>this.toggleEditMode(l));let i=this.createElement("span","lcms-toggle-slider"),s=this.createElement("span","lcms-toggle-label");s.textContent="Edit",e.appendChild(this.editToggle),e.appendChild(i),e.appendChild(s),t.appendChild(e),this.langSwitchEl=this.createElement("div","lcms-lang-switch lcms-hidden"),this.buildLangButtons(),t.appendChild(this.langSwitchEl);let n=document.createElement("button");n.className="lcms-close-btn",n.innerHTML=p.close,n.addEventListener("click",l=>{l.stopPropagation(),this.togglePanel()}),t.appendChild(n),this.panelEl.appendChild(t),this.siteIdEl=this.createElement("div","lcms-site-id");let a=this.siteIdentifier.includes(".");this.siteIdEl.innerHTML=`<span class="lcms-site-id-icon">${a?"\u{1F310}":"\u{1F511}"}</span><span class="lcms-site-id-text">${a?this.siteIdentifier:this.siteIdentifier.substring(0,8)}</span>`,this.panelEl.appendChild(this.siteIdEl),this.editModeContent=this.createElement("div","lcms-hidden"),this.changesInfoEl=this.createElement("div","lcms-changes-info lcms-hidden"),this.editModeContent.appendChild(this.changesInfoEl);let o=this.createElement("div","lcms-undo-row");this.undoBtn=document.createElement("button"),this.undoBtn.className="lcms-icon-btn",this.undoBtn.innerHTML=p.undo,this.undoBtn.disabled=!0,this.undoBtn.addEventListener("click",l=>{l.stopPropagation(),this.onUndo()}),this.redoBtn=document.createElement("button"),this.redoBtn.className="lcms-icon-btn",this.redoBtn.innerHTML=p.redo,this.redoBtn.disabled=!0,this.redoBtn.addEventListener("click",l=>{l.stopPropagation(),this.onRedo()}),o.appendChild(this.undoBtn),o.appendChild(this.redoBtn),this.editModeContent.appendChild(o);let r=this.createElement("div","lcms-theme-row"),d=this.createElement("span","lcms-theme-label");d.textContent="Theme",r.appendChild(d);let c=this.createElement("div","lcms-theme-colors"),m=["#00C853","#6722FB","#2196F3","#FF5722","#E91E63","#FFD600"];for(let l of m){let f=this.createElement("div","lcms-theme-swatch");f.style.background=l,f.dataset.color=l,l===this.highlightColor&&f.classList.add("active"),f.addEventListener("click",S=>{S.stopPropagation(),this.applyThemeColor(l)}),c.appendChild(f)}let h=this.createElement("div","lcms-theme-custom"),u=this.createElement("div","lcms-theme-custom-preview"),y=document.createElement("input");y.type="color",y.value=this.highlightColor,y.addEventListener("input",l=>{l.stopPropagation(),this.applyThemeColor(l.target.value)}),h.appendChild(u),h.appendChild(y),c.appendChild(h),r.appendChild(c),this.editModeContent.appendChild(r),this.historyBtnEl=document.createElement("button"),this.historyBtnEl.className="lcms-history-btn",this.historyBtnEl.innerHTML=`${p.history} History (7 days)`,this.historyBtnEl.addEventListener("click",l=>{l.stopPropagation(),this.toggleHistory()}),this.editModeContent.appendChild(this.historyBtnEl),this.historyPanelEl=this.createElement("div","lcms-history-panel lcms-hidden");let E=this.createElement("div","lcms-history-title");E.textContent="Edit History",this.historyPanelEl.appendChild(E),this.historyListEl=this.createElement("div","lcms-history-list"),this.historyPanelEl.appendChild(this.historyListEl),this.editModeContent.appendChild(this.historyPanelEl),this.actionsEl=this.createElement("div","lcms-actions"),this.saveBtn=document.createElement("button"),this.saveBtn.className="lcms-btn-save",this.saveBtn.innerHTML=`${p.save} Save Draft`,this.saveBtn.addEventListener("click",l=>{l.stopPropagation(),this.saveChanges()}),this.publishBtn=document.createElement("button"),this.publishBtn.className="lcms-btn-publish",this.publishBtn.innerHTML=`${p.publish} Publish`,this.publishBtn.addEventListener("click",l=>{l.stopPropagation(),this.publishChanges()}),this.cancelBtn=document.createElement("button"),this.cancelBtn.className="lcms-btn-cancel",this.cancelBtn.textContent="Cancel",this.cancelBtn.addEventListener("click",l=>{l.stopPropagation(),this.cancelEditing()}),this.actionsEl.appendChild(this.saveBtn),this.actionsEl.appendChild(this.publishBtn),this.actionsEl.appendChild(this.cancelBtn),this.editModeContent.appendChild(this.actionsEl),this.panelEl.appendChild(this.editModeContent),this.brandingEl=this.createElement("div","lcms-branding"),this.brandingEl.innerHTML='<div class="lcms-branding-logo"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg></div><div class="lcms-branding-text">Powered by <span>XtroEdge</span></div>',this.brandingEl.addEventListener("click",l=>{l.stopPropagation(),window.open("https://xtro.vercel.app/","_blank")}),this.panelEl.appendChild(this.brandingEl)}buildLangButtons(){if(this.langSwitchEl){this.langSwitchEl.innerHTML="";for(let t of this.languages){let e=document.createElement("button");e.className="lcms-lang-btn"+(this.currentLang===t?" active":""),e.textContent=t.toUpperCase(),e.addEventListener("click",i=>{i.stopPropagation(),this.switchLang(t)}),this.langSwitchEl.appendChild(e)}}}updateUI(){if(this.fabEl&&(this.fabEl.style.display=this.isEditAllowed?"":"none"),this.fabBtn&&(this.fabBtn.style.display=this.isOpen?"none":"",this.fabBtn.classList.toggle("lcms-fab-active",this.editMode)),this.panelEl&&(this.panelEl.classList.toggle("lcms-hidden",!this.isOpen),this.isOpen)){let t=this.posY>window.innerHeight/2,e=this.posX>window.innerWidth/2;this.panelEl.style.bottom=t?"0":"",this.panelEl.style.top=t?"":"0",this.panelEl.style.right=e?"0":"",this.panelEl.style.left=e?"":"0"}this.badgeEl&&(this.badgeEl.classList.toggle("lcms-hidden",this.unsavedChanges===0),this.badgeEl.textContent=String(this.unsavedChanges)),this.editToggle&&(this.editToggle.checked=this.editMode),this.langSwitchEl&&(this.langSwitchEl.classList.toggle("lcms-hidden",!this.editMode||this.languages.length<=1),this.langSwitchEl.querySelectorAll(".lcms-lang-btn").forEach(e=>{e.classList.toggle("active",e.textContent===this.currentLang.toUpperCase())})),this.editModeContent&&this.editModeContent.classList.toggle("lcms-hidden",!this.editMode),this.changesInfoEl&&(this.changesInfoEl.classList.toggle("lcms-hidden",this.unsavedChanges===0),this.changesInfoEl.textContent=`${this.unsavedChanges} unsaved change${this.unsavedChanges>1?"s":""}`),this.undoBtn&&(this.undoBtn.disabled=!this.canUndo),this.redoBtn&&(this.redoBtn.disabled=!this.canRedo),this.historyBtnEl&&this.historyBtnEl.classList.toggle("active",this.showHistory),this.historyPanelEl&&this.historyPanelEl.classList.toggle("lcms-hidden",!this.showHistory),this.saveBtn&&(this.saveBtn.disabled=this.isSaving||this.isPublishing||this.unsavedChanges===0,this.saveBtn.innerHTML=this.isSaving?'<span class="lcms-spinner"></span> Saving...':`${p.save} Save Draft`),this.publishBtn&&(this.publishBtn.disabled=this.isSaving||this.isPublishing,this.publishBtn.innerHTML=this.isPublishing?'<span class="lcms-spinner"></span> Publishing...':`${p.publish} Publish`),this.cancelBtn&&(this.cancelBtn.disabled=this.isSaving||this.isPublishing),this.loaderEl&&this.loaderEl.classList.toggle("lcms-hidden",!this.loading),this.imgOverlay&&this.imgOverlay.classList.toggle("lcms-hidden",!this.imageUploading)}autoDetectAndScan(){this.autoDetectElements(),this.scanDOM(),this.scanImages()}resolveContainer(){return this.containerSelector&&document.querySelector(this.containerSelector)||document.body}autoDetectElements(){let t=this.resolveContainer();if(!t)return;for(let r of this.autoDetectedElements)document.contains(r)||this.autoDetectedElements.delete(r);let e=r=>{let d=r.parentElement;for(;d&&d!==document.body;){let c=d.tagName.toLowerCase();if(c==="header"||c.endsWith("-header"))return"/header";if(c==="footer"||c.endsWith("-footer"))return"/footer";d=d.parentElement}return this.currentSlug},i={},s=(r,d)=>{let c=d==="/header"?"header":d==="/footer"?"footer":"page";i[c]||(i[c]={});let m=r.tagName.toLowerCase();i[c][m]||(i[c][m]=0);let u=`${c!=="page"?`${c}_`:""}xcms_${m}_${i[c][m]}`;i[c][m]++,r.setAttribute("data-cms",u),r.setAttribute("data-cms-section",d),this.autoDetectedElements.add(r)},n=this.editableTags.join(",");t.querySelectorAll(n).forEach(r=>{r.hasAttribute("data-cms")||r.closest("#xtroedge-cms-root, script, style, noscript")||r.children.length>3||this.getDirectTextContent(r).trim().length<2||s(r,e(r))}),t.querySelectorAll("[data-editable]").forEach(r=>{r.hasAttribute("data-cms")||r.closest("#xtroedge-cms-root, script, style, noscript")||s(r,e(r))})}scanDOM(){document.querySelectorAll("[data-cms]").forEach(e=>{if(e.closest("#xtroedge-cms-root"))return;let i=e.getAttribute("data-cms");this.registeredKeys.add(i),this.managedElements.has(e)||this.attachElement(e,i)});for(let[e]of this.managedElements)document.contains(e)||this.detachElement(e)}scanImages(){let t=this.resolveContainer();if(!t)return;let e={...this.pageImages},i=!1;t.querySelectorAll("img").forEach(n=>{if(n.closest("#xtroedge-cms-root")||this.managedImages.has(n))return;let a=n.getAttribute("src")||"";!a||a.startsWith("data:")||(this.attachImage(n,a),e[a]||(e[a]=a,i=!0))}),i&&(this.pageImages=e,this.originalImages=JSON.parse(JSON.stringify(e)));for(let[n]of this.managedImages)document.contains(n)||this.detachImage(n)}getDirectTextContent(t){let e="";for(let i=0;i<t.childNodes.length;i++)t.childNodes[i].nodeType===Node.TEXT_NODE&&(e+=t.childNodes[i].textContent||"");return e}attachElement(t,e){let i=()=>{let r=t.textContent?.trim()||"",d=this.getPageText(e);r!==d&&this.onTextChanged(e,r)},s=r=>{r.key==="Enter"&&(r.preventDefault(),t.blur())},n=()=>{let r=t.textContent?.trim()||"",d=this.getPageText(e);r!==d&&this.onTextChanged(e,r)},a=r=>{r.preventDefault(),r.stopPropagation()},o=t.getAttribute("data-cms-section")||this.currentSlug;this.managedElements.set(t,{key:e,sectionSlug:o,blurHandler:i,keydownHandler:s,inputHandler:n,clickHandler:a}),this.editMode&&this.enableElementEdit(t,e,i,s,n,a)}detachElement(t){let e=this.managedElements.get(t);e&&(t.removeEventListener("blur",e.blurHandler),t.removeEventListener("keydown",e.keydownHandler),t.removeEventListener("input",e.inputHandler),t.removeEventListener("click",e.clickHandler,!0),t.removeAttribute("contenteditable"),this.managedElements.delete(t))}enableElementEdit(t,e,i,s,n,a){let o=this.getPageText(e);o&&(t.textContent=o),t.setAttribute("contenteditable","true"),t.style.borderBottom=`2px dashed ${this.highlightColor}`,t.style.padding="2px 4px",t.style.borderRadius="3px",t.style.cursor="text",t.style.outline="none",t.style.transition="background 0.2s",t.style.minWidth="20px",t.addEventListener("blur",i),t.addEventListener("keydown",s),t.addEventListener("input",n),t.addEventListener("click",a,!0)}disableElementEdit(t,e,i,s,n,a){t.removeAttribute("contenteditable"),t.style.borderBottom="",t.style.padding="",t.style.borderRadius="",t.style.cursor="",t.style.outline="",t.style.transition="",t.style.minWidth="";let o=this.getPageText(e);o&&(t.textContent=o),t.removeEventListener("blur",i),t.removeEventListener("keydown",s),t.removeEventListener("input",n),t.removeEventListener("click",a,!0)}applyEditMode(t){for(let[e,i]of this.managedElements)t?this.enableElementEdit(e,i.key,i.blurHandler,i.keydownHandler,i.inputHandler,i.clickHandler):this.disableElementEdit(e,i.key,i.blurHandler,i.keydownHandler,i.inputHandler,i.clickHandler);this.applyImageEditMode(t)}updateElementTexts(){this.observer?.disconnect();for(let[t,e]of this.managedElements){if(document.activeElement===t)continue;let i=this.getPageText(e.key);i&&t.textContent!==i&&(t.textContent=i)}this.observer?.observe(document.body,{childList:!0,subtree:!0})}cleanupManagedElements(){for(let[t]of this.managedElements)this.detachElement(t);this.managedElements.clear();for(let t of this.autoDetectedElements)t.removeAttribute("data-cms");this.autoDetectedElements.clear(),this.cleanupManagedImages()}attachImage(t,e){let i=s=>{this.editMode&&(s.preventDefault(),s.stopPropagation(),this.showImageContextMenu(s.clientX,s.clientY,t))};this.managedImages.set(t,{key:e,ctxHandler:i}),this.editMode&&this.enableImageEdit(t,i)}detachImage(t){let e=this.managedImages.get(t);e&&(t.removeEventListener("contextmenu",e.ctxHandler),t.style.outline="",t.style.cursor="",this.managedImages.delete(t))}cleanupManagedImages(){for(let[t]of this.managedImages)this.detachImage(t);this.managedImages.clear(),this.dismissImageCtxMenu()}applyImageEditMode(t){for(let[e,i]of this.managedImages)t?this.enableImageEdit(e,i.ctxHandler):this.disableImageEdit(e,i.ctxHandler);t||this.dismissImageCtxMenu()}enableImageEdit(t,e){t.style.outline=`2px dashed ${this.highlightColor}`,t.style.cursor="context-menu",t.addEventListener("contextmenu",e)}disableImageEdit(t,e){t.style.outline="",t.style.cursor="",t.removeEventListener("contextmenu",e)}showImageContextMenu(t,e,i){this.dismissImageCtxMenu();let s=document.createElement("div");Object.assign(s.style,{position:"fixed",zIndex:"10005",minWidth:"160px",background:"rgba(30,15,60,0.85)",backdropFilter:"blur(16px)",webkitBackdropFilter:"blur(16px)",border:"1px solid rgba(139,92,246,0.3)",borderRadius:"10px",padding:"4px",boxShadow:"0 8px 32px rgba(0,0,0,0.4)",fontFamily:"system-ui, -apple-system, sans-serif",left:Math.min(t,window.innerWidth-180)+"px",top:Math.min(e,window.innerHeight-50)+"px"});let n=document.createElement("button");Object.assign(n.style,{width:"100%",padding:"8px 12px",border:"none",borderRadius:"7px",background:"transparent",color:"white",fontSize:"12px",fontWeight:"500",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px"}),n.innerHTML=`${p.image} Upload Image`,n.addEventListener("mouseenter",()=>n.style.background="rgba(103,34,251,0.3)"),n.addEventListener("mouseleave",()=>n.style.background="transparent"),n.addEventListener("click",()=>{this.activeImageEl=i,this.fileInput&&(this.fileInput.value="",this.fileInput.click()),this.dismissImageCtxMenu()}),s.appendChild(n),document.body.appendChild(s),this.imageCtxMenu=s;let a=o=>{s.contains(o.target)||(this.dismissImageCtxMenu(),document.removeEventListener("mousedown",a))};setTimeout(()=>document.addEventListener("mousedown",a),0)}dismissImageCtxMenu(){this.imageCtxMenu&&(this.imageCtxMenu.remove(),this.imageCtxMenu=null)}onImageFileSelected(t){let i=t.target.files?.[0];if(!i||!this.activeImageEl)return;this.imageUploading=!0,this.updateUI();let s=new FileReader;s.onload=()=>{let n=s.result;this.uploadImageToApi(n)},s.readAsDataURL(i)}async uploadImageToApi(t){try{let e=await fetch(`${this.config.apiBase}/web/upload-image`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:t})});if(!e.ok)throw new Error(`HTTP ${e.status}`);let i=await e.json(),n=(this.config.imageBaseUrl||(this.config.apiBase?new URL(this.config.apiBase).origin:""))+i.path;if(this.activeImageEl){let a=this.managedImages.get(this.activeImageEl)?.key||"";this.activeImageEl.src=n,this.onImageChanged(a,n)}this.imageUploading=!1,this.activeImageEl=null,this.updateUI(),this.showToast("Image updated!","success")}catch(e){this.imageUploading=!1,this.activeImageEl=null,this.updateUI(),this.showToast("Image upload failed.","error"),this.config.onError?.("upload-image",e)}}applyPageImages(){for(let[t,e]of this.managedImages){let i=this.pageImages[e.key];i&&t.src!==i&&(t.src=i)}}getPageText(t){return this.pageTexts[t]?.[this.currentLang]||""}onTextChanged(t,e){this.undoStack.push(this.createSnapshot()),this.redoStack=[],this.canUndo=!0,this.canRedo=!1,this.pageTexts[t]||(this.pageTexts[t]={}),this.pageTexts[t]={...this.pageTexts[t],[this.currentLang]:e},this.dirtyKeys.add(t),this.unsavedChanges=this.dirtyKeys.size+this.dirtyImageKeys.size,this.pushHistory(t,this.currentLang),this.updateUI()}onImageChanged(t,e){this.undoStack.push(this.createSnapshot()),this.redoStack=[],this.canUndo=!0,this.canRedo=!1,this.pageImages={...this.pageImages,[t]:e},this.dirtyImageKeys.add(t),this.unsavedChanges=this.dirtyKeys.size+this.dirtyImageKeys.size,this.pushHistory(t,"img"),this.updateUI()}createSnapshot(){return JSON.stringify({texts:this.pageTexts,images:this.pageImages})}applySnapshot(t){let e=JSON.parse(t);e.texts?(this.pageTexts=e.texts,e.images&&(this.pageImages=e.images)):this.pageTexts=e}onUndo(){this.undoStack.length!==0&&(this.redoStack.push(this.createSnapshot()),this.applySnapshot(this.undoStack.pop()),this.canUndo=this.undoStack.length>0,this.canRedo=!0,this.recalcDirtyKeys(),this.updateElementTexts(),this.applyPageImages(),this.updateUI())}onRedo(){this.redoStack.length!==0&&(this.undoStack.push(this.createSnapshot()),this.applySnapshot(this.redoStack.pop()),this.canUndo=!0,this.canRedo=this.redoStack.length>0,this.recalcDirtyKeys(),this.updateElementTexts(),this.applyPageImages(),this.updateUI())}recalcDirtyKeys(){this.dirtyKeys.clear();for(let t of this.registeredKeys)JSON.stringify(this.pageTexts[t])!==JSON.stringify(this.originalTexts[t])&&this.dirtyKeys.add(t);this.unsavedChanges=this.dirtyKeys.size+this.dirtyImageKeys.size}resetAll(){this.dirtyKeys.clear(),this.dirtyImageKeys.clear(),this.unsavedChanges=0,this.undoStack=[],this.redoStack=[],this.canUndo=!1,this.canRedo=!1,this.updateUI()}resetAfterSave(){this.dirtyKeys.clear(),this.dirtyImageKeys.clear(),this.unsavedChanges=0,this.originalTexts=JSON.parse(JSON.stringify(this.pageTexts)),this.originalImages=JSON.parse(JSON.stringify(this.pageImages))}cancelEditing(){this.pageTexts=JSON.parse(JSON.stringify(this.originalTexts)),this.pageImages=JSON.parse(JSON.stringify(this.originalImages)),this.dirtyKeys.clear(),this.dirtyImageKeys.clear(),this.unsavedChanges=0,this.updateElementTexts(),this.applyPageImages(),this.updateUI()}async loadTranslationsAndInit(t){if(this.config.i18nBasePath)try{let e=this.currentLang,i=await fetch(`${this.config.i18nBasePath}/${e}.json`);if(i.ok){let s=await i.json();this.translationCache.clear(),this.flattenTranslations(s,"",this.getPageSection())}}catch{}this.autoDetectAndScan(),this.editMode&&this.applyEditMode(!0),this.config.apiBase?t?this.loadPageContent("draft"):this.loadPublishedContent():(this.buildDefaultTexts(),this.originalTexts=JSON.parse(JSON.stringify(this.pageTexts)),this.originalImages=JSON.parse(JSON.stringify(this.pageImages)),this.setLoading(!1)),this.updateUI()}flattenTranslations(t,e,i){for(let s of Object.keys(t)){let n=e?`${e}.${s}`:s;if(typeof t[s]=="string"){let a=t[s].trim();a.length>=2&&(!this.translationCache.get(a)||n.toUpperCase().startsWith(i))&&this.translationCache.set(a,n)}else typeof t[s]=="object"&&t[s]!==null&&!Array.isArray(t[s])&&this.flattenTranslations(t[s],n,i)}}getPageSection(){return this.currentSlug.replace(/^\//,"").replace(/-/g,"_").toUpperCase()}async fetchSectionTexts(t,e){try{let i=await fetch(`${this.config.apiBase}/web-page/get?slug=${encodeURIComponent(t)}&status=${e}&site_identifier=${encodeURIComponent(this.siteIdentifier)}`);if(!i.ok)return null;let s=await i.json();return s?.published_content?.texts||s?.content?.texts||null}catch{return null}}async loadPageContent(t){this.setLoading(!0),this.cleanOldHistory();try{let[e,i,s]=await Promise.all([this.fetchSectionTexts(this.currentSlug,t),this.fetchSectionTexts("/header",t),this.fetchSectionTexts("/footer",t)]);e||i||s?this.pageTexts={...e||{},...i||{},...s||{}}:this.buildDefaultTexts();let n=await fetch(`${this.config.apiBase}/web-page/get?slug=${encodeURIComponent(this.currentSlug)}&status=${t}&site_identifier=${encodeURIComponent(this.siteIdentifier)}`).catch(()=>null);if(n?.ok){let a=await n.json(),o=a?.published_content?.images||a?.content?.images;o&&(this.pageImages=JSON.parse(JSON.stringify(o)),this.applyPageImages())}this.originalTexts=JSON.parse(JSON.stringify(this.pageTexts)),this.originalImages=JSON.parse(JSON.stringify(this.pageImages)),this.resetAll(),this.updateElementTexts()}catch{this.buildDefaultTexts(),this.originalTexts=JSON.parse(JSON.stringify(this.pageTexts)),this.originalImages=JSON.parse(JSON.stringify(this.pageImages)),this.resetAll()}finally{this.setLoading(!1)}}async loadPublishedContent(){this.setLoading(!0);try{let[t,e,i]=await Promise.all([this.fetchSectionTexts(this.currentSlug,"published"),this.fetchSectionTexts("/header","published"),this.fetchSectionTexts("/footer","published")]),s={...t||{},...e||{},...i||{}};Object.keys(s).length>0&&(this.pageTexts=JSON.parse(JSON.stringify(s)),this.updateElementTexts());let n=await fetch(`${this.config.apiBase}/web-page/get?slug=${encodeURIComponent(this.currentSlug)}&status=published&site_identifier=${encodeURIComponent(this.siteIdentifier)}`);if(n.ok){let o=(await n.json())?.published_content?.images;o&&Object.keys(o).length>0&&(this.pageImages=JSON.parse(JSON.stringify(o)),this.applyPageImages())}}catch{}finally{this.setLoading(!1)}}buildDefaultTexts(){let t={};for(let e of this.registeredKeys){let s=document.querySelector(`[data-cms="${e}"]`)?.textContent?.trim()||"";t[e]={[this.currentLang]:s}}if(this.pageTexts=t,this.config.i18nBasePath){let e=this.languages.filter(i=>i!==this.currentLang);for(let i of e)fetch(`${this.config.i18nBasePath}/${i}.json`).then(s=>s.json()).then(s=>{let n={...this.pageTexts};for(let a of this.registeredKeys){let o=a.split("."),r=s;for(let d of o)r=r?.[d];r&&typeof r=="string"&&(n[a]={...n[a],[i]:r})}this.pageTexts=n,this.originalTexts=JSON.parse(JSON.stringify(n)),this.updateElementTexts()}).catch(()=>{})}}groupTextsBySection(){let t={};for(let[,e]of this.managedElements){let i=e.sectionSlug;t[i]||(t[i]={}),this.pageTexts[e.key]!==void 0&&(t[i][e.key]=this.pageTexts[e.key])}return t}async saveChanges(){if(!this.config.apiBase){this.showToast("No API configured. Set apiBase to enable save.","error");return}this.isSaving=!0,this.updateUI();try{let t=this.groupTextsBySection(),e=Object.entries(t).map(([s,n])=>fetch(`${this.config.apiBase}/web_page/save`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:s,title:s===this.currentSlug?this.currentTitle:s.replace("/",""),site_identifier:this.siteIdentifier,content:{texts:n,...s===this.currentSlug?{images:this.pageImages}:{}}})}));if((await Promise.all(e)).some(s=>!s.ok))throw new Error("One or more sections failed to save");this.isSaving=!1,this.resetAfterSave(),this.updateUI(),this.showToast("Draft saved successfully!","success"),this.config.onSaved?.()}catch(t){this.isSaving=!1,this.updateUI(),this.showToast("Save failed. Please try again.","error"),this.config.onError?.("save",t)}}async publishChanges(){if(!this.config.apiBase){this.showToast("No API configured. Set apiBase to enable publish.","error");return}this.isPublishing=!0,this.updateUI();try{let t=this.groupTextsBySection(),e=Object.entries(t).map(([s,n])=>fetch(`${this.config.apiBase}/web_page/publish`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:s,title:s===this.currentSlug?this.currentTitle:s.replace("/",""),site_identifier:this.siteIdentifier,published_content:{texts:n,...s===this.currentSlug?{images:this.pageImages}:{}}})}));if((await Promise.all(e)).some(s=>!s.ok))throw new Error("One or more sections failed to publish");this.isPublishing=!1,this.resetAfterSave(),this.updateUI(),this.showToast("Published successfully!","success"),this.config.onPublished?.()}catch(t){this.isPublishing=!1,this.updateUI(),this.showToast("Publish failed. Please try again.","error"),this.config.onError?.("publish",t)}}async toggleHistory(){this.showHistory=!this.showHistory,this.showHistory&&await this.loadHistory(),this.updateUI()}async loadHistory(){try{let t=await this.openDB(),e=await new Promise((i,s)=>{let r=t.transaction(b,"readonly").objectStore(b).index("slug").getAll(this.currentSlug);r.onsuccess=()=>i(r.result.sort((d,c)=>c.timestamp-d.timestamp).slice(0,30)),r.onerror=()=>s(r.error)});this.historyList=e,this.renderHistoryList()}catch{}}renderHistoryList(){if(this.historyListEl){if(this.historyListEl.innerHTML="",this.historyList.length===0){let t=this.createElement("div","lcms-history-empty");t.textContent="No history yet",this.historyListEl.appendChild(t);return}for(let t of this.historyList){let e=document.createElement("button");e.className="lcms-history-item";let i=this.createElement("div","lcms-history-label");i.textContent=t.label;let s=this.createElement("div","lcms-history-meta"),n=this.createElement("span","lcms-history-lang");n.textContent=t.lang.toUpperCase();let a=document.createTextNode(" "+this.formatDate(t.timestamp));s.appendChild(n),s.appendChild(a),e.appendChild(i),e.appendChild(s),e.addEventListener("click",o=>{o.stopPropagation(),this.restoreHistory(t)}),this.historyListEl.appendChild(e)}}}restoreHistory(t){this.undoStack.push(this.createSnapshot()),this.canUndo=!0,this.applySnapshot(t.snapshot),this.recalcDirtyKeys(),this.showHistory=!1,this.updateElementTexts(),this.applyPageImages(),this.updateUI(),this.showToast("Restored from history","success")}pushHistory(t,e){let i=e==="img",s=i?t.split("/").pop()||"image":t.split("_").pop()||t,n=i?`Changed ${s}`:`Edited ${s}`;this.openDB().then(a=>{a.transaction(b,"readwrite").objectStore(b).add({slug:this.currentSlug,timestamp:Date.now(),label:n,lang:e,snapshot:JSON.stringify({texts:this.pageTexts,images:this.pageImages})})}).catch(()=>{})}async cleanOldHistory(){try{let t=await this.openDB(),e=Date.now()-this.historyRetentionMs,n=t.transaction(b,"readwrite").objectStore(b).index("timestamp").openCursor(IDBKeyRange.upperBound(e));n.onsuccess=()=>{let a=n.result;a&&(a.delete(),a.continue())}}catch{}}openDB(){return this.db?Promise.resolve(this.db):new Promise((t,e)=>{let i=indexedDB.open(H,1);i.onupgradeneeded=()=>{let s=i.result;if(!s.objectStoreNames.contains(b)){let n=s.createObjectStore(b,{keyPath:"id",autoIncrement:!0});n.createIndex("slug","slug",{unique:!1}),n.createIndex("timestamp","timestamp",{unique:!1})}},i.onsuccess=()=>{this.db=i.result,t(this.db)},i.onerror=()=>e(i.error)})}showToast(t,e){if(!this.toastEl)return;this.toastMessage=t,this.toastType=e;let i=e==="success"?p.check:p.error;this.toastEl.className=`lcms-toast lcms-toast-${e}`,this.toastEl.innerHTML=`${i} ${t}`,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=setTimeout(()=>{this.toastEl&&this.toastEl.classList.add("lcms-hidden")},3e3)}onFabClick(t){t.stopPropagation(),!this.hasMoved&&(this.isOpen=!this.isOpen,this.updateUI())}togglePanel(){this.hasMoved||(this.isOpen=!this.isOpen,this.updateUI())}toggleEditMode(t){t.stopPropagation(),t.target.checked?(sessionStorage.setItem("builder_edit_mode","true"),this.editMode=!0,this.currentLang=this.detectCurrentLanguage(),this.applyEditMode(!0),this.loadPageContent("draft")):(sessionStorage.removeItem("builder_edit_mode"),this.editMode=!1,this.applyEditMode(!1)),this.updateUI(),this.config.onEditModeChanged?.(this.editMode)}switchLang(t){this.currentLang=t;let e=document.documentElement;e.setAttribute("lang",t),e.setAttribute("dir",t==="ar"?"rtl":"ltr"),localStorage.setItem("selectedLanguage",t),this.updateElementTexts(),this.buildLangButtons(),this.updateUI(),window.dispatchEvent(new CustomEvent("cms:langChanged",{detail:{lang:t}})),this.config.onLangChanged?.(t)}onDragStart(t){t.target.closest("button:not(.lcms-fab-btn)")||t.target.closest(".lcms-panel")||(this.isDragging=!0,this.hasMoved=!1,this.dragStartX=t.clientX,this.dragStartY=t.clientY,this.startPosX=this.posX,this.startPosY=this.posY,document.addEventListener("mousemove",this.boundMouseMove),document.addEventListener("mouseup",this.boundMouseUp))}onDragMove(t){if(!this.isDragging||!this.fabEl)return;let e=t.clientX-this.dragStartX,i=t.clientY-this.dragStartY;(Math.abs(e)>3||Math.abs(i)>3)&&(this.hasMoved=!0),this.posX=Math.max(0,Math.min(window.innerWidth-60,this.startPosX+e)),this.posY=Math.max(0,Math.min(window.innerHeight-60,this.startPosY+i)),this.fabEl.style.left=this.posX+"px",this.fabEl.style.top=this.posY+"px"}onDragEnd(){this.isDragging=!1,document.removeEventListener("mousemove",this.boundMouseMove),document.removeEventListener("mouseup",this.boundMouseUp)}onTouchStart(t){if(t.target.closest("button:not(.lcms-fab-btn)")||t.target.closest(".lcms-panel"))return;let e=t.touches[0];this.isDragging=!0,this.hasMoved=!1,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.startPosX=this.posX,this.startPosY=this.posY,document.addEventListener("touchmove",this.boundTouchMove,{passive:!1}),document.addEventListener("touchend",this.boundTouchEnd)}onTouchMove(t){if(!this.isDragging||!this.fabEl)return;t.preventDefault();let e=t.touches[0],i=e.clientX-this.dragStartX,s=e.clientY-this.dragStartY;(Math.abs(i)>3||Math.abs(s)>3)&&(this.hasMoved=!0),this.posX=Math.max(0,Math.min(window.innerWidth-60,this.startPosX+i)),this.posY=Math.max(0,Math.min(window.innerHeight-60,this.startPosY+s)),this.fabEl.style.left=this.posX+"px",this.fabEl.style.top=this.posY+"px"}onTouchEnd(){this.isDragging=!1,document.removeEventListener("touchmove",this.boundTouchMove),document.removeEventListener("touchend",this.boundTouchEnd)}setLoading(t){this.loading=t,this.updateUI()}detectCurrentLanguage(){let t=document.documentElement.getAttribute("lang");if(t&&this.languages.includes(t))return t;let e=localStorage.getItem("selectedLanguage");return e&&this.languages.includes(e)?e:this.defaultLanguage}createElement(t,e){let i=document.createElement(t);return i.className=e,i}formatDate(t){let e=new Date(t),i=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=e.getHours(),n=e.getMinutes().toString().padStart(2,"0"),a=s>=12?"PM":"AM",o=s%12||12;return`${i[e.getMonth()]} ${e.getDate()}, ${o}:${n} ${a}`}showLoginModal(){if(this.loginModalEl)return;let t=document.createElement("div");t.className="lcms-login-overlay",t.id="lcms-login-modal",t.innerHTML=`
|
|
304
|
+
</div>`,this.rootEl.appendChild(this.loaderEl),this.toastEl=this.createElement("div","lcms-toast lcms-hidden"),this.rootEl.appendChild(this.toastEl),this.fabEl=this.createElement("div","lcms-fab"),this.fabEl.style.left=this.posX+"px",this.fabEl.style.top=this.posY+"px",this.fabEl.addEventListener("mousedown",t=>this.onDragStart(t)),this.fabEl.addEventListener("touchstart",t=>this.onTouchStart(t),{passive:!0}),this.fabBtn=document.createElement("button"),this.fabBtn.className="lcms-fab-btn",this.fabBtn.innerHTML=p.edit,this.fabBtn.addEventListener("click",t=>this.onFabClick(t)),this.badgeEl=this.createElement("span","lcms-badge lcms-hidden"),this.fabBtn.appendChild(this.badgeEl),this.fabEl.appendChild(this.fabBtn),this.panelEl=this.createElement("div","lcms-panel lcms-hidden"),this.buildPanel(),this.fabEl.appendChild(this.panelEl),this.rootEl.appendChild(this.fabEl),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/*",this.fileInput.style.display="none",this.fileInput.addEventListener("change",t=>this.onImageFileSelected(t)),this.rootEl.appendChild(this.fileInput),this.imgOverlay=this.createElement("div","lcms-img-upload-overlay lcms-hidden"),this.imgOverlay.innerHTML='<div class="lcms-img-upload-content"><div class="lcms-spinner-lg"></div><span>Uploading image...</span></div>',this.rootEl.appendChild(this.imgOverlay),document.body.appendChild(this.rootEl)}buildPanel(){if(!this.panelEl)return;let t=this.createElement("div","lcms-panel-header"),e=this.createElement("label","lcms-toggle");e.addEventListener("click",l=>l.stopPropagation()),this.editToggle=document.createElement("input"),this.editToggle.type="checkbox",this.editToggle.checked=this.editMode,this.editToggle.addEventListener("change",l=>this.toggleEditMode(l));let i=this.createElement("span","lcms-toggle-slider"),s=this.createElement("span","lcms-toggle-label");s.textContent="Edit",e.appendChild(this.editToggle),e.appendChild(i),e.appendChild(s),t.appendChild(e),this.langSwitchEl=this.createElement("div","lcms-lang-switch lcms-hidden"),this.buildLangButtons(),t.appendChild(this.langSwitchEl);let n=document.createElement("button");n.className="lcms-close-btn",n.innerHTML=p.close,n.addEventListener("click",l=>{l.stopPropagation(),this.togglePanel()}),t.appendChild(n),this.panelEl.appendChild(t),this.siteIdEl=this.createElement("div","lcms-site-id");let a=this.siteIdentifier.includes(".");this.siteIdEl.innerHTML=`<span class="lcms-site-id-icon">${a?"\u{1F310}":"\u{1F511}"}</span><span class="lcms-site-id-text">${a?this.siteIdentifier:this.siteIdentifier.substring(0,8)}</span>`,this.panelEl.appendChild(this.siteIdEl),this.editModeContent=this.createElement("div","lcms-hidden"),this.changesInfoEl=this.createElement("div","lcms-changes-info lcms-hidden"),this.editModeContent.appendChild(this.changesInfoEl);let o=this.createElement("div","lcms-undo-row");this.undoBtn=document.createElement("button"),this.undoBtn.className="lcms-icon-btn",this.undoBtn.innerHTML=p.undo,this.undoBtn.disabled=!0,this.undoBtn.addEventListener("click",l=>{l.stopPropagation(),this.onUndo()}),this.redoBtn=document.createElement("button"),this.redoBtn.className="lcms-icon-btn",this.redoBtn.innerHTML=p.redo,this.redoBtn.disabled=!0,this.redoBtn.addEventListener("click",l=>{l.stopPropagation(),this.onRedo()}),o.appendChild(this.undoBtn),o.appendChild(this.redoBtn),this.editModeContent.appendChild(o);let r=this.createElement("div","lcms-theme-row"),d=this.createElement("span","lcms-theme-label");d.textContent="Theme",r.appendChild(d);let c=this.createElement("div","lcms-theme-colors"),m=["#00C853","#6722FB","#2196F3","#FF5722","#E91E63","#FFD600"];for(let l of m){let f=this.createElement("div","lcms-theme-swatch");f.style.background=l,f.dataset.color=l,l===this.highlightColor&&f.classList.add("active"),f.addEventListener("click",S=>{S.stopPropagation(),this.applyThemeColor(l)}),c.appendChild(f)}let h=this.createElement("div","lcms-theme-custom"),u=this.createElement("div","lcms-theme-custom-preview"),y=document.createElement("input");y.type="color",y.value=this.highlightColor,y.addEventListener("input",l=>{l.stopPropagation(),this.applyThemeColor(l.target.value)}),h.appendChild(u),h.appendChild(y),c.appendChild(h),r.appendChild(c),this.editModeContent.appendChild(r),this.historyBtnEl=document.createElement("button"),this.historyBtnEl.className="lcms-history-btn",this.historyBtnEl.innerHTML=`${p.history} History (7 days)`,this.historyBtnEl.addEventListener("click",l=>{l.stopPropagation(),this.toggleHistory()}),this.editModeContent.appendChild(this.historyBtnEl),this.historyPanelEl=this.createElement("div","lcms-history-panel lcms-hidden");let E=this.createElement("div","lcms-history-title");E.textContent="Edit History",this.historyPanelEl.appendChild(E),this.historyListEl=this.createElement("div","lcms-history-list"),this.historyPanelEl.appendChild(this.historyListEl),this.editModeContent.appendChild(this.historyPanelEl),this.actionsEl=this.createElement("div","lcms-actions"),this.saveBtn=document.createElement("button"),this.saveBtn.className="lcms-btn-save",this.saveBtn.innerHTML=`${p.save} Save Draft`,this.saveBtn.addEventListener("click",l=>{l.stopPropagation(),this.saveChanges()}),this.publishBtn=document.createElement("button"),this.publishBtn.className="lcms-btn-publish",this.publishBtn.innerHTML=`${p.publish} Publish`,this.publishBtn.addEventListener("click",l=>{l.stopPropagation(),this.publishChanges()}),this.cancelBtn=document.createElement("button"),this.cancelBtn.className="lcms-btn-cancel",this.cancelBtn.textContent="Cancel",this.cancelBtn.addEventListener("click",l=>{l.stopPropagation(),this.cancelEditing()}),this.actionsEl.appendChild(this.saveBtn),this.actionsEl.appendChild(this.publishBtn),this.actionsEl.appendChild(this.cancelBtn),this.editModeContent.appendChild(this.actionsEl),this.panelEl.appendChild(this.editModeContent),this.brandingEl=this.createElement("div","lcms-branding"),this.brandingEl.innerHTML='<div class="lcms-branding-logo"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg></div><div class="lcms-branding-text">Powered by <span>XtroEdge</span></div>',this.brandingEl.addEventListener("click",l=>{l.stopPropagation(),window.open("https://xtro.vercel.app/","_blank")}),this.panelEl.appendChild(this.brandingEl)}buildLangButtons(){if(!this.langSwitchEl)return;this.langSwitchEl.innerHTML="";let t=document.createElement("select");t.className="lcms-lang-select";for(let i of this.languages){let s=document.createElement("option");s.value=i,s.textContent=i.toUpperCase(),i===this.currentLang&&(s.selected=!0),t.appendChild(s)}t.addEventListener("change",i=>{i.stopPropagation(),this.switchLang(i.target.value)}),this.langSwitchEl.appendChild(t);let e=document.createElement("span");e.className="lcms-lang-arrow",e.textContent="\u25BC",this.langSwitchEl.appendChild(e)}updateUI(){if(this.fabEl&&(this.fabEl.style.display=this.isEditAllowed?"":"none"),this.fabBtn&&(this.fabBtn.style.display=this.isOpen?"none":"",this.fabBtn.classList.toggle("lcms-fab-active",this.editMode)),this.panelEl&&(this.panelEl.classList.toggle("lcms-hidden",!this.isOpen),this.isOpen)){let t=this.posY>window.innerHeight/2,e=this.posX>window.innerWidth/2;this.panelEl.style.bottom=t?"0":"",this.panelEl.style.top=t?"":"0",this.panelEl.style.right=e?"0":"",this.panelEl.style.left=e?"":"0"}if(this.badgeEl&&(this.badgeEl.classList.toggle("lcms-hidden",this.unsavedChanges===0),this.badgeEl.textContent=String(this.unsavedChanges)),this.editToggle&&(this.editToggle.checked=this.editMode),this.langSwitchEl){this.langSwitchEl.classList.toggle("lcms-hidden",!this.editMode||this.languages.length<=1);let t=this.langSwitchEl.querySelector(".lcms-lang-select");t&&(t.value=this.currentLang)}this.editModeContent&&this.editModeContent.classList.toggle("lcms-hidden",!this.editMode),this.changesInfoEl&&(this.changesInfoEl.classList.toggle("lcms-hidden",this.unsavedChanges===0),this.changesInfoEl.textContent=`${this.unsavedChanges} unsaved change${this.unsavedChanges>1?"s":""}`),this.undoBtn&&(this.undoBtn.disabled=!this.canUndo),this.redoBtn&&(this.redoBtn.disabled=!this.canRedo),this.historyBtnEl&&this.historyBtnEl.classList.toggle("active",this.showHistory),this.historyPanelEl&&this.historyPanelEl.classList.toggle("lcms-hidden",!this.showHistory),this.saveBtn&&(this.saveBtn.disabled=this.isSaving||this.isPublishing||this.unsavedChanges===0,this.saveBtn.innerHTML=this.isSaving?'<span class="lcms-spinner"></span> Saving...':`${p.save} Save Draft`),this.publishBtn&&(this.publishBtn.disabled=this.isSaving||this.isPublishing,this.publishBtn.innerHTML=this.isPublishing?'<span class="lcms-spinner"></span> Publishing...':`${p.publish} Publish`),this.cancelBtn&&(this.cancelBtn.disabled=this.isSaving||this.isPublishing),this.loaderEl&&this.loaderEl.classList.toggle("lcms-hidden",!this.loading),this.imgOverlay&&this.imgOverlay.classList.toggle("lcms-hidden",!this.imageUploading)}autoDetectAndScan(){this.autoDetectElements(),this.scanDOM(),this.scanImages()}resolveContainer(){return this.containerSelector&&document.querySelector(this.containerSelector)||document.body}autoDetectElements(){let t=this.resolveContainer();if(!t)return;for(let r of this.autoDetectedElements)document.contains(r)||this.autoDetectedElements.delete(r);let e=r=>{let d=r.parentElement;for(;d&&d!==document.body;){let c=d.tagName.toLowerCase();if(c==="header"||c.endsWith("-header"))return"/header";if(c==="footer"||c.endsWith("-footer"))return"/footer";d=d.parentElement}return this.currentSlug},i={},s=(r,d)=>{let c=d==="/header"?"header":d==="/footer"?"footer":"page";i[c]||(i[c]={});let m=r.tagName.toLowerCase();i[c][m]||(i[c][m]=0);let u=`${c!=="page"?`${c}_`:""}xcms_${m}_${i[c][m]}`;i[c][m]++,r.setAttribute("data-cms",u),r.setAttribute("data-cms-section",d),this.autoDetectedElements.add(r)},n=this.editableTags.join(",");t.querySelectorAll(n).forEach(r=>{r.hasAttribute("data-cms")||r.closest("#xtroedge-cms-root, script, style, noscript")||r.children.length>3||this.getDirectTextContent(r).trim().length<2||s(r,e(r))}),t.querySelectorAll("[data-editable]").forEach(r=>{r.hasAttribute("data-cms")||r.closest("#xtroedge-cms-root, script, style, noscript")||s(r,e(r))})}scanDOM(){document.querySelectorAll("[data-cms]").forEach(e=>{if(e.closest("#xtroedge-cms-root"))return;let i=e.getAttribute("data-cms");this.registeredKeys.add(i),this.managedElements.has(e)||this.attachElement(e,i)});for(let[e]of this.managedElements)document.contains(e)||this.detachElement(e)}scanImages(){let t=this.resolveContainer();if(!t)return;let e={...this.pageImages},i=!1;t.querySelectorAll("img").forEach(n=>{if(n.closest("#xtroedge-cms-root")||this.managedImages.has(n))return;let a=n.getAttribute("src")||"";!a||a.startsWith("data:")||(this.attachImage(n,a),e[a]||(e[a]=a,i=!0))}),i&&(this.pageImages=e,this.originalImages=JSON.parse(JSON.stringify(e)));for(let[n]of this.managedImages)document.contains(n)||this.detachImage(n)}getDirectTextContent(t){let e="";for(let i=0;i<t.childNodes.length;i++)t.childNodes[i].nodeType===Node.TEXT_NODE&&(e+=t.childNodes[i].textContent||"");return e}attachElement(t,e){let i=()=>{let r=t.textContent?.trim()||"",d=this.getPageText(e);r!==d&&this.onTextChanged(e,r)},s=r=>{r.key==="Enter"&&(r.preventDefault(),t.blur())},n=()=>{let r=t.textContent?.trim()||"",d=this.getPageText(e);r!==d&&this.onTextChanged(e,r)},a=r=>{r.preventDefault(),r.stopPropagation()},o=t.getAttribute("data-cms-section")||this.currentSlug;this.managedElements.set(t,{key:e,sectionSlug:o,blurHandler:i,keydownHandler:s,inputHandler:n,clickHandler:a}),this.editMode&&this.enableElementEdit(t,e,i,s,n,a)}detachElement(t){let e=this.managedElements.get(t);e&&(t.removeEventListener("blur",e.blurHandler),t.removeEventListener("keydown",e.keydownHandler),t.removeEventListener("input",e.inputHandler),t.removeEventListener("click",e.clickHandler,!0),t.removeAttribute("contenteditable"),this.managedElements.delete(t))}enableElementEdit(t,e,i,s,n,a){let o=this.getPageText(e);o&&(t.textContent=o),t.setAttribute("contenteditable","true"),t.style.borderBottom=`2px dashed ${this.highlightColor}`,t.style.padding="2px 4px",t.style.borderRadius="3px",t.style.cursor="text",t.style.outline="none",t.style.transition="background 0.2s",t.style.minWidth="20px",t.addEventListener("blur",i),t.addEventListener("keydown",s),t.addEventListener("input",n),t.addEventListener("click",a,!0)}disableElementEdit(t,e,i,s,n,a){t.removeAttribute("contenteditable"),t.style.borderBottom="",t.style.padding="",t.style.borderRadius="",t.style.cursor="",t.style.outline="",t.style.transition="",t.style.minWidth="";let o=this.getPageText(e);o&&(t.textContent=o),t.removeEventListener("blur",i),t.removeEventListener("keydown",s),t.removeEventListener("input",n),t.removeEventListener("click",a,!0)}applyEditMode(t){for(let[e,i]of this.managedElements)t?this.enableElementEdit(e,i.key,i.blurHandler,i.keydownHandler,i.inputHandler,i.clickHandler):this.disableElementEdit(e,i.key,i.blurHandler,i.keydownHandler,i.inputHandler,i.clickHandler);this.applyImageEditMode(t)}updateElementTexts(){this.observer?.disconnect();for(let[t,e]of this.managedElements){if(document.activeElement===t)continue;let i=this.getPageText(e.key);i&&t.textContent!==i&&(t.textContent=i)}this.observer?.observe(document.body,{childList:!0,subtree:!0})}cleanupManagedElements(){for(let[t]of this.managedElements)this.detachElement(t);this.managedElements.clear();for(let t of this.autoDetectedElements)t.removeAttribute("data-cms");this.autoDetectedElements.clear(),this.cleanupManagedImages()}attachImage(t,e){let i=s=>{this.editMode&&(s.preventDefault(),s.stopPropagation(),this.showImageContextMenu(s.clientX,s.clientY,t))};this.managedImages.set(t,{key:e,ctxHandler:i}),this.editMode&&this.enableImageEdit(t,i)}detachImage(t){let e=this.managedImages.get(t);e&&(t.removeEventListener("contextmenu",e.ctxHandler),t.style.outline="",t.style.cursor="",this.managedImages.delete(t))}cleanupManagedImages(){for(let[t]of this.managedImages)this.detachImage(t);this.managedImages.clear(),this.dismissImageCtxMenu()}applyImageEditMode(t){for(let[e,i]of this.managedImages)t?this.enableImageEdit(e,i.ctxHandler):this.disableImageEdit(e,i.ctxHandler);t||this.dismissImageCtxMenu()}enableImageEdit(t,e){t.style.outline=`2px dashed ${this.highlightColor}`,t.style.cursor="context-menu",t.addEventListener("contextmenu",e)}disableImageEdit(t,e){t.style.outline="",t.style.cursor="",t.removeEventListener("contextmenu",e)}showImageContextMenu(t,e,i){this.dismissImageCtxMenu();let s=document.createElement("div");Object.assign(s.style,{position:"fixed",zIndex:"10005",minWidth:"160px",background:"rgba(30,15,60,0.85)",backdropFilter:"blur(16px)",webkitBackdropFilter:"blur(16px)",border:"1px solid rgba(139,92,246,0.3)",borderRadius:"10px",padding:"4px",boxShadow:"0 8px 32px rgba(0,0,0,0.4)",fontFamily:"system-ui, -apple-system, sans-serif",left:Math.min(t,window.innerWidth-180)+"px",top:Math.min(e,window.innerHeight-50)+"px"});let n=document.createElement("button");Object.assign(n.style,{width:"100%",padding:"8px 12px",border:"none",borderRadius:"7px",background:"transparent",color:"white",fontSize:"12px",fontWeight:"500",cursor:"pointer",display:"flex",alignItems:"center",gap:"8px"}),n.innerHTML=`${p.image} Upload Image`,n.addEventListener("mouseenter",()=>n.style.background="rgba(103,34,251,0.3)"),n.addEventListener("mouseleave",()=>n.style.background="transparent"),n.addEventListener("click",()=>{this.activeImageEl=i,this.fileInput&&(this.fileInput.value="",this.fileInput.click()),this.dismissImageCtxMenu()}),s.appendChild(n),document.body.appendChild(s),this.imageCtxMenu=s;let a=o=>{s.contains(o.target)||(this.dismissImageCtxMenu(),document.removeEventListener("mousedown",a))};setTimeout(()=>document.addEventListener("mousedown",a),0)}dismissImageCtxMenu(){this.imageCtxMenu&&(this.imageCtxMenu.remove(),this.imageCtxMenu=null)}onImageFileSelected(t){let i=t.target.files?.[0];if(!i||!this.activeImageEl)return;this.imageUploading=!0,this.updateUI();let s=new FileReader;s.onload=()=>{let n=s.result;this.uploadImageToApi(n)},s.readAsDataURL(i)}async uploadImageToApi(t){try{let e=await fetch(`${this.config.apiBase}/web/upload-image`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:t})});if(!e.ok)throw new Error(`HTTP ${e.status}`);let i=await e.json(),n=(this.config.imageBaseUrl||(this.config.apiBase?new URL(this.config.apiBase).origin:""))+i.path;if(this.activeImageEl){let a=this.managedImages.get(this.activeImageEl)?.key||"";this.activeImageEl.src=n,this.onImageChanged(a,n)}this.imageUploading=!1,this.activeImageEl=null,this.updateUI(),this.showToast("Image updated!","success")}catch(e){this.imageUploading=!1,this.activeImageEl=null,this.updateUI(),this.showToast("Image upload failed.","error"),this.config.onError?.("upload-image",e)}}applyPageImages(){for(let[t,e]of this.managedImages){let i=this.pageImages[e.key];i&&t.src!==i&&(t.src=i)}}getPageText(t){return this.pageTexts[t]?.[this.currentLang]||""}onTextChanged(t,e){this.undoStack.push(this.createSnapshot()),this.redoStack=[],this.canUndo=!0,this.canRedo=!1,this.pageTexts[t]||(this.pageTexts[t]={}),this.pageTexts[t]={...this.pageTexts[t],[this.currentLang]:e},this.dirtyKeys.add(t),this.unsavedChanges=this.dirtyKeys.size+this.dirtyImageKeys.size,this.pushHistory(t,this.currentLang),this.updateUI()}onImageChanged(t,e){this.undoStack.push(this.createSnapshot()),this.redoStack=[],this.canUndo=!0,this.canRedo=!1,this.pageImages={...this.pageImages,[t]:e},this.dirtyImageKeys.add(t),this.unsavedChanges=this.dirtyKeys.size+this.dirtyImageKeys.size,this.pushHistory(t,"img"),this.updateUI()}createSnapshot(){return JSON.stringify({texts:this.pageTexts,images:this.pageImages})}applySnapshot(t){let e=JSON.parse(t);e.texts?(this.pageTexts=e.texts,e.images&&(this.pageImages=e.images)):this.pageTexts=e}onUndo(){this.undoStack.length!==0&&(this.redoStack.push(this.createSnapshot()),this.applySnapshot(this.undoStack.pop()),this.canUndo=this.undoStack.length>0,this.canRedo=!0,this.recalcDirtyKeys(),this.updateElementTexts(),this.applyPageImages(),this.updateUI())}onRedo(){this.redoStack.length!==0&&(this.undoStack.push(this.createSnapshot()),this.applySnapshot(this.redoStack.pop()),this.canUndo=!0,this.canRedo=this.redoStack.length>0,this.recalcDirtyKeys(),this.updateElementTexts(),this.applyPageImages(),this.updateUI())}recalcDirtyKeys(){this.dirtyKeys.clear();for(let t of this.registeredKeys)JSON.stringify(this.pageTexts[t])!==JSON.stringify(this.originalTexts[t])&&this.dirtyKeys.add(t);this.unsavedChanges=this.dirtyKeys.size+this.dirtyImageKeys.size}resetAll(){this.dirtyKeys.clear(),this.dirtyImageKeys.clear(),this.unsavedChanges=0,this.undoStack=[],this.redoStack=[],this.canUndo=!1,this.canRedo=!1,this.updateUI()}resetAfterSave(){this.dirtyKeys.clear(),this.dirtyImageKeys.clear(),this.unsavedChanges=0,this.originalTexts=JSON.parse(JSON.stringify(this.pageTexts)),this.originalImages=JSON.parse(JSON.stringify(this.pageImages))}cancelEditing(){this.pageTexts=JSON.parse(JSON.stringify(this.originalTexts)),this.pageImages=JSON.parse(JSON.stringify(this.originalImages)),this.dirtyKeys.clear(),this.dirtyImageKeys.clear(),this.unsavedChanges=0,this.updateElementTexts(),this.applyPageImages(),this.updateUI()}async loadTranslationsAndInit(t){if(this.config.i18nBasePath)try{let e=this.currentLang,i=await fetch(`${this.config.i18nBasePath}/${e}.json`);if(i.ok){let s=await i.json();this.translationCache.clear(),this.flattenTranslations(s,"",this.getPageSection())}}catch{}this.autoDetectAndScan(),this.editMode&&this.applyEditMode(!0),this.config.apiBase?t?this.loadPageContent("draft"):this.loadPublishedContent():(this.buildDefaultTexts(),this.originalTexts=JSON.parse(JSON.stringify(this.pageTexts)),this.originalImages=JSON.parse(JSON.stringify(this.pageImages)),this.setLoading(!1)),this.updateUI()}flattenTranslations(t,e,i){for(let s of Object.keys(t)){let n=e?`${e}.${s}`:s;if(typeof t[s]=="string"){let a=t[s].trim();a.length>=2&&(!this.translationCache.get(a)||n.toUpperCase().startsWith(i))&&this.translationCache.set(a,n)}else typeof t[s]=="object"&&t[s]!==null&&!Array.isArray(t[s])&&this.flattenTranslations(t[s],n,i)}}getPageSection(){return this.currentSlug.replace(/^\//,"").replace(/-/g,"_").toUpperCase()}async fetchSectionTexts(t,e){try{let i=await fetch(`${this.config.apiBase}/web-page/get?slug=${encodeURIComponent(t)}&status=${e}&site_identifier=${encodeURIComponent(this.siteIdentifier)}`);if(!i.ok)return null;let s=await i.json();return s?.published_content?.texts||s?.content?.texts||null}catch{return null}}async loadPageContent(t){this.setLoading(!0),this.cleanOldHistory();try{let[e,i,s]=await Promise.all([this.fetchSectionTexts(this.currentSlug,t),this.fetchSectionTexts("/header",t),this.fetchSectionTexts("/footer",t)]);e||i||s?this.pageTexts={...e||{},...i||{},...s||{}}:this.buildDefaultTexts();let n=await fetch(`${this.config.apiBase}/web-page/get?slug=${encodeURIComponent(this.currentSlug)}&status=${t}&site_identifier=${encodeURIComponent(this.siteIdentifier)}`).catch(()=>null);if(n?.ok){let a=await n.json(),o=a?.published_content?.images||a?.content?.images;o&&(this.pageImages=JSON.parse(JSON.stringify(o)),this.applyPageImages())}this.originalTexts=JSON.parse(JSON.stringify(this.pageTexts)),this.originalImages=JSON.parse(JSON.stringify(this.pageImages)),this.resetAll(),this.updateElementTexts()}catch{this.buildDefaultTexts(),this.originalTexts=JSON.parse(JSON.stringify(this.pageTexts)),this.originalImages=JSON.parse(JSON.stringify(this.pageImages)),this.resetAll()}finally{this.setLoading(!1)}}async loadPublishedContent(){this.setLoading(!0);try{let[t,e,i]=await Promise.all([this.fetchSectionTexts(this.currentSlug,"published"),this.fetchSectionTexts("/header","published"),this.fetchSectionTexts("/footer","published")]),s={...t||{},...e||{},...i||{}};Object.keys(s).length>0&&(this.pageTexts=JSON.parse(JSON.stringify(s)),this.updateElementTexts());let n=await fetch(`${this.config.apiBase}/web-page/get?slug=${encodeURIComponent(this.currentSlug)}&status=published&site_identifier=${encodeURIComponent(this.siteIdentifier)}`);if(n.ok){let o=(await n.json())?.published_content?.images;o&&Object.keys(o).length>0&&(this.pageImages=JSON.parse(JSON.stringify(o)),this.applyPageImages())}}catch{}finally{this.setLoading(!1)}}buildDefaultTexts(){let t={};for(let e of this.registeredKeys){let s=document.querySelector(`[data-cms="${e}"]`)?.textContent?.trim()||"";t[e]={[this.currentLang]:s}}if(this.pageTexts=t,this.config.i18nBasePath){let e=this.languages.filter(i=>i!==this.currentLang);for(let i of e)fetch(`${this.config.i18nBasePath}/${i}.json`).then(s=>s.json()).then(s=>{let n={...this.pageTexts};for(let a of this.registeredKeys){let o=a.split("."),r=s;for(let d of o)r=r?.[d];r&&typeof r=="string"&&(n[a]={...n[a],[i]:r})}this.pageTexts=n,this.originalTexts=JSON.parse(JSON.stringify(n)),this.updateElementTexts()}).catch(()=>{})}}groupTextsBySection(){let t={};for(let[,e]of this.managedElements){let i=e.sectionSlug;t[i]||(t[i]={}),this.pageTexts[e.key]!==void 0&&(t[i][e.key]=this.pageTexts[e.key])}return t}async saveChanges(){if(!this.config.apiBase){this.showToast("No API configured. Set apiBase to enable save.","error");return}this.isSaving=!0,this.updateUI();try{let t=this.groupTextsBySection(),e=Object.entries(t).map(([s,n])=>fetch(`${this.config.apiBase}/web_page/save`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:s,title:s===this.currentSlug?this.currentTitle:s.replace("/",""),site_identifier:this.siteIdentifier,content:{texts:n,...s===this.currentSlug?{images:this.pageImages}:{}}})}));if((await Promise.all(e)).some(s=>!s.ok))throw new Error("One or more sections failed to save");this.isSaving=!1,this.resetAfterSave(),this.updateUI(),this.showToast("Draft saved successfully!","success"),this.config.onSaved?.()}catch(t){this.isSaving=!1,this.updateUI(),this.showToast("Save failed. Please try again.","error"),this.config.onError?.("save",t)}}async publishChanges(){if(!this.config.apiBase){this.showToast("No API configured. Set apiBase to enable publish.","error");return}this.isPublishing=!0,this.updateUI();try{let t=this.groupTextsBySection(),e=Object.entries(t).map(([s,n])=>fetch(`${this.config.apiBase}/web_page/publish`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:s,title:s===this.currentSlug?this.currentTitle:s.replace("/",""),site_identifier:this.siteIdentifier,published_content:{texts:n,...s===this.currentSlug?{images:this.pageImages}:{}}})}));if((await Promise.all(e)).some(s=>!s.ok))throw new Error("One or more sections failed to publish");this.isPublishing=!1,this.resetAfterSave(),this.updateUI(),this.showToast("Published successfully!","success"),this.config.onPublished?.()}catch(t){this.isPublishing=!1,this.updateUI(),this.showToast("Publish failed. Please try again.","error"),this.config.onError?.("publish",t)}}async toggleHistory(){this.showHistory=!this.showHistory,this.showHistory&&await this.loadHistory(),this.updateUI()}async loadHistory(){try{let t=await this.openDB(),e=await new Promise((i,s)=>{let r=t.transaction(b,"readonly").objectStore(b).index("slug").getAll(this.currentSlug);r.onsuccess=()=>i(r.result.sort((d,c)=>c.timestamp-d.timestamp).slice(0,30)),r.onerror=()=>s(r.error)});this.historyList=e,this.renderHistoryList()}catch{}}renderHistoryList(){if(this.historyListEl){if(this.historyListEl.innerHTML="",this.historyList.length===0){let t=this.createElement("div","lcms-history-empty");t.textContent="No history yet",this.historyListEl.appendChild(t);return}for(let t of this.historyList){let e=document.createElement("button");e.className="lcms-history-item";let i=this.createElement("div","lcms-history-label");i.textContent=t.label;let s=this.createElement("div","lcms-history-meta"),n=this.createElement("span","lcms-history-lang");n.textContent=t.lang.toUpperCase();let a=document.createTextNode(" "+this.formatDate(t.timestamp));s.appendChild(n),s.appendChild(a),e.appendChild(i),e.appendChild(s),e.addEventListener("click",o=>{o.stopPropagation(),this.restoreHistory(t)}),this.historyListEl.appendChild(e)}}}restoreHistory(t){this.undoStack.push(this.createSnapshot()),this.canUndo=!0,this.applySnapshot(t.snapshot),this.recalcDirtyKeys(),this.showHistory=!1,this.updateElementTexts(),this.applyPageImages(),this.updateUI(),this.showToast("Restored from history","success")}pushHistory(t,e){let i=e==="img",s=i?t.split("/").pop()||"image":t.split("_").pop()||t,n=i?`Changed ${s}`:`Edited ${s}`;this.openDB().then(a=>{a.transaction(b,"readwrite").objectStore(b).add({slug:this.currentSlug,timestamp:Date.now(),label:n,lang:e,snapshot:JSON.stringify({texts:this.pageTexts,images:this.pageImages})})}).catch(()=>{})}async cleanOldHistory(){try{let t=await this.openDB(),e=Date.now()-this.historyRetentionMs,n=t.transaction(b,"readwrite").objectStore(b).index("timestamp").openCursor(IDBKeyRange.upperBound(e));n.onsuccess=()=>{let a=n.result;a&&(a.delete(),a.continue())}}catch{}}openDB(){return this.db?Promise.resolve(this.db):new Promise((t,e)=>{let i=indexedDB.open(P,1);i.onupgradeneeded=()=>{let s=i.result;if(!s.objectStoreNames.contains(b)){let n=s.createObjectStore(b,{keyPath:"id",autoIncrement:!0});n.createIndex("slug","slug",{unique:!1}),n.createIndex("timestamp","timestamp",{unique:!1})}},i.onsuccess=()=>{this.db=i.result,t(this.db)},i.onerror=()=>e(i.error)})}showToast(t,e){if(!this.toastEl)return;this.toastMessage=t,this.toastType=e;let i=e==="success"?p.check:p.error;this.toastEl.className=`lcms-toast lcms-toast-${e}`,this.toastEl.innerHTML=`${i} ${t}`,this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=setTimeout(()=>{this.toastEl&&this.toastEl.classList.add("lcms-hidden")},3e3)}onFabClick(t){t.stopPropagation(),!this.hasMoved&&(this.isOpen=!this.isOpen,this.updateUI())}togglePanel(){this.hasMoved||(this.isOpen=!this.isOpen,this.updateUI())}toggleEditMode(t){t.stopPropagation(),t.target.checked?(sessionStorage.setItem("builder_edit_mode","true"),this.editMode=!0,this.currentLang=this.detectCurrentLanguage(),this.applyEditMode(!0),this.loadPageContent("draft")):(sessionStorage.removeItem("builder_edit_mode"),this.editMode=!1,this.applyEditMode(!1)),this.updateUI(),this.config.onEditModeChanged?.(this.editMode)}switchLang(t){this.currentLang=t,localStorage.setItem("selectedLanguage",t),document.documentElement.setAttribute("lang",t),document.documentElement.setAttribute("dir",t==="ar"?"rtl":"ltr"),this.config.onLangChanged?.(t),window.dispatchEvent(new CustomEvent("cms:langChanged",{detail:{lang:t}})),window.location.reload()}onDragStart(t){t.target.closest("button:not(.lcms-fab-btn)")||t.target.closest(".lcms-panel")||(this.isDragging=!0,this.hasMoved=!1,this.dragStartX=t.clientX,this.dragStartY=t.clientY,this.startPosX=this.posX,this.startPosY=this.posY,document.addEventListener("mousemove",this.boundMouseMove),document.addEventListener("mouseup",this.boundMouseUp))}onDragMove(t){if(!this.isDragging||!this.fabEl)return;let e=t.clientX-this.dragStartX,i=t.clientY-this.dragStartY;(Math.abs(e)>3||Math.abs(i)>3)&&(this.hasMoved=!0),this.posX=Math.max(0,Math.min(window.innerWidth-60,this.startPosX+e)),this.posY=Math.max(0,Math.min(window.innerHeight-60,this.startPosY+i)),this.fabEl.style.left=this.posX+"px",this.fabEl.style.top=this.posY+"px"}onDragEnd(){this.isDragging=!1,document.removeEventListener("mousemove",this.boundMouseMove),document.removeEventListener("mouseup",this.boundMouseUp)}onTouchStart(t){if(t.target.closest("button:not(.lcms-fab-btn)")||t.target.closest(".lcms-panel"))return;let e=t.touches[0];this.isDragging=!0,this.hasMoved=!1,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.startPosX=this.posX,this.startPosY=this.posY,document.addEventListener("touchmove",this.boundTouchMove,{passive:!1}),document.addEventListener("touchend",this.boundTouchEnd)}onTouchMove(t){if(!this.isDragging||!this.fabEl)return;t.preventDefault();let e=t.touches[0],i=e.clientX-this.dragStartX,s=e.clientY-this.dragStartY;(Math.abs(i)>3||Math.abs(s)>3)&&(this.hasMoved=!0),this.posX=Math.max(0,Math.min(window.innerWidth-60,this.startPosX+i)),this.posY=Math.max(0,Math.min(window.innerHeight-60,this.startPosY+s)),this.fabEl.style.left=this.posX+"px",this.fabEl.style.top=this.posY+"px"}onTouchEnd(){this.isDragging=!1,document.removeEventListener("touchmove",this.boundTouchMove),document.removeEventListener("touchend",this.boundTouchEnd)}setLoading(t){this.loading=t,this.updateUI()}detectCurrentLanguage(){let t=document.documentElement.getAttribute("lang");if(t&&this.languages.includes(t))return t;let e=localStorage.getItem("selectedLanguage");return e&&this.languages.includes(e)?e:this.defaultLanguage}createElement(t,e){let i=document.createElement(t);return i.className=e,i}formatDate(t){let e=new Date(t),i=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=e.getHours(),n=e.getMinutes().toString().padStart(2,"0"),a=s>=12?"PM":"AM",o=s%12||12;return`${i[e.getMonth()]} ${e.getDate()}, ${o}:${n} ${a}`}showLoginModal(){if(this.loginModalEl)return;let t=document.createElement("div");t.className="lcms-login-overlay",t.id="lcms-login-modal",t.innerHTML=`
|
|
303
305
|
<div class="lcms-login-box">
|
|
304
306
|
<div class="lcms-login-logo">
|
|
305
307
|
<div class="lcms-login-logo-icon">
|
|
@@ -320,4 +322,4 @@
|
|
|
320
322
|
<button class="lcms-login-btn" id="lcms-login-btn">Sign In</button>
|
|
321
323
|
<div class="lcms-login-error" id="lcms-login-error"></div>
|
|
322
324
|
</div>
|
|
323
|
-
`,document.body.appendChild(t),this.loginModalEl=t;let e=t.querySelector("#lcms-login-btn"),i=t.querySelector("#lcms-login-email"),s=t.querySelector("#lcms-login-password"),n=()=>this.attemptLogin(i.value.trim(),s.value);e.addEventListener("click",n),s.addEventListener("keydown",a=>{a.key==="Enter"&&n()}),setTimeout(()=>i.focus(),50)}hideLoginModal(){this.loginModalEl?.remove(),this.loginModalEl=null}async attemptLogin(t,e){let i=document.getElementById("lcms-login-btn"),s=document.getElementById("lcms-login-error");if(!t||!e){s.textContent="Please enter your username and password.",s.classList.add("visible");return}i.disabled=!0,i.textContent="Signing in...",s.classList.remove("visible");try{let n=this.config.loginUrl||`${this.config.apiBase}/auth/login`,a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:e})}),o=null;try{o=await a.json()}catch{}if(!a.ok){let d=o?.message||o?.error||null;throw new Error(d||`HTTP ${a.status}`)}let r=o?.token||o?.authToken||o?.auth_token||o?.data?.token;if(!r)throw new Error("Login successful but no token returned.");localStorage.setItem("builder_token",r),this.hideLoginModal(),this.editMode=!0,this.pendingEditMode=!1,sessionStorage.setItem("builder_edit_mode","true"),this.applyEditMode(!0),this.updateUI(),this.loadPageContent("draft")}catch(n){i.disabled=!1,i.textContent="Sign In",s.textContent=n?.message||"Login failed. Please try again.",s.classList.add("visible")}}resolveSiteIdentifier(){let t=window.location.hostname;if(t&&t!=="localhost"&&t!=="127.0.0.1"&&!t.startsWith("192.168."))return t;let e=localStorage.getItem("xtroedge_site_id");return e||(e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let s=Math.random()*16|0;return(i==="x"?s:s&3|8).toString(16)}),localStorage.setItem("xtroedge_site_id",e)),e}hexToRgb(t){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?`${parseInt(e[1],16)},${parseInt(e[2],16)},${parseInt(e[3],16)}`:"0,200,83"}getDarkerColor(t){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(!e)return"#2E7D32";let i=Math.max(0,Math.floor(parseInt(e[1],16)*.6)),s=Math.max(0,Math.floor(parseInt(e[2],16)*.6)),n=Math.max(0,Math.floor(parseInt(e[3],16)*.6));return`#${i.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`}applyThemeColor(t){if(this.highlightColor=t,document.documentElement.style.setProperty("--lcms-primary",t),document.documentElement.style.setProperty("--lcms-primary-rgb",this.hexToRgb(t)),document.documentElement.style.setProperty("--lcms-primary-dark",this.getDarkerColor(t)),this.editMode){for(let[i]of this.managedElements)i.style.borderBottom=`2px dashed ${t}`;for(let[i]of this.managedImages)i.style.outline=`2px dashed ${t}`}this.panelEl?.querySelectorAll(".lcms-theme-swatch")?.forEach(i=>{i.classList.toggle("active",i.dataset.color===t)}),localStorage.setItem("xtroedge_theme_color",t)}static create(t){let e=new g(t);return e.init(),e}static autoInit(){if(window.__xtroedge_cms_instance__)return;let t=window.__XTROEDGE_CMS_CONFIG__||{},e=g.create(t);window.__xtroedge_cms_instance__=e}};function T(){v.autoInit()}typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",T):T());return
|
|
325
|
+
`,document.body.appendChild(t),this.loginModalEl=t;let e=t.querySelector("#lcms-login-btn"),i=t.querySelector("#lcms-login-email"),s=t.querySelector("#lcms-login-password"),n=()=>this.attemptLogin(i.value.trim(),s.value);e.addEventListener("click",n),s.addEventListener("keydown",a=>{a.key==="Enter"&&n()}),setTimeout(()=>i.focus(),50)}hideLoginModal(){this.loginModalEl?.remove(),this.loginModalEl=null}async attemptLogin(t,e){let i=document.getElementById("lcms-login-btn"),s=document.getElementById("lcms-login-error");if(!t||!e){s.textContent="Please enter your username and password.",s.classList.add("visible");return}i.disabled=!0,i.textContent="Signing in...",s.classList.remove("visible");try{let n=this.config.loginUrl||`${this.config.apiBase}/auth/login`,a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:e})}),o=null;try{o=await a.json()}catch{}if(!a.ok){let d=o?.message||o?.error||null;throw new Error(d||`HTTP ${a.status}`)}let r=o?.token||o?.authToken||o?.auth_token||o?.data?.token;if(!r)throw new Error("Login successful but no token returned.");localStorage.setItem("builder_token",r),this.hideLoginModal(),this.editMode=!0,this.pendingEditMode=!1,sessionStorage.setItem("builder_edit_mode","true"),this.applyEditMode(!0),this.updateUI(),this.loadPageContent("draft")}catch(n){i.disabled=!1,i.textContent="Sign In",s.textContent=n?.message||"Login failed. Please try again.",s.classList.add("visible")}}resolveSiteIdentifier(){let t=window.location.hostname;if(t&&t!=="localhost"&&t!=="127.0.0.1"&&!t.startsWith("192.168."))return t;let e=localStorage.getItem("xtroedge_site_id");return e||(e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let s=Math.random()*16|0;return(i==="x"?s:s&3|8).toString(16)}),localStorage.setItem("xtroedge_site_id",e)),e}hexToRgb(t){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?`${parseInt(e[1],16)},${parseInt(e[2],16)},${parseInt(e[3],16)}`:"0,200,83"}getDarkerColor(t){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(!e)return"#2E7D32";let i=Math.max(0,Math.floor(parseInt(e[1],16)*.6)),s=Math.max(0,Math.floor(parseInt(e[2],16)*.6)),n=Math.max(0,Math.floor(parseInt(e[3],16)*.6));return`#${i.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`}applyThemeColor(t){if(this.highlightColor=t,document.documentElement.style.setProperty("--lcms-primary",t),document.documentElement.style.setProperty("--lcms-primary-rgb",this.hexToRgb(t)),document.documentElement.style.setProperty("--lcms-primary-dark",this.getDarkerColor(t)),this.editMode){for(let[i]of this.managedElements)i.style.borderBottom=`2px dashed ${t}`;for(let[i]of this.managedImages)i.style.outline=`2px dashed ${t}`}this.panelEl?.querySelectorAll(".lcms-theme-swatch")?.forEach(i=>{i.classList.toggle("active",i.dataset.color===t)}),localStorage.setItem("xtroedge_theme_color",t)}static create(t){let e=new g(t);return e.init(),e}static autoInit(){if(window.__xtroedge_cms_instance__)return;let t=window.__XTROEDGE_CMS_CONFIG__||{},e=g.create(t);window.__xtroedge_cms_instance__=e}};function T(){v.autoInit()}typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",T):T());return H(O);})();
|
package/dist/index.js
CHANGED
|
@@ -157,10 +157,12 @@ var CMS_STYLES = `
|
|
|
157
157
|
.lcms-toggle input:checked + .lcms-toggle-slider::after { transform: translateX(16px); background: white; }
|
|
158
158
|
.lcms-toggle-label { font-size: 12px; font-weight: 700; color: rgba(255,255,255,0.5); letter-spacing: 0.5px; transition: color 0.25s; }
|
|
159
159
|
.lcms-toggle input:checked ~ .lcms-toggle-label { color: rgba(var(--lcms-primary-rgb, 0,200,83),0.75); }
|
|
160
|
-
.lcms-lang-switch {
|
|
161
|
-
.lcms-lang-
|
|
162
|
-
.lcms-lang-
|
|
163
|
-
.lcms-lang-
|
|
160
|
+
.lcms-lang-switch { margin-left: auto; position: relative; }
|
|
161
|
+
.lcms-lang-select { background: rgba(var(--lcms-primary-rgb, 0,200,83),0.15); border: 1px solid rgba(var(--lcms-primary-rgb, 0,200,83),0.4); border-radius: 6px; color: white; padding: 3px 24px 3px 8px; font-size: 11px; font-weight: 600; cursor: pointer; appearance: none; -webkit-appearance: none; outline: none; transition: all 0.2s; }
|
|
162
|
+
.lcms-lang-select:hover { background: rgba(var(--lcms-primary-rgb, 0,200,83),0.3); }
|
|
163
|
+
.lcms-lang-select:focus { border-color: var(--lcms-primary, #00C853); }
|
|
164
|
+
.lcms-lang-select option { background: #1a1a2e; color: white; }
|
|
165
|
+
.lcms-lang-arrow { position: absolute; right: 6px; top: 50%; transform: translateY(-50%); pointer-events: none; color: rgba(255,255,255,0.6); font-size: 10px; }
|
|
164
166
|
.lcms-close-btn { background: transparent; border: none; color: rgba(255,255,255,0.4); cursor: pointer; padding: 2px; display: flex; transition: color 0.2s; }
|
|
165
167
|
.lcms-close-btn:hover { color: white; }
|
|
166
168
|
.lcms-changes-info { font-size: 12px; color: rgba(var(--lcms-primary-rgb, 0,200,83),0.75); margin-bottom: 10px; padding-left: 2px; }
|
|
@@ -764,16 +766,24 @@ var XtroedgeCMS = class _XtroedgeCMS {
|
|
|
764
766
|
buildLangButtons() {
|
|
765
767
|
if (!this.langSwitchEl) return;
|
|
766
768
|
this.langSwitchEl.innerHTML = "";
|
|
769
|
+
const select = document.createElement("select");
|
|
770
|
+
select.className = "lcms-lang-select";
|
|
767
771
|
for (const lang of this.languages) {
|
|
768
|
-
const
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
this.switchLang(lang);
|
|
774
|
-
});
|
|
775
|
-
this.langSwitchEl.appendChild(btn);
|
|
772
|
+
const opt = document.createElement("option");
|
|
773
|
+
opt.value = lang;
|
|
774
|
+
opt.textContent = lang.toUpperCase();
|
|
775
|
+
if (lang === this.currentLang) opt.selected = true;
|
|
776
|
+
select.appendChild(opt);
|
|
776
777
|
}
|
|
778
|
+
select.addEventListener("change", (e) => {
|
|
779
|
+
e.stopPropagation();
|
|
780
|
+
this.switchLang(e.target.value);
|
|
781
|
+
});
|
|
782
|
+
this.langSwitchEl.appendChild(select);
|
|
783
|
+
const arrow = document.createElement("span");
|
|
784
|
+
arrow.className = "lcms-lang-arrow";
|
|
785
|
+
arrow.textContent = "\u25BC";
|
|
786
|
+
this.langSwitchEl.appendChild(arrow);
|
|
777
787
|
}
|
|
778
788
|
// ===============================================
|
|
779
789
|
// UI UPDATE
|
|
@@ -804,10 +814,8 @@ var XtroedgeCMS = class _XtroedgeCMS {
|
|
|
804
814
|
if (this.editToggle) this.editToggle.checked = this.editMode;
|
|
805
815
|
if (this.langSwitchEl) {
|
|
806
816
|
this.langSwitchEl.classList.toggle("lcms-hidden", !this.editMode || this.languages.length <= 1);
|
|
807
|
-
const
|
|
808
|
-
|
|
809
|
-
btn.classList.toggle("active", btn.textContent === this.currentLang.toUpperCase());
|
|
810
|
-
});
|
|
817
|
+
const sel = this.langSwitchEl.querySelector(".lcms-lang-select");
|
|
818
|
+
if (sel) sel.value = this.currentLang;
|
|
811
819
|
}
|
|
812
820
|
if (this.editModeContent) {
|
|
813
821
|
this.editModeContent.classList.toggle("lcms-hidden", !this.editMode);
|
|
@@ -1694,15 +1702,12 @@ var XtroedgeCMS = class _XtroedgeCMS {
|
|
|
1694
1702
|
}
|
|
1695
1703
|
switchLang(lang) {
|
|
1696
1704
|
this.currentLang = lang;
|
|
1697
|
-
const html = document.documentElement;
|
|
1698
|
-
html.setAttribute("lang", lang);
|
|
1699
|
-
html.setAttribute("dir", lang === "ar" ? "rtl" : "ltr");
|
|
1700
1705
|
localStorage.setItem("selectedLanguage", lang);
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
this.updateUI();
|
|
1704
|
-
window.dispatchEvent(new CustomEvent("cms:langChanged", { detail: { lang } }));
|
|
1706
|
+
document.documentElement.setAttribute("lang", lang);
|
|
1707
|
+
document.documentElement.setAttribute("dir", lang === "ar" ? "rtl" : "ltr");
|
|
1705
1708
|
this.config.onLangChanged?.(lang);
|
|
1709
|
+
window.dispatchEvent(new CustomEvent("cms:langChanged", { detail: { lang } }));
|
|
1710
|
+
window.location.reload();
|
|
1706
1711
|
}
|
|
1707
1712
|
// ===============================================
|
|
1708
1713
|
// FAB DRAG
|