visualci-gallery 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,24 @@
1
+ import type { PreloadCaps, Size, Theme } from "./model.js";
2
+ import { type Env } from "./preload.js";
3
+ export interface Gallery {
4
+ /** The gallery's element (the contract's `section.vg`). */
5
+ root: HTMLElement;
6
+ setTheme(theme: Theme): void;
7
+ setSize(size: Size): void;
8
+ /** Opens the full-size view of a screen by its key. */
9
+ open(key: string): void;
10
+ close(): void;
11
+ /** Removes the listeners hydrate() added. */
12
+ destroy(): void;
13
+ }
14
+ export interface HydrateOptions {
15
+ /** Over the markup's data-vg-preload: false turns preloading off, an object sets its caps. */
16
+ preload?: boolean | PreloadCaps;
17
+ /** The loader, idle callback and timing source, for tests. */
18
+ env?: Env;
19
+ }
20
+ /** The gallery already hydrated on this element, if any. */
21
+ export declare function hydratedGallery(root: HTMLElement): Gallery | undefined;
22
+ /** Hydrates a gallery's markup: `el` is the contract's `section.vg`, or an element holding one. Hydrating twice
23
+ * returns the first. */
24
+ export declare function hydrate(el: HTMLElement, options?: HydrateOptions): Gallery;
@@ -0,0 +1,560 @@
1
+ // Brings the contract's markup to life (contract/SPEC.md, "Behaviour"): one theme and one size for the whole gallery
2
+ // and its full-size view, tabs, the strip's scroll buttons, and the full-size view itself, a native <dialog> with
3
+ // previous and next. It reads only the markup, so it works the same on HTML a server rendered and on HTML mount()
4
+ // rendered. Without <dialog> (Safari before 15.4) each card stays a link to its image.
5
+ //
6
+ // Every attribute it reads or sets starts with data-vg-, so a site's own [data-theme] rules never reach the gallery.
7
+ import { DEFAULT_CAPS, Preloader, estimateBytes, neighbours, plan, tabItems, } from "./preload.js";
8
+ const hydrated = new WeakMap();
9
+ /** The caps from the options, else the markup (none: the defaults; "off": null). */
10
+ function preloadCaps(root, option) {
11
+ if (option === false)
12
+ return null;
13
+ if (typeof option === "object" && option !== null)
14
+ return sane({ ...DEFAULT_CAPS, ...definedOnly(option) });
15
+ if (option === true)
16
+ return { ...DEFAULT_CAPS };
17
+ const attr = root.getAttribute("data-vg-preload");
18
+ if (attr === null)
19
+ return { ...DEFAULT_CAPS };
20
+ if (attr === "off")
21
+ return null;
22
+ const caps = { ...DEFAULT_CAPS };
23
+ for (const pair of attr.split(" ")) {
24
+ const [k, v] = pair.split("=");
25
+ if (k in caps && /^\d+$/.test(v ?? ""))
26
+ caps[k] = Number(v);
27
+ }
28
+ return sane(caps);
29
+ }
30
+ /** At least one request at once and at most 8, as buildModel enforces, so nothing can stall the reader's own
31
+ * requests. */
32
+ function sane(caps) {
33
+ return { ...caps, parallel: Math.min(Math.max(Math.floor(caps.parallel) || 1, 1), 8) };
34
+ }
35
+ function definedOnly(o) {
36
+ const out = {};
37
+ for (const [k, v] of Object.entries(o))
38
+ if (typeof v === "number")
39
+ out[k] = v;
40
+ return out;
41
+ }
42
+ /** Save-Data, a 2G connection or prefers-reduced-data: only the shown tab's thumbnails. Chromium alone reports the
43
+ * connection, so the preloader also measures its own requests (Preloader.slow). */
44
+ function lowData() {
45
+ const c = navigator.connection;
46
+ if (c?.saveData || /(^|-)2g$/.test(c?.effectiveType ?? ""))
47
+ return true;
48
+ return typeof matchMedia === "function" && matchMedia("(prefers-reduced-data: reduce)").matches;
49
+ }
50
+ /** The browser side of the preloader: an Image per request at low or high fetch priority, idle callbacks, and each
51
+ * request's timing (Resource Timing for its bytes where the server allows, else the request's own clock). */
52
+ const REQUEST_TIMEOUT_MS = 30_000;
53
+ function browserEnv() {
54
+ const clock = new Map();
55
+ const now = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
56
+ return {
57
+ load(url, high) {
58
+ const img = new Image();
59
+ img.decoding = "async";
60
+ img.fetchPriority = high ? "high" : "low";
61
+ let settle = () => { };
62
+ const done = new Promise((resolve) => (settle = resolve));
63
+ const start = now();
64
+ img.onload = () => {
65
+ clock.set(url, { start, end: now() });
66
+ settle(true);
67
+ };
68
+ img.onerror = () => settle(false);
69
+ img.src = url;
70
+ const cancel = () => {
71
+ clearTimeout(timer);
72
+ img.onload = img.onerror = null;
73
+ img.removeAttribute("src");
74
+ settle(false);
75
+ };
76
+ // A server that never answers doesn't hold a slot for good.
77
+ const timer = setTimeout(cancel, REQUEST_TIMEOUT_MS);
78
+ done.then(() => clearTimeout(timer));
79
+ return { done, cancel };
80
+ },
81
+ later: (fn, ms) => void setTimeout(fn, ms),
82
+ idle(fn) {
83
+ if (typeof requestIdleCallback === "function")
84
+ requestIdleCallback(() => fn(), { timeout: 2000 });
85
+ else
86
+ setTimeout(fn, 50);
87
+ },
88
+ timing(url) {
89
+ const own = clock.get(url);
90
+ clock.delete(url);
91
+ const entries = typeof performance !== "undefined" && performance.getEntriesByName ? performance.getEntriesByName(url) : [];
92
+ const e = entries[entries.length - 1];
93
+ // Only this request's own entry: a memory-cache hit records none, and the page's earlier entry for the same
94
+ // URL would date the request back to page load.
95
+ if (e && e.responseEnd > 0 && (!own || e.startTime >= own.start - 1))
96
+ return { start: e.startTime, end: e.responseEnd, bytes: e.encodedBodySize > 0 ? e.encodedBodySize : null };
97
+ return own ? { ...own, bytes: null } : null;
98
+ },
99
+ };
100
+ }
101
+ function pageTheme() {
102
+ const set = document.documentElement.getAttribute("data-theme");
103
+ if (set === "light" || set === "dark")
104
+ return set;
105
+ return matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
106
+ }
107
+ function canOpen() {
108
+ return typeof HTMLDialogElement === "function" && typeof HTMLDialogElement.prototype.showModal === "function";
109
+ }
110
+ function reducedMotion() {
111
+ return matchMedia("(prefers-reduced-motion: reduce)").matches;
112
+ }
113
+ /** An image that can't load shows its description instead, in the same place. */
114
+ function watch(img) {
115
+ const fail = () => {
116
+ const span = document.createElement("span");
117
+ span.className = "vg-img vg-missing";
118
+ span.setAttribute("data-vg-size", img.getAttribute("data-vg-size") ?? "");
119
+ span.setAttribute("data-vg-theme", img.getAttribute("data-vg-theme") ?? "");
120
+ span.textContent = img.alt;
121
+ img.replaceWith(span);
122
+ };
123
+ if (img.complete && img.getAttribute("src") && img.naturalWidth === 0)
124
+ fail();
125
+ else
126
+ img.addEventListener("error", fail, { once: true });
127
+ }
128
+ const listOf = (value) => (value ?? "").split(" ").filter(Boolean);
129
+ const toArray = (list) => Array.prototype.slice.call(list);
130
+ /** The gallery already hydrated on this element, if any. */
131
+ export function hydratedGallery(root) {
132
+ return hydrated.get(root);
133
+ }
134
+ /** Hydrates a gallery's markup: `el` is the contract's `section.vg`, or an element holding one. Hydrating twice
135
+ * returns the first. */
136
+ export function hydrate(el, options = {}) {
137
+ const found = el.matches("[data-vg]") ? el : el.querySelector("[data-vg]");
138
+ if (!found)
139
+ throw new Error("hydrate: no gallery markup ([data-vg]) in this element");
140
+ const root = found;
141
+ const existing = hydrated.get(root);
142
+ if (existing)
143
+ return existing;
144
+ const box = root.querySelector(".vg-box");
145
+ const view = box.querySelector(".vg-box-view");
146
+ const boxTitle = box.querySelector(".vg-box-title");
147
+ const all = (selector) => toArray(root.querySelectorAll(selector));
148
+ const tabs = all('[role="tab"]');
149
+ const track = root.querySelector(".vg-track");
150
+ const followsPage = root.getAttribute("data-vg-theme-source") === "page";
151
+ let current = null;
152
+ let opener = null;
153
+ const theme = () => root.getAttribute("data-vg-theme") ?? "light";
154
+ const size = () => root.getAttribute("data-vg-size") ?? "desktop";
155
+ const panel = () => root.querySelector(".vg-panel:not([hidden])");
156
+ const panelOf = (t) => all(".vg-panel").find((p) => p.id === t.getAttribute("aria-controls")) ?? null;
157
+ const cardOf = (key, within) => toArray(within.querySelectorAll("[data-vg-screen]")).find((c) => c.getAttribute("data-vg-screen") === key) ?? null;
158
+ const sizesOf = (el) => listOf(el?.getAttribute("data-vg-sizes"));
159
+ /** The card's image for the gallery's theme and size. */
160
+ const shownIn = (card) => card.querySelector(`.vg-img[data-vg-size="${size()}"][data-vg-theme~="${theme()}"]`);
161
+ function sync() {
162
+ // Each card links to the image it shows, so a middle click or a browser without <dialog> opens that one.
163
+ for (const card of all(".vg-card")) {
164
+ const img = shownIn(card);
165
+ const src = img?.getAttribute("data-src-full") ?? img?.getAttribute("src");
166
+ const link = card.querySelector("a.vg-thumb");
167
+ if (link && src)
168
+ link.setAttribute("href", src);
169
+ }
170
+ if (box.open && current)
171
+ show(current);
172
+ }
173
+ function set(key, value) {
174
+ root.setAttribute(`data-vg-${key}`, value);
175
+ for (const b of all(`[data-vg-set-${key}]`)) {
176
+ b.setAttribute("aria-pressed", String(b.getAttribute(`data-vg-set-${key}`) === value));
177
+ }
178
+ sync();
179
+ if (!selecting)
180
+ replan();
181
+ }
182
+ // The size the reader chose (phone to begin with on a narrow screen). A tab without it shows the size it has,
183
+ // without changing the choice, so the next tab is back at the chosen size.
184
+ let chosen = matchMedia("(max-width: 47.99rem)").matches ? "phone" : "desktop";
185
+ function fit() {
186
+ const sizes = sizesOf(panel());
187
+ set("size", sizes.length === 0 || sizes.indexOf(chosen) !== -1 ? chosen : sizes[0]);
188
+ }
189
+ let selecting = false;
190
+ function select(tab, focus = false) {
191
+ const changed = tab.getAttribute("aria-selected") !== "true";
192
+ selecting = true;
193
+ for (const t of tabs) {
194
+ const on = t === tab;
195
+ t.setAttribute("aria-selected", String(on));
196
+ t.tabIndex = on ? 0 : -1;
197
+ const p = panelOf(t);
198
+ if (p)
199
+ p.hidden = !on;
200
+ }
201
+ if (focus)
202
+ tab.focus();
203
+ fit();
204
+ selecting = false;
205
+ // A tab the reader opened loads first, at high priority: its fold, then the rest. Then the queue is planned
206
+ // again from the new tab.
207
+ if (preloader && changed) {
208
+ const t = planTabs();
209
+ preloader.jump(tabItems(t.tabs[t.current], theme()), true);
210
+ }
211
+ replan();
212
+ }
213
+ /** The cards the full-size view steps through: the shown panel's, at the gallery's size. */
214
+ function cards() {
215
+ return all(".vg-panel:not([hidden]) .vg-card").filter((c) => sizesOf(c).indexOf(size()) !== -1);
216
+ }
217
+ function show(card) {
218
+ current = card;
219
+ boxTitle.textContent = card.querySelector(".vg-card-title")?.textContent ?? "";
220
+ // The view's size buttons: only the sizes this screen has, so switching never shows nothing.
221
+ const sizes = sizesOf(card);
222
+ const boxSizes = box.querySelector(".vg-box-sizes");
223
+ if (boxSizes) {
224
+ boxSizes.hidden = sizes.length < 2;
225
+ for (const b of toArray(boxSizes.querySelectorAll("[data-vg-set-size]"))) {
226
+ b.hidden = sizes.indexOf(b.getAttribute("data-vg-set-size")) === -1;
227
+ }
228
+ }
229
+ const shown = shownIn(card);
230
+ view.setAttribute("data-vg-size", size());
231
+ // One screen's worth fits the view whole: a window (a group shown whole), a phone screen at most 2.4 times as
232
+ // tall as it is wide, or a desktop one at most 0.8 times. A taller full-page capture scrolls. The dialog carries
233
+ // the mark too, so its height is set without :has().
234
+ const tall = Number(shown?.getAttribute("height")) / Number(shown?.getAttribute("width"));
235
+ const whole = shown instanceof HTMLImageElement &&
236
+ (card.getAttribute("data-vg-fit") === "contain" || tall <= (size() === "phone" ? 2.4 : 0.8));
237
+ for (const el of [box, view]) {
238
+ if (whole)
239
+ el.setAttribute("data-vg-fit", "");
240
+ else
241
+ el.removeAttribute("data-vg-fit");
242
+ }
243
+ // A new element each time: reusing one keeps the previous picture on screen until the new one loads.
244
+ view.replaceChildren();
245
+ if (shown instanceof HTMLImageElement) {
246
+ const big = document.createElement("img");
247
+ // The original, not the card's thumbnail.
248
+ const src = shown.getAttribute("data-src-full") ?? shown.getAttribute("src") ?? "";
249
+ big.alt = shown.alt;
250
+ // The image's own size from the markup (its .width is the thumbnail's rendered width).
251
+ big.setAttribute("width", shown.getAttribute("width") ?? "");
252
+ big.setAttribute("height", shown.getAttribute("height") ?? "");
253
+ big.decoding = "async";
254
+ const x2 = shown.getAttribute("data-src-2x");
255
+ if (x2) {
256
+ big.srcset = `${src} 1x, ${x2} 2x`;
257
+ // A 2x copy that can't load: the 1x one.
258
+ big.addEventListener("error", () => big.removeAttribute("srcset"), { once: true });
259
+ }
260
+ big.src = src;
261
+ view.append(big);
262
+ }
263
+ else if (shown) {
264
+ view.append(shown.cloneNode(true));
265
+ }
266
+ view.scrollTop = 0;
267
+ // The screens either side, in the order the reader is likely to step.
268
+ if (preloader && !light()) {
269
+ const list = cards();
270
+ const i = list.indexOf(card);
271
+ if (i !== -1)
272
+ preloader.jump(neighbours(list.map(planCard), i, theme(), hiDpi()).filter((n) => n.url !== ""), false);
273
+ }
274
+ }
275
+ function open(card) {
276
+ // A screen without the gallery's size (opened by key) shows the size it has.
277
+ const sizes = sizesOf(card);
278
+ if (sizes.length && sizes.indexOf(size()) === -1)
279
+ set("size", sizes[0]);
280
+ opener = card.querySelector("[data-vg-open]");
281
+ show(card);
282
+ if (!box.open) {
283
+ box.showModal();
284
+ lockPage();
285
+ }
286
+ }
287
+ // The page behind the open view doesn't scroll. A page that had a scrollbar keeps its gutter, so it doesn't shift
288
+ // sideways; a short page gets none.
289
+ let unlock = null;
290
+ function lockPage() {
291
+ if (unlock)
292
+ return;
293
+ const html = document.documentElement;
294
+ const before = [html.style.overflow, html.style.getPropertyValue("scrollbar-gutter")];
295
+ if (html.scrollHeight > html.clientHeight)
296
+ html.style.setProperty("scrollbar-gutter", "stable");
297
+ html.style.overflow = "hidden";
298
+ unlock = () => {
299
+ html.style.overflow = before[0];
300
+ if (before[1])
301
+ html.style.setProperty("scrollbar-gutter", before[1]);
302
+ else
303
+ html.style.removeProperty("scrollbar-gutter");
304
+ unlock = null;
305
+ };
306
+ }
307
+ function step(by) {
308
+ const list = cards();
309
+ if (!current || list.length === 0)
310
+ return;
311
+ const i = list.indexOf(current);
312
+ // From a screen that isn't in the list (it lacks this size): the first or the last.
313
+ const next = i === -1 ? (by > 0 ? 0 : list.length - 1) : (i + by + list.length) % list.length;
314
+ show(list[next]);
315
+ }
316
+ function edges() {
317
+ if (!track)
318
+ return;
319
+ const prev = root.querySelector('[data-vg-scroll="-1"]');
320
+ const next = root.querySelector('[data-vg-scroll="1"]');
321
+ if (prev)
322
+ prev.disabled = track.scrollLeft <= 1;
323
+ if (next)
324
+ next.disabled = track.scrollLeft + track.clientWidth >= track.scrollWidth - 1;
325
+ }
326
+ // --- Preloading (preload.ts): the plan comes from the markup as it stands. ---
327
+ const caps = preloadCaps(root, options.preload);
328
+ let preloader = null;
329
+ const hiDpi = () => (typeof devicePixelRatio === "number" ? devicePixelRatio : 1) > 1;
330
+ const num = (img, name) => {
331
+ const v = img.getAttribute(name);
332
+ return v !== null && /^\d+$/.test(v) ? Number(v) : null;
333
+ };
334
+ function planImage(img) {
335
+ const width = Number(img.getAttribute("width")) || 1;
336
+ const height = Number(img.getAttribute("height")) || 1;
337
+ const behind = img.getAttribute("data-src-full");
338
+ const x2 = img.getAttribute("data-src-2x");
339
+ // What the full-size view loads: the 2x copy on a high-density screen, else the original behind a thumbnail,
340
+ // else nothing more (the card's image is the full one).
341
+ const use2x = hiDpi() && x2 !== null;
342
+ const tw = Math.min(width, 640);
343
+ return {
344
+ url: img.getAttribute("src") ?? "",
345
+ full: use2x ? x2 : behind,
346
+ width,
347
+ height,
348
+ bytes: num(img, "data-vg-bytes") ?? (behind ? estimateBytes(tw, Math.round((height * tw) / width)) : estimateBytes(width, height)),
349
+ fullBytes: use2x
350
+ ? num(img, "data-vg-2x-bytes") ?? estimateBytes(width * 2, height * 2)
351
+ : num(img, "data-vg-full-bytes") ?? estimateBytes(width, height),
352
+ };
353
+ }
354
+ const planCardAt = (card, sz) => {
355
+ const imgs = toArray(card.querySelectorAll(`img.vg-img[data-vg-size="${sz}"]`));
356
+ const light = imgs.find((i) => listOf(i.getAttribute("data-vg-theme")).indexOf("light") !== -1);
357
+ const dark = imgs.find((i) => listOf(i.getAttribute("data-vg-theme")).indexOf("dark") !== -1);
358
+ return light && dark ? { light: planImage(light), dark: planImage(dark) } : null;
359
+ };
360
+ const planCard = (card) => planCardAt(card, size()) ?? { light: blank, dark: blank };
361
+ const blank = { url: "", full: null, width: 1, height: 1, bytes: 0, fullBytes: 0 };
362
+ /** The cards above the fold: in the viewport now. Other tabs can't be measured while hidden, so they're estimated
363
+ * from the shown one (a phone card is about half as wide as a desktop one). */
364
+ function planTabs() {
365
+ const panels = tabs.length ? tabs.map(panelOf) : all(".vg-panel");
366
+ const shown = panel();
367
+ const current = Math.max(0, panels.indexOf(shown));
368
+ const sizeOf = (p) => {
369
+ const sizes = sizesOf(p);
370
+ return sizes.length === 0 || sizes.indexOf(chosen) !== -1 ? chosen : sizes[0];
371
+ };
372
+ const shownSize = size();
373
+ let fold = 0;
374
+ const tabsOut = panels.map((p, i) => {
375
+ const sz = i === current ? shownSize : sizeOf(p);
376
+ const els = p ? toArray(p.querySelectorAll(".vg-card")).filter((c) => sizesOf(c).indexOf(sz) !== -1) : [];
377
+ // Cards whose image failed (replaced by its description) have nothing to load.
378
+ const pairs = els.map((el) => ({ el, card: planCardAt(el, sz) })).filter((x) => x.card !== null);
379
+ if (i === current) {
380
+ fold = pairs.filter(({ el }) => {
381
+ const r = el.getBoundingClientRect();
382
+ return r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth;
383
+ }).length;
384
+ }
385
+ return { sz, cards: pairs.map((x) => x.card) };
386
+ });
387
+ const out = tabsOut.map((t, i) => {
388
+ const f = i === current ? fold : t.sz === shownSize ? fold : t.sz === "phone" ? fold * 2 : Math.ceil(fold / 2);
389
+ return { cards: t.cards, fold: Math.min(f, t.cards.length) };
390
+ });
391
+ return { tabs: out, current };
392
+ }
393
+ /** Save-Data, 2G, reduced data or a slow measured rate: the shown tab's thumbnails, and nothing else predicted. */
394
+ const light = () => lowData() || !!preloader?.slow;
395
+ function replan() {
396
+ if (!preloader || !caps)
397
+ return;
398
+ const t = planTabs();
399
+ preloader.setPlan(plan({
400
+ tabs: t.tabs,
401
+ current: t.current,
402
+ theme: theme(),
403
+ caps,
404
+ mode: light() ? "light" : "full",
405
+ hiDpi: hiDpi(),
406
+ done: preloader.loaded(),
407
+ spent: preloader.spent,
408
+ }));
409
+ }
410
+ const onIntent = (e) => {
411
+ const tab = e.target.closest?.('[role="tab"]');
412
+ if (!preloader || light() || !tab || !root.contains(tab) || tab.getAttribute("aria-selected") === "true")
413
+ return;
414
+ const t = planTabs();
415
+ const i = tabs.indexOf(tab);
416
+ if (i !== -1 && t.tabs[i])
417
+ preloader.hint(tabItems(t.tabs[i], theme(), true));
418
+ };
419
+ let destroyed = false;
420
+ const env = options.env ?? browserEnv();
421
+ const start = () => {
422
+ if (destroyed || !caps || preloader)
423
+ return;
424
+ preloader = new Preloader(env, caps, () => replan());
425
+ replan();
426
+ };
427
+ const onLoad = () => env.idle(start);
428
+ const onClick = (e) => {
429
+ const target = e.target;
430
+ if (target === box)
431
+ return box.close(); // the dimmed backdrop, outside the dialog's box
432
+ const link = target.closest("a[data-vg-open]");
433
+ if (link && root.contains(link)) {
434
+ if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || !canOpen())
435
+ return;
436
+ e.preventDefault();
437
+ open(link.closest(".vg-card"));
438
+ return;
439
+ }
440
+ const b = target.closest("button");
441
+ if (!b || !root.contains(b))
442
+ return;
443
+ const setTheme = b.getAttribute("data-vg-set-theme");
444
+ const setSize = b.getAttribute("data-vg-set-size");
445
+ const stepBy = b.getAttribute("data-vg-step");
446
+ const scroll = b.getAttribute("data-vg-scroll");
447
+ if (setTheme)
448
+ set("theme", setTheme);
449
+ else if (setSize) {
450
+ chosen = setSize;
451
+ set("size", setSize);
452
+ }
453
+ else if (stepBy)
454
+ step(Number(stepBy));
455
+ else if (scroll && track) {
456
+ track.scrollBy({ left: Number(scroll) * track.clientWidth * 0.9, behavior: reducedMotion() ? "auto" : "smooth" });
457
+ }
458
+ else if (b.hasAttribute("data-vg-close"))
459
+ box.close();
460
+ else if (b.getAttribute("role") === "tab")
461
+ select(b);
462
+ };
463
+ const onKey = (e) => {
464
+ const target = e.target;
465
+ if (box.open && box.contains(target)) {
466
+ if (e.key === "ArrowRight")
467
+ step(1);
468
+ else if (e.key === "ArrowLeft")
469
+ step(-1);
470
+ return;
471
+ }
472
+ if (target.getAttribute("role") !== "tab")
473
+ return;
474
+ const i = tabs.indexOf(target);
475
+ const next = e.key === "ArrowRight" ? i + 1 : e.key === "ArrowLeft" ? i - 1 : e.key === "Home" ? 0 : e.key === "End" ? tabs.length - 1 : null;
476
+ if (next === null || i === -1)
477
+ return;
478
+ e.preventDefault();
479
+ select(tabs[(next + tabs.length) % tabs.length], true);
480
+ };
481
+ const onClose = () => {
482
+ unlock?.();
483
+ current = null;
484
+ view.replaceChildren();
485
+ if (opener?.isConnected)
486
+ opener.focus();
487
+ opener = null;
488
+ };
489
+ // A gallery without theme buttons follows the page: <html data-theme> as it changes, else the reader's setting.
490
+ const scheme = matchMedia("(prefers-color-scheme: dark)");
491
+ const onScheme = () => set("theme", pageTheme());
492
+ let observer = null;
493
+ if (followsPage) {
494
+ observer = new MutationObserver(onScheme);
495
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
496
+ scheme.addEventListener?.("change", onScheme);
497
+ }
498
+ // The strip's buttons follow its width too (a rotated phone, a gallery that was hidden when it hydrated).
499
+ const resize = track && typeof ResizeObserver === "function" ? new ResizeObserver(edges) : null;
500
+ if (track && resize)
501
+ resize.observe(track);
502
+ root.addEventListener("click", onClick);
503
+ if (caps) {
504
+ root.addEventListener("pointerover", onIntent);
505
+ root.addEventListener("focusin", onIntent);
506
+ // After the page has loaded, in idle time: preloading never competes with the page itself.
507
+ if (document.readyState === "complete")
508
+ onLoad();
509
+ else
510
+ addEventListener("load", onLoad, { once: true });
511
+ }
512
+ root.addEventListener("keydown", onKey);
513
+ box.addEventListener("close", onClose);
514
+ track?.addEventListener("scroll", edges, { passive: true });
515
+ for (const img of all("img.vg-img"))
516
+ watch(img);
517
+ set("theme", pageTheme());
518
+ fit();
519
+ edges();
520
+ const gallery = {
521
+ root,
522
+ setTheme: (t) => set("theme", t),
523
+ setSize: (s) => {
524
+ chosen = s;
525
+ fit();
526
+ },
527
+ open: (key) => {
528
+ for (const t of tabs) {
529
+ const p = panelOf(t);
530
+ if (p && cardOf(key, p))
531
+ select(t);
532
+ }
533
+ const shownPanel = panel();
534
+ const card = shownPanel ? cardOf(key, shownPanel) : null;
535
+ if (!card)
536
+ throw new Error(`no screen "${key}" in this gallery`);
537
+ open(card);
538
+ },
539
+ close: () => box.close(),
540
+ destroy: () => {
541
+ unlock?.();
542
+ root.removeEventListener("click", onClick);
543
+ root.removeEventListener("pointerover", onIntent);
544
+ root.removeEventListener("focusin", onIntent);
545
+ removeEventListener("load", onLoad);
546
+ destroyed = true;
547
+ preloader?.stop();
548
+ preloader = null;
549
+ root.removeEventListener("keydown", onKey);
550
+ box.removeEventListener("close", onClose);
551
+ track?.removeEventListener("scroll", edges);
552
+ observer?.disconnect();
553
+ resize?.disconnect();
554
+ scheme.removeEventListener?.("change", onScheme);
555
+ hydrated.delete(root);
556
+ },
557
+ };
558
+ hydrated.set(root, gallery);
559
+ return gallery;
560
+ }
@@ -0,0 +1,10 @@
1
+ import { type Gallery } from "./hydrate.js";
2
+ import { type LoadOptions } from "./load.js";
3
+ export { buildModel, parseShot, humanize, slugify, DEFAULT_TITLE } from "./model.js";
4
+ export type { Manifest, ManifestGroup, ManifestItem, Model, Group, Screen, Variant, Thumb, Options, PreloadCaps, Size, Theme } from "./model.js";
5
+ export { render, escapeHtml } from "./render.js";
6
+ export { hydrate, type Gallery, type HydrateOptions } from "./hydrate.js";
7
+ export { load, type LoadOptions } from "./load.js";
8
+ /** Renders the gallery into an empty element and hydrates it. When the manifest can't be read, the element says so
9
+ * and the promise rejects. */
10
+ export declare function mount(el: HTMLElement, options: LoadOptions): Promise<Gallery>;
package/dist/index.js ADDED
@@ -0,0 +1,36 @@
1
+ // visualci-gallery: a screenshots page from VisualCI's public gallery (https://visualci.com/docs/gallery/).
2
+ //
3
+ // mount(el, { manifest }) fetches the manifest, renders the gallery into an empty element and hydrates it.
4
+ // hydrate(el) brings markup a server rendered (the Astro component, the Ruby gem, the Python package)
5
+ // to life.
6
+ // load(options) the manifest's model, for rendering at build time: it throws when the manifest can't be
7
+ // read or has nothing to show, so a static site's build fails instead of shipping an empty
8
+ // page.
9
+ import { render } from "./render.js";
10
+ import { hydrate, hydratedGallery } from "./hydrate.js";
11
+ import { load } from "./load.js";
12
+ export { buildModel, parseShot, humanize, slugify, DEFAULT_TITLE } from "./model.js";
13
+ export { render, escapeHtml } from "./render.js";
14
+ export { hydrate } from "./hydrate.js";
15
+ export { load } from "./load.js";
16
+ /** Renders the gallery into an empty element and hydrates it. When the manifest can't be read, the element says so
17
+ * and the promise rejects. */
18
+ export async function mount(el, options) {
19
+ let model;
20
+ try {
21
+ model = await load(options);
22
+ }
23
+ catch (e) {
24
+ const p = document.createElement("p");
25
+ p.className = "vg-error";
26
+ p.textContent = "The screenshots couldn't be loaded.";
27
+ el.replaceChildren(p);
28
+ throw e;
29
+ }
30
+ // Mounting again replaces the gallery: the old one's listeners go first.
31
+ const old = el.querySelector("[data-vg]");
32
+ if (old)
33
+ hydratedGallery(old)?.destroy();
34
+ el.innerHTML = render(model);
35
+ return hydrate(el);
36
+ }
package/dist/load.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { type Model, type Options } from "./model.js";
2
+ export interface LoadOptions extends Options {
3
+ /** The manifest's URL: `https://app.visualci.com/g/<org>/<project>.json`. */
4
+ manifest: string;
5
+ /** How long to wait for it, in milliseconds. Default 20000. */
6
+ timeout?: number;
7
+ /** How many times to try. Default 3. */
8
+ attempts?: number;
9
+ /** A fetch to use in place of the global one. */
10
+ fetch?: typeof fetch;
11
+ }
12
+ /** Fetches the manifest and builds its model. Throws, naming the URL, when it can't be read or shows nothing. */
13
+ export declare function load(options: LoadOptions): Promise<Model>;