@plusguard/reels 0.0.0-stage → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1212 @@
1
+ /*
2
+ * reels — shoppable reels for a store: a strip of video cards on the page,
3
+ * each card a group of clips, each clip with its own product.
4
+ *
5
+ * <section data-pg-reels>
6
+ * <button data-pg-reels-prev aria-controls="strip">‹</button>
7
+ * <div data-pg-reels-strip id="strip">
8
+ * <article data-pg-reels-group>
9
+ * <div data-pg-reels-card> the 9:16 card
10
+ * <figure data-pg-reels-clip> a clip: a video…
11
+ * <video src="a.mp4" poster="a.jpg" muted playsinline preload="none"></video>
12
+ * </figure>
13
+ * <figure data-pg-reels-clip data-pg-reels-duration="5s">
14
+ * <img src="b.jpg" alt="" /> …or a picture, for a while
15
+ * </figure>
16
+ * <button data-pg-reels-sound aria-pressed="false">…</button>
17
+ * <button data-pg-reels-open>…</button>
18
+ * </div>
19
+ * <div data-pg-reels-bars></div> filled here: a bar per clip
20
+ * <div data-pg-reels-products> one per clip, in order
21
+ * <a data-pg-reels-product href="/a">…</a>
22
+ * <a data-pg-reels-product href="/b">…</a>
23
+ * </div>
24
+ * </article>
25
+ * </div>
26
+ * <button data-pg-reels-next aria-controls="strip">›</button>
27
+ * </section>
28
+ *
29
+ * On the page: every card in sight plays, muted until its sound button is
30
+ * pressed (sound is one card's alone: another card's button pressed gives
31
+ * it to that card; the card going out of sight takes it away) — its clips
32
+ * one after another, round and round, as stories do, a picture for its
33
+ * data-pg-reels-duration;
34
+ * the bars under it fill as each plays. A bar pressed is that clip at
35
+ * once. The clip playing shows its product: the products under the card
36
+ * are one per clip, and only the playing one's shows. The others wait on
37
+ * their posters. Out of sight, nothing plays.
38
+ *
39
+ * The strip scrolls sideways — a finger, a wheel, its arrows; it never
40
+ * moves by itself. data-pg-reels-start / -end on the section while it
41
+ * stands at either end (the arrows' to hide or dim).
42
+ *
43
+ * A card pressed — anywhere but its own buttons and links — or its
44
+ * data-pg-reels-open: the full view opens on that group and clip. First
45
+ * the event pg-reels:open on the section (detail: group, clip); a site
46
+ * that calls preventDefault() on it opens its own.
47
+ *
48
+ * The full view — a <dialog>, built here on <body>, its contents copies:
49
+ * the clip playing, the group's data-pg-reels-head, the clip's product.
50
+ * Within a group: the bars on top, a press on the video's right or left,
51
+ * → and ←. Between groups: a finger (or the mouse) dragging the video up
52
+ * or down — it follows, the next group coming in under it, and let go
53
+ * goes on or back — its ↑ and ↓ buttons, a wheel, ↑ and ↓; after a
54
+ * group's last clip, the next group. The product changes once it has
55
+ * landed. Held
56
+ * down — a finger, the mouse — it stands still; its own play / pause, its
57
+ * sound, its close — under the close; left of it, the group's view count
58
+ * (its data-pg-reels-views, the site's). Esc, Back, the dark around it
59
+ * close it too. The
60
+ * product: on a computer a panel beside the video — the product's
61
+ * <template data-pg-reels-detail>, the site's markup: a title (its
62
+ * data-pg-reels-title goes to the panel's head, beside the close), a big
63
+ * picture (data-pg-reels-big), small ones (data-pg-reels-thumb, a press
64
+ * shows it big), variants (data-pg-reels-variant buttons: each its
65
+ * price, its gallery — data-pg-reels-gallery of the same name — and its
66
+ * link), the price, a link (its data-pg-reels-foot is pinned to
67
+ * the panel's foot, the rest scrolling above it) — on a phone under the
68
+ * video, the product as on the card, and its details opened by a button.
69
+ *
70
+ * Marks written here: data-pg-reels-current on the playing clip and its
71
+ * product, on each group's own clip and product too; data-pg-reels-playing
72
+ * on the group that plays; aria-current on its bar, data-pg-reels-done on
73
+ * the bars before it, and --pg-reels-progress (0 to 1) on the bar playing.
74
+ *
75
+ * Seen: a group whose every clip has been shown in the full view is seen —
76
+ * data-pg-reels-seen="true" on it ("false" before), for its ring to go
77
+ * pale as stories' do; for --pg-reels-seen-for (24h by default), then
78
+ * bright again; --pg-reels-seen: off and never. With a data-pg-reels-id on
79
+ * the group it is remembered in this browser; forgetReelsSeen() forgets it
80
+ * all — every ring bright again, at once.
81
+ *
82
+ * CSS, per screen size: --pg-reels-show (cards across: 4; 1.5 on a phone
83
+ * shows one and half the next), --pg-reels-gap, --pg-reels-duration (a
84
+ * picture's time, 5s) — see index.css.
85
+ *
86
+ * With reduced motion asked for, nothing plays by itself: the posters, and
87
+ * a bar pressed shows its clip. React's markup is never moved: the bars go
88
+ * into the empty data-pg-reels-bars; everything else only gets marks.
89
+ *
90
+ * No dependencies.
91
+ */
92
+ const ROOT = "data-pg-reels";
93
+ const STRIP = "data-pg-reels-strip";
94
+ const GROUP = "data-pg-reels-group";
95
+ const CARD = "data-pg-reels-card";
96
+ const CLIP = "data-pg-reels-clip";
97
+ const BARS = "data-pg-reels-bars";
98
+ const BAR = "data-pg-reels-bar";
99
+ const PRODUCT = "data-pg-reels-product";
100
+ const CURRENT = "data-pg-reels-current";
101
+ const PLAYING = "data-pg-reels-playing";
102
+ const DONE = "data-pg-reels-done";
103
+ const DURATION = "data-pg-reels-duration";
104
+ const SOUND = "data-pg-reels-sound";
105
+ const SOUND_ON = "data-pg-reels-sound-on";
106
+ const OPEN = "data-pg-reels-open";
107
+ const PREV = "data-pg-reels-prev";
108
+ const NEXT = "data-pg-reels-next";
109
+ const START = "data-pg-reels-start";
110
+ const END = "data-pg-reels-end";
111
+ const PROGRESS = "--pg-reels-progress";
112
+ const HEAD = "data-pg-reels-head";
113
+ const DETAIL = "data-pg-reels-detail";
114
+ const BIG = "data-pg-reels-big";
115
+ const THUMB = "data-pg-reels-thumb";
116
+ const VIEWER = "data-pg-reels-viewer";
117
+ const VIEW_BAR = "data-pg-reels-view-bar";
118
+ const PAUSED = "data-pg-reels-paused";
119
+ const HELD = "data-pg-reels-held";
120
+ const DETAILS = "data-pg-reels-details";
121
+ const NO_PRODUCT = "data-pg-reels-no-product";
122
+ const TITLE = "data-pg-reels-title";
123
+ const FOOT = "data-pg-reels-foot";
124
+ const ID = "data-pg-reels-id";
125
+ const VIEWS = "data-pg-reels-views";
126
+ const VARIANT = "data-pg-reels-variant";
127
+ const VARIANT_PRICE = "data-pg-reels-variant-price";
128
+ const VARIANT_HREF = "data-pg-reels-variant-href";
129
+ const GALLERY = "data-pg-reels-gallery";
130
+ const PRICE = "data-pg-reels-price";
131
+ const SEEN = "data-pg-reels-seen";
132
+ const SEEN_KEY = "pg-reels-seen";
133
+ const SLIDING = "data-pg-reels-sliding";
134
+ /* A finger this far up or down, more than across: the video follows it. */
135
+ const DRAG_PX = 10;
136
+ /* Let go this fast (px a ms) the way it was going: on, however short. */
137
+ const FLICK = 0.45;
138
+ /* Held this long, a press stops it — not a tap. */
139
+ const HOLD_MS = 220;
140
+ /* A wheel's turn this far is a step; then a pause before the next. */
141
+ const WHEEL_PX = 60;
142
+ const WHEEL_REST_MS = 700;
143
+ /* A picture's time when nothing says. */
144
+ const PICTURE_MS = 5000;
145
+ /* In sight enough to play: this much of the card. */
146
+ const IN_SIGHT = 0.6;
147
+ const px = (value) => parseFloat(value) || 0;
148
+ /* A time — seconds or ms written — in ms. */
149
+ function timeOf(raw, fallback) {
150
+ const text = (raw ?? "").trim();
151
+ const n = Number.parseFloat(text);
152
+ if (!Number.isFinite(n))
153
+ return fallback;
154
+ return Math.max(0, text.endsWith("ms") ? n : n * 1000);
155
+ }
156
+ const reduced = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
157
+ const videoOf = (clip) => clip?.querySelector("video") ?? null;
158
+ /* A picture's time: its own data-pg-reels-duration, or the page's
159
+ --pg-reels-duration, or 5s. */
160
+ function pictureTime(g, clip) {
161
+ const own = clip.getAttribute(DURATION);
162
+ if (own)
163
+ return timeOf(own, PICTURE_MS);
164
+ return timeOf(getComputedStyle(g.el).getPropertyValue("--pg-reels-duration"), PICTURE_MS);
165
+ }
166
+ /* ---------- Sound ----------
167
+ One sound at a time: the playing card's, or the full view's. */
168
+ let sound = false;
169
+ /* ---------- Copies for the full view ---------- */
170
+ /* A copy of the site's markup for the full view: no ids — they stay
171
+ unique — and none of this file's marks. */
172
+ function copyOf(el) {
173
+ const copy = el.cloneNode(true);
174
+ [copy, ...copy.querySelectorAll("*")].forEach((x) => {
175
+ x.removeAttribute("id");
176
+ [CURRENT, PLAYING, DONE].forEach((name) => x.removeAttribute(name));
177
+ });
178
+ copy.querySelectorAll(`[${DETAIL}]`).forEach((t) => t.remove());
179
+ return copy;
180
+ }
181
+ const svg = (paths) => `<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${paths}</svg>`;
182
+ const ICONS = {
183
+ soundOff: '<path d="M4 9h4l5-4v14l-5-4H4zM17 9l5 6M22 9l-5 6"/>',
184
+ soundOn: '<path d="M4 9h4l5-4v14l-5-4H4zM17 8.5a5 5 0 0 1 0 7M19.5 6a8.5 8.5 0 0 1 0 12"/>',
185
+ pause: '<path d="M8 5v14M16 5v14"/>',
186
+ play: '<path d="M7 5v14l12-7z"/>',
187
+ close: '<path d="M6 6l12 12M18 6 6 18"/>',
188
+ up: '<path d="M12 19V5M5 12l7-7 7 7"/>',
189
+ down: '<path d="M12 5v14M19 12l-7 7-7-7"/>',
190
+ chevron: '<path d="m6 15 6-6 6 6"/>',
191
+ };
192
+ /* ---------- One group ---------- */
193
+ function partsOf(el, root) {
194
+ const own = (x) => x.closest(`[${GROUP}]`) === el;
195
+ const clips = [...el.querySelectorAll(`[${CLIP}]`)].filter(own);
196
+ const products = [...el.querySelectorAll(`[${PRODUCT}]`)].filter(own);
197
+ const holder = [...el.querySelectorAll(`[${BARS}]`)].find(own);
198
+ // One bar a clip — made here, in the empty holder, once.
199
+ let bars = [];
200
+ if (holder) {
201
+ if (holder.children.length !== clips.length) {
202
+ holder.replaceChildren(...clips.map((_, i) => {
203
+ const bar = document.createElement("button");
204
+ bar.type = "button";
205
+ bar.setAttribute(BAR, "");
206
+ bar.setAttribute("aria-label", `Clip ${i + 1} of ${clips.length}`);
207
+ bar.append(document.createElement("span"));
208
+ return bar;
209
+ }));
210
+ }
211
+ bars = [...holder.children];
212
+ }
213
+ const current = clips.findIndex((c) => c.hasAttribute(CURRENT));
214
+ return { el, root, clips, products, bars, at: Math.max(0, current), ratio: 0, shown: 0, since: 0 };
215
+ }
216
+ /* Show clip `i` of the group: its clip, its product, its bar. */
217
+ function show(g, i) {
218
+ const n = g.clips.length;
219
+ if (!n)
220
+ return;
221
+ const was = g.clips[g.at];
222
+ if (was && g.at !== i) {
223
+ const v = videoOf(was);
224
+ if (v) {
225
+ v.pause();
226
+ v.currentTime = 0;
227
+ }
228
+ }
229
+ g.at = ((i % n) + n) % n;
230
+ g.shown = 0;
231
+ g.since = performance.now();
232
+ g.clips.forEach((c, k) => c.toggleAttribute(CURRENT, k === g.at));
233
+ g.products.forEach((p, k) => p.toggleAttribute(CURRENT, k === g.at));
234
+ g.bars.forEach((b, k) => {
235
+ b.toggleAttribute(DONE, k < g.at);
236
+ if (k === g.at)
237
+ b.setAttribute("aria-current", "true");
238
+ else
239
+ b.removeAttribute("aria-current");
240
+ b.style.setProperty(PROGRESS, k < g.at ? "1" : "0");
241
+ });
242
+ }
243
+ /* ---------- Seen, kept in this browser ----------
244
+ A group is seen once every one of its clips has been shown in the full
245
+ view. Set on the section or above:
246
+ --pg-reels-seen all (default) · off: the rings never go pale
247
+ --pg-reels-seen-for how long it stays seen: 24h (default), 1h, 30m,
248
+ 7d — then bright again; forever: until forgotten */
249
+ // Groups with a data-pg-reels-id: in localStorage, as { id: when }.
250
+ // Without: this visit only.
251
+ const seenHere = new WeakMap();
252
+ const SEEN_FOR_DEFAULT = 24 * 60 * 60 * 1000;
253
+ function seenMap() {
254
+ try {
255
+ const kept = JSON.parse(localStorage.getItem(SEEN_KEY) || "{}");
256
+ // An older list of ids: seen now.
257
+ if (Array.isArray(kept))
258
+ return Object.fromEntries(kept.map((id) => [String(id), Date.now()]));
259
+ return kept && typeof kept === "object" ? kept : {};
260
+ }
261
+ catch {
262
+ return {};
263
+ }
264
+ }
265
+ /* "24h", "30m", "90s", "500ms", "7d" → ms; "forever" → Infinity. */
266
+ function spanOf(raw) {
267
+ const text = raw.trim().toLowerCase();
268
+ if (!text)
269
+ return SEEN_FOR_DEFAULT;
270
+ if (text === "forever" || text === "none")
271
+ return Infinity;
272
+ const m = /^(-?[\d.]+)\s*(ms|s|m|h|d)?$/.exec(text);
273
+ if (!m)
274
+ return SEEN_FOR_DEFAULT;
275
+ const n = Number(m[1]);
276
+ const unit = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 }[(m[2] ?? "ms")];
277
+ return Number.isFinite(n) ? Math.max(0, n * unit) : SEEN_FOR_DEFAULT;
278
+ }
279
+ function seenRules(el) {
280
+ const cs = getComputedStyle(el);
281
+ return {
282
+ off: cs.getPropertyValue("--pg-reels-seen").trim() === "off",
283
+ span: spanOf(cs.getPropertyValue("--pg-reels-seen-for")),
284
+ };
285
+ }
286
+ function isSeen(el, map = seenMap()) {
287
+ const { off, span } = seenRules(el);
288
+ if (off)
289
+ return false;
290
+ const id = el.getAttribute(ID);
291
+ const when = id ? map[id] : seenHere.get(el);
292
+ return typeof when === "number" && Date.now() - when < span;
293
+ }
294
+ function markSeen(el) {
295
+ if (seenRules(el).off)
296
+ return;
297
+ const id = el.getAttribute(ID);
298
+ if (!id)
299
+ seenHere.set(el, Date.now());
300
+ else {
301
+ const map = seenMap();
302
+ map[id] = Date.now();
303
+ try {
304
+ localStorage.setItem(SEEN_KEY, JSON.stringify(map));
305
+ }
306
+ catch {
307
+ // Private mode, or storage full: seen for this visit only.
308
+ seenHere.set(el, Date.now());
309
+ }
310
+ }
311
+ paintSeen();
312
+ }
313
+ function paintSeen() {
314
+ const map = seenMap();
315
+ document.querySelectorAll(`[${GROUP}]`).forEach((el) => {
316
+ const value = String(isSeen(el, map));
317
+ if (el.getAttribute(SEEN) !== value)
318
+ el.setAttribute(SEEN, value);
319
+ });
320
+ }
321
+ /* Forget what was seen, in this browser: every ring bright again, at once
322
+ — no reload. */
323
+ export function forgetReelsSeen() {
324
+ try {
325
+ localStorage.removeItem(SEEN_KEY);
326
+ }
327
+ catch {
328
+ // Storage blocked: nothing kept, nothing to forget.
329
+ }
330
+ document.querySelectorAll(`[${GROUP}]`).forEach((el) => seenHere.delete(el));
331
+ watched = new WeakMap();
332
+ paintSeen();
333
+ }
334
+ // The clips of each group shown in the full view so far, this visit.
335
+ let watched = new WeakMap();
336
+ /* ---------- Everything on the page ---------- */
337
+ let live = null;
338
+ /* Start watching every reels section on the page, those rendered later
339
+ too; returns the cleanup for a React effect. Only the newest call
340
+ answers. */
341
+ export function initReels() {
342
+ if (typeof document === "undefined")
343
+ return () => { };
344
+ const self = {};
345
+ live = self;
346
+ const groups = new Map();
347
+ // The groups playing: every one in sight.
348
+ const playing = new Set();
349
+ let frame = 0;
350
+ // Which groups play: every one at least IN_SIGHT in sight.
351
+ const sights = typeof IntersectionObserver === "undefined"
352
+ ? null
353
+ : new IntersectionObserver((entries) => {
354
+ entries.forEach((e) => {
355
+ const g = groups.get(e.target.closest(`[${GROUP}]`));
356
+ if (g)
357
+ g.ratio = e.isIntersecting ? e.intersectionRatio : 0;
358
+ });
359
+ choose();
360
+ }, { threshold: [0, 0.25, 0.5, 0.6, 0.75, 0.9, 1] });
361
+ const choose = () => {
362
+ if (live !== self || view.open)
363
+ return;
364
+ let changed = false;
365
+ groups.forEach((g) => {
366
+ const on = g.ratio >= IN_SIGHT;
367
+ if (on === playing.has(g))
368
+ return;
369
+ changed = true;
370
+ if (on) {
371
+ playing.add(g);
372
+ start(g);
373
+ }
374
+ else {
375
+ playing.delete(g);
376
+ stop(g);
377
+ }
378
+ });
379
+ // The card with the sound gone out of sight: the sound goes too.
380
+ if (sound && (!owner || !playing.has(owner))) {
381
+ sound = false;
382
+ changed = true;
383
+ }
384
+ if (changed)
385
+ applySound();
386
+ };
387
+ const stopAll = () => {
388
+ playing.forEach(stop);
389
+ playing.clear();
390
+ };
391
+ // The group whose sound button turned it on — or the one last seen in
392
+ // the full view.
393
+ let owner = null;
394
+ const applySound = () => {
395
+ groups.forEach((g) => {
396
+ const on = sound && !view.open && g === owner && playing.has(g);
397
+ g.clips.forEach((c) => {
398
+ const v = videoOf(c);
399
+ if (v)
400
+ v.muted = !on;
401
+ });
402
+ g.el.querySelectorAll(`[${SOUND}]`).forEach((b) => b.setAttribute("aria-pressed", String(on)));
403
+ });
404
+ document.querySelectorAll(`[${ROOT}]`).forEach((r) => r.toggleAttribute(SOUND_ON, sound && !view.open && !!owner && playing.has(owner) && owner.root === r));
405
+ const v = viewVideo();
406
+ if (v)
407
+ v.muted = !sound;
408
+ dialog.querySelector(`[${SOUND}]`)?.setAttribute("aria-pressed", String(sound && view.open));
409
+ };
410
+ const start = (g) => {
411
+ g.el.setAttribute(PLAYING, "");
412
+ if (reduced())
413
+ return;
414
+ const clip = g.clips[g.at];
415
+ const v = videoOf(clip);
416
+ g.since = performance.now();
417
+ if (v) {
418
+ v.muted = !(sound && g === owner);
419
+ v.preload = "auto";
420
+ v.play().catch(() => { });
421
+ }
422
+ tick();
423
+ };
424
+ const stop = (g) => {
425
+ g.el.removeAttribute(PLAYING);
426
+ const clip = g.clips[g.at];
427
+ videoOf(clip)?.pause();
428
+ // A picture keeps the time it has shown.
429
+ g.shown += performance.now() - g.since;
430
+ };
431
+ // One frame loop for every group that plays: its bar fills; a picture
432
+ // whose time is up — data-pg-reels-duration, --pg-reels-duration — or
433
+ // a video ended, is the next clip.
434
+ const tick = () => {
435
+ if (frame)
436
+ return;
437
+ frame = requestAnimationFrame(function step(now) {
438
+ frame = 0;
439
+ if (live !== self || !playing.size || reduced())
440
+ return;
441
+ const due = [];
442
+ playing.forEach((g) => {
443
+ const clip = g.clips[g.at];
444
+ const v = videoOf(clip);
445
+ let progress;
446
+ if (v)
447
+ progress = v.duration ? v.currentTime / v.duration : 0;
448
+ else
449
+ progress = (g.shown + now - g.since) / Math.max(1, pictureTime(g, clip));
450
+ g.bars[g.at]?.style.setProperty(PROGRESS, String(Math.min(1, progress)));
451
+ if (!v && progress >= 1)
452
+ due.push(g);
453
+ });
454
+ // The loop goes on first: next() asks for it too, and is
455
+ // answered by this one.
456
+ frame = requestAnimationFrame(step);
457
+ due.forEach(next);
458
+ });
459
+ };
460
+ const next = (g) => {
461
+ show(g, g.at + 1);
462
+ if (playing.has(g))
463
+ start(g);
464
+ };
465
+ // A video that ends: the next clip.
466
+ const onEnded = (event) => {
467
+ const clip = event.target.closest(`[${CLIP}]`);
468
+ const g = clip && groups.get(clip.closest(`[${GROUP}]`));
469
+ if (g && g.clips[g.at] === clip)
470
+ next(g);
471
+ };
472
+ // The strip's ends: data-pg-reels-start / -end on the section.
473
+ const ends = (root) => {
474
+ const strip = root.querySelector(`[${STRIP}]`);
475
+ if (!strip)
476
+ return;
477
+ root.toggleAttribute(START, strip.scrollLeft <= 1);
478
+ root.toggleAttribute(END, strip.scrollLeft + strip.clientWidth >= strip.scrollWidth - 1);
479
+ };
480
+ const onScroll = (event) => {
481
+ const strip = event.target;
482
+ if (strip instanceof HTMLElement && strip.hasAttribute(STRIP))
483
+ ends(strip.closest(`[${ROOT}]`));
484
+ };
485
+ // Look round the page: every group, its parts.
486
+ const look = () => {
487
+ if (live !== self)
488
+ return;
489
+ const now = new Set();
490
+ document.querySelectorAll(`[${ROOT}]`).forEach((root) => {
491
+ root.querySelectorAll(`[${GROUP}]`).forEach((el) => {
492
+ if (el.closest(`[${ROOT}]`) !== root)
493
+ return;
494
+ now.add(el);
495
+ if (groups.has(el))
496
+ return;
497
+ const g = partsOf(el, root);
498
+ groups.set(el, g);
499
+ show(g, g.at);
500
+ const card = el.querySelector(`[${CARD}]`) ?? el;
501
+ sights?.observe(card);
502
+ });
503
+ ends(root);
504
+ });
505
+ paintSeen();
506
+ groups.forEach((g, el) => {
507
+ if (now.has(el))
508
+ return;
509
+ if (playing.has(g)) {
510
+ stop(g);
511
+ playing.delete(g);
512
+ }
513
+ groups.delete(el);
514
+ });
515
+ applySound();
516
+ if (!sights) {
517
+ // No observer: the first plays.
518
+ const first = groups.values().next().value;
519
+ if (first && !playing.size) {
520
+ first.ratio = 1;
521
+ choose();
522
+ }
523
+ }
524
+ };
525
+ // Presses: a bar, the sound, the arrows, the card.
526
+ const onClick = (event) => {
527
+ if (live !== self || !(event.target instanceof Element))
528
+ return;
529
+ const t = event.target;
530
+ const bar = t.closest(`[${BAR}]`);
531
+ if (bar) {
532
+ const g = groups.get(bar.closest(`[${GROUP}]`));
533
+ if (!g)
534
+ return;
535
+ const was = playing.has(g);
536
+ show(g, g.bars.indexOf(bar));
537
+ if (was)
538
+ start(g);
539
+ return;
540
+ }
541
+ const soundButton = t.closest(`[${SOUND}]`);
542
+ if (soundButton) {
543
+ const g = groups.get(soundButton.closest(`[${GROUP}]`));
544
+ if (!g || view.open)
545
+ sound = !sound;
546
+ // The card with the sound: off. Another card's: the sound is
547
+ // that card's — it plays, the others are muted.
548
+ else if (g === owner && sound)
549
+ sound = false;
550
+ else {
551
+ if (!playing.has(g)) {
552
+ playing.add(g);
553
+ start(g);
554
+ }
555
+ sound = true;
556
+ owner = g;
557
+ }
558
+ applySound();
559
+ return;
560
+ }
561
+ const arrow = t.closest(`[${PREV}], [${NEXT}]`);
562
+ if (arrow) {
563
+ const id = arrow.getAttribute("aria-controls");
564
+ const strip = (id ? document.getElementById(id) : null) ?? arrow.closest(`[${ROOT}]`)?.querySelector(`[${STRIP}]`);
565
+ const first = strip?.querySelector(`[${GROUP}]`);
566
+ if (!strip || !first)
567
+ return;
568
+ const gap = px(getComputedStyle(strip).columnGap);
569
+ const by = first.getBoundingClientRect().width + gap;
570
+ strip.scrollBy({ left: arrow.hasAttribute(NEXT) ? by : -by, behavior: reduced() ? "instant" : "smooth" });
571
+ return;
572
+ }
573
+ // The card — not a link or a button of its own — or its open
574
+ // button: the full view's to show.
575
+ const openButton = t.closest(`[${OPEN}]`);
576
+ const card = t.closest(`[${CARD}]`);
577
+ if (!openButton && (!card || t.closest("a, button, input, select, textarea")))
578
+ return;
579
+ const groupEl = (openButton ?? card).closest(`[${GROUP}]`);
580
+ const g = groupEl && groups.get(groupEl);
581
+ if (!g)
582
+ return;
583
+ const asked = new CustomEvent("pg-reels:open", { bubbles: true, cancelable: true, detail: { group: g.el, clip: g.at } });
584
+ if (g.root.dispatchEvent(asked))
585
+ openView(g, g.at);
586
+ };
587
+ /* ---------- The full view ---------- */
588
+ const dialog = document.createElement("dialog");
589
+ dialog.setAttribute(VIEWER, "");
590
+ dialog.setAttribute("aria-label", "Reels");
591
+ dialog.setAttribute("data-lenis-prevent", "");
592
+ // Opened, the focus is the view's own — not its first button's: the
593
+ // keys work at once, no ring on a button nobody chose.
594
+ dialog.tabIndex = -1;
595
+ dialog.innerHTML = `
596
+ <div data-pg-reels-stage>
597
+ <div data-pg-reels-feed>
598
+ <div data-pg-reels-view-peek="before" aria-hidden="true" hidden></div>
599
+ <div data-pg-reels-screen>
600
+ <div data-pg-reels-view-media></div>
601
+ <button type="button" data-pg-reels-view-back tabindex="-1" aria-label="Previous clip"></button>
602
+ <button type="button" data-pg-reels-view-on tabindex="-1" aria-label="Next clip"></button>
603
+ <div data-pg-reels-view-top>
604
+ <div data-pg-reels-view-bars></div>
605
+ <div data-pg-reels-view-row>
606
+ <div data-pg-reels-view-head></div>
607
+ <div data-pg-reels-view-tools>
608
+ <div data-pg-reels-view-views></div>
609
+ <button type="button" data-pg-reels-view-close aria-label="Close">${svg(ICONS.close)}</button>
610
+ <button type="button" ${SOUND} aria-pressed="false" aria-label="Sound">${svg(ICONS.soundOff)}${svg(ICONS.soundOn)}</button>
611
+ <button type="button" data-pg-reels-view-play aria-label="Pause">${svg(ICONS.pause)}${svg(ICONS.play)}</button>
612
+ </div>
613
+ </div>
614
+ </div>
615
+ </div>
616
+ <button type="button" data-pg-reels-view-peek="after" tabindex="-1" aria-label="Next reel" hidden></button>
617
+ </div>
618
+ <div data-pg-reels-view-steps>
619
+ <button type="button" data-pg-reels-view-up aria-label="Previous reel">${svg(ICONS.up)}</button>
620
+ <button type="button" data-pg-reels-view-down aria-label="Next reel">${svg(ICONS.down)}</button>
621
+ </div>
622
+ <aside data-pg-reels-panel>
623
+ <div data-pg-reels-panel-head>
624
+ <div data-pg-reels-panel-title></div>
625
+ <button type="button" data-pg-reels-panel-close aria-label="Close">${svg(ICONS.close)}</button>
626
+ </div>
627
+ <div data-pg-reels-panel-band>
628
+ <div data-pg-reels-panel-summary></div>
629
+ <button type="button" data-pg-reels-panel-toggle aria-expanded="false">Details ${svg(ICONS.chevron)}</button>
630
+ </div>
631
+ <div data-pg-reels-panel-detail></div>
632
+ <div data-pg-reels-panel-foot></div>
633
+ </aside>
634
+ </div>`;
635
+ const part = (name) => dialog.querySelector(`[data-pg-reels-${name}]`);
636
+ const media = part("view-media");
637
+ const feed = part("feed");
638
+ const screen = part("screen");
639
+ const before = dialog.querySelector('[data-pg-reels-view-peek="before"]');
640
+ const after = dialog.querySelector('[data-pg-reels-view-peek="after"]');
641
+ const viewBars = part("view-bars");
642
+ const playButton = part("view-play");
643
+ const upButton = part("view-up");
644
+ const downButton = part("view-down");
645
+ const toggle = part("panel-toggle");
646
+ document.body.append(dialog);
647
+ // The band at a phone's foot, its height for the site:
648
+ // --pg-reels-band on the view, 0 where the product is beside it.
649
+ const band = part("panel-band");
650
+ const panel = part("panel");
651
+ const bandSize = new ResizeObserver(() => {
652
+ const cs = getComputedStyle(panel);
653
+ const h = band.offsetHeight ? band.offsetHeight + px(cs.paddingTop) + px(cs.paddingBottom) : 0;
654
+ dialog.style.setProperty("--pg-reels-band", `${h}px`);
655
+ });
656
+ bandSize.observe(band);
657
+ const view = {
658
+ open: false,
659
+ list: [],
660
+ gi: 0,
661
+ ci: 0,
662
+ paused: false,
663
+ // Held down, dragged, sliding: standing still for now.
664
+ held: false,
665
+ shown: 0,
666
+ since: 0,
667
+ pushed: false,
668
+ frame: 0,
669
+ };
670
+ const viewVideo = () => media.querySelector("video");
671
+ const current = () => view.list[view.gi];
672
+ let headOf = null;
673
+ // A group's first clip, for the video above or under the one shown:
674
+ // a picture, or a video on its poster — never playing.
675
+ const peekOf = (holder, g) => {
676
+ holder.replaceChildren(...(g ? [copyOf(g.clips[0])] : []));
677
+ holder.hidden = !g;
678
+ holder.querySelectorAll("video").forEach((x) => {
679
+ x.muted = true;
680
+ x.preload = "none";
681
+ x.removeAttribute("autoplay");
682
+ });
683
+ };
684
+ // Show the view's clip, with its head, its bars, its product — and the
685
+ // groups above and under it, ready to slide in.
686
+ const render = () => {
687
+ const g = current();
688
+ const n = g.clips.length;
689
+ const clip = g.clips[view.ci];
690
+ viewVideo()?.pause();
691
+ const head = g.el.querySelector(`[${HEAD}]`);
692
+ part("view-head").replaceChildren(...(head ? [copyOf(head)] : []));
693
+ // The group's view count — the site's, written in its card — left
694
+ // of the close.
695
+ const views = g.el.querySelector(`[${VIEWS}]`);
696
+ part("view-views").replaceChildren(...(views ? [copyOf(views)] : []));
697
+ // The head as it was before this group was looked at — its ring
698
+ // bright the first time, through all its clips — and from now on,
699
+ // seen.
700
+ if (headOf !== g) {
701
+ headOf = g;
702
+ part("view-head").setAttribute(SEEN, String(isSeen(g.el)));
703
+ }
704
+ // This clip shown; every clip of the group shown: seen.
705
+ const shown = watched.get(g.el) ?? new Set();
706
+ shown.add(view.ci);
707
+ watched.set(g.el, shown);
708
+ if (shown.size >= n)
709
+ markSeen(g.el);
710
+ viewBars.replaceChildren(...g.clips.map((_, i) => {
711
+ const bar = document.createElement("button");
712
+ bar.type = "button";
713
+ bar.setAttribute(VIEW_BAR, "");
714
+ bar.setAttribute("aria-label", `Clip ${i + 1} of ${n}`);
715
+ bar.append(document.createElement("span"));
716
+ bar.toggleAttribute(DONE, i < view.ci);
717
+ if (i === view.ci)
718
+ bar.setAttribute("aria-current", "true");
719
+ bar.style.setProperty(PROGRESS, i < view.ci ? "1" : "0");
720
+ return bar;
721
+ }));
722
+ viewBars.hidden = n < 2;
723
+ const copy = copyOf(clip);
724
+ const v = copy.querySelector("video");
725
+ if (v) {
726
+ v.muted = !sound;
727
+ v.preload = "auto";
728
+ v.loop = false;
729
+ }
730
+ media.replaceChildren(copy);
731
+ peekOf(before, view.list[view.gi - 1]);
732
+ peekOf(after, view.list[view.gi + 1]);
733
+ const product = g.products[view.ci];
734
+ part("panel-summary").replaceChildren(...(product ? [copyOf(product)] : []));
735
+ // The details: in the product, or in the clip — a <template>, or
736
+ // any element kept hidden (React: a <template>'s markup is not
737
+ // hydrated, and a link cannot sit inside the product's link but
738
+ // in a template). A template parsed from HTML keeps its markup in
739
+ // .content; one rendered by script holds it as children. Its
740
+ // data-pg-reels-title goes to the panel's head, beside the close.
741
+ const detail = product?.querySelector(`[${DETAIL}]`) ?? clip.querySelector(`[${DETAIL}]`);
742
+ const from = detail instanceof HTMLTemplateElement && detail.content.childNodes.length ? detail.content : detail;
743
+ const holder = document.createElement("div");
744
+ holder.append(...(from ? [...from.childNodes].map((x) => x.cloneNode(true)) : []));
745
+ const title = holder.querySelector(`[${TITLE}]`);
746
+ part("panel-title").replaceChildren(...(title ? [title] : []));
747
+ // Its data-pg-reels-foot — the link to the product — to the
748
+ // panel's foot, always in sight under what scrolls.
749
+ const foot = holder.querySelector(`[${FOOT}]`);
750
+ part("panel-foot").replaceChildren(...(foot ? [foot] : []));
751
+ part("panel-detail").replaceChildren(...holder.childNodes);
752
+ part("panel-detail").scrollTop = 0;
753
+ // Its variants: the one marked current, or the first, chosen.
754
+ const variants = panel.querySelectorAll(`[${VARIANT}]`);
755
+ if (variants.length)
756
+ chooseVariant([...variants].find((x) => x.hasAttribute(CURRENT)) ?? variants[0]);
757
+ dialog.toggleAttribute(NO_PRODUCT, !product);
758
+ upButton.disabled = view.gi === 0;
759
+ downButton.disabled = view.gi === view.list.length - 1;
760
+ view.shown = 0;
761
+ view.since = performance.now();
762
+ playView();
763
+ };
764
+ const playView = () => {
765
+ const v = viewVideo();
766
+ const still = view.paused || view.held;
767
+ dialog.toggleAttribute(PAUSED, view.paused);
768
+ playButton.setAttribute("aria-label", view.paused ? "Play" : "Pause");
769
+ if (still) {
770
+ v?.pause();
771
+ return;
772
+ }
773
+ view.since = performance.now();
774
+ v?.play().catch(() => { });
775
+ tickView();
776
+ };
777
+ // Still for now — held, dragged, sliding — its time kept.
778
+ const holdView = () => {
779
+ if (view.held)
780
+ return;
781
+ if (!view.paused)
782
+ view.shown += performance.now() - view.since;
783
+ view.held = true;
784
+ viewVideo()?.pause();
785
+ };
786
+ const letGo = () => {
787
+ view.held = false;
788
+ playView();
789
+ };
790
+ const tickView = () => {
791
+ if (view.frame)
792
+ return;
793
+ view.frame = requestAnimationFrame(function step(now) {
794
+ view.frame = 0;
795
+ if (!view.open || view.paused || view.held)
796
+ return;
797
+ const g = current();
798
+ const clip = g.clips[view.ci];
799
+ const v = viewVideo();
800
+ const progress = v ? (v.duration ? v.currentTime / v.duration : 0) : (view.shown + now - view.since) / Math.max(1, pictureTime(g, clip));
801
+ viewBars.children[view.ci]?.setAttribute("style", `${PROGRESS}: ${Math.min(1, progress)}`);
802
+ if (!v && progress >= 1) {
803
+ nextClip(true);
804
+ return;
805
+ }
806
+ view.frame = requestAnimationFrame(step);
807
+ });
808
+ };
809
+ /* Between groups: the video and the one above or under it move
810
+ together — after a finger, or by themselves — by a video and its
811
+ gap; landed, the one that came in is the one shown, its product in
812
+ the panel. */
813
+ let sliding = false;
814
+ const shift = () => screen.offsetHeight + px(getComputedStyle(feed).rowGap);
815
+ const setY = (y) => {
816
+ feed.style.transform = y ? `translateY(${y}px)` : "";
817
+ };
818
+ const can = (dir) => view.gi + dir >= 0 && view.gi + dir < view.list.length;
819
+ const EASE = "cubic-bezier(0.2, 0, 0, 1)";
820
+ // `last`: land on the group's last clip — going back from a first clip.
821
+ const slide = (dir, from = 0, last = false) => {
822
+ if (sliding)
823
+ return;
824
+ const land = () => {
825
+ view.gi += dir;
826
+ view.ci = last ? current().clips.length - 1 : 0;
827
+ view.held = false;
828
+ dialog.removeAttribute(SLIDING);
829
+ render();
830
+ };
831
+ if (!can(dir))
832
+ return settle(from);
833
+ if (reduced()) {
834
+ setY(0);
835
+ return land();
836
+ }
837
+ sliding = true;
838
+ holdView();
839
+ dialog.setAttribute(SLIDING, "");
840
+ const by = shift();
841
+ const to = -dir * by;
842
+ setY(0);
843
+ const run = feed.animate({ transform: [`translateY(${from}px)`, `translateY(${to}px)`] }, { duration: Math.max(140, (340 * Math.abs(to - from)) / by), easing: EASE, fill: "forwards" });
844
+ run.onfinish = () => {
845
+ land();
846
+ run.cancel();
847
+ sliding = false;
848
+ };
849
+ };
850
+ // Not far enough: back where it was.
851
+ const settle = (from) => {
852
+ const done = () => {
853
+ dialog.removeAttribute(SLIDING);
854
+ letGo();
855
+ };
856
+ setY(0);
857
+ if (!from || reduced())
858
+ return done();
859
+ sliding = true;
860
+ const run = feed.animate({ transform: [`translateY(${from}px)`, "none"] }, { duration: 220, easing: EASE });
861
+ run.onfinish = () => {
862
+ sliding = false;
863
+ done();
864
+ };
865
+ };
866
+ // Within a group, and on to the next — after the last group, the first.
867
+ const nextClip = (auto = false) => {
868
+ if (view.ci < current().clips.length - 1) {
869
+ view.ci += 1;
870
+ render();
871
+ }
872
+ else if (can(1))
873
+ slide(1);
874
+ else if (auto && view.list.length > 1) {
875
+ view.gi = 0;
876
+ view.ci = 0;
877
+ render();
878
+ }
879
+ else {
880
+ view.ci = 0;
881
+ render();
882
+ }
883
+ };
884
+ const prevClip = () => {
885
+ if (view.ci > 0) {
886
+ view.ci -= 1;
887
+ render();
888
+ }
889
+ else if (can(-1))
890
+ slide(-1, 0, true);
891
+ else
892
+ render();
893
+ };
894
+ const nextGroup = () => slide(1);
895
+ const prevGroup = () => slide(-1);
896
+ const openView = (g, clip) => {
897
+ // Opened from a card the sound was not on: none.
898
+ if (g !== owner)
899
+ sound = false;
900
+ stopAll();
901
+ // Every group of its section, in the page's order.
902
+ headOf = null;
903
+ view.list = [...groups.values()].filter((x) => x.root === g.root).sort((a, b) => (a.el.compareDocumentPosition(b.el) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1));
904
+ view.gi = view.list.indexOf(g);
905
+ view.ci = clip;
906
+ view.open = true;
907
+ // Reduced motion: it waits for its play button.
908
+ view.paused = reduced();
909
+ view.held = false;
910
+ dialog.removeAttribute(DETAILS);
911
+ dialog.removeAttribute(SLIDING);
912
+ setY(0);
913
+ toggle.setAttribute("aria-expanded", "false");
914
+ if (!dialog.open)
915
+ dialog.showModal();
916
+ dialog.focus({ preventScroll: true });
917
+ try {
918
+ history.pushState({ ...(history.state ?? {}), pgReels: true }, "");
919
+ view.pushed = true;
920
+ }
921
+ catch {
922
+ view.pushed = false;
923
+ }
924
+ render();
925
+ applySound();
926
+ };
927
+ // Closed: the card it came from shows the clip last seen; the strip
928
+ // plays again. A Back step of its own is taken back — unless Back
929
+ // closed it.
930
+ const closeView = (byBack = false) => {
931
+ if (!view.open)
932
+ return;
933
+ view.open = false;
934
+ viewVideo()?.pause();
935
+ if (view.frame)
936
+ cancelAnimationFrame(view.frame);
937
+ view.frame = 0;
938
+ feed.getAnimations().forEach((a) => a.cancel());
939
+ sliding = false;
940
+ press = null;
941
+ const g = current();
942
+ if (g)
943
+ show(g, view.ci);
944
+ // Its sound goes on with the card last seen, if that one plays.
945
+ owner = g ?? null;
946
+ if (dialog.open)
947
+ dialog.close();
948
+ media.replaceChildren();
949
+ if (view.pushed && !byBack)
950
+ history.back();
951
+ view.pushed = false;
952
+ choose();
953
+ applySound();
954
+ paintSeen();
955
+ };
956
+ const onViewClick = (event) => {
957
+ if (!(event.target instanceof Element))
958
+ return;
959
+ const t = event.target;
960
+ if (swallow) {
961
+ swallow = false;
962
+ event.preventDefault();
963
+ return;
964
+ }
965
+ // The dark around it.
966
+ if (t === dialog || t.hasAttribute("data-pg-reels-stage"))
967
+ return closeView();
968
+ if (t.closest("[data-pg-reels-view-close], [data-pg-reels-panel-close]"))
969
+ return closeView();
970
+ if (sliding)
971
+ return;
972
+ if (t.closest("[data-pg-reels-view-on]"))
973
+ return nextClip();
974
+ if (t.closest("[data-pg-reels-view-back]"))
975
+ return prevClip();
976
+ if (t.closest("[data-pg-reels-view-up]"))
977
+ return prevGroup();
978
+ if (t.closest('[data-pg-reels-view-down], [data-pg-reels-view-peek="after"]'))
979
+ return nextGroup();
980
+ const bar = t.closest(`[${VIEW_BAR}]`);
981
+ if (bar) {
982
+ view.ci = [...viewBars.children].indexOf(bar);
983
+ return render();
984
+ }
985
+ if (t.closest("[data-pg-reels-view-play]"))
986
+ return togglePause();
987
+ if (t.closest("[data-pg-reels-panel-toggle]")) {
988
+ const open = !dialog.hasAttribute(DETAILS);
989
+ dialog.toggleAttribute(DETAILS, open);
990
+ toggle.setAttribute("aria-expanded", String(open));
991
+ return;
992
+ }
993
+ // A variant pressed: its price, its pictures, its link.
994
+ const variant = t.closest(`[${VARIANT}]`);
995
+ if (variant && panel.contains(variant))
996
+ return chooseVariant(variant);
997
+ // A small picture of the product, pressed: shown big — in its own
998
+ // gallery, when each variant has one — and brought into sight,
999
+ // when the row of them scrolls.
1000
+ const thumb = t.closest(`[${THUMB}]`);
1001
+ if (thumb) {
1002
+ const detail = thumb.closest(`[${GALLERY}]`) ?? thumb.closest("[data-pg-reels-panel-detail]");
1003
+ const big = detail?.querySelector(`[${BIG}] img, img[${BIG}]`);
1004
+ const src = thumb.getAttribute(THUMB) || thumb.querySelector("img")?.src;
1005
+ if (big && src)
1006
+ big.src = src;
1007
+ detail?.querySelectorAll(`[${THUMB}]`).forEach((x) => x.toggleAttribute(CURRENT, x === thumb));
1008
+ thumb.scrollIntoView({ block: "nearest", inline: "nearest", behavior: reduced() ? "instant" : "smooth" });
1009
+ }
1010
+ };
1011
+ /* A variant chosen — 1 kg, 500 g; a colour — in the panel: it is
1012
+ data-pg-reels-current (aria-pressed too); the gallery of the same
1013
+ name shows, the others hide; data-pg-reels-price shows its price;
1014
+ the foot's link goes to its page. */
1015
+ const chooseVariant = (variant) => {
1016
+ const name = variant.getAttribute(VARIANT);
1017
+ panel.querySelectorAll(`[${VARIANT}]`).forEach((x) => {
1018
+ x.toggleAttribute(CURRENT, x === variant);
1019
+ if (x.tagName === "BUTTON")
1020
+ x.setAttribute("aria-pressed", String(x === variant));
1021
+ });
1022
+ const galleries = panel.querySelectorAll(`[${GALLERY}]`);
1023
+ if ([...galleries].some((x) => x.getAttribute(GALLERY) === name))
1024
+ galleries.forEach((x) => x.toggleAttribute(CURRENT, x.getAttribute(GALLERY) === name));
1025
+ const price = variant.getAttribute(VARIANT_PRICE);
1026
+ if (price !== null)
1027
+ panel.querySelectorAll(`[${PRICE}]`).forEach((x) => (x.textContent = price));
1028
+ const href = variant.getAttribute(VARIANT_HREF);
1029
+ if (href)
1030
+ panel.querySelectorAll(`a[${FOOT}]`).forEach((x) => (x.href = href));
1031
+ };
1032
+ const togglePause = () => {
1033
+ if (!view.paused && !view.held)
1034
+ view.shown += performance.now() - view.since;
1035
+ view.paused = !view.paused;
1036
+ playView();
1037
+ };
1038
+ dialog.addEventListener("click", onViewClick);
1039
+ dialog.addEventListener("cancel", (event) => {
1040
+ event.preventDefault();
1041
+ closeView();
1042
+ });
1043
+ // A video that ends in the view: the next clip.
1044
+ media.addEventListener("ended", () => nextClip(true), true);
1045
+ /* A press on the video. Held: still, the controls out of the way.
1046
+ Dragged up or down — at once, or after holding it: the video follows the finger — the next group
1047
+ coming in under it, or the one before above it — and let go, goes
1048
+ on to it if pulled far enough or flicked, or back if not. A press
1049
+ that was either is no tap. */
1050
+ let press = null;
1051
+ let swallow = false;
1052
+ const noTap = () => {
1053
+ swallow = true;
1054
+ setTimeout(() => (swallow = false));
1055
+ };
1056
+ // How far the video moves for a finger's `dy`: past the first or the
1057
+ // last group, a quarter — it gives, and comes back.
1058
+ const pulled = (dy) => (can(dy < 0 ? 1 : -1) ? dy : dy / 4);
1059
+ screen.addEventListener("pointerdown", (event) => {
1060
+ if (event.button !== 0 || sliding || event.target.closest("button:not([data-pg-reels-view-on]):not([data-pg-reels-view-back]), a"))
1061
+ return;
1062
+ const timer = window.setTimeout(() => {
1063
+ if (!press || press.drag)
1064
+ return;
1065
+ dialog.setAttribute(HELD, "");
1066
+ holdView();
1067
+ }, HOLD_MS);
1068
+ press = { id: event.pointerId, x: event.clientX, y: event.clientY, timer, drag: false, lastY: event.clientY, lastT: event.timeStamp, speed: 0 };
1069
+ });
1070
+ screen.addEventListener("pointermove", (event) => {
1071
+ if (!press || press.id !== event.pointerId)
1072
+ return;
1073
+ const dx = event.clientX - press.x;
1074
+ const dy = event.clientY - press.y;
1075
+ if (!press.drag) {
1076
+ if (Math.hypot(dx, dy) > 10)
1077
+ clearTimeout(press.timer);
1078
+ if (Math.abs(dy) < DRAG_PX || Math.abs(dy) < Math.abs(dx))
1079
+ return;
1080
+ // Held first, then dragged: a drag all the same.
1081
+ press.drag = true;
1082
+ dialog.removeAttribute(HELD);
1083
+ screen.setPointerCapture(event.pointerId);
1084
+ holdView();
1085
+ dialog.setAttribute(SLIDING, "");
1086
+ }
1087
+ // The finger's speed, px a ms, smoothed.
1088
+ const dt = Math.max(1, event.timeStamp - press.lastT);
1089
+ press.speed = press.speed * 0.6 + ((event.clientY - press.lastY) / dt) * 0.4;
1090
+ press.lastY = event.clientY;
1091
+ press.lastT = event.timeStamp;
1092
+ setY(pulled(dy));
1093
+ });
1094
+ const release = (event) => {
1095
+ if (!press || press.id !== event.pointerId)
1096
+ return;
1097
+ const p = press;
1098
+ press = null;
1099
+ clearTimeout(p.timer);
1100
+ if (p.drag) {
1101
+ noTap();
1102
+ const dy = event.clientY - p.y;
1103
+ const dir = dy < 0 ? 1 : -1;
1104
+ const far = Math.abs(dy) > shift() * 0.2;
1105
+ const flick = Math.abs(p.speed) > FLICK && Math.sign(p.speed) === Math.sign(dy);
1106
+ if (event.type === "pointerup" && can(dir) && (far || flick))
1107
+ slide(dir, pulled(dy));
1108
+ else
1109
+ settle(pulled(dy));
1110
+ return;
1111
+ }
1112
+ if (dialog.hasAttribute(HELD)) {
1113
+ dialog.removeAttribute(HELD);
1114
+ noTap();
1115
+ letGo();
1116
+ }
1117
+ };
1118
+ screen.addEventListener("pointerup", release);
1119
+ screen.addEventListener("pointercancel", release);
1120
+ // A wheel, a trackpad: a step per turn, then a rest.
1121
+ let wheelSum = 0;
1122
+ let wheelRest = 0;
1123
+ dialog.addEventListener("wheel", (event) => {
1124
+ if (event.target.closest("[data-pg-reels-panel]"))
1125
+ return;
1126
+ event.preventDefault();
1127
+ if (event.timeStamp < wheelRest || sliding || press)
1128
+ return;
1129
+ wheelSum += event.deltaY;
1130
+ if (Math.abs(wheelSum) < WHEEL_PX)
1131
+ return;
1132
+ if (wheelSum > 0)
1133
+ nextGroup();
1134
+ else
1135
+ prevGroup();
1136
+ wheelSum = 0;
1137
+ wheelRest = event.timeStamp + WHEEL_REST_MS;
1138
+ }, { passive: false });
1139
+ dialog.addEventListener("keydown", (event) => {
1140
+ if (!view.open || event.altKey || event.ctrlKey || event.metaKey)
1141
+ return;
1142
+ const onControl = event.target.closest("button, a, input, textarea, select");
1143
+ if (sliding && event.key.startsWith("Arrow"))
1144
+ return event.preventDefault();
1145
+ if (event.key === "ArrowDown" || event.key === "PageDown")
1146
+ nextGroup();
1147
+ else if (event.key === "ArrowUp" || event.key === "PageUp")
1148
+ prevGroup();
1149
+ else if (event.key === "ArrowRight")
1150
+ nextClip();
1151
+ else if (event.key === "ArrowLeft")
1152
+ prevClip();
1153
+ else if ((event.key === " " || event.key === "k") && !onControl)
1154
+ togglePause();
1155
+ else
1156
+ return;
1157
+ event.preventDefault();
1158
+ });
1159
+ // Back closes it.
1160
+ const onPop = () => {
1161
+ if (view.open) {
1162
+ view.pushed = false;
1163
+ closeView(true);
1164
+ }
1165
+ };
1166
+ addEventListener("popstate", onPop);
1167
+ // Rendered later — React, a list that arrives — or taken away.
1168
+ const mo = new MutationObserver((records) => {
1169
+ if (records.some((r) => [...r.addedNodes, ...r.removedNodes].some((n) => n instanceof Element && (n.matches(`[${ROOT}], [${GROUP}]`) || !!n.querySelector(`[${GROUP}]`)))))
1170
+ look();
1171
+ });
1172
+ mo.observe(document.body, { childList: true, subtree: true });
1173
+ document.addEventListener("click", onClick);
1174
+ document.addEventListener("ended", onEnded, true);
1175
+ document.addEventListener("scroll", onScroll, true);
1176
+ const onResize = () => document.querySelectorAll(`[${ROOT}]`).forEach(ends);
1177
+ addEventListener("resize", onResize);
1178
+ const onHidden = () => {
1179
+ if (view.open) {
1180
+ if (document.hidden)
1181
+ holdView();
1182
+ else if (!press && !sliding)
1183
+ letGo();
1184
+ return;
1185
+ }
1186
+ playing.forEach(document.hidden ? stop : start);
1187
+ // Back after a while: what was seen may have run out.
1188
+ if (!document.hidden)
1189
+ paintSeen();
1190
+ };
1191
+ document.addEventListener("visibilitychange", onHidden);
1192
+ look();
1193
+ return () => {
1194
+ mo.disconnect();
1195
+ sights?.disconnect();
1196
+ document.removeEventListener("click", onClick);
1197
+ document.removeEventListener("ended", onEnded, true);
1198
+ document.removeEventListener("scroll", onScroll, true);
1199
+ removeEventListener("resize", onResize);
1200
+ document.removeEventListener("visibilitychange", onHidden);
1201
+ if (frame)
1202
+ cancelAnimationFrame(frame);
1203
+ stopAll();
1204
+ removeEventListener("popstate", onPop);
1205
+ if (view.open)
1206
+ closeView();
1207
+ bandSize.disconnect();
1208
+ dialog.remove();
1209
+ if (live === self)
1210
+ live = null;
1211
+ };
1212
+ }