@qzsy/dsh-image-viewer 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.
package/dist/client.js ADDED
@@ -0,0 +1,2542 @@
1
+ /**
2
+ * Client half of `@qzsy/dsh-image-viewer`.
3
+ *
4
+ * Replaces the bare built-in image lightbox with a full-screen viewer that
5
+ * behaves like the iPhone Photos app:
6
+ *
7
+ * - open/close zooms from and back to the thumbnail (with cover-crop and radius)
8
+ * - pinch to zoom around the fingers, pan with momentum and rubber-band edges
9
+ * - double-tap / double-click to zoom into the tapped point and back
10
+ * - swipe left/right between every previewable image in the same scroll area
11
+ * - swipe down (or up) to dismiss, with the backdrop fading as you drag
12
+ * - pinch in below fit size to close
13
+ * - single tap toggles the chrome on touch devices
14
+ * - desktop: wheel / Ctrl+wheel / trackpad pinch zoom, trackpad swipe paging,
15
+ * drag to pan, arrow keys, + / - / 0, Esc, filmstrip and download
16
+ *
17
+ * The plugin owns no Host capability. It listens for clicks in the capture
18
+ * phase on `document`, so it runs before React's root listener and the
19
+ * built-in lightbox never opens for images it handles. Clicks with a modifier
20
+ * key, images inside links, and anything marked `data-qiv-ignore` pass through.
21
+ */
22
+ window.__ModuleLoader__.load({
23
+ id: '@qzsy/dsh-image-viewer',
24
+ factory() {
25
+ 'use strict';
26
+
27
+ /** Client dictionary namespace owned by this plugin. */
28
+ const NS = 'imageViewer';
29
+ const ROOT_ATTR = 'data-qiv-root';
30
+ const STYLE_ATTR = 'data-qiv-style';
31
+ const IGNORE_ATTR = 'data-qiv-ignore';
32
+
33
+ /** Horizontal gap between slides, in CSS px. */
34
+ const GAP = 24;
35
+ /** Movement before a press becomes a drag. */
36
+ const SLOP = 8;
37
+ const TAP_MAX_MS = 500;
38
+ const DOUBLE_TAP_MS = 300;
39
+ const DOUBLE_TAP_PX = 32;
40
+ /** iOS UIScrollView "normal" deceleration rate, per millisecond. */
41
+ const DECEL = 0.998;
42
+ const MAX_ITEMS = 400;
43
+ /** Bare <img> elements smaller than this are treated as icons. */
44
+ const MIN_BARE_W = 96;
45
+ const MIN_BARE_H = 64;
46
+
47
+ /** Spring presets: k = stiffness, c = damping (unit mass). */
48
+ const SPRING = {
49
+ snap: { k: 420, c: 36 },
50
+ open: { k: 300, c: 31 },
51
+ close: { k: 380, c: 39 },
52
+ page: { k: 260, c: 31 },
53
+ glide: { k: 170, c: 26 },
54
+ };
55
+
56
+ const zh = {
57
+ dialog: '图片查看器',
58
+ close: '关闭',
59
+ prev: '上一张',
60
+ next: '下一张',
61
+ zoomIn: '放大',
62
+ zoomOut: '还原',
63
+ download: '下载原图',
64
+ counter: '{i} / {n}',
65
+ failed: '图片加载失败',
66
+ thumb: '第 {i} 张',
67
+ edit: '编辑标注',
68
+ 'edit.dialog': '标注图片',
69
+ 'edit.tools': '标注工具',
70
+ 'edit.pen': '画笔',
71
+ 'edit.shapes': '形状',
72
+ 'edit.eraser': '橡皮擦',
73
+ 'edit.undo': '撤销',
74
+ 'edit.redo': '重做',
75
+ 'edit.cancel': '返回',
76
+ 'edit.done': '完成并添加到输入框',
77
+ 'edit.size': '笔触粗细',
78
+ 'edit.color': '颜色',
79
+ 'edit.custom': '自定义颜色',
80
+ 'edit.color.white': '白色',
81
+ 'edit.color.black': '黑色',
82
+ 'edit.color.red': '红色',
83
+ 'edit.color.orange': '橙色',
84
+ 'edit.color.yellow': '黄色',
85
+ 'edit.color.green': '绿色',
86
+ 'edit.color.blue': '蓝色',
87
+ 'edit.color.purple': '紫色',
88
+ 'edit.shape.rect': '矩形',
89
+ 'edit.shape.ellipse': '椭圆',
90
+ 'edit.shape.arrow': '箭头',
91
+ 'edit.shape.line': '直线',
92
+ 'edit.injected': '已添加到输入框,补充说明后发送',
93
+ 'edit.noComposer': '没有找到输入框,已下载标注后的图片',
94
+ 'edit.tainted': '这张图片来自其他站点,浏览器不允许导出',
95
+ 'edit.taintedHint': '图片来自其他站点,可能无法导出',
96
+ 'edit.exportFailed': '导出图片失败',
97
+ };
98
+ const en = {
99
+ dialog: 'Image viewer',
100
+ close: 'Close',
101
+ prev: 'Previous image',
102
+ next: 'Next image',
103
+ zoomIn: 'Zoom in',
104
+ zoomOut: 'Reset zoom',
105
+ download: 'Download original',
106
+ counter: '{i} / {n}',
107
+ failed: 'Image failed to load',
108
+ thumb: 'Image {i}',
109
+ edit: 'Edit and annotate',
110
+ 'edit.dialog': 'Annotate image',
111
+ 'edit.tools': 'Annotation tools',
112
+ 'edit.pen': 'Pen',
113
+ 'edit.shapes': 'Shapes',
114
+ 'edit.eraser': 'Eraser',
115
+ 'edit.undo': 'Undo',
116
+ 'edit.redo': 'Redo',
117
+ 'edit.cancel': 'Back',
118
+ 'edit.done': 'Done, add to message',
119
+ 'edit.size': 'Stroke width',
120
+ 'edit.color': 'Colour',
121
+ 'edit.custom': 'Custom colour',
122
+ 'edit.color.white': 'White',
123
+ 'edit.color.black': 'Black',
124
+ 'edit.color.red': 'Red',
125
+ 'edit.color.orange': 'Orange',
126
+ 'edit.color.yellow': 'Yellow',
127
+ 'edit.color.green': 'Green',
128
+ 'edit.color.blue': 'Blue',
129
+ 'edit.color.purple': 'Purple',
130
+ 'edit.shape.rect': 'Rectangle',
131
+ 'edit.shape.ellipse': 'Ellipse',
132
+ 'edit.shape.arrow': 'Arrow',
133
+ 'edit.shape.line': 'Line',
134
+ 'edit.injected': 'Added to the message box. Add a prompt and send.',
135
+ 'edit.noComposer': 'No message box found; the annotated image was downloaded.',
136
+ 'edit.tainted': 'This image comes from another site and the browser blocks exporting it.',
137
+ 'edit.taintedHint': 'Image from another site; export may be blocked.',
138
+ 'edit.exportFailed': 'Could not export the image.',
139
+ };
140
+
141
+ //#region utilities
142
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
143
+ const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
144
+
145
+ /** UIScrollView rubber-band: resistance grows with distance past the edge. */
146
+ function rubber(over, dim) {
147
+ const d = Math.max(1, dim);
148
+ const sign = over < 0 ? -1 : 1;
149
+ const x = Math.abs(over);
150
+ return sign * (1 - 1 / ((x * 0.55) / d + 1)) * d;
151
+ }
152
+
153
+ function rubberClamp(v, lo, hi, dim) {
154
+ if (v < lo) return lo + rubber(v - lo, dim);
155
+ if (v > hi) return hi + rubber(v - hi, dim);
156
+ return v;
157
+ }
158
+
159
+ function media(query) {
160
+ try {
161
+ return typeof window.matchMedia === 'function' && window.matchMedia(query).matches === true;
162
+ } catch {
163
+ return false;
164
+ }
165
+ }
166
+
167
+ const reduceMotion = () => media('(prefers-reduced-motion: reduce)');
168
+
169
+ function format(text, params) {
170
+ return String(text).replace(/\{(\w+)\}/g, (match, key) =>
171
+ params !== undefined && params !== null && key in params ? String(params[key]) : match,
172
+ );
173
+ }
174
+
175
+ function fallbackT(key, params) {
176
+ const lang = (document.documentElement.getAttribute('lang') || navigator.language || 'en').toLowerCase();
177
+ const dict = lang.startsWith('zh') ? zh : en;
178
+ return format(dict[key] ?? en[key] ?? key, params);
179
+ }
180
+
181
+ function h(tag, className, attrs) {
182
+ const node = document.createElement(tag);
183
+ if (className) node.className = className;
184
+ if (attrs) for (const [key, value] of Object.entries(attrs)) node.setAttribute(key, value);
185
+ return node;
186
+ }
187
+
188
+ function cssPx(value, basis) {
189
+ const text = String(value || '0').split(' ')[0];
190
+ const num = parseFloat(text);
191
+ if (!Number.isFinite(num)) return 0;
192
+ return text.endsWith('%') ? (num / 100) * basis : num;
193
+ }
194
+
195
+ function fileName(src) {
196
+ try {
197
+ if (src.startsWith('data:')) {
198
+ const match = /^data:image\/([\w+.-]+)/.exec(src);
199
+ return 'image.' + (match ? match[1].replace('jpeg', 'jpg').replace('svg+xml', 'svg') : 'png');
200
+ }
201
+ const url = new URL(src, location.href);
202
+ const raw = url.searchParams.get('path') || url.pathname;
203
+ const base = decodeURIComponent(raw.split(/[\\/]/).pop() || '');
204
+ return base || 'image';
205
+ } catch {
206
+ return 'image';
207
+ }
208
+ }
209
+ //#endregion
210
+
211
+ //#region spring animator
212
+ /**
213
+ * Drives numeric keys of `state` toward targets with damped springs.
214
+ * Springs keep their velocity when re-targeted, so a gesture can hand its
215
+ * finger velocity to the animation that follows it.
216
+ */
217
+ function createAnimator(state, onFrame) {
218
+ const springs = new Map();
219
+ let calls = [];
220
+ let raf = 0;
221
+ let last = 0;
222
+
223
+ const eps = (key) => (key === 'x' || key === 'y' || key === 'trackX' || key === 'radius' ? 0.2 : 0.001);
224
+
225
+ function frame(ts) {
226
+ raf = 0;
227
+ let dt = (ts - last) / 1000;
228
+ last = ts;
229
+ if (!(dt > 0)) dt = 1 / 60;
230
+ if (dt > 0.064) dt = 0.064;
231
+ const steps = Math.ceil(dt / 0.004);
232
+ const step = dt / steps;
233
+ const settled = [];
234
+ for (const [key, spring] of springs) {
235
+ let x = state[key];
236
+ let v = spring.v;
237
+ for (let i = 0; i < steps; i += 1) {
238
+ const a = -spring.k * (x - spring.target) - spring.c * v;
239
+ v += a * step;
240
+ x += v * step;
241
+ }
242
+ const e = eps(key);
243
+ if (Math.abs(x - spring.target) < e && Math.abs(v) < e * 20) {
244
+ x = spring.target;
245
+ v = 0;
246
+ settled.push(key);
247
+ }
248
+ state[key] = x;
249
+ spring.v = v;
250
+ }
251
+ for (const key of settled) {
252
+ springs.delete(key);
253
+ for (const call of calls) call.keys.delete(key);
254
+ }
255
+ const fire = [];
256
+ calls = calls.filter((call) => {
257
+ if (call.keys.size > 0) return true;
258
+ fire.push(call.cb);
259
+ return false;
260
+ });
261
+ onFrame();
262
+ if (springs.size > 0 && raf === 0) raf = requestAnimationFrame(frame);
263
+ for (const cb of fire) cb();
264
+ }
265
+
266
+ function forget(keys) {
267
+ for (const key of keys) {
268
+ springs.delete(key);
269
+ for (const call of calls) call.keys.delete(key);
270
+ }
271
+ calls = calls.filter((call) => call.keys.size > 0);
272
+ }
273
+
274
+ return {
275
+ to(targets, options = {}) {
276
+ const cfg = options.spring || SPRING.snap;
277
+ const velocity = options.velocity || {};
278
+ const keys = Object.keys(targets);
279
+ // A re-targeted key no longer belongs to the call that started it.
280
+ for (const call of calls) for (const key of keys) call.keys.delete(key);
281
+ calls = calls.filter((call) => call.keys.size > 0);
282
+ if (reduceMotion()) {
283
+ for (const key of keys) {
284
+ springs.delete(key);
285
+ state[key] = targets[key];
286
+ }
287
+ onFrame();
288
+ if (options.onDone) options.onDone();
289
+ return;
290
+ }
291
+ for (const key of keys) {
292
+ const prev = springs.get(key);
293
+ springs.set(key, {
294
+ target: targets[key],
295
+ v: key in velocity ? velocity[key] : prev ? prev.v : 0,
296
+ k: cfg.k,
297
+ c: cfg.c,
298
+ });
299
+ }
300
+ if (options.onDone) calls.push({ keys: new Set(keys), cb: options.onDone });
301
+ if (raf === 0 && springs.size > 0) {
302
+ last = now();
303
+ raf = requestAnimationFrame(frame);
304
+ }
305
+ },
306
+ /** Freeze the given keys (or all) at their current values. */
307
+ stop(keys) {
308
+ forget(keys || [...springs.keys()]);
309
+ if (springs.size === 0 && raf !== 0) {
310
+ cancelAnimationFrame(raf);
311
+ raf = 0;
312
+ }
313
+ },
314
+ destroy() {
315
+ springs.clear();
316
+ calls = [];
317
+ if (raf !== 0) cancelAnimationFrame(raf);
318
+ raf = 0;
319
+ },
320
+ };
321
+ }
322
+ //#endregion
323
+
324
+ //#region icons
325
+ const svg = (body) =>
326
+ '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
327
+ body +
328
+ '</svg>';
329
+ const ICON = {
330
+ close: svg('<path d="M6 6l12 12M18 6L6 18"/>'),
331
+ prev: svg('<path d="M15 5l-7 7 7 7"/>'),
332
+ next: svg('<path d="M9 5l7 7-7 7"/>'),
333
+ zoomIn: svg('<circle cx="11" cy="11" r="6.5"/><path d="M20 20l-4.2-4.2M8.5 11h5M11 8.5v5"/>'),
334
+ zoomOut: svg('<circle cx="11" cy="11" r="6.5"/><path d="M20 20l-4.2-4.2M8.5 11h5"/>'),
335
+ download: svg('<path d="M12 4v11M7 10.5l5 5 5-5M5 20h14"/>'),
336
+ edit: svg('<path d="M4 20h4L19 9l-4-4L4 16v4z"/><path d="M13.5 6.5l4 4"/>'),
337
+ back: svg('<path d="M15 5l-7 7 7 7"/>'),
338
+ pen: svg('<path d="M3 17c3-1 4-6 7-6s1 6 4 6 4-8 7-9"/>'),
339
+ shapes: svg('<path d="M12 3l4 6H8z"/><rect x="3.5" y="13" width="7" height="7" rx="1.5"/><circle cx="17" cy="16.5" r="3.5"/>'),
340
+ eraser: svg('<path d="M14.5 4.5l5 5-9 9H6l-2.5-2.5a1.5 1.5 0 010-2.1z"/><path d="M9 10l5 5M10.5 18.5H20"/>'),
341
+ undo: svg('<path d="M9 7H5V3"/><path d="M5.5 7a8 8 0 11-1.3 7"/>'),
342
+ redo: svg('<path d="M15 7h4V3"/><path d="M18.5 7a8 8 0 101.3 7"/>'),
343
+ check: svg('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),
344
+ rect: svg('<rect x="4" y="6" width="16" height="12" rx="1.5"/>'),
345
+ ellipse: svg('<ellipse cx="12" cy="12" rx="8.5" ry="6"/>'),
346
+ arrow: svg('<path d="M5 19L19 5M10 5h9v9"/>'),
347
+ line: svg('<path d="M5 19L19 5"/>'),
348
+ };
349
+ //#endregion
350
+
351
+ //#region styles
352
+ const CSS = `
353
+ [${ROOT_ATTR}]{position:fixed;inset:0;z-index:2147483000;touch-action:none;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent;overscroll-behavior:contain;outline:none;color:#fff;font:13px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;cursor:default}
354
+ [${ROOT_ATTR}] *{box-sizing:border-box}
355
+ .qiv-bg{position:absolute;inset:0;background:#000}
356
+ .qiv-track{position:absolute;inset:0;overflow:hidden}
357
+ .qiv-slide{position:absolute;inset:0;contain:layout style}
358
+ .qiv-frame{position:absolute;left:50%;top:50%;transform-origin:50% 50%;cursor:zoom-in}
359
+ [${ROOT_ATTR}][data-gesture] .qiv-frame,[${ROOT_ATTR}][data-state=opening] .qiv-frame{will-change:transform}
360
+ [${ROOT_ATTR}][data-zoomed] .qiv-frame{cursor:grab}
361
+ [${ROOT_ATTR}][data-gesture=pan] .qiv-frame{cursor:grabbing}
362
+ .qiv-frame img{display:block;width:100%;height:100%;object-fit:contain;-webkit-user-drag:none;user-select:none}
363
+ .qiv-status{position:absolute;inset:0;display:grid;place-items:center;pointer-events:none;font-size:13px;opacity:.85}
364
+ .qiv-spin{width:28px;height:28px;border-radius:50%;border:2.5px solid rgba(255,255,255,.25);border-top-color:#fff;opacity:0;animation:qiv-in .2s .25s forwards,qiv-rot .8s linear infinite}
365
+ @keyframes qiv-in{to{opacity:1}}
366
+ @keyframes qiv-rot{to{transform:rotate(360deg)}}
367
+ .qiv-chrome{transition:opacity .22s ease}
368
+ [${ROOT_ATTR}][data-chrome=hidden] .qiv-chrome,[${ROOT_ATTR}][data-state=closing] .qiv-chrome,[${ROOT_ATTR}][data-state=opening] .qiv-chrome,[${ROOT_ATTR}][data-gesture=dismiss] .qiv-chrome,[${ROOT_ATTR}][data-gesture=pinch] .qiv-chrome{opacity:0;pointer-events:none}
369
+ .qiv-top{position:absolute;left:0;right:0;top:0;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:calc(env(safe-area-inset-top,0px) + 10px) calc(env(safe-area-inset-right,0px) + 12px) 18px calc(env(safe-area-inset-left,0px) + 18px);background:linear-gradient(rgba(0,0,0,.5),rgba(0,0,0,0))}
370
+ .qiv-count{font-size:14px;font-weight:600;letter-spacing:.02em;font-variant-numeric:tabular-nums;text-shadow:0 1px 2px rgba(0,0,0,.5)}
371
+ .qiv-actions{display:flex;gap:8px;margin-left:auto}
372
+ .qiv-btn{appearance:none;width:40px;height:40px;padding:0;border:0;border-radius:999px;background:rgba(255,255,255,.14);color:inherit;display:grid;place-items:center;cursor:pointer;text-decoration:none;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);transition:background-color .15s,opacity .15s}
373
+ .qiv-btn:hover{background:rgba(255,255,255,.26)}
374
+ .qiv-btn:active{background:rgba(255,255,255,.34)}
375
+ .qiv-btn:focus-visible,.qiv-thumb:focus-visible{outline:2px solid #fff;outline-offset:2px}
376
+ .qiv-nav{position:absolute;top:50%;width:44px;height:44px;margin-top:-22px}
377
+ .qiv-prev{left:calc(env(safe-area-inset-left,0px) + 16px)}
378
+ .qiv-next{right:calc(env(safe-area-inset-right,0px) + 16px)}
379
+ .qiv-nav[disabled]{opacity:0;pointer-events:none}
380
+ [${ROOT_ATTR}][data-coarse] .qiv-nav,[${ROOT_ATTR}][data-single] .qiv-nav{display:none}
381
+ .qiv-strip{position:absolute;left:0;right:0;bottom:0;display:flex;overflow-x:auto;touch-action:pan-x;scrollbar-width:none;padding:18px 16px calc(env(safe-area-inset-bottom,0px) + 12px);background:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.5))}
382
+ .qiv-strip::-webkit-scrollbar{display:none}
383
+ .qiv-strip-inner{display:flex;gap:6px;margin:0 auto}
384
+ .qiv-thumb{appearance:none;flex:none;width:40px;height:40px;padding:0;border:0;border-radius:6px;overflow:hidden;background:rgba(255,255,255,.1);opacity:.5;cursor:pointer;transition:opacity .15s,transform .15s}
385
+ .qiv-thumb:hover{opacity:.8}
386
+ .qiv-thumb[aria-current=true]{opacity:1;transform:scale(1.1);box-shadow:0 0 0 2px #fff}
387
+ .qiv-thumb img{display:block;width:100%;height:100%;object-fit:cover;pointer-events:none}
388
+ .qiv-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
389
+ @media (prefers-reduced-motion:reduce){.qiv-chrome,.qiv-thumb{transition:none}}
390
+ `;
391
+
392
+ function installStyles() {
393
+ if (typeof document === 'undefined') return () => {};
394
+ if (document.querySelector(`style[${STYLE_ATTR}]`) !== null) return () => {};
395
+ const tag = document.createElement('style');
396
+ tag.setAttribute(STYLE_ATTR, '');
397
+ tag.textContent = CSS + EDIT_CSS;
398
+ document.head.appendChild(tag);
399
+ return () => tag.remove();
400
+ }
401
+ //#endregion
402
+
403
+ //#region image discovery
404
+ function isZoomCursor(node) {
405
+ try {
406
+ return String(getComputedStyle(node).cursor || '').includes('zoom-in');
407
+ } catch {
408
+ return false;
409
+ }
410
+ }
411
+
412
+ const srcOf = (img) => img.currentSrc || img.src || '';
413
+
414
+ /**
415
+ * Map a click target to a previewable image, or null to let the click
416
+ * through. Buttons qualify only when they wrap exactly one image and show
417
+ * a zoom-in cursor (how DSH marks its own lightbox triggers). Bare images
418
+ * qualify with a zoom-in cursor or when they are large enough to not be
419
+ * an icon.
420
+ */
421
+ function resolveTrigger(node) {
422
+ if (!(node instanceof Element)) return null;
423
+ if (node.closest(`[${ROOT_ATTR}],[${EDIT_ATTR}],[${IGNORE_ATTR}],[aria-modal="true"],[contenteditable="true"]`) !== null) return null;
424
+ const host = node.closest('button,[role="button"]');
425
+ if (host !== null) {
426
+ if (host.closest('a[href]') !== null) return null;
427
+ const imgs = host.getElementsByTagName('img');
428
+ if (imgs.length !== 1) return null;
429
+ const img = imgs[0];
430
+ if (!isZoomCursor(host) && !isZoomCursor(img)) return null;
431
+ if (srcOf(img) === '') return null;
432
+ return { host, img };
433
+ }
434
+ if (node.tagName !== 'IMG') return null;
435
+ const img = node;
436
+ if (srcOf(img) === '') return null;
437
+ if (img.closest('a[href],nav,header,[role="toolbar"],[role="menu"],[role="menubar"],[role="listbox"],[role="tablist"]') !== null) return null;
438
+ if (isZoomCursor(img)) return { host: img, img };
439
+ const rect = img.getBoundingClientRect();
440
+ if (rect.width >= MIN_BARE_W && rect.height >= MIN_BARE_H) return { host: img, img };
441
+ return null;
442
+ }
443
+
444
+ /** The nearest vertically scrolling ancestor scopes the gallery (the transcript). */
445
+ function scrollerOf(node) {
446
+ for (let el = node.parentElement; el !== null && el !== document.body; el = el.parentElement) {
447
+ let style;
448
+ try {
449
+ style = getComputedStyle(el);
450
+ } catch {
451
+ continue;
452
+ }
453
+ const oy = style.overflowY;
454
+ if (oy !== 'auto' && oy !== 'scroll' && oy !== 'overlay') continue;
455
+ if (el.scrollHeight > el.clientHeight + 1 || el.clientHeight >= window.innerHeight * 0.5) return el;
456
+ }
457
+ return document.body;
458
+ }
459
+
460
+ function makeItem(trigger, scope) {
461
+ const img = trigger.img;
462
+ const rect = img.getBoundingClientRect();
463
+ return {
464
+ el: img,
465
+ host: trigger.host,
466
+ src: srcOf(img),
467
+ alt: img.getAttribute('alt') || '',
468
+ referrerPolicy: img.referrerPolicy || '',
469
+ w: img.naturalWidth || 0,
470
+ h: img.naturalHeight || 0,
471
+ fw0: rect.width,
472
+ fh0: rect.height,
473
+ scope,
474
+ inset: { x: 0, y: 0 },
475
+ index: 0,
476
+ };
477
+ }
478
+
479
+ function collect(trigger) {
480
+ const scope = scrollerOf(trigger.host);
481
+ const hasLayout = trigger.img.getBoundingClientRect().width > 0;
482
+ const seen = new Set();
483
+ const items = [];
484
+ for (const img of scope.querySelectorAll('img')) {
485
+ if (items.length >= MAX_ITEMS && seen.has(trigger.img)) break;
486
+ const tr = img === trigger.img ? trigger : resolveTrigger(img);
487
+ if (tr === null || seen.has(tr.img)) continue;
488
+ if (hasLayout && img !== trigger.img) {
489
+ const rect = img.getBoundingClientRect();
490
+ if (rect.width === 0 && rect.height === 0) continue;
491
+ }
492
+ seen.add(tr.img);
493
+ items.push(makeItem(tr, scope));
494
+ }
495
+ if (!seen.has(trigger.img)) items.push(makeItem(trigger, scope));
496
+ items.forEach((item, i) => {
497
+ item.index = i;
498
+ });
499
+ return { items, index: items.findIndex((item) => item.el === trigger.img) };
500
+ }
501
+ //#endregion
502
+
503
+ //#region viewer
504
+ function openViewer(items, startIndex, t, onDestroyed) {
505
+ const n = items.length;
506
+ const coarse = media('(pointer: coarse)');
507
+ const restoreFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
508
+ const s = { x: 0, y: 0, scale: 1, clip: 0, radius: 0, bg: 0, alpha: 1, trackX: 0 };
509
+ const slides = new Map();
510
+ const pointers = new Map();
511
+ let index = startIndex;
512
+ let vw = window.innerWidth;
513
+ let vh = window.innerHeight;
514
+ let outgoing = null;
515
+ let closing = false;
516
+ let destroyed = false;
517
+ /** Open annotation editor; the viewer pauses keyboard input under it. */
518
+ let editor = null;
519
+ let gesture = null;
520
+ let samples = [];
521
+ let tapTimer = 0;
522
+ let lastTap = null;
523
+ let lastZoomed = null;
524
+ let hiddenItem = null;
525
+ let wheelAccum = 0;
526
+ let wheelLast = 0;
527
+ let wheelLock = 0;
528
+
529
+ //#region dom
530
+ const root = h('div', 'qiv', { role: 'dialog', 'aria-modal': 'true', 'aria-label': t('dialog'), tabindex: '-1' });
531
+ root.setAttribute(ROOT_ATTR, '');
532
+ root.dataset.state = 'opening';
533
+ if (coarse) root.setAttribute('data-coarse', '');
534
+ if (n <= 1) root.setAttribute('data-single', '');
535
+ const bg = h('div', 'qiv-bg');
536
+ const track = h('div', 'qiv-track');
537
+ const top = h('div', 'qiv-top qiv-chrome');
538
+ const counter = h('div', 'qiv-count', { 'aria-hidden': 'true' });
539
+ const actions = h('div', 'qiv-actions');
540
+ const iconButton = (className, label, icon) => {
541
+ const button = h('button', className, { type: 'button', 'aria-label': label, title: label });
542
+ button.innerHTML = icon;
543
+ return button;
544
+ };
545
+ const zoomBtn = iconButton('qiv-btn', t('zoomIn'), ICON.zoomIn);
546
+ const download = h('a', 'qiv-btn', { 'aria-label': t('download'), title: t('download'), rel: 'noopener', target: '_blank' });
547
+ download.innerHTML = ICON.download;
548
+ const closeBtn = iconButton('qiv-btn', t('close'), ICON.close);
549
+ const editBtn = canEdit() ? iconButton('qiv-btn', t('edit'), ICON.edit) : null;
550
+ if (editBtn !== null) actions.append(zoomBtn, editBtn, download, closeBtn);
551
+ else actions.append(zoomBtn, download, closeBtn);
552
+ top.append(counter, actions);
553
+ const prevBtn = iconButton('qiv-btn qiv-nav qiv-prev qiv-chrome', t('prev'), ICON.prev);
554
+ const nextBtn = iconButton('qiv-btn qiv-nav qiv-next qiv-chrome', t('next'), ICON.next);
555
+ const live = h('div', 'qiv-sr', { 'aria-live': 'polite' });
556
+ root.append(bg, track, top, prevBtn, nextBtn, live);
557
+
558
+ const thumbs = [];
559
+ let strip = null;
560
+ if (n > 1) {
561
+ strip = h('div', 'qiv-strip qiv-chrome');
562
+ const inner = h('div', 'qiv-strip-inner');
563
+ items.forEach((item, i) => {
564
+ const button = h('button', 'qiv-thumb', { type: 'button', 'aria-label': t('thumb', { i: i + 1 }) });
565
+ const img = h('img', '', { alt: '', loading: 'lazy', decoding: 'async', draggable: 'false' });
566
+ if (item.referrerPolicy) img.referrerPolicy = item.referrerPolicy;
567
+ img.src = item.src;
568
+ button.append(img);
569
+ button.addEventListener('click', () => jumpTo(i));
570
+ inner.append(button);
571
+ thumbs.push(button);
572
+ });
573
+ strip.append(inner);
574
+ root.append(strip);
575
+ }
576
+ //#endregion
577
+
578
+ //#region geometry
579
+ function pads() {
580
+ if (coarse) return { x: 0, y: 0 };
581
+ return { x: n > 1 ? 76 : 32, y: n > 1 ? 84 : 64 };
582
+ }
583
+
584
+ /** Displayed size at scale 1, and its ratio to natural pixels. */
585
+ function fitOf(i) {
586
+ const item = items[i];
587
+ const pad = pads();
588
+ const aw = Math.max(40, vw - pad.x * 2);
589
+ const ah = Math.max(40, vh - pad.y * 2);
590
+ const nw = item.w || item.fw0 || aw;
591
+ const nh = item.h || item.fh0 || ah;
592
+ let k = Math.min(aw / nw, ah / nh);
593
+ // Desktop never upsamples past natural size; touch fills the screen like Photos.
594
+ if (!coarse && item.w > 0) k = Math.min(k, 1);
595
+ return { w: nw * k, h: nh * k, k };
596
+ }
597
+
598
+ function maxScaleOf(i) {
599
+ return clamp(2 / Math.max(fitOf(i).k, 0.01), 4, 12);
600
+ }
601
+
602
+ function doubleTapScale() {
603
+ const f = fitOf(index);
604
+ const fill = Math.max(vw / f.w, vh / f.h);
605
+ // Fill the screen only when that is a meaningful zoom; otherwise 2.5x like Photos.
606
+ return clamp(fill >= 1.8 && fill <= 4 ? fill : 2.5, 1, maxScaleOf(index));
607
+ }
608
+
609
+ function bounds(scale) {
610
+ const f = fitOf(index);
611
+ return { x: Math.max(0, (f.w * scale - vw) / 2), y: Math.max(0, (f.h * scale - vh) / 2) };
612
+ }
613
+
614
+ /** Translation that keeps screen point (px, py) fixed while scaling to `scale`. */
615
+ function focal(scale, px, py, from = s) {
616
+ const cx = vw / 2;
617
+ const cy = vh / 2;
618
+ const lx = (px - cx - from.x) / from.scale;
619
+ const ly = (py - cy - from.y) / from.scale;
620
+ return { x: px - cx - lx * scale, y: py - cy - ly * scale };
621
+ }
622
+
623
+ function hitImage(px, py) {
624
+ const f = fitOf(index);
625
+ return Math.abs(px - (vw / 2 + s.x)) <= (f.w * s.scale) / 2 && Math.abs(py - (vh / 2 + s.y)) <= (f.h * s.scale) / 2;
626
+ }
627
+
628
+ function radiusOf(item, rect) {
629
+ let r = 0;
630
+ for (const node of [item.el, item.host]) {
631
+ try {
632
+ r = Math.max(r, cssPx(getComputedStyle(node).borderTopLeftRadius, rect.width));
633
+ } catch {
634
+ // detached
635
+ }
636
+ }
637
+ return Math.min(r, rect.width / 2, rect.height / 2);
638
+ }
639
+
640
+ /** Where the thumbnail of `item` sits, expressed as viewer state; null if not visible. */
641
+ function sourceTarget(item) {
642
+ const el = item.el;
643
+ if (!el || !el.isConnected) return null;
644
+ const rect = el.getBoundingClientRect();
645
+ if (rect.width < 2 || rect.height < 2) return null;
646
+ if (rect.bottom < 0 || rect.top > vh || rect.right < 0 || rect.left > vw) return null;
647
+ if (item.scope && item.scope !== document.body) {
648
+ const box = item.scope.getBoundingClientRect();
649
+ if (rect.bottom < box.top || rect.top > box.bottom) return null;
650
+ }
651
+ const f = fitOf(item.index);
652
+ let cover = false;
653
+ try {
654
+ cover = getComputedStyle(el).objectFit === 'cover';
655
+ } catch {
656
+ cover = false;
657
+ }
658
+ let scale;
659
+ const inset = { x: 0, y: 0 };
660
+ if (cover) {
661
+ scale = Math.max(rect.width / f.w, rect.height / f.h);
662
+ inset.x = Math.max(0, (f.w - rect.width / scale) / 2);
663
+ inset.y = Math.max(0, (f.h - rect.height / scale) / 2);
664
+ } else {
665
+ scale = Math.min(rect.width / f.w, rect.height / f.h);
666
+ }
667
+ return {
668
+ x: rect.left + rect.width / 2 - vw / 2,
669
+ y: rect.top + rect.height / 2 - vh / 2,
670
+ scale,
671
+ inset,
672
+ radius: radiusOf(item, rect),
673
+ };
674
+ }
675
+ //#endregion
676
+
677
+ //#region slides + render
678
+ function createSlide(i) {
679
+ const item = items[i];
680
+ const slide = h('div', 'qiv-slide');
681
+ const frame = h('div', 'qiv-frame');
682
+ const img = h('img', '', { alt: item.alt, draggable: 'false', decoding: 'async' });
683
+ if (item.referrerPolicy) img.referrerPolicy = item.referrerPolicy;
684
+ const status = h('div', 'qiv-status');
685
+ frame.append(img);
686
+ slide.append(frame, status);
687
+ const record = { slide, frame, img, status, key: '' };
688
+ const ready = () => {
689
+ if (img.naturalWidth > 0) {
690
+ item.w = img.naturalWidth;
691
+ item.h = img.naturalHeight;
692
+ }
693
+ status.replaceChildren();
694
+ if (i === index && gesture === null) clampView();
695
+ render();
696
+ };
697
+ img.addEventListener('load', ready, { once: true });
698
+ img.addEventListener('error', () => {
699
+ status.replaceChildren(document.createTextNode(t('failed')));
700
+ }, { once: true });
701
+ img.src = item.src;
702
+ if (!(img.complete && img.naturalWidth > 0)) status.append(h('div', 'qiv-spin'));
703
+ track.append(slide);
704
+ return record;
705
+ }
706
+
707
+ function syncSlides() {
708
+ const want = new Set();
709
+ for (const i of [index - 1, index, index + 1]) if (i >= 0 && i < n) want.add(i);
710
+ if (outgoing !== null) want.add(outgoing.index);
711
+ for (const [i, record] of slides) {
712
+ if (!want.has(i)) {
713
+ record.slide.remove();
714
+ slides.delete(i);
715
+ }
716
+ }
717
+ for (const i of want) if (!slides.has(i)) slides.set(i, createSlide(i));
718
+ }
719
+
720
+ function render() {
721
+ if (destroyed) return;
722
+ const step = vw + GAP;
723
+ bg.style.opacity = String(clamp(s.bg, 0, 1));
724
+ for (const [i, record] of slides) {
725
+ const f = fitOf(i);
726
+ const key = f.w.toFixed(2) + 'x' + f.h.toFixed(2);
727
+ if (record.key !== key) {
728
+ record.key = key;
729
+ const st = record.frame.style;
730
+ st.width = f.w + 'px';
731
+ st.height = f.h + 'px';
732
+ st.marginLeft = -f.w / 2 + 'px';
733
+ st.marginTop = -f.h / 2 + 'px';
734
+ }
735
+ record.slide.style.transform = `translate3d(${(i - index) * step + s.trackX}px,0,0)`;
736
+ const st = record.frame.style;
737
+ if (i === index) {
738
+ st.transform = `translate3d(${s.x}px,${s.y}px,0) scale(${s.scale})`;
739
+ st.opacity = s.alpha >= 0.999 ? '' : String(clamp(s.alpha, 0, 1));
740
+ if (s.clip > 0.001 || s.radius > 0.2) {
741
+ const inset = items[i].inset;
742
+ const r = s.radius / Math.max(s.scale, 0.01);
743
+ st.clipPath = `inset(${inset.y * s.clip}px ${inset.x * s.clip}px round ${r}px)`;
744
+ } else {
745
+ st.clipPath = '';
746
+ }
747
+ } else if (outgoing !== null && i === outgoing.index) {
748
+ st.transform = `translate3d(${outgoing.x}px,${outgoing.y}px,0) scale(${outgoing.scale})`;
749
+ st.clipPath = '';
750
+ st.opacity = '';
751
+ } else {
752
+ st.transform = '';
753
+ st.clipPath = '';
754
+ st.opacity = '';
755
+ }
756
+ }
757
+ const zoomed = s.scale > 1.01;
758
+ if (zoomed !== lastZoomed) {
759
+ lastZoomed = zoomed;
760
+ root.toggleAttribute('data-zoomed', zoomed);
761
+ const label = zoomed ? t('zoomOut') : t('zoomIn');
762
+ zoomBtn.innerHTML = zoomed ? ICON.zoomOut : ICON.zoomIn;
763
+ zoomBtn.setAttribute('aria-label', label);
764
+ zoomBtn.title = label;
765
+ }
766
+ }
767
+
768
+ function hideSource(item) {
769
+ if (hiddenItem === item) return;
770
+ showSource();
771
+ if (item && item.el.isConnected) {
772
+ item.prevVisibility = item.el.style.visibility;
773
+ item.el.style.visibility = 'hidden';
774
+ hiddenItem = item;
775
+ }
776
+ }
777
+
778
+ function showSource() {
779
+ if (hiddenItem === null) return;
780
+ hiddenItem.el.style.visibility = hiddenItem.prevVisibility || '';
781
+ hiddenItem = null;
782
+ }
783
+
784
+ function updateChrome() {
785
+ const item = items[index];
786
+ const text = n > 1 ? t('counter', { i: index + 1, n }) : '';
787
+ counter.textContent = text;
788
+ live.textContent = text;
789
+ prevBtn.disabled = index === 0;
790
+ nextBtn.disabled = index === n - 1;
791
+ download.href = item.src;
792
+ download.setAttribute('download', fileName(item.src));
793
+ thumbs.forEach((thumb, i) => thumb.setAttribute('aria-current', i === index ? 'true' : 'false'));
794
+ if (strip !== null && thumbs[index]) {
795
+ const thumb = thumbs[index];
796
+ const left = thumb.offsetLeft - strip.clientWidth / 2 + thumb.offsetWidth / 2;
797
+ if (typeof strip.scrollTo === 'function') strip.scrollTo({ left, behavior: reduceMotion() ? 'auto' : 'smooth' });
798
+ else strip.scrollLeft = left;
799
+ }
800
+ hideSource(item);
801
+ }
802
+ //#endregion
803
+
804
+ //#region animation helpers
805
+ const anim = createAnimator(s, render);
806
+
807
+ function clearOutgoing() {
808
+ if (outgoing === null) return;
809
+ outgoing = null;
810
+ syncSlides();
811
+ render();
812
+ }
813
+
814
+ function clampView() {
815
+ const b = bounds(s.scale);
816
+ s.x = clamp(s.x, -b.x, b.x);
817
+ s.y = clamp(s.y, -b.y, b.y);
818
+ }
819
+
820
+ /** Settle zoom/pan into range; velocities in px/ms become momentum. */
821
+ function settleView(vx = 0, vy = 0, fx = vw / 2, fy = vh / 2) {
822
+ const scale = clamp(s.scale, 1, maxScaleOf(index));
823
+ let tx = s.x;
824
+ let ty = s.y;
825
+ if (Math.abs(scale - s.scale) > 1e-4) {
826
+ const p = focal(scale, fx, fy);
827
+ tx = p.x;
828
+ ty = p.y;
829
+ }
830
+ tx += (vx * DECEL) / (1 - DECEL);
831
+ ty += (vy * DECEL) / (1 - DECEL);
832
+ const b = bounds(scale);
833
+ tx = clamp(tx, -b.x, b.x);
834
+ ty = clamp(ty, -b.y, b.y);
835
+ const moving = vx !== 0 || vy !== 0;
836
+ anim.to(
837
+ { x: tx, y: ty, scale, bg: 1, alpha: 1 },
838
+ { spring: moving ? SPRING.glide : SPRING.snap, velocity: { x: vx * 1000, y: vy * 1000 } },
839
+ );
840
+ }
841
+
842
+ function settleTrack(v = 0) {
843
+ if (Math.abs(s.trackX) < 0.5 && v === 0) {
844
+ s.trackX = 0;
845
+ clearOutgoing();
846
+ return;
847
+ }
848
+ anim.to({ trackX: 0 }, { spring: SPRING.page, velocity: { trackX: v }, onDone: clearOutgoing });
849
+ }
850
+
851
+ function commitPage(dir, v = 0) {
852
+ const step = vw + GAP;
853
+ anim.stop(['x', 'y', 'scale', 'clip', 'radius', 'trackX']);
854
+ outgoing = { index, x: s.x, y: s.y, scale: s.scale };
855
+ index += dir;
856
+ s.trackX += dir * step;
857
+ s.x = 0;
858
+ s.y = 0;
859
+ s.scale = 1;
860
+ s.clip = 0;
861
+ s.radius = 0;
862
+ s.bg = 1;
863
+ s.alpha = 1;
864
+ syncSlides();
865
+ updateChrome();
866
+ render();
867
+ anim.to({ trackX: 0 }, { spring: SPRING.page, velocity: { trackX: v }, onDone: clearOutgoing });
868
+ }
869
+
870
+ function go(dir) {
871
+ const target = index + dir;
872
+ if (target < 0 || target >= n || closing) return;
873
+ commitPage(dir, 0);
874
+ }
875
+
876
+ function jumpTo(target) {
877
+ if (target === index || target < 0 || target >= n || closing) return;
878
+ if (Math.abs(target - index) === 1) {
879
+ commitPage(target - index, 0);
880
+ return;
881
+ }
882
+ const dir = target > index ? 1 : -1;
883
+ anim.stop();
884
+ outgoing = null;
885
+ index = target;
886
+ Object.assign(s, { x: 0, y: 0, scale: 1, clip: 0, radius: 0, bg: 1, alpha: 1, trackX: dir * (vw + GAP) * 0.35 });
887
+ syncSlides();
888
+ updateChrome();
889
+ render();
890
+ anim.to({ trackX: 0 }, { spring: SPRING.page });
891
+ }
892
+
893
+ function toggleZoom(px, py) {
894
+ if (s.scale > 1.01) {
895
+ anim.to({ scale: 1, x: 0, y: 0 }, { spring: SPRING.snap });
896
+ return;
897
+ }
898
+ const scale = doubleTapScale();
899
+ const p = focal(scale, px, py);
900
+ const b = bounds(scale);
901
+ anim.to({ scale, x: clamp(p.x, -b.x, b.x), y: clamp(p.y, -b.y, b.y) }, { spring: SPRING.snap });
902
+ }
903
+
904
+ function zoomBy(factor, px, py, animate) {
905
+ const scale = clamp(s.scale * factor, 1, maxScaleOf(index));
906
+ const p = focal(scale, px, py);
907
+ const b = bounds(scale);
908
+ const target = { scale, x: clamp(p.x, -b.x, b.x), y: clamp(p.y, -b.y, b.y) };
909
+ if (animate) {
910
+ anim.to(target, { spring: SPRING.snap });
911
+ } else {
912
+ anim.stop(['x', 'y', 'scale']);
913
+ Object.assign(s, target);
914
+ render();
915
+ }
916
+ }
917
+
918
+ function toggleChrome() {
919
+ root.dataset.chrome = root.dataset.chrome === 'hidden' ? 'shown' : 'hidden';
920
+ }
921
+ //#endregion
922
+
923
+ //#region pointer gestures
924
+ function clearTap() {
925
+ if (tapTimer !== 0) clearTimeout(tapTimer);
926
+ tapTimer = 0;
927
+ lastTap = null;
928
+ }
929
+
930
+ function velocity() {
931
+ const tNow = now();
932
+ const recent = samples.filter((p) => tNow - p.t <= 100);
933
+ if (recent.length < 2) return { x: 0, y: 0 };
934
+ const a = recent[0];
935
+ const b = recent[recent.length - 1];
936
+ const dt = b.t - a.t;
937
+ if (dt <= 0 || tNow - b.t > 60) return { x: 0, y: 0 };
938
+ return { x: (b.x - a.x) / dt, y: (b.y - a.y) / dt };
939
+ }
940
+
941
+ function setGesture(mode) {
942
+ if (mode === null) delete root.dataset.gesture;
943
+ else root.dataset.gesture = mode;
944
+ }
945
+
946
+ function pointPair() {
947
+ const list = [...pointers.values()];
948
+ return [list[0], list[1]];
949
+ }
950
+
951
+ function startPinch() {
952
+ clearTap();
953
+ const [a, b] = pointPair();
954
+ gesture = {
955
+ mode: 'pinch',
956
+ d0: Math.max(1, Math.hypot(a.x - b.x, a.y - b.y)),
957
+ s0: s.scale,
958
+ x0: s.x,
959
+ y0: s.y,
960
+ mx: (a.x + b.x) / 2,
961
+ my: (a.y + b.y) / 2,
962
+ lastMx: (a.x + b.x) / 2,
963
+ lastMy: (a.y + b.y) / 2,
964
+ };
965
+ setGesture('pinch');
966
+ }
967
+
968
+ function startSingle(id, p) {
969
+ gesture = {
970
+ mode: 'pending',
971
+ id,
972
+ type: p.type,
973
+ sx: p.x,
974
+ sy: p.y,
975
+ t0: now(),
976
+ x0: s.x,
977
+ y0: s.y,
978
+ track0: s.trackX,
979
+ atMin: false,
980
+ atMax: false,
981
+ };
982
+ samples = [{ t: now(), x: p.x, y: p.y }];
983
+ }
984
+
985
+ function classify(dx, dy) {
986
+ if (Math.abs(s.trackX) > 1) return 'page';
987
+ if (s.scale > 1.01) return 'pan';
988
+ return Math.abs(dx) > Math.abs(dy) ? 'page' : 'dismiss';
989
+ }
990
+
991
+ function onDown(e) {
992
+ if (closing) return;
993
+ if (e.pointerType === 'mouse' && e.button !== 0) return;
994
+ if (e.target instanceof Element && e.target.closest('.qiv-chrome') !== null) return;
995
+ e.preventDefault();
996
+ try {
997
+ root.setPointerCapture(e.pointerId);
998
+ } catch {
999
+ // capture is best-effort
1000
+ }
1001
+ const p = { x: e.clientX, y: e.clientY, type: e.pointerType || 'mouse' };
1002
+ pointers.set(e.pointerId, p);
1003
+ anim.stop(['x', 'y', 'scale', 'bg', 'alpha', 'trackX']);
1004
+ if (pointers.size === 1) startSingle(e.pointerId, p);
1005
+ else if (pointers.size === 2) startPinch();
1006
+ }
1007
+
1008
+ function movePinch() {
1009
+ const [a, b] = pointPair();
1010
+ const g = gesture;
1011
+ const d = Math.hypot(a.x - b.x, a.y - b.y);
1012
+ const mx = (a.x + b.x) / 2;
1013
+ const my = (a.y + b.y) / 2;
1014
+ const max = maxScaleOf(index);
1015
+ const raw = (g.s0 * d) / g.d0;
1016
+ let scale = raw;
1017
+ if (raw > max) scale = max * Math.pow(raw / max, 0.35);
1018
+ else if (raw < 1) scale = Math.pow(raw, 0.7);
1019
+ scale = Math.max(0.25, scale);
1020
+ const cx = vw / 2;
1021
+ const cy = vh / 2;
1022
+ const lx = (g.mx - cx - g.x0) / g.s0;
1023
+ const ly = (g.my - cy - g.y0) / g.s0;
1024
+ s.scale = scale;
1025
+ s.x = mx - cx - lx * scale;
1026
+ s.y = my - cy - ly * scale;
1027
+ s.bg = scale < 1 ? clamp((scale - 0.4) / 0.6, 0, 1) : 1;
1028
+ g.lastMx = mx;
1029
+ g.lastMy = my;
1030
+ render();
1031
+ }
1032
+
1033
+ function onMove(e) {
1034
+ const p = pointers.get(e.pointerId);
1035
+ if (p === undefined) return;
1036
+ p.x = e.clientX;
1037
+ p.y = e.clientY;
1038
+ const g = gesture;
1039
+ if (g === null) return;
1040
+ if (g.mode === 'pinch') {
1041
+ if (pointers.size >= 2) movePinch();
1042
+ return;
1043
+ }
1044
+ if (e.pointerId !== g.id) return;
1045
+ samples.push({ t: now(), x: p.x, y: p.y });
1046
+ if (samples.length > 24) samples.splice(0, samples.length - 24);
1047
+ let dx = p.x - g.sx;
1048
+ let dy = p.y - g.sy;
1049
+ if (g.mode === 'pending') {
1050
+ if (Math.hypot(dx, dy) < SLOP) return;
1051
+ clearTap();
1052
+ g.mode = classify(dx, dy);
1053
+ // Rebase so the drag starts from here instead of jumping by SLOP.
1054
+ g.sx = p.x;
1055
+ g.sy = p.y;
1056
+ g.x0 = s.x;
1057
+ g.y0 = s.y;
1058
+ g.track0 = s.trackX;
1059
+ if (g.mode === 'pan') {
1060
+ const b = bounds(s.scale);
1061
+ g.atMin = s.x <= -b.x + 1;
1062
+ g.atMax = s.x >= b.x - 1;
1063
+ }
1064
+ setGesture(g.mode);
1065
+ return;
1066
+ }
1067
+ if (g.mode === 'pan') {
1068
+ const b = bounds(s.scale);
1069
+ const nx = g.x0 + dx;
1070
+ const ny = g.y0 + dy;
1071
+ const horizontal = Math.abs(dx) > Math.abs(dy);
1072
+ // Zoomed photo already at its edge: keep dragging to reach the neighbour.
1073
+ if (horizontal && nx > b.x && g.atMax && index > 0) {
1074
+ g.mode = 'page';
1075
+ g.fromPan = true;
1076
+ // trackX = track0 + dx must equal the overflow nx - b.x.
1077
+ g.track0 = s.trackX + g.x0 - b.x;
1078
+ s.x = b.x;
1079
+ setGesture('page');
1080
+ } else if (horizontal && nx < -b.x && g.atMin && index < n - 1) {
1081
+ g.mode = 'page';
1082
+ g.fromPan = true;
1083
+ g.track0 = s.trackX + g.x0 + b.x;
1084
+ s.x = -b.x;
1085
+ setGesture('page');
1086
+ } else {
1087
+ s.x = rubberClamp(nx, -b.x, b.x, vw);
1088
+ s.y = rubberClamp(ny, -b.y, b.y, vh);
1089
+ render();
1090
+ return;
1091
+ }
1092
+ }
1093
+ if (g.mode === 'page') {
1094
+ let tx = g.track0 + dx;
1095
+ if ((tx > 0 && index === 0) || (tx < 0 && index === n - 1)) tx = rubber(tx, vw);
1096
+ s.trackX = tx;
1097
+ } else if (g.mode === 'dismiss') {
1098
+ s.x = g.x0 + dx;
1099
+ s.y = g.y0 + dy;
1100
+ const progress = clamp(Math.abs(s.y) / (vh * 0.5), 0, 1);
1101
+ s.scale = 1 - 0.3 * progress;
1102
+ s.bg = 1 - Math.min(1, Math.abs(s.y) / (vh * 0.35));
1103
+ }
1104
+ render();
1105
+ }
1106
+
1107
+ function onTap(e, g) {
1108
+ const tNow = now();
1109
+ const x = e.clientX;
1110
+ const y = e.clientY;
1111
+ const mouse = g.type === 'mouse';
1112
+ if (lastTap !== null && tNow - lastTap.t < DOUBLE_TAP_MS && Math.hypot(x - lastTap.x, y - lastTap.y) < DOUBLE_TAP_PX) {
1113
+ clearTap();
1114
+ toggleZoom(x, y);
1115
+ return;
1116
+ }
1117
+ clearTap();
1118
+ if (mouse && !hitImage(x, y)) {
1119
+ close();
1120
+ return;
1121
+ }
1122
+ lastTap = { t: tNow, x, y };
1123
+ tapTimer = setTimeout(() => {
1124
+ tapTimer = 0;
1125
+ lastTap = null;
1126
+ if (!mouse) toggleChrome();
1127
+ }, DOUBLE_TAP_MS);
1128
+ }
1129
+
1130
+ function releasePage(vx) {
1131
+ const step = vw + GAP;
1132
+ let dir = 0;
1133
+ if ((s.trackX < -step * 0.5 || (vx < -0.3 && s.trackX < -10)) && index < n - 1) dir = 1;
1134
+ else if ((s.trackX > step * 0.5 || (vx > 0.3 && s.trackX > 10)) && index > 0) dir = -1;
1135
+ if (dir !== 0) commitPage(dir, vx * 1000);
1136
+ else settleTrack(vx * 1000);
1137
+ }
1138
+
1139
+ function releaseDismiss(v) {
1140
+ const dy = s.y;
1141
+ const against = Math.abs(v.y) > 0.3 && Math.sign(v.y) !== Math.sign(dy);
1142
+ const fling = Math.abs(v.y) > 0.45 && Math.sign(v.y) === Math.sign(dy);
1143
+ if (!against && (fling || Math.abs(dy) > Math.min(140, vh * 0.14))) {
1144
+ close({ x: v.x * 1000, y: v.y * 1000 });
1145
+ return;
1146
+ }
1147
+ anim.to({ x: 0, y: 0, scale: 1, bg: 1 }, { spring: SPRING.snap, velocity: { x: v.x * 1000, y: v.y * 1000 } });
1148
+ }
1149
+
1150
+ function onUp(e) {
1151
+ if (!pointers.has(e.pointerId)) return;
1152
+ pointers.delete(e.pointerId);
1153
+ try {
1154
+ root.releasePointerCapture(e.pointerId);
1155
+ } catch {
1156
+ // already released
1157
+ }
1158
+ const g = gesture;
1159
+ if (g === null) return;
1160
+ const cancelled = e.type === 'pointercancel';
1161
+ if (g.mode === 'pinch') {
1162
+ if (pointers.size === 1) {
1163
+ // One finger left: keep going as a pan from where it is.
1164
+ const [id, p] = [...pointers.entries()][0];
1165
+ startSingle(id, p);
1166
+ gesture.mode = 'pan';
1167
+ const b = bounds(s.scale);
1168
+ gesture.atMin = s.x <= -b.x + 1;
1169
+ gesture.atMax = s.x >= b.x - 1;
1170
+ setGesture('pan');
1171
+ return;
1172
+ }
1173
+ if (pointers.size === 0) {
1174
+ gesture = null;
1175
+ setGesture(null);
1176
+ if (s.scale < 0.8 && g.s0 <= 1.05) close();
1177
+ else settleView(0, 0, g.lastMx, g.lastMy);
1178
+ }
1179
+ return;
1180
+ }
1181
+ if (e.pointerId !== g.id) return;
1182
+ const v = cancelled ? { x: 0, y: 0 } : velocity();
1183
+ gesture = null;
1184
+ setGesture(null);
1185
+ if (g.mode === 'pending') {
1186
+ settleTrack();
1187
+ settleView();
1188
+ if (!cancelled && now() - g.t0 < TAP_MAX_MS) onTap(e, g);
1189
+ return;
1190
+ }
1191
+ if (g.mode === 'page') {
1192
+ releasePage(v.x);
1193
+ settleView();
1194
+ } else if (g.mode === 'pan') {
1195
+ settleTrack();
1196
+ settleView(v.x, v.y);
1197
+ } else if (g.mode === 'dismiss') {
1198
+ releaseDismiss(v);
1199
+ }
1200
+ }
1201
+ //#endregion
1202
+
1203
+ //#region wheel + keyboard + resize
1204
+ function onWheel(e) {
1205
+ e.preventDefault();
1206
+ if (closing) return;
1207
+ const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? vh : 1;
1208
+ const dx = e.deltaX * unit;
1209
+ const dy = e.deltaY * unit;
1210
+ if (e.ctrlKey || e.metaKey) {
1211
+ // Trackpad pinch arrives as ctrl+wheel with small deltas.
1212
+ zoomBy(Math.exp(-dy * 0.01), e.clientX, e.clientY, false);
1213
+ return;
1214
+ }
1215
+ const mouseWheel = e.deltaMode !== 0 || (dx === 0 && Math.abs(dy) >= 40 && Number.isInteger(dy));
1216
+ if (mouseWheel) {
1217
+ zoomBy(Math.exp(-dy * 0.0025), e.clientX, e.clientY, true);
1218
+ return;
1219
+ }
1220
+ if (s.scale > 1.01) {
1221
+ const b = bounds(s.scale);
1222
+ anim.stop(['x', 'y']);
1223
+ s.x = clamp(s.x - dx, -b.x, b.x);
1224
+ s.y = clamp(s.y - dy, -b.y, b.y);
1225
+ render();
1226
+ return;
1227
+ }
1228
+ const tNow = now();
1229
+ if (tNow < wheelLock) {
1230
+ // Swallow the inertial tail of a trackpad swipe that already paged.
1231
+ wheelLock = tNow + 200;
1232
+ return;
1233
+ }
1234
+ if (tNow - wheelLast > 200) wheelAccum = 0;
1235
+ wheelLast = tNow;
1236
+ if (Math.abs(dx) <= Math.abs(dy)) return;
1237
+ wheelAccum += dx;
1238
+ if (Math.abs(wheelAccum) > 60) {
1239
+ go(wheelAccum > 0 ? 1 : -1);
1240
+ wheelAccum = 0;
1241
+ wheelLock = tNow + 450;
1242
+ }
1243
+ }
1244
+
1245
+ function trapFocus(e) {
1246
+ const focusables = [...root.querySelectorAll('button:not([disabled]),a[href]')].filter(
1247
+ (node) => getComputedStyle(node).display !== 'none',
1248
+ );
1249
+ if (focusables.length === 0) {
1250
+ root.focus();
1251
+ return;
1252
+ }
1253
+ const at = focusables.indexOf(document.activeElement);
1254
+ const next = e.shiftKey ? (at <= 0 ? focusables.length - 1 : at - 1) : at === -1 || at === focusables.length - 1 ? 0 : at + 1;
1255
+ focusables[next].focus();
1256
+ }
1257
+
1258
+ function onKey(e) {
1259
+ if (closing || destroyed || editor !== null) return;
1260
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
1261
+ let handled = true;
1262
+ switch (e.key) {
1263
+ case 'Escape':
1264
+ close();
1265
+ break;
1266
+ case 'ArrowLeft':
1267
+ go(-1);
1268
+ break;
1269
+ case 'ArrowRight':
1270
+ go(1);
1271
+ break;
1272
+ case '+':
1273
+ case '=':
1274
+ zoomBy(1.5, vw / 2, vh / 2, true);
1275
+ break;
1276
+ case '-':
1277
+ case '_':
1278
+ zoomBy(1 / 1.5, vw / 2, vh / 2, true);
1279
+ break;
1280
+ case '0':
1281
+ anim.to({ scale: 1, x: 0, y: 0 }, { spring: SPRING.snap });
1282
+ break;
1283
+ case 'Tab':
1284
+ trapFocus(e);
1285
+ break;
1286
+ default:
1287
+ handled = false;
1288
+ }
1289
+ if (handled) e.preventDefault();
1290
+ // Keep app shortcuts from firing behind the viewer.
1291
+ e.stopPropagation();
1292
+ }
1293
+
1294
+ function onResize() {
1295
+ vw = root.clientWidth || window.innerWidth;
1296
+ vh = root.clientHeight || window.innerHeight;
1297
+ anim.stop(['x', 'y', 'scale', 'trackX']);
1298
+ s.trackX = 0;
1299
+ clearOutgoing();
1300
+ clampView();
1301
+ render();
1302
+ }
1303
+
1304
+ const preventDefault = (e) => e.preventDefault();
1305
+ //#endregion
1306
+
1307
+ //#region open / close
1308
+ function close(velocity = {}) {
1309
+ if (closing || destroyed) return;
1310
+ closing = true;
1311
+ clearTap();
1312
+ root.dataset.state = 'closing';
1313
+ root.style.pointerEvents = 'none';
1314
+ pointers.clear();
1315
+ gesture = null;
1316
+ setGesture(null);
1317
+ anim.stop();
1318
+ outgoing = null;
1319
+ syncSlides();
1320
+ const item = items[index];
1321
+ const target = sourceTarget(item);
1322
+ const fallback = setTimeout(finish, 1200);
1323
+ const done = () => {
1324
+ clearTimeout(fallback);
1325
+ finish();
1326
+ };
1327
+ if (target !== null) {
1328
+ item.inset = target.inset;
1329
+ anim.to(
1330
+ { x: target.x, y: target.y, scale: target.scale, clip: 1, radius: target.radius, bg: 0, trackX: 0, alpha: 1 },
1331
+ { spring: SPRING.close, velocity, onDone: done },
1332
+ );
1333
+ } else {
1334
+ anim.to({ bg: 0, alpha: 0, scale: s.scale * 0.9, trackX: 0 }, { spring: SPRING.close, velocity, onDone: done });
1335
+ }
1336
+ }
1337
+
1338
+ function finish(restore = true) {
1339
+ if (destroyed) return;
1340
+ destroyed = true;
1341
+ if (editor !== null) {
1342
+ editor.destroy();
1343
+ editor = null;
1344
+ }
1345
+ anim.destroy();
1346
+ clearTap();
1347
+ showSource();
1348
+ window.removeEventListener('keydown', onKey, true);
1349
+ window.removeEventListener('resize', onResize);
1350
+ root.remove();
1351
+ if (restore && restoreFocus !== null && restoreFocus.isConnected) {
1352
+ try {
1353
+ restoreFocus.focus({ preventScroll: true });
1354
+ } catch {
1355
+ // focus is best-effort
1356
+ }
1357
+ }
1358
+ onDestroyed();
1359
+ }
1360
+
1361
+ root.addEventListener('pointerdown', onDown);
1362
+ root.addEventListener('pointermove', onMove);
1363
+ root.addEventListener('pointerup', onUp);
1364
+ root.addEventListener('pointercancel', onUp);
1365
+ root.addEventListener('wheel', onWheel, { passive: false });
1366
+ root.addEventListener('dragstart', preventDefault);
1367
+ root.addEventListener('gesturestart', preventDefault);
1368
+ root.addEventListener('gesturechange', preventDefault);
1369
+ window.addEventListener('keydown', onKey, true);
1370
+ window.addEventListener('resize', onResize);
1371
+ zoomBtn.addEventListener('click', () => {
1372
+ if (s.scale > 1.01) anim.to({ scale: 1, x: 0, y: 0 }, { spring: SPRING.snap });
1373
+ else zoomBy(doubleTapScale(), vw / 2, vh / 2, true);
1374
+ });
1375
+ function openEdit() {
1376
+ if (closing || destroyed || editor !== null) return;
1377
+ clearTap();
1378
+ editor = openEditor(items[index], t, {
1379
+ cancel: () => {
1380
+ editor = null;
1381
+ try {
1382
+ editBtn.focus({ preventScroll: true });
1383
+ } catch {
1384
+ // focus is best-effort
1385
+ }
1386
+ },
1387
+ done: (injected) => {
1388
+ editor = null;
1389
+ // Injected: focus stays in the composer. Downloaded: return to the thumbnail.
1390
+ finish(!injected);
1391
+ },
1392
+ });
1393
+ }
1394
+ if (editBtn !== null) editBtn.addEventListener('click', openEdit);
1395
+ closeBtn.addEventListener('click', () => close());
1396
+ prevBtn.addEventListener('click', () => go(-1));
1397
+ nextBtn.addEventListener('click', () => go(1));
1398
+
1399
+ document.body.appendChild(root);
1400
+ vw = root.clientWidth || window.innerWidth;
1401
+ vh = root.clientHeight || window.innerHeight;
1402
+
1403
+ const first = items[index];
1404
+ const from = sourceTarget(first);
1405
+ if (from !== null) {
1406
+ first.inset = from.inset;
1407
+ Object.assign(s, { x: from.x, y: from.y, scale: from.scale, clip: 1, radius: from.radius, bg: 0, alpha: 1 });
1408
+ } else {
1409
+ Object.assign(s, { scale: 0.92, bg: 0, alpha: 0 });
1410
+ }
1411
+ syncSlides();
1412
+ updateChrome();
1413
+ render();
1414
+ try {
1415
+ closeBtn.focus({ preventScroll: true });
1416
+ } catch {
1417
+ root.focus();
1418
+ }
1419
+ anim.to({ x: 0, y: 0, scale: 1, clip: 0, radius: 0, bg: 1, alpha: 1 }, {
1420
+ spring: SPRING.open,
1421
+ onDone: () => {
1422
+ if (!closing) root.dataset.state = 'open';
1423
+ },
1424
+ });
1425
+ // Interrupted opens still need to leave the "opening" state.
1426
+ setTimeout(() => {
1427
+ if (!closing && !destroyed) root.dataset.state = 'open';
1428
+ }, 600);
1429
+ //#endregion
1430
+
1431
+ return { close, destroy: finish };
1432
+ }
1433
+ //#endregion
1434
+
1435
+ //#region composer injection
1436
+ /** Canvas export is required for the annotation editor. */
1437
+ function canEdit() {
1438
+ try {
1439
+ const canvas = document.createElement('canvas');
1440
+ return typeof canvas.getContext === 'function' && typeof canvas.toBlob === 'function' && canvas.getContext('2d') !== null;
1441
+ } catch {
1442
+ return false;
1443
+ }
1444
+ }
1445
+
1446
+ function visible(el) {
1447
+ const rect = el.getBoundingClientRect();
1448
+ return rect.width > 0 && rect.height > 0;
1449
+ }
1450
+
1451
+ /** The chat composer is a Lexical root marked `data-composer-input`. */
1452
+ function findComposer() {
1453
+ const all = [...document.querySelectorAll('[data-composer-input]')].filter(
1454
+ (el) => el.isConnected && el.closest(`[${ROOT_ATTR}],[${EDIT_ATTR}]`) === null,
1455
+ );
1456
+ const editable = all.filter((el) => el.getAttribute('contenteditable') === 'true');
1457
+ const pool = editable.length > 0 ? editable : all;
1458
+ return pool.find(visible) || pool[0] || null;
1459
+ }
1460
+
1461
+ /** A real DataTransfer when the browser allows it, else a structural stand-in. */
1462
+ function transferOf(file) {
1463
+ try {
1464
+ const dt = new DataTransfer();
1465
+ dt.items.add(file);
1466
+ if (dt.files.length === 1) return dt;
1467
+ } catch {
1468
+ // fall through to the stand-in
1469
+ }
1470
+ const item = { kind: 'file', type: file.type, getAsFile: () => file, webkitGetAsEntry: () => null };
1471
+ return {
1472
+ files: [file],
1473
+ items: [item],
1474
+ types: ['Files'],
1475
+ dropEffect: 'copy',
1476
+ effectAllowed: 'all',
1477
+ getData: () => '',
1478
+ setData() {},
1479
+ clearData() {},
1480
+ };
1481
+ }
1482
+
1483
+ function synthetic(type, field, transfer, Ctor) {
1484
+ let ev = null;
1485
+ try {
1486
+ if (typeof Ctor === 'function') ev = new Ctor(type, { bubbles: true, cancelable: true, [field]: transfer });
1487
+ } catch {
1488
+ ev = null;
1489
+ }
1490
+ if (ev === null) ev = new Event(type, { bubbles: true, cancelable: true });
1491
+ if (ev[field] !== transfer) {
1492
+ try {
1493
+ Object.defineProperty(ev, field, { value: transfer, configurable: true });
1494
+ } catch {
1495
+ // keep whatever the constructor produced
1496
+ }
1497
+ }
1498
+ return ev;
1499
+ }
1500
+
1501
+ /**
1502
+ * Hand one image to the composer the way a paste would. The composer's own
1503
+ * paste command calls preventDefault after it accepts files; the attachment
1504
+ * view's document drop listener is the fallback.
1505
+ * @returns 'composer' | 'none'
1506
+ */
1507
+ function injectFile(file) {
1508
+ const composer = findComposer();
1509
+ if (composer !== null && composer.getAttribute('contenteditable') === 'true') {
1510
+ try {
1511
+ composer.focus({ preventScroll: false });
1512
+ } catch {
1513
+ // focus is best-effort
1514
+ }
1515
+ const paste = synthetic('paste', 'clipboardData', transferOf(file), window.ClipboardEvent);
1516
+ composer.dispatchEvent(paste);
1517
+ if (paste.defaultPrevented) return 'composer';
1518
+ }
1519
+ if (composer !== null) {
1520
+ const drop = synthetic('drop', 'dataTransfer', transferOf(file), window.DragEvent);
1521
+ document.body.dispatchEvent(drop);
1522
+ if (drop.defaultPrevented) {
1523
+ try {
1524
+ composer.focus({ preventScroll: false });
1525
+ } catch {
1526
+ // focus is best-effort
1527
+ }
1528
+ return 'composer';
1529
+ }
1530
+ }
1531
+ return 'none';
1532
+ }
1533
+
1534
+ function toast(text) {
1535
+ const node = h('div', 'qiv-toast', { role: 'status', [IGNORE_ATTR]: '' });
1536
+ node.textContent = text;
1537
+ document.body.appendChild(node);
1538
+ requestAnimationFrame(() => node.setAttribute('data-show', ''));
1539
+ setTimeout(() => {
1540
+ node.removeAttribute('data-show');
1541
+ setTimeout(() => node.remove(), 300);
1542
+ }, 2600);
1543
+ }
1544
+
1545
+ function downloadFile(file) {
1546
+ const url = URL.createObjectURL(file);
1547
+ const a = h('a', '', { href: url, download: file.name, [IGNORE_ATTR]: '' });
1548
+ a.style.display = 'none';
1549
+ document.body.appendChild(a);
1550
+ a.click();
1551
+ a.remove();
1552
+ setTimeout(() => URL.revokeObjectURL(url), 30000);
1553
+ }
1554
+ //#endregion
1555
+
1556
+ //#region annotation editor
1557
+ const EDIT_ATTR = 'data-qiv-edit';
1558
+ const COLORS = [
1559
+ ['#ffffff', 'white'],
1560
+ ['#000000', 'black'],
1561
+ ['#ff3b30', 'red'],
1562
+ ['#ff9500', 'orange'],
1563
+ ['#ffcc00', 'yellow'],
1564
+ ['#34c759', 'green'],
1565
+ ['#007aff', 'blue'],
1566
+ ['#af52de', 'purple'],
1567
+ ];
1568
+ const SIZE_MIN = 2;
1569
+ const SIZE_MAX = 36;
1570
+ /** Working canvas limits; keeps mobile Safari under its canvas memory cap. */
1571
+ const EDIT_MAX_EDGE = 4096;
1572
+ const EDIT_MAX_PIXELS = 12e6;
1573
+ const EXPORT_MAX_BYTES = 8 * 1024 * 1024;
1574
+
1575
+ function needsCors(src) {
1576
+ try {
1577
+ const url = new URL(src, location.href);
1578
+ if (url.protocol === 'data:' || url.protocol === 'blob:') return false;
1579
+ return url.protocol !== location.protocol || url.host !== location.host;
1580
+ } catch {
1581
+ return false;
1582
+ }
1583
+ }
1584
+
1585
+ function loadImage(src, cors) {
1586
+ return new Promise((resolve, reject) => {
1587
+ const img = new Image();
1588
+ if (cors) img.crossOrigin = 'anonymous';
1589
+ img.decoding = 'async';
1590
+ img.onload = () => resolve(img);
1591
+ img.onerror = () => reject(new Error('load failed'));
1592
+ img.src = src;
1593
+ });
1594
+ }
1595
+
1596
+ /** Prefer a CORS load so export works; fall back to a tainted copy so drawing still does. */
1597
+ async function loadEditable(src) {
1598
+ if (!needsCors(src)) return { img: await loadImage(src, false), tainted: false };
1599
+ try {
1600
+ return { img: await loadImage(src, true), tainted: false };
1601
+ } catch {
1602
+ return { img: await loadImage(src, false), tainted: true };
1603
+ }
1604
+ }
1605
+
1606
+ const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
1607
+ function segDist(p, a, b) {
1608
+ const dx = b.x - a.x;
1609
+ const dy = b.y - a.y;
1610
+ const len = dx * dx + dy * dy;
1611
+ const k = len === 0 ? 0 : clamp(((p.x - a.x) * dx + (p.y - a.y) * dy) / len, 0, 1);
1612
+ return Math.hypot(p.x - (a.x + k * dx), p.y - (a.y + k * dy));
1613
+ }
1614
+
1615
+ function arrowHead(a, b, w) {
1616
+ const len = dist(a, b);
1617
+ const size = Math.min(Math.max(w * 3.2, 14), len * 0.45);
1618
+ const ang = Math.atan2(b.y - a.y, b.x - a.x);
1619
+ const spread = Math.PI / 7;
1620
+ return [
1621
+ { x: b.x - size * Math.cos(ang - spread), y: b.y - size * Math.sin(ang - spread) },
1622
+ { x: b.x - size * Math.cos(ang + spread), y: b.y - size * Math.sin(ang + spread) },
1623
+ ];
1624
+ }
1625
+
1626
+ /** Polylines used for hit-testing every stroke kind with one segment test. */
1627
+ function outlines(st) {
1628
+ if (st.kind === 'pen') return [st.points];
1629
+ const [a, b] = [st.a, st.b];
1630
+ if (st.kind === 'line') return [[a, b]];
1631
+ if (st.kind === 'arrow') {
1632
+ const [l, r] = arrowHead(a, b, st.w);
1633
+ return [[a, b], [l, b, r]];
1634
+ }
1635
+ if (st.kind === 'rect') {
1636
+ return [[a, { x: b.x, y: a.y }, b, { x: a.x, y: b.y }, a]];
1637
+ }
1638
+ const cx = (a.x + b.x) / 2;
1639
+ const cy = (a.y + b.y) / 2;
1640
+ const rx = Math.abs(b.x - a.x) / 2;
1641
+ const ry = Math.abs(b.y - a.y) / 2;
1642
+ const pts = [];
1643
+ for (let i = 0; i <= 48; i++) {
1644
+ const t = (i / 48) * Math.PI * 2;
1645
+ pts.push({ x: cx + rx * Math.cos(t), y: cy + ry * Math.sin(t) });
1646
+ }
1647
+ return [pts];
1648
+ }
1649
+
1650
+ function hitStroke(st, p, tol) {
1651
+ const reach = tol + st.w / 2;
1652
+ for (const line of outlines(st)) {
1653
+ if (line.length === 1 && dist(line[0], p) <= reach) return true;
1654
+ for (let i = 1; i < line.length; i++) if (segDist(p, line[i - 1], line[i]) <= reach) return true;
1655
+ }
1656
+ return false;
1657
+ }
1658
+
1659
+ function drawStroke(ctx, st) {
1660
+ ctx.save();
1661
+ ctx.strokeStyle = st.color;
1662
+ ctx.fillStyle = st.color;
1663
+ ctx.lineWidth = st.w;
1664
+ ctx.lineCap = 'round';
1665
+ ctx.lineJoin = 'round';
1666
+ ctx.beginPath();
1667
+ if (st.kind === 'pen') {
1668
+ const pts = st.points;
1669
+ if (pts.length === 1) {
1670
+ ctx.arc(pts[0].x, pts[0].y, st.w / 2, 0, Math.PI * 2);
1671
+ ctx.fill();
1672
+ ctx.restore();
1673
+ return;
1674
+ }
1675
+ ctx.moveTo(pts[0].x, pts[0].y);
1676
+ for (let i = 1; i < pts.length - 1; i++) {
1677
+ const mx = (pts[i].x + pts[i + 1].x) / 2;
1678
+ const my = (pts[i].y + pts[i + 1].y) / 2;
1679
+ ctx.quadraticCurveTo(pts[i].x, pts[i].y, mx, my);
1680
+ }
1681
+ const last = pts[pts.length - 1];
1682
+ ctx.lineTo(last.x, last.y);
1683
+ } else if (st.kind === 'line' || st.kind === 'arrow') {
1684
+ ctx.moveTo(st.a.x, st.a.y);
1685
+ ctx.lineTo(st.b.x, st.b.y);
1686
+ if (st.kind === 'arrow') {
1687
+ const [l, r] = arrowHead(st.a, st.b, st.w);
1688
+ ctx.moveTo(l.x, l.y);
1689
+ ctx.lineTo(st.b.x, st.b.y);
1690
+ ctx.lineTo(r.x, r.y);
1691
+ }
1692
+ } else if (st.kind === 'rect') {
1693
+ ctx.rect(Math.min(st.a.x, st.b.x), Math.min(st.a.y, st.b.y), Math.abs(st.b.x - st.a.x), Math.abs(st.b.y - st.a.y));
1694
+ } else {
1695
+ ctx.ellipse((st.a.x + st.b.x) / 2, (st.a.y + st.b.y) / 2, Math.abs(st.b.x - st.a.x) / 2, Math.abs(st.b.y - st.a.y) / 2, 0, 0, Math.PI * 2);
1696
+ }
1697
+ ctx.stroke();
1698
+ ctx.restore();
1699
+ }
1700
+
1701
+ function stemOf(src) {
1702
+ const base = fileName(src).replace(/\.[a-z0-9]+$/i, '');
1703
+ const safe = base.replace(/[^\w\u4e00-\u9fff-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60);
1704
+ return safe || 'image';
1705
+ }
1706
+
1707
+ /**
1708
+ * Full-screen markup editor (pen / shapes / eraser, colours, width,
1709
+ * undo/redo, pinch zoom). Done exports PNG and pastes it into the composer.
1710
+ * @param item - viewer item ({ src, alt }).
1711
+ * @param hooks - { cancel(), done() }.
1712
+ */
1713
+ function openEditor(item, t, hooks) {
1714
+ const root = h('div', 'qie', { [EDIT_ATTR]: '', [IGNORE_ATTR]: '', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('edit.dialog'), tabindex: '-1' });
1715
+ const btn = (className, label, icon, extra) => {
1716
+ const b = h('button', className, { type: 'button', 'aria-label': label, title: label, ...(extra || {}) });
1717
+ b.innerHTML = icon;
1718
+ return b;
1719
+ };
1720
+
1721
+ //#region dom
1722
+ const top = h('div', 'qie-top');
1723
+ const backBtn = btn('qie-round', t('edit.cancel'), ICON.back);
1724
+ const tools = h('div', 'qie-tools', { role: 'toolbar', 'aria-label': t('edit.tools') });
1725
+ const penBtn = btn('qie-tool', t('edit.pen'), ICON.pen, { 'aria-pressed': 'true' });
1726
+ const shapeBtn = btn('qie-tool', t('edit.shapes'), ICON.shapes, { 'aria-pressed': 'false', 'aria-haspopup': 'true', 'aria-expanded': 'false' });
1727
+ const eraseBtn = btn('qie-tool', t('edit.eraser'), ICON.eraser, { 'aria-pressed': 'false' });
1728
+ tools.append(penBtn, shapeBtn, eraseBtn);
1729
+ const history = h('div', 'qie-history');
1730
+ const undoBtn = btn('qie-round', t('edit.undo'), ICON.undo);
1731
+ const redoBtn = btn('qie-round', t('edit.redo'), ICON.redo);
1732
+ history.append(undoBtn, redoBtn);
1733
+ const pop = h('div', 'qie-pop', { role: 'group', 'aria-label': t('edit.shapes') });
1734
+ pop.hidden = true;
1735
+ const shapeButtons = {};
1736
+ for (const kind of ['arrow', 'rect', 'ellipse', 'line']) {
1737
+ const b = btn('qie-shape', t('edit.shape.' + kind), ICON[kind], { 'data-kind': kind, 'aria-pressed': 'false' });
1738
+ shapeButtons[kind] = b;
1739
+ pop.appendChild(b);
1740
+ }
1741
+ top.append(backBtn, tools, history, pop);
1742
+
1743
+ const area = h('div', 'qie-area');
1744
+ const stage = h('div', 'qie-stage');
1745
+ let base = h('img', 'qie-base', { alt: item.alt || '', draggable: 'false' });
1746
+ const ink = h('canvas', 'qie-ink');
1747
+ const live = h('canvas', 'qie-live');
1748
+ stage.append(base, ink, live);
1749
+ const status = h('div', 'qie-status');
1750
+ status.innerHTML = '<div class="qiv-spin"></div>';
1751
+ const note = h('div', 'qie-note');
1752
+ note.hidden = true;
1753
+ note.textContent = t('edit.taintedHint');
1754
+ area.append(stage, status, note);
1755
+
1756
+ const slider = h('div', 'qie-size', {
1757
+ role: 'slider',
1758
+ tabindex: '0',
1759
+ 'aria-label': t('edit.size'),
1760
+ 'aria-orientation': 'vertical',
1761
+ 'aria-valuemin': String(SIZE_MIN),
1762
+ 'aria-valuemax': String(SIZE_MAX),
1763
+ });
1764
+ const rail = h('div', 'qie-rail');
1765
+ const knob = h('div', 'qie-knob');
1766
+ const preview = h('div', 'qie-preview', { 'aria-hidden': 'true' });
1767
+ rail.appendChild(knob);
1768
+ slider.append(rail, preview);
1769
+
1770
+ const bottom = h('div', 'qie-bottom');
1771
+ const palette = h('div', 'qie-palette', { role: 'radiogroup', 'aria-label': t('edit.color') });
1772
+ const customWrap = h('label', 'qie-swatch qie-custom', { title: t('edit.custom') });
1773
+ const customInput = h('input', '', { type: 'color', 'aria-label': t('edit.custom') });
1774
+ customWrap.appendChild(customInput);
1775
+ palette.appendChild(customWrap);
1776
+ const swatches = [];
1777
+ for (const [hex, name] of COLORS) {
1778
+ const sw = h('button', 'qie-swatch', { type: 'button', role: 'radio', 'aria-checked': 'false', 'aria-label': t('edit.color.' + name), title: t('edit.color.' + name), 'data-color': hex });
1779
+ sw.style.setProperty('--qie-c', hex);
1780
+ swatches.push(sw);
1781
+ palette.appendChild(sw);
1782
+ }
1783
+ const doneBtn = btn('qie-done', t('edit.done'), ICON.check);
1784
+ bottom.append(palette, doneBtn);
1785
+ root.append(top, area, slider, bottom);
1786
+ //#endregion
1787
+
1788
+ //#region state
1789
+ let W = 0;
1790
+ let H = 0;
1791
+ let img = null;
1792
+ let tainted = false;
1793
+ let inkCtx = null;
1794
+ let liveCtx = null;
1795
+ let strokes = [];
1796
+ const past = [];
1797
+ const future = [];
1798
+ let tool = 'pen';
1799
+ let shape = 'arrow';
1800
+ let color = '#ff3b30';
1801
+ let size = 6;
1802
+ let customColor = null;
1803
+ const view = { z: 1, x: 0, y: 0 };
1804
+ let fitW = 0;
1805
+ let fitH = 0;
1806
+ const pts = new Map();
1807
+ let op = null;
1808
+ let pinch = null;
1809
+ let sawPen = false;
1810
+ let busy = false;
1811
+ let ready = false;
1812
+ let destroyed = false;
1813
+ let raf = 0;
1814
+ //#endregion
1815
+
1816
+ //#region layout + view
1817
+ function layout() {
1818
+ const aw = area.clientWidth || window.innerWidth;
1819
+ const ah = area.clientHeight || window.innerHeight * 0.7;
1820
+ if (W === 0 || H === 0) return;
1821
+ const k = Math.min((aw - 24) / W, (ah - 24) / H);
1822
+ fitW = Math.max(1, W * k);
1823
+ fitH = Math.max(1, H * k);
1824
+ stage.style.width = fitW + 'px';
1825
+ stage.style.height = fitH + 'px';
1826
+ applyView();
1827
+ }
1828
+
1829
+ function viewBounds(z) {
1830
+ const aw = area.clientWidth || window.innerWidth;
1831
+ const ah = area.clientHeight || window.innerHeight * 0.7;
1832
+ return { x: Math.max(0, (fitW * z - aw) / 2 + 12), y: Math.max(0, (fitH * z - ah) / 2 + 12) };
1833
+ }
1834
+
1835
+ function applyView() {
1836
+ stage.style.transform = `translate(-50%,-50%) translate(${view.x}px,${view.y}px) scale(${view.z})`;
1837
+ root.toggleAttribute('data-zoomed', view.z > 1.01);
1838
+ }
1839
+
1840
+ function settleView() {
1841
+ view.z = clamp(view.z, 1, 8);
1842
+ if (view.z <= 1.01) {
1843
+ view.z = 1;
1844
+ view.x = 0;
1845
+ view.y = 0;
1846
+ } else {
1847
+ const b = viewBounds(view.z);
1848
+ view.x = clamp(view.x, -b.x, b.x);
1849
+ view.y = clamp(view.y, -b.y, b.y);
1850
+ }
1851
+ root.setAttribute('data-settle', '');
1852
+ applyView();
1853
+ setTimeout(() => root.removeAttribute('data-settle'), 260);
1854
+ }
1855
+
1856
+ /** Zoom so the content point under (cx, cy) stays put. */
1857
+ function zoomAround(z, cx, cy) {
1858
+ const r = area.getBoundingClientRect();
1859
+ const ox = cx - (r.left + r.width / 2);
1860
+ const oy = cy - (r.top + r.height / 2);
1861
+ const k = z / view.z;
1862
+ view.x = ox - (ox - view.x) * k;
1863
+ view.y = oy - (oy - view.y) * k;
1864
+ view.z = z;
1865
+ applyView();
1866
+ }
1867
+
1868
+ /** Client point -> working-canvas pixel. */
1869
+ function toImage(e) {
1870
+ const r = stage.getBoundingClientRect();
1871
+ const rw = r.width || fitW * view.z || 1;
1872
+ const rh = r.height || fitH * view.z || 1;
1873
+ return { x: ((e.clientX - r.left) / rw) * W, y: ((e.clientY - r.top) / rh) * H };
1874
+ }
1875
+
1876
+ /** Screen px -> image px at the current zoom. */
1877
+ function imagePx(px) {
1878
+ return (px * W) / Math.max(1, fitW * view.z);
1879
+ }
1880
+ //#endregion
1881
+
1882
+ //#region drawing
1883
+ function redraw() {
1884
+ if (inkCtx === null) return;
1885
+ inkCtx.clearRect(0, 0, W, H);
1886
+ for (const st of strokes) drawStroke(inkCtx, st);
1887
+ }
1888
+
1889
+ function paintLive() {
1890
+ raf = 0;
1891
+ if (liveCtx === null) return;
1892
+ liveCtx.clearRect(0, 0, W, H);
1893
+ if (op !== null && op.stroke) drawStroke(liveCtx, op.stroke);
1894
+ }
1895
+
1896
+ function scheduleLive() {
1897
+ if (raf === 0) raf = requestAnimationFrame(paintLive);
1898
+ }
1899
+
1900
+ function syncHistory() {
1901
+ undoBtn.disabled = past.length === 0;
1902
+ redoBtn.disabled = future.length === 0;
1903
+ }
1904
+
1905
+ function eraseAt(p) {
1906
+ const tol = imagePx(Math.max(8, size));
1907
+ const kept = strokes.filter((st) => !hitStroke(st, p, tol));
1908
+ if (kept.length === strokes.length) return;
1909
+ if (op.before === null) op.before = strokes;
1910
+ strokes = kept;
1911
+ redraw();
1912
+ }
1913
+
1914
+ function undo() {
1915
+ if (past.length === 0) return;
1916
+ future.push(strokes);
1917
+ strokes = past.pop();
1918
+ redraw();
1919
+ syncHistory();
1920
+ }
1921
+
1922
+ function redo() {
1923
+ if (future.length === 0) return;
1924
+ past.push(strokes);
1925
+ strokes = future.pop();
1926
+ redraw();
1927
+ syncHistory();
1928
+ }
1929
+
1930
+ /** Abandon the in-flight operation (a second finger arrived). */
1931
+ function cancelOp() {
1932
+ if (op === null) return;
1933
+ if (op.kind === 'erase' && op.before !== null) {
1934
+ past.push(op.before);
1935
+ future.length = 0;
1936
+ syncHistory();
1937
+ }
1938
+ op = null;
1939
+ if (raf !== 0) cancelAnimationFrame(raf);
1940
+ paintLive();
1941
+ }
1942
+ //#endregion
1943
+
1944
+ //#region pointer input
1945
+ function onDown(e) {
1946
+ if (!ready || busy) return;
1947
+ if (e.pointerType === 'mouse' && e.button !== 0 && e.button !== 1) return;
1948
+ if (e.pointerType === 'pen') sawPen = true;
1949
+ // Palm rejection: with an Apple Pencil in use, fingers only navigate.
1950
+ const navOnly = sawPen && e.pointerType === 'touch';
1951
+ e.preventDefault();
1952
+ try {
1953
+ area.setPointerCapture(e.pointerId);
1954
+ } catch {
1955
+ // capture is best-effort
1956
+ }
1957
+ pts.set(e.pointerId, { x: e.clientX, y: e.clientY, type: e.pointerType });
1958
+ closePop();
1959
+ if (pts.size >= 2) {
1960
+ cancelOp();
1961
+ const [a, b] = [...pts.values()];
1962
+ pinch = { d: Math.max(1, dist(a, b)), z: view.z, vx: view.x, vy: view.y, mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
1963
+ return;
1964
+ }
1965
+ if (e.button === 1 || navOnly || (e.pointerType === 'mouse' && e.altKey && view.z > 1)) {
1966
+ op = { kind: 'pan', id: e.pointerId, sx: e.clientX, sy: e.clientY, vx: view.x, vy: view.y };
1967
+ return;
1968
+ }
1969
+ const p = toImage(e);
1970
+ if (tool === 'erase') {
1971
+ op = { kind: 'erase', id: e.pointerId, before: null };
1972
+ eraseAt(p);
1973
+ return;
1974
+ }
1975
+ const w = imagePx(size);
1976
+ const stroke = tool === 'pen' ? { kind: 'pen', color, w, points: [p] } : { kind: shape, color, w, a: p, b: p };
1977
+ op = { kind: 'draw', id: e.pointerId, stroke, sx: e.clientX, sy: e.clientY, moved: 0 };
1978
+ scheduleLive();
1979
+ }
1980
+
1981
+ function onMove(e) {
1982
+ const p0 = pts.get(e.pointerId);
1983
+ if (p0 === undefined) return;
1984
+ p0.x = e.clientX;
1985
+ p0.y = e.clientY;
1986
+ if (pinch !== null) {
1987
+ if (pts.size < 2) return;
1988
+ const [a, b] = [...pts.values()];
1989
+ const z = clamp(pinch.z * (dist(a, b) / pinch.d), 0.6, 10);
1990
+ const mx = (a.x + b.x) / 2;
1991
+ const my = (a.y + b.y) / 2;
1992
+ const r = area.getBoundingClientRect();
1993
+ const ox = pinch.mx - (r.left + r.width / 2);
1994
+ const oy = pinch.my - (r.top + r.height / 2);
1995
+ const k = z / pinch.z;
1996
+ view.z = z;
1997
+ view.x = ox - (ox - pinch.vx) * k + (mx - pinch.mx);
1998
+ view.y = oy - (oy - pinch.vy) * k + (my - pinch.my);
1999
+ applyView();
2000
+ return;
2001
+ }
2002
+ if (op === null || op.id !== e.pointerId) return;
2003
+ if (op.kind === 'pan') {
2004
+ view.x = op.vx + e.clientX - op.sx;
2005
+ view.y = op.vy + e.clientY - op.sy;
2006
+ applyView();
2007
+ return;
2008
+ }
2009
+ const events = typeof e.getCoalescedEvents === 'function' ? e.getCoalescedEvents() : [];
2010
+ const list = events.length > 0 ? events : [e];
2011
+ if (op.kind === 'erase') {
2012
+ for (const ev of list) eraseAt(toImage(ev));
2013
+ return;
2014
+ }
2015
+ op.moved = Math.max(op.moved, Math.hypot(e.clientX - op.sx, e.clientY - op.sy));
2016
+ const st = op.stroke;
2017
+ if (st.kind === 'pen') {
2018
+ const min = imagePx(1.2);
2019
+ for (const ev of list) {
2020
+ const p = toImage(ev);
2021
+ if (dist(p, st.points[st.points.length - 1]) >= min) st.points.push(p);
2022
+ }
2023
+ } else {
2024
+ let b = toImage(e);
2025
+ if (e.shiftKey) {
2026
+ const dx = b.x - st.a.x;
2027
+ const dy = b.y - st.a.y;
2028
+ if (st.kind === 'rect' || st.kind === 'ellipse') {
2029
+ const m = Math.max(Math.abs(dx), Math.abs(dy));
2030
+ b = { x: st.a.x + Math.sign(dx || 1) * m, y: st.a.y + Math.sign(dy || 1) * m };
2031
+ } else {
2032
+ const ang = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);
2033
+ const len = Math.hypot(dx, dy);
2034
+ b = { x: st.a.x + len * Math.cos(ang), y: st.a.y + len * Math.sin(ang) };
2035
+ }
2036
+ }
2037
+ st.b = b;
2038
+ }
2039
+ scheduleLive();
2040
+ }
2041
+
2042
+ function onUp(e) {
2043
+ if (!pts.has(e.pointerId)) return;
2044
+ pts.delete(e.pointerId);
2045
+ if (pinch !== null) {
2046
+ if (pts.size < 2) {
2047
+ pinch = null;
2048
+ settleView();
2049
+ }
2050
+ return;
2051
+ }
2052
+ if (op === null || op.id !== e.pointerId) return;
2053
+ const done = op;
2054
+ op = null;
2055
+ if (done.kind === 'pan') {
2056
+ settleView();
2057
+ return;
2058
+ }
2059
+ if (done.kind === 'erase') {
2060
+ if (done.before !== null) {
2061
+ past.push(done.before);
2062
+ future.length = 0;
2063
+ syncHistory();
2064
+ }
2065
+ return;
2066
+ }
2067
+ if (raf !== 0) {
2068
+ cancelAnimationFrame(raf);
2069
+ raf = 0;
2070
+ }
2071
+ liveCtx.clearRect(0, 0, W, H);
2072
+ const st = done.stroke;
2073
+ if (e.type === 'pointercancel') return;
2074
+ if (st.kind !== 'pen' && dist(st.a, st.b) < imagePx(4)) return;
2075
+ past.push(strokes);
2076
+ future.length = 0;
2077
+ strokes = strokes.concat([st]);
2078
+ drawStroke(inkCtx, st);
2079
+ syncHistory();
2080
+ }
2081
+
2082
+ function onWheel(e) {
2083
+ if (!ready) return;
2084
+ e.preventDefault();
2085
+ if (e.ctrlKey || e.metaKey || view.z <= 1.01) {
2086
+ const unit = e.deltaMode === 1 ? 16 : 1;
2087
+ const z = clamp(view.z * Math.exp((-e.deltaY * unit) / (e.ctrlKey ? 100 : 400)), 1, 8);
2088
+ zoomAround(z, e.clientX, e.clientY);
2089
+ if (z <= 1.01) settleView();
2090
+ } else {
2091
+ view.x -= e.deltaX;
2092
+ view.y -= e.deltaY;
2093
+ const b = viewBounds(view.z);
2094
+ view.x = clamp(view.x, -b.x, b.x);
2095
+ view.y = clamp(view.y, -b.y, b.y);
2096
+ applyView();
2097
+ }
2098
+ }
2099
+ //#endregion
2100
+
2101
+ //#region tools, colour, size
2102
+ function closePop() {
2103
+ if (pop.hidden) return;
2104
+ pop.hidden = true;
2105
+ shapeBtn.setAttribute('aria-expanded', 'false');
2106
+ }
2107
+
2108
+ function setTool(next) {
2109
+ tool = next;
2110
+ penBtn.setAttribute('aria-pressed', String(next === 'pen'));
2111
+ shapeBtn.setAttribute('aria-pressed', String(next === 'shape'));
2112
+ eraseBtn.setAttribute('aria-pressed', String(next === 'erase'));
2113
+ root.setAttribute('data-tool', next);
2114
+ shapeBtn.innerHTML = ICON[shape];
2115
+ for (const [kind, b] of Object.entries(shapeButtons)) b.setAttribute('aria-pressed', String(kind === shape));
2116
+ }
2117
+
2118
+ function setColor(hex, custom) {
2119
+ color = hex;
2120
+ for (const sw of swatches) sw.setAttribute('aria-checked', String(!custom && sw.dataset.color === hex));
2121
+ customWrap.toggleAttribute('data-checked', custom === true);
2122
+ root.style.setProperty('--qie-ink', hex);
2123
+ if (tool === 'erase') setTool('pen');
2124
+ syncSize();
2125
+ }
2126
+
2127
+ function syncSize() {
2128
+ const k = Math.sqrt((size - SIZE_MIN) / (SIZE_MAX - SIZE_MIN));
2129
+ slider.style.setProperty('--qie-k', String(k));
2130
+ slider.setAttribute('aria-valuenow', String(Math.round(size)));
2131
+ const d = Math.max(4, size);
2132
+ preview.style.width = d + 'px';
2133
+ preview.style.height = d + 'px';
2134
+ }
2135
+
2136
+ function sizeFromPointer(e) {
2137
+ const r = rail.getBoundingClientRect();
2138
+ const k = clamp(1 - (e.clientY - r.top) / Math.max(1, r.height), 0, 1);
2139
+ size = SIZE_MIN + k * k * (SIZE_MAX - SIZE_MIN);
2140
+ syncSize();
2141
+ }
2142
+
2143
+ let sizeDrag = null;
2144
+ function onSizeDown(e) {
2145
+ e.preventDefault();
2146
+ e.stopPropagation();
2147
+ sizeDrag = e.pointerId;
2148
+ try {
2149
+ slider.setPointerCapture(e.pointerId);
2150
+ } catch {
2151
+ // capture is best-effort
2152
+ }
2153
+ slider.setAttribute('data-active', '');
2154
+ sizeFromPointer(e);
2155
+ }
2156
+ function onSizeMove(e) {
2157
+ if (sizeDrag === e.pointerId) sizeFromPointer(e);
2158
+ }
2159
+ function onSizeUp(e) {
2160
+ if (sizeDrag !== e.pointerId) return;
2161
+ sizeDrag = null;
2162
+ slider.removeAttribute('data-active');
2163
+ }
2164
+ function onSizeKey(e) {
2165
+ const step = e.shiftKey ? 4 : 1;
2166
+ if (e.key === 'ArrowUp' || e.key === 'ArrowRight') size = clamp(size + step, SIZE_MIN, SIZE_MAX);
2167
+ else if (e.key === 'ArrowDown' || e.key === 'ArrowLeft') size = clamp(size - step, SIZE_MIN, SIZE_MAX);
2168
+ else return;
2169
+ e.preventDefault();
2170
+ e.stopPropagation();
2171
+ syncSize();
2172
+ }
2173
+ //#endregion
2174
+
2175
+ //#region keyboard + focus
2176
+ function trap(e) {
2177
+ const list = [...root.querySelectorAll('button:not([disabled]),input,[tabindex="0"]')].filter(
2178
+ (el) => el.closest('[hidden]') === null,
2179
+ );
2180
+ if (list.length === 0) return;
2181
+ const first = list[0];
2182
+ const last = list[list.length - 1];
2183
+ const active = document.activeElement;
2184
+ if (!root.contains(active)) {
2185
+ e.preventDefault();
2186
+ first.focus();
2187
+ } else if (e.shiftKey && active === first) {
2188
+ e.preventDefault();
2189
+ last.focus();
2190
+ } else if (!e.shiftKey && active === last) {
2191
+ e.preventDefault();
2192
+ first.focus();
2193
+ }
2194
+ }
2195
+
2196
+ function onKey(e) {
2197
+ if (destroyed) return;
2198
+ const mod = e.ctrlKey || e.metaKey;
2199
+ if (e.key === 'Escape') {
2200
+ e.preventDefault();
2201
+ if (!pop.hidden) closePop();
2202
+ else cancel();
2203
+ } else if (mod && (e.key === 'z' || e.key === 'Z')) {
2204
+ e.preventDefault();
2205
+ if (e.shiftKey) redo();
2206
+ else undo();
2207
+ } else if (mod && (e.key === 'y' || e.key === 'Y')) {
2208
+ e.preventDefault();
2209
+ redo();
2210
+ } else if (e.key === 'Enter' && !mod) {
2211
+ const target = e.target;
2212
+ if (target instanceof Element && target.closest('button,input,[role="slider"]') !== null) return;
2213
+ e.preventDefault();
2214
+ confirm();
2215
+ } else if (e.key === 'Tab') {
2216
+ trap(e);
2217
+ }
2218
+ // The editor is modal: nothing behind it reacts to keys.
2219
+ e.stopPropagation();
2220
+ }
2221
+ //#endregion
2222
+
2223
+ //#region export + finish
2224
+ function blobOf(canvas, type, quality) {
2225
+ return new Promise((resolve, reject) => {
2226
+ try {
2227
+ canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('export failed'))), type, quality);
2228
+ } catch (error) {
2229
+ reject(error);
2230
+ }
2231
+ });
2232
+ }
2233
+
2234
+ async function exportFile() {
2235
+ const out = document.createElement('canvas');
2236
+ out.width = W;
2237
+ out.height = H;
2238
+ const ctx = out.getContext('2d');
2239
+ ctx.drawImage(img, 0, 0, W, H);
2240
+ ctx.drawImage(ink, 0, 0);
2241
+ let blob = await blobOf(out, 'image/png');
2242
+ let ext = 'png';
2243
+ if (blob.size > EXPORT_MAX_BYTES) {
2244
+ const flat = document.createElement('canvas');
2245
+ flat.width = W;
2246
+ flat.height = H;
2247
+ const fctx = flat.getContext('2d');
2248
+ fctx.fillStyle = '#fff';
2249
+ fctx.fillRect(0, 0, W, H);
2250
+ fctx.drawImage(out, 0, 0);
2251
+ blob = await blobOf(flat, 'image/jpeg', 0.9);
2252
+ ext = 'jpg';
2253
+ flat.width = 0;
2254
+ flat.height = 0;
2255
+ }
2256
+ out.width = 0;
2257
+ out.height = 0;
2258
+ const name = stemOf(item.src) + '-annotated.' + ext;
2259
+ try {
2260
+ return new File([blob], name, { type: blob.type, lastModified: Date.now() });
2261
+ } catch {
2262
+ blob.name = name;
2263
+ return blob;
2264
+ }
2265
+ }
2266
+
2267
+ async function confirm() {
2268
+ if (!ready || busy || destroyed) return;
2269
+ busy = true;
2270
+ root.setAttribute('data-busy', '');
2271
+ doneBtn.disabled = true;
2272
+ let file;
2273
+ try {
2274
+ file = await exportFile();
2275
+ } catch (error) {
2276
+ busy = false;
2277
+ root.removeAttribute('data-busy');
2278
+ doneBtn.disabled = false;
2279
+ toast(error && error.name === 'SecurityError' ? t('edit.tainted') : t('edit.exportFailed'));
2280
+ return;
2281
+ }
2282
+ if (destroyed) return;
2283
+ const where = injectFile(file);
2284
+ if (where === 'composer') {
2285
+ toast(t('edit.injected'));
2286
+ } else {
2287
+ downloadFile(file);
2288
+ toast(t('edit.noComposer'));
2289
+ }
2290
+ destroy(false);
2291
+ hooks.done(where === 'composer');
2292
+ }
2293
+
2294
+ function cancel() {
2295
+ if (busy) return;
2296
+ destroy(true);
2297
+ hooks.cancel();
2298
+ }
2299
+
2300
+ function destroy(restore) {
2301
+ if (destroyed) return;
2302
+ destroyed = true;
2303
+ if (raf !== 0) cancelAnimationFrame(raf);
2304
+ window.removeEventListener('keydown', onKey, true);
2305
+ window.removeEventListener('resize', layout);
2306
+ for (const c of [ink, live]) {
2307
+ c.width = 0;
2308
+ c.height = 0;
2309
+ }
2310
+ root.remove();
2311
+ void restore;
2312
+ }
2313
+ //#endregion
2314
+
2315
+ //#region load
2316
+ async function load() {
2317
+ let loaded;
2318
+ try {
2319
+ loaded = await loadEditable(item.src);
2320
+ } catch {
2321
+ if (destroyed) return;
2322
+ status.textContent = t('failed');
2323
+ doneBtn.disabled = true;
2324
+ return;
2325
+ }
2326
+ if (destroyed) return;
2327
+ img = loaded.img;
2328
+ tainted = loaded.tainted;
2329
+ const nw = img.naturalWidth || img.width || item.w || 1024;
2330
+ const nh = img.naturalHeight || img.height || item.h || 768;
2331
+ const k = Math.min(1, EDIT_MAX_EDGE / Math.max(nw, nh), Math.sqrt(EDIT_MAX_PIXELS / (nw * nh)));
2332
+ W = Math.max(1, Math.round(nw * k));
2333
+ H = Math.max(1, Math.round(nh * k));
2334
+ for (const c of [ink, live]) {
2335
+ c.width = W;
2336
+ c.height = H;
2337
+ }
2338
+ inkCtx = ink.getContext('2d');
2339
+ liveCtx = live.getContext('2d');
2340
+ img.className = 'qie-base';
2341
+ img.alt = item.alt || '';
2342
+ img.draggable = false;
2343
+ base.replaceWith(img);
2344
+ base = img;
2345
+ status.hidden = true;
2346
+ note.hidden = !tainted;
2347
+ ready = true;
2348
+ root.setAttribute('data-ready', '');
2349
+ layout();
2350
+ }
2351
+ //#endregion
2352
+
2353
+ area.addEventListener('pointerdown', onDown);
2354
+ area.addEventListener('pointermove', onMove);
2355
+ area.addEventListener('pointerup', onUp);
2356
+ area.addEventListener('pointercancel', onUp);
2357
+ area.addEventListener('wheel', onWheel, { passive: false });
2358
+ root.addEventListener('dragstart', (e) => e.preventDefault());
2359
+ root.addEventListener('gesturestart', (e) => e.preventDefault());
2360
+ root.addEventListener('contextmenu', (e) => {
2361
+ if (area.contains(e.target)) e.preventDefault();
2362
+ });
2363
+ slider.addEventListener('pointerdown', onSizeDown);
2364
+ slider.addEventListener('pointermove', onSizeMove);
2365
+ slider.addEventListener('pointerup', onSizeUp);
2366
+ slider.addEventListener('pointercancel', onSizeUp);
2367
+ slider.addEventListener('keydown', onSizeKey);
2368
+ window.addEventListener('keydown', onKey, true);
2369
+ window.addEventListener('resize', layout);
2370
+ backBtn.addEventListener('click', cancel);
2371
+ undoBtn.addEventListener('click', undo);
2372
+ redoBtn.addEventListener('click', redo);
2373
+ penBtn.addEventListener('click', () => {
2374
+ closePop();
2375
+ setTool('pen');
2376
+ });
2377
+ eraseBtn.addEventListener('click', () => {
2378
+ closePop();
2379
+ setTool('erase');
2380
+ });
2381
+ shapeBtn.addEventListener('click', () => {
2382
+ if (tool === 'shape' && pop.hidden) {
2383
+ pop.hidden = false;
2384
+ shapeBtn.setAttribute('aria-expanded', 'true');
2385
+ } else if (!pop.hidden) {
2386
+ closePop();
2387
+ } else {
2388
+ setTool('shape');
2389
+ }
2390
+ });
2391
+ for (const [kind, b] of Object.entries(shapeButtons)) {
2392
+ b.addEventListener('click', () => {
2393
+ shape = kind;
2394
+ setTool('shape');
2395
+ closePop();
2396
+ });
2397
+ }
2398
+ for (const sw of swatches) sw.addEventListener('click', () => setColor(sw.dataset.color, false));
2399
+ customInput.addEventListener('input', () => {
2400
+ customColor = customInput.value;
2401
+ customWrap.style.setProperty('--qie-c', customColor);
2402
+ setColor(customColor, true);
2403
+ });
2404
+ customWrap.addEventListener('click', () => {
2405
+ if (customColor !== null) setColor(customColor, true);
2406
+ });
2407
+ doneBtn.addEventListener('click', confirm);
2408
+
2409
+ setTool('pen');
2410
+ setColor(color, false);
2411
+ syncHistory();
2412
+ document.body.appendChild(root);
2413
+ try {
2414
+ doneBtn.focus({ preventScroll: true });
2415
+ } catch {
2416
+ // focus is best-effort
2417
+ }
2418
+ load();
2419
+
2420
+ return {
2421
+ destroy: () => destroy(false),
2422
+ /** Test hooks: inspect strokes without reaching into closures. */
2423
+ get strokes() {
2424
+ return strokes.length;
2425
+ },
2426
+ };
2427
+ }
2428
+
2429
+ const EDIT_CSS = `
2430
+ [${EDIT_ATTR}]{position:fixed;inset:0;z-index:2147483001;display:flex;flex-direction:column;background:#000;color:#fff;font:13px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent;overscroll-behavior:contain;outline:none;--qie-ink:#ff3b30}
2431
+ [${EDIT_ATTR}] *{box-sizing:border-box}
2432
+ .qie-top{position:relative;flex:none;display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:8px;padding:calc(env(safe-area-inset-top,0px) + 10px) calc(env(safe-area-inset-right,0px) + 14px) 10px calc(env(safe-area-inset-left,0px) + 14px)}
2433
+ .qie-round,.qie-tool,.qie-shape{appearance:none;border:0;padding:0;color:inherit;display:grid;place-items:center;cursor:pointer;transition:background-color .15s,opacity .15s}
2434
+ .qie-round{width:44px;height:44px;border-radius:999px;background:rgba(255,255,255,.14)}
2435
+ .qie-round:hover{background:rgba(255,255,255,.24)}
2436
+ .qie-round[disabled]{opacity:.35;cursor:default}
2437
+ .qie-top>.qie-round{justify-self:start}
2438
+ .qie-history{justify-self:end;display:flex;gap:8px}
2439
+ .qie-tools{display:flex;gap:4px;padding:4px;border-radius:999px;background:rgba(255,255,255,.14)}
2440
+ .qie-tool{width:52px;height:40px;border-radius:999px;background:transparent}
2441
+ .qie-tool:hover{background:rgba(255,255,255,.12)}
2442
+ .qie-tool[aria-pressed=true]{background:rgba(255,255,255,.26)}
2443
+ .qie-tool svg,.qie-round svg{width:22px;height:22px}
2444
+ .qie-pop{position:absolute;top:100%;left:50%;transform:translateX(-50%);z-index:2;display:flex;gap:4px;padding:6px;border-radius:16px;background:rgba(40,40,42,.96);box-shadow:0 8px 28px rgba(0,0,0,.5)}
2445
+ .qie-pop[hidden]{display:none}
2446
+ .qie-shape{width:48px;height:44px;border-radius:12px;background:transparent}
2447
+ .qie-shape:hover{background:rgba(255,255,255,.12)}
2448
+ .qie-shape[aria-pressed=true]{background:rgba(255,255,255,.24)}
2449
+ .qie-area{position:relative;flex:1;min-height:0;overflow:hidden;touch-action:none;cursor:crosshair}
2450
+ [${EDIT_ATTR}][data-tool=erase] .qie-area{cursor:cell}
2451
+ .qie-stage{position:absolute;left:50%;top:50%;transform-origin:50% 50%;box-shadow:0 0 0 1px rgba(255,255,255,.08)}
2452
+ [${EDIT_ATTR}][data-settle] .qie-stage{transition:transform .24s cubic-bezier(.2,.8,.2,1)}
2453
+ .qie-stage>img,.qie-stage>canvas{position:absolute;inset:0;display:block;width:100%;height:100%;-webkit-user-drag:none;pointer-events:none}
2454
+ .qie-status{position:absolute;inset:0;display:grid;place-items:center;pointer-events:none;opacity:.85}
2455
+ .qie-status[hidden],.qie-note[hidden]{display:none}
2456
+ .qie-note{position:absolute;left:50%;top:10px;transform:translateX(-50%);max-width:calc(100% - 32px);padding:6px 12px;border-radius:999px;background:rgba(255,255,255,.16);font-size:12px;text-align:center;pointer-events:none}
2457
+ .qie-size{position:fixed;left:calc(env(safe-area-inset-left,0px) + 8px);top:50%;transform:translateY(-50%);z-index:1;width:36px;height:min(38vh,260px);display:flex;justify-content:center;touch-action:none;cursor:ns-resize;outline:none}
2458
+ .qie-rail{position:relative;width:4px;height:100%;border-radius:2px;background:rgba(255,255,255,.35)}
2459
+ .qie-knob{position:absolute;left:50%;top:calc((1 - var(--qie-k,0.3)) * 100%);width:26px;height:26px;margin:-13px 0 0 -13px;border-radius:50%;background:#fff;box-shadow:0 1px 6px rgba(0,0,0,.5)}
2460
+ .qie-size:focus-visible .qie-knob{outline:2px solid #fff;outline-offset:3px}
2461
+ .qie-preview{position:absolute;left:52px;top:50%;transform:translateY(-50%);border-radius:50%;background:var(--qie-ink);box-shadow:0 0 0 2px rgba(255,255,255,.7);opacity:0;transition:opacity .15s;pointer-events:none}
2462
+ .qie-size[data-active] .qie-preview{opacity:1}
2463
+ .qie-bottom{flex:none;display:flex;align-items:center;gap:12px;padding:10px calc(env(safe-area-inset-right,0px) + 14px) calc(env(safe-area-inset-bottom,0px) + 12px) calc(env(safe-area-inset-left,0px) + 14px)}
2464
+ .qie-palette{flex:1;min-width:0;display:flex;align-items:center;gap:10px;overflow-x:auto;scrollbar-width:none;padding:6px 4px}
2465
+ .qie-palette::-webkit-scrollbar{display:none}
2466
+ .qie-swatch{appearance:none;position:relative;flex:none;width:32px;height:32px;padding:0;border:0;border-radius:50%;background:var(--qie-c);box-shadow:inset 0 0 0 1px rgba(255,255,255,.25);cursor:pointer}
2467
+ .qie-swatch[aria-checked=true],.qie-custom[data-checked]{box-shadow:0 0 0 2px #000,0 0 0 4px #0a84ff}
2468
+ .qie-custom{background:conic-gradient(#ff3b30,#ffcc00,#34c759,#5ac8fa,#007aff,#af52de,#ff3b30)}
2469
+ .qie-custom::after{content:"";position:absolute;inset:5px;border-radius:50%;background:var(--qie-c,#fff);box-shadow:0 0 0 2px #000}
2470
+ .qie-custom input{position:absolute;inset:0;width:100%;height:100%;opacity:0;border:0;padding:0;cursor:pointer}
2471
+ .qie-swatch:focus-visible,.qie-tool:focus-visible,.qie-round:focus-visible,.qie-shape:focus-visible,.qie-done:focus-visible{outline:2px solid #fff;outline-offset:2px}
2472
+ .qie-done{appearance:none;flex:none;width:52px;height:52px;padding:0;border:0;border-radius:50%;background:#0a84ff;color:#fff;display:grid;place-items:center;cursor:pointer}
2473
+ .qie-done svg{width:26px;height:26px}
2474
+ .qie-done[disabled]{opacity:.5;cursor:default}
2475
+ [${EDIT_ATTR}][data-busy] .qie-done svg{display:none}
2476
+ [${EDIT_ATTR}][data-busy] .qie-done::after{content:"";width:22px;height:22px;border-radius:50%;border:2.5px solid rgba(255,255,255,.35);border-top-color:#fff;animation:qiv-rot .8s linear infinite}
2477
+ .qiv-toast{position:fixed;left:50%;bottom:calc(env(safe-area-inset-bottom,0px) + 96px);z-index:2147483002;transform:translate(-50%,8px);max-width:calc(100vw - 32px);padding:10px 16px;border-radius:12px;background:rgba(30,30,32,.94);color:#fff;font:13px/1.45 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;box-shadow:0 8px 24px rgba(0,0,0,.35);opacity:0;transition:opacity .2s,transform .2s;pointer-events:none}
2478
+ .qiv-toast[data-show]{opacity:1;transform:translate(-50%,0)}
2479
+ @media (prefers-reduced-motion:reduce){[${EDIT_ATTR}][data-settle] .qie-stage,.qiv-toast{transition:none}}
2480
+ `;
2481
+ //#endregion
2482
+
2483
+ //#region click interception
2484
+ function installInterceptor(t) {
2485
+ let viewer = null;
2486
+ const onClick = (e) => {
2487
+ if (e.defaultPrevented || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;
2488
+ const trigger = resolveTrigger(e.target);
2489
+ if (trigger === null) return;
2490
+ const { items, index } = collect(trigger);
2491
+ if (index < 0) return;
2492
+ e.preventDefault();
2493
+ e.stopPropagation();
2494
+ e.stopImmediatePropagation();
2495
+ if (viewer !== null) viewer.destroy();
2496
+ viewer = openViewer(items, index, t, () => {
2497
+ viewer = null;
2498
+ });
2499
+ };
2500
+ document.addEventListener('click', onClick, true);
2501
+ return () => {
2502
+ document.removeEventListener('click', onClick, true);
2503
+ if (viewer !== null) viewer.destroy();
2504
+ };
2505
+ }
2506
+ //#endregion
2507
+
2508
+ //#region apply
2509
+ const inject = ['locale'];
2510
+
2511
+ /**
2512
+ * Install styles and the capture-phase click interceptor.
2513
+ * @param ctx - client root context.
2514
+ */
2515
+ function apply(ctx) {
2516
+ let t = fallbackT;
2517
+ const locale = ctx.locale;
2518
+ if (locale && typeof locale.register === 'function') {
2519
+ ctx.effect(() => locale.register(NS, { zh, en }), 'image-viewer: dictionaries');
2520
+ if (typeof locale.bind === 'function') {
2521
+ const bound = locale.bind(NS);
2522
+ t = (key, params) => {
2523
+ let value;
2524
+ try {
2525
+ value = bound(key, params);
2526
+ } catch {
2527
+ value = undefined;
2528
+ }
2529
+ return typeof value === 'string' && value !== '' && value !== key && value !== NS + '.' + key
2530
+ ? value
2531
+ : fallbackT(key, params);
2532
+ };
2533
+ }
2534
+ }
2535
+ ctx.effect(() => installStyles(), 'image-viewer: styles');
2536
+ ctx.effect(() => installInterceptor(t), 'image-viewer: click interceptor');
2537
+ }
2538
+ //#endregion
2539
+
2540
+ return { inject, apply };
2541
+ },
2542
+ });