-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitqi.js
More file actions
8613 lines (7727 loc) · 368 KB
/
gitqi.js
File metadata and controls
8613 lines (7727 loc) · 368 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
/**
* gitqi.js — v1.1.0
* Zero-dependency browser-based site editor.
* Always activates; features degrade based on which secrets are present:
* - With geminiKey: AI-driven Reformat / Add Section / Add Page.
* - With githubToken + repo: one-click Publish + asset uploads to GitHub.
* - With neither (offline): in-place edits, sections, sync, Duplicate Page,
* Export. Folder access is still required.
* Stripped from exported/published HTML automatically.
*/
(function () {
'use strict';
const VERSION = '1.1.0';
// SITE_SECRETS is optional. When absent or partial, the editor runs in
// degraded mode: features that require remote services are hidden, but
// local editing (text, images via folder access, sections, sync) still works.
// - githubToken + repo present → Publish enabled, image uploads pushed to GitHub
// - geminiKey present → AI features enabled (Reformat, Add Section, Add Page)
// - neither present → "offline" mode: Export + folder-based editing only
const SITE_SECRETS = window.SITE_SECRETS || {};
// Base URL of this script on disk / CDN — used to locate sibling assets like
// google-fonts.json. Captured here while document.currentScript is still valid
// (it becomes null after the synchronous IIFE returns).
const SCRIPT_SRC = (document.currentScript && document.currentScript.src) || '';
const SCRIPT_BASE_URL = SCRIPT_SRC.substring(0, SCRIPT_SRC.lastIndexOf('/') + 1);
// ─── Theme ────────────────────────────────────────────────────────────────
// Mirrors the gitqi.com site palette + typography so the editor UI
// feels stylistically consistent with the marketing site. These values are
// used only inside editor UI elements (toolbar, modals, panels) — they are
// never injected into the user's <head>, so the shared-head sync is unaffected.
const T = {
primary: '#1a1b3a', // deep navy — toolbar bg, headings, active states
secondary: '#d946ef', // magenta — reformat accent
accent: '#ff8c3c', // orange — primary CTA (Publish, Submit)
accent2: '#2dd4bf', // teal — link/info accent
accent3: '#fde047', // yellow — highlights
accent4: '#f472b6', // pink
bg: '#fdfbf5', // cream — modal / panel bg
bgAlt: '#f3ede0', // warm cream — inputs, subtle surfaces
text: '#1a1b3a',
textMuted: '#5a5d7a',
border: 'rgba(26, 27, 58, 0.12)',
borderSoft:'rgba(26, 27, 58, 0.07)',
danger: '#e04a4a',
success: '#10b981',
fontHead: "'Fraunces', 'Playfair Display', Georgia, serif",
fontBody: "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif",
fontMono: "'JetBrains Mono', 'SF Mono', Menlo, Consolas, monospace",
radius: '14px',
radiusSm: '8px',
radiusPill:'999px',
shadow: '0 20px 48px -16px rgba(26, 27, 58, 0.28)',
shadowSm: '0 6px 18px -8px rgba(26, 27, 58, 0.25)',
shadowCta: '0 14px 32px -12px rgba(255, 140, 60, 0.55)',
};
const { geminiKey, githubToken, repo, branch = 'main' } = SITE_SECRETS;
// Capability flags — checked throughout to gate features that depend on
// remote services. Computed once at load and read freely; SITE_SECRETS is
// not expected to change during a session.
const hasGitHub = !!(githubToken && repo);
const hasGemini = !!geminiKey;
// ─── State ────────────────────────────────────────────────────────────────
let isDirty = false;
let mutationObserver = null;
let statusTimer = null;
let originalBodyPaddingTop = '';
let originalNavTop = null; // set when a fixed nav is shifted down for the toolbar
let autoSaveTimer = null;
let dirHandle = null; // FileSystemDirectoryHandle when folder access is granted
let pagesInventory = null; // { pages: [{ file, title, navLabel }] } — loaded from gitqi-pages.json
let lastSyncedSharedSnapshot = ''; // JSON snapshot of shared head + nav after last sync; change detection for auto-save
const UNDO_LIMIT = 20;
let undoStack = [];
let redoStack = [];
// GitQi requires the File System Access API. Only Chromium-based browsers
// (Chrome, Edge) are supported. Safari and Firefox are not supported.
if (!('showDirectoryPicker' in window)) {
const msg = document.createElement('div');
Object.assign(msg.style, {
position: 'fixed', inset: '0', zIndex: '9999999',
display: 'flex', alignItems: 'center', justifyContent: 'center',
background: 'rgba(26, 27, 58, 0.85)', fontFamily: T.fontBody,
padding: '20px', boxSizing: 'border-box',
});
msg.innerHTML = `
<div style="background:${T.bg};border-radius:${T.radius};padding:34px 38px;max-width:440px;text-align:center;box-shadow:${T.shadow};font-family:${T.fontBody};">
<div style="font-size:36px;margin-bottom:14px;">🌐</div>
<h2 style="margin:0 0 10px;font-size:22px;color:${T.primary};font-family:${T.fontHead};font-weight:600;letter-spacing:-0.02em;">Unsupported Browser</h2>
<p style="margin:0;font-size:14px;color:${T.textMuted};line-height:1.6;">
GitQi requires access to the local file system and works in
<strong style="color:${T.primary}">Chrome</strong> and <strong style="color:${T.primary}">Edge</strong>.<br><br>
Please open this page in Chrome or Edge to use the editor.
</p>
</div>`;
document.body.appendChild(msg);
return;
}
// Derive the current page's filename from the URL (e.g. "about.html", "index.html")
const CURRENT_FILENAME = (location.pathname.split('/').pop()) || 'index.html';
// Key the stored folder handle by site directory so all pages in the same folder
// share one handle — previously keyed by pathname which differed per page.
const _siteDir = location.href.substring(0, location.href.lastIndexOf('/') + 1);
const HANDLE_KEY = 'dir:' + _siteDir;
// ─── Toolbar ──────────────────────────────────────────────────────────────
function makeIconButton(text, titleAttr) {
const btn = el('button', { 'data-editor-ui': '' });
btn.textContent = text;
btn.title = titleAttr;
css(btn, {
width: '26px', height: '26px', padding: '0',
marginLeft: '4px',
border: '1.5px solid rgba(253, 251, 245, 0.4)',
borderRadius: '50%',
background: 'transparent',
color: T.bg,
cursor: 'pointer',
fontSize: '13px',
fontWeight: '600',
fontFamily: T.fontBody,
lineHeight: '1',
transition: 'background 0.18s ease, border-color 0.18s ease',
});
btn.addEventListener('mouseenter', () => {
btn.style.background = 'rgba(253, 251, 245, 0.15)';
btn.style.borderColor = T.accent3;
});
btn.addEventListener('mouseleave', () => {
btn.style.background = 'transparent';
btn.style.borderColor = 'rgba(253, 251, 245, 0.4)';
});
return btn;
}
function injectToolbar() {
const bar = el('div', {
id: '__gitqi-toolbar',
'data-editor-ui': '',
});
css(bar, {
position: 'fixed',
top: '0',
left: '0',
right: '0',
zIndex: '999999',
display: 'flex',
alignItems: 'center',
gap: '6px',
padding: '0 18px',
height: '44px',
background: T.primary,
color: T.bg,
fontFamily: T.fontBody,
fontSize: '13px',
boxShadow: '0 8px 24px -10px rgba(26, 27, 58, 0.35)',
boxSizing: 'border-box',
borderBottom: '1px solid rgba(255, 255, 255, 0.08)',
});
// Calligraphic 气 mark on a gradient pill — echoes the site nav logo
const logo = el('span', { 'data-editor-ui': '' });
logo.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640" width="18" height="18" aria-hidden="true"><g transform="translate(0 -412.36)"><path fill="#fff" stroke="#fff" stroke-width="20" stroke-linejoin="round" stroke-linecap="round" paint-order="stroke" d="m394.1 866.46q0-15-3.6-39-5.4-29.4-6-38.4v-7.2q0-11.4-7.2-14.4h-34.8q-7.8 3.6-18 3.6h-12q-9 0-18 2.4-8.4 3-13.2 3-8.4 0-14.4-1.8-15 3.6-45 7.2-29.4 3.6-45 7.2l-5.4 1.8q-4.2 1.8-5.4 1.8-4.8 0-11.4 2.4-6 3-8.4 3-12.6-4.2-12.6-3.6 0-20.4-5.4-25.2l-6-4.2q-3.6-2.4-6.6-6.6 1.8-5.4 12.6-5.4-0.6 1.8 10.8 1.8 15 0 40.8-1.8t40.2-1.8l9 1.8h52.2q7.2-3.6 24-3.6h18l7.2-1.8 8.4 1.8q33.6 0 47.4-4.8 15.6-5.4 25.8-22.8 19.2-19.2 26.4-19.2 3 0 14.4 8.4 27.6 27.6 27.6 25.8-5.4 17.4-6 18-10.2 10.2-18 12.6l-15.6 34.2v64.8q0 1.2 2.4 7.2l2.4 7.2q0 9 57.6 52.8 25.8 19.2 45.6 19.2 16.2 0 27-31.2 7.2-21.6 7.2-31.2 22.2-52.8 20.4-52.8 4.8 0 4.8 5.4 0 4.2-3 9-3.6 6-4.2 9 0.6 4.8-2.4 13.8t-3 13.2q1.2 4.8-1.2 14.4l-2.4 13.2q0 2.4 1.8 16.8t1.8 16.8q0 9 6.6 22.8 6 13.2 6 19.2 0 28.8-27 28.8-25.2 0-70.8-20.4-3.6-1.8-11.4-4.2t-11.4-4.2q-27-14.4-49.2-34.8-0.6-1.2-9.6-7.2-8.4-5.4-8.4-8.4l-4.8-14.4q-19.2-48.6-21.6-60zm-166.8-388.2q0-4.2-2.4-12.6-3-8.4-3-13.8 0-6 3.6-6 34.2 0 48.6 14.4 27.6 27.6 27.6 32.4 0 12-10.8 21.6-36 36-36 38.4 0 7.2 10.8 7.2 9.6-0.6 27.6-3.6 18.6-3 27.6-3.6 19.2 0.6 39.6-3.6 21-3.6 27.6-3.6-6 1.2 34.8-3 29.4-3 50.4-13.8 2.4-1.2 12.6-14.4 8.4-10.8 17.4-10.8 3.6 0 14.4 13.2 34.8 25.8 34.8 48 0 2.4-6 9-6.6 6-8.4 5.4h-56.4l-15.6-3.6q-8.4 4.2-7.2 2.4-2.4 0-11.4-1.8l-9-1.8-4.8 1.2q-9.6 0-20.4-1.8l-10.8-1.8-4.8 2.4-49.8-0.6q-54.6 0-93 11.4-1.2 0-6 1.8l-5.4 1.8q-31.2 10.2-30.6 9.6-2.4 4.2-9 10.2-4.8 4.8-5.4 7.8-7.8 1.2-21.6 25.2-12 10.2-28.8 28.2l-21.6 23.4q-5.4 9.6-52.2 56.4-2.4 0.6-10.2 7.8-7.8 6.6-11.4 6.6-2.4 0-9 6-6 6.6-12.6 6.6-0.6-4.8 21.6-21.6-1.2 0.6 15.6-18 17.4-16.8 27.6-33 0.6-1.8 7.2-10.8l36-51.6q2.4-4.2 8.4-10.8 6-6 7.8-9.6 12.6-28.8 25.2-42 2.4-3.6 28.8-54 0-5.4 9-21 9-15 9-25.8zm-39.6 175.2q0-3.6 1.8-3.6h76.2q54 0 54-4.8l6.6-0.6q6.6-0.6 9 1.8 66.6 1.2 96-8.4 4.8-1.8 18.6-12 11.4-8.4 17.4-8.4 13.2 0 24 7.2 1.2 1.8 9 9 6.6 5.4 12.6 19.8 0 13.2-13.2 24-19.2 0-69-5.4-50.4-4.8-81-4.8l-26.4 0.6-6-4.8q0 3.6-30 10.8-3 0-31.8 3.6-29.4 3.6-31.8 3.6-16.2 0.6-19.2-4.2l-2.4-6.6q-1.8-5.4-5.4-9.6-1.8 0-5.4-3.6-3-3.6-3.6-3.6zm290.4 20.4q-1.2 0-1.2 1.8t1.2 1.8 1.2-1.8-1.2-1.8zm-165.6-102q-1.2 0-1.2 2.4 0 1.2 1.2 1.2 0.6 0 0.6-1.2 0-2.4-0.6-2.4z"/></g></svg>';
css(logo, {
width: '26px', height: '26px',
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
borderRadius: '8px',
background: `linear-gradient(135deg, ${T.accent} 0%, ${T.secondary} 55%, ${T.accent2} 100%)`,
boxShadow: '0 6px 14px -6px rgba(217, 70, 239, 0.6)',
marginRight: '4px',
flexShrink: '0',
});
const title = el('span', { id: '__gitqi-title' });
title.textContent = document.title || 'Site Editor';
css(title, {
fontFamily: T.fontHead,
fontWeight: '500',
fontSize: '15px',
letterSpacing: '-0.01em',
color: T.bg,
});
const status = el('span', { id: '__gitqi-status' });
css(status, {
fontSize: '11.5px',
opacity: '0.7',
marginLeft: '6px',
letterSpacing: '0.01em',
fontStyle: 'italic',
});
const spacer = el('div');
css(spacer, { flex: '1' });
const undoBtn = toolbarBtn('↩');
undoBtn.id = '__gitqi-undo-btn';
undoBtn.title = 'Undo (Ctrl+Z)';
undoBtn.disabled = true;
undoBtn.style.opacity = '0.35';
const redoBtn = toolbarBtn('↪');
redoBtn.id = '__gitqi-redo-btn';
redoBtn.title = 'Redo (Ctrl+Shift+Z)';
redoBtn.disabled = true;
redoBtn.style.opacity = '0.35';
undoBtn.addEventListener('click', undo);
redoBtn.addEventListener('click', redo);
const syncBtn = toolbarBtn('⟲');
syncBtn.title = 'Sync nav + footer + theme to all other pages';
syncBtn.addEventListener('click', manualSync);
const pagesBtn = toolbarBtn('Pages');
const themeBtn = toolbarBtn('Theme');
const exportBtn = toolbarBtn('Export', !hasGitHub); // Export becomes the CTA when Publish is hidden
const publishBtn = hasGitHub ? toolbarBtn('Publish', true) : null;
pagesBtn.addEventListener('click', openPagesPanel);
themeBtn.addEventListener('click', openThemeEditor);
exportBtn.addEventListener('click', exportToFile);
if (publishBtn) publishBtn.addEventListener('click', publishSite);
// Site-wide utilities. Houses one-time operations (folder relink, page
// init, asset cleanup) so the routine panels stay focused on the
// day-to-day edits.
const gearBtn = makeIconButton('⚙', 'Site utilities');
gearBtn.addEventListener('click', openGearPanel);
// Help "?" icon: a small circular button always present at the right edge.
// Opens a side panel describing capabilities + degraded-mode notice.
const helpBtn = makeIconButton('?', 'GitQi help & capabilities');
helpBtn.addEventListener('click', openHelpPanel);
const toolbarChildren = [logo, title, spacer, status, undoBtn, redoBtn, syncBtn, pagesBtn, themeBtn, exportBtn];
if (publishBtn) toolbarChildren.push(publishBtn);
toolbarChildren.push(gearBtn, helpBtn);
bar.append(...toolbarChildren);
document.body.prepend(bar);
// Push body content down so toolbar doesn't overlap
originalBodyPaddingTop = document.body.style.paddingTop || '';
const current = parseFloat(getComputedStyle(document.body).paddingTop) || 0;
document.body.style.paddingTop = (current + 44) + 'px';
// If the page has a fixed nav, shift it down so the toolbar doesn't overlap it
const nav = document.querySelector('nav');
if (nav && getComputedStyle(nav).position === 'fixed') {
originalNavTop = nav.style.top || '';
const navTop = parseFloat(getComputedStyle(nav).top) || 0;
nav.style.top = (navTop + 44) + 'px';
}
}
function toolbarBtn(label, primary = false) {
const btn = el('button', { 'data-editor-ui': '' });
btn.textContent = label;
css(btn, {
padding: '6px 15px',
border: primary ? '2px solid transparent' : '1.5px solid rgba(253, 251, 245, 0.22)',
borderRadius: T.radiusPill,
background: primary ? T.accent : 'transparent',
color: primary ? T.primary : T.bg,
cursor: 'pointer',
fontSize: '12.5px',
fontFamily: T.fontBody,
fontWeight: primary ? '600' : '500',
letterSpacing: '-0.005em',
lineHeight: '1',
boxShadow: primary ? T.shadowCta : 'none',
transition: 'background 0.18s ease, color 0.18s ease, border-color 0.18s ease, transform 0.18s ease',
});
btn.addEventListener('mouseenter', () => {
if (primary) {
btn.style.background = T.accent2;
btn.style.transform = 'translateY(-1px)';
} else {
btn.style.background = 'rgba(253, 251, 245, 0.12)';
btn.style.borderColor = 'rgba(253, 251, 245, 0.4)';
}
});
btn.addEventListener('mouseleave', () => {
if (primary) {
btn.style.background = T.accent;
btn.style.transform = 'translateY(0)';
} else {
btn.style.background = 'transparent';
btn.style.borderColor = 'rgba(253, 251, 245, 0.22)';
}
});
return btn;
}
function showStatus(msg, isError = false) {
const statusEl = document.getElementById('__gitqi-status');
if (!statusEl) return;
statusEl.textContent = msg;
statusEl.style.color = isError ? T.accent4 : T.accent3;
statusEl.style.opacity = '1';
clearTimeout(statusTimer);
if (!isError) {
statusTimer = setTimeout(() => {
statusEl.textContent = '';
statusEl.style.opacity = '0.7';
}, 4000);
}
}
function setDirty(val) {
isDirty = val;
const titleEl = document.getElementById('__gitqi-title');
if (titleEl) titleEl.textContent = (val ? '● ' : '') + (document.title || 'Site Editor');
if (val) scheduleAutoSave();
}
// ─── File persistence ─────────────────────────────────────────────────────
//
// File System Access API (Chrome, Edge):
// - User selects their site folder once; handle is stored in IndexedDB.
// - Auto-save writes the current page to disk; images are saved to assets/.
// - On reload the file on disk is always current — nothing to restore.
function scheduleAutoSave() {
clearTimeout(autoSaveTimer);
autoSaveTimer = setTimeout(saveChanges, 1500);
}
async function saveChanges() {
// Drop <link>s for fonts that are no longer referenced before we persist or sync.
// Running it here (rather than per-font-change) also cleans up state that predates
// the prune logic, on the first save after upgrade.
pruneUnusedGoogleFontLinks();
if (dirHandle) {
await writeCurrentPageToLocalFile();
const result = await syncSharedToOtherPagesIfChanged();
// Auto-sync: stay quiet when nothing changed, but announce real propagation
// so the user can tell when nav/footer edits reached the other pages.
if (result && !result.skipped && result.syncedCount > 0) {
const n = result.syncedCount;
showStatus(`Synced shared elements to ${n} other page${n === 1 ? '' : 's'} ✓`);
}
}
// No dirHandle yet — changes accumulate in the DOM until the folder is linked.
}
// Manual sync trigger (toolbar ⟲ button). Forces a sync even when nothing
// looks changed — useful after hand-editing the HTML outside the editor, or
// when the user wants to confirm propagation. Always shows a status message.
async function manualSync() {
if (!dirHandle) {
showStatus('Link your site folder before syncing', true);
return;
}
if (!pagesInventory || pagesInventory.pages.length <= 1) {
showStatus('Nothing to sync — only one page', false);
return;
}
// Reset the baseline so the change-detection guard doesn't short-circuit a
// manual request. This matches the pattern used by reformatNav / addPage.
lastSyncedSharedSnapshot = '';
showStatus('Syncing…');
const result = await syncSharedToOtherPagesIfChanged();
if (!result || result.skipped) {
showStatus('Sync skipped', true);
return;
}
const n = result.syncedCount;
if (result.failedFiles && result.failedFiles.length) {
showStatus(`Synced ${n} page${n === 1 ? '' : 's'}; ${result.failedFiles.length} failed: ${result.failedFiles.join(', ')}`, true);
} else {
showStatus(`Synced shared elements to ${n} other page${n === 1 ? '' : 's'} ✓`);
}
}
// ── File System Access path ──────────────────────────────────────────────
async function writeCurrentPageToLocalFile() {
try {
const fh = await dirHandle.getFileHandle(CURRENT_FILENAME, { create: true });
const writable = await fh.createWritable();
await writable.write(serialize({ local: true }));
await writable.close();
} catch (e) {
// Lost access (e.g. folder moved) — drop handle and prompt re-link
dirHandle = null;
showAccessBanner();
}
}
// Write any page file (used when creating new pages or syncing other pages)
async function writePageToLocalFile(filename, content) {
if (!dirHandle) return;
try {
const fh = await dirHandle.getFileHandle(filename, { create: true });
const writable = await fh.createWritable();
await writable.write(content);
await writable.close();
} catch (_) {}
}
async function writeImageToLocalDir(file) {
if (!dirHandle) return;
try {
const assetsDir = await dirHandle.getDirectoryHandle('assets', { create: true });
const fh = await assetsDir.getFileHandle(file.name, { create: true });
const writable = await fh.createWritable();
await writable.write(file);
await writable.close();
} catch (e) {
// Non-fatal — image is still on GitHub even if local write fails
}
}
// IndexedDB — persists FileSystemDirectoryHandle across sessions
function openHandleDB() {
return new Promise((resolve, reject) => {
const req = indexedDB.open('__gitqi_fs', 1);
req.onupgradeneeded = e => e.target.result.createObjectStore('handles');
req.onsuccess = e => resolve(e.target.result);
req.onerror = () => reject(req.error);
});
}
async function storeHandleInDB(handle) {
const db = await openHandleDB();
return new Promise((resolve, reject) => {
const tx = db.transaction('handles', 'readwrite');
tx.objectStore('handles').put(handle, HANDLE_KEY);
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
}
async function loadHandleFromDB() {
const db = await openHandleDB();
return new Promise((resolve, reject) => {
const tx = db.transaction('handles', 'readonly');
const req = tx.objectStore('handles').get(HANDLE_KEY);
req.onsuccess = () => resolve(req.result || null);
req.onerror = () => reject(req.error);
});
}
async function verifyPermission(handle) {
const opts = { mode: 'readwrite' };
if (await handle.queryPermission(opts) === 'granted') return true;
if (await handle.requestPermission(opts) === 'granted') return true;
return false;
}
// Called at init — silently restores folder access or shows the link banner
async function initFileAccess() {
try {
const stored = await loadHandleFromDB();
if (stored && await verifyPermission(stored)) {
dirHandle = stored;
await loadPagesInventory(); // load or seed the pages manifest
return; // Silent success — folder is linked, auto-save is active
}
} catch (_) {}
showAccessBanner();
}
// Blocking modal — the editor cannot save without a linked, writable folder,
// so the overlay covers the page and has no dismiss button. It only closes
// once showDirectoryPicker returns a handle with readwrite permission granted.
function showAccessBanner() {
if (document.getElementById('__gitqi-access-banner')) return;
const overlay = el('div', { id: '__gitqi-access-banner', 'data-editor-ui': '' });
css(overlay, {
position: 'fixed',
inset: '0',
zIndex: '9999999',
background: 'rgba(26, 27, 58, 0.88)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontFamily: T.fontBody,
padding: '20px',
boxSizing: 'border-box',
});
const hintPath = location.protocol === 'file:'
? decodeURIComponent(location.pathname.substring(0, location.pathname.lastIndexOf('/')))
: null;
const hintHtml = hintPath
? `<div style="margin-top:16px;background:${T.bgAlt};padding:10px 14px;border-radius:${T.radiusSm};font-family:${T.fontMono};font-size:12px;color:${T.primary};word-break:break-all;border:1px solid ${T.borderSoft};">${hintPath}</div>`
: '';
const modal = el('div');
css(modal, {
background: T.bg,
borderRadius: T.radius,
padding: '36px 38px',
maxWidth: '480px',
width: '100%',
textAlign: 'center',
boxShadow: T.shadow,
boxSizing: 'border-box',
fontFamily: T.fontBody,
position: 'relative',
overflow: 'hidden',
});
modal.innerHTML = `
<div style="position:absolute;top:0;left:0;right:0;height:5px;background:linear-gradient(90deg, ${T.accent}, ${T.secondary} 50%, ${T.accent2});"></div>
<div style="font-size:38px;margin-bottom:14px;">💾</div>
<h2 style="margin:0 0 10px;font-size:22px;color:${T.primary};font-family:${T.fontHead};font-weight:600;letter-spacing:-0.02em;line-height:1.15;">Folder access required</h2>
<p style="margin:0;font-size:14px;color:${T.textMuted};line-height:1.6;">
GitQi needs write access to your site folder so edits save directly to your files.
Without this permission, the editor cannot save your changes.
</p>
${hintHtml}
<button id="__gitqi-banner-grant"
style="margin-top:22px;background:${T.accent};color:${T.primary};border:2px solid transparent;font-weight:600;padding:11px 26px;border-radius:${T.radiusPill};cursor:pointer;font-size:14px;font-family:${T.fontBody};box-shadow:${T.shadowCta};letter-spacing:-0.005em;transition:transform 0.2s ease, background 0.2s ease;">
Select Folder
</button>
<div id="__gitqi-banner-error" style="margin-top:14px;font-size:12.5px;color:${T.danger};min-height:16px;"></div>
`;
const grantBtn = modal.querySelector('#__gitqi-banner-grant');
grantBtn.addEventListener('mouseenter', () => { grantBtn.style.background = T.accent2; grantBtn.style.transform = 'translateY(-2px)'; });
grantBtn.addEventListener('mouseleave', () => { grantBtn.style.background = T.accent; grantBtn.style.transform = 'translateY(0)'; });
overlay.appendChild(modal);
document.body.appendChild(overlay);
const errEl = modal.querySelector('#__gitqi-banner-error');
modal.querySelector('#__gitqi-banner-grant').addEventListener('click', async () => {
errEl.textContent = '';
try {
const handle = await window.showDirectoryPicker({ mode: 'readwrite', startIn: 'documents' });
// Confirm the handle is actually writable before clearing the overlay
if (!(await verifyPermission(handle))) {
errEl.textContent = 'Write permission was not granted. Please try again.';
return;
}
dirHandle = handle;
await storeHandleInDB(handle);
overlay.remove();
await writeCurrentPageToLocalFile();
await loadPagesInventory();
lastSyncedSharedSnapshot = getSharedSnapshot();
showStatus('Folder linked ✓ — edits now save to your files automatically');
} catch (e) {
if (e.name !== 'AbortError') errEl.textContent = e.message || 'Could not access folder';
}
});
}
// ─── Pages Inventory ──────────────────────────────────────────────────────
//
// gitqi-pages.json tracks all pages managed by the editor.
// It lives alongside the HTML files in the site folder and is pushed to GitHub on publish.
// Structure: { "pages": [{ "file": "index.html", "title": "Home", "navLabel": "Home" }] }
async function loadPagesInventory() {
if (!dirHandle) {
// No folder access — seed a minimal in-memory inventory for the current page
pagesInventory = { pages: [{ file: CURRENT_FILENAME, title: document.title || CURRENT_FILENAME, navLabel: document.title || CURRENT_FILENAME }] };
return;
}
try {
const fh = await dirHandle.getFileHandle('gitqi-pages.json');
const inventoryFile = await fh.getFile();
pagesInventory = JSON.parse(await inventoryFile.text());
// Ensure the current page is registered
if (!pagesInventory.pages.find(p => p.file === CURRENT_FILENAME)) {
pagesInventory.pages.push({ file: CURRENT_FILENAME, title: document.title || CURRENT_FILENAME, navLabel: document.title || CURRENT_FILENAME });
await savePagesInventory();
}
} catch (_) {
// No inventory on disk — seed from the current page and write it
pagesInventory = { pages: [{ file: CURRENT_FILENAME, title: document.title || CURRENT_FILENAME, navLabel: document.title || CURRENT_FILENAME }] };
await savePagesInventory();
}
}
async function savePagesInventory() {
if (!dirHandle || !pagesInventory) return;
try {
const fh = await dirHandle.getFileHandle('gitqi-pages.json', { create: true });
const writable = await fh.createWritable();
await writable.write(JSON.stringify(pagesInventory, null, 2));
await writable.close();
} catch (_) {}
}
// ─── Shared Head + Nav Sync ───────────────────────────────────────────────
//
// On every auto-save we snapshot the current page's shared head elements plus
// the nav, and compare against the last synced version. If anything changed,
// we push the updated shared elements into every other local page file.
//
// Synced: <nav>, <footer> (or [data-zone="footer"]), main <style> (CSS
// variables + base styles), <style id="__gitqi-nav-styles">, the footer's
// <style id="__gitqi-section-{footerSlug}-styles"> block, <link rel="icon">,
// <link rel="apple-touch-icon">, Google Fonts <link>s and their preconnects.
// NOT synced: <title>, <meta name="description">, <meta name="keywords"> —
// these are intentionally page-specific.
function getNavHTML() {
const nav = document.querySelector('nav');
if (!nav) return '';
const clone = nav.cloneNode(true);
clone.querySelectorAll('[data-editor-ui]').forEach(n => n.remove());
clone.removeAttribute('data-gitqi-nav-bound');
// Strip per-item binding markers added by native nav controls so the
// serialized HTML matches what would be produced by a fresh activate.
clone.querySelectorAll('[data-gitqi-nav-item-bound]').forEach(n => n.removeAttribute('data-gitqi-nav-item-bound'));
return clone.outerHTML;
}
// The footer is the semantic <footer>, falling back to [data-zone="footer"]
// for sites that structure it as a regular section.
function getFooterElement(root) {
root = root || document;
return root.querySelector('footer') || root.querySelector('[data-zone="footer"]');
}
function getFooterHTML() {
const footer = getFooterElement();
if (!footer) return '';
const clone = footer.cloneNode(true);
// Strip everything runtime so the disk copy matches what a clean save would write.
clone.querySelectorAll('[data-editor-ui]').forEach(n => n.remove());
clone.querySelectorAll('[contenteditable]').forEach(n => n.removeAttribute('contenteditable'));
clone.querySelectorAll('[spellcheck]').forEach(n => n.removeAttribute('spellcheck'));
clone.querySelectorAll('[data-gitqi-bound]').forEach(n => n.removeAttribute('data-gitqi-bound'));
clone.querySelectorAll('[data-gitqi-video-bound]').forEach(n => n.removeAttribute('data-gitqi-video-bound'));
return clone.outerHTML;
}
function getFooterSectionStyle(root) {
root = root || document;
const footer = getFooterElement(root);
const slug = footer && footer.dataset ? footer.dataset.zone : '';
if (!slug) return null;
return root.getElementById('__gitqi-section-' + slug + '-styles');
}
// The main <style> block is the first <style> that isn't one of GitQi's
// managed blocks (nav or per-section). Matches what the theme editor uses.
function getMainStyleElement(root) {
const head = root.head || root;
const styles = Array.from(head.querySelectorAll('style'));
return styles.find(s => !s.id || !s.id.startsWith('__gitqi-')) || null;
}
function getSharedHeadElements() {
const head = document.head;
return {
mainStyle: getMainStyleElement(document),
navStyle: head.querySelector('style#__gitqi-nav-styles'),
footerStyle: getFooterSectionStyle(),
favicon: head.querySelector('link[rel="icon"]'),
appleIcon: head.querySelector('link[rel="apple-touch-icon"]'),
googleFontLinks: Array.from(head.querySelectorAll(
'link[href*="fonts.googleapis.com"], link[href*="fonts.gstatic.com"]'
)),
};
}
function getSharedSnapshot() {
const s = getSharedHeadElements();
const footer = getFooterElement();
return JSON.stringify({
nav: getNavHTML(),
footer: getFooterHTML(),
footerSlug: footer && footer.dataset ? (footer.dataset.zone || '') : '',
mainStyle: s.mainStyle ? s.mainStyle.textContent : '',
navStyle: s.navStyle ? s.navStyle.textContent : '',
footerStyle: s.footerStyle ? s.footerStyle.textContent : '',
favicon: s.favicon ? s.favicon.outerHTML : '',
appleIcon: s.appleIcon ? s.appleIcon.outerHTML : '',
googleFontLinks: s.googleFontLinks.map(l => l.outerHTML).sort(),
});
}
// Normalize an href to a plain filename for comparison (drops ./, fragment, query).
function normalizeHref(href) {
return (href || '').replace(/^\.\//, '').split('#')[0].split('?')[0];
}
// Match an anchor href against a page filename, tolerating common home-link
// aliases ("./", "/", "", ".") that all resolve to index.html.
function hrefMatchesFilename(href, filename) {
const norm = normalizeHref(href);
if (norm === filename) return true;
if (filename === 'index.html' && (norm === '' || norm === '.' || norm === '/')) return true;
return false;
}
// Common "current page" marker classes used by hand-written and AI-generated navs.
const ACTIVE_CLASS_CANDIDATES = ['active', 'current', 'is-active', 'is-current', 'selected'];
// Inspect the source nav to learn how the current page marks its own link as active.
// Returns { classes, ariaCurrent } or null if no recognised marker is present.
// Only classes from ACTIVE_CLASS_CANDIDATES are treated as active markers — this
// avoids false positives on unrelated unique classes (e.g. `has-megamenu`).
function extractActiveMarker(navEl, sourceFilename) {
const sourceAnchors = Array.from(navEl.querySelectorAll('a[href]'))
.filter(a => hrefMatchesFilename(a.getAttribute('href'), sourceFilename));
if (!sourceAnchors.length) return null;
const ref = sourceAnchors[0];
const classes = Array.from(ref.classList).filter(c => ACTIVE_CLASS_CANDIDATES.includes(c));
const ariaCurrent = ref.getAttribute('aria-current');
if (!classes.length && !ariaCurrent) return null;
return { classes, ariaCurrent };
}
// Remove all known active markers from every anchor in `navEl`, then apply
// `marker` to anchors whose href targets `destFilename`.
function retargetActiveMarker(navEl, marker, destFilename) {
navEl.querySelectorAll('a').forEach(a => {
ACTIVE_CLASS_CANDIDATES.forEach(c => a.classList.remove(c));
a.removeAttribute('aria-current');
if (a.hasAttribute('class') && a.classList.length === 0) a.removeAttribute('class');
});
if (!marker) return;
navEl.querySelectorAll('a[href]').forEach(a => {
if (!hrefMatchesFilename(a.getAttribute('href'), destFilename)) return;
marker.classes.forEach(c => a.classList.add(c));
if (marker.ariaCurrent) a.setAttribute('aria-current', marker.ariaCurrent);
});
}
async function syncSharedToOtherPagesIfChanged() {
if (!dirHandle || !pagesInventory) return { skipped: true, reason: 'no-folder' };
const snapshot = getSharedSnapshot();
if (snapshot === lastSyncedSharedSnapshot) return { skipped: true, reason: 'unchanged' };
const shared = getSharedHeadElements();
const currentNavHTML = getNavHTML();
const currentFooterHTML = getFooterHTML();
const sourceFooterEl = getFooterElement();
const sourceFooterSlug = sourceFooterEl && sourceFooterEl.dataset ? (sourceFooterEl.dataset.zone || '') : '';
const sourceNav = document.querySelector('nav');
const activeMarker = sourceNav ? extractActiveMarker(sourceNav, CURRENT_FILENAME) : null;
let syncedCount = 0;
const failedFiles = [];
for (const page of pagesInventory.pages) {
if (page.file === CURRENT_FILENAME) continue;
try {
const fh = await dirHandle.getFileHandle(page.file);
const pageFile = await fh.getFile();
const text = await pageFile.text();
const doc = new DOMParser().parseFromString(text, 'text/html');
// Replace <nav> — re-target the "current page" active marker so each
// destination page marks its own link, not the link of the source page.
// Prefer the source's marker, but fall back to the destination's own
// existing marker if the source has none. This prevents the sync from
// wiping active markers off every page just because the source page's
// nav happens to be in a transient state without one.
if (currentNavHTML) {
const existingNav = doc.querySelector('nav');
if (existingNav) {
const destMarker = activeMarker || extractActiveMarker(existingNav, page.file);
const tmp = doc.createElement('div');
tmp.innerHTML = currentNavHTML;
const newNav = tmp.querySelector('nav');
if (newNav) {
retargetActiveMarker(newNav, destMarker, page.file);
existingNav.replaceWith(newNav);
}
}
}
// Replace main <style>
if (shared.mainStyle) {
const destMain = getMainStyleElement(doc);
if (destMain) {
destMain.textContent = shared.mainStyle.textContent;
} else {
const s = doc.createElement('style');
s.textContent = shared.mainStyle.textContent;
doc.head.appendChild(s);
}
}
// Replace <footer> — matched the same way as the source (semantic
// <footer> first, [data-zone="footer"] fallback). Copied verbatim;
// footers don't carry per-page "active link" markers the way navs do.
if (currentFooterHTML) {
const existingFooter = getFooterElement(doc);
if (existingFooter) {
const tmp = doc.createElement('div');
tmp.innerHTML = currentFooterHTML;
const newFooter = tmp.firstElementChild;
if (newFooter) existingFooter.replaceWith(newFooter);
}
}
// Replace the footer's per-section style block, keyed by the source
// footer's zone slug.
if (sourceFooterSlug) {
const destFooterStyleId = '__gitqi-section-' + sourceFooterSlug + '-styles';
const destFooterStyleEl = doc.getElementById(destFooterStyleId);
if (shared.footerStyle) {
if (destFooterStyleEl) {
destFooterStyleEl.textContent = shared.footerStyle.textContent;
} else {
const s = doc.createElement('style');
s.id = destFooterStyleId;
s.textContent = shared.footerStyle.textContent;
doc.head.appendChild(s);
}
} else if (destFooterStyleEl) {
destFooterStyleEl.remove();
}
}
// Replace nav style block (or remove if source no longer has one)
const destNavStyle = doc.head.querySelector('style#__gitqi-nav-styles');
if (shared.navStyle) {
if (destNavStyle) {
destNavStyle.textContent = shared.navStyle.textContent;
} else {
const s = doc.createElement('style');
s.id = '__gitqi-nav-styles';
s.textContent = shared.navStyle.textContent;
doc.head.appendChild(s);
}
} else if (destNavStyle) {
destNavStyle.remove();
}
// Sync favicon links
syncLinkRelInDoc(doc, 'icon', shared.favicon);
syncLinkRelInDoc(doc, 'apple-touch-icon', shared.appleIcon);
// Sync Google Fonts <link>s (plus preconnects)
syncGoogleFontLinksInDoc(doc, shared.googleFontLinks);
const updated = '<!DOCTYPE html>\n' + doc.documentElement.outerHTML;
const writeFh = await dirHandle.getFileHandle(page.file, { create: false });
const writable = await writeFh.createWritable();
await writable.write(updated);
await writable.close();
syncedCount++;
} catch (_) {
failedFiles.push(page.file); // Non-fatal — surfaced to caller, sync continues
}
}
lastSyncedSharedSnapshot = snapshot;
return { skipped: false, syncedCount, failedFiles };
}
// Upsert or remove a <link rel="X"> in `doc` to match the source element.
// Source null → any existing link with that rel is removed.
function syncLinkRelInDoc(doc, rel, source) {
let link = doc.head.querySelector(`link[rel="${rel}"]`);
if (source) {
if (!link) {
link = doc.createElement('link');
doc.head.appendChild(link);
}
Array.from(link.attributes).forEach(a => link.removeAttribute(a.name));
Array.from(source.attributes).forEach(a => link.setAttribute(a.name, a.value));
} else if (link) {
link.remove();
}
}
// Replace all Google Fonts <link>s in `doc` with copies of `sourceLinks`.
// Inserted before the first <style> so fonts load before inline CSS references them.
function syncGoogleFontLinksInDoc(doc, sourceLinks) {
doc.head.querySelectorAll(
'link[href*="fonts.googleapis.com"], link[href*="fonts.gstatic.com"]'
).forEach(l => l.remove());
const firstStyle = doc.head.querySelector('style');
sourceLinks.forEach(src => {
const link = doc.createElement('link');
Array.from(src.attributes).forEach(a => link.setAttribute(a.name, a.value));
if (firstStyle) doc.head.insertBefore(link, firstStyle);
else doc.head.appendChild(link);
});
}
// ─── Zone Manager ─────────────────────────────────────────────────────────
function activateZones() {
document.querySelectorAll('[data-zone]').forEach(zone => activateZone(zone));
if (hasGemini) injectAddSectionButtons(); // section creation requires AI; hidden when offline
}
function preventBlockOnEnter(e) {
if (e.key !== 'Enter') return;
e.preventDefault();
// execCommand('insertLineBreak') inserts <br> and positions the cursor correctly,
// avoiding the <div>-wrapping that browsers default to in contenteditable.
document.execCommand('insertLineBreak');
}
function activateZone(section) {
section.querySelectorAll('[data-editable]').forEach(node => {
node.contentEditable = 'true';
node.setAttribute('spellcheck', 'true');
// Browsers (especially Chrome) insert <div> on Enter inside contenteditable,
// which breaks styling and leaves new content without data-editable.
// Force <br> instead so inline text elements stay flat.
node.addEventListener('keydown', preventBlockOnEnter);
bindEmptyRemoveToEditable(node);
});
// Bind image handlers to ALL images in the zone — not just those with
// data-editable-image, so bootstrap-generated images are always editable.
section.querySelectorAll('img').forEach(img => {
if (img.closest('[data-editor-ui]')) return;
if (img.dataset.gitqiBound) return; // already activated (e.g. re-injection)
img.dataset.gitqiBound = '1';
bindImageHandler(img);
});
// Bind video handlers to [data-editable-video] wrappers (iframes eat pointer
// events so we bind on the wrapper and inject a click-intercept overlay).
section.querySelectorAll('[data-editable-video]').forEach(wrapper => {
if (wrapper.closest('[data-editor-ui]')) return;
if (wrapper.dataset.gitqiVideoBound) return;
wrapper.dataset.gitqiVideoBound = '1';
bindVideoHandler(wrapper);
});
// Ensure the section has an id matching its zone slug so anchor links work when deployed
if (section.dataset.zone && !section.id) section.id = section.dataset.zone;
// Duplicate + move arrows are only meaningful for ordinary sections —
// the footer is unique per page and is replicated across pages by the
// shared sync, so duplicating it or moving it would produce broken state.
// Append order matches left-to-right visual order in the flex wrapper:
// Duplicate | Reformat | Delete.
if (!isFooterSection(section)) {
injectDuplicateButton(section);
injectMoveButtons(section);
}
if (hasGemini) injectReformatButton(section); // AI-driven; hidden when offline
injectDeleteButton(section);
}
function isFooterSection(section) {
return section === getFooterElement();
}
// ─── Empty editable remove control ────────────────────────────────────────
// When a user deletes all content from a [data-editable] element, the element
// itself still occupies layout space. Show a floating ✕ button while the
// element is empty + focused/hovered so the owner can remove it entirely.
const emptyBoundNodes = new WeakSet();
let emptyRemoveBtn = null;
let emptyRemoveTarget = null;
let emptyRepositionBound = false;
function isEditableEmpty(node) {
if (!node || !node.isConnected) return false;
if (node.textContent && node.textContent.trim() !== '') return false;
if (node.querySelector('img, svg, iframe, video, picture, canvas')) return false;
return true;
}
function getOrCreateEmptyRemoveBtn() {
if (emptyRemoveBtn) return emptyRemoveBtn;
const btn = el('button', { 'data-editor-ui': '', type: 'button', title: 'Remove empty element' });
btn.textContent = '✕';
css(btn, {
position: 'absolute',
zIndex: '999999',
width: '22px',
height: '22px',
padding: '0',
background: T.accent4,
color: '#fff',
border: 'none',
borderRadius: '999px',
cursor: 'pointer',
fontSize: '12px',
lineHeight: '22px',
fontFamily: T.fontBody,
fontWeight: '700',
boxShadow: '0 6px 14px -6px rgba(244, 114, 182, 0.55)',
display: 'none',