Repository navigation
Expand file tree
/
Copy pathdeck-stage.js
More file actions
2969 lines (2849 loc) · 133 KB
/
Copy pathdeck-stage.js
File metadata and controls
2969 lines (2849 loc) · 133 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
// @ds-adherence-ignore -- omelette starter scaffold (raw elements/hex/px by design)
// Copied omelette starter. Re-running copy_starter_component with this kind overwrites this file with the latest version (page content is unaffected).
/* ═══ THIS PROJECT USES DESIGN COMPONENTS (.dc.html) ═══
* Reference this stage from your <x-dc> template as an import — NEVER as a
* raw <deck-stage> tag plus a <script src> (that hides the whole deck until
* the stream finishes):
*
* <x-import component-from-global-scope="deck-stage" from="./deck-stage.js"
* width="1920" height="1080" hint-size="100%,100%">
* <section data-label="Title" style="...">…</section>
* <section data-label="Agenda" style="...">…</section>
* </x-import>
*
* Slides are inline-styled <section> siblings; do not add a stylesheet or a
* deck-stage:not(:defined) rule. The plain-HTML "Usage" block in the comment
* below does NOT apply to .dc.html templates.
*/
/* BEGIN USAGE */
/**
* <deck-stage> — reusable web component for HTML decks.
*
* Handles:
* (a) speaker notes — reads <script type="application/json" id="speaker-notes">
* and posts {slideIndexChanged: N} to the parent window on nav.
* (b) keyboard navigation — ←/→ and ↑/↓, PgUp/PgDn, Space, Home/End,
* number keys.
* On touch devices, tapping the left/right half of the stage goes
* prev/next — taps on links, buttons and other interactive slide
* content are left alone.
* (c) press R to reset to slide 0 (with a tasteful keyboard hint).
* (d) bottom-center overlay showing slide count + hints, fades out on
* idle; hovering or focusing its controls pins it visible until the
* pointer/focus leaves. While presenting it is pointer-summoned only:
* mouse movement (or hover/focus) shows it, slide changes never do.
* (e) auto-scaling — inner canvas is a fixed design size (default 1920×1080)
* scaled with `transform: scale()` to fit the viewport, letterboxed.
* Set the `noscale` attribute to render at authored size (1:1) — the
* PPTX exporter sets this so its DOM capture sees unscaled geometry.
* (f) print — `@media print` lays every slide out as its own page at the
* design size, so the browser's Print → Save as PDF produces a clean
* one-page-per-slide PDF with no extra setup.
* (g) thumbnail rail — resizable left-hand column of per-slide thumbnails
* (static clones). Click to navigate — the clicked slide becomes the
* selected (highlighted) slide; shift-click selects a range and
* cmd/ctrl-click toggles slides in and out of the selection
* (Escape collapses it back to the current slide); ↑/↓ with a
* thumbnail focused to step between slides; Delete/Backspace with a
* thumbnail focused to delete the selection (one confirm dialog,
* one undoable operation); drag to reorder (dragging collapses a
* multi-selection); right-click for
* Skip / Move up / Move down / Duplicate / Delete — over a
* multi-selection the menu offers "Delete N slides". Drag the rail's right edge to resize;
* width persists to
* localStorage. Skipped slides carry `data-deck-skip`, are dimmed in
* the rail, omitted from prev/next navigation, and hidden at print.
* They also carry no rail number and are excluded from the overlay's
* slide count: the remaining slides are numbered contiguously
* (Keynote-style), and a skipped CURRENT slide (reachable by rail
* click or deep link, never by prev/next) shows '–' as its position.
* The rail is suppressed in presenting mode, in the host's Preview
* mode (ViewerMode='none'), on `noscale`, on narrow viewports
* (≤640px), and via the `no-rail` attribute. Rail mutations dispatch
* a `dc-op` CustomEvent on the element (see docs/dc-ops.md) and do
* NOT touch the DOM: the host applies the op and re-renders;
* structural rail input is locked until the host posts
* {__dc_op_ack: true, applied}.
* (h) typographic defaults — a zero-specificity stylesheet injected into
* the document gives headings `text-wrap: balance` and body text
* (p, li, blockquote, figcaption) `text-wrap: pretty`, so slides
* avoid widowed/orphaned words by default. Any text-wrap declaration
* you author on those elements wins over these defaults.
*
* Slides are HIDDEN, not unmounted. Non-active slides stay in the DOM with
* `visibility: hidden` + `opacity: 0`, so their state (videos, iframes,
* form inputs, React trees) is preserved across navigation.
*
* Lifecycle event — the component dispatches a `slidechange` CustomEvent on
* itself whenever the active slide changes (including the initial mount).
* The event bubbles and composes out of shadow DOM, so you can listen on
* the <deck-stage> element or on document:
*
* document.querySelector('deck-stage').addEventListener('slidechange', (e) => {
* e.detail.index // new 0-based index
* e.detail.previousIndex // previous index, or -1 on init
* e.detail.total // total slide count
* e.detail.slide // the new active slide element
* e.detail.previousSlide // the prior slide element, or null on init
* e.detail.reason // 'init' | 'keyboard' | 'click' | 'tap' | 'api'
* });
*
* Persistence: none at the deck level. The host app keeps the current slide
* in its own URL (?slide=) and re-delivers it via location.hash on load, so a
* bare load with no hash always starts at slide 1.
*
* Usage:
* <style>deck-stage:not(:defined){visibility:hidden}</style>
* <deck-stage width="1920" height="1080">
* <section data-label="Title">...</section>
* <section data-label="Agenda">...</section>
* </deck-stage>
* <script src="deck-stage.js"></script>
*
* The :not(:defined) rule prevents a flash of the first slide at its
* authored styles before this script runs and attaches the shadow root.
*
* Slides are the direct element children of <deck-stage>. Each slide is
* automatically tagged with:
* - data-screen-label="NN Label" (1-indexed, for comment flow)
* - data-om-validate="no_overflowing_text,no_overlapping_text,slide_sized_text"
*
* Speaker notes stay in sync because the component posts {slideIndexChanged: N}
* to the parent — just include the #speaker-notes script tag if asked for notes.
*
* Authoring guidance:
* - Write slide bodies as static HTML inside <deck-stage>, with sizing via
* CSS custom properties in a <style> block rather than JS constants.
* Static slide markup is what lets the user click a heading in edit mode
* and retype it directly; a slide rendered through <script type="text/babel">,
* React, or a loop over a JS array has to round-trip every tweak through a
* chat message instead. Reach for script-generated slides only when the
* content genuinely needs interactive behaviour static HTML can't express.
* - Do NOT set position/inset/width/height on the slide <section> elements —
* the component absolutely positions every slotted child for you.
* - Entrance animations: make the visible end-state the base style and
* animate *from* hidden, so print and reduced-motion show content.
* Gate the animation on [data-deck-active] and the motion query, e.g.
* `@media (prefers-reduced-motion:no-preference){ [data-deck-active] .x{animation:fade-in .5s both} }`.
* Avoid infinite decorative loops on slide content.
*/
/* END USAGE */
(() => {
const DESIGN_W_DEFAULT = 1920;
const DESIGN_H_DEFAULT = 1080;
const OVERLAY_HIDE_MS = 1800;
const VALIDATE_ATTR = 'no_overflowing_text,no_overlapping_text,slide_sized_text';
const FINE_POINTER_MQ = matchMedia('(hover: hover) and (pointer: fine)');
const NARROW_MQ = matchMedia('(max-width: 640px)');
// Slide-authored controls that should keep a tap instead of it navigating.
const INTERACTIVE_SEL = 'a[href], button, input, select, textarea, summary, label, video[controls], audio[controls], [role="button"], [onclick], [tabindex]:not([tabindex^="-"]), [contenteditable]:not([contenteditable="false" i])';
const pad2 = (n) => String(n).padStart(2, '0');
// Label precedence: data-label → data-screen-label (number stripped) → first heading → "Slide".
const getSlideLabel = (el) => {
const explicit = el.getAttribute('data-label');
if (explicit) return explicit;
const existing = el.getAttribute('data-screen-label');
if (existing) return existing.replace(/^\s*\d+\s*/, '').trim() || existing;
const h = el.querySelector('h1, h2, h3, [data-title]');
const t = h && (h.textContent || '').trim().slice(0, 40);
if (t) return t;
return 'Slide';
};
const stylesheet = `
:host {
position: fixed;
inset: 0;
display: block;
background: #000;
color: #fff;
font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif;
overflow: hidden;
-webkit-tap-highlight-color: transparent;
}
/* connectedCallback holds this until document.fonts.ready (capped 2s) so
* the first visible paint has the deck's real typography + final rail
* layout. opacity (not visibility) so the active slide can't un-hide
* itself via the ::slotted([data-deck-active]) visibility:visible rule.
* Only the stage/rail hide — the black :host background stays, so the
* iframe doesn't flash the page's default white. */
:host([data-fonts-pending]) .stage,
:host([data-fonts-pending]) .rail { opacity: 0; pointer-events: none; }
.stage {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
}
.canvas {
position: relative;
transform-origin: center center;
flex-shrink: 0;
background: #fff;
will-change: transform;
/* Slide edge on the black stage. Dark decks override the canvas
* fill toward the stage's own black, leaving nothing to mark where
* the slide ends — the faint white ring keeps the boundary legible
* there while disappearing into the white of light decks. A
* box-shadow, not outline/border: it follows any canvas rounding
* and adds no layout size. */
box-shadow: 0 0 0 1.5px rgba(255, 255, 255, 0.12);
}
/* Slides live in light DOM (via <slot>) so authored CSS still applies.
We absolutely position each slotted child to stack them. */
::slotted(*) {
position: absolute !important;
inset: 0 !important;
width: 100% !important;
height: 100% !important;
box-sizing: border-box !important;
overflow: hidden;
opacity: 0;
pointer-events: none;
visibility: hidden;
}
::slotted([data-deck-active]) {
opacity: 1;
pointer-events: auto;
visibility: visible;
}
.overlay {
position: fixed;
left: 50%;
bottom: 22px;
transform: translate(-50%, 6px) scale(0.92);
filter: blur(6px);
display: flex;
align-items: center;
gap: 4px;
padding: 4px;
background: #000;
color: #fff;
border-radius: 999px;
font-size: 12px;
font-feature-settings: "tnum" 1;
letter-spacing: 0.01em;
opacity: 0;
pointer-events: none;
transition: opacity 260ms ease, transform 260ms cubic-bezier(.2,.8,.2,1), filter 260ms ease;
transform-origin: center bottom;
z-index: 2147483000;
user-select: none;
}
.overlay[data-visible] {
opacity: 1;
pointer-events: auto;
transform: translate(-50%, 0) scale(1);
filter: blur(0);
}
.btn {
appearance: none;
-webkit-appearance: none;
background: transparent;
border: 0;
margin: 0;
padding: 0;
color: inherit;
font: inherit;
cursor: default;
display: inline-flex;
align-items: center;
justify-content: center;
height: 28px;
min-width: 28px;
border-radius: 999px;
color: rgba(255,255,255,0.72);
transition: background 140ms ease, color 140ms ease;
-webkit-tap-highlight-color: transparent;
}
.btn:hover { background: rgba(255,255,255,0.12); color: #fff; }
.btn:active { background: rgba(255,255,255,0.18); }
.btn:focus { outline: none; }
.btn:focus-visible { outline: none; }
.btn::-moz-focus-inner { border: 0; }
.btn svg { width: 14px; height: 14px; display: block; }
.btn.reset {
font-size: 11px;
font-weight: 500;
letter-spacing: 0.02em;
padding: 0 10px 0 12px;
gap: 6px;
color: rgba(255,255,255,0.72);
}
.btn.reset .kbd {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 16px;
height: 16px;
padding: 0 4px;
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1;
color: rgba(255,255,255,0.88);
background: rgba(255,255,255,0.12);
border-radius: 4px;
}
.count {
font-variant-numeric: tabular-nums;
color: #fff;
font-weight: 500;
padding: 0 8px;
min-width: 42px;
text-align: center;
font-size: 12px;
}
.count .sep { color: rgba(255,255,255,0.45); margin: 0 3px; font-weight: 400; }
.count .total { color: rgba(255,255,255,0.55); }
.divider {
width: 1px;
height: 14px;
background: rgba(255,255,255,0.18);
margin: 0 2px;
}
/* ── Thumbnail rail ──────────────────────────────────────────────────
Fixed column on the left; each thumbnail is a static deep-clone of
the light-DOM slide scaled into a 16:9 (or design-aspect) frame. The
stage re-fits around it (see _fit); hidden during present / noscale
/ print so capture geometry and fullscreen output are unchanged. */
.rail {
position: fixed;
left: 0;
top: 0;
bottom: 0;
width: var(--deck-rail-w, 188px);
background: #141414;
border-right: 1px solid rgba(255,255,255,0.08);
overflow-y: auto;
overflow-x: hidden;
padding: 12px 10px;
box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 12px;
z-index: 2147482500;
scrollbar-width: thin;
scrollbar-color: rgba(255,255,255,0.18) transparent;
}
.rail::-webkit-scrollbar { width: 8px; }
.rail::-webkit-scrollbar-track { background: transparent; margin: 2px; }
.rail::-webkit-scrollbar-thumb {
background: rgba(255,255,255,0.18);
border-radius: 4px;
border: 2px solid transparent;
background-clip: content-box;
}
.rail::-webkit-scrollbar-thumb:hover {
background: rgba(255,255,255,0.28);
border: 2px solid transparent;
background-clip: content-box;
}
:host([no-rail]) .rail,
:host([noscale]) .rail { display: none; }
.rail[data-presenting] { display: none; }
@media (max-width: 640px) {
.rail, .rail-resize { display: none; }
}
/* User-driven show/hide (the TweaksPanel toggle) slides instead of
popping. Transitions are gated on :host([data-rail-anim]) — set only
for the 200ms around the toggle — so window-resize and rail-width
drag (which also call _fit) don't lag behind the cursor. */
.rail[data-user-hidden] { transform: translateX(-100%); }
:host([data-rail-anim]) .rail { transition: transform 200ms cubic-bezier(.3,.7,.4,1); }
:host([data-rail-anim]) .stage { transition: left 200ms cubic-bezier(.3,.7,.4,1); }
:host([data-rail-anim]) .canvas { transition: transform 200ms cubic-bezier(.3,.7,.4,1); }
/* transition shorthand replaces rather than merges — repeat the base
.overlay opacity/transform/filter transitions so visibility changes
during the 200ms toggle window still fade instead of popping. */
:host([data-rail-anim]) .overlay {
transition: margin-left 200ms cubic-bezier(.3,.7,.4,1),
opacity 260ms ease,
transform 260ms cubic-bezier(.2,.8,.2,1),
filter 260ms ease;
}
.thumb {
position: relative;
display: flex;
align-items: flex-start;
gap: 8px;
cursor: pointer;
user-select: none;
}
.thumb .num {
width: 16px;
flex-shrink: 0;
font-size: 11px;
font-weight: 500;
text-align: right;
color: rgba(255,255,255,0.55);
padding-top: 2px;
font-variant-numeric: tabular-nums;
}
.thumb .frame {
position: relative;
flex: 1;
min-width: 0;
aspect-ratio: var(--deck-aspect);
background: #fff;
border-radius: 4px;
outline: 2px solid transparent;
outline-offset: 0;
overflow: hidden;
transition: outline-color 120ms ease;
}
.thumb:hover .frame { outline-color: rgba(255,255,255,0.25); }
.thumb { outline: none; }
.thumb:focus-visible .frame { outline-color: rgba(255,255,255,0.5); }
.thumb[data-selected] .num { color: #fff; }
.thumb[data-selected] .frame {
outline-color: rgba(217,119,87,0.65);
box-shadow: 0 0 0 4px rgba(217,119,87,0.18);
}
.thumb[data-current] .num { color: #fff; }
.thumb[data-current] .frame {
outline-color: #D97757;
box-shadow: 0 0 0 4px rgba(217,119,87,0.25);
}
/* While dragging, the thumb itself is the drag visual (the native drag
image is suppressed in dragstart so the snapshot can't wander off the
rail horizontally): elevate it rather than dim it, and let hit-testing
ignore it so dragover reaches the sibling thumb under the pointer
instead of the moving element itself. */
.thumb[data-dragging] { opacity: 0.9; z-index: 30; pointer-events: none; }
.thumb[data-dragging] .frame {
outline-color: rgba(255,255,255,0.5);
box-shadow: 0 6px 24px rgba(0,0,0,0.5);
}
.thumb::before {
content: '';
position: absolute;
left: 24px;
right: 0;
height: 3px;
border-radius: 2px;
background: #D97757;
opacity: 0;
pointer-events: none;
}
.thumb[data-drop="before"]::before { top: -8px; opacity: 1; }
.thumb[data-drop="after"]::before { bottom: -8px; opacity: 1; }
.thumb[data-skip] .frame { opacity: 0.35; }
.thumb[data-skip] .frame::after {
content: 'Skipped';
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0,0,0,0.45);
color: #fff;
font-size: 10px;
font-weight: 500;
letter-spacing: 0.04em;
}
.ctxmenu {
position: fixed;
min-width: 150px;
padding: 4px;
background: #242424;
border: 1px solid rgba(255,255,255,0.12);
border-radius: 7px;
box-shadow: 0 8px 24px rgba(0,0,0,0.45);
z-index: 2147483100;
display: none;
font-size: 12px;
}
.ctxmenu[data-open] { display: block; }
.ctxmenu button {
display: block;
width: 100%;
appearance: none;
border: 0;
background: transparent;
color: #e8e8e8;
font: inherit;
text-align: left;
padding: 6px 10px;
border-radius: 4px;
cursor: pointer;
}
.ctxmenu button:hover:not(:disabled) { background: rgba(255,255,255,0.08); }
.ctxmenu button:disabled { opacity: 0.35; cursor: default; }
.ctxmenu hr {
border: 0;
border-top: 1px solid rgba(255,255,255,0.1);
margin: 4px 2px;
}
.rail-resize {
position: fixed;
left: calc(var(--deck-rail-w, 188px) - 3px);
top: 0;
bottom: 0;
width: 6px;
cursor: col-resize;
z-index: 2147482600;
touch-action: none;
}
.rail-resize:hover,
.rail-resize[data-dragging] { background: rgba(255,255,255,0.12); }
:host([no-rail]) .rail-resize,
:host([noscale]) .rail-resize,
.rail[data-presenting] + .rail-resize,
.rail[data-user-hidden] + .rail-resize { display: none; }
/* Delete-confirm popup — matches the SPA's ConfirmDialog layout
(title + message body, depressed footer with Cancel / Delete). */
.confirm-backdrop {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.45);
z-index: 2147483200;
display: none;
align-items: center;
justify-content: center;
}
.confirm-backdrop[data-open] { display: flex; }
.confirm {
width: 320px;
max-width: calc(100vw - 32px);
background: #2a2a2a;
color: #e8e8e8;
border: 1px solid rgba(255,255,255,0.12);
border-radius: 12px;
box-shadow: 0 12px 32px rgba(0,0,0,0.5);
overflow: hidden;
font-family: inherit;
animation: deck-confirm-in 0.18s ease;
}
@keyframes deck-confirm-in {
from { opacity: 0; transform: scale(0.96); }
to { opacity: 1; transform: scale(1); }
}
.confirm .body { padding: 20px 20px 16px; }
.confirm .title { font-size: 14px; font-weight: 600; margin-bottom: 4px; }
.confirm .msg { font-size: 13px; line-height: 1.5; color: rgba(255,255,255,0.65); }
.confirm .footer {
padding: 14px 20px;
background: #1f1f1f;
border-top: 1px solid rgba(255,255,255,0.08);
display: flex;
justify-content: flex-end;
gap: 8px;
}
.confirm button {
appearance: none;
font: inherit;
font-size: 13px;
font-weight: 500;
padding: 8px 16px;
border-radius: 8px;
cursor: pointer;
}
.confirm .cancel {
background: transparent;
border: 0;
color: rgba(255,255,255,0.8);
}
.confirm .cancel:hover { background: rgba(255,255,255,0.08); }
.confirm .danger {
background: #c96442;
border: 1px solid rgba(0,0,0,0.15);
color: #fff;
box-shadow: 0 1px 3px rgba(166,50,68,0.3), 0 2px 6px rgba(166,50,68,0.18);
}
.confirm .danger:hover { background: #b5563a; }
/* ── Print: one page per slide, no chrome ────────────────────────────
The screen layout stacks every slide at inset:0 inside a scaled
canvas; for print we want them in document flow at the authored
design size so the browser paginates one slide per sheet. The
@page size is set from the width/height attributes via the inline
<style id="deck-stage-print-page"> that _syncPrintPageRule appends
to the document (the @page at-rule has no effect inside shadow DOM). */
@media print {
:host {
position: static;
inset: auto;
background: none;
overflow: visible;
color: inherit;
}
.stage { position: static; display: block; }
.canvas {
transform: none !important;
width: auto !important;
height: auto !important;
background: none;
will-change: auto;
}
::slotted(*) {
position: relative !important;
inset: auto !important;
width: var(--deck-design-w) !important;
height: var(--deck-design-h) !important;
box-sizing: border-box !important;
/* Size containment: slotted content that overflows the design box
* (an image-slot's aspect-ratio-derived width, say) must not count
* toward Chromium's print document width — without this, an
* abs-positioned child past the page edge shrinks the whole PDF
* to fit (~75%). Containment is safe here because the definite
* width/height above size the slide regardless of content.
* (Absorbed from PR #2619 with its owner's agreement.) */
contain: size !important;
opacity: 1 !important;
visibility: visible !important;
pointer-events: auto;
break-after: page;
page-break-after: always;
break-inside: avoid;
overflow: hidden;
}
/* :last-child alone isn't enough once data-deck-skip hides the
trailing slide(s) — the last *visible* slide still carries
break-after:page and prints a blank sheet. _markLastVisible()
maintains data-deck-last-visible on the last non-skipped slide. */
::slotted(*:last-child),
::slotted([data-deck-last-visible]) {
break-after: auto;
page-break-after: auto;
}
::slotted([data-deck-skip]) { display: none !important; }
.overlay, .rail, .rail-resize, .ctxmenu, .confirm-backdrop { display: none !important; }
}
`;
class DeckStage extends HTMLElement {
static get observedAttributes() { return ['width', 'height', 'noscale', 'no-rail']; }
constructor() {
super();
this._root = this.attachShadow({ mode: 'open' });
this._index = 0;
this._slides = [];
// Explicit multi-selection (slide elements). Empty means the
// selection is implicitly the current slide, so Delete always has
// a well-defined target while the rail has focus.
this._selected = new Set();
this._selAnchor = null;
this._notes = [];
this._hideTimer = null;
this._mouseIdleTimer = null;
this._menuIndex = -1;
// Overlay pinning: while the pointer is over the controls toolbar or
// a control has keyboard focus, the idle-hide timeout must not
// dismiss it (a pointer parked ON the controls doesn't generate
// mousemove, so without the pin the toolbar vanishes under the
// user's cursor after OVERLAY_HIDE_MS). Read by _flashOverlay's
// hide timeout; cleared by mouseleave/focusout, which resume the
// normal idle fade.
this._overlayHover = false;
this._overlayFocus = false;
// Capability marker for the host's injected guest bundle. Copies
// WITHOUT _navArrowsUpDown are frozen per-project builds that
// predate native ArrowUp/ArrowDown slide nav — the bundle translates
// Up/Down to Right/Left for those (installDeckArrowKeyTranslator in
// apps/web/src/guest/edit-mode.ts) and must stand down here or every
// press would advance twice. A marker, not a version number, so a
// future capability can add its own independent probe.
this._navArrowsUpDown = true;
// Same contract for rail Delete/Backspace: copies WITHOUT
// _railDeleteKey predate the thumbs' own Delete/Backspace binding,
// and the bundle opens the delete confirm for them
// (installDeckRailDeleteFallback in apps/web/src/guest/edit-mode.ts).
// Current builds consume the key at the thumb (stopPropagation), so
// the marker is belt-and-braces — it keeps the fallback standing
// down even if a future build lets the key bubble past the thumb.
this._railDeleteKey = true;
// Same contract for skip-aware numbering: copies WITHOUT
// _railSkipNumbers number every thumb 1..N and count skipped slides
// in the overlay total — the bundle rewrites both for those
// (installDeckSkipNumberingFallback in apps/web/src/guest/edit-mode.ts).
// Here the component renumbers natively, so the fallback stands down.
this._railSkipNumbers = true;
this._onKey = this._onKey.bind(this);
this._onResize = this._onResize.bind(this);
this._onSlotChange = this._onSlotChange.bind(this);
this._onMouseMove = this._onMouseMove.bind(this);
this._onTap = this._onTap.bind(this);
this._onMessage = this._onMessage.bind(this);
// Capture-phase close so a click anywhere dismisses the menu, but
// ignore clicks that land inside the menu itself — otherwise the
// capture handler runs before the menu's own (bubble) handler and
// clears _menuIndex out from under it.
this._onDocClick = (e) => {
if (this._menu && e.composedPath && e.composedPath().includes(this._menu)) return;
this._closeMenu();
};
}
get designWidth() {
return parseInt(this.getAttribute('width'), 10) || DESIGN_W_DEFAULT;
}
get designHeight() {
return parseInt(this.getAttribute('height'), 10) || DESIGN_H_DEFAULT;
}
connectedCallback() {
// Presenter-view popup loads deckUrl?_snthumb=...#N for its prev/cur/
// next thumbnails — the rail has no business rendering inside those
// (wrong scale, and it offsets the stage so the thumb shows a gutter).
if (/[?&]_snthumb=/.test(location.search)) this.setAttribute('no-rail', '');
this._render();
this._loadNotes();
this._syncPrintPageRule();
this._ensurePrintSizingMeta();
this._ensureTextWrapDefaults();
window.addEventListener('keydown', this._onKey);
window.addEventListener('resize', this._onResize);
window.addEventListener('mousemove', this._onMouseMove, { passive: true });
window.addEventListener('message', this._onMessage);
window.addEventListener('click', this._onDocClick, true);
this.addEventListener('click', this._onTap);
// Print lays every slide out as its own page, so [data-deck-active]-
// gated entrance styles need the attribute on every slide (not just
// the current one) or their content prints at the hidden base style.
// The transient freeze style lands BEFORE the attributes so any
// attribute-keyed transition fires at 0s (changing transition-
// duration after a transition has started doesn't affect it).
this._onBeforePrint = () => {
this._syncPrintPageRule();
// Self-heal: a departed doc-page may have removed the page-global
// print-sizing meta this deck deferred to at connect time.
this._ensurePrintSizingMeta();
if (this._freezeStyle) this._freezeStyle.remove();
this._freezeStyle = document.createElement('style');
this._freezeStyle.textContent = '*,*::before,*::after{transition-duration:0s !important}';
document.head.appendChild(this._freezeStyle);
this._slides.forEach((s) => s.setAttribute('data-deck-active', ''));
};
this._onAfterPrint = () => {
this._applyIndex({ showOverlay: false, broadcast: false });
if (this._freezeStyle) { this._freezeStyle.remove(); this._freezeStyle = null; }
};
window.addEventListener('beforeprint', this._onBeforePrint);
window.addEventListener('afterprint', this._onAfterPrint);
// Initial collection + layout happens via slotchange, which fires on mount.
this._enableRail();
// Hold the stage hidden until webfonts are ready so the first visible
// paint has the deck's real typography — the :not(:defined) guard in
// the page HTML only covers custom-element upgrade, not font load.
// Capped so a 404'd font URL can't blank the deck indefinitely.
this.setAttribute('data-fonts-pending', '');
const reveal = () => this.removeAttribute('data-fonts-pending');
// Unconditional cap — rAF can be suspended in a hidden iframe, which
// would strand the one inside the rAF callback.
setTimeout(reveal, 2000);
// rAF first: fonts.ready is a pre-resolved promise until layout has
// resolved the slotted text's font-family and pushed a FontFace into
// 'loading'. Reading it here in connectedCallback (parse-time) would
// settle the race in a microtask before any font fetch starts.
requestAnimationFrame(() => {
Promise.race([
document.fonts ? document.fonts.ready : Promise.resolve(),
new Promise((r) => setTimeout(r, 2000)),
]).then(reveal, reveal);
});
}
_enableRail() {
// Idempotent — older host builds still post __omelette_rail_enabled.
// no-rail guard keeps the observers/stylesheet walk off the cheap path
// for presenter-popup thumbnail iframes (three per view — cur/prev/next).
if (this._railEnabled || this.hasAttribute('no-rail')) return;
this._railEnabled = true;
// Per-viewer preference — restored alongside rail width. Default on;
// only a stored '0' (from the TweaksPanel toggle) hides it.
this._railVisible = true;
try {
if (localStorage.getItem('deck-stage.railVisible') === '0') this._railVisible = false;
} catch (e) {}
// Live thumbnail updates: watch the light-DOM slides for content
// edits and re-clone just the affected thumb(s), debounced. Ignore
// the data-deck-* / data-screen-label / data-om-validate attributes
// this component itself writes so nav doesn't trigger spurious
// refreshes — except data-deck-skip, which now arrives from the host
// re-render and is what updates the rail badge, print bookkeeping,
// and deckSkipped re-broadcast. Also ignore data-dc-tpl /
// data-om-slide-id — host-reserved bookkeeping stamps (the host's
// ATTR_RESERVED guard bounds them the same way) that structural
// edits renumber/re-mint on slides whose content didn't change;
// re-cloning on that churn is what made a slide move flash its
// thumbnails.
const OWN_ATTRS = /^data-(deck-(?!skip$)|screen-label$|om-(validate|slide-id)$|dc-tpl$)/;
this._liveDirty = new Set();
this._liveObserver = new MutationObserver((records) => {
for (const r of records) {
if (r.type === 'attributes' && OWN_ATTRS.test(r.attributeName || '')) continue;
let n = r.target;
while (n && n.parentElement !== this) n = n.parentElement;
// Skip/unskip is handled below without re-cloning (the badge sits
// on the thumb wrapper, not the clone) — don't mark the slide
// dirty for an attr change whose only visible effect is the badge.
if (n && this._slideSet && this._slideSet.has(n)
&& !(r.type === 'attributes' && r.attributeName === 'data-deck-skip')) {
this._liveDirty.add(n);
}
// Host-driven skip toggle: sync the rail badge + print + presenter
// skipped-list the way _toggleSkip used to do locally.
if (r.type === 'attributes' && r.attributeName === 'data-deck-skip'
&& n && this._slideSet && this._slideSet.has(n)) {
const i = this._slides.indexOf(n);
if (this._thumbs && this._thumbs[i]) {
if (n.hasAttribute('data-deck-skip')) this._thumbs[i].thumb.setAttribute('data-skip', '');
else this._thumbs[i].thumb.removeAttribute('data-skip');
}
this._markLastVisible();
this._renumberRail();
this._syncCount();
try { window.postMessage({ slideIndexChanged: this._index, deckTotal: this._slides.length, deckSkipped: this._skippedIndices() }, '*'); } catch (e) {}
}
}
if (this._liveDirty.size && !this._liveTimer) {
this._liveTimer = setTimeout(() => {
this._liveTimer = null;
this._liveDirty.forEach((s) => this._refreshThumb(s));
this._liveDirty.clear();
}, 200);
}
});
this._liveObserver.observe(this, {
subtree: true, childList: true, characterData: true, attributes: true,
});
// Lazy thumbnail materialization — clone the slide only when its
// frame scrolls into (or near) the rail viewport. rootMargin gives
// ~4 thumbs of pre-load so fast scrolling doesn't flash blanks.
this._railObserver = new IntersectionObserver((entries) => {
entries.forEach((e) => {
if (e.isIntersecting && e.target.__deckThumb) {
this._materialize(e.target.__deckThumb);
}
});
}, { root: this._rail, rootMargin: '400px 0px' });
// Tweaks typically change CSS vars / attrs OUTSIDE <deck-stage>
// (on <html>, <body>, a wrapper div, or a <style> tag), which
// _liveObserver can't see. Re-snapshot author CSS (constructable
// sheet is shared by reference, so one replaceSync updates every
// thumb shadow root) and re-sync each thumb host's attrs + custom
// properties. In-slide DOM mutations are _liveObserver's job.
// Debounced so slider drags don't thrash.
this._onTweakChange = () => {
clearTimeout(this._tweakTimer);
this._tweakTimer = setTimeout(() => {
this._snapshotAuthorCss();
// One getComputedStyle for the whole batch — each
// getPropertyValue read below reuses the same computed style
// as long as nothing invalidates layout between thumbs.
const cs = getComputedStyle(this);
(this._thumbs || []).forEach((t) => {
if (t.host) this._syncThumbHostAttrs(t.host, cs);
});
}, 120);
};
window.addEventListener('tweakchange', this._onTweakChange);
// Stylesheets that finish loading AFTER the snapshot below never
// reach the thumbs on their own: a still-pending <link> contributes
// nothing to document.styleSheets, and nothing re-reads it on load,
// so the live slides restyle while every clone keeps the stale
// sheet. dc-runtime's helmet mounts design-system <link>s at render
// time, so a deck-stage that connects first snapshots before that
// CSS exists. Funnel late arrivals into the same debounced resync:
// hook load/error on every current <link>, and watch <head> for
// links and styles mounted or rewritten later. Deliberately not
// rAF- or fonts.ready-driven — rAF is throttled/suspended in hidden
// iframes (thumbnail/presenter contexts), and a font-file load
// doesn't change cssRules, so it needs no resync.
this._hookedLinks = [];
this._hookSheetLoad = (el) => {
if (!el.matches || !el.matches('link[rel~="stylesheet" i]')) return;
if (this._hookedLinks.indexOf(el) !== -1) return;
this._hookedLinks.push(el);
el.addEventListener('load', this._onTweakChange);
el.addEventListener('error', this._onTweakChange);
};
document.querySelectorAll('link[rel~="stylesheet" i]')
.forEach(this._hookSheetLoad);
this._headObserver = new MutationObserver((records) => {
let resync = false;
for (const r of records) {
if (r.type === 'characterData') {
// Only <style> text is CSS — a ticking <title> shouldn't
// wake the resync forever.
const p = r.target.parentNode;
if (p && p.nodeName === 'STYLE') resync = true;
continue;
}
if (r.type === 'attributes') {
// A late rel/href rewrite turns an inert <link> into a
// stylesheet (hook it; its load fires even on cache hits);
// a media/disabled flip changes effective rules with no
// event. Resync only if this link is or ever was a
// stylesheet — favicon/preload/canonical href churn isn't
// a resync.
if (r.target.nodeName === 'LINK') {
this._hookSheetLoad(r.target);
if (this._hookedLinks.indexOf(r.target) !== -1) resync = true;
} else if (r.target.nodeName === 'STYLE') resync = true;
continue;
}
// childList: only links and styles carry CSS. A new <link> has
// no rules until it loads — hook it rather than resync now; a
// <style> mount/unmount or text-node swap takes effect
// immediately. _freezeStyle (our beforeprint helper) is skipped
// on add only — no removal-side guard: _onAfterPrint nulls the
// ref before the observer fires, so that check would be dead;
// the one debounced no-op resync per print is harmless.
if (r.target.nodeName === 'STYLE') resync = true;
for (const n of r.addedNodes) {
if (n.nodeName === 'LINK') this._hookSheetLoad(n);
else if (n.nodeName === 'STYLE' && n !== this._freezeStyle) resync = true;
}
for (const n of r.removedNodes) {
if (n.nodeName === 'LINK') {
const hi = this._hookedLinks.indexOf(n);
if (hi !== -1) {
this._hookedLinks.splice(hi, 1);
n.removeEventListener('load', this._onTweakChange);
n.removeEventListener('error', this._onTweakChange);
resync = true;
}
} else if (n.nodeName === 'STYLE') resync = true;
}
}
if (resync) this._onTweakChange();
});
this._headObserver.observe(document.head, {
childList: true, subtree: true, characterData: true,
attributes: true, attributeFilter: ['rel', 'href', 'media', 'disabled'],
});
this._snapshotAuthorCss();
// Re-snapshot once any still-loading stylesheet settles — it throws on
// .cssRules above and silently contributes '' → unstyled thumbs on a
// cold mount. {once:true}; routed through the debounced handler.
document.querySelectorAll('link[rel~="stylesheet"]').forEach((l) => {
try { if (l.sheet && l.sheet.cssRules) return; } catch (e) {}
l.addEventListener('load', this._onTweakChange, { once: true });
l.addEventListener('error', this._onTweakChange, { once: true });
});
if (document.fonts) document.fonts.ready.then(this._onTweakChange, this._onTweakChange);
// Build the rail now that it's enabled — slotchange already fired,
// so _renderRail's early-return skipped the initial build.
this._syncRailHidden();
this._renderRail();
this._fit();
}
/** Snapshot document stylesheets into a constructable sheet that each
* thumbnail's nested shadow root adopts — so author CSS styles the
* cloned slide content without touching this component's chrome.
* Cross-origin sheets throw on .cssRules — skip them. Re-callable:
* the existing constructable sheet is reused via replaceSync so every
* already-adopted shadow root picks up the fresh CSS without re-adopt. */
_snapshotAuthorCss() {
// :root in an adopted sheet inside a shadow root matches nothing
// (only the document root qualifies), so author rules like
// `:root[data-voice="modern"] .serif` never reach the clones.
// Rewrite :root → :host and mirror <html>'s data-*/class/lang onto
// each thumb host (see _syncThumbHostAttrs) so the same selectors
// match inside the thumbnail's shadow tree.
const authorCss = Array.from(document.styleSheets).map((sh) => {
try {
return Array.from(sh.cssRules).map((r) => r.cssText).join('\n');
} catch (e) { return ''; }
}).join('\n')
// The shadow host is featureless outside the functional :host(...)
// form, so any compound on :root — [attr], .class, #id, :pseudo —
// must become :host(<compound>) not :host<compound>. Same for the
// html type selector (Tailwind class-strategy dark mode emits
// html.dark; Pico uses html[data-theme]), which has nothing to
// match inside the thumb's shadow tree.
.replace(/:root((?:\[[^\]]*\]|[.#][-\w]+|:[-\w]+(?:\([^)]*\))?)+)/g, ':host($1)')
.replace(/:root\b/g, ':host')
.replace(/(^|[\s,>~+(}])html((?:\[[^\]]*\]|[.#][-\w]+|:[-\w]+(?:\([^)]*\))?)+)(?![-\w])/g, '$1:host($2)')
.replace(/(^|[\s,>~+(}])html(?![-\w])/g, '$1:host');
// Every custom property the author references. _syncThumbHostAttrs
// mirrors each one's *computed* value at <deck-stage> onto the
// thumb host so the live value wins over the :host default above
// regardless of which ancestor the tweak wrote to (<html>, <body>,
// a wrapper div, or the deck-stage element itself all inherit
// down to getComputedStyle(this)).
this._authorVars = new Set(authorCss.match(/--[\w-]+/g) || []);
try {
if (!this._adoptedSheet) this._adoptedSheet = new CSSStyleSheet();
this._adoptedSheet.replaceSync(authorCss);
} catch (e) {
this._adoptedSheet = null;
this._authorCss = authorCss;
}
}
_syncThumbHostAttrs(host, cs) {
const de = document.documentElement;
// setAttribute overwrites but can't delete — an attr removed from