dsh-gallery 0.0.0-stage → 0.7.2

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/client.js ADDED
@@ -0,0 +1,2817 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-gallery',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+
7
+ /** 与 Host 半部一致的路由(exact Fetch 路由的 path)。 */
8
+ const ROUTE = '/api/dsh-gallery'
9
+ /** tab 类型的身份;也是正文与标题在 keyed slot 里的 key。 */
10
+ const KIND = 'gallery'
11
+ const ID = 'dsh-gallery'
12
+ /** 缩略图最长边(像素)——客户端压缩目标。 */
13
+ const THUMB_SIZE = 200
14
+ /** 放大视图最长边;仍然是 canvas 缩放结果,不把原图直接塞进 <img>。 */
15
+ const VIEW_SIZE = 1600
16
+ /** 单图请求超时,避免一张卡死的图拖住整面板。 */
17
+ const RAW_TIMEOUT_MS = 15000
18
+ /** 同一时刻最多几个缩略图在解码,避免一次性拉扯大量原图。 */
19
+ const MAX_CONCURRENT = 4
20
+
21
+ /** 查看器缩放上限与单次滚轮步进。 */
22
+ const MAX_ZOOM = 8
23
+ const ZOOM_STEP = 0.35
24
+
25
+ /** 自动刷新间隔(毫秒):产出落盘后无需手动点刷新。 */
26
+ const AUTO_REFRESH_MS = 5000
27
+
28
+ /** 文本预览最大字符数:超出截断,避免超大日志卡死面板。 */
29
+ const MAX_TEXT_CHARS = 200000
30
+
31
+ const NS = 'dshGallery'
32
+
33
+ /** 插件自己的 context;侧栏入口按钮需要它来开 tab。 */
34
+ const ctxRef = { current: null }
35
+
36
+ const zh = {
37
+ 'type.label': '产出画廊',
38
+ 'guide.title': '产出画廊',
39
+ 'guide.description': '最近 24 小时的产出图片',
40
+ loading: '正在扫描…',
41
+ refreshing: '刷新中…',
42
+ refresh: '刷新',
43
+ preview: '预览',
44
+ previewInSidebar: '在 DSH 右侧栏预览该文件',
45
+ copy: '复制路径',
46
+ copyPath: '复制该文件的绝对路径',
47
+ copied: '已复制',
48
+ openFolder: '打开所在文件夹',
49
+ kindImage: '图片',
50
+ kindFile: '文件',
51
+ scopeGlobal: '全局资产',
52
+ scopeSession: '当前对话',
53
+ scopeGlobalHint: 'G 盘全部产出,按产出时间倒序',
54
+ scopeSessionHint: '仅本对话产出过的文件',
55
+ scopeUnknown: '未记录本对话产出',
56
+ scopeNotFound: '找不到本对话的会话记录',
57
+ scopeLogEmpty: '本对话的会话记录为空',
58
+ subCount: '{shown} / {total} 条',
59
+ // 设置面板
60
+ settingsTitle: '设置产出根目录',
61
+ rootLabel: '产出根目录',
62
+ rootsLabel: '扫描目录({count} 个)',
63
+ rootAddPlaceholder: '输入要新增的目录绝对路径,如 D:\\输出',
64
+ addRoot: '添加目录',
65
+ addingRoot: '添加中…',
66
+ removeRootHint: '从扫描列表移除(不会删除文件)',
67
+ rootsTip: '可加多个目录:DSH 每个会话有独立工作目录,产出不一定落在同一个目录下。',
68
+ done: '完成',
69
+ resetDefaultHint: '改为自动探测到的默认目录(会替换整个列表)',
70
+ rootHint: '当前来源:{source}',
71
+ rootExists: '✓ 目录存在',
72
+ rootMissingShort: '✗ 目录不存在,请修改',
73
+ settingsFileAt: '设置保存在:{path}',
74
+ rootSourceSettings: '面板内设置(优先级最高)',
75
+ rootSourceConfig: 'cordis.patch.yml 配置',
76
+ rootSourceAuto: '自动探测',
77
+ save: '保存并生效',
78
+ saving: '保存中…',
79
+ resetDefault: '恢复默认',
80
+ cancel: '取消',
81
+ savedImmediately: '✓ 已保存,立即生效(无需重启)',
82
+ binaryHint: '该格式不支持内联预览,请用文件管理器打开',
83
+ empty: '最近 24 小时没有新图片',
84
+ emptyFile: '最近 24 小时没有新文件',
85
+ emptySession: '本对话还没产出过文件',
86
+ errorTitle: '扫描失败',
87
+ retry: '重试',
88
+ rootMissing: '目录不存在:{root}',
89
+ changeRoot: '修改产出根目录',
90
+ rootEmptyHint: '当前目录下没有符合条件的产出,可换个目录或在设置里调整',
91
+ dgStatusAction: '',
92
+ more: '还有 {count} 张',
93
+ dragHint: '拖动右侧滑块或直接拖图平移',
94
+ panUpHint: '向上移动图片',
95
+ panDownHint: '向下移动图片',
96
+ trackHint: '点击此位置跳转',
97
+ zoomInHint: '放大(也可按 +)',
98
+ zoomOutHint: '缩小(也可按 -)',
99
+ zoomResetHint: '恢复原始大小(也可按 0)',
100
+ // 右键菜单
101
+ ctxHint: '右键更多操作',
102
+ ctxHide: '隐藏(不再列出)',
103
+ ctxUnhide: '取消隐藏',
104
+ ctxReveal: '打开所在文件夹',
105
+ ctxCopy: '复制路径',
106
+ ctxDelete: '删除文件',
107
+ ctxDeleteConfirm: '确认删除?此操作不可恢复',
108
+ ctxDeleteYes: '确认删除',
109
+ ctxDeleteNo: '取消',
110
+ ctxHiddenDone: '已隐藏,可在设置里恢复',
111
+ ctxDeleting: '删除中…',
112
+ ctxDeleteFailed: '删除失败',
113
+ // 已隐藏管理
114
+ hiddenCount: '已隐藏 {count} 个',
115
+ hiddenClear: '全部恢复',
116
+ hiddenClearing: '恢复中…',
117
+ hiddenClearHint: '让所有被隐藏的文件重新出现在列表里(不会删除文件)',
118
+ hiddenCleared: '已全部恢复',
119
+ hiddenMore: '还有 {count} 个未显示',
120
+ pagerRange: '第 {start}–{end} 条 · 共 {total} 条',
121
+ pageTip: '跳到第 {page} 页',
122
+ thumbFailed: '无法加载',
123
+ dims: '{w} × {h}',
124
+ dimsUnknown: '尺寸未知',
125
+ close: '关闭',
126
+ prev: '上一张',
127
+ next: '下一张',
128
+ zoomed: '放大查看',
129
+ meta: '{size} · {time}',
130
+ scanned: '已扫描 {dirs} 个目录',
131
+ capped: '已达扫描上限,结果可能不完整',
132
+ }
133
+
134
+ const en = {
135
+ 'type.label': 'Output Gallery',
136
+ 'guide.title': 'Output Gallery',
137
+ 'guide.description': 'Images from the last 24 hours',
138
+ loading: 'Scanning…',
139
+ refreshing: 'Refreshing…',
140
+ refresh: 'Refresh',
141
+ preview: 'Preview',
142
+ previewInSidebar: 'Preview this file in the DSH sidebar',
143
+ copy: 'Copy path',
144
+ copyPath: 'Copy the absolute path of this file',
145
+ copied: 'Copied',
146
+ openFolder: 'Open containing folder',
147
+ kindImage: 'Images',
148
+ kindFile: 'Files',
149
+ scopeGlobal: 'All assets',
150
+ scopeSession: 'This chat',
151
+ scopeGlobalHint: 'Every output on the G drive, newest first',
152
+ scopeSessionHint: 'Only files produced in this chat',
153
+ scopeUnknown: 'No outputs recorded for this chat',
154
+ scopeNotFound: 'Cannot find this chat’s session log',
155
+ scopeLogEmpty: 'This chat’s session log is empty',
156
+ subCount: '{shown} of {total}',
157
+ // Settings panel
158
+ settingsTitle: 'Output root folder',
159
+ rootLabel: 'Output root',
160
+ rootsLabel: 'Scan folders ({count})',
161
+ rootAddPlaceholder: 'Absolute path to add, e.g. D:\\outputs',
162
+ addRoot: 'Add folder',
163
+ addingRoot: 'Adding…',
164
+ removeRootHint: 'Remove from scan list (files are not deleted)',
165
+ rootsTip: 'Multiple folders allowed: each DSH session has its own working directory, so outputs may land outside one root.',
166
+ done: 'Done',
167
+ resetDefaultHint: 'Switch to the auto-detected default folder (replaces the whole list)',
168
+ rootHint: 'Current source: {source}',
169
+ rootExists: '✓ Folder exists',
170
+ rootMissingShort: '✗ Folder missing, please change it',
171
+ settingsFileAt: 'Saved in: {path}',
172
+ rootSourceSettings: 'Set in panel (highest priority)',
173
+ rootSourceConfig: 'cordis.patch.yml',
174
+ rootSourceAuto: 'Auto-detected',
175
+ save: 'Save and apply',
176
+ saving: 'Saving…',
177
+ resetDefault: 'Reset to default',
178
+ cancel: 'Cancel',
179
+ savedImmediately: '✓ Saved and applied immediately (no restart needed)',
180
+ binaryHint: 'This format cannot be previewed inline; open it in your file manager',
181
+ empty: 'No new images in the last 24 hours',
182
+ emptyFile: 'No new files in the last 24 hours',
183
+ emptySession: 'Nothing has been produced in this chat yet',
184
+ errorTitle: 'Scan failed',
185
+ retry: 'Retry',
186
+ rootMissing: 'Folder not found: {root}',
187
+ changeRoot: 'Change output root',
188
+ rootEmptyHint: 'Nothing matches in this folder. Pick another folder or adjust settings.',
189
+ dgStatusAction: '',
190
+ more: '{count} more',
191
+ dragHint: 'Drag the scrollbar on the right, or drag the image',
192
+ panUpHint: 'Move image up',
193
+ panDownHint: 'Move image down',
194
+ trackHint: 'Click here to jump',
195
+ zoomInHint: 'Zoom in (or press +)',
196
+ zoomOutHint: 'Zoom out (or press -)',
197
+ zoomResetHint: 'Reset zoom (or press 0)',
198
+ ctxHint: 'Right-click for more',
199
+ ctxHide: 'Hide (stop listing)',
200
+ ctxUnhide: 'Unhide',
201
+ ctxReveal: 'Open containing folder',
202
+ ctxCopy: 'Copy path',
203
+ ctxDelete: 'Delete file',
204
+ ctxDeleteConfirm: 'Delete permanently? This cannot be undone',
205
+ ctxDeleteYes: 'Delete',
206
+ ctxDeleteNo: 'Cancel',
207
+ ctxHiddenDone: 'Hidden. Restore it in settings later.',
208
+ ctxDeleting: 'Deleting…',
209
+ ctxDeleteFailed: 'Delete failed',
210
+ hiddenCount: '{count} hidden',
211
+ hiddenClear: 'Restore all',
212
+ hiddenClearing: 'Restoring…',
213
+ hiddenClearHint: 'Show all hidden files again (files are not deleted)',
214
+ hiddenCleared: 'All restored',
215
+ hiddenMore: '{count} more not shown',
216
+ pagerRange: '{start}–{end} of {total}',
217
+ pageTip: 'Go to page {page}',
218
+ thumbFailed: 'Cannot load',
219
+ dims: '{w} × {h}',
220
+ dimsUnknown: 'Size unknown',
221
+ close: 'Close',
222
+ prev: 'Previous',
223
+ next: 'Next',
224
+ zoomed: 'Enlarged view',
225
+ meta: '{size} · {time}',
226
+ scanned: 'Scanned {dirs} folders',
227
+ capped: 'Scan limit reached; results may be incomplete',
228
+ }
229
+
230
+ /** 极简模板替换:字典里只有 {name} 占位。 */
231
+ function format(template, values) {
232
+ return String(template).replace(/\{(\w+)\}/g, (whole, key) => {
233
+ const value = values?.[key]
234
+ return value === undefined ? whole : String(value)
235
+ })
236
+ }
237
+
238
+ function formatBytes(bytes) {
239
+ if (!Number.isFinite(bytes) || bytes <= 0) return '—'
240
+ if (bytes < 1024) return `${bytes} B`
241
+ const kb = bytes / 1024
242
+ if (kb < 1024) return `${kb < 10 ? kb.toFixed(1) : Math.round(kb)} KB`
243
+ const mb = kb / 1024
244
+ return `${mb < 10 ? mb.toFixed(1) : Math.round(mb)} MB`
245
+ }
246
+
247
+ function formatTime(ms) {
248
+ if (!Number.isFinite(ms)) return '—'
249
+ const date = new Date(ms)
250
+ const pad = (n) => String(n).padStart(2, '0')
251
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
252
+ }
253
+
254
+ /** POST 到 Host 私有路由,统一把失败转成可展示的错误。 */
255
+ async function callHost(op, payload, signal) {
256
+ const response = await fetch(ROUTE, {
257
+ method: 'POST',
258
+ credentials: 'same-origin',
259
+ headers: { 'content-type': 'application/json' },
260
+ body: JSON.stringify({ op, ...(payload ?? {}) }),
261
+ signal,
262
+ })
263
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
264
+ return response.json()
265
+ }
266
+
267
+ /** 拉取一张原图的 Blob;超时即放弃,让调用方显示占位符。 */
268
+ async function fetchRaw(relPath, signal) {
269
+ const timeout = new AbortController()
270
+ const timer = setTimeout(() => timeout.abort(), RAW_TIMEOUT_MS)
271
+ const merged = typeof AbortSignal.any === 'function' ? AbortSignal.any([signal, timeout.signal]) : timeout.signal
272
+ try {
273
+ const response = await fetch(ROUTE, {
274
+ method: 'POST',
275
+ credentials: 'same-origin',
276
+ headers: { 'content-type': 'application/json' },
277
+ body: JSON.stringify({ op: 'raw', path: relPath }),
278
+ signal: merged,
279
+ })
280
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
281
+ return await response.blob()
282
+ } finally {
283
+ clearTimeout(timer)
284
+ }
285
+ }
286
+
287
+ /**
288
+ * 把原图按最长边 maxEdge 压成 JPEG data URL 或 object URL。
289
+ * 选项 `preferObjectUrl` 为 true 时返回 Blob URL(缩略图用),否则返回 data URL。
290
+ * 用 createImageBitmap + OffscreenCanvas;不可用时不阻断,抛错由调用方显示占位符。
291
+ */
292
+ async function makeScaled(blob, maxEdge, preferObjectUrl) {
293
+ const bitmap = await createImageBitmap(blob)
294
+ try {
295
+ const scale = Math.min(1, maxEdge / Math.max(bitmap.width, bitmap.height))
296
+ const width = Math.max(1, Math.round(bitmap.width * scale))
297
+ const height = Math.max(1, Math.round(bitmap.height * scale))
298
+
299
+ let canvas
300
+ if (typeof OffscreenCanvas === 'function') {
301
+ canvas = new OffscreenCanvas(width, height)
302
+ } else {
303
+ canvas = document.createElement('canvas')
304
+ canvas.width = width
305
+ canvas.height = height
306
+ }
307
+ const context = canvas.getContext('2d')
308
+ if (context === null) throw new Error('canvas 2d context unavailable')
309
+ context.imageSmoothingEnabled = true
310
+ context.imageSmoothingQuality = 'high'
311
+ context.drawImage(bitmap, 0, 0, width, height)
312
+
313
+ const quality = preferObjectUrl ? 0.82 : 0.9
314
+ if (typeof canvas.convertToBlob === 'function') {
315
+ const out = await canvas.convertToBlob({ type: 'image/jpeg', quality })
316
+ return {
317
+ url: preferObjectUrl ? URL.createObjectURL(out) : null,
318
+ blob: preferObjectUrl ? null : out,
319
+ dataUrl: preferObjectUrl ? null : await toDataUrl(out),
320
+ width: bitmap.width,
321
+ height: bitmap.height,
322
+ }
323
+ }
324
+ const dataUrl = canvas.toDataURL('image/jpeg', quality)
325
+ return { url: null, blob: null, dataUrl, width: bitmap.width, height: bitmap.height }
326
+ } finally {
327
+ if (typeof bitmap.close === 'function') bitmap.close()
328
+ }
329
+ }
330
+
331
+ /** Blob → data URL(仅给放大视图用,避免额外 object URL 生命周期)。 */
332
+ function toDataUrl(blob) {
333
+ return new Promise((resolve, reject) => {
334
+ const reader = new FileReader()
335
+ reader.onload = () => resolve(String(reader.result))
336
+ reader.onerror = () => reject(new Error('read failed'))
337
+ reader.readAsDataURL(blob)
338
+ })
339
+ }
340
+
341
+
342
+ /** 全局并发闸门:缩略图同一时刻只解压这么多个。 */
343
+ function createLimiter(max) {
344
+ let active = 0
345
+ const waiting = []
346
+ const release = () => {
347
+ active -= 1
348
+ const next = waiting.shift()
349
+ if (next !== undefined) next()
350
+ }
351
+ return async function run(task) {
352
+ if (active >= max) await new Promise((resolve) => waiting.push(resolve))
353
+ active += 1
354
+ try {
355
+ return await task()
356
+ } finally {
357
+ release()
358
+ }
359
+ }
360
+ }
361
+
362
+ /** 面板内的样式:只用宿主 theme token,深色/浅色自动跟随。 */
363
+ const CSS = `
364
+ .dg-root {
365
+ display: flex;
366
+ flex-direction: column;
367
+ height: 100%;
368
+ min-height: 0;
369
+ color: var(--dsw-alias-label-primary);
370
+ background: var(--dsw-alias-bg-base);
371
+ font-size: 13px;
372
+ position: relative;
373
+ }
374
+ .dg-header {
375
+ display: flex;
376
+ align-items: center;
377
+ gap: 8px;
378
+ padding: 8px 10px;
379
+ border-bottom: 1px solid var(--dsw-alias-border-l1);
380
+ background: var(--dsw-alias-bg-layer-1);
381
+ flex: 0 0 auto;
382
+ flex-wrap: wrap;
383
+ }
384
+ .dg-headerInfo { flex: 1 1 96px; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
385
+ .dg-switch { flex: 0 0 auto; display: inline-flex; border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px; overflow: hidden; }
386
+ .dg-seg { appearance: none; border: 0; background: transparent; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 11px; padding: 4px 9px; cursor: pointer; }
387
+ .dg-seg:hover { background: var(--dsw-alias-interactive-bg-hover); }
388
+ .dg-segActive { background: var(--dsw-alias-interactive-bg-selected); color: var(--dsw-alias-label-primary); font-weight: 600; }
389
+ /* 分类开关:全局资产 / 当前对话 */
390
+ .dg-scopeSwitch {
391
+ flex: 0 0 auto;
392
+ display: inline-flex;
393
+ gap: 2px;
394
+ padding: 2px;
395
+ border: 1px solid var(--dsw-alias-border-l1);
396
+ border-radius: 7px;
397
+ background: var(--dsw-alias-bg-layer-2);
398
+ }
399
+ .dg-scopeBtn {
400
+ appearance: none;
401
+ border: 0;
402
+ background: transparent;
403
+ color: var(--dsw-alias-label-secondary);
404
+ font: inherit;
405
+ font-size: 11px;
406
+ line-height: 1;
407
+ padding: 5px 10px;
408
+ border-radius: 5px;
409
+ cursor: pointer;
410
+ white-space: nowrap;
411
+ transition: color .15s ease, background .15s ease;
412
+ }
413
+ .dg-scopeBtn:hover { color: var(--dsw-alias-label-primary); background: var(--dsw-alias-interactive-bg-hover); }
414
+ .dg-scopeActive {
415
+ color: var(--dsw-alias-label-primary);
416
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 16%, transparent);
417
+ box-shadow: inset 0 0 0 1px var(--dsw-alias-brand-primary);
418
+ font-weight: 600;
419
+ }
420
+ .dg-scopeActive:hover {
421
+ color: var(--dsw-alias-label-primary);
422
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 24%, transparent);
423
+ }
424
+ .dg-scopeBtn:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
425
+ .dg-title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
426
+ .dg-sub { color: var(--dsw-alias-label-secondary); font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
427
+ .dg-btn {
428
+ appearance: none;
429
+ border: 1px solid var(--dsw-alias-border-l1);
430
+ background: var(--dsw-alias-bg-layer-2);
431
+ color: var(--dsw-alias-label-primary);
432
+ border-radius: 6px;
433
+ padding: 4px 10px;
434
+ font-size: 12px;
435
+ line-height: 18px;
436
+ cursor: pointer;
437
+ flex: 0 0 auto;
438
+ }
439
+ .dg-btn:hover:not(:disabled) { border-color: var(--dsw-alias-border-l2); }
440
+ .dg-btn:disabled { opacity: .55; cursor: default; }
441
+ .dg-btn:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
442
+ .dg-btnIcon { min-width: 30px; padding: 4px 8px; font-size: 14px; line-height: 18px; }
443
+
444
+ /* ===== 设置面板 ===== */
445
+ .dg-settingsLayer {
446
+ position: absolute; inset: 0; z-index: 40;
447
+ display: flex; align-items: center; justify-content: center;
448
+ padding: 16px;
449
+ background: color-mix(in srgb, var(--dsw-alias-bg-overlay) 72%, transparent);
450
+ }
451
+ .dg-settings {
452
+ width: 100%; max-width: 460px; max-height: 100%;
453
+ display: flex; flex-direction: column;
454
+ background: var(--dsw-alias-bg-layer-1);
455
+ border: 1px solid var(--dsw-alias-border-l2);
456
+ border-radius: 10px;
457
+ box-shadow: 0 8px 32px rgba(0,0,0,.22);
458
+ overflow: hidden;
459
+ }
460
+ .dg-settingsHead {
461
+ display: flex; align-items: center; gap: 8px;
462
+ padding: 10px 12px;
463
+ border-bottom: 1px solid var(--dsw-alias-border-l1);
464
+ background: var(--dsw-alias-bg-layer-2);
465
+ }
466
+ .dg-settingsTitle { flex: 1 1 auto; font-size: 13px; font-weight: 600; }
467
+ .dg-settingsBody { padding: 12px; display: flex; flex-direction: column; gap: 10px; overflow: auto; }
468
+ .dg-field { display: flex; flex-direction: column; gap: 6px; }
469
+ .dg-fieldHead { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; }
470
+ .dg-fieldLabel { font-size: 12px; font-weight: 600; }
471
+ .dg-fieldHint { font-size: 11px; color: var(--dsw-alias-label-secondary); line-height: 1.5; }
472
+
473
+ /* ===== 多扫描目录列表 ===== */
474
+ .dg-rootsList {
475
+ margin: 0;
476
+ padding: 0;
477
+ list-style: none;
478
+ display: flex;
479
+ flex-direction: column;
480
+ gap: 4px;
481
+ max-height: 168px;
482
+ overflow: auto;
483
+ }
484
+ .dg-rootItem {
485
+ display: flex;
486
+ align-items: center;
487
+ gap: 7px;
488
+ padding: 6px 8px;
489
+ font-size: 12px;
490
+ background: var(--dsw-alias-bg-base);
491
+ border: 1px solid var(--dsw-alias-border-l1);
492
+ border-radius: 6px;
493
+ }
494
+ .dg-rootItemMissing {
495
+ border-color: var(--dsw-alias-state-error-primary);
496
+ background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 8%, transparent);
497
+ }
498
+ .dg-rootOk { flex: 0 0 auto; font-size: 12px; color: var(--dsw-alias-brand-primary); }
499
+ .dg-rootItemMissing .dg-rootOk { color: var(--dsw-alias-state-error-primary); }
500
+ .dg-rootPath {
501
+ flex: 1 1 auto;
502
+ min-width: 0;
503
+ overflow: hidden;
504
+ text-overflow: ellipsis;
505
+ white-space: nowrap;
506
+ color: var(--dsw-alias-label-primary);
507
+ }
508
+ .dg-rootRemove {
509
+ flex: 0 0 auto;
510
+ width: 20px;
511
+ height: 20px;
512
+ padding: 0;
513
+ display: inline-flex;
514
+ align-items: center;
515
+ justify-content: center;
516
+ font-size: 12px;
517
+ line-height: 1;
518
+ color: var(--dsw-alias-label-secondary);
519
+ background: transparent;
520
+ border: 1px solid transparent;
521
+ border-radius: 4px;
522
+ cursor: pointer;
523
+ }
524
+ .dg-rootRemove:hover:not(:disabled) {
525
+ color: var(--dsw-alias-state-error-primary);
526
+ border-color: var(--dsw-alias-state-error-primary);
527
+ }
528
+ .dg-rootRemove:disabled { opacity: .4; cursor: default; }
529
+ .dg-rootAdd { display: flex; gap: 6px; align-items: center; }
530
+ .dg-rootInput { flex: 1 1 auto; min-width: 0; }
531
+ .dg-input {
532
+ width: 100%; box-sizing: border-box;
533
+ padding: 7px 10px;
534
+ font: inherit; font-size: 12px;
535
+ color: var(--dsw-alias-label-primary);
536
+ background: var(--dsw-alias-bg-base);
537
+ border: 1px solid var(--dsw-alias-border-l1);
538
+ border-radius: 6px;
539
+ }
540
+ .dg-input:focus {
541
+ outline: none;
542
+ border-color: var(--dsw-alias-brand-primary);
543
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--dsw-alias-brand-primary) 22%, transparent);
544
+ }
545
+ .dg-settingsMeta {
546
+ display: flex; flex-direction: column; gap: 3px;
547
+ font-size: 11px; color: var(--dsw-alias-label-secondary);
548
+ word-break: break-all;
549
+ }
550
+ .dg-settingsActions { display: flex; gap: 8px; flex-wrap: wrap; padding-top: 2px; }
551
+
552
+ /* ===== 已隐藏管理区块 ===== */
553
+ .dg-hiddenBox {
554
+ display: flex;
555
+ flex-direction: column;
556
+ gap: 6px;
557
+ padding: 9px 10px;
558
+ background: var(--dsw-alias-bg-layer-2);
559
+ border: 1px solid var(--dsw-alias-border-l1);
560
+ border-radius: 8px;
561
+ }
562
+ .dg-hiddenRow {
563
+ display: flex;
564
+ align-items: center;
565
+ gap: 8px;
566
+ flex-wrap: wrap;
567
+ }
568
+ .dg-hiddenLabel {
569
+ flex: 1 1 auto;
570
+ min-width: 0;
571
+ font-size: 12px;
572
+ font-weight: 600;
573
+ color: var(--dsw-alias-label-primary);
574
+ }
575
+ .dg-hiddenList {
576
+ margin: 0;
577
+ padding: 0 0 0 14px;
578
+ list-style: disc;
579
+ display: flex;
580
+ flex-direction: column;
581
+ gap: 2px;
582
+ max-height: 96px;
583
+ overflow: auto;
584
+ }
585
+ .dg-hiddenItem {
586
+ font-size: 11px;
587
+ color: var(--dsw-alias-label-secondary);
588
+ white-space: nowrap;
589
+ overflow: hidden;
590
+ text-overflow: ellipsis;
591
+ }
592
+ .dg-hiddenMore { font-size: 11px; color: var(--dsw-alias-label-secondary); padding-left: 2px; }
593
+ .dg-primaryBtn {
594
+ color: var(--dsw-alias-label-primary);
595
+ border-color: var(--dsw-alias-brand-primary);
596
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 12%, transparent);
597
+ }
598
+ .dg-primaryBtn:hover:not(:disabled) {
599
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 20%, transparent);
600
+ }
601
+ .dg-ok { color: var(--dsw-alias-brand-primary); }
602
+ .dg-statusAction { padding-top: 0; }
603
+ .dg-body { flex: 1 1 auto; min-height: 0; overflow: auto; padding: 10px; }
604
+ /* 网格区外层:定位容器,右侧挂滚动辅助列(无滚轮场景) */
605
+ .dg-bodyWrap {
606
+ flex: 1 1 auto;
607
+ min-height: 0;
608
+ position: relative;
609
+ display: flex;
610
+ overflow: hidden;
611
+ }
612
+ .dg-bodyWrap > .dg-body {
613
+ flex: 1 1 auto;
614
+ min-width: 0;
615
+ /* 右侧留出 38px 给辅助列,避免滑块压住卡片 */
616
+ padding-right: 42px;
617
+ }
618
+ .dg-status { color: var(--dsw-alias-label-secondary); padding: 16px 4px; text-align: center; }
619
+ .dg-error { color: var(--dsw-alias-state-error-primary); }
620
+ .dg-grid {
621
+ display: grid;
622
+ grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));
623
+ gap: 10px;
624
+ }
625
+ .dg-card {
626
+ display: flex;
627
+ flex-direction: column;
628
+ gap: 0;
629
+ border: 1px solid var(--dsw-alias-border-l1);
630
+ border-radius: 8px;
631
+ overflow: hidden;
632
+ background: var(--dsw-alias-bg-layer-1);
633
+ padding: 0;
634
+ cursor: zoom-in;
635
+ appearance: none;
636
+ text-align: left;
637
+ color: inherit;
638
+ font: inherit;
639
+ }
640
+ .dg-card:hover { border-color: var(--dsw-alias-border-l2); }
641
+ .dg-card:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
642
+ .dg-thumb {
643
+ display: flex;
644
+ align-items: center;
645
+ justify-content: center;
646
+ aspect-ratio: 1 / 1;
647
+ background: var(--dsw-alias-bg-layer-2);
648
+ overflow: hidden;
649
+ }
650
+ .dg-thumb img { max-width: 100%; max-height: 100%; display: block; object-fit: contain; }
651
+ .dg-placeholder {
652
+ color: var(--dsw-alias-label-secondary);
653
+ font-size: 11px;
654
+ padding: 8px;
655
+ text-align: center;
656
+ line-height: 1.5;
657
+ }
658
+ .dg-placeholder code { color: var(--dsw-alias-label-primary); word-break: break-all; }
659
+ .dg-meta { padding: 6px 8px 8px; display: flex; flex-direction: column; gap: 2px; min-width: 0; }
660
+ .dg-name { font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
661
+ .dg-dim { font-size: 11px; color: var(--dsw-alias-label-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
662
+ .dg-more {
663
+ margin: 12px 0 4px;
664
+ padding: 8px 10px;
665
+ border-radius: 8px;
666
+ background: var(--dsw-alias-bg-layer-2);
667
+ border: 1px solid var(--dsw-alias-border-l1);
668
+ color: var(--dsw-alias-label-secondary);
669
+ text-align: center;
670
+ font-size: 12px;
671
+ }
672
+
673
+ /* ===== 分页条:常驻网格下方 ===== */
674
+ .dg-pager {
675
+ flex: 0 0 auto;
676
+ display: flex;
677
+ align-items: center;
678
+ flex-wrap: wrap;
679
+ gap: 8px 12px;
680
+ padding: 8px 12px;
681
+ border-top: 1px solid var(--dsw-alias-border-l1);
682
+ background: var(--dsw-alias-bg-layer-1);
683
+ }
684
+ .dg-pagerInfo {
685
+ font-size: 12px;
686
+ color: var(--dsw-alias-label-secondary);
687
+ white-space: nowrap;
688
+ }
689
+ .dg-pagerRemain {
690
+ font-size: 12px;
691
+ color: var(--dsw-alias-label-secondary);
692
+ white-space: nowrap;
693
+ }
694
+ .dg-pagerBtns {
695
+ margin-left: auto;
696
+ display: inline-flex;
697
+ align-items: center;
698
+ gap: 4px;
699
+ flex-wrap: wrap;
700
+ }
701
+ .dg-pageBtn {
702
+ appearance: none;
703
+ min-width: 28px;
704
+ height: 26px;
705
+ padding: 0 8px;
706
+ font: inherit;
707
+ font-size: 12px;
708
+ line-height: 1;
709
+ color: var(--dsw-alias-label-secondary);
710
+ background: var(--dsw-alias-bg-base);
711
+ border: 1px solid var(--dsw-alias-border-l1);
712
+ border-radius: 6px;
713
+ cursor: pointer;
714
+ transition: color .15s ease, border-color .15s ease, background .15s ease;
715
+ }
716
+ .dg-pageBtn:hover:not(:disabled) {
717
+ color: var(--dsw-alias-label-primary);
718
+ border-color: var(--dsw-alias-brand-primary);
719
+ background: var(--dsw-alias-interactive-bg-hover);
720
+ }
721
+ .dg-pageActive {
722
+ color: var(--dsw-alias-label-primary);
723
+ border-color: var(--dsw-alias-brand-primary);
724
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 14%, transparent);
725
+ font-weight: 600;
726
+ cursor: default;
727
+ }
728
+ .dg-pageActive:disabled { opacity: 1; }
729
+ .dg-pageGap {
730
+ padding: 0 2px;
731
+ font-size: 12px;
732
+ color: var(--dsw-alias-label-secondary);
733
+ }
734
+ .dg-pageBtn:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
735
+
736
+ /* ===== 右键菜单 ===== */
737
+ .dg-ctxLayer { position: fixed; inset: 0; z-index: 60; }
738
+ .dg-ctxMenu {
739
+ position: fixed;
740
+ min-width: 180px;
741
+ max-width: 260px;
742
+ padding: 6px;
743
+ background: var(--dsw-alias-bg-layer-1);
744
+ border: 1px solid var(--dsw-alias-border-l2);
745
+ border-radius: 8px;
746
+ box-shadow: 0 8px 28px rgba(0,0,0,.22);
747
+ display: flex;
748
+ flex-direction: column;
749
+ gap: 2px;
750
+ }
751
+ .dg-ctxHead {
752
+ padding: 5px 8px 7px;
753
+ font-size: 11px;
754
+ color: var(--dsw-alias-label-secondary);
755
+ white-space: nowrap;
756
+ overflow: hidden;
757
+ text-overflow: ellipsis;
758
+ border-bottom: 1px solid var(--dsw-alias-border-l1);
759
+ margin-bottom: 3px;
760
+ }
761
+ .dg-ctxItem {
762
+ appearance: none;
763
+ display: flex;
764
+ align-items: center;
765
+ gap: 8px;
766
+ width: 100%;
767
+ padding: 7px 9px;
768
+ text-align: left;
769
+ font: inherit;
770
+ font-size: 12px;
771
+ line-height: 1.3;
772
+ color: var(--dsw-alias-label-primary);
773
+ background: transparent;
774
+ border: 0;
775
+ border-radius: 6px;
776
+ cursor: pointer;
777
+ }
778
+ .dg-ctxItem:hover { background: var(--dsw-alias-interactive-bg-hover); }
779
+ .dg-ctxItem:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
780
+ .dg-ctxIco { flex: 0 0 auto; font-size: 13px; line-height: 1; opacity: .85; }
781
+ .dg-ctxDanger { color: var(--dsw-alias-state-error-primary); }
782
+ .dg-ctxDanger:hover { background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent); }
783
+
784
+ /* ===== 删除确认 ===== */
785
+ .dg-confirmLayer {
786
+ position: absolute; inset: 0; z-index: 70;
787
+ display: flex; align-items: center; justify-content: center;
788
+ padding: 16px;
789
+ background: color-mix(in srgb, var(--dsw-alias-bg-overlay) 72%, transparent);
790
+ }
791
+ .dg-confirm {
792
+ width: 100%; max-width: 340px;
793
+ padding: 14px;
794
+ background: var(--dsw-alias-bg-layer-1);
795
+ border: 1px solid var(--dsw-alias-border-l2);
796
+ border-radius: 10px;
797
+ box-shadow: 0 8px 32px rgba(0,0,0,.24);
798
+ display: flex; flex-direction: column; gap: 10px;
799
+ }
800
+ .dg-confirmTitle { font-size: 13px; font-weight: 600; color: var(--dsw-alias-label-primary); }
801
+ .dg-confirmName {
802
+ font-size: 12px;
803
+ color: var(--dsw-alias-label-secondary);
804
+ word-break: break-all;
805
+ padding: 7px 9px;
806
+ background: var(--dsw-alias-bg-layer-2);
807
+ border-radius: 6px;
808
+ }
809
+ .dg-confirmActions { display: flex; justify-content: flex-end; gap: 8px; }
810
+ .dg-dangerBtn {
811
+ color: #fff;
812
+ background: var(--dsw-alias-state-error-primary);
813
+ border-color: var(--dsw-alias-state-error-primary);
814
+ }
815
+ .dg-dangerBtn:hover:not(:disabled) {
816
+ background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 85%, #000 15%);
817
+ border-color: var(--dsw-alias-state-error-primary);
818
+ }
819
+
820
+ /* ===== 放大预览:舞台 + 右侧平移控制列 ===== */
821
+ .dg-viewerStage {
822
+ flex: 1 1 auto;
823
+ min-height: 0;
824
+ position: relative;
825
+ display: flex;
826
+ }
827
+ .dg-zoomBadge {
828
+ flex: 0 0 auto;
829
+ padding: 2px 7px;
830
+ font-size: 11px;
831
+ font-weight: 600;
832
+ color: var(--dsw-alias-brand-primary);
833
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 12%, transparent);
834
+ border: 1px solid var(--dsw-alias-brand-primary);
835
+ border-radius: 5px;
836
+ line-height: 1.4;
837
+ }
838
+ .dg-zoomCtl { display: inline-flex; align-items: center; gap: 2px; flex: 0 0 auto; }
839
+ .dg-btnTiny {
840
+ min-width: 26px;
841
+ padding: 2px 6px;
842
+ font-size: 12px;
843
+ line-height: 16px;
844
+ }
845
+
846
+ /* 右侧竖列:▲ 按钮、轨道、▼ 按钮(放大页与列表页共用) */
847
+ .dg-panRail {
848
+ position: absolute;
849
+ top: 8px;
850
+ right: 4px;
851
+ bottom: 8px;
852
+ width: 30px;
853
+ display: flex;
854
+ flex-direction: column;
855
+ align-items: center;
856
+ gap: 4px;
857
+ z-index: 6;
858
+ }
859
+ /* 列表页的辅助列:贴着网格区右侧,上下各留一点边 */
860
+ .dg-bodyWrap > .dg-panRail {
861
+ top: 10px;
862
+ bottom: 10px;
863
+ }
864
+ .dg-panBtn {
865
+ flex: 0 0 auto;
866
+ width: 28px;
867
+ height: 28px;
868
+ display: inline-flex;
869
+ align-items: center;
870
+ justify-content: center;
871
+ font-size: 13px;
872
+ line-height: 1;
873
+ color: var(--dsw-alias-label-primary);
874
+ background: var(--dsw-alias-bg-layer-2);
875
+ border: 1px solid var(--dsw-alias-border-l1);
876
+ border-radius: 6px;
877
+ cursor: pointer;
878
+ transition: background .15s ease, border-color .15s ease;
879
+ }
880
+ .dg-panBtn:hover:not(:disabled) {
881
+ border-color: var(--dsw-alias-brand-primary);
882
+ background: var(--dsw-alias-interactive-bg-hover);
883
+ }
884
+ .dg-panBtn:disabled { opacity: .35; cursor: default; }
885
+ .dg-panBtn:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
886
+
887
+ .dg-dragTrack {
888
+ flex: 1 1 auto;
889
+ position: relative;
890
+ width: 10px;
891
+ border-radius: 5px;
892
+ background: color-mix(in srgb, var(--dsw-alias-label-primary) 10%, transparent);
893
+ cursor: pointer;
894
+ user-select: none;
895
+ touch-action: none;
896
+ }
897
+ .dg-dragTrack:hover { background: color-mix(in srgb, var(--dsw-alias-label-primary) 18%, transparent); }
898
+ .dg-dragThumb {
899
+ position: absolute;
900
+ left: 1px;
901
+ right: 1px;
902
+ top: 0;
903
+ min-height: 24px;
904
+ border-radius: 4px;
905
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 55%, transparent);
906
+ border: 1px solid var(--dsw-alias-brand-primary);
907
+ cursor: grab;
908
+ transition: background .15s ease;
909
+ }
910
+ .dg-dragThumb:hover { background: var(--dsw-alias-brand-primary); }
911
+ .dg-dragThumbActive { background: var(--dsw-alias-brand-primary); box-shadow: 0 0 0 2px color-mix(in srgb, var(--dsw-alias-brand-primary) 35%, transparent); }
912
+ .dg-dragThumb:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
913
+
914
+ .dg-viewer {
915
+ position: relative;
916
+ flex: 1 1 auto;
917
+ min-height: 0;
918
+ display: flex;
919
+ flex-direction: column;
920
+ background: var(--dsw-alias-bg-overlay);
921
+ }
922
+ .dg-viewerBar {
923
+ display: flex;
924
+ align-items: center;
925
+ gap: 8px;
926
+ padding: 8px 10px;
927
+ border-bottom: 1px solid var(--dsw-alias-border-l1);
928
+ background: var(--dsw-alias-bg-layer-1);
929
+ flex: 0 0 auto;
930
+ }
931
+ .dg-viewerTitle { flex: 1 1 auto; min-width: 0; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
932
+ .dg-viewerBody { flex: 1 1 auto; min-height: 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 10px 42px 10px 10px; }
933
+ .dg-viewerBody img { max-width: 100%; max-height: 100%; object-fit: contain; display: block; }
934
+ .dg-viewerLayer { position: absolute; inset: 0; z-index: 30; background: var(--dsw-specific-sidebar-fill, #111); display: flex; flex-direction: column; }
935
+ .dg-viewerLayer .dg-viewer { flex: 1 1 auto; min-height: 0; }
936
+ .dg-viewerBody { touch-action: none; }
937
+ .dg-textBody { display: block; overflow: auto; padding: 12px 14px; user-select: text; touch-action: auto; }
938
+
939
+ /* ===== 文件卡片 v2:三段式 ===== */
940
+ .dg-fileCard2 {
941
+ display: flex; flex-direction: column; gap: 10px;
942
+ padding: 12px 14px; text-align: left;
943
+ background: var(--dsw-alias-bg-layer-1);
944
+ border: 1px solid var(--dsw-alias-border-l1);
945
+ border-radius: 10px; cursor: pointer;
946
+ transition: border-color .15s ease, background .15s ease, box-shadow .15s ease;
947
+ }
948
+ .dg-fileCard2:hover {
949
+ background: var(--dsw-alias-bg-layer-2);
950
+ border-color: var(--dsw-alias-brand-primary);
951
+ box-shadow: 0 2px 10px rgba(0,0,0,.08);
952
+ }
953
+ .dg-fileCard2:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }
954
+
955
+ /* ① 头部 */
956
+ .dg-fcHead { display: flex; align-items: center; gap: 10px; min-width: 0; }
957
+ .dg-fcBadge {
958
+ flex: 0 0 auto; min-width: 42px; height: 28px; padding: 0 8px;
959
+ display: inline-flex; align-items: center; justify-content: center;
960
+ font-size: 10px; font-weight: 700; letter-spacing: .06em;
961
+ color: var(--dsw-alias-label-primary);
962
+ background: var(--dsw-alias-interactive-bg-hover);
963
+ border: 1px solid var(--dsw-alias-border-l1);
964
+ border-radius: 6px;
965
+ }
966
+ .dg-fcName {
967
+ flex: 1 1 auto; min-width: 0;
968
+ font-size: 13px; font-weight: 600; color: var(--dsw-alias-label-primary);
969
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
970
+ }
971
+
972
+ /* ② 操作行 */
973
+ .dg-fcActions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
974
+ .dg-fcBtn {
975
+ display: inline-flex; align-items: center; justify-content: center; gap: 5px;
976
+ height: 30px; padding: 0 12px;
977
+ font: inherit; font-size: 12px; line-height: 1;
978
+ color: var(--dsw-alias-label-secondary);
979
+ background: var(--dsw-alias-bg-base);
980
+ border: 1px solid var(--dsw-alias-border-l1);
981
+ border-radius: 7px; cursor: pointer;
982
+ transition: color .15s ease, border-color .15s ease, background .15s ease;
983
+ }
984
+ .dg-fcBtn:hover {
985
+ color: var(--dsw-alias-label-primary);
986
+ border-color: var(--dsw-alias-border-l2);
987
+ background: var(--dsw-alias-interactive-bg-hover);
988
+ }
989
+ .dg-fcBtnPrimary {
990
+ color: var(--dsw-alias-label-primary);
991
+ border-color: var(--dsw-alias-brand-primary);
992
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 10%, transparent);
993
+ }
994
+ .dg-fcBtnPrimary:hover {
995
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary) 20%, transparent);
996
+ }
997
+ .dg-fcBtnOk { color: var(--dsw-alias-brand-primary); border-color: var(--dsw-alias-brand-primary); }
998
+ .dg-fcBtnIcon { flex: 0 0 auto; min-width: 34px; padding: 0 8px; font-size: 13px; }
999
+ .dg-fcIco { font-size: 12px; line-height: 1; opacity: .9; }
1000
+
1001
+ /* ③ 底部 */
1002
+ .dg-fcFoot {
1003
+ font-size: 11px; color: var(--dsw-alias-label-secondary);
1004
+ padding-top: 2px; border-top: 1px solid var(--dsw-alias-border-l1);
1005
+ }
1006
+ .dg-textPre { margin: 0; font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 12px; line-height: 1.65; white-space: pre-wrap; word-break: break-word; color: var(--dsw-alias-label-primary); user-select: text; }
1007
+ .dg-fileBody { padding-top: 4px; }
1008
+ .dg-fileGrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 10px; }
1009
+ .dg-fileCard2 { cursor: pointer; } /* 覆盖 .dg-card 的 zoom-in 与 overflow/padding */
1010
+ .dg-fileCard2 { overflow: visible; padding: 12px 14px; }
1011
+ .dg-copyBtn { flex: 0 0 auto; font-size: 11px; padding: 3px 8px; white-space: nowrap; }
1012
+ .dg-previewBtn { border-color: var(--dsw-alias-interactive-border-accent, var(--dsw-alias-border-l1)); }
1013
+ .dg-fileCardClickable { cursor: pointer; }
1014
+ .dg-fileCardClickable:hover { background: var(--dsw-alias-interactive-bg-hover); }
1015
+ .dg-fileCardClickable:focus-visible { outline: 2px solid var(--dsw-alias-border-accent, #4b9eff); outline-offset: 1px; }
1016
+ .dg-copied { color: var(--dsw-alias-label-primary); font-weight: 600; opacity: .85; }
1017
+ .dg-viewerFoot { flex: 0 0 auto; padding: 6px 10px 10px; color: var(--dsw-alias-label-secondary); font-size: 11px; word-break: break-all; }
1018
+ .dg-open { white-space: nowrap; }
1019
+ .dg-openCompact { padding: 2px 6px; line-height: 16px; font-size: 12px; }
1020
+ `
1021
+
1022
+ /**
1023
+ * 复制文本到剪贴板。优先 Clipboard API,失败回退 execCommand。
1024
+ * @param text - 要复制的内容。
1025
+ * @returns 是否成功。
1026
+ */
1027
+ /**
1028
+ * 用根目录与相对路径拼出 Windows 绝对路径。
1029
+ * 全程用 split/join,不用正则,避免转义歧义。
1030
+ * @param root - 根目录(可能以 \ 或 / 结尾)。
1031
+ * @param relPath - 相对路径(以 / 分隔)。
1032
+ * @returns 绝对路径。
1033
+ */
1034
+ /**
1035
+ * 构造 DSH 原生资源地址(session 作用域)。
1036
+ * 文档预览的 canOpen 只认 scope=session,故必须用 session 形式,不能用 absolute。
1037
+ * @param sessionId - 当前会话 id(slot props.sessionId)。
1038
+ * @param absPath - 文件绝对路径。
1039
+ * @returns dsh-resource://file/session/<sessionId>/<path>
1040
+ */
1041
+ function sessionFileAddressOf(sessionId, absPath) {
1042
+ const norm = String(absPath).split(String.fromCharCode(92)).join('/').replace(/^\.\//, '')
1043
+ const segs = norm.split('/').filter((s) => s !== '')
1044
+ const encoded = segs.map((s) => encodeURIComponent(s).replace(/%3A/gi, ':')).join('/')
1045
+ return 'dsh-resource://file/session/' + encodeURIComponent(sessionId) + '/' + encoded
1046
+ }
1047
+
1048
+ function buildAbsPath(root, relPath) {
1049
+ const BS = String.fromCharCode(92) // 反斜杠
1050
+ const cleanedRoot = String(root).split('/').join(BS).split(BS).filter((s) => s !== '').join(BS)
1051
+ const parts = String(relPath).split('/').filter((s) => s !== '')
1052
+ return cleanedRoot + BS + parts.join(BS)
1053
+ }
1054
+
1055
+ async function copyText(text) {
1056
+ try {
1057
+ if (navigator.clipboard !== undefined && navigator.clipboard !== null) {
1058
+ await navigator.clipboard.writeText(text)
1059
+ return true
1060
+ }
1061
+ } catch (error) {
1062
+ console.warn('dsh-gallery: clipboard API 失败,回退', error)
1063
+ }
1064
+ try {
1065
+ const host = document.createElement('textarea')
1066
+ host.value = text
1067
+ host.style.position = 'fixed'
1068
+ host.style.opacity = '0'
1069
+ document.body.appendChild(host)
1070
+ host.select()
1071
+ const ok = document.execCommand('copy')
1072
+ document.body.removeChild(host)
1073
+ return ok
1074
+ } catch (error) {
1075
+ console.error('dsh-gallery: 复制失败', error)
1076
+ return false
1077
+ }
1078
+ }
1079
+
1080
+ /**
1081
+ * 文件卡片:三段式布局。
1082
+ * ① 头部:类型图标 + 文件名 + 简介(悬停展开,此处用大小/时间)
1083
+ * ② 中部:三个操作按钮(侧边预览 / 复制路径 / 打开本地位置)
1084
+ * ③ 底部:元信息
1085
+ */
1086
+ /**
1087
+ * 右键菜单:隐藏 / 打开位置 / 复制路径 / 删除。
1088
+ * 挂在卡片上,位置跟随鼠标;点外部或按 Esc 关闭。
1089
+ * 删除需要二次确认(走 ConfirmDialog)。
1090
+ */
1091
+ function ContextMenu({ t, x, y, item, actions, onClose }) {
1092
+ const menuRef = React.useRef(null)
1093
+ const [pos, setPos] = React.useState({ left: x, top: y })
1094
+
1095
+ // 边界处理:靠近视口右侧/底部时向内收,避免被截断
1096
+ React.useLayoutEffect(() => {
1097
+ const node = menuRef.current
1098
+ if (node === null) return
1099
+ const rect = node.getBoundingClientRect()
1100
+ const pad = 8
1101
+ let left = x
1102
+ let top = y
1103
+ if (left + rect.width > window.innerWidth - pad) left = window.innerWidth - rect.width - pad
1104
+ if (top + rect.height > window.innerHeight - pad) top = window.innerHeight - rect.height - pad
1105
+ setPos({ left: Math.max(pad, left), top: Math.max(pad, top) })
1106
+ }, [x, y])
1107
+
1108
+ React.useEffect(() => {
1109
+ const onDown = (event) => {
1110
+ if (menuRef.current !== null && menuRef.current.contains(event.target)) return
1111
+ onClose()
1112
+ }
1113
+ const onKey = (event) => { if (event.key === 'Escape') onClose() }
1114
+ // 捕获阶段监听,确保点击卡片本身也能关闭菜单
1115
+ document.addEventListener('pointerdown', onDown, true)
1116
+ window.addEventListener('keydown', onKey)
1117
+ return () => {
1118
+ document.removeEventListener('pointerdown', onDown, true)
1119
+ window.removeEventListener('keydown', onKey)
1120
+ }
1121
+ }, [onClose])
1122
+
1123
+ const entry = (key, label, icon, run, danger) => h('button', {
1124
+ type: 'button',
1125
+ key,
1126
+ className: `dg-ctxItem${danger ? ' dg-ctxDanger' : ''}`,
1127
+ 'data-gallery-ctx': key,
1128
+ onClick: (event) => {
1129
+ event.stopPropagation()
1130
+ event.preventDefault()
1131
+ onClose()
1132
+ run()
1133
+ },
1134
+ }, [
1135
+ h('span', { className: 'dg-ctxIco', key: 'i' }, icon),
1136
+ h('span', { key: 'l' }, label),
1137
+ ])
1138
+
1139
+ return h('div', {
1140
+ className: 'dg-ctxLayer',
1141
+ key: 'ctxLayer',
1142
+ onPointerDown: (event) => event.stopPropagation(),
1143
+ onContextMenu: (event) => event.preventDefault(),
1144
+ }, h('div', {
1145
+ className: 'dg-ctxMenu',
1146
+ key: 'menu',
1147
+ ref: menuRef,
1148
+ role: 'menu',
1149
+ 'data-gallery-contextmenu': item.relPath,
1150
+ style: { left: `${pos.left}px`, top: `${pos.top}px` },
1151
+ }, [
1152
+ h('div', { className: 'dg-ctxHead', key: 'head' }, item.name),
1153
+ entry('hide', t('ctxHide'), '🚫', () => actions.onHide()),
1154
+ entry('reveal', t('ctxReveal'), '📂', () => actions.onReveal()),
1155
+ entry('copy', t('ctxCopy'), '⧉', () => actions.onCopy()),
1156
+ entry('delete', t('ctxDelete'), '🗑', () => actions.onDelete(), true),
1157
+ ]))
1158
+ }
1159
+
1160
+ /** 删除确认弹窗:删除不可逆,必须二次确认。 */
1161
+ function ConfirmDialog({ t, name, busy, onCancel, onConfirm }) {
1162
+ React.useEffect(() => {
1163
+ const onKey = (event) => {
1164
+ if (busy) return
1165
+ if (event.key === 'Escape') { event.preventDefault(); onCancel() }
1166
+ }
1167
+ window.addEventListener('keydown', onKey)
1168
+ return () => window.removeEventListener('keydown', onKey)
1169
+ }, [busy, onCancel])
1170
+
1171
+ return h('div', {
1172
+ className: 'dg-confirmLayer',
1173
+ key: 'confirmLayer',
1174
+ onPointerDown: (event) => event.stopPropagation(),
1175
+ }, h('div', {
1176
+ className: 'dg-confirm',
1177
+ role: 'alertdialog',
1178
+ 'aria-modal': true,
1179
+ 'data-gallery-confirm-delete': name,
1180
+ }, [
1181
+ h('div', { className: 'dg-confirmTitle', key: 'title' }, t('ctxDeleteConfirm')),
1182
+ h('div', { className: 'dg-confirmName', key: 'name' }, name),
1183
+ h('div', { className: 'dg-confirmActions', key: 'actions' }, [
1184
+ h('button', {
1185
+ type: 'button', key: 'no', className: 'dg-btn',
1186
+ disabled: busy,
1187
+ onClick: onCancel,
1188
+ }, t('ctxDeleteNo')),
1189
+ h('button', {
1190
+ type: 'button', key: 'yes', className: 'dg-btn dg-dangerBtn',
1191
+ disabled: busy,
1192
+ 'data-gallery-confirm-yes': true,
1193
+ onClick: onConfirm,
1194
+ }, busy ? t('ctxDeleting') : t('ctxDeleteYes')),
1195
+ ]),
1196
+ ]))
1197
+ }
1198
+
1199
+ function FileCard({ item, t, absPath, onOpenFolder, onPreview, onContextMenu }) {
1200
+ const ext = (item.extension ?? '').replace(/^\./, '').toLowerCase()
1201
+ const badge = (ext === '' ? 'FILE' : ext).slice(0, 4).toUpperCase()
1202
+ const [copied, setCopied] = React.useState(false)
1203
+
1204
+ React.useEffect(() => {
1205
+ if (copied === false) return undefined
1206
+ const timer = setTimeout(() => setCopied(false), 1600)
1207
+ return () => clearTimeout(timer)
1208
+ }, [copied])
1209
+
1210
+ const onCopy = async (event) => {
1211
+ event.stopPropagation()
1212
+ const ok = await copyText(absPath)
1213
+ setCopied(ok)
1214
+ }
1215
+ const onEye = (event) => {
1216
+ event.stopPropagation()
1217
+ onPreview(absPath)
1218
+ }
1219
+ const onFolder = (event) => {
1220
+ event.stopPropagation()
1221
+ onOpenFolder(absPath)
1222
+ }
1223
+
1224
+ return h('div', {
1225
+ className: 'dg-card dg-fileCard2',
1226
+ role: 'button',
1227
+ tabIndex: 0,
1228
+ title: `${item.name}
1229
+ ${absPath}
1230
+ 点击在 DSH 右侧栏预览`,
1231
+ onClick: () => onPreview(absPath),
1232
+ onContextMenu: (event) => {
1233
+ event.preventDefault()
1234
+ event.stopPropagation()
1235
+ if (typeof onContextMenu === 'function') onContextMenu(item, absPath, event)
1236
+ },
1237
+ onKeyDown: (event) => {
1238
+ if (event.key === 'Enter' || event.key === ' ') {
1239
+ event.preventDefault()
1240
+ onPreview(absPath)
1241
+ }
1242
+ },
1243
+ 'data-gallery-file': item.relPath,
1244
+ }, [
1245
+ // ① 头部
1246
+ h('div', { className: 'dg-fcHead', key: 'head' }, [
1247
+ h('span', { className: 'dg-fcBadge', key: 'badge' }, badge),
1248
+ h('span', { className: 'dg-fcName', key: 'name' }, item.name),
1249
+ ]),
1250
+ // ② 中部操作行
1251
+ h('div', { className: 'dg-fcActions', key: 'actions' }, [
1252
+ h('button', {
1253
+ type: 'button', key: 'eye',
1254
+ className: 'dg-fcBtn dg-fcBtnPrimary',
1255
+ 'data-gallery-preview': item.relPath,
1256
+ title: t('previewInSidebar'),
1257
+ onClick: onEye,
1258
+ }, [h('span', { className: 'dg-fcIco', key: 'i' }, '👁'), h('span', { key: 'l' }, t('preview'))]),
1259
+ h('button', {
1260
+ type: 'button', key: 'copy',
1261
+ className: `dg-fcBtn${copied ? ' dg-fcBtnOk' : ''}`,
1262
+ 'data-gallery-copy': item.relPath,
1263
+ title: t('copyPath'),
1264
+ onClick: onCopy,
1265
+ }, [h('span', { className: 'dg-fcIco', key: 'i' }, copied ? '✓' : '⧉'), h('span', { key: 'l' }, copied ? t('copied') : t('copy'))]),
1266
+ h('button', {
1267
+ type: 'button', key: 'folder',
1268
+ className: 'dg-fcBtn dg-fcBtnIcon',
1269
+ title: t('openFolder'),
1270
+ onClick: onFolder,
1271
+ }, '📂'),
1272
+ ]),
1273
+ // ③ 底部元信息
1274
+ h('div', { className: 'dg-fcFoot', key: 'foot' },
1275
+ `${formatBytes(item.size)} · ${formatTime(item.mtime)}`),
1276
+ ])
1277
+ }
1278
+
1279
+ /** 单张缩略图卡片:独立加载、独立失败,互不影响。 */
1280
+ function Card({ item, t, onOpen, limiter, onContextMenu }) {
1281
+ const [state, setState] = React.useState({ status: 'pending' })
1282
+ const [node, setNode] = React.useState(null)
1283
+
1284
+ React.useEffect(() => {
1285
+ if (node === null) return undefined
1286
+ let cancelled = false
1287
+ let started = false
1288
+ let sourceUrl = null
1289
+ const controller = new AbortController()
1290
+
1291
+ const run = () => {
1292
+ if (started) return
1293
+ started = true
1294
+ setState({ status: 'pending' })
1295
+ limiter(async () => {
1296
+ const blob = await fetchRaw(item.relPath, controller.signal)
1297
+ const thumb = await makeScaled(blob, THUMB_SIZE, true)
1298
+ if (cancelled) {
1299
+ if (thumb.url !== null) URL.revokeObjectURL(thumb.url)
1300
+ return
1301
+ }
1302
+ sourceUrl = thumb.url
1303
+ setState({ status: 'ready', url: thumb.url })
1304
+ }).catch((error) => {
1305
+ if (cancelled || controller.signal.aborted) return
1306
+ setState({ status: 'failed', message: String(error?.message ?? error) })
1307
+ })
1308
+ }
1309
+
1310
+ // 环境不支持 IntersectionObserver 时直接加载,保证可用性。
1311
+ if (typeof IntersectionObserver !== 'function') {
1312
+ run()
1313
+ return () => {
1314
+ cancelled = true
1315
+ controller.abort()
1316
+ if (sourceUrl !== null) URL.revokeObjectURL(sourceUrl)
1317
+ }
1318
+ }
1319
+
1320
+ const observer = new IntersectionObserver((entries) => {
1321
+ for (const entry of entries) {
1322
+ if (!entry.isIntersecting) continue
1323
+ observer.disconnect()
1324
+ run()
1325
+ }
1326
+ }, { rootMargin: '120px' })
1327
+ observer.observe(node)
1328
+
1329
+ return () => {
1330
+ cancelled = true
1331
+ observer.disconnect()
1332
+ controller.abort()
1333
+ if (sourceUrl !== null) URL.revokeObjectURL(sourceUrl)
1334
+ }
1335
+ }, [node, item.relPath, limiter])
1336
+
1337
+ const dims = item.width !== null && item.height !== null
1338
+ ? format(t('dims'), { w: item.width, h: item.height })
1339
+ : t('dimsUnknown')
1340
+
1341
+ return h('button', {
1342
+ type: 'button',
1343
+ ref: setNode,
1344
+ className: 'dg-card',
1345
+ title: item.relPath,
1346
+ 'data-gallery-card': item.relPath,
1347
+ onClick: (event) => onOpen(item, event.currentTarget),
1348
+ onContextMenu: (event) => {
1349
+ event.preventDefault()
1350
+ event.stopPropagation()
1351
+ if (typeof onContextMenu === 'function') onContextMenu(item, null, event)
1352
+ },
1353
+ }, [
1354
+ h('div', { className: 'dg-thumb', key: 'thumb' },
1355
+ state.status === 'ready'
1356
+ ? h('img', {
1357
+ src: state.url,
1358
+ alt: item.name,
1359
+ decoding: 'async',
1360
+ loading: 'lazy',
1361
+ width: THUMB_SIZE,
1362
+ height: THUMB_SIZE,
1363
+ })
1364
+ : h('div', { className: 'dg-placeholder', 'data-gallery-placeholder': state.status },
1365
+ state.status === 'failed'
1366
+ ? [h('div', { key: 'msg' }, t('thumbFailed')), h('code', { key: 'name' }, item.name)]
1367
+ : t('loading')),
1368
+ ),
1369
+ h('div', { className: 'dg-meta', key: 'meta' }, [
1370
+ h('span', { className: 'dg-name', key: 'name' }, item.name),
1371
+ h('span', { className: 'dg-dim', key: 'dim' }, dims),
1372
+ h('span', { className: 'dg-dim', key: 'time' }, formatTime(item.mtime)),
1373
+ ]),
1374
+ ])
1375
+ }
1376
+
1377
+ /** 文本类扩展名(仅用于判断,不再在插件内渲染)。 */
1378
+ const TEXT_EXTS = new Set([
1379
+ '.md', '.markdown', '.txt', '.log', '.json', '.jsonl', '.csv', '.tsv',
1380
+ '.yaml', '.yml', '.xml', '.toml', '.ini', '.cfg', '.conf',
1381
+ '.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx',
1382
+ '.ps1', '.sh', '.bat', '.cmd', '.sql', '.ipynb',
1383
+ '.html', '.htm', '.css', '.scss', '.url',
1384
+ ])
1385
+
1386
+ /** 判断某个文件是否可按文本预览(保留给需要提示的场景)。 */
1387
+ function isTextLike(ext) {
1388
+ return TEXT_EXTS.has(String(ext ?? '').toLowerCase())
1389
+ }
1390
+
1391
+ /**
1392
+ * 面板内放大查看(**仅图片**)。
1393
+ * 交互:左键点图退出、滚轮缩放、中键拖动平移。
1394
+ * 文件不走这里——文件点击直接交给 DSH 自带侧栏预览。
1395
+ */
1396
+ function Viewer({ items, index, onClose, onStep, t }) {
1397
+ const item = items[index]
1398
+ // 文件预览已改走 DSH 原生侧栏(session 地址);此处 Viewer 仅处理图片,isText 恒 false,
1399
+ // 下面的文本分支保留为死代码,供 v0.2 若需插件内预览时复用
1400
+ const isText = false
1401
+ const [state, setState] = React.useState({ status: 'pending' })
1402
+ const [zoom, setZoom] = React.useState(1)
1403
+ const [pan, setPan] = React.useState({ x: 0, y: 0 })
1404
+ const [dragging, setDragging] = React.useState(false)
1405
+ const bodyRef = React.useRef(null)
1406
+ const dragRef = React.useRef(null)
1407
+ // 上一次拖动是否真的产生了位移(用于区分「拖图」和「单击关闭」)
1408
+ const lastDragMoved = React.useRef(false)
1409
+
1410
+ React.useEffect(() => {
1411
+ let alive = true
1412
+ const controller = new AbortController()
1413
+ setState({ status: 'pending' })
1414
+ // 既不是文本、也不是图片的二进制文件(pdf/docx/zip 等)不做内联解码
1415
+ const ext = String(item.extension ?? '').toLowerCase()
1416
+ const isImage = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp'].includes(ext)
1417
+ if (!isText && !isImage) {
1418
+ setState({ status: 'binary' })
1419
+ return () => { alive = false }
1420
+ }
1421
+ fetchRaw(item.relPath, controller.signal)
1422
+ .then(async (blob) => {
1423
+ if (isText) {
1424
+ // 文本预览:按大小截断,避免超大日志卡死面板
1425
+ const text = await blob.text()
1426
+ const capped = text.length > MAX_TEXT_CHARS
1427
+ ? text.slice(0, MAX_TEXT_CHARS) + `\n\n…(已截断,原文 ${text.length} 字符)`
1428
+ : text
1429
+ if (!alive) return
1430
+ setState({ status: 'ready', text: capped, truncated: text.length > MAX_TEXT_CHARS })
1431
+ return
1432
+ }
1433
+ const scaled = await makeScaled(blob, VIEW_SIZE, false)
1434
+ if (!alive) return
1435
+ setState({ status: 'ready', url: scaled.dataUrl ?? (scaled.url ?? '') })
1436
+ })
1437
+ .catch((error) => {
1438
+ if (!alive || controller.signal.aborted) return
1439
+ setState({ status: 'failed', message: String(error?.message ?? error) })
1440
+ })
1441
+ return () => {
1442
+ alive = false
1443
+ controller.abort()
1444
+ }
1445
+ }, [item.relPath, isText])
1446
+
1447
+ // 切换图片时重置缩放与平移
1448
+ React.useEffect(() => {
1449
+ setZoom(1)
1450
+ setPan({ x: 0, y: 0 })
1451
+ setDragging(false)
1452
+ dragRef.current = null
1453
+ }, [item.relPath])
1454
+
1455
+ // 滚轮缩放:以鼠标位置为中心,避免放大后目标跑出视野(仅图片模式)。
1456
+ // 文本预览用原生滚动,不拦截滚轮。
1457
+ React.useEffect(() => {
1458
+ const node = bodyRef.current
1459
+ if (node === null || state.status !== 'ready' || isText) return undefined
1460
+ const onWheel = (event) => {
1461
+ event.preventDefault()
1462
+ const delta = event.deltaY < 0 ? 1 : -1
1463
+ const rect = node.getBoundingClientRect()
1464
+ // 光标相对预览框中心的偏移
1465
+ const cx = event.clientX - (rect.left + rect.width / 2)
1466
+ const cy = event.clientY - (rect.top + rect.height / 2)
1467
+
1468
+ setZoom((current) => {
1469
+ const next = Math.min(MAX_ZOOM, Math.max(1, current + delta * ZOOM_STEP))
1470
+ if (next === 1) { setPan({ x: 0, y: 0 }); return 1 }
1471
+ // 以光标为不动点缩放:光标下的像素点在缩放前后保持同一屏幕位置
1472
+ const ratio = next / current
1473
+ setPan((p) => ({
1474
+ x: cx - (cx - p.x) * ratio,
1475
+ y: cy - (cy - p.y) * ratio,
1476
+ }))
1477
+ return next
1478
+ })
1479
+ }
1480
+ node.addEventListener('wheel', onWheel, { passive: false })
1481
+ return () => node.removeEventListener('wheel', onWheel)
1482
+ }, [state.status, isText])
1483
+
1484
+ /**
1485
+ * 拖拽平移:放大后生效。支持**左键拖动**与**中键拖动**。
1486
+ * 区分「拖动」与「单击退出」:位移超过阈值才算拖动,否则视为点击关闭。
1487
+ */
1488
+ const onPointerDown = (event) => {
1489
+ if (zoom <= 1) return
1490
+ // 左键(0) 与中键(1) 都可拖;中键默认会触发浏览器自动滚动,需拦截
1491
+ if (event.button !== 0 && event.button !== 1) return
1492
+ event.preventDefault()
1493
+ event.stopPropagation()
1494
+ dragRef.current = {
1495
+ x: event.clientX,
1496
+ y: event.clientY,
1497
+ ox: pan.x,
1498
+ oy: pan.y,
1499
+ moved: false,
1500
+ }
1501
+ try { event.currentTarget.setPointerCapture(event.pointerId) } catch {}
1502
+ setDragging(true)
1503
+ }
1504
+ const onPointerMove = (event) => {
1505
+ const d = dragRef.current
1506
+ if (d === null) return
1507
+ event.preventDefault()
1508
+ const dx = event.clientX - d.x
1509
+ const dy = event.clientY - d.y
1510
+ // 3px 阈值,避免手抖导致「点了却变成微拖」
1511
+ if (!d.moved && Math.abs(dx) + Math.abs(dy) > 3) d.moved = true
1512
+ setPan({ x: d.ox + dx, y: d.oy + dy })
1513
+ }
1514
+ const endDrag = (event) => {
1515
+ const d = dragRef.current
1516
+ if (d === null) return
1517
+ dragRef.current = null
1518
+ // 把「这次是否真的拖动了」记下来,供紧随其后的 click 判断
1519
+ lastDragMoved.current = d.moved === true
1520
+ setDragging(false)
1521
+ if (event !== undefined) {
1522
+ try { event.currentTarget.releasePointerCapture(event.pointerId) } catch {}
1523
+ }
1524
+ }
1525
+ // 中键按下时阻止浏览器默认的自动滚动
1526
+ const onMouseDown = (event) => {
1527
+ if (event.button === 1) event.preventDefault()
1528
+ }
1529
+ /**
1530
+ * 点击退出:只在「本次按下没有拖动过」时触发。
1531
+ * 放大状态下左键是用来拖图的,松手后若真的移动过就不算点击。
1532
+ */
1533
+ const onClickBody = (event) => {
1534
+ event.preventDefault()
1535
+ if (lastDragMoved.current === true) {
1536
+ lastDragMoved.current = false
1537
+ return
1538
+ }
1539
+ onClose()
1540
+ }
1541
+
1542
+ // 键盘快捷键在 panStep/zoomBy 定义之后再绑定(见下方 effect)
1543
+
1544
+ const dims = item.width !== null && item.height !== null
1545
+ ? format(t('dims'), { w: item.width, h: item.height })
1546
+ : t('dimsUnknown')
1547
+
1548
+ // ---- 右侧垂直拖动条(zoom > 1 时出现)----
1549
+ // 滑块高度 = 视口高 / 缩放倍率;拖动滑块即沿 y 轴平移图片。
1550
+ const clampPanY = React.useCallback((y) => {
1551
+ const node = bodyRef.current
1552
+ if (node === null || zoom <= 1) return 0
1553
+ const overflow = Math.max(0, (node.clientHeight * (zoom - 1)) / 2)
1554
+ return Math.max(-overflow, Math.min(overflow, y))
1555
+ }, [zoom])
1556
+
1557
+ // ---- 缩放与平移的「无鼠标」友好操作 ----
1558
+ // 远程控制(如 ToDesk)常常没有实体鼠标,滚轮与精细拖动都难用。
1559
+ // 所以提供:点击轨道跳转、上下按钮、键盘方向键、缩放按钮。
1560
+ const PAN_STEP = 0.25 // 每次按钮/键盘移动「可视范围」的 25%
1561
+
1562
+ /** 当前竖向可平移范围(居中坐标系,±overflow)。 */
1563
+ const vOverflow = React.useCallback(() => {
1564
+ const node = bodyRef.current
1565
+ if (node === null || zoom <= 1) return 0
1566
+ return Math.max(0, (node.clientHeight * (zoom - 1)) / 2)
1567
+ }, [zoom])
1568
+
1569
+ /** 按比例平移:ratio 为 +1 → 移到顶部,-1 → 移到底部。 */
1570
+ const panTo = React.useCallback((ratio) => {
1571
+ const overflow = vOverflow()
1572
+ if (overflow <= 0) return
1573
+ const r = Math.max(-1, Math.min(1, ratio))
1574
+ setPan((p) => ({ x: p.x, y: -r * overflow }))
1575
+ }, [vOverflow])
1576
+
1577
+ /** 步进一步:direction = -1 向上、+1 向下。 */
1578
+ const panStep = React.useCallback((direction) => {
1579
+ const overflow = vOverflow()
1580
+ if (overflow <= 0) return
1581
+ const step = overflow * PAN_STEP * (direction > 0 ? -1 : 1)
1582
+ setPan((p) => ({ x: p.x, y: Math.max(-overflow, Math.min(overflow, p.y + step)) }))
1583
+ }, [vOverflow])
1584
+
1585
+ const zoomBy = React.useCallback((direction) => {
1586
+ setZoom((current) => {
1587
+ const next = Math.min(MAX_ZOOM, Math.max(1, current + direction * ZOOM_STEP))
1588
+ if (next === 1) setPan({ x: 0, y: 0 })
1589
+ return next
1590
+ })
1591
+ }, [])
1592
+
1593
+ /**
1594
+ * 点击轨道空白处:直接跳到该位置(省去精细拖动)。
1595
+ * 远程控制下这比拖滑块好用得多。
1596
+ */
1597
+ const onTrackClick = (event) => {
1598
+ event.preventDefault()
1599
+ event.stopPropagation()
1600
+ const rect = event.currentTarget.getBoundingClientRect()
1601
+ const ratio = (event.clientY - rect.top) / Math.max(1, rect.height)
1602
+ // ratio 0 = 轨道顶部 → 图片顶部
1603
+ panTo(1 - ratio * 2)
1604
+ }
1605
+
1606
+ // 键盘:方向键左右切图、上下平移、+/- 缩放、Esc 退出。
1607
+ // 远程控制下键盘比鼠标精确,是主要操作方式。
1608
+ React.useEffect(() => {
1609
+ const onKey = (event) => {
1610
+ const key = event.key
1611
+ if (key === 'Escape') {
1612
+ event.preventDefault()
1613
+ onClose()
1614
+ } else if (key === 'ArrowLeft') {
1615
+ event.preventDefault()
1616
+ onStep(-1)
1617
+ } else if (key === 'ArrowRight') {
1618
+ event.preventDefault()
1619
+ onStep(1)
1620
+ } else if (key === 'ArrowUp') {
1621
+ event.preventDefault()
1622
+ panStep(-1)
1623
+ } else if (key === 'ArrowDown') {
1624
+ event.preventDefault()
1625
+ panStep(1)
1626
+ } else if (key === '+' || key === '=') {
1627
+ event.preventDefault()
1628
+ zoomBy(1)
1629
+ } else if (key === '-' || key === '_') {
1630
+ event.preventDefault()
1631
+ zoomBy(-1)
1632
+ } else if (key === '0') {
1633
+ event.preventDefault()
1634
+ setZoom(1)
1635
+ setPan({ x: 0, y: 0 })
1636
+ }
1637
+ }
1638
+ window.addEventListener('keydown', onKey)
1639
+ return () => window.removeEventListener('keydown', onKey)
1640
+ }, [onClose, onStep, panStep, zoomBy])
1641
+
1642
+ const sliderDragRef = React.useRef(null)
1643
+ const onSliderPointerDown = (event) => {
1644
+ event.preventDefault()
1645
+ event.stopPropagation()
1646
+ const node = bodyRef.current
1647
+ if (node === null) return
1648
+ const trackH = node.clientHeight
1649
+ const overflow = Math.max(0, (trackH * (zoom - 1)) / 2)
1650
+ if (overflow <= 0) return
1651
+ sliderDragRef.current = { startY: event.clientY, startPanY: pan.y, overflow, trackH }
1652
+ try { event.currentTarget.setPointerCapture(event.pointerId) } catch {}
1653
+ }
1654
+ const onSliderPointerMove = (event) => {
1655
+ const d = sliderDragRef.current
1656
+ if (d === null) return
1657
+ event.preventDefault()
1658
+ const sliderH = Math.max(24, d.trackH / zoom)
1659
+ const travel = Math.max(1, d.trackH - sliderH)
1660
+ const deltaPx = event.clientY - d.startY
1661
+ // 滑块移动整条 travel 对应图片从 +overflow 移到 -overflow
1662
+ const nextY = d.startPanY - (deltaPx * (2 * d.overflow)) / travel
1663
+ setPan((p) => ({ x: p.x, y: clampPanY(nextY) }))
1664
+ }
1665
+ const endSliderDrag = (event) => {
1666
+ if (sliderDragRef.current === null) return
1667
+ sliderDragRef.current = null
1668
+ if (event !== undefined) {
1669
+ try { event.currentTarget.releasePointerCapture(event.pointerId) } catch {}
1670
+ }
1671
+ }
1672
+
1673
+ // 右侧竖列:↑ 按钮 + 轨道 + ↓ 按钮。远程控制下没有滚轮也能上下移动。
1674
+ const slider = (() => {
1675
+ if (isText || zoom <= 1 || state.status !== 'ready') return null
1676
+ const node = bodyRef.current
1677
+ const trackH = node === null ? 0 : node.clientHeight
1678
+ if (trackH <= 0) return null
1679
+ const overflow = Math.max(0, (trackH * (zoom - 1)) / 2)
1680
+ const sliderH = Math.max(24, trackH / zoom)
1681
+ const travel = Math.max(1, trackH - sliderH)
1682
+ const ratio = overflow <= 0 ? 0.5 : (pan.y + overflow) / (2 * overflow)
1683
+ const top = Math.max(0, Math.min(travel, travel * (1 - ratio)))
1684
+ const atTop = overflow > 0 && pan.y >= overflow - 1
1685
+ const atBottom = overflow > 0 && pan.y <= -overflow + 1
1686
+
1687
+ return h('div', { className: 'dg-panRail', key: 'panRail', 'data-gallery-panrail': true }, [
1688
+ h('button', {
1689
+ type: 'button',
1690
+ className: 'dg-panBtn',
1691
+ key: 'up',
1692
+ 'data-gallery-pan': 'up',
1693
+ title: t('panUpHint'),
1694
+ 'aria-label': t('panUpHint'),
1695
+ disabled: atTop,
1696
+ onClick: (event) => { event.stopPropagation(); panStep(-1) },
1697
+ }, '▲'),
1698
+ h('div', {
1699
+ className: 'dg-dragTrack',
1700
+ key: 'dragTrack',
1701
+ 'data-gallery-dragtrack': true,
1702
+ title: t('trackHint'),
1703
+ onPointerDown: (event) => event.stopPropagation(),
1704
+ onClick: onTrackClick,
1705
+ }, h('div', {
1706
+ className: `dg-dragThumb${dragging ? ' dg-dragThumbActive' : ''}`,
1707
+ key: 'thumb',
1708
+ 'data-gallery-dragthumb': true,
1709
+ role: 'slider',
1710
+ 'aria-orientation': 'vertical',
1711
+ 'aria-label': t('dragHint'),
1712
+ style: { height: `${Math.round(sliderH)}px`, transform: `translateY(${Math.round(top)}px)` },
1713
+ title: t('dragHint'),
1714
+ onPointerDown: onSliderPointerDown,
1715
+ onPointerMove: onSliderPointerMove,
1716
+ onPointerUp: endSliderDrag,
1717
+ onPointerCancel: endSliderDrag,
1718
+ })),
1719
+ h('button', {
1720
+ type: 'button',
1721
+ className: 'dg-panBtn',
1722
+ key: 'down',
1723
+ 'data-gallery-pan': 'down',
1724
+ title: t('panDownHint'),
1725
+ 'aria-label': t('panDownHint'),
1726
+ disabled: atBottom,
1727
+ onClick: (event) => { event.stopPropagation(); panStep(1) },
1728
+ }, '▼'),
1729
+ ])
1730
+ })()
1731
+
1732
+ return h('div', {
1733
+ className: 'dg-viewer',
1734
+ role: 'dialog',
1735
+ 'aria-modal': false,
1736
+ 'aria-label': t('zoomed'),
1737
+ 'data-gallery-viewer': item.relPath,
1738
+ }, [
1739
+ h('div', { className: 'dg-viewerBar', key: 'bar' }, [
1740
+ h('span', { className: 'dg-viewerTitle', key: 'title' }, item.name),
1741
+ zoom > 1
1742
+ ? h('span', { className: 'dg-zoomBadge', key: 'zoom', 'data-gallery-zoom-badge': zoom }, `${zoom.toFixed(1)}×`)
1743
+ : null,
1744
+ // 缩放按钮:远程控制下没有滚轮也能操作
1745
+ !isText && h('div', { className: 'dg-zoomCtl', key: 'zoomCtl' }, [
1746
+ h('button', {
1747
+ type: 'button', className: 'dg-btn dg-btnTiny', key: 'out',
1748
+ 'data-gallery-zoom-out': true,
1749
+ disabled: zoom <= 1,
1750
+ title: t('zoomOutHint'), 'aria-label': t('zoomOutHint'),
1751
+ onClick: (event) => { event.stopPropagation(); zoomBy(-1) },
1752
+ }, '-'),
1753
+ h('button', {
1754
+ type: 'button', className: 'dg-btn dg-btnTiny', key: 'in',
1755
+ 'data-gallery-zoom-in': true,
1756
+ disabled: zoom >= MAX_ZOOM,
1757
+ title: t('zoomInHint'), 'aria-label': t('zoomInHint'),
1758
+ onClick: (event) => { event.stopPropagation(); zoomBy(1) },
1759
+ }, '+'),
1760
+ h('button', {
1761
+ type: 'button', className: 'dg-btn dg-btnTiny', key: 'fit',
1762
+ 'data-gallery-zoom-reset': true,
1763
+ disabled: zoom <= 1,
1764
+ title: t('zoomResetHint'), 'aria-label': t('zoomResetHint'),
1765
+ onClick: (event) => { event.stopPropagation(); setZoom(1); setPan({ x: 0, y: 0 }) },
1766
+ }, '1:1'),
1767
+ ]),
1768
+ h('button', { type: 'button', className: 'dg-btn', key: 'prev', onClick: () => onStep(-1), 'aria-label': t('prev') }, '‹'),
1769
+ h('button', { type: 'button', className: 'dg-btn', key: 'next', onClick: () => onStep(1), 'aria-label': t('next') }, '›'),
1770
+ h('button', { type: 'button', className: 'dg-btn', key: 'close', onClick: onClose, 'aria-label': t('close') }, '✕'),
1771
+ ]),
1772
+ h('div', { className: 'dg-viewerStage', key: 'stage' }, [
1773
+ h('div', {
1774
+ className: `dg-viewerBody${isText ? ' dg-textBody' : ''}`,
1775
+ key: 'body',
1776
+ ref: bodyRef,
1777
+ 'data-gallery-zoom': isText ? 1 : zoom,
1778
+ 'data-gallery-text': isText ? true : undefined,
1779
+ style: isText
1780
+ ? { overflow: 'auto', cursor: 'default' }
1781
+ : {
1782
+ overflow: zoom > 1 ? 'hidden' : 'auto',
1783
+ cursor: zoom > 1 ? (dragging ? 'grabbing' : 'grab') : 'zoom-out',
1784
+ },
1785
+ onClick: isText ? undefined : onClickBody,
1786
+ onMouseDown: isText ? undefined : onMouseDown,
1787
+ onPointerDown: isText ? undefined : onPointerDown,
1788
+ onPointerMove: isText ? undefined : onPointerMove,
1789
+ onPointerUp: isText ? undefined : endDrag,
1790
+ onPointerLeave: isText ? undefined : endDrag,
1791
+ onPointerCancel: isText ? undefined : endDrag,
1792
+ onAuxClick: isText ? undefined : (event) => { if (event.button === 1) event.preventDefault() },
1793
+ },
1794
+ state.status === 'ready'
1795
+ ? (isText
1796
+ ? h('pre', { className: 'dg-textPre', key: 'text' }, state.text)
1797
+ : h('img', {
1798
+ src: state.url,
1799
+ alt: item.name,
1800
+ decoding: 'async',
1801
+ draggable: false,
1802
+ style: {
1803
+ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
1804
+ transition: dragRef.current === null ? 'transform 120ms ease-out' : 'none',
1805
+ userSelect: 'none',
1806
+ pointerEvents: 'none',
1807
+ },
1808
+ }))
1809
+ : state.status === 'binary'
1810
+ ? h('div', { className: 'dg-placeholder', key: 'bin' }, t('binaryHint'))
1811
+ : h('div', { className: state.status === 'failed' ? 'dg-placeholder dg-error' : 'dg-placeholder' },
1812
+ state.status === 'failed' ? `${t('thumbFailed')}:${item.name}` : t('loading')),
1813
+ ),
1814
+ slider,
1815
+ ]),
1816
+ h('div', { className: 'dg-viewerFoot', key: 'foot' },
1817
+ zoom > 1
1818
+ ? `${dims} · ${formatBytes(item.size)} · ${formatTime(item.mtime)} · ${t('dragHint')}`
1819
+ : `${dims} · ${formatBytes(item.size)} · ${formatTime(item.mtime)}`),
1820
+ ])
1821
+ }
1822
+
1823
+ /**
1824
+ * 设置面板:修改「产出根目录」。
1825
+ * 用户填一个绝对路径 → Host 校验 → 写入运行时配置 → 立即生效(不重启)。
1826
+ * 也可以点「恢复默认」,回到自动探测的结果。
1827
+ */
1828
+ function SettingsPanel({ t, onClose, onSaved }) {
1829
+ const [loading, setLoading] = React.useState(true)
1830
+ const [info, setInfo] = React.useState(null)
1831
+ const [draft, setDraft] = React.useState('')
1832
+ const [error, setError] = React.useState(null)
1833
+ const [saving, setSaving] = React.useState(false)
1834
+ const [saved, setSaved] = React.useState(false)
1835
+ // 全部恢复
1836
+ const [clearing, setClearing] = React.useState(false)
1837
+ const [hiddenCleared, setHiddenCleared] = React.useState(false)
1838
+ // 多目录增删
1839
+ const [adding, setAdding] = React.useState(false)
1840
+ const [removing, setRemoving] = React.useState(null)
1841
+
1842
+ React.useEffect(() => {
1843
+ let alive = true
1844
+ callHost('settings')
1845
+ .then((payload) => {
1846
+ if (!alive) return
1847
+ if (payload?.ok === false) throw new Error(payload?.error?.message ?? t('errorTitle'))
1848
+ const s = payload.settings
1849
+ setInfo(s)
1850
+ setDraft(s.root)
1851
+ setLoading(false)
1852
+ })
1853
+ .catch((e) => {
1854
+ if (!alive) return
1855
+ setError(String(e?.message ?? e))
1856
+ setLoading(false)
1857
+ })
1858
+ return () => { alive = false }
1859
+ }, [t])
1860
+
1861
+ const save = React.useCallback(async (nextRoot) => {
1862
+ setSaving(true)
1863
+ setError(null)
1864
+ setSaved(false)
1865
+ try {
1866
+ const payload = await callHost('setRoot', { root: nextRoot })
1867
+ if (payload?.ok === false) throw new Error(payload?.error?.message ?? t('errorTitle'))
1868
+ setInfo(payload.settings)
1869
+ setDraft(payload.settings.root)
1870
+ setSaved(true)
1871
+ setTimeout(() => setSaved(false), 2000)
1872
+ if (typeof onSaved === 'function') onSaved()
1873
+ } catch (e) {
1874
+ setError(String(e?.message ?? e))
1875
+ } finally {
1876
+ setSaving(false)
1877
+ }
1878
+ }, [t, onSaved])
1879
+
1880
+ /** 追加一个扫描目录。 */
1881
+ const addRoot = React.useCallback(async (nextRoot) => {
1882
+ if (typeof nextRoot !== 'string' || nextRoot.trim() === '') return
1883
+ setAdding(true)
1884
+ setError(null)
1885
+ try {
1886
+ const payload = await callHost('addRoot', { root: nextRoot.trim() })
1887
+ if (payload?.ok === false) throw new Error(payload?.error?.message ?? t('errorTitle'))
1888
+ setInfo(payload.settings)
1889
+ setDraft('')
1890
+ setSaved(true)
1891
+ setTimeout(() => setSaved(false), 2000)
1892
+ if (typeof onSaved === 'function') onSaved()
1893
+ } catch (e) {
1894
+ setError(String(e?.message ?? e))
1895
+ } finally {
1896
+ setAdding(false)
1897
+ }
1898
+ }, [t, onSaved])
1899
+
1900
+ /** 移除一个扫描目录(至少保留一个)。 */
1901
+ const removeRoot = React.useCallback(async (target) => {
1902
+ if (typeof target !== 'string' || target === '') return
1903
+ setRemoving(target)
1904
+ setError(null)
1905
+ try {
1906
+ const payload = await callHost('removeRoot', { root: target })
1907
+ if (payload?.ok === false) throw new Error(payload?.error?.message ?? t('errorTitle'))
1908
+ setInfo(payload.settings)
1909
+ setSaved(true)
1910
+ setTimeout(() => setSaved(false), 2000)
1911
+ if (typeof onSaved === 'function') onSaved()
1912
+ } catch (e) {
1913
+ setError(String(e?.message ?? e))
1914
+ } finally {
1915
+ setRemoving(null)
1916
+ }
1917
+ }, [t, onSaved])
1918
+
1919
+ const sourceLabel = React.useMemo(() => {
1920
+ if (info === null) return ''
1921
+ if (info.rootSource === 'settings') return t('rootSourceSettings')
1922
+ if (info.rootSource === 'config') return t('rootSourceConfig')
1923
+ return t('rootSourceAuto')
1924
+ }, [info, t])
1925
+
1926
+ /** 全部恢复:清空隐藏列表,让被隐藏的条目重新出现在列表里。 */
1927
+ const clearHidden = React.useCallback(async () => {
1928
+ if (info === null || info.hiddenCount === 0) return
1929
+ setClearing(true)
1930
+ setError(null)
1931
+ setHiddenCleared(false)
1932
+ try {
1933
+ const payload = await callHost('clearHidden', {})
1934
+ if (payload?.ok === false) throw new Error(payload?.error?.message ?? t('errorTitle'))
1935
+ // 重新拉一次设置,拿到最新的 hiddenCount
1936
+ const fresh = await callHost('settings')
1937
+ if (fresh?.ok !== false) setInfo(fresh.settings)
1938
+ setHiddenCleared(true)
1939
+ setTimeout(() => setHiddenCleared(false), 2000)
1940
+ if (typeof onSaved === 'function') onSaved()
1941
+ } catch (e) {
1942
+ setError(String(e?.message ?? e))
1943
+ } finally {
1944
+ setClearing(false)
1945
+ }
1946
+ }, [info, t, onSaved])
1947
+
1948
+ return h('div', { className: 'dg-settingsLayer', key: 'settingsLayer' }, [
1949
+ h('div', {
1950
+ className: 'dg-settings',
1951
+ key: 'panel',
1952
+ role: 'dialog',
1953
+ 'aria-modal': true,
1954
+ 'aria-label': t('settingsTitle'),
1955
+ 'data-gallery-settings-panel': true,
1956
+ }, [
1957
+ h('div', { className: 'dg-settingsHead', key: 'head' }, [
1958
+ h('span', { className: 'dg-settingsTitle', key: 'title' }, t('settingsTitle')),
1959
+ h('button', {
1960
+ type: 'button', className: 'dg-btn', key: 'close',
1961
+ 'aria-label': t('close'),
1962
+ onClick: onClose,
1963
+ }, '✕'),
1964
+ ]),
1965
+
1966
+ loading
1967
+ ? h('p', { className: 'dg-status', key: 'loading' }, t('loading'))
1968
+ : h('div', { className: 'dg-settingsBody', key: 'body' }, [
1969
+ // ---- 扫描目录列表(多目录)----
1970
+ h('div', { className: 'dg-field', key: 'roots' }, [
1971
+ h('div', { className: 'dg-fieldHead', key: 'head' }, [
1972
+ h('span', { className: 'dg-fieldLabel', key: 'l' },
1973
+ format(t('rootsLabel'), { count: info === null ? 0 : (info.roots?.length ?? 0) })),
1974
+ info === null ? null : h('span', { className: 'dg-fieldHint', key: 'h' },
1975
+ format(t('rootHint'), { source: sourceLabel })),
1976
+ ]),
1977
+ h('ul', { className: 'dg-rootsList', key: 'list', 'data-gallery-roots': info === null ? 0 : info.roots.length },
1978
+ (info?.rootsInfo ?? []).map((r, i) => h('li', {
1979
+ className: `dg-rootItem${r.exists ? '' : ' dg-rootItemMissing'}`,
1980
+ key: r.path,
1981
+ 'data-gallery-root-item': r.path,
1982
+ title: r.path,
1983
+ }, [
1984
+ h('span', { className: 'dg-rootOk', key: 'ok' }, r.exists ? '✓' : '✗'),
1985
+ h('span', { className: 'dg-rootPath', key: 'p' }, r.path),
1986
+ (info.roots?.length ?? 0) > 1
1987
+ ? h('button', {
1988
+ type: 'button',
1989
+ className: 'dg-rootRemove',
1990
+ key: 'rm',
1991
+ disabled: saving || removing === r.path,
1992
+ title: t('removeRootHint'),
1993
+ 'aria-label': t('removeRootHint'),
1994
+ 'data-gallery-root-remove': r.path,
1995
+ onClick: () => { void removeRoot(r.path) },
1996
+ }, '✕')
1997
+ : null,
1998
+ ])),
1999
+ ),
2000
+ // 添加新目录
2001
+ h('div', { className: 'dg-rootAdd', key: 'add' }, [
2002
+ h('input', {
2003
+ type: 'text',
2004
+ className: 'dg-input dg-rootInput',
2005
+ key: 'i',
2006
+ value: draft,
2007
+ spellCheck: false,
2008
+ placeholder: t('rootAddPlaceholder'),
2009
+ 'data-gallery-root-input': true,
2010
+ onChange: (event) => setDraft(event.target.value),
2011
+ onKeyDown: (event) => {
2012
+ if (event.key === 'Enter' && saving === false) { event.preventDefault(); void addRoot(draft) }
2013
+ },
2014
+ }),
2015
+ h('button', {
2016
+ type: 'button',
2017
+ className: 'dg-btn dg-primaryBtn',
2018
+ key: 'btn',
2019
+ disabled: saving || draft.trim() === '',
2020
+ 'data-gallery-root-add': true,
2021
+ onClick: () => { void addRoot(draft) },
2022
+ }, adding ? t('addingRoot') : t('addRoot')),
2023
+ ]),
2024
+ h('span', { className: 'dg-fieldHint', key: 'tip' }, t('rootsTip')),
2025
+ ]),
2026
+
2027
+ info === null ? null : h('div', { className: 'dg-settingsMeta', key: 'meta' }, [
2028
+ h('span', { key: 'status' },
2029
+ info.rootExists ? t('rootExists') : t('rootMissingShort')),
2030
+ h('span', { key: 'file' },
2031
+ format(t('settingsFileAt'), { path: info.settingsFile })),
2032
+ ]),
2033
+
2034
+ // ---- 已隐藏条目管理 ----
2035
+ info === null ? null : h('div', { className: 'dg-hiddenBox', key: 'hiddenBox', 'data-gallery-hidden-box': info.hiddenCount }, [
2036
+ h('div', { className: 'dg-hiddenRow', key: 'row' }, [
2037
+ h('span', { className: 'dg-hiddenLabel', key: 'label' },
2038
+ format(t('hiddenCount'), { count: info.hiddenCount })),
2039
+ h('button', {
2040
+ type: 'button',
2041
+ className: 'dg-btn',
2042
+ key: 'clear',
2043
+ 'data-gallery-clear-hidden': true,
2044
+ disabled: clearing || info.hiddenCount === 0,
2045
+ title: t('hiddenClearHint'),
2046
+ onClick: () => { void clearHidden() },
2047
+ }, clearing ? t('hiddenClearing') : t('hiddenClear')),
2048
+ ]),
2049
+ info.hiddenCount > 0 && Array.isArray(info.hiddenSample) && info.hiddenSample.length > 0
2050
+ ? h('ul', { className: 'dg-hiddenList', key: 'list' },
2051
+ info.hiddenSample.map((p) => h('li', { className: 'dg-hiddenItem', key: p, title: p }, p)))
2052
+ : null,
2053
+ info.hiddenCount > info.hiddenSample?.length
2054
+ ? h('div', { className: 'dg-hiddenMore', key: 'more' },
2055
+ format(t('hiddenMore'), { count: info.hiddenCount - info.hiddenSample.length }))
2056
+ : null,
2057
+ hiddenCleared
2058
+ ? h('p', { className: 'dg-status dg-ok', key: 'cleared' }, t('hiddenCleared'))
2059
+ : null,
2060
+ ]),
2061
+
2062
+ error === null ? null : h('p', { className: 'dg-status dg-error', key: 'err' }, error),
2063
+ saved ? h('p', { className: 'dg-status dg-ok', key: 'ok' }, t('savedImmediately')) : null,
2064
+
2065
+ h('div', { className: 'dg-settingsActions', key: 'actions' }, [
2066
+ h('button', {
2067
+ type: 'button', className: 'dg-btn', key: 'reset',
2068
+ disabled: saving || info === null,
2069
+ title: t('resetDefaultHint'),
2070
+ onClick: () => { if (info !== null) { setDraft(info.defaults.root); void save(info.defaults.root) } },
2071
+ }, t('resetDefault')),
2072
+ h('button', {
2073
+ type: 'button', className: 'dg-btn dg-primaryBtn', key: 'close2',
2074
+ onClick: onClose,
2075
+ }, t('done')),
2076
+ ]),
2077
+ ]),
2078
+ ]),
2079
+ ])
2080
+ }
2081
+
2082
+ /** 画廊正文:Header(刷新)+ 网格 + 面板内放大。 */
2083
+ function GalleryBody(props) {
2084
+ const { t, sessionId } = props
2085
+ const [view, setView] = React.useState({ status: 'loading' })
2086
+ const [refreshing, setRefreshing] = React.useState(false)
2087
+ const [viewer, setViewer] = React.useState(null)
2088
+ const limiter = React.useRef(null)
2089
+ if (limiter.current === null) limiter.current = createLimiter(MAX_CONCURRENT)
2090
+
2091
+ const load = React.useCallback(async (signal, kind = 'image', scope = 'global', page = 1) => {
2092
+ const payload = await callHost('list', { kind, scope, sessionId, page }, signal)
2093
+ if (payload?.ok === false) throw new Error(payload?.error?.message ?? t('errorTitle'))
2094
+ return payload
2095
+ }, [t, sessionId])
2096
+
2097
+ const [kind, setKind] = React.useState('image')
2098
+ // 分类:全局资产(整个 G 盘产出)/ 当前对话(仅本对话产出过的)
2099
+ // 从「当前对话」切回「全局」时保留上次选择,但不持久化,避免误导。
2100
+ const [scope, setScope] = React.useState('global')
2101
+ // 当前页码(从 1 开始)。切换 kind / scope 时回到第 1 页。
2102
+ const [page, setPage] = React.useState(1)
2103
+ // 设置面板开关(改产出根目录)
2104
+ const [settingsOpen, setSettingsOpen] = React.useState(false)
2105
+ // 右键菜单:{ item, absPath, x, y }
2106
+ const [ctxMenu, setCtxMenu] = React.useState(null)
2107
+ // 删除确认:{ item, busy }
2108
+ const [deleteTarget, setDeleteTarget] = React.useState(null)
2109
+ // 网格滚动位置:打开查看器前记录,关闭后恢复,让视图停在原缩略图处
2110
+ const bodyScrollRef = React.useRef(null)
2111
+ const savedScrollRef = React.useRef(null)
2112
+
2113
+ /** 打开右键菜单。 */
2114
+ const openContextMenu = React.useCallback((item, absPath, event) => {
2115
+ setCtxMenu({
2116
+ item,
2117
+ absPath: absPath ?? buildAbsPath(view.status === 'ready' ? view.data.root : '', item.relPath),
2118
+ x: event.clientX,
2119
+ y: event.clientY,
2120
+ })
2121
+ }, [view])
2122
+
2123
+ const closeContextMenu = React.useCallback(() => setCtxMenu(null), [])
2124
+
2125
+ /** 打开某张图:先记住当前滚动位置。 */
2126
+ const openViewer = React.useCallback((index, anchorEl) => {
2127
+ const scroller = bodyScrollRef.current
2128
+ if (scroller !== null) {
2129
+ savedScrollRef.current = {
2130
+ top: scroller.scrollTop,
2131
+ // 记录被点中的卡片相对滚动容器的偏移,用于精确回位
2132
+ offset: anchorEl !== null && anchorEl !== undefined
2133
+ ? anchorEl.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop
2134
+ : null,
2135
+ }
2136
+ }
2137
+ setViewer({ index })
2138
+ }, [])
2139
+
2140
+ /** 关闭查看器:恢复到原来那张缩略图的位置。 */
2141
+ const closeViewer = React.useCallback(() => {
2142
+ setViewer(null)
2143
+ const saved = savedScrollRef.current
2144
+ if (saved === null) return
2145
+ // 等覆盖层卸载、网格重新可见后再滚
2146
+ requestAnimationFrame(() => {
2147
+ const scroller = bodyScrollRef.current
2148
+ if (scroller === null) return
2149
+ const top = saved.offset !== null && saved.offset !== undefined ? saved.offset : saved.top
2150
+ scroller.scrollTop = Math.max(0, top)
2151
+ savedScrollRef.current = null
2152
+ })
2153
+ }, [])
2154
+
2155
+ /** 隐藏当前右键的条目(只从列表移除,不动文件)。 */
2156
+ const doHide = React.useCallback(async (item) => {
2157
+ try {
2158
+ const payload = await callHost('hide', { path: item.relPath })
2159
+ if (payload?.ok === false) throw new Error(payload?.error?.message ?? t('errorTitle'))
2160
+ await load(undefined, kind, scope, page).then((data) => setView({ status: 'ready', data })).catch(() => {})
2161
+ } catch (error) {
2162
+ console.error('dsh-gallery: 隐藏失败', error)
2163
+ }
2164
+ }, [load, kind, scope, page, t])
2165
+
2166
+ /** 在资源管理器里定位。 */
2167
+ const doReveal = React.useCallback(async (item) => {
2168
+ try {
2169
+ const payload = await callHost('reveal', { path: item.relPath })
2170
+ if (payload?.ok === false) throw new Error(payload?.error?.message ?? t('errorTitle'))
2171
+ } catch (error) {
2172
+ console.error('dsh-gallery: reveal 失败', error)
2173
+ }
2174
+ }, [t])
2175
+
2176
+ /** 执行删除(需二次确认)。 */
2177
+ const doDelete = React.useCallback(async () => {
2178
+ const target = deleteTarget
2179
+ if (target === null || target.busy === true) return
2180
+ setDeleteTarget({ ...target, busy: true })
2181
+ try {
2182
+ const payload = await callHost('delete', { path: target.item.relPath, confirm: true })
2183
+ if (payload?.ok === false) throw new Error(payload?.error?.message ?? t('errorTitle'))
2184
+ setDeleteTarget(null)
2185
+ await load(undefined, kind, scope, page).then((data) => setView({ status: 'ready', data })).catch(() => {})
2186
+ } catch (error) {
2187
+ console.error('dsh-gallery: 删除失败', error)
2188
+ setDeleteTarget(null)
2189
+ }
2190
+ }, [deleteTarget, load, kind, scope, page, t])
2191
+
2192
+ const refresh = React.useCallback(async () => {
2193
+ setRefreshing(true)
2194
+ try {
2195
+ setView({ status: 'ready', data: await load(undefined, kind, scope, page) })
2196
+ } catch (error) {
2197
+ if (error?.name === 'AbortError') return
2198
+ setView({ status: 'failed', message: String(error?.message ?? error) })
2199
+ } finally {
2200
+ setRefreshing(false)
2201
+ }
2202
+ }, [load, kind, scope, page])
2203
+
2204
+ React.useEffect(() => {
2205
+ let alive = true
2206
+ const controller = new AbortController()
2207
+ load(controller.signal, kind, scope, page)
2208
+ .then((data) => {
2209
+ if (alive) setView({ status: 'ready', data })
2210
+ })
2211
+ .catch((error) => {
2212
+ if (alive && error?.name !== 'AbortError') setView({ status: 'failed', message: String(error?.message ?? error) })
2213
+ })
2214
+ return () => {
2215
+ alive = false
2216
+ controller.abort()
2217
+ }
2218
+ }, [load, kind, scope, page])
2219
+
2220
+ // 自动刷新:定时拉取最新列表;查看器打开时暂停,避免打断放大查看
2221
+ React.useEffect(() => {
2222
+ if (viewer !== null) return undefined
2223
+ let alive = true
2224
+ const timer = setInterval(() => {
2225
+ if (!alive) return
2226
+ load(undefined, kind, scope, page)
2227
+ .then((data) => { if (alive) setView({ status: 'ready', data }) })
2228
+ .catch(() => { /* 自动刷新失败保持现有列表,避免闪错 */ })
2229
+ }, AUTO_REFRESH_MS)
2230
+ return () => {
2231
+ alive = false
2232
+ clearInterval(timer)
2233
+ }
2234
+ }, [load, kind, scope, page, viewer])
2235
+
2236
+ React.useEffect(() => {
2237
+ if (viewer === null) return undefined
2238
+ const onKey = (event) => {
2239
+ if (event.key === 'Escape') {
2240
+ event.preventDefault()
2241
+ setViewer(null)
2242
+ }
2243
+ }
2244
+ window.addEventListener('keydown', onKey)
2245
+ return () => window.removeEventListener('keydown', onKey)
2246
+ }, [viewer])
2247
+
2248
+ const data = view.status === 'ready' ? view.data : null
2249
+ const items = data?.items ?? []
2250
+ const step = React.useCallback((delta) => {
2251
+ setViewer((current) => current === null ? null : {
2252
+ index: (current.index + delta + items.length) % items.length,
2253
+ })
2254
+ }, [items.length])
2255
+
2256
+ // 分类开关:全局资产 / 当前对话
2257
+ const scopeSwitch = h('div', { className: 'dg-scopeSwitch', key: 'scope' }, [
2258
+ h('button', {
2259
+ type: 'button',
2260
+ key: 'global',
2261
+ className: `dg-scopeBtn${scope === 'global' ? ' dg-scopeActive' : ''}`,
2262
+ 'data-gallery-scope': 'global',
2263
+ title: t('scopeGlobalHint'),
2264
+ onClick: () => { if (scope !== 'global') { setScope('global'); setPage(1); setViewer(null) } },
2265
+ }, t('scopeGlobal')),
2266
+ h('button', {
2267
+ type: 'button',
2268
+ key: 'session',
2269
+ className: `dg-scopeBtn${scope === 'session' ? ' dg-scopeActive' : ''}`,
2270
+ 'data-gallery-scope': 'session',
2271
+ title: t('scopeSessionHint'),
2272
+ onClick: () => { if (scope !== 'session') { setScope('session'); setPage(1); setViewer(null) } },
2273
+ }, t('scopeSession')),
2274
+ ])
2275
+
2276
+ // 设置按钮:打开产出根目录设置面板
2277
+ const settingsBtn = h('button', {
2278
+ type: 'button',
2279
+ key: 'settings',
2280
+ className: 'dg-btn dg-btnIcon',
2281
+ 'data-gallery-settings': true,
2282
+ title: t('settingsTitle'),
2283
+ onClick: () => setSettingsOpen(true),
2284
+ }, '⚙')
2285
+
2286
+ const header = h('div', { className: 'dg-header', key: 'header' }, [
2287
+ h('div', { className: 'dg-headerInfo', key: 'info' }, [
2288
+ h('span', { className: 'dg-title', key: 'title' },
2289
+ scope === 'session' ? t('scopeSession') : t('scopeGlobal')),
2290
+ h('span', { className: 'dg-sub', key: 'sub' },
2291
+ data === null
2292
+ ? (view.status === 'failed' ? t('errorTitle') : t('loading'))
2293
+ : format(t('subCount'), { shown: items.length, total: data.total })),
2294
+ ]),
2295
+ scopeSwitch,
2296
+ // 图片 / 文件 双画廊切换
2297
+ h('div', { className: 'dg-switch', key: 'switch' }, [
2298
+ h('button', {
2299
+ type: 'button',
2300
+ key: 'img',
2301
+ className: `dg-seg${kind === 'image' ? ' dg-segActive' : ''}`,
2302
+ 'data-gallery-kind': 'image',
2303
+ onClick: () => { setKind('image'); setPage(1); setViewer(null) },
2304
+ }, t('kindImage')),
2305
+ h('button', {
2306
+ type: 'button',
2307
+ key: 'file',
2308
+ className: `dg-seg${kind === 'file' ? ' dg-segActive' : ''}`,
2309
+ 'data-gallery-kind': 'file',
2310
+ onClick: () => { setKind('file'); setPage(1); setViewer(null) },
2311
+ }, t('kindFile')),
2312
+ ]),
2313
+ settingsBtn,
2314
+ h('button', {
2315
+ type: 'button',
2316
+ className: 'dg-btn',
2317
+ key: 'refresh',
2318
+ 'data-gallery-refresh': true,
2319
+ disabled: refreshing,
2320
+ onClick: () => { void refresh() },
2321
+ }, refreshing ? t('refreshing') : t('refresh')),
2322
+ ])
2323
+
2324
+ let body
2325
+ if (view.status === 'loading') {
2326
+ body = h('div', { className: 'dg-body', key: 'body' }, h('p', { className: 'dg-status' }, t('loading')))
2327
+ } else if (view.status === 'failed') {
2328
+ body = h('div', { className: 'dg-body', key: 'body' }, [
2329
+ h('p', { className: 'dg-status dg-error', key: 'msg' }, `${t('errorTitle')}:${view.message}`),
2330
+ h('p', { className: 'dg-status', key: 'retry' },
2331
+ h('button', { type: 'button', className: 'dg-btn', onClick: () => { void refresh() } }, t('retry'))),
2332
+ ])
2333
+ } else if (data !== null && data.rootMissing) {
2334
+ // 目录不存在是最常见的「装上打不开」原因:直接给出改目录入口
2335
+ body = h('div', { className: 'dg-body', key: 'body' }, [
2336
+ h('p', { className: 'dg-status', key: 'msg' },
2337
+ format(t('rootMissing'), { root: data.root })),
2338
+ h('p', { className: 'dg-status dg-statusAction', key: 'fix' },
2339
+ h('button', {
2340
+ type: 'button',
2341
+ className: 'dg-btn dg-primaryBtn',
2342
+ 'data-gallery-fix-root': true,
2343
+ onClick: () => setSettingsOpen(true),
2344
+ }, t('changeRoot'))),
2345
+ ])
2346
+ } else if (items.length === 0) {
2347
+ // 当前对话为空时,要区分:会话记录没找到 / 日志空 / 找到了但确实没产出
2348
+ // 全局为空时,按画廊类型给不同文案(图片 / 文件)
2349
+ let emptyText = kind === 'file' ? t('emptyFile') : t('empty')
2350
+ if (scope === 'session' && data !== null) {
2351
+ const info = data.scopeInfo ?? {}
2352
+ if (info.ok === false) {
2353
+ emptyText = info.reason === 'session-not-found' ? t('scopeNotFound') : t('scopeLogEmpty')
2354
+ } else if (info.taskDirs === 0) {
2355
+ emptyText = t('scopeUnknown')
2356
+ } else {
2357
+ emptyText = t('emptySession')
2358
+ }
2359
+ }
2360
+ body = h('div', { className: 'dg-body', key: 'body' },
2361
+ h('p', { className: 'dg-status' }, emptyText))
2362
+ } else {
2363
+ const gridChildren = items.map((item) => kind === 'file'
2364
+ ? h(FileCard, {
2365
+ key: item.relPath,
2366
+ item,
2367
+ t,
2368
+ absPath: buildAbsPath(data.root, item.relPath),
2369
+ onOpenFolder: (abs) => { void callHost('reveal', { path: item.relPath }).catch((e) => console.error('dsh-gallery: reveal 失败', e)) },
2370
+ onContextMenu: openContextMenu,
2371
+ onPreview: (abs) => {
2372
+ const address = sessionFileAddressOf(sessionId, abs)
2373
+ try {
2374
+ ctxRef.current.sidebarRight.openResource(address, { kind: 'text' })
2375
+ } catch (error) {
2376
+ console.error('dsh-gallery: 侧栏预览失败', error, address)
2377
+ // 兜底:至少把路径复制给用户
2378
+ void copyText(abs)
2379
+ }
2380
+ },
2381
+ })
2382
+ : h(Card, {
2383
+ key: item.relPath,
2384
+ item,
2385
+ t,
2386
+ limiter: limiter.current,
2387
+ onContextMenu: openContextMenu,
2388
+ onOpen: (opened, anchorEl) => openViewer(items.indexOf(opened), anchorEl),
2389
+ }))
2390
+ // 网格区外面包一层定位容器,右侧放滚动辅助列(无滚轮场景用)
2391
+ body = h('div', { className: 'dg-bodyWrap', key: 'bodyWrap' }, [
2392
+ h('div', {
2393
+ className: `dg-body${kind === 'file' ? ' dg-fileBody' : ''}`,
2394
+ key: 'body',
2395
+ 'data-gallery-body': true,
2396
+ ref: bodyScrollRef,
2397
+ }, [
2398
+ h('div', { className: `dg-grid${kind === 'file' ? ' dg-fileGrid' : ''}`, key: 'grid' }, gridChildren),
2399
+ data.scan.capped
2400
+ ? h('div', { className: 'dg-more', key: 'capped' }, t('capped'))
2401
+ : null,
2402
+ ]),
2403
+ h(ScrollRail, {
2404
+ key: 'rail',
2405
+ scrollerRef: bodyScrollRef,
2406
+ t,
2407
+ railClassName: kind === 'file' ? 'dg-panRailFiles' : '',
2408
+ }),
2409
+ ])
2410
+ }
2411
+
2412
+ // 分页条:常驻显示「还有 X 张」+ 页码。单页时只显示总数,不渲染页码按钮。
2413
+ const pager = data !== null && items.length > 0
2414
+ ? h(Pager, {
2415
+ key: 'pager',
2416
+ t,
2417
+ page: data.page ?? 1,
2418
+ pageCount: data.pageCount ?? 1,
2419
+ pageSize: data.pageSize ?? items.length,
2420
+ total: data.total,
2421
+ remaining: data.hidden,
2422
+ onGo: (next) => {
2423
+ if (next === page) return
2424
+ // 翻页时回到顶部,避免停在新页中段
2425
+ const scroller = bodyScrollRef.current
2426
+ if (scroller !== null) scroller.scrollTop = 0
2427
+ savedScrollRef.current = null
2428
+ setViewer(null)
2429
+ setPage(next)
2430
+ },
2431
+ })
2432
+ : null
2433
+
2434
+ // 查看器作为覆盖层叠在网格上:网格保持挂载,滚动位置不丢
2435
+ const viewerLayer = viewer !== null && items.length > 0
2436
+ ? h('div', { className: 'dg-viewerLayer', key: 'viewerLayer' },
2437
+ h(Viewer, {
2438
+ items,
2439
+ index: viewer.index,
2440
+ t,
2441
+ onClose: closeViewer,
2442
+ onStep: step,
2443
+ }))
2444
+ : null
2445
+
2446
+ // 设置面板:覆盖在整块之上
2447
+ const settingsLayer = settingsOpen
2448
+ ? h(SettingsPanel, {
2449
+ key: 'settingsPanel',
2450
+ t,
2451
+ onClose: () => setSettingsOpen(false),
2452
+ onSaved: () => { void refresh() },
2453
+ })
2454
+ : null
2455
+
2456
+ // 右键菜单
2457
+ const ctxLayer = ctxMenu !== null
2458
+ ? h(ContextMenu, {
2459
+ key: 'ctxMenu',
2460
+ t,
2461
+ x: ctxMenu.x,
2462
+ y: ctxMenu.y,
2463
+ item: ctxMenu.item,
2464
+ onClose: closeContextMenu,
2465
+ actions: {
2466
+ onHide: () => { void doHide(ctxMenu.item) },
2467
+ onReveal: () => { void doReveal(ctxMenu.item) },
2468
+ onCopy: () => { void copyText(ctxMenu.absPath) },
2469
+ onDelete: () => setDeleteTarget({ item: ctxMenu.item, busy: false }),
2470
+ },
2471
+ })
2472
+ : null
2473
+
2474
+ // 删除确认弹窗
2475
+ const confirmLayer = deleteTarget !== null
2476
+ ? h(ConfirmDialog, {
2477
+ key: 'confirmLayer',
2478
+ t,
2479
+ name: deleteTarget.item.name,
2480
+ busy: deleteTarget.busy === true,
2481
+ onCancel: () => setDeleteTarget(null),
2482
+ onConfirm: () => { void doDelete() },
2483
+ })
2484
+ : null
2485
+
2486
+ return h('div', { className: 'dg-root', 'data-gallery-root': true }, [
2487
+ header,
2488
+ body,
2489
+ pager,
2490
+ viewerLayer,
2491
+ settingsLayer,
2492
+ ctxLayer,
2493
+ confirmLayer,
2494
+ ])
2495
+ }
2496
+
2497
+ /**
2498
+ * 分页条:常驻在网格下方。
2499
+ * 左边「还有 X 张」说清总量分布,右边页码点击切页。
2500
+ * 单页时也渲染(只显示「共 N 张」),保持视觉稳定。
2501
+ */
2502
+ function Pager({ t, page, pageCount, pageSize, total, remaining, onGo }) {
2503
+ const start = total === 0 ? 0 : (page - 1) * pageSize + 1
2504
+ const end = Math.min(page * pageSize, total)
2505
+
2506
+ // 页码按钮:页数很多时折叠,始终露出首末页与当前页邻域
2507
+ const numbers = React.useMemo(() => {
2508
+ if (pageCount <= 7) return Array.from({ length: pageCount }, (_, i) => i + 1)
2509
+ const set = new Set([1, pageCount, page, page - 1, page + 1])
2510
+ if (page <= 3) [2, 3, 4].forEach((n) => set.add(n))
2511
+ if (page >= pageCount - 2) [pageCount - 1, pageCount - 2, pageCount - 3].forEach((n) => set.add(n))
2512
+ const sorted = [...set].filter((n) => n >= 1 && n <= pageCount).sort((a, b) => a - b)
2513
+ // 插入省略号
2514
+ const out = []
2515
+ let prev = 0
2516
+ for (const n of sorted) {
2517
+ if (prev !== 0 && n - prev > 1) out.push('…' + n)
2518
+ out.push(n)
2519
+ prev = n
2520
+ }
2521
+ return out
2522
+ }, [page, pageCount])
2523
+
2524
+ const kids = []
2525
+ kids.push(h('span', {
2526
+ className: 'dg-pagerInfo',
2527
+ key: 'info',
2528
+ 'data-gallery-page-info': true,
2529
+ }, format(t('pagerRange'), { start, end, total })))
2530
+
2531
+ if (remaining > 0) {
2532
+ kids.push(h('span', {
2533
+ className: 'dg-pagerRemain',
2534
+ key: 'remain',
2535
+ 'data-gallery-more': remaining,
2536
+ }, format(t('more'), { count: remaining })))
2537
+ }
2538
+
2539
+ if (pageCount > 1) {
2540
+ const btn = (key, label, target, extra) => h('button', {
2541
+ type: 'button',
2542
+ key,
2543
+ className: `dg-pageBtn${extra ? ' ' + extra : ''}${target === page ? ' dg-pageActive' : ''}`,
2544
+ 'data-gallery-page': target,
2545
+ disabled: target === page && extra !== 'nav',
2546
+ title: format(t('pageTip'), { page: target }),
2547
+ onClick: () => onGo(target),
2548
+ }, label)
2549
+
2550
+ kids.push(h('div', { className: 'dg-pagerBtns', key: 'btns' }, [
2551
+ btn('prev', '‹', Math.max(1, page - 1), 'nav'),
2552
+ ...numbers.map((n) => typeof n === 'number'
2553
+ ? btn('p' + n, String(n), n)
2554
+ : h('span', { className: 'dg-pageGap', key: 'gap' + n }, '…')),
2555
+ btn('next', '›', Math.min(pageCount, page + 1), 'nav'),
2556
+ ]))
2557
+ }
2558
+
2559
+ return h('div', { className: 'dg-pager', key: 'pagerBar', 'data-gallery-pager': page }, kids)
2560
+ }
2561
+
2562
+ /**
2563
+ * 通用滚动辅助列:▲ + 轨道 + ▼。
2564
+ * 用于没有滚轮的场景(远程控制 / 触屏),列表页与放大页共用同一套交互。
2565
+ *
2566
+ * @param scrollerRef - 指向上层滚动容器(带 overflow 的那个 div)的 ref。
2567
+ * @param t - 文案函数。
2568
+ * @param onChange - 可选,滚动位置变化后的回调(放大页用它同步 pan)。
2569
+ * @param zoom - 放大页传当前倍率;列表页不传(按 1 处理,滑块按内容比例)。
2570
+ */
2571
+ function ScrollRail({ scrollerRef, t, onChange, zoom = 1, trackClassName = '', railClassName = '' }) {
2572
+ const [metrics, setMetrics] = React.useState({ scrollTop: 0, scrollHeight: 0, clientHeight: 0 })
2573
+ const thumbDragRef = React.useRef(null)
2574
+
2575
+ const measure = React.useCallback(() => {
2576
+ const el = scrollerRef.current
2577
+ if (el === null) return
2578
+ setMetrics({
2579
+ scrollTop: el.scrollTop,
2580
+ scrollHeight: el.scrollHeight,
2581
+ clientHeight: el.clientHeight,
2582
+ })
2583
+ }, [scrollerRef])
2584
+
2585
+ // 监听滚动与尺寸变化,让滑块跟手
2586
+ React.useEffect(() => {
2587
+ const el = scrollerRef.current
2588
+ if (el === null) return undefined
2589
+ measure()
2590
+ el.addEventListener('scroll', measure, { passive: true })
2591
+ const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(measure) : null
2592
+ if (ro !== null) {
2593
+ ro.observe(el)
2594
+ // 内容(网格)高度变化也要重算:缩略图异步加载会改变 scrollHeight
2595
+ for (const child of el.children) ro.observe(child)
2596
+ }
2597
+ // 缩略图陆续加载完成时高度会跳动,补几个延时测量
2598
+ const timers = [80, 300, 900, 2000].map((ms) => setTimeout(measure, ms))
2599
+ window.addEventListener('resize', measure)
2600
+ return () => {
2601
+ el.removeEventListener('scroll', measure)
2602
+ if (ro !== null) ro.disconnect()
2603
+ for (const t of timers) clearTimeout(t)
2604
+ window.removeEventListener('resize', measure)
2605
+ }
2606
+ }, [scrollerRef, measure])
2607
+
2608
+ const maxScroll = Math.max(0, metrics.scrollHeight - metrics.clientHeight)
2609
+ const canScroll = maxScroll > 1
2610
+ const trackH = Math.max(1, metrics.clientHeight)
2611
+ // 滑块高度按「可视 / 总内容」比例,至少 28px 保证可点
2612
+ const thumbH = metrics.scrollHeight <= 0
2613
+ ? trackH
2614
+ : Math.max(28, Math.min(trackH, (metrics.clientHeight / metrics.scrollHeight) * trackH))
2615
+ const travel = Math.max(1, trackH - thumbH)
2616
+ const progress = maxScroll <= 0 ? 0 : metrics.scrollTop / maxScroll
2617
+ const thumbTop = travel * progress
2618
+
2619
+ /** 滚到指定 scrollTop(0..maxScroll)。 */
2620
+ const scrollTo = (value) => {
2621
+ const el = scrollerRef.current
2622
+ if (el === null) return
2623
+ el.scrollTop = Math.max(0, Math.min(maxScroll, value))
2624
+ measure()
2625
+ if (typeof onChange === 'function') onChange()
2626
+ }
2627
+
2628
+ /** 步进:一次半屏,远程操作下比滚轮更省力。 */
2629
+ const step = (direction) => scrollTo(metrics.scrollTop + direction * (metrics.clientHeight * 0.75))
2630
+
2631
+ // 点轨道空白处直接跳转
2632
+ const onTrackClick = (event) => {
2633
+ event.preventDefault()
2634
+ event.stopPropagation()
2635
+ const rect = event.currentTarget.getBoundingClientRect()
2636
+ const ratio = (event.clientY - rect.top) / Math.max(1, rect.height)
2637
+ scrollTo(ratio * maxScroll)
2638
+ }
2639
+
2640
+ // 拖滑块
2641
+ const onThumbDown = (event) => {
2642
+ event.preventDefault()
2643
+ event.stopPropagation()
2644
+ thumbDragRef.current = { startY: event.clientY, startTop: metrics.scrollTop }
2645
+ try { event.currentTarget.setPointerCapture(event.pointerId) } catch {}
2646
+ }
2647
+ const onThumbMove = (event) => {
2648
+ const d = thumbDragRef.current
2649
+ if (d === null) return
2650
+ event.preventDefault()
2651
+ const deltaPx = event.clientY - d.startY
2652
+ scrollTo(d.startTop + (deltaPx * maxScroll) / travel)
2653
+ }
2654
+ const onThumbUp = (event) => {
2655
+ if (thumbDragRef.current === null) return
2656
+ thumbDragRef.current = null
2657
+ if (event !== undefined) {
2658
+ try { event.currentTarget.releasePointerCapture(event.pointerId) } catch {}
2659
+ }
2660
+ }
2661
+
2662
+ const atTop = metrics.scrollTop <= 1
2663
+ const atBottom = metrics.scrollTop >= maxScroll - 1
2664
+
2665
+ // 没有可滚动空间时不占位(避免列表很短时多出一列空栏)
2666
+ if (!canScroll) return null
2667
+
2668
+ return h('div', {
2669
+ className: `dg-panRail ${railClassName}`.trim(),
2670
+ key: 'scrollRail',
2671
+ 'data-gallery-scrollrail': true,
2672
+ onPointerDown: (event) => event.stopPropagation(),
2673
+ onClick: (event) => event.stopPropagation(),
2674
+ }, [
2675
+ h('button', {
2676
+ type: 'button', className: 'dg-panBtn', key: 'up',
2677
+ 'data-gallery-scroll': 'up',
2678
+ disabled: atTop,
2679
+ title: t('panUpHint'), 'aria-label': t('panUpHint'),
2680
+ onClick: (event) => { event.stopPropagation(); step(-1) },
2681
+ }, '▲'),
2682
+ h('div', {
2683
+ className: `dg-dragTrack ${trackClassName}`.trim(),
2684
+ key: 'track',
2685
+ title: t('trackHint'),
2686
+ onClick: onTrackClick,
2687
+ }, h('div', {
2688
+ className: 'dg-dragThumb',
2689
+ key: 'thumb',
2690
+ 'data-gallery-scrollthumb': true,
2691
+ role: 'slider',
2692
+ 'aria-orientation': 'vertical',
2693
+ style: { height: `${Math.round(thumbH)}px`, transform: `translateY(${Math.round(thumbTop)}px)` },
2694
+ onPointerDown: onThumbDown,
2695
+ onPointerMove: onThumbMove,
2696
+ onPointerUp: onThumbUp,
2697
+ onPointerCancel: onThumbUp,
2698
+ })),
2699
+ h('button', {
2700
+ type: 'button', className: 'dg-panBtn', key: 'down',
2701
+ 'data-gallery-scroll': 'down',
2702
+ disabled: atBottom,
2703
+ title: t('panDownHint'), 'aria-label': t('panDownHint'),
2704
+ onClick: (event) => { event.stopPropagation(); step(1) },
2705
+ }, '▼'),
2706
+ ])
2707
+ }
2708
+
2709
+ /** tab 标题(chip / 浮动面板标题)。 */
2710
+ function GalleryTitle({ t }) {
2711
+ return h('span', { className: 'dg-title' }, t('type.label'))
2712
+ }
2713
+
2714
+ /** 侧栏脚部入口按钮:点击打开画廊 tab。 */
2715
+ function OpenButton({ t, wide }) {
2716
+ return h('button', {
2717
+ type: 'button',
2718
+ className: 'dg-btn dg-open',
2719
+ 'data-gallery-open': true,
2720
+ title: t('type.label'),
2721
+ 'aria-label': t('type.label'),
2722
+ onClick: () => {
2723
+ try {
2724
+ ctxRef.current?.sidebarRight.openTab(KIND)
2725
+ } catch (error) {
2726
+ console.error('dsh-gallery: open failed', error)
2727
+ }
2728
+ },
2729
+ }, wide ? t('type.label') : '▦')
2730
+ }
2731
+
2732
+ /** 对话区入口:编辑框右侧的紧凑按钮。 */
2733
+ function ComposerButton({ t }) {
2734
+ return h('button', {
2735
+ type: 'button',
2736
+ className: 'dg-btn dg-openCompact',
2737
+ 'data-gallery-open-composer': true,
2738
+ title: t('type.label'),
2739
+ 'aria-label': t('type.label'),
2740
+ onClick: () => {
2741
+ try {
2742
+ ctxRef.current?.sidebarRight.openTab(KIND)
2743
+ } catch (error) {
2744
+ console.error('dsh-gallery: open failed', error)
2745
+ }
2746
+ },
2747
+ }, '▦')
2748
+ }
2749
+
2750
+ return {
2751
+ inject: ['slots', 'locale', 'sidebarRightTabs', 'sidebarRight'],
2752
+ apply(ctx) {
2753
+ ctxRef.current = ctx
2754
+ ctx.effect(() => () => { ctxRef.current = null }, 'dsh-gallery: context handle')
2755
+ const t = ctx.locale.bind(NS)
2756
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-gallery: dictionaries')
2757
+
2758
+ ctx.effect(() => {
2759
+ const tag = document.createElement('style')
2760
+ tag.dataset.plugin = 'dsh-gallery'
2761
+ tag.dataset.pluginCss = 'dsh-gallery/gallery'
2762
+ tag.textContent = CSS
2763
+ document.head.appendChild(tag)
2764
+ return () => tag.remove()
2765
+ }, 'dsh-gallery: styles')
2766
+
2767
+ ctx.effect(() => ctx.sidebarRightTabs.register({
2768
+ id: ID,
2769
+ kind: KIND,
2770
+ priority: 'extension',
2771
+ // 正文保活:点文件/图片预览会切到另一个 tab,若不保活,画廊正文会被卸载,
2772
+ // 切回来时 kind 重置为图片、滚动位置归零 —— 关闭预览就回不到原来那张缩略图。
2773
+ // 声明 keepMounted 后,切 tab / 切会话 / 收起面板期间正文保持挂载,
2774
+ // 当前画廊类型、网格滚动位置、最近查看的卡片都原样保留。
2775
+ keepMounted: true,
2776
+ title: () => t('type.label'),
2777
+ guide: [{
2778
+ id: 'gallery',
2779
+ order: 20,
2780
+ title: () => t('guide.title'),
2781
+ description: () => t('guide.description'),
2782
+ }],
2783
+ }), 'dsh-gallery: tab type')
2784
+
2785
+ ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
2786
+ name: 'sidebar.right.pane.tab',
2787
+ key: ID,
2788
+ locale: NS,
2789
+ }, GalleryBody)), 'dsh-gallery: tab body')
2790
+
2791
+ ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
2792
+ name: 'sidebar.right.pane.tab.title',
2793
+ key: ID,
2794
+ locale: NS,
2795
+ }, GalleryTitle)), 'dsh-gallery: tab title')
2796
+
2797
+ // 入口一:左侧边栏脚部(宽态显示文字,窄态显示图标)。
2798
+ ctx.effect(() => ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
2799
+ name: 'sidebar.footer.action',
2800
+ id: 'dsh-gallery-open',
2801
+ order: 20,
2802
+ label: () => t('type.label'),
2803
+ locale: NS,
2804
+ }, OpenButton)), 'dsh-gallery: sidebar entry')
2805
+
2806
+ // 入口二:对话编辑框右侧的紧凑按钮。
2807
+ ctx.effect(() => ctx.slots.inject('conversation.input.right', () => ctx.slots.register({
2808
+ name: 'conversation.input.right',
2809
+ id: 'dsh-gallery-open',
2810
+ order: 30,
2811
+ label: () => t('type.label'),
2812
+ locale: NS,
2813
+ }, ComposerButton)), 'dsh-gallery: composer entry')
2814
+ },
2815
+ }
2816
+ },
2817
+ })