-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeck.js
More file actions
867 lines (766 loc) · 35.7 KB
/
Copy pathdeck.js
File metadata and controls
867 lines (766 loc) · 35.7 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
/* Presentation kit deck runtime. No dependencies.
Reads <section class="s" data-label="01 · Cover" data-notes="…"> and wires up
chrome, rail, notes, jump modal, keyboard stepping, reveals, counters,
accordions, before/after toggles, checklists, and drop-to-fill image slots. */
(function () {
'use strict';
/* Captured before anything mutates the DOM, so Export can write a clean file
instead of one full of runtime state (rail buttons, is-in classes, timers). */
var PRISTINE = document.documentElement.outerHTML;
var deckKey = document.body.getAttribute('data-deck') || 'deck';
var EASE_OUT = function (p) { return 1 - Math.pow(1 - p, 3); };
var reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
function $(sel, root) { return (root || document).querySelector(sel); }
function $$(sel, root) { return Array.prototype.slice.call((root || document).querySelectorAll(sel)); }
function pad(n) { return String(n).padStart(2, '0'); }
/* ── theme ─────────────────────────────────────────────────────────────
Dark by default. Set <body data-theme="light"> to have a deck open light
instead, for brands that are daylight-first. Once the viewer presses L the
stored preference wins, and it is shared across every deck. */
var THEME_KEY = 'deck-theme';
var themeBtn = $('[data-action="theme"]');
function setTheme(light, persist) {
document.body.classList.toggle('is-light', light);
if (themeBtn) {
themeBtn.innerHTML = (light ? 'Dark' : 'Light') + ' <kbd>L</kbd>';
themeBtn.setAttribute('aria-label', light ? 'Switch to dark theme' : 'Switch to light theme');
}
if (persist) { try { localStorage.setItem(THEME_KEY, light ? 'light' : 'dark'); } catch (err) {} }
}
function isLight() { return document.body.classList.contains('is-light'); }
(function initTheme() {
var stored = null;
try { stored = localStorage.getItem(THEME_KEY); } catch (err) {}
var fallback = document.body.getAttribute('data-theme') === 'light';
setTheme(stored === null ? fallback : stored === 'light', false);
})();
/* ── sections ──────────────────────────────────────────────────────── */
var sections = $$('section[data-label]');
var idx = 0;
function labelParts(el) {
var raw = el.getAttribute('data-label') || '';
var bits = raw.split('·');
return {
num: (bits[0] || '').trim(),
title: (bits[1] || bits[0] || '').trim(),
note: el.getAttribute('data-notes') || ''
};
}
/* ── chrome ────────────────────────────────────────────────────────── */
var counterEl = $('.chrome__counter');
var labelEl = $('.chrome__label');
var progressEl = $('.chrome__progress');
var notesTextEl = $('.notes__text');
var railItems = [];
var jumpCells = [];
function buildNav() {
var rail = $('.rail');
var grid = $('.jump__grid');
if (rail) rail.innerHTML = '';
if (grid) grid.innerHTML = '';
sections.forEach(function (el, i) {
var p = labelParts(el);
var isBreak = el.hasAttribute('data-break');
if (rail) {
var item = document.createElement('button');
item.className = 'rail__item' + (isBreak ? ' rail__item--break' : '');
item.type = 'button';
item.title = p.title;
item.setAttribute('aria-label', 'Go to ' + p.title);
item.innerHTML = '<span class="rail__num"></span><span class="rail__tick"></span>';
$('.rail__num', item).textContent = p.num;
item.addEventListener('click', function () { goTo(i); });
rail.appendChild(item);
railItems.push(item);
}
if (grid) {
var cell = document.createElement('button');
cell.className = 'jump__cell' + (isBreak ? ' jump__cell--break' : '');
cell.type = 'button';
cell.innerHTML = '<span class="jump__cell-num"></span><span class="jump__cell-title"></span>';
$('.jump__cell-num', cell).textContent = p.num;
$('.jump__cell-title', cell).textContent = p.title;
cell.addEventListener('click', function () { goTo(i); setJump(false); });
grid.appendChild(cell);
jumpCells.push(cell);
}
});
}
function paintActive() {
var p = labelParts(sections[idx] || document.createElement('div'));
if (counterEl) counterEl.textContent = pad(idx + 1) + ' / ' + pad(sections.length);
if (labelEl) labelEl.textContent = p.title;
if (notesTextEl) notesTextEl.textContent = p.note || 'No note for this section.';
railItems.forEach(function (el, i) { el.classList.toggle('is-on', i === idx); });
jumpCells.forEach(function (el, i) { el.classList.toggle('is-on', i === idx); });
}
function measure() {
if (!sections.length) return;
var max = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
var pct = Math.min(1, Math.max(0, window.scrollY / max));
if (progressEl) progressEl.style.transform = 'scaleX(' + pct.toFixed(4) + ')';
var mid = window.scrollY + window.innerHeight * 0.4;
var next = 0;
sections.forEach(function (el, i) { if (el.offsetTop <= mid) next = i; });
if (next !== idx) { idx = next; paintActive(); }
}
function goTo(i) {
var el = sections[Math.max(0, Math.min(sections.length - 1, i))];
if (!el) return;
window.scrollTo({ top: el.offsetTop, behavior: reduceMotion ? 'auto' : 'smooth' });
}
function step(d) { goTo(idx + d); }
/* ── panels ────────────────────────────────────────────────────────── */
function setNotes(on) { document.body.classList.toggle('is-notes', on); }
function setJump(on) { document.body.classList.toggle('is-jump', on); }
function setFocus(on) { document.body.classList.toggle('is-focus', on); }
function toggle(cls) { return document.body.classList.toggle(cls); }
/* ── timer ─────────────────────────────────────────────────────────── */
var elapsed = 0;
var clockEl = $('.chrome__clock');
setInterval(function () {
elapsed += 1;
if (clockEl) clockEl.textContent = pad(Math.floor(elapsed / 60)) + ':' + pad(elapsed % 60);
}, 1000);
/* ── reveals, counters, bars ───────────────────────────────────────── */
function animate(from, to, ms, cb) {
if (reduceMotion) { cb(to); return; }
var t0 = performance.now();
(function frame(now) {
var p = Math.min(1, (now - t0) / ms);
/* the last frame snaps to the target rather than easing towards it, so a
decimal counter lands on its real value instead of near it */
if (p >= 1) { cb(to); return; }
var e = EASE_OUT(p);
cb(from.map(function (f, i) { return f + (to[i] - f) * e; }));
requestAnimationFrame(frame);
})(t0);
}
function formatCount(el, n) {
var fmt = el.getAttribute('data-format') || 'int';
var dp = Math.max(0, Math.min(4, Number(el.getAttribute('data-decimals')) || 0));
var out = fmt === 'plain'
? Number(n).toFixed(dp)
: Number(n).toLocaleString('en-US', { minimumFractionDigits: dp, maximumFractionDigits: dp });
return (el.getAttribute('data-prefix') || '') + out + (el.getAttribute('data-suffix') || '');
}
function runCounters(scope) {
var els = $$('[data-count]', scope);
if (!els.length) return;
var targets = els.map(function (el) { return Number(el.getAttribute('data-count')) || 0; });
animate(targets.map(function () { return 0; }), targets, 1100, function (vals) {
els.forEach(function (el, i) { el.textContent = formatCount(el, vals[i]); });
});
}
function runBars(scope) {
$$('[data-bar]', scope).forEach(function (el) {
var pct = Math.max(0, Math.min(100, Number(el.getAttribute('data-bar')) || 0));
requestAnimationFrame(function () { el.style.transform = 'scaleX(' + (pct / 100) + ')'; });
});
}
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (en) {
if (!en.isIntersecting) return;
var el = en.target;
el.classList.add('is-in');
runCounters(el);
runBars(el);
io.unobserve(el);
});
}, { threshold: 0.25 });
$$('[data-reveal]').forEach(function (el) {
if (!reduceMotion) el.classList.add('is-armed');
io.observe(el);
});
// Counters/bars living outside a [data-reveal] block still need observing.
$$('[data-count],[data-bar]').forEach(function (el) {
if (el.closest('[data-reveal]')) return;
var host = el.closest('section') || el;
io.observe(host);
});
/* ── accordions ────────────────────────────────────────────────────── */
$$('[data-acc]').forEach(function (acc) {
var items = $$('.acc__item', acc);
var openFirst = acc.getAttribute('data-acc') === 'open-first';
items.forEach(function (item, i) {
if (openFirst && i === 0) item.classList.add('is-open');
item.addEventListener('click', function () {
var wasOpen = item.classList.contains('is-open');
items.forEach(function (o) { o.classList.remove('is-open'); });
if (!wasOpen) item.classList.add('is-open');
});
});
});
/* ── before / after ────────────────────────────────────────────────── */
$$('[data-compare]').forEach(function (root) {
var buttons = $$('[data-compare-set]', root);
var cols = $$('[data-compare-side]', root);
function apply(mode) {
buttons.forEach(function (b) { b.classList.toggle('is-on', b.getAttribute('data-compare-set') === mode); });
cols.forEach(function (c) {
var side = c.getAttribute('data-compare-side');
c.classList.toggle('is-dim', mode !== 'both' && mode !== side);
});
}
buttons.forEach(function (b) {
b.addEventListener('click', function () { apply(b.getAttribute('data-compare-set')); });
});
apply('both');
});
/* ── checklist ─────────────────────────────────────────────────────── */
$$('.check__item').forEach(function (item) {
item.addEventListener('click', function () { item.classList.toggle('is-done'); });
});
/* ── inline editing ────────────────────────────────────────────────────
Press E to edit any text on the page in place. Edits are kept in
localStorage so they survive a reload, and Export writes a real HTML file
with them baked in, so the deck on disk never drifts from what you see.
Elements are addressed by position (section index + order within the
section) rather than by an id you'd have to add to the markup, which means
every existing deck gets this for free. Each edit stores the original text
alongside the new one: if the source file changes underneath a stored edit,
the file wins and the orphan is dropped. */
var TXT_KEY = 'deck:' + deckKey + ':txt';
var editing = false;
var edits = {};
try { edits = JSON.parse(localStorage.getItem(TXT_KEY) || '{}'); } catch (err) { edits = {}; }
var SKIP_TAGS = { SCRIPT: 1, STYLE: 1, BR: 1, HR: 1, 'IMAGE-SLOT': 1, IMG: 1, IFRAME: 1, KBD: 1, CANVAS: 1 };
var SKIP_SEL = '[data-count],[data-bar],.check__box,.acc__plus,.rail__tick,.rail__num,.byline__avatar,.chrome__mark';
function isSkipped(el) {
return SKIP_TAGS[el.tagName] || el.matches(SKIP_SEL);
}
function hasDirectText(el) {
for (var i = 0; i < el.childNodes.length; i++) {
var n = el.childNodes[i];
if (n.nodeType === 3 && n.nodeValue && n.nodeValue.trim()) return true;
}
return false;
}
/* An element owns its text the moment it holds any of its own, so a headline
like `Stop typing.<br><em>Start talking.</em>` is edited as one field
rather than losing the bare half. Anything that is purely a wrapper gets
walked past, which keeps editable regions from nesting. */
function collectIn(section) {
var found = [];
(function walk(el) {
Array.prototype.slice.call(el.children).forEach(function (kid) {
if (isSkipped(kid)) return;
if (!kid.textContent || !kid.textContent.trim()) return;
if (hasDirectText(kid)) { found.push(kid); return; }
walk(kid);
});
})(section);
return found;
}
function eachEditable(root, fn) {
var secs = Array.prototype.slice.call(root.querySelectorAll('section[data-label]'));
secs.forEach(function (sec, si) {
collectIn(sec).forEach(function (el, oi) { fn(el, si + '.' + oi, sec, si); });
});
}
function saveEdits() {
try { localStorage.setItem(TXT_KEY, JSON.stringify(edits)); return true; }
catch (err) { return false; }
}
/* Applied at load. A stored edit only lands if the element still holds the
text it was made against. */
function applyStored() {
eachEditable(document, function (el, eid) {
var rec = edits[eid];
if (!rec) return;
if (rec.o !== el.innerHTML) { delete edits[eid]; return; }
el.innerHTML = rec.t;
});
sections.forEach(function (sec, si) {
var rec = edits['n' + si];
if (!rec) return;
if (rec.o !== (sec.getAttribute('data-notes') || '')) { delete edits['n' + si]; return; }
sec.setAttribute('data-notes', rec.t);
});
saveEdits();
}
function record(eid, original, next) {
if (next === original) delete edits[eid];
else edits[eid] = { o: original, t: next };
saveEdits();
paintEditCount();
}
function setEdit(on) {
editing = on;
document.body.classList.toggle('is-edit', on);
eachEditable(document, function (el, eid) {
if (on) {
if (!el.hasAttribute('data-orig')) el.setAttribute('data-orig', el.innerHTML);
el.setAttribute('contenteditable', 'true');
el.setAttribute('spellcheck', 'true');
el.setAttribute('data-eid', eid);
} else {
el.removeAttribute('contenteditable');
el.removeAttribute('spellcheck');
}
});
if (notesTextEl) {
if (on) notesTextEl.setAttribute('contenteditable', 'true');
else notesTextEl.removeAttribute('contenteditable');
}
if (on) setNotes(true);
if (!on) hideSelBar();
paintEditCount();
}
/* Typing inside a control shouldn't also fire the control. */
document.addEventListener('click', function (e) {
if (!editing) return;
if (e.target && e.target.closest && e.target.closest('[contenteditable="true"]')) {
e.stopPropagation();
e.preventDefault();
}
}, true);
document.addEventListener('input', function (e) {
if (!editing) return;
var el = e.target;
if (el === notesTextEl) {
var sec = sections[idx];
if (!sec) return;
if (!sec.hasAttribute('data-orig-notes')) sec.setAttribute('data-orig-notes', sec.getAttribute('data-notes') || '');
record('n' + idx, sec.getAttribute('data-orig-notes'), el.textContent);
sec.setAttribute('data-notes', el.textContent);
return;
}
if (!el.hasAttribute || !el.hasAttribute('data-eid')) return;
record(el.getAttribute('data-eid'), el.getAttribute('data-orig'), el.innerHTML);
});
/* Paste as plain text, and keep Enter from injecting <div> soup. */
document.addEventListener('paste', function (e) {
if (!editing || !e.target.closest || !e.target.closest('[contenteditable="true"]')) return;
e.preventDefault();
var text = (e.clipboardData || window.clipboardData).getData('text/plain');
document.execCommand('insertText', false, text);
});
document.addEventListener('keydown', function (e) {
if (!editing) return;
var host = e.target.closest && e.target.closest('[contenteditable="true"]');
if (!host) return;
if (e.key === 'Enter') {
e.preventDefault();
document.execCommand('insertLineBreak');
}
// Cmd/Ctrl+I is the shortcut for gold; the rest live on the selection bar.
if ((e.metaKey || e.ctrlKey) && (e.key === 'i' || e.key === 'I')) {
e.preventDefault();
applyAccent('gold');
}
if (e.key === 'Escape') { e.preventDefault(); hideSelBar(); host.blur(); }
}, true);
/* ── accents ───────────────────────────────────────────────────────────
Accents carry fixed meaning from DESIGN.md, so the bar offers the four
the system defines and nothing else. Clicking the accent a run already
has removes it, which is what makes it a toggle rather than a one-way
door. */
var ACCENTS = [
{ k: 'gold', label: 'Gold', hint: 'Personal' },
{ k: 'green', label: 'Green', hint: 'Positive' },
{ k: 'navy', label: 'Navy', hint: 'Work' },
{ k: 'red', label: 'Red', hint: 'Problem' }
];
var ACCENT_RE = /(^|\s)em-(gold|green|navy|red)(\s|$)/;
function editHost(node) {
var el = node && node.nodeType === 1 ? node : (node && node.parentNode);
return el && el.closest ? el.closest('[contenteditable="true"]') : null;
}
function accentAncestor(node, host) {
var el = node && node.nodeType === 1 ? node : (node && node.parentNode);
while (el && el !== host) {
if (el.tagName === 'EM' && ACCENT_RE.test(el.className || '')) return el;
el = el.parentNode;
}
return null;
}
function unwrap(el) {
var parent = el.parentNode;
while (el.firstChild) parent.insertBefore(el.firstChild, el);
parent.removeChild(el);
parent.normalize();
}
function currentAccent() {
var sel = window.getSelection();
if (!sel || !sel.rangeCount) return null;
var host = editHost(sel.getRangeAt(0).commonAncestorContainer);
if (!host) return null;
var em = accentAncestor(sel.getRangeAt(0).commonAncestorContainer, host);
if (!em) return null;
var m = (em.className || '').match(/em-(gold|green|navy|red)/);
return m ? m[1] : null;
}
function applyAccent(style) {
var sel = window.getSelection();
if (!sel || !sel.rangeCount || sel.isCollapsed) return;
var range = sel.getRangeAt(0);
var host = editHost(range.commonAncestorContainer);
if (!host) return;
var existing = accentAncestor(range.commonAncestorContainer, host);
if (existing) {
// Selection sits inside an accent already: retarget it or strip it.
var was = (existing.className.match(/em-(gold|green|navy|red)/) || [])[1];
if (style === 'plain' || style === was) unwrap(existing);
else existing.className = 'em-' + style;
} else {
var frag = range.extractContents();
// A partial selection can drag whole accent runs along with it.
Array.prototype.slice.call(frag.querySelectorAll('em')).forEach(function (em) {
if (ACCENT_RE.test(em.className || '')) unwrap(em);
});
if (style === 'plain') {
range.insertNode(frag);
} else {
var em = document.createElement('em');
em.className = 'em-' + style;
em.appendChild(frag);
range.insertNode(em);
sel.removeAllRanges();
var r = document.createRange();
r.selectNodeContents(em);
sel.addRange(r);
}
}
// Extraction can leave hollow accent tags behind.
Array.prototype.slice.call(host.querySelectorAll('em')).forEach(function (em) {
if (!em.textContent.trim()) em.parentNode.removeChild(em);
});
host.normalize();
record(host.getAttribute('data-eid'), host.getAttribute('data-orig'), host.innerHTML);
paintSelBar();
}
/* ── selection bar ─────────────────────────────────────────────────── */
var selBar = null;
function buildSelBar() {
selBar = document.createElement('div');
selBar.className = 'selbar';
selBar.innerHTML = ACCENTS.map(function (a) {
return '<button class="selbar__btn" data-accent-set="' + a.k + '" type="button" title="' + a.hint + '">' +
'<span class="selbar__dot selbar__dot--' + a.k + '"></span>' + a.label + '</button>';
}).join('') +
'<span class="selbar__sep"></span>' +
'<button class="selbar__btn" data-accent-set="plain" type="button" title="Remove accent">Plain</button>';
document.body.appendChild(selBar);
// mousedown would collapse the selection before the click lands.
selBar.addEventListener('mousedown', function (e) { e.preventDefault(); });
selBar.addEventListener('click', function (e) {
var btn = e.target.closest && e.target.closest('[data-accent-set]');
if (!btn) return;
applyAccent(btn.getAttribute('data-accent-set'));
});
}
function hideSelBar() { if (selBar) selBar.classList.remove('is-on'); }
function paintSelBar() {
if (!selBar) return;
var active = currentAccent();
$$('[data-accent-set]', selBar).forEach(function (b) {
b.classList.toggle('is-on', b.getAttribute('data-accent-set') === active);
});
}
function positionSelBar() {
if (!editing || !selBar) return hideSelBar();
var sel = window.getSelection();
if (!sel || !sel.rangeCount || sel.isCollapsed) return hideSelBar();
var range = sel.getRangeAt(0);
if (!editHost(range.commonAncestorContainer)) return hideSelBar();
var r = range.getBoundingClientRect();
if (!r.width && !r.height) return hideSelBar();
selBar.classList.add('is-on');
var w = selBar.offsetWidth;
var left = Math.min(window.innerWidth - w - 12, Math.max(12, r.left + r.width / 2 - w / 2));
var top = r.top - selBar.offsetHeight - 10;
if (top < 64) top = r.bottom + 10; // flip below when it would hit the chrome
selBar.style.left = Math.round(left) + 'px';
selBar.style.top = Math.round(top) + 'px';
paintSelBar();
}
document.addEventListener('selectionchange', function () {
if (!editing) return;
// Let the browser finish updating the selection before measuring it.
requestAnimationFrame(positionSelBar);
});
window.addEventListener('scroll', function () { if (editing) positionSelBar(); }, { passive: true });
window.addEventListener('resize', function () { if (editing) positionSelBar(); });
/* ── edit bar ──────────────────────────────────────────────────────── */
var editBar = null;
var editCountEl = null;
function paintEditCount() {
if (!editCountEl) return;
var n = Object.keys(edits).length;
editCountEl.textContent = n === 0 ? 'No changes' : n + (n === 1 ? ' change' : ' changes');
}
function buildEditUI() {
var tools = $('.chrome__tools');
if (tools && !$('[data-action="edit"]')) {
var btn = document.createElement('button');
btn.className = 'btn-chrome';
btn.type = 'button';
btn.setAttribute('data-action', 'edit');
btn.innerHTML = 'Edit <kbd>E</kbd>';
tools.insertBefore(btn, tools.firstChild.nextSibling);
}
editBar = document.createElement('div');
editBar.className = 'editbar';
editBar.innerHTML =
'<span class="editbar__dot"></span>' +
'<span class="editbar__label">Editing</span>' +
'<span class="editbar__count"></span>' +
'<span class="editbar__hint">Click any text · select to recolour · Esc to leave a field</span>' +
'<button class="editbar__btn" data-edit="export" type="button">Export HTML</button>' +
'<button class="editbar__btn" data-edit="revert" type="button">Revert all</button>' +
'<button class="editbar__btn editbar__btn--solid" data-edit="done" type="button">Done</button>';
document.body.appendChild(editBar);
editCountEl = $('.editbar__count', editBar);
editBar.addEventListener('click', function (e) {
var act = e.target.getAttribute && e.target.getAttribute('data-edit');
if (act === 'done') setEdit(false);
if (act === 'export') exportHTML();
if (act === 'revert') revertAll();
});
paintEditCount();
}
function revertAll() {
if (!window.confirm('Discard every text change and go back to the file as written?')) return;
edits = {};
saveEdits();
eachEditable(document, function (el) {
if (el.hasAttribute('data-orig')) el.innerHTML = el.getAttribute('data-orig');
});
sections.forEach(function (sec) {
if (sec.hasAttribute('data-orig-notes')) sec.setAttribute('data-notes', sec.getAttribute('data-orig-notes'));
});
paintActive();
paintEditCount();
}
/* Rebuilds the file from the pristine snapshot rather than the live DOM, so
the download has none of the runtime's classes, timers, or generated nav. */
function exportHTML() {
var doc = new DOMParser().parseFromString(PRISTINE, 'text/html');
var applied = 0;
eachEditable(doc, function (el, eid) {
var rec = edits[eid];
if (!rec || rec.o !== el.innerHTML) return;
el.innerHTML = rec.t;
applied++;
});
Array.prototype.slice.call(doc.querySelectorAll('section[data-label]')).forEach(function (sec, si) {
var rec = edits['n' + si];
if (!rec || rec.o !== (sec.getAttribute('data-notes') || '')) return;
sec.setAttribute('data-notes', rec.t);
applied++;
});
var html = '<!DOCTYPE html>\n' + doc.documentElement.outerHTML + '\n';
var blob = new Blob([html], { type: 'text/html' });
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'index.html';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
var total = Object.keys(edits).length;
if (applied < total) {
window.alert('Exported ' + applied + ' of ' + total + ' changes.\n\n' +
(total - applied) + ' could not be placed because the file changed since they were made. ' +
'Those are still on screen but not in the download.');
}
}
buildEditUI();
buildSelBar();
applyStored();
/* ── keyboard ──────────────────────────────────────────────────────── */
window.addEventListener('keydown', function (e) {
if (e.metaKey || e.ctrlKey || e.altKey) return;
var tag = (e.target && e.target.tagName) || '';
if (tag === 'INPUT' || tag === 'TEXTAREA') return;
if (editing) {
// Only Escape gets through while editing, or typing would navigate the deck.
if (e.key === 'Escape' && !(e.target.closest && e.target.closest('[contenteditable="true"]'))) {
e.preventDefault();
setEdit(false);
}
return;
}
var k = e.key;
if (k === 'e' || k === 'E') { e.preventDefault(); setEdit(true); return; }
if (k === 'ArrowRight' || k === 'ArrowDown' || k === 'PageDown' || k === ' ') { e.preventDefault(); step(1); }
else if (k === 'ArrowLeft' || k === 'ArrowUp' || k === 'PageUp') { e.preventDefault(); step(-1); }
else if (k === 'g' || k === 'G') { e.preventDefault(); setJump(!document.body.classList.contains('is-jump')); }
else if (k === 'n' || k === 'N') { e.preventDefault(); setNotes(!document.body.classList.contains('is-notes')); }
else if (k === 'f' || k === 'F') { e.preventDefault(); setFocus(!document.body.classList.contains('is-focus')); }
else if (k === 'l' || k === 'L') { e.preventDefault(); setTheme(!isLight(), true); }
else if (k === 't' || k === 'T') { e.preventDefault(); toggle('is-timer'); }
else if (k === 'r' || k === 'R') { elapsed = 0; }
else if (k === 'Escape') { setJump(false); }
else if (k === 'Home') { e.preventDefault(); goTo(0); }
else if (k === 'End') { e.preventDefault(); goTo(sections.length - 1); }
});
/* ── chrome buttons ────────────────────────────────────────────────── */
$$('[data-action]').forEach(function (btn) {
btn.addEventListener('click', function () {
var a = btn.getAttribute('data-action');
if (a === 'jump') setJump(!document.body.classList.contains('is-jump'));
if (a === 'notes') setNotes(!document.body.classList.contains('is-notes'));
if (a === 'theme') setTheme(!isLight(), true);
if (a === 'edit') setEdit(!editing);
if (a === 'close-jump') setJump(false);
});
});
var jumpBackdrop = $('.jump');
if (jumpBackdrop) {
jumpBackdrop.addEventListener('click', function (e) { if (e.target === jumpBackdrop) setJump(false); });
}
/* ── scroll ────────────────────────────────────────────────────────── */
var raf = null;
function onScroll() {
if (raf) return;
raf = requestAnimationFrame(function () { raf = null; measure(); });
}
window.addEventListener('scroll', onScroll, { passive: true });
window.addEventListener('resize', onScroll);
buildNav();
paintActive();
measure();
/* ── <image-slot> ──────────────────────────────────────────────────────
Drop an image on it (or click to browse). Stored as a downscaled JPEG in
localStorage under the deck key, so it survives reload. A `src` attribute
pointing at assets/ always wins and needs no storage. */
var MAX_EDGE = 1800;
function storeKey(id) { return 'deck:' + deckKey + ':img:' + id; }
function readStore(id) {
try { return localStorage.getItem(storeKey(id)); } catch (err) { return null; }
}
function writeStore(id, data) {
try { localStorage.setItem(storeKey(id), data); return true; }
catch (err) { return false; }
}
function downscale(file, cb) {
var reader = new FileReader();
reader.onload = function () {
var img = new Image();
img.onload = function () {
var scale = Math.min(1, MAX_EDGE / Math.max(img.width, img.height));
var w = Math.round(img.width * scale);
var h = Math.round(img.height * scale);
var canvas = document.createElement('canvas');
canvas.width = w; canvas.height = h;
canvas.getContext('2d').drawImage(img, 0, 0, w, h);
cb(canvas.toDataURL('image/jpeg', 0.82));
};
img.onerror = function () { cb(null); };
img.src = reader.result;
};
reader.onerror = function () { cb(null); };
reader.readAsDataURL(file);
}
var SLOT_CSS =
':host{display:block;position:absolute;inset:0;overflow:hidden}' +
':host([shape="circle"]) .frame{border-radius:50%}' +
'.frame{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;' +
'background:repeating-linear-gradient(45deg,transparent,transparent 7px,' +
'var(--slot-stripe,rgba(237,235,232,.035)) 7px,var(--slot-stripe,rgba(237,235,232,.035)) 8px);' +
'border:1px dashed var(--hairline-strong,#3B3C3B);cursor:pointer;transition:border-color .15s,background-color .15s}' +
'.frame.is-over{border-color:var(--green,#5E9C7B);background-color:var(--green-wash,rgba(94,156,123,.1))}' +
'.frame.is-filled{border:0;background:none;cursor:default}' +
'img{width:100%;height:100%;object-fit:cover;display:block}' +
':host([fit="contain"]) img{object-fit:contain}' +
'.hint{font:600 10.5px/1.5 var(--sans,system-ui,sans-serif);letter-spacing:1.4px;text-transform:uppercase;' +
'color:var(--muted,#797671);text-align:center;padding:0 18px;max-width:340px;pointer-events:none}' +
'.clear{position:absolute;top:8px;right:8px;background:var(--slot-clear,rgba(18,19,18,.82));' +
'border:1px solid var(--hairline-strong,#3B3C3B);' +
'color:var(--body,#ADAAA5);font:500 10px/1 var(--sans,system-ui,sans-serif);letter-spacing:.6px;text-transform:uppercase;' +
'padding:5px 8px;border-radius:3px;cursor:pointer;opacity:0;transition:opacity .15s}' +
'.frame:hover .clear{opacity:1}' +
'.err{font:400 11px/1.5 var(--sans,system-ui,sans-serif);color:var(--red,#B36A63);padding:0 18px;text-align:center}';
class ImageSlot extends HTMLElement {}
ImageSlot.prototype.connectedCallback = function () {
if (this._built) return;
this._built = true;
var self = this;
var root = this.attachShadow({ mode: 'open' });
var style = document.createElement('style');
style.textContent = SLOT_CSS;
var frame = document.createElement('div');
frame.className = 'frame';
root.appendChild(style);
root.appendChild(frame);
this._frame = frame;
var input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.style.display = 'none';
root.appendChild(input);
this.render();
frame.addEventListener('click', function (e) {
if (e.target && e.target.className === 'clear') return;
if (frame.classList.contains('is-filled')) return;
input.click();
});
input.addEventListener('change', function () {
if (input.files && input.files[0]) self.accept(input.files[0]);
input.value = '';
});
['dragenter', 'dragover'].forEach(function (evt) {
frame.addEventListener(evt, function (e) { e.preventDefault(); frame.classList.add('is-over'); });
});
['dragleave', 'dragend'].forEach(function (evt) {
frame.addEventListener(evt, function () { frame.classList.remove('is-over'); });
});
frame.addEventListener('drop', function (e) {
e.preventDefault();
frame.classList.remove('is-over');
var f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
if (f && /^image\//.test(f.type)) self.accept(f);
});
};
ImageSlot.prototype.accept = function (file) {
var self = this;
var id = this.getAttribute('id');
downscale(file, function (data) {
if (!data) { self.showError('Could not read that image.'); return; }
if (id && !writeStore(id, data)) {
self.showError('Image too large to remember. Put it in assets/ and set src instead.');
}
self._data = data;
self.render();
});
};
ImageSlot.prototype.showError = function (msg) {
this._frame.innerHTML = '<div class="err"></div>';
this._frame.firstChild.textContent = msg;
};
ImageSlot.prototype.render = function () {
var id = this.getAttribute('id');
var src = this.getAttribute('src') || this._data || (id ? readStore(id) : null);
var frame = this._frame;
frame.innerHTML = '';
if (src) {
frame.classList.add('is-filled');
var img = document.createElement('img');
img.src = src;
img.alt = this.getAttribute('placeholder') || '';
frame.appendChild(img);
if (!this.getAttribute('src')) {
var clear = document.createElement('button');
clear.className = 'clear';
clear.textContent = 'Replace';
clear.addEventListener('click', function (e) {
e.stopPropagation();
try { if (id) localStorage.removeItem(storeKey(id)); } catch (err) { /* ignore */ }
this._data = null;
frame.classList.remove('is-filled');
this.render();
}.bind(this));
frame.appendChild(clear);
}
return;
}
frame.classList.remove('is-filled');
var hint = document.createElement('div');
hint.className = 'hint';
hint.textContent = this.getAttribute('placeholder') || 'Drop an image';
frame.appendChild(hint);
};
if (!customElements.get('image-slot')) customElements.define('image-slot', ImageSlot);
})();