ngx-xtroedge-cms 1.3.2 → 1.3.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.
- package/dist/index.d.mts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.global.js +76 -3
- package/dist/index.js +152 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +152 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -18,6 +18,8 @@ interface XtroedgeCmsConfig {
|
|
|
18
18
|
historyRetentionDays?: number;
|
|
19
19
|
/** Highlight color for editable elements (default: '#6722FB') */
|
|
20
20
|
highlightColor?: string;
|
|
21
|
+
/** Login API URL — if builder_token not found in localStorage, show login modal (default: apiBase + '/auth/login') */
|
|
22
|
+
loginUrl?: string;
|
|
21
23
|
onSaved?: () => void;
|
|
22
24
|
onPublished?: () => void;
|
|
23
25
|
onError?: (action: string, error: any) => void;
|
|
@@ -70,6 +72,8 @@ declare class XtroedgeCMS {
|
|
|
70
72
|
private historyRetentionMs;
|
|
71
73
|
private siteIdentifier;
|
|
72
74
|
private siteIdEl;
|
|
75
|
+
private loginModalEl;
|
|
76
|
+
private pendingEditMode;
|
|
73
77
|
private editMode;
|
|
74
78
|
private currentLang;
|
|
75
79
|
private pageTexts;
|
|
@@ -222,6 +226,9 @@ declare class XtroedgeCMS {
|
|
|
222
226
|
private detectCurrentLanguage;
|
|
223
227
|
private createElement;
|
|
224
228
|
private formatDate;
|
|
229
|
+
private showLoginModal;
|
|
230
|
+
private hideLoginModal;
|
|
231
|
+
private attemptLogin;
|
|
225
232
|
private resolveSiteIdentifier;
|
|
226
233
|
private hexToRgb;
|
|
227
234
|
private getDarkerColor;
|
package/dist/index.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ interface XtroedgeCmsConfig {
|
|
|
18
18
|
historyRetentionDays?: number;
|
|
19
19
|
/** Highlight color for editable elements (default: '#6722FB') */
|
|
20
20
|
highlightColor?: string;
|
|
21
|
+
/** Login API URL — if builder_token not found in localStorage, show login modal (default: apiBase + '/auth/login') */
|
|
22
|
+
loginUrl?: string;
|
|
21
23
|
onSaved?: () => void;
|
|
22
24
|
onPublished?: () => void;
|
|
23
25
|
onError?: (action: string, error: any) => void;
|
|
@@ -70,6 +72,8 @@ declare class XtroedgeCMS {
|
|
|
70
72
|
private historyRetentionMs;
|
|
71
73
|
private siteIdentifier;
|
|
72
74
|
private siteIdEl;
|
|
75
|
+
private loginModalEl;
|
|
76
|
+
private pendingEditMode;
|
|
73
77
|
private editMode;
|
|
74
78
|
private currentLang;
|
|
75
79
|
private pageTexts;
|
|
@@ -222,6 +226,9 @@ declare class XtroedgeCMS {
|
|
|
222
226
|
private detectCurrentLanguage;
|
|
223
227
|
private createElement;
|
|
224
228
|
private formatDate;
|
|
229
|
+
private showLoginModal;
|
|
230
|
+
private hideLoginModal;
|
|
231
|
+
private attemptLogin;
|
|
225
232
|
private resolveSiteIdentifier;
|
|
226
233
|
private hexToRgb;
|
|
227
234
|
private getDarkerColor;
|
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 L=Object.getOwnPropertyNames;var C=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 L(t))!C.call(g,s)&&s!==e&&x(g,s,{get:()=>t[s],enumerable:!(i=M(t,s))||i.enumerable});return g};var P=g=>I(x({},"__esModule",{value:!0}),g);var O={};k(O,{XtroedgeCMS:()=>v});var w=`
|
|
2
2
|
/* ===== XTROEDGE CMS ===== */
|
|
3
3
|
|
|
4
4
|
/* LOADER */
|
|
@@ -236,9 +236,61 @@
|
|
|
236
236
|
}
|
|
237
237
|
.lcms-spinner-lg { width: 36px; height: 36px; border: 3px solid rgba(255,255,255,0.2); border-top-color: var(--lcms-primary, #00C853); border-radius: 50%; animation: lcmsSpin 0.6s linear infinite; }
|
|
238
238
|
|
|
239
|
+
/* LOGIN MODAL */
|
|
240
|
+
.lcms-login-overlay {
|
|
241
|
+
position: fixed; inset: 0; z-index: 10010;
|
|
242
|
+
display: flex; align-items: center; justify-content: center;
|
|
243
|
+
background: rgba(8, 8, 15, 0.75);
|
|
244
|
+
backdrop-filter: blur(16px) saturate(1.4);
|
|
245
|
+
-webkit-backdrop-filter: blur(16px) saturate(1.4);
|
|
246
|
+
font-family: system-ui, -apple-system, sans-serif;
|
|
247
|
+
}
|
|
248
|
+
.lcms-login-box {
|
|
249
|
+
background: #13151a; border: 1px solid rgba(255,255,255,0.1);
|
|
250
|
+
border-radius: 16px; padding: 36px 32px; width: 340px;
|
|
251
|
+
box-shadow: 0 24px 60px rgba(0,0,0,0.6);
|
|
252
|
+
}
|
|
253
|
+
.lcms-login-logo {
|
|
254
|
+
display: flex; align-items: center; justify-content: center;
|
|
255
|
+
gap: 8px; margin-bottom: 24px;
|
|
256
|
+
}
|
|
257
|
+
.lcms-login-logo-icon {
|
|
258
|
+
width: 32px; height: 32px; border-radius: 8px;
|
|
259
|
+
background: linear-gradient(135deg, var(--lcms-primary, #00C853), var(--lcms-primary-dark, #2E7D32));
|
|
260
|
+
display: flex; align-items: center; justify-content: center;
|
|
261
|
+
}
|
|
262
|
+
.lcms-login-logo-text { color: white; font-size: 15px; font-weight: 700; letter-spacing: 0.5px; }
|
|
263
|
+
.lcms-login-title { color: white; font-size: 18px; font-weight: 700; text-align: center; margin-bottom: 6px; }
|
|
264
|
+
.lcms-login-sub { color: rgba(255,255,255,0.4); font-size: 12px; text-align: center; margin-bottom: 24px; }
|
|
265
|
+
.lcms-login-field { margin-bottom: 14px; }
|
|
266
|
+
.lcms-login-label { display: block; color: rgba(255,255,255,0.6); font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.8px; margin-bottom: 6px; }
|
|
267
|
+
.lcms-login-input {
|
|
268
|
+
width: 100%; box-sizing: border-box;
|
|
269
|
+
background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.12);
|
|
270
|
+
border-radius: 8px; padding: 10px 12px;
|
|
271
|
+
color: white; font-size: 13px; font-family: inherit; outline: none;
|
|
272
|
+
transition: border-color 0.2s;
|
|
273
|
+
}
|
|
274
|
+
.lcms-login-input:focus { border-color: var(--lcms-primary, #00C853); }
|
|
275
|
+
.lcms-login-input::placeholder { color: rgba(255,255,255,0.25); }
|
|
276
|
+
.lcms-login-btn {
|
|
277
|
+
width: 100%; padding: 11px; margin-top: 6px; border: none; border-radius: 8px; cursor: pointer;
|
|
278
|
+
background: linear-gradient(135deg, var(--lcms-primary, #00C853), var(--lcms-primary-dark, #2E7D32));
|
|
279
|
+
color: white; font-size: 13px; font-weight: 700; font-family: inherit;
|
|
280
|
+
letter-spacing: 0.3px; transition: filter 0.2s;
|
|
281
|
+
}
|
|
282
|
+
.lcms-login-btn:hover { filter: brightness(1.1); }
|
|
283
|
+
.lcms-login-btn:disabled { opacity: 0.6; cursor: not-allowed; }
|
|
284
|
+
.lcms-login-error {
|
|
285
|
+
background: rgba(239,68,68,0.15); border: 1px solid rgba(239,68,68,0.3);
|
|
286
|
+
border-radius: 8px; padding: 9px 12px; color: #f87171;
|
|
287
|
+
font-size: 12px; text-align: center; margin-top: 12px; display: none;
|
|
288
|
+
}
|
|
289
|
+
.lcms-login-error.visible { display: block; }
|
|
290
|
+
|
|
239
291
|
/* HIDDEN ELEMENTS */
|
|
240
292
|
.lcms-hidden { display: none !important; }
|
|
241
|
-
`;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>'},H="xtroedge_cms_history",
|
|
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>'},H="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">
|
|
242
294
|
<div class="lcms-orbit-loader">
|
|
243
295
|
<div class="lcms-orbit lcms-orbit-1"><span class="lcms-particle"></span></div>
|
|
244
296
|
<div class="lcms-orbit lcms-orbit-2"><span class="lcms-particle"></span></div>
|
|
@@ -247,4 +299,25 @@
|
|
|
247
299
|
<div class="lcms-core"></div>
|
|
248
300
|
</div>
|
|
249
301
|
<span class="lcms-loader-text">Loading</span>
|
|
250
|
-
</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 r=this.siteIdentifier.includes(".");this.siteIdEl.innerHTML=`<span class="lcms-site-id-icon">${r?"\u{1F310}":"\u{1F511}"}</span><span class="lcms-site-id-text">${r?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 a=this.createElement("div","lcms-theme-row"),d=this.createElement("span","lcms-theme-label");d.textContent="Theme",a.appendChild(d);let c=this.createElement("div","lcms-theme-colors"),h=["#00C853","#6722FB","#2196F3","#FF5722","#E91E63","#FFD600"];for(let l of h){let v=this.createElement("div","lcms-theme-swatch");v.style.background=l,v.dataset.color=l,l===this.highlightColor&&v.classList.add("active"),v.addEventListener("click",S=>{S.stopPropagation(),this.applyThemeColor(l)}),c.appendChild(v)}let m=this.createElement("div","lcms-theme-custom"),y=this.createElement("div","lcms-theme-custom-preview"),f=document.createElement("input");f.type="color",f.value=this.highlightColor,f.addEventListener("input",l=>{l.stopPropagation(),this.applyThemeColor(l.target.value)}),m.appendChild(y),m.appendChild(f),c.appendChild(m),a.appendChild(c),this.editModeContent.appendChild(a),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 a of this.autoDetectedElements)document.contains(a)||this.autoDetectedElements.delete(a);let e=a=>{let d=a.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=(a,d)=>{let c=d==="/header"?"header":d==="/footer"?"footer":"page";i[c]||(i[c]={});let h=a.tagName.toLowerCase();i[c][h]||(i[c][h]=0);let y=`${c!=="page"?`${c}_`:""}xcms_${h}_${i[c][h]}`;i[c][h]++,a.setAttribute("data-cms",y),a.setAttribute("data-cms-section",d),this.autoDetectedElements.add(a)},n=this.editableTags.join(",");t.querySelectorAll(n).forEach(a=>{a.hasAttribute("data-cms")||a.closest("#xtroedge-cms-root, script, style, noscript")||a.children.length>3||this.getDirectTextContent(a).trim().length<2||s(a,e(a))}),t.querySelectorAll("[data-editable]").forEach(a=>{a.hasAttribute("data-cms")||a.closest("#xtroedge-cms-root, script, style, noscript")||s(a,e(a))})}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 r=n.getAttribute("src")||"";!r||r.startsWith("data:")||(this.attachImage(n,r),e[r]||(e[r]=r,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 a=t.textContent?.trim()||"",d=this.getPageText(e);a!==d&&this.onTextChanged(e,a)},s=a=>{a.key==="Enter"&&(a.preventDefault(),t.blur())},n=()=>{let a=t.textContent?.trim()||"",d=this.getPageText(e);a!==d&&this.onTextChanged(e,a)},r=a=>{a.preventDefault(),a.stopPropagation()},o=t.getAttribute("data-cms-section")||this.currentSlug;this.managedElements.set(t,{key:e,sectionSlug:o,blurHandler:i,keydownHandler:s,inputHandler:n,clickHandler:r}),this.editMode&&this.enableElementEdit(t,e,i,s,n,r)}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,r){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",r,!0)}disableElementEdit(t,e,i,s,n,r){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",r,!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 r=o=>{s.contains(o.target)||(this.dismissImageCtxMenu(),document.removeEventListener("mousedown",r))};setTimeout(()=>document.addEventListener("mousedown",r),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 r=this.managedImages.get(this.activeImageEl)?.key||"";this.activeImageEl.src=n,this.onImageChanged(r,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 r=t[s].trim();r.length>=2&&(!this.translationCache.get(r)||n.toUpperCase().startsWith(i))&&this.translationCache.set(r,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 r=await n.json(),o=r?.published_content?.images||r?.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 r of this.registeredKeys){let o=r.split("."),a=s;for(let d of o)a=a?.[d];a&&typeof a=="string"&&(n[r]={...n[r],[i]:a})}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 a=t.transaction(u,"readonly").objectStore(u).index("slug").getAll(this.currentSlug);a.onsuccess=()=>i(a.result.sort((d,c)=>c.timestamp-d.timestamp).slice(0,30)),a.onerror=()=>s(a.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 r=document.createTextNode(" "+this.formatDate(t.timestamp));s.appendChild(n),s.appendChild(r),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(r=>{r.transaction(u,"readwrite").objectStore(u).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(u,"readwrite").objectStore(u).index("timestamp").openCursor(IDBKeyRange.upperBound(e));n.onsuccess=()=>{let r=n.result;r&&(r.delete(),r.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(u)){let n=s.createObjectStore(u,{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,this.updateElementTexts(),this.buildLangButtons(),this.updateUI(),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"),r=s>=12?"PM":"AM",o=s%12||12;return`${i[e.getMonth()]} ${e.getDate()}, ${o}:${n} ${r}`}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(){b.autoInit()}typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",T):T());return P(O);})();
|
|
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,this.updateElementTexts(),this.buildLangButtons(),this.updateUI(),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=`
|
|
303
|
+
<div class="lcms-login-box">
|
|
304
|
+
<div class="lcms-login-logo">
|
|
305
|
+
<div class="lcms-login-logo-icon">
|
|
306
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" 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>
|
|
307
|
+
</div>
|
|
308
|
+
<span class="lcms-login-logo-text">XtroEdge CMS</span>
|
|
309
|
+
</div>
|
|
310
|
+
<div class="lcms-login-title">Builder Login</div>
|
|
311
|
+
<div class="lcms-login-sub">Sign in to access edit mode</div>
|
|
312
|
+
<div class="lcms-login-field">
|
|
313
|
+
<label class="lcms-login-label">Username</label>
|
|
314
|
+
<input class="lcms-login-input" id="lcms-login-email" type="text" placeholder="Enter your username" autocomplete="username" />
|
|
315
|
+
</div>
|
|
316
|
+
<div class="lcms-login-field">
|
|
317
|
+
<label class="lcms-login-label">Password</label>
|
|
318
|
+
<input class="lcms-login-input" id="lcms-login-password" type="password" placeholder="Enter your password" autocomplete="current-password" />
|
|
319
|
+
</div>
|
|
320
|
+
<button class="lcms-login-btn" id="lcms-login-btn">Sign In</button>
|
|
321
|
+
<div class="lcms-login-error" id="lcms-login-error"></div>
|
|
322
|
+
</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})});if(!a.ok)throw new Error(`HTTP ${a.status}`);let o=await a.json(),r=o?.token||o?.authToken||o?.auth_token||o?.data?.token;if(!r)throw new Error("No token in response");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{i.disabled=!1,i.textContent="Sign In",s.textContent="Invalid credentials. 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 P(O);})();
|
package/dist/index.js
CHANGED
|
@@ -263,6 +263,58 @@ var CMS_STYLES = `
|
|
|
263
263
|
}
|
|
264
264
|
.lcms-spinner-lg { width: 36px; height: 36px; border: 3px solid rgba(255,255,255,0.2); border-top-color: var(--lcms-primary, #00C853); border-radius: 50%; animation: lcmsSpin 0.6s linear infinite; }
|
|
265
265
|
|
|
266
|
+
/* LOGIN MODAL */
|
|
267
|
+
.lcms-login-overlay {
|
|
268
|
+
position: fixed; inset: 0; z-index: 10010;
|
|
269
|
+
display: flex; align-items: center; justify-content: center;
|
|
270
|
+
background: rgba(8, 8, 15, 0.75);
|
|
271
|
+
backdrop-filter: blur(16px) saturate(1.4);
|
|
272
|
+
-webkit-backdrop-filter: blur(16px) saturate(1.4);
|
|
273
|
+
font-family: system-ui, -apple-system, sans-serif;
|
|
274
|
+
}
|
|
275
|
+
.lcms-login-box {
|
|
276
|
+
background: #13151a; border: 1px solid rgba(255,255,255,0.1);
|
|
277
|
+
border-radius: 16px; padding: 36px 32px; width: 340px;
|
|
278
|
+
box-shadow: 0 24px 60px rgba(0,0,0,0.6);
|
|
279
|
+
}
|
|
280
|
+
.lcms-login-logo {
|
|
281
|
+
display: flex; align-items: center; justify-content: center;
|
|
282
|
+
gap: 8px; margin-bottom: 24px;
|
|
283
|
+
}
|
|
284
|
+
.lcms-login-logo-icon {
|
|
285
|
+
width: 32px; height: 32px; border-radius: 8px;
|
|
286
|
+
background: linear-gradient(135deg, var(--lcms-primary, #00C853), var(--lcms-primary-dark, #2E7D32));
|
|
287
|
+
display: flex; align-items: center; justify-content: center;
|
|
288
|
+
}
|
|
289
|
+
.lcms-login-logo-text { color: white; font-size: 15px; font-weight: 700; letter-spacing: 0.5px; }
|
|
290
|
+
.lcms-login-title { color: white; font-size: 18px; font-weight: 700; text-align: center; margin-bottom: 6px; }
|
|
291
|
+
.lcms-login-sub { color: rgba(255,255,255,0.4); font-size: 12px; text-align: center; margin-bottom: 24px; }
|
|
292
|
+
.lcms-login-field { margin-bottom: 14px; }
|
|
293
|
+
.lcms-login-label { display: block; color: rgba(255,255,255,0.6); font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.8px; margin-bottom: 6px; }
|
|
294
|
+
.lcms-login-input {
|
|
295
|
+
width: 100%; box-sizing: border-box;
|
|
296
|
+
background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.12);
|
|
297
|
+
border-radius: 8px; padding: 10px 12px;
|
|
298
|
+
color: white; font-size: 13px; font-family: inherit; outline: none;
|
|
299
|
+
transition: border-color 0.2s;
|
|
300
|
+
}
|
|
301
|
+
.lcms-login-input:focus { border-color: var(--lcms-primary, #00C853); }
|
|
302
|
+
.lcms-login-input::placeholder { color: rgba(255,255,255,0.25); }
|
|
303
|
+
.lcms-login-btn {
|
|
304
|
+
width: 100%; padding: 11px; margin-top: 6px; border: none; border-radius: 8px; cursor: pointer;
|
|
305
|
+
background: linear-gradient(135deg, var(--lcms-primary, #00C853), var(--lcms-primary-dark, #2E7D32));
|
|
306
|
+
color: white; font-size: 13px; font-weight: 700; font-family: inherit;
|
|
307
|
+
letter-spacing: 0.3px; transition: filter 0.2s;
|
|
308
|
+
}
|
|
309
|
+
.lcms-login-btn:hover { filter: brightness(1.1); }
|
|
310
|
+
.lcms-login-btn:disabled { opacity: 0.6; cursor: not-allowed; }
|
|
311
|
+
.lcms-login-error {
|
|
312
|
+
background: rgba(239,68,68,0.15); border: 1px solid rgba(239,68,68,0.3);
|
|
313
|
+
border-radius: 8px; padding: 9px 12px; color: #f87171;
|
|
314
|
+
font-size: 12px; text-align: center; margin-top: 12px; display: none;
|
|
315
|
+
}
|
|
316
|
+
.lcms-login-error.visible { display: block; }
|
|
317
|
+
|
|
266
318
|
/* HIDDEN ELEMENTS */
|
|
267
319
|
.lcms-hidden { display: none !important; }
|
|
268
320
|
`;
|
|
@@ -312,6 +364,9 @@ var XtroedgeCMS = class _XtroedgeCMS {
|
|
|
312
364
|
this.brandingEl = null;
|
|
313
365
|
this.siteIdentifier = "";
|
|
314
366
|
this.siteIdEl = null;
|
|
367
|
+
this.loginModalEl = null;
|
|
368
|
+
this.pendingEditMode = false;
|
|
369
|
+
// edit=true was requested but token missing
|
|
315
370
|
// ===== State =====
|
|
316
371
|
this.editMode = false;
|
|
317
372
|
this.currentLang = "en";
|
|
@@ -501,12 +556,24 @@ var XtroedgeCMS = class _XtroedgeCMS {
|
|
|
501
556
|
this.resetAll();
|
|
502
557
|
}
|
|
503
558
|
const editFromSession = sessionStorage.getItem("builder_edit_mode") === "true";
|
|
504
|
-
|
|
559
|
+
const wantsEdit = editViaParam || editFromSession;
|
|
560
|
+
if (wantsEdit) {
|
|
561
|
+
const token = localStorage.getItem("builder_token");
|
|
562
|
+
if (!token) {
|
|
563
|
+
this.pendingEditMode = true;
|
|
564
|
+
this.currentLang = this.detectCurrentLanguage();
|
|
565
|
+
this.setLoading(true);
|
|
566
|
+
setTimeout(() => {
|
|
567
|
+
this.loadTranslationsAndInit(false);
|
|
568
|
+
this.showLoginModal();
|
|
569
|
+
}, 300);
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
505
572
|
this.editMode = true;
|
|
506
573
|
}
|
|
507
574
|
this.currentLang = this.detectCurrentLanguage();
|
|
508
575
|
this.setLoading(true);
|
|
509
|
-
const loadDraft =
|
|
576
|
+
const loadDraft = wantsEdit;
|
|
510
577
|
setTimeout(() => {
|
|
511
578
|
this.loadTranslationsAndInit(loadDraft);
|
|
512
579
|
}, 300);
|
|
@@ -1717,6 +1784,89 @@ var XtroedgeCMS = class _XtroedgeCMS {
|
|
|
1717
1784
|
return `${months[d.getMonth()]} ${d.getDate()}, ${h12}:${m} ${ampm}`;
|
|
1718
1785
|
}
|
|
1719
1786
|
// ===============================================
|
|
1787
|
+
// LOGIN MODAL
|
|
1788
|
+
// ===============================================
|
|
1789
|
+
showLoginModal() {
|
|
1790
|
+
if (this.loginModalEl) return;
|
|
1791
|
+
const overlay = document.createElement("div");
|
|
1792
|
+
overlay.className = "lcms-login-overlay";
|
|
1793
|
+
overlay.id = "lcms-login-modal";
|
|
1794
|
+
overlay.innerHTML = `
|
|
1795
|
+
<div class="lcms-login-box">
|
|
1796
|
+
<div class="lcms-login-logo">
|
|
1797
|
+
<div class="lcms-login-logo-icon">
|
|
1798
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" 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>
|
|
1799
|
+
</div>
|
|
1800
|
+
<span class="lcms-login-logo-text">XtroEdge CMS</span>
|
|
1801
|
+
</div>
|
|
1802
|
+
<div class="lcms-login-title">Builder Login</div>
|
|
1803
|
+
<div class="lcms-login-sub">Sign in to access edit mode</div>
|
|
1804
|
+
<div class="lcms-login-field">
|
|
1805
|
+
<label class="lcms-login-label">Username</label>
|
|
1806
|
+
<input class="lcms-login-input" id="lcms-login-email" type="text" placeholder="Enter your username" autocomplete="username" />
|
|
1807
|
+
</div>
|
|
1808
|
+
<div class="lcms-login-field">
|
|
1809
|
+
<label class="lcms-login-label">Password</label>
|
|
1810
|
+
<input class="lcms-login-input" id="lcms-login-password" type="password" placeholder="Enter your password" autocomplete="current-password" />
|
|
1811
|
+
</div>
|
|
1812
|
+
<button class="lcms-login-btn" id="lcms-login-btn">Sign In</button>
|
|
1813
|
+
<div class="lcms-login-error" id="lcms-login-error"></div>
|
|
1814
|
+
</div>
|
|
1815
|
+
`;
|
|
1816
|
+
document.body.appendChild(overlay);
|
|
1817
|
+
this.loginModalEl = overlay;
|
|
1818
|
+
const btn = overlay.querySelector("#lcms-login-btn");
|
|
1819
|
+
const emailInput = overlay.querySelector("#lcms-login-email");
|
|
1820
|
+
const passInput = overlay.querySelector("#lcms-login-password");
|
|
1821
|
+
const doLogin = () => this.attemptLogin(emailInput.value.trim(), passInput.value);
|
|
1822
|
+
btn.addEventListener("click", doLogin);
|
|
1823
|
+
passInput.addEventListener("keydown", (e) => {
|
|
1824
|
+
if (e.key === "Enter") doLogin();
|
|
1825
|
+
});
|
|
1826
|
+
setTimeout(() => emailInput.focus(), 50);
|
|
1827
|
+
}
|
|
1828
|
+
hideLoginModal() {
|
|
1829
|
+
this.loginModalEl?.remove();
|
|
1830
|
+
this.loginModalEl = null;
|
|
1831
|
+
}
|
|
1832
|
+
async attemptLogin(email, password) {
|
|
1833
|
+
const btn = document.getElementById("lcms-login-btn");
|
|
1834
|
+
const errorEl = document.getElementById("lcms-login-error");
|
|
1835
|
+
if (!email || !password) {
|
|
1836
|
+
errorEl.textContent = "Please enter your username and password.";
|
|
1837
|
+
errorEl.classList.add("visible");
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1840
|
+
btn.disabled = true;
|
|
1841
|
+
btn.textContent = "Signing in...";
|
|
1842
|
+
errorEl.classList.remove("visible");
|
|
1843
|
+
try {
|
|
1844
|
+
const loginUrl = this.config.loginUrl || `${this.config.apiBase}/auth/login`;
|
|
1845
|
+
const res = await fetch(loginUrl, {
|
|
1846
|
+
method: "POST",
|
|
1847
|
+
headers: { "Content-Type": "application/json" },
|
|
1848
|
+
body: JSON.stringify({ username: email, password })
|
|
1849
|
+
});
|
|
1850
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
1851
|
+
const data = await res.json();
|
|
1852
|
+
const token = data?.token || data?.authToken || data?.auth_token || data?.data?.token;
|
|
1853
|
+
if (!token) throw new Error("No token in response");
|
|
1854
|
+
localStorage.setItem("builder_token", token);
|
|
1855
|
+
this.hideLoginModal();
|
|
1856
|
+
this.editMode = true;
|
|
1857
|
+
this.pendingEditMode = false;
|
|
1858
|
+
sessionStorage.setItem("builder_edit_mode", "true");
|
|
1859
|
+
this.applyEditMode(true);
|
|
1860
|
+
this.updateUI();
|
|
1861
|
+
this.loadPageContent("draft");
|
|
1862
|
+
} catch {
|
|
1863
|
+
btn.disabled = false;
|
|
1864
|
+
btn.textContent = "Sign In";
|
|
1865
|
+
errorEl.textContent = "Invalid credentials. Please try again.";
|
|
1866
|
+
errorEl.classList.add("visible");
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
// ===============================================
|
|
1720
1870
|
// SITE IDENTIFIER
|
|
1721
1871
|
// ===============================================
|
|
1722
1872
|
resolveSiteIdentifier() {
|