-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1632 lines (1396 loc) · 68.1 KB
/
Copy pathapp.js
File metadata and controls
1632 lines (1396 loc) · 68.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { WebContainerGitService } from './WebContainerGitService.js';
import { WasmBridge } from './lib/runtime/WasmBridge.js';
import { IframeSyncService } from './lib/services/IframeSyncService.js';
import cms from './cms.js'; // The visual editor bridge
// Robust detection to ensure we don't suppress the UI in LocalCorp/Proxy environments
const isHostApp = window.self === window.top;
// --- RUNTIME: Register Service Worker for WASM Previews ---
if ('serviceWorker' in navigator && isHostApp) {
navigator.serviceWorker.register('/runtime-sw.js', { scope: '/' })
.then(reg => console.log('[0CMS] Runtime Service Worker registered:', reg.scope))
.catch(err => console.warn('[0CMS] Runtime SW registration failed:', err));
}
// --- IFRAME GUARD: Fix Flickering & Prevent Recursive Init ---
if (!isHostApp) {
console.log('[0CMS] Running in preview mode (iframe). Dashboard UI suppressed.');
}
const ui = isHostApp ? {
dashboard: document.getElementById('cmsDashboard'),
landingProject: document.getElementById('cmsLandingProject'),
landingRepoName: document.getElementById('landingRepoName'),
landingAuthAction: document.getElementById('heroAuthAction'),
landingLoginBtn: document.getElementById('landingLoginBtn'),
btnClose: document.getElementById('btnCloseCms'),
preview: document.getElementById('cmsPreviewFrame'),
statusLabel: document.getElementById('cmsStatusLabel'),
repoDisplay: document.getElementById('cmsActiveRepo'),
stepLogin: document.getElementById('cmsStepLogin'),
stepPicker: document.getElementById('cmsStepPicker'),
repoList: document.getElementById('cmsRepoList'),
repoLoader: document.getElementById('cmsRepoLoader'),
loginBtn: document.getElementById('cmsLoginBtn'),
saveBtn: document.getElementById('cmsSaveBtn'),
urlChipStatus: document.getElementById('urlChipStatus'),
navNewPage: document.getElementById('navNewPage'),
navSEO: document.getElementById('navSEO'),
historyDrawer: document.getElementById('cmsHistoryDrawer'),
pageSettingsPanel: document.getElementById('cmsPageSettingsPanel'),
seoTitle: document.getElementById('seoTitle'),
seoDesc: document.getElementById('seoDesc'),
seoImage: document.getElementById('seoImage'),
seoSaveBtn: document.getElementById('seoSaveBtn'),
createPanel: document.getElementById('cmsCreatePanel'),
createLoader: document.getElementById('cmsCreateLoader'),
createList: document.getElementById('cmsCreateList'),
previewLoader: document.getElementById('previewLoader'),
navBack: document.getElementById('navBack'),
navForward: document.getElementById('navForward'),
landingRepoSection: document.getElementById('landingRepoSection'),
landingRepoList: document.getElementById('landingRepoList'),
btnToggleLanding: document.getElementById('toggleCmsBtnLanding'),
historyList: document.getElementById('cmsHistoryList'),
loaderStatus: document.getElementById('cmsLoaderStatus'),
viewDesktop: document.getElementById('viewDesktop'),
viewTablet: document.getElementById('viewTablet'),
viewMobile: document.getElementById('viewMobile'),
// NEW DOCK ELEMENTS
modeToggle: document.getElementById('cmsModeToggle'),
modeLabel: document.getElementById('cmsModeLabel'),
modeIcon: document.getElementById('cmsModeIcon'),
// removed historyBtnCount (redundant)
// NEW REPO PICKER CONTROLS
accountSwitcherBtn: document.getElementById('accountSwitcherBtn'),
selectedAccountAvatar: document.getElementById('selectedAccountAvatar'),
selectedAccountName: document.getElementById('selectedAccountName'),
accountDropdown: document.getElementById('accountDropdown'),
repoSearchInput: document.getElementById('repoSearchInput'),
ghAppSettingsLink: document.getElementById('ghAppSettingsLink'),
navDemoBtn: document.getElementById('landingDemoBtn'),
prewarmLoader: document.getElementById('prewarmLoader'),
toast: document.getElementById('cmsToast'),
// EXTRACTION UI
btnExtractMode: document.getElementById('btnExtractMode'),
btnAddComponent: document.getElementById('btnAddComponent'),
extractPanel: document.getElementById('cmsExtractPanel'),
extractNameInput: document.getElementById('extractComponentName'),
btnConfirmExtract: document.getElementById('btnConfirmExtract'),
// SIDEBAR TABS & VIEWS
tabChanges: document.getElementById('tabChanges'),
tabComponents: document.getElementById('tabComponents'),
viewChanges: document.getElementById('viewChanges'),
viewComponents: document.getElementById('viewComponents'),
viewAssets: document.getElementById('viewAssets'),
assetList: document.getElementById('cmsAssetList'),
assetDropZone: document.getElementById('assetDropZone'),
tabAssets: document.getElementById('tabAssets'),
componentList: document.getElementById('cmsComponentList'),
componentSearch: document.getElementById('componentSearch'),
categoryFilter: document.getElementById('cmsCategoryFilter'),
// PROGRESS & LOGGING
progressCircle: document.getElementById('cmsProgressCircle'),
terminal: document.getElementById('cmsTerminalText'),
terminalOverlay: document.getElementById('cmsTerminalOverlay')
} : {};
if (isHostApp) {
// Helper to safely bind events without crashing if element is missing
const safeBind = (el, event, handler) => {
if (el) el[event] = handler;
};
let settings = JSON.parse(localStorage.getItem('zcms-settings') || '{}');
// --- AUTHENTICATION FLOW ---
// Extraction from URL is handled in <head> for zero-flicker experience.
// We just need to ensure our local 'settings' object matches localStorage.
let cmsActive = false;
let cmsService = null;
let preWarmPromise = null;
let changes = {};
let entries = [];
let currentRepos = [];
let installations = [];
let selectedInstallationId = null;
let currentInstallationToken = null;
const urlParams = new URLSearchParams(window.location.search);
let isDemoMode = urlParams.get('demo') === 'true';
function getActiveToken() {
if (currentInstallationToken) return currentInstallationToken;
try {
const d = JSON.parse(localStorage.getItem('zcms-inst'));
if (d && d.token && d.expires > Date.now()) return d.token;
} catch (e) {}
return settings.token;
}
// --- EVENT LISTENERS (CRITICAL FIRST) ---
safeBind(ui.accountSwitcherBtn, 'onclick', (e) => {
e.stopPropagation();
if (!ui.accountDropdown) return;
const isOpen = ui.accountDropdown.classList.contains('open');
ui.accountDropdown.classList.toggle('open', !isOpen);
ui.accountSwitcherBtn.classList.toggle('active', !isOpen);
});
safeBind(ui.repoSearchInput, 'oninput', (e) => renderRepos(e.target.value));
document.addEventListener('click', (e) => {
if (ui.accountDropdown && ui.accountSwitcherBtn && !ui.accountSwitcherBtn.contains(e.target)) {
ui.accountDropdown.classList.remove('open');
ui.accountSwitcherBtn.classList.remove('active');
}
});
// Unconditionally refresh UI state on load to ensure persistence
if (isHostApp) {
refreshLandingUI();
}
// 1. QUANTUM PRE-WARM: Start engine immediately if we have a repo (UNLESS in Demo Mode)
// - [x] Implement `MarkerService.js` (Zero-Width Encoding/Decoding)
// - [x] Create `TaggerTrait.js` (WebContainer Instrumentation logic)
// - [x] Integrate `TaggerTrait` into `WebContainerGitService.js` (Pre-build hook)
// - [x] Update `cms.js` (Bridge detection and source mapping)
// - [x] Handle Source Mapping in `app.js`
// - [ ] Implement `cleanup` logic (Remove markers before save/publish)
// - [ ] Verification with Astro/Hexo sample
let preWarmingService = null;
if (settings.repo && settings.token && !isDemoMode) {
preWarmingService = new WebContainerGitService();
preWarmingService.repoUrl = `https://github.com/${settings.repo}`;
preWarmingService.token = getActiveToken();
preWarmPromise = preWarmingService.initWebContainer()
.then(() => preWarmingService.boot(preWarmingService.repoUrl, localStorage.getItem('zcms-manual-command')))
.catch(e => console.error('Pre-warm failed:', e));
}
// 2. DASHBOARD UI CONTROLS
// If we started via ?demo=true, boot the demo engine immediately once the UI is ready
if (isDemoMode && isHostApp) {
document.addEventListener('DOMContentLoaded', () => {
window.startDemoMode();
});
}
// --- COMPONENT EXTRACTION & SOURCE TRACKING ---
let isExtractMode = false;
let activeSourceMetadata = null; // Deterministic Marker Cache
window.toggleExtractMode = (enabled) => {
isExtractMode = enabled !== undefined ? enabled : !isExtractMode;
ui.btnExtractMode?.classList.toggle('active', isExtractMode);
ui.extractPanel.style.display = isExtractMode ? 'flex' : 'none';
// Notify the bridge
ui.preview?.contentWindow.postMessage({
type: 'CMS_EXTRACT_MODE',
enabled: isExtractMode
}, '*');
if (isExtractMode) showToast('Click any element to select for extraction', 'info');
};
safeBind(ui.btnExtractMode, 'onclick', () => window.toggleExtractMode());
safeBind(ui.btnAddComponent, 'onclick', () => {
window.toggleHistory(true);
ui.tabComponents.click();
});
// SIDEBAR TAB SWITCHING
const switchSidebarTab = (tabId) => {
ui.tabChanges.classList.toggle('active', tabId === 'tabChanges');
ui.tabComponents.classList.toggle('active', tabId === 'tabComponents');
ui.tabAssets.classList.toggle('active', tabId === 'tabAssets');
ui.viewChanges.style.display = tabId === 'tabChanges' ? 'flex' : 'none';
ui.viewComponents.style.display = tabId === 'tabComponents' ? 'flex' : 'none';
ui.viewAssets.style.display = tabId === 'tabAssets' ? 'flex' : 'none';
// Auto-scan on Switch
if (tabId === 'tabComponents') scanProjectComponents();
if (tabId === 'tabAssets') scanProjectAssets();
};
safeBind(ui.tabChanges, 'onclick', () => switchSidebarTab('tabChanges'));
safeBind(ui.tabComponents, 'onclick', () => switchSidebarTab('tabComponents'));
safeBind(ui.tabAssets, 'onclick', () => switchSidebarTab('tabAssets'));
safeBind(ui.btnConfirmExtract, 'onclick', () => {
const name = ui.extractNameInput.value.trim();
if (!name) return showToast('Please enter a component name', 'error');
ui.preview?.contentWindow.postMessage({
type: 'CMS_EXTRACT_TRIGGER',
name: name
}, '*');
});
// Listener for extracted data from bridge (Universal Components)
// Listener for generic postMessages from iframe
window.addEventListener('message', async (e) => {
// 1. UNIVERSAL COMPONENT CAPTURE
if (e.data.type === 'CMS_COMPONENT_CAPTURED') {
const { name, html } = e.data;
if (!cmsService) return;
if (ui.btnAddComponent) ui.btnAddComponent.style.display = 'flex';
const path = `/repo/src/components/zcms/${name.toLowerCase().replace(/\s+/g, '_')}.html`;
await cmsService.updateFile(path, html);
renderComponentCard({ name, html });
showToast(`Component "${name}" discovered!`, 'success');
}
// 2. DETERMINISTIC SOURCE MAPPING
if (e.data.type === 'CMS_SOURCE_LOCATED') {
const { fileId, line, selector } = e.data;
activeSourceMetadata = { fileId, line, selector };
if (cmsService) {
const path = cmsService.tagger.pathMap.get(fileId);
if (path) {
const filename = path.split('/').pop();
if (ui.loaderStatus) {
ui.loaderStatus.textContent = `Source Verified: ${filename} (Line ${line})`;
ui.previewLoader.style.display = 'flex';
ui.previewLoader.classList.remove('hidden');
ui.previewLoader.style.opacity = '1';
setTimeout(() => {
if (ui.loaderStatus.textContent.includes('Source Verified')) {
ui.previewLoader.style.opacity = '0';
setTimeout(() => {
ui.previewLoader.style.display = 'none';
ui.previewLoader.classList.add('hidden');
}, 500);
}
}, 2000);
}
}
}
}
// 3. SEO DATA RECEPTION
if (e.data.type === 'CMS_SEO_DATA') {
ui.seoTitle.value = e.data.title || '';
ui.seoDesc.value = e.data.description || '';
ui.seoImage.value = e.data.image || '';
}
// 4. CMS READY SIGNAL
if (e.data.type === 'CMS_READY') {
if (ui.previewLoader) {
ui.previewLoader.style.opacity = '0';
setTimeout(() => {
ui.previewLoader.style.display = 'none';
ui.previewLoader.classList.add('hidden');
}, 500);
}
if (ui.statusLabel) {
ui.statusLabel.textContent = '0 unchanged changes';
ui.statusLabel.style.color = 'var(--text-muted)';
ui.statusLabel.style.opacity = '0.7';
}
const statusIcon = document.getElementById('cmsStatusIcon');
if (statusIcon) statusIcon.style.stroke = 'var(--text-muted)';
ui.preview.contentWindow.postMessage({ type: 'CMS_TOGGLE', enabled: true }, '*');
}
// 5. CHANGE TRACKING
if (e.data.type === 'CMS_CHANGED') {
const count = Object.keys(e.data.changes).length;
changes = e.data.changes;
entries = e.data.entries || [];
if (ui.historyCount) ui.historyCount.textContent = count;
if (ui.statusLabel) {
ui.statusLabel.textContent = `${count} unchanged change${count !== 1 ? 's' : ''}`;
ui.statusLabel.style.color = count > 0 ? 'var(--primary)' : 'var(--text-muted)';
}
// Autosync logic
if (entries.length > 0 && cmsService) {
const lastEntry = entries[entries.length - 1];
if (lastEntry.original && lastEntry.updated && lastEntry.original !== lastEntry.updated) {
const metadata = (activeSourceMetadata && activeSourceMetadata.selector === lastEntry.selector) ? activeSourceMetadata : null;
cmsService.applySmartMatchChange(lastEntry.original, lastEntry.updated, metadata).then(async (result) => {
if (result && result.path && result.content) {
WasmBridge.getInstance().syncFile(result.path, result.content);
IframeSyncService.getInstance().sync(ui.preview, ui.preview.src, result.markerId);
}
}).catch(err => console.error('[CMS] Autosync failed:', err));
}
}
if (ui.historyList) {
renderHistoryList(count, entries);
}
}
});
// COMPONENT LIBRARY HELPERS
let allComponents = [];
let activeCategory = 'all';
const scanProjectComponents = async () => {
if (!cmsService) return;
allComponents = await cmsService.listComponents();
if (allComponents.length > 0) {
if (ui.btnAddComponent) ui.btnAddComponent.style.display = 'flex';
renderCategoryFilters();
renderComponentList();
}
};
const renderCategoryFilters = () => {
if (!ui.categoryFilter) return;
const categories = ['all', ...new Set(allComponents.map(c => c.category))];
ui.categoryFilter.innerHTML = categories.map(cat => `
<div class="category-pill ${activeCategory === cat ? 'active' : ''}"
data-category="${cat}"
onclick="setCategoryFilter('${cat}')">
${cat === 'all' ? 'All' : cat}
</div>
`).join('');
};
window.setCategoryFilter = (cat) => {
activeCategory = cat;
renderCategoryFilters();
renderComponentList();
};
const renderComponentList = () => {
const query = ui.componentSearch?.value.toLowerCase() || '';
const filtered = allComponents.filter(comp => {
const matchesQuery = comp.name.toLowerCase().includes(query) ||
comp.category.toLowerCase().includes(query);
const matchesCategory = activeCategory === 'all' || comp.category === activeCategory;
return matchesQuery && matchesCategory;
});
if (filtered.length === 0) {
ui.componentList.innerHTML = '<div style="text-align:center; padding-top:40px; color:var(--text-muted); font-size:0.8rem;">No components matching your search.</div>';
return;
}
ui.componentList.innerHTML = '';
// Group by category for visual clarity
const groups = {};
filtered.forEach(comp => {
if (!groups[comp.category]) groups[comp.category] = [];
groups[comp.category].push(comp);
});
Object.keys(groups).sort().forEach(category => {
const header = document.createElement('div');
header.className = 'component-section-header';
header.textContent = category;
ui.componentList.appendChild(header);
groups[category].forEach(comp => renderComponentCard(comp));
});
};
// ASSET LIBRARY HELPERS
const scanProjectAssets = async () => {
if (!cmsService) return;
const assets = await cmsService.listAssets();
ui.assetList.innerHTML = '';
if (assets.length === 0) {
ui.assetList.innerHTML = '<div style="text-align:center; padding-top:40px; color:var(--text-muted); font-size:0.8rem; grid-column: 1 / -1;">No assets found in /public.</div>';
} else {
assets.forEach(asset => renderAssetCard(asset));
}
};
const renderAssetCard = (asset) => {
const card = document.createElement('div');
card.className = 'asset-card';
card.innerHTML = `
<div class="asset-preview">
${asset.type === 'svg' ? `<img src="${asset.url}" style="object-fit:contain; padding:10px;">` : `<img src="${asset.url}">`}
</div>
<div class="asset-actions">
<div class="action-chip" onclick="event.stopPropagation(); copyToClipboard('${asset.url}')">Path</div>
</div>
<div class="asset-info">
<div class="asset-name" title="${asset.name}">${asset.name}</div>
<div class="asset-meta">${asset.type.toUpperCase()} • ${asset.url}</div>
</div>
`;
ui.assetList.appendChild(card);
};
window.copyToClipboard = (text) => {
navigator.clipboard.writeText(text).then(() => {
showToast(`Copied: ${text}`, 'success');
});
};
// UPLOAD HANDLER
if (ui.assetDropZone) {
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(name => {
ui.assetDropZone.addEventListener(name, (e) => {
e.preventDefault(); e.stopPropagation();
}, false);
});
ui.assetDropZone.addEventListener('dragenter', () => ui.assetDropZone.classList.add('active'));
ui.assetDropZone.addEventListener('dragover', () => ui.assetDropZone.classList.add('active'));
ui.assetDropZone.addEventListener('dragleave', () => ui.assetDropZone.classList.remove('active'));
ui.assetDropZone.addEventListener('drop', async (e) => {
ui.assetDropZone.classList.remove('active');
const files = e.dataTransfer.files;
if (files.length > 0) {
showToast(`Uploading ${files.length} file(s)...`, 'info');
for (let file of files) {
try {
await cmsService.saveAsset(file);
} catch (err) {
showToast(`Failed to upload ${file.name}`, 'error');
}
}
showToast('Upload complete!', 'success');
scanProjectAssets();
}
});
}
// Real-time search listener
if (ui.componentSearch) {
ui.componentSearch.oninput = () => renderComponentList();
}
const renderComponentCard = (comp) => {
const placeholder = ui.componentList.querySelector('div[style*="text-align:center"]');
if (placeholder) placeholder.remove();
const card = document.createElement('div');
card.className = 'component-card';
card.innerHTML = `
<div class="component-card-preview">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="opacity:0.3"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path></svg>
</div>
<div class="component-card-name">${comp.name}</div>
<div class="component-card-meta">HTML Fragment • Cleaned</div>
`;
card.onclick = () => {
showToast('Entering Insertion Mode. Click anywhere in the preview to place this component.', 'info');
ui.preview.contentWindow.postMessage({ type: 'CMS_ENTER_INSERT_MODE', html: comp.html, name: comp.name }, '*');
};
ui.componentList.prepend(card);
};
// HISTORY RENDERER
const renderHistoryList = (count, entries) => {
if (count === 0) {
ui.historyList.innerHTML = '<div style="text-align:center; padding-top:40px; color:var(--text-muted); font-size:0.8rem;">No changes yet.</div>';
return;
}
const displayEntries = [...entries].reverse();
ui.historyList.innerHTML = displayEntries.map(entry => {
const oldVal = (entry.original || '').trim();
const newVal = (entry.updated || '').trim();
const isImage = newVal.match(/\.(jpg|jpeg|png|gif|webp|svg)/i) || (newVal.startsWith('http') && (oldVal.match(/\.(jpg|jpeg|png|gif|webp|svg)/i) || oldVal === ''));
const displayOld = oldVal.length > 50 ? oldVal.substring(0, 50) + '...' : oldVal;
const displayNew = newVal.length > 50 ? newVal.substring(0, 50) + '...' : newVal;
const label = entry.selector.startsWith('seo:') ? entry.selector.replace('seo:', 'SEO ').split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ') : entry.selector;
return `
<div class="history-item" onclick="${entry.selector.startsWith('seo:') ? '' : `highlightElement('${entry.selector}')`}">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
<span class="history-item-label" style="font-size:0.75rem; opacity:0.6; display:flex; align-items:center; gap:4px;">
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
${entry.time}
${entry.selector.startsWith('seo:') ? `• <span style="color:var(--primary); font-weight:700;">${label}</span>` : ''}
</span>
<button class="btn-undo" onclick="event.stopPropagation(); undoChange('${entry.selector}')">Revert</button>
</div>
<div class="history-item-diff">
${isImage ? `<img src="${newVal}" style="width:40px; height:40px; object-fit:cover;">` : `<div class="diff-old">${displayOld || '(Empty)'}</div><div class="diff-new">${displayNew || '(Empty)'}</div>`}
</div>
</div>`;
}).join('');
};
window.openDashboard = async () => {
if (!ui.dashboard) return;
// If engine is still pre-warming, show loader on the button
if (preWarmPromise) {
const btn = ui.btnToggleLanding;
if (btn && ui.prewarmLoader) {
ui.prewarmLoader.style.display = 'block';
btn.classList.add('loading');
try {
await preWarmPromise;
} finally {
ui.prewarmLoader.style.display = 'none';
btn.classList.remove('loading');
}
}
}
ui.dashboard.style.display = 'flex';
// UI Refs for new elements
if (ui.modeToggle) {
ui.modeToggle.onclick = () => {
const isText = ui.modeLabel.textContent.includes('Text');
const newMode = isText ? 'layout' : 'text';
ui.modeLabel.textContent = newMode === 'text' ? 'Text Mode' : 'Layout Mode';
ui.modeToggle.classList.toggle('active', newMode === 'text');
// Switch Icon
ui.modeIcon.innerHTML = newMode === 'text'
? '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>'
: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>';
ui.preview.contentWindow.postMessage({ type: 'CMS_MODE', mode: newMode }, '*');
};
}
// Check for demo mode and set layout
if (isDemoMode) {
ui.dashboard.classList.add('demo-active');
ui.dashboard.classList.remove('drawer-left-open');
} else {
ui.dashboard.classList.add('drawer-left-open');
}
// Slight delay to ensure display:flex is painted before adding .active for transition
requestAnimationFrame(() => {
ui.dashboard.classList.add('active');
});
// Safety: ensure demo mode is cleared if we are opening a real project
if (settings.repo && settings.token && isDemoMode) {
isDemoMode = false;
document.documentElement.classList.remove('demo-mode');
}
if (settings.repo && settings.token) {
if (ui.stepLogin) ui.stepLogin.classList.add('hidden');
if (ui.stepPicker) ui.stepPicker.classList.add('hidden');
await startCmsEngine(settings.repo, getActiveToken());
} else if (settings.token) {
if (ui.stepLogin) ui.stepLogin.classList.add('hidden');
if (ui.stepPicker) ui.stepPicker.classList.remove('hidden');
fetchRepos();
}
};
window.startDemoMode = async () => {
// Alias for the old 'startDemo' name used in inline HTML handlers
window.startDemo = window.startDemoMode;
isDemoMode = true;
document.documentElement.classList.add('demo-mode');
if (!ui.dashboard) return;
ui.dashboard.style.display = 'flex';
requestAnimationFrame(() => {
ui.dashboard.classList.add('active');
});
if (ui.stepLogin) ui.stepLogin.classList.add('hidden');
if (ui.stepPicker) ui.stepPicker.classList.add('hidden');
await startCmsEngine('Demo: 0CMS Landing Page', null, true);
};
safeBind(ui.btnToggleLanding, 'onclick', window.openDashboard);
safeBind(ui.navDemoBtn, 'onclick', () => window.startDemoMode());
safeBind(ui.btnClose, 'onclick', async () => {
ui.dashboard.classList.remove('active');
// RELIABLE SESSION MANAGEMENT: Shutdown engine on close
if (cmsService) {
await cmsService.shutdown();
}
setTimeout(() => {
ui.dashboard.style.display = 'none';
document.documentElement.classList.remove('demo-mode');
document.documentElement.classList.remove('demo-mode-child');
const mark = document.getElementById('demoCoachMark');
if (mark) mark.style.display = 'none';
isDemoMode = false;
cmsActive = false;
}, 500);
});
/**
* HARD RESET: Wipes all local state, caches, and reloads the page.
* Use when the CMS is in a broken state.
*/
window.hardReset = async () => {
if (!confirm('Hard Reset will clear all cached data and restart the CMS. Continue?')) return;
// 1. Kill running processes
if (cmsService) {
try { await cmsService.shutdown(); } catch(e) {}
}
// 2. Clear all localStorage keys related to ZCMS
Object.keys(localStorage).filter(k => k.startsWith('zcms')).forEach(k => localStorage.removeItem(k));
// 3. Clear all browser caches
if ('caches' in window) {
const names = await caches.keys();
await Promise.all(names.map(n => caches.delete(n)));
}
// 4. Unregister service workers
if ('serviceWorker' in navigator) {
const regs = await navigator.serviceWorker.getRegistrations();
await Promise.all(regs.map(r => r.unregister()));
}
// 5. Delete all IndexedDB databases (lightning-fs stores data here)
try {
const dbs = await indexedDB.databases();
await Promise.all(dbs.map(db => new Promise((res, rej) => {
const req = indexedDB.deleteDatabase(db.name);
req.onsuccess = res; req.onerror = rej;
})));
} catch(e) {}
// 6. Hard reload
window.location.href = window.location.origin + '/?reset=1';
};
safeBind(ui.loginBtn, 'onclick', () => window.location.href = '/github/login');
safeBind(ui.landingLoginBtn, 'onclick', () => window.location.href = '/github/login');
safeBind(ui.navNewPage, 'onclick', async () => {
const isVisible = ui.createPanel.style.display === 'flex';
if (isVisible) {
ui.createPanel.style.display = 'none';
ui.navNewPage.classList.remove('active');
return;
}
ui.pageSettingsPanel.style.display = 'none';
ui.navSEO.classList.remove('active');
ui.createPanel.style.display = 'flex';
ui.navNewPage.classList.add('active');
ui.createLoader.style.display = 'block';
ui.createList.innerHTML = '';
if (cmsService) {
const collections = await cmsService.scanCollections();
ui.createLoader.style.display = 'none';
if (collections.length === 0) {
ui.createList.innerHTML = '<div style="color:var(--text-muted); font-size:0.85rem;">No templates found.</div>';
return;
}
collections.forEach(col => {
const btn = document.createElement('button');
btn.className = 'btn-cms';
btn.style.width = '100%';
btn.style.justifyContent = 'flex-start';
btn.style.padding = '8px 12px';
// capitalize name
const name = col.name.charAt(0).toUpperCase() + col.name.slice(1);
btn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right:8px"><path d="M12 5v14m-7-7h14"/></svg> New ${name}`;
btn.onclick = async () => {
const title = prompt(`Enter title for new ${name}:`);
if (!title) return;
ui.createPanel.style.display = 'none';
showToast(`Creating ${title}...`, 'info');
try {
const newPath = await cmsService.createNewItem(col.path, title, col.templateFile);
showToast(`Created successfully!`, 'success');
setTimeout(() => {
let urlPath = newPath.replace('/src/pages', '').replace('/src/content', '').replace('/content', '').replace('/source', '').replace('.md', '').replace('.mdx', '').replace('.html', '').replace('.njk', '').replace('/index', '');
if (urlPath === '' || urlPath.startsWith('//')) urlPath = '/';
ui.preview.src = cmsService.serverUrl + urlPath;
}, 1800);
} catch (err) {
showToast('Error creating item', 'error');
}
};
ui.createList.appendChild(btn);
});
}
});
ui.pageSettingsPanel = document.getElementById('cmsPageSettingsPanel');
safeBind(ui.urlChipStatus, 'onclick', () => window.toggleHistory());
safeBind(ui.navSEO, 'onclick', () => {
const isVisible = ui.pageSettingsPanel.style.display === 'flex';
if (isVisible) {
ui.pageSettingsPanel.style.display = 'none';
ui.navSEO.classList.remove('active');
} else {
ui.pageSettingsPanel.style.display = 'flex';
ui.navSEO.classList.add('active');
ui.navNewPage.classList.remove('active');
ui.preview.contentWindow.postMessage({ type: 'CMS_GET_SEO' }, '*');
}
});
let lastSEOData = {};
const syncSEO = () => {
const data = {
title: ui.seoTitle.value,
description: ui.seoDesc.value,
image: ui.seoImage.value
};
if (JSON.stringify(data) === JSON.stringify(lastSEOData)) return;
lastSEOData = data;
ui.preview.contentWindow.postMessage({ type: 'CMS_SET_SEO', ...data }, '*');
};
safeBind(ui.seoTitle, 'onblur', syncSEO);
safeBind(ui.seoDesc, 'onblur', syncSEO);
safeBind(ui.seoImage, 'onblur', syncSEO);
// Window Event Listener for generic postMessages from iframe
window.addEventListener('message', (e) => {
if (e.data.type === 'CMS_SEO_DATA') {
ui.seoTitle.value = e.data.title || '';
ui.seoDesc.value = e.data.description || '';
ui.seoImage.value = e.data.image || '';
}
if (e.data.type === 'CMS_READY') {
// showToast('Visual Editor Ready', 'success'); // Redundant when spinner hides
if (ui.previewLoader) {
ui.previewLoader.style.opacity = '0';
setTimeout(() => {
ui.previewLoader.style.display = 'none';
ui.previewLoader.classList.add('hidden');
}, 500);
}
if (ui.statusLabel) {
ui.statusLabel.textContent = '0 unchanged changes';
ui.statusLabel.style.color = 'var(--text-muted)';
ui.statusLabel.style.opacity = '0.7';
}
const statusIcon = document.getElementById('cmsStatusIcon');
if (statusIcon) statusIcon.style.stroke = 'var(--text-muted)';
// FORCE ENABLE BRIDGE
ui.preview.contentWindow.postMessage({ type: 'CMS_TOGGLE', enabled: true }, '*');
// SILENT RESTORE: If we have persisted changes, send them to the bridge
if (cmsService && cmsService.repoUrl) {
const saved = localStorage.getItem(`zcms-session-${cmsService.repoUrl}`);
if (saved) {
try {
const data = JSON.parse(saved);
if (data.changes && Object.keys(data.changes).length > 0) {
console.log(`[0CMS] Silently restoring ${Object.keys(data.changes).length} unsaved changes...`);
ui.preview.contentWindow.postMessage({
type: 'CMS_RESTORE_CHANGES',
changes: data.changes,
entries: data.entries
}, '*');
}
} catch (e) {}
}
}
}
if (e.data.type === 'CMS_CHANGED') {
const count = Object.keys(e.data.changes).length;
changes = e.data.changes;
entries = e.data.entries || []; // Update global, no shadowing
if (ui.historyCount) ui.historyCount.textContent = count;
if (ui.statusLabel) {
ui.statusLabel.textContent = `${count} unchanged change${count !== 1 ? 's' : ''}`;
ui.statusLabel.style.color = count > 0 ? 'var(--primary)' : 'var(--text-muted)';
}
// SILENT SYNC: Trigger background persistence to virtual disk
if (cmsService && e.data.changes) {
cmsService.syncChangesToDisk(e.data.changes);
}
// REAL-TIME SYNC: Apply the last change to the WebContainer FS
if (entries.length > 0 && cmsService) {
const lastEntry = entries[entries.length - 1];
if (lastEntry.original && lastEntry.updated && lastEntry.original !== lastEntry.updated) {
// Enhanced Deterministic Editing
const metadata = (activeSourceMetadata && activeSourceMetadata.selector === lastEntry.selector)
? activeSourceMetadata
: null;
cmsService.applySmartMatchChange(
lastEntry.original,
lastEntry.updated,
metadata
).then(async (result) => {
if (result && result.path && result.content) {
if (cmsService && cmsService.repoUrl) {
const persistData = {
url: cmsService.repoUrl,
changes: changes,
entries: entries,
timestamp: Date.now()
};
localStorage.setItem(`zcms-session-${cmsService.repoUrl}`, JSON.stringify(persistData));
}
WasmBridge.getInstance().syncFile(result.path, result.content);
const currentUrl = ui.preview.src;
IframeSyncService.getInstance().sync(ui.preview, currentUrl, result.markerId);
}
}).catch(err => console.error('[CMS] Autosync failed:', err));
}
}
if (e.data.canUndo) ui.navBack.classList.remove('disabled');
else ui.navBack.classList.add('disabled');
if (e.data.canRedo) ui.navForward.classList.remove('disabled');
else ui.navForward.classList.add('disabled');
if (ui.historyList) {
if (count === 0) {
ui.historyList.innerHTML = '<div style="text-align:center; padding-top:40px; color:var(--text-muted); font-size:0.8rem;">No changes yet.</div>';
} else {
const displayEntries = [...entries].reverse();
ui.historyList.innerHTML = displayEntries.map(entry => {
const oldVal = (entry.original || '').trim();
const newVal = (entry.updated || '').trim();
const isImage = newVal.match(/\.(jpg|jpeg|png|gif|webp|svg)/i) || (newVal.startsWith('http') && (oldVal.match(/\.(jpg|jpeg|png|gif|webp|svg)/i) || oldVal === ''));
const displayOld = oldVal.length > 50 ? oldVal.substring(0, 50) + '...' : oldVal;
const displayNew = newVal.length > 50 ? newVal.substring(0, 50) + '...' : newVal;
const isSEO = entry.selector.startsWith('seo:');
let label = entry.selector;
if (isSEO) {
label = entry.selector.replace('seo:', 'SEO ').split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
}
return `
<div class="history-item" onclick="${isSEO ? '' : `highlightElement('${entry.selector}')`}">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
<span class="history-item-label" style="font-size:0.75rem; opacity:0.6; display:flex; align-items:center; gap:4px;">
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
${entry.time}
${isSEO ? `• <span style="color:var(--primary); font-weight:700;">${label}</span>` : ''}
</span>
<button class="btn-undo" onclick="event.stopPropagation(); undoChange('${entry.selector}')">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M3 10h10a8 8 0 018 8v2M3 10l6-6M3 10l6 6"/></svg>
Revert
</button>
</div>
<div class="history-item-diff">
${isImage ? `
<div style="display:flex; align-items:center; gap:12px;">
<div style="width:40px; height:40px; border-radius:4px; overflow:hidden; border:1px solid var(--border); background:#eee;">
<img src="${oldVal}" style="width:100%; height:100%; object-fit:cover; opacity:0.5;">
</div>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
<div style="width:40px; height:40px; border-radius:4px; overflow:hidden; border:1px solid var(--primary); background:#fff;">
<img src="${newVal}" style="width:100%; height:100%; object-fit:cover;">
</div>
</div>
` : `
<div class="diff-old">${displayOld || '(Empty)'}</div>
<div style="font-size:0.6rem; opacity:0.5; margin: -2px 0; font-weight:700;">TO ➜</div>
<div class="diff-new">${displayNew || '(Empty)'}</div>
`}
</div>
<div class="history-item-selector" title="${entry.selector}">${isSEO ? 'Metadata Optimization' : entry.selector}</div>
</div>
`;}).join('');
}
}
}
});
// Responsive Preview Viewport Controls
const updateViewport = (view) => {
ui.viewDesktop.classList.remove('active');
ui.viewTablet.classList.remove('active');
ui.viewMobile.classList.remove('active');
ui.preview.className = '';
if (view === 'desktop') {
ui.viewDesktop.classList.add('active');
} else if (view === 'tablet') {
ui.viewTablet.classList.add('active');
ui.preview.classList.add('view-tablet');
} else if (view === 'mobile') {
ui.viewMobile.classList.add('active');
ui.preview.classList.add('view-mobile');
}
};
safeBind(ui.viewDesktop, 'onclick', () => updateViewport('desktop'));
safeBind(ui.viewTablet, 'onclick', () => updateViewport('tablet'));
safeBind(ui.viewMobile, 'onclick', () => updateViewport('mobile'));
// CMS Initialization Logic
async function startCmsEngine(repo, token, demo = false) {
if (cmsActive && !demo) return;
cmsActive = true;
isDemoMode = !!demo;
ui.repoDisplay.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="position:relative;top:2px;margin-right:4px;"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path><circle cx="12" cy="10" r="3"></circle></svg> ${repo}`;
if (isDemoMode) {
ui.statusLabel.textContent = '0 Changes Unsaved';
ui.previewLoader.classList.add('hidden');
// STABILITY DELAY: Wait 300ms before hitting the same origin again for the iframe.
// This prevents 'Connection Refused' during heavy cold-boots (cache clear).
setTimeout(() => {
ui.preview.src = window.location.origin + '/?demo=true';
ui.preview.onload = () => {
ui.preview.contentWindow.postMessage({
type: 'CMS_CONFIG',
proxyUrl: `${window.location.origin}/proxy?url=`
}, '*');
ui.preview.contentWindow.postMessage({ type: 'CMS_TOGGLE', enabled: true }, '*');
};
}, 300);
return;
}
if (!preWarmingService) {
preWarmingService = new WebContainerGitService();
}
cmsService = preWarmingService;
let bootLogBuffer = '';
cmsService.onLog = (msg) => {
bootLogBuffer += (msg + '\n');
if (ui.terminal) {
ui.terminal.textContent = bootLogBuffer;