@allons-y/actions-file-diff 0.2.0 โ†’ 0.3.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.
package/src/render.js DELETED
@@ -1,191 +0,0 @@
1
- /*!
2
- * Copyright 2025 Allons-Y. All rights reserved.
3
- *
4
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License. You may obtain a copy
6
- * of the License at <http://www.apache.org/licenses/LICENSE-2.0>
7
- */
8
-
9
- import { isReportedFile, printChange, printPercentChange } from "./report.js";
10
- import { bytesToSize } from "./utilities.js";
11
-
12
- /** GitHub caps a step summary at 1 MiB; keep headroom for the size report. */
13
- export const SUMMARY_BUDGET = 900 * 1024;
14
-
15
- /** Width of the text bars in the markdown size chart. */
16
- const BAR_WIDTH = 20;
17
-
18
- /** Status labels shared by both renderers. */
19
- const STATUS_LABEL = { added: "๐Ÿ†• added", removed: "๐Ÿšจ removed", modified: "โœ๏ธ modified" };
20
-
21
- /**
22
- * @typedef {object} SizeRow
23
- * @property {string} packageName
24
- * @property {string} [packageDir] Package directory relative to the root.
25
- * @property {string} file Readable filename within the package.
26
- * @property {number|undefined} headByteSize
27
- * @property {number|undefined} baseByteSize
28
- */
29
-
30
- /**
31
- * Escapes text for HTML.
32
- * @param {unknown} value
33
- * @returns {string}
34
- */
35
- export function escapeHtml(value) {
36
- return String(value ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
37
- }
38
-
39
- /**
40
- * Flattens report sections into one row per reported file.
41
- * @param {import("./report.js").Section[]} sections
42
- * @returns {SizeRow[]}
43
- */
44
- export function sizeRows(sections = []) {
45
- return sections.flatMap(({ name, packageDir, files }) =>
46
- [...files.keys()]
47
- .filter(isReportedFile)
48
- .sort()
49
- .map((file) => ({ packageName: name, packageDir, file, ...files.get(file) })),
50
- );
51
- }
52
-
53
- /**
54
- * Bar length as a 0โ€“1 fraction of `max`, on a log scale so small files stay
55
- * visible next to large ones.
56
- * @param {number|undefined} value
57
- * @param {number} max
58
- * @returns {number}
59
- */
60
- export function barScale(value, max) {
61
- if (!value || !max) return 0;
62
- return Math.log1p(value) / Math.log1p(max);
63
- }
64
-
65
- /**
66
- * Text bar scaled against a maximum (log scale, see barScale).
67
- * @param {number|undefined} value
68
- * @param {number} max
69
- * @returns {string}
70
- */
71
- export function textBar(value, max) {
72
- if (!value || !max) return "";
73
- return "โ–ˆ".repeat(Math.max(1, Math.round(barScale(value, max) * BAR_WIDTH)));
74
- }
75
-
76
- /**
77
- * Markdown fence longer than any backtick run in the content.
78
- * @param {string} content
79
- * @returns {string}
80
- */
81
- export function fenceFor(content) {
82
- const longest = Math.max(0, ...(String(content).match(/`+/g) ?? []).map((run) => run.length));
83
- return "`".repeat(Math.max(3, longest + 1));
84
- }
85
-
86
- /**
87
- * Unified diff text for one change, including file headers.
88
- * @param {import("./changes.js").TextChange} change
89
- * @returns {string}
90
- */
91
- export function unifiedDiff({ file, status, hunks }) {
92
- const from = status === "added" ? "/dev/null" : `a/${file}`;
93
- const to = status === "removed" ? "/dev/null" : `b/${file}`;
94
- const body = hunks.flatMap(({ oldStart, oldLines, newStart, newLines, lines }) => [`@@ -${oldStart},${oldLines} +${newStart},${newLines} @@`, ...lines]);
95
- return [`--- ${from}`, `+++ ${to}`, ...body].join("\n");
96
- }
97
-
98
- /**
99
- * One-line change stats for the pull request comment.
100
- * @param {object} options
101
- * @param {import("./changes.js").Stats} options.stats
102
- * @param {number} [options.imageCount]
103
- * @returns {string}
104
- */
105
- export function renderStats({ stats, imageCount = 0 }) {
106
- const files = stats.added + stats.removed + stats.modified;
107
- if (files === 0) return "**Changed files**: none";
108
- const parts = [`**Changed files**: ${files}`, `${stats.added} added`, `${stats.removed} removed`, `${stats.modified} modified`];
109
- const lines = `**Lines**: +${stats.additions} / โˆ’${stats.deletions}`;
110
- const images = imageCount ? ` ยท **Images**: ${imageCount}` : "";
111
- return `${parts[0]} (${parts.slice(1).join(", ")}) ยท ${lines}${images}`;
112
- }
113
-
114
- /**
115
- * Markdown size chart: one row per file with base/head text bars.
116
- * @param {SizeRow[]} rows
117
- * @param {boolean} hasBase
118
- * @returns {string[]}
119
- */
120
- export function renderSizeChartMarkdown(rows, hasBase) {
121
- if (rows.length === 0) return ["No size changes."];
122
- const max = Math.max(...rows.flatMap(({ headByteSize, baseByteSize }) => [headByteSize ?? 0, baseByteSize ?? 0]));
123
- const header = hasBase ? ["Package", "File", "Base", "Head", "ฮ”", "Chart (base / head, log)"] : ["Package", "File", "Head", "Chart (log)"];
124
- const body = rows.map(({ packageName, file, headByteSize, baseByteSize }) => {
125
- const headBar = `\`${textBar(headByteSize, max) || "ยท"}\``;
126
- if (!hasBase) return [packageName, file, bytesToSize(headByteSize), headBar];
127
- const baseBar = `\`${textBar(baseByteSize, max) || "ยท"}\``;
128
- const percent = printPercentChange(headByteSize, baseByteSize);
129
- const delta = printChange(headByteSize, baseByteSize);
130
- return [packageName, file, bytesToSize(baseByteSize), bytesToSize(headByteSize), delta !== "-" && percent ? `${delta} (${percent})` : delta, `${baseBar}<br/>${headBar}`];
131
- });
132
- return [header, header.map(() => "-"), ...body].map((row) => `| ${row.join(" | ")} |`);
133
- }
134
-
135
- /**
136
- * Job summary markdown with collapsible Sizes, Line diffs and (when present)
137
- * Visual diffs sections. Line diffs stop once the byte budget is spent.
138
- * @param {object} options
139
- * @param {SizeRow[]} options.rows
140
- * @param {boolean} options.hasBase
141
- * @param {ReturnType<import("./changes.js").collectChanges>} options.changes
142
- * @param {number} [options.budget] Byte budget for the diff section.
143
- * @param {string} [options.reportUrl] Full report link shown when diffs are truncated.
144
- * @returns {string}
145
- */
146
- export function renderSummaryMarkdown({ rows, hasBase, changes, budget = SUMMARY_BUDGET, reportUrl }) {
147
- const out = ["<details open>", "<summary><b>๐Ÿ“Š Sizes</b></summary>", "", ...renderSizeChartMarkdown(rows, hasBase), "", "</details>", ""];
148
-
149
- out.push("<details>", `<summary><b>๐Ÿ“ Line diffs (${changes.text.length})</b></summary>`, "");
150
- if (changes.text.length === 0) out.push("No text changes.", "");
151
-
152
- let spent = 0;
153
- const truncated = [];
154
- changes.text.forEach((change) => {
155
- const counts = change.skipped ? "" : ` (+${change.additions} / โˆ’${change.deletions})`;
156
- const heading = `#### \`${change.file}\` โ€” ${STATUS_LABEL[change.status]}${counts}`;
157
- if (change.skipped) {
158
- out.push(heading, "", `_Line diff skipped: ${change.skipped}._`, "");
159
- return;
160
- }
161
- if (change.omitted) {
162
- out.push(heading, "", `_Diff left out because ${change.omitted}. Raise \`max-diff-lines\` to include it._`, "");
163
- return;
164
- }
165
- const diff = unifiedDiff(change);
166
- const fence = fenceFor(diff);
167
- const block = [heading, "", `${fence}diff`, diff, fence, ""].join("\n");
168
- const size = Buffer.byteLength(block);
169
- if (spent + size > budget) {
170
- truncated.push(change.file);
171
- return;
172
- }
173
- spent += size;
174
- out.push(block);
175
- });
176
-
177
- if (truncated.length > 0) {
178
- const where = reportUrl ? ` See the [full report](${reportUrl}).` : "";
179
- out.push(`> [!NOTE]`, `> ${truncated.length} diff(s) omitted to stay under GitHub's summary size limit: ${truncated.map((f) => `\`${f}\``).join(", ")}.${where}`, "");
180
- }
181
- out.push("</details>", "");
182
-
183
- if (changes.images.length > 0) {
184
- out.push("<details>", `<summary><b>๐Ÿ–ผ๏ธ Visual diffs (${changes.images.length})</b></summary>`, "");
185
- out.push("| File | Status | Base | Head |", "| - | - | - | - |");
186
- changes.images.forEach(({ file, status, baseByteSize, headByteSize }) => out.push(`| \`${file}\` | ${STATUS_LABEL[status]} | ${bytesToSize(baseByteSize)} | ${bytesToSize(headByteSize)} |`));
187
- out.push("", reportUrl ? `Side-by-side previews are in the [full report](${reportUrl}).` : "_Set `visual-diff: branch` to publish side-by-side image previews._", "", "</details>", "");
188
- }
189
-
190
- return out.join("\n");
191
- }
@@ -1,398 +0,0 @@
1
- /* Browser script for the visual diff page (inlined by page.js). */
2
- (() => {
3
- const $ = (sel, root = document) => root.querySelector(sel);
4
- const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
5
- const store = {
6
- get(key) {
7
- try {
8
- return localStorage.getItem(`file-diff:${key}`);
9
- } catch {
10
- return null;
11
- }
12
- },
13
- set(key, value) {
14
- try {
15
- localStorage.setItem(`file-diff:${key}`, value);
16
- } catch {
17
- // Storage blocked; the choice still applies to this view.
18
- }
19
- },
20
- };
21
-
22
- const code = $(".code-main");
23
-
24
- /** Index an arrow, Home or End key moves to in a horizontal list, or undefined for other keys. */
25
- function targetIndex(key, i, length, rtl) {
26
- const step = { ArrowRight: rtl ? -1 : 1, ArrowLeft: rtl ? 1 : -1 }[key];
27
- if (step) return (i + step + length) % length;
28
- if (key === "Home") return 0;
29
- if (key === "End") return length - 1;
30
- return undefined;
31
- }
32
-
33
- /* ---- Tabs: selection follows focus, roving tabindex ------------------ */
34
- const tablist = $('[role="tablist"]');
35
- const tabs = $$('[role="tab"]', tablist);
36
- const panelFor = (tab) => document.getElementById(tab.id.replace(/^tab-/, "panel-"));
37
-
38
- function selectTab(tab, { focus = false, push = true } = {}) {
39
- tabs.forEach((t) => {
40
- const on = t === tab;
41
- t.setAttribute("aria-selected", String(on));
42
- t.tabIndex = on ? 0 : -1;
43
- const panel = panelFor(t);
44
- if (on) panel.removeAttribute("hidden");
45
- else panel.setAttribute("hidden", "until-found");
46
- });
47
- if (focus) tab.focus();
48
- tab.scrollIntoView({ block: "nearest", inline: "nearest" });
49
- if (push) history.replaceState(null, "", `#${tab.id.slice(4)}`);
50
- }
51
-
52
- tablist.addEventListener("click", (e) => {
53
- const tab = e.target.closest('[role="tab"]');
54
- if (tab) selectTab(tab);
55
- });
56
- tablist.addEventListener("keydown", (e) => {
57
- const i = tabs.indexOf(document.activeElement);
58
- const next = i < 0 ? undefined : targetIndex(e.key, i, tabs.length, getComputedStyle(tablist).direction === "rtl");
59
- if (next === undefined) return;
60
- e.preventDefault();
61
- selectTab(tabs[next], { focus: true });
62
- });
63
- // Find-in-page revealed a hidden panel: select its tab.
64
- $$('[role="tabpanel"]').forEach((panel) =>
65
- panel.addEventListener("beforematch", () => {
66
- const tab = document.getElementById(panel.getAttribute("aria-labelledby"));
67
- if (tab) selectTab(tab, { push: false });
68
- }),
69
- );
70
-
71
- /** Shows the tab holding an element, then scrolls to it. */
72
- function reveal(el) {
73
- const panel = el.closest('[role="tabpanel"]');
74
- const tab = panel && document.getElementById(panel.getAttribute("aria-labelledby"));
75
- if (tab && tab.getAttribute("aria-selected") !== "true") selectTab(tab, { push: false });
76
- const details = el.querySelector("details");
77
- if (details) {
78
- details.open = true;
79
- renderFile(el);
80
- }
81
- el.scrollIntoView({ block: "start" });
82
- }
83
-
84
- document.addEventListener("click", (e) => {
85
- const link = e.target.closest('a[href^="#f-"]');
86
- if (!link) return;
87
- const target = document.getElementById(link.hash.slice(1));
88
- if (!target) return;
89
- e.preventDefault();
90
- reveal(target);
91
- history.replaceState(null, "", link.hash);
92
- });
93
-
94
- /* ---- Toolbars: one tab stop, arrow keys move (focusgroup fallback) --- */
95
- $$('[role="toolbar"]').forEach((bar) => {
96
- if ("focusGroup" in HTMLElement.prototype) return bar.setAttribute("focusgroup", "toolbar wrap");
97
- const items = () => $$("button", bar);
98
- items().forEach((b, i) => (b.tabIndex = i ? -1 : 0));
99
- bar.addEventListener("focusin", ({ target }) => {
100
- if (items().includes(target)) items().forEach((b) => (b.tabIndex = b === target ? 0 : -1));
101
- });
102
- bar.addEventListener("keydown", (e) => {
103
- const list = items();
104
- const i = list.indexOf(document.activeElement);
105
- const next = i < 0 ? undefined : targetIndex(e.key, i, list.length, getComputedStyle(bar).direction === "rtl");
106
- if (next === undefined) return;
107
- e.preventDefault();
108
- list[next].focus();
109
- });
110
- });
111
-
112
- /** Presses one button in a segmented group. */
113
- function press(group, button) {
114
- $$("button", group).forEach((b) => b.setAttribute("aria-pressed", String(b === button)));
115
- }
116
-
117
- /* ---- Code: rows are built from JSON when a file opens ----------------- */
118
- const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
119
- const esc = (text) => text.replace(/[&<>"']/g, (c) => ESCAPES[c]);
120
-
121
- /** Escapes a line, wrapping the changed `[start, end, โ€ฆ]` ranges in <mark>. */
122
- function markup(text, ranges) {
123
- if (!ranges) return esc(text);
124
- let out = "";
125
- let at = 0;
126
- for (let k = 0; k < ranges.length; k += 2) {
127
- out += `${esc(text.slice(at, ranges[k]))}<mark>${esc(text.slice(ranges[k], ranges[k + 1]))}</mark>`;
128
- at = ranges[k + 1];
129
- }
130
- return out + esc(text.slice(at));
131
- }
132
-
133
- /** Old and new line numbers for every line of a hunk (null where a side has none). */
134
- function numbers({ o, n, l }) {
135
- let oldNo = o;
136
- let newNo = n;
137
- return l.map((line) => (line[0] === "-" ? [oldNo++, null] : line[0] === "+" ? [null, newNo++] : line[0] === "\\" ? [null, null] : [oldNo++, newNo++]));
138
- }
139
-
140
- const metaRow = (line, cols) => `<tr class="meta"><td colspan="${cols}">${esc(line)}</td></tr>`;
141
-
142
- function unifiedRows(hunk) {
143
- const nos = numbers(hunk);
144
- const rows = [`<tr class="hunk"><td colspan="3">${esc(hunk.h)}</td></tr>`];
145
- hunk.l.forEach((line, i) => {
146
- const sign = line[0];
147
- if (sign === "\\") return rows.push(metaRow(line, 3));
148
- const kind = sign === "-" ? "del" : sign === "+" ? "add" : "ctx";
149
- rows.push(`<tr class="${kind}"><td class="ln">${nos[i][0] ?? ""}</td><td class="ln">${nos[i][1] ?? ""}</td><td class="code"><span class="sign">${sign}</span>${markup(line.slice(1), hunk.m[i])}</td></tr>`);
150
- });
151
- return rows;
152
- }
153
-
154
- const EMPTY_CELLS = '<td class="ln empty"></td><td class="code empty"></td>';
155
-
156
- /** Side-by-side rows. Edited line pairs share a row; other changes fill the gaps between them. */
157
- function splitRows(hunk) {
158
- const nos = numbers(hunk);
159
- const pairOf = new Map(hunk.p);
160
- const cells = (i, kind, no) => (i < 0 ? EMPTY_CELLS : `<td class="ln ${kind}">${no}</td><td class="code ${kind}">${markup(hunk.l[i].slice(1), hunk.m[i])}</td>`);
161
- const rows = [`<tr class="hunk"><td colspan="4">${esc(hunk.h)}</td></tr>`];
162
-
163
- for (let i = 0; i < hunk.l.length; ) {
164
- const sign = hunk.l[i][0];
165
- if (sign === "\\") {
166
- rows.push(metaRow(hunk.l[i++], 4));
167
- } else if (sign !== "-" && sign !== "+") {
168
- const text = markup(hunk.l[i].slice(1));
169
- rows.push(`<tr class="ctx"><td class="ln">${nos[i][0]}</td><td class="code">${text}</td><td class="ln">${nos[i][1]}</td><td class="code">${text}</td></tr>`);
170
- i++;
171
- } else {
172
- const dels = [];
173
- const adds = [];
174
- const notes = [];
175
- while (hunk.l[i]?.[0] === "-") dels.push(i++);
176
- while (hunk.l[i]?.[0] === "\\") notes.push(i++);
177
- while (hunk.l[i]?.[0] === "+") adds.push(i++);
178
-
179
- const pairs = [];
180
- let di = 0;
181
- let ai = 0;
182
- const fill = (dEnd, aEnd) => {
183
- for (let k = 0, n = Math.max(dEnd - di, aEnd - ai); k < n; k++) pairs.push([di + k < dEnd ? dels[di + k] : -1, ai + k < aEnd ? adds[ai + k] : -1]);
184
- di = dEnd;
185
- ai = aEnd;
186
- };
187
- dels.forEach((d, dPos) => {
188
- const aPos = adds.indexOf(pairOf.get(d));
189
- if (aPos < ai) return;
190
- fill(dPos, aPos);
191
- pairs.push([d, adds[aPos]]);
192
- di = dPos + 1;
193
- ai = aPos + 1;
194
- });
195
- fill(dels.length, adds.length);
196
-
197
- pairs.forEach(([d, a]) => rows.push(`<tr>${cells(d, "del", nos[d]?.[0])}${cells(a, "add", nos[a]?.[1])}</tr>`));
198
- notes.forEach((n) => rows.push(metaRow(hunk.l[n], 4)));
199
- }
200
- }
201
- return rows;
202
- }
203
-
204
- const parsed = new WeakMap();
205
-
206
- /** Builds a file's diff table for the current layout, once per layout. */
207
- function renderFile(section) {
208
- const scroll = section && $(".diff-scroll", section);
209
- if (!scroll || !code) return;
210
- const view = code.dataset.view;
211
- if (scroll.dataset.view === view) return;
212
- if (!parsed.has(scroll)) parsed.set(scroll, JSON.parse($('script[type="application/json"]', scroll).textContent));
213
- const rows = parsed.get(scroll).flatMap((hunk) => (view === "split" ? splitRows(hunk) : unifiedRows(hunk)));
214
- const table = view === "split" ? `<table class="diff split"><colgroup><col class="ln-col"><col><col class="ln-col"><col></colgroup>${rows.join("")}</table>` : `<table class="diff unified">${rows.join("")}</table>`;
215
- $(".rendered", scroll)?.remove();
216
- scroll.insertAdjacentHTML("beforeend", `<div class="rendered">${table}</div>`);
217
- scroll.dataset.view = view;
218
- }
219
-
220
- if (code) {
221
- const sections = $$(".file", code);
222
- const renderOpen = () => sections.filter((section) => $("details", section).open).forEach(renderFile);
223
- const layout = $('[aria-label="Diff layout"]', code);
224
- const collapse = $('[data-action="collapse"]', code);
225
- const syncCollapse = () => (collapse.textContent = sections.every((section) => $("details", section).open) ? "Collapse all" : "Expand all");
226
-
227
- const setView = (view) => {
228
- code.dataset.view = view;
229
- press(layout, $(`button[data-view="${view}"]`, code));
230
- renderOpen();
231
- };
232
-
233
- layout.addEventListener("click", (e) => {
234
- const b = e.target.closest("button[data-view]");
235
- if (!b) return;
236
- setView(b.dataset.view);
237
- store.set("view", b.dataset.view);
238
- });
239
- collapse.addEventListener("click", () => {
240
- const open = collapse.textContent.startsWith("Expand");
241
- sections.forEach((section) => ($("details", section).open = open));
242
- syncCollapse();
243
- });
244
- // `toggle` doesn't bubble, so listen while it travels down.
245
- code.addEventListener(
246
- "toggle",
247
- (e) => {
248
- if (e.target.open) renderFile(e.target.closest(".file"));
249
- syncCollapse();
250
- },
251
- true,
252
- );
253
-
254
- setView(store.get("view") === "split" ? "split" : "unified");
255
- syncCollapse();
256
- }
257
-
258
- /* ---- Visual: modes, sliders, swipe drag, zoom, pager ----------------- */
259
- const viewer = $(".viewer");
260
- if (viewer) {
261
- const items = $$(".image-item", viewer);
262
- const listButtons = $$(".filelist button", viewer.parentElement);
263
- const modes = $(".modes", viewer);
264
- let index = 0;
265
-
266
- const current = () => items[index];
267
-
268
- const FIT_HEIGHT = 420;
269
-
270
- /** Sizes both versions by one scale so stacked modes stay aligned. Fit fills the stage. */
271
- function applyZoom() {
272
- const item = current();
273
- const imgs = $$("img", item);
274
- if (!imgs.every((img) => img.complete && img.naturalWidth)) {
275
- imgs.forEach((img) => img.addEventListener("load", applyZoom, { once: true }));
276
- return;
277
- }
278
- const zoom = viewer.dataset.zoom;
279
- let scale = Number(zoom);
280
- if (zoom === "fit") {
281
- const stage = $(".stage", item);
282
- const pad = parseFloat(getComputedStyle(stage).paddingLeft) * 2;
283
- const columns = viewer.dataset.mode === "side" && !item.hasAttribute("data-single") ? 2 : 1;
284
- const width = (stage.clientWidth - pad - (columns - 1) * 16) / columns;
285
- // The stage has no size while its tab is hidden; the ResizeObserver reruns this once it shows.
286
- if (width <= 0) return;
287
- const maxW = Math.max(...imgs.map((img) => img.naturalWidth));
288
- const maxH = Math.max(...imgs.map((img) => img.naturalHeight));
289
- scale = Math.min(width / maxW, FIT_HEIGHT / maxH);
290
- }
291
- imgs.forEach((img) => {
292
- img.style.inlineSize = `${Math.round(img.naturalWidth * scale)}px`;
293
- img.classList.toggle("upscaled", scale > 1);
294
- });
295
- }
296
- new ResizeObserver(() => viewer.dataset.zoom === "fit" && applyZoom()).observe(viewer);
297
-
298
- function syncModes() {
299
- const single = current().hasAttribute("data-single");
300
- $$("button", modes).forEach((b) => {
301
- if (b.dataset.mode === "side") return;
302
- if (single) b.setAttribute("aria-disabled", "true");
303
- else b.removeAttribute("aria-disabled");
304
- });
305
- }
306
-
307
- function show(i) {
308
- index = (i + items.length) % items.length;
309
- items.forEach((item, k) => (item.hidden = k !== index));
310
- listButtons.forEach((b, k) => (k === index ? b.setAttribute("aria-current", "true") : b.removeAttribute("aria-current")));
311
- $(".pager-count", viewer).textContent = `${index + 1} of ${items.length}`;
312
- syncModes();
313
- applyZoom();
314
- }
315
-
316
- // Natural dimensions under each image header.
317
- items.forEach((item) =>
318
- $$("img", item).forEach((img) => {
319
- const write = () => {
320
- const out = $(`[data-dims="${img.dataset.side}"]`, item);
321
- if (out) out.textContent = `${img.dataset.side} ${img.naturalWidth}ร—${img.naturalHeight}`;
322
- };
323
- if (img.complete && img.naturalWidth) write();
324
- else img.addEventListener("load", write, { once: true });
325
- }),
326
- );
327
-
328
- $(".toolbar", viewer).addEventListener("click", (e) => {
329
- const b = e.target.closest("button");
330
- if (!b || b.getAttribute("aria-disabled") === "true") return;
331
- for (const key of ["mode", "bg", "zoom"]) {
332
- if (b.dataset[key] === undefined) continue;
333
- viewer.dataset[key] = b.dataset[key];
334
- press(b.parentElement, b);
335
- if (key !== "bg") applyZoom();
336
- if (key !== "zoom") store.set(key, b.dataset[key]);
337
- }
338
- });
339
- for (const key of ["mode", "bg"]) {
340
- const saved = store.get(key);
341
- const b = saved && $(`button[data-${key}="${saved}"]`, viewer);
342
- if (b) {
343
- viewer.dataset[key] = saved;
344
- press(b.parentElement, b);
345
- }
346
- }
347
-
348
- // Range inputs drive --opacity / --pos; keep the filled track in sync.
349
- $$('input[type="range"]', viewer).forEach((input) => {
350
- const output = input.nextElementSibling;
351
- const sync = () => {
352
- const v = Number(input.value);
353
- input.style.setProperty("--control-value", v);
354
- input.style.setProperty("--attr-min", input.min || 0);
355
- input.style.setProperty("--attr-max", input.max || 100);
356
- viewer.style.setProperty(input.dataset.control === "opacity" ? "--opacity" : "--pos", input.dataset.control === "opacity" ? v / 100 : `${v}%`);
357
- output.textContent = `${v}%`;
358
- };
359
- input.addEventListener("input", sync);
360
- sync();
361
- });
362
-
363
- // Drag directly on the image in swipe mode.
364
- const swipeInput = $('input[data-control="pos"]', viewer);
365
- items.forEach((item) => {
366
- const layers = $(".layers", item);
367
- const move = (e) => {
368
- const box = layers.getBoundingClientRect();
369
- swipeInput.value = String(Math.round(Math.min(100, Math.max(0, ((e.clientX - box.left) / box.width) * 100))));
370
- swipeInput.dispatchEvent(new Event("input"));
371
- };
372
- layers.addEventListener("pointerdown", (e) => {
373
- if (viewer.dataset.mode !== "swipe" || item.hasAttribute("data-single")) return;
374
- layers.setPointerCapture(e.pointerId);
375
- move(e);
376
- layers.addEventListener("pointermove", move);
377
- // Fires after pointerup and pointercancel alike, so the listener never outlives the drag.
378
- layers.addEventListener("lostpointercapture", () => layers.removeEventListener("pointermove", move), { once: true });
379
- });
380
- });
381
-
382
- listButtons.forEach((b, k) => b.addEventListener("click", () => show(k)));
383
- $$("[data-step]", viewer).forEach((b) => b.addEventListener("click", () => show(index + Number(b.dataset.step))));
384
- document.addEventListener("keydown", (e) => {
385
- if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;
386
- if ($("#panel-visual")?.hidden || e.target.closest("input, textarea, select, [contenteditable]")) return;
387
- if (e.key === "j" || e.key === "k") show(index + (e.key === "j" ? 1 : -1));
388
- });
389
-
390
- show(0);
391
- }
392
-
393
- /* ---- Open the tab or file named in the URL ---------------------------- */
394
- const initial = location.hash.slice(1);
395
- const initialTab = document.getElementById(`tab-${initial}`);
396
- if (initialTab) selectTab(initialTab, { push: false });
397
- else if (initial && document.getElementById(initial)) reveal(document.getElementById(initial));
398
- })();