dsh-knit 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,7 +31,14 @@ window.__ModuleLoader__.load({
31
31
 
32
32
  'count': '{n} 篇',
33
33
  'count.filtered': '{hit} / {total} 篇',
34
+ 'count.media': '{n} 个媒体',
35
+ 'count.media.filtered': '{hit} / {total} 个媒体',
36
+ 'count.all': '{n} 项',
37
+ 'count.all.filtered': '{hit} / {total} 项',
34
38
  'action.refresh': '刷新',
39
+ 'path.openTitle': '在文件管理器中打开',
40
+ 'peek.openPanel': '点击打开面板',
41
+ 'peek.empty': '这个工作区里还没有 Markdown 文档。',
35
42
  'action.refreshNow': '立即刷新',
36
43
 
37
44
  'sort.relevance': '相关',
@@ -39,6 +46,11 @@ window.__ModuleLoader__.load({
39
46
  'sort.relevanceTitle': '按与当前对话的相关性排序(纯本地关键词匹配,不调模型)',
40
47
  'sort.timeTitle': '按文件修改时间倒序',
41
48
 
49
+ 'kind.all': '全部',
50
+ 'kind.doc': '文档',
51
+ 'kind.media': '图片与视频',
52
+ 'kind.title': '切换要列出的产物类型',
53
+
42
54
  'filter.placeholder': '过滤标题 / 摘要 / 路径',
43
55
  'filter.aria': '过滤文档',
44
56
 
@@ -54,8 +66,15 @@ window.__ModuleLoader__.load({
54
66
  'list.failed': '读取失败:{error}',
55
67
  'list.failedHint': '确认插件宿主半边已加载。',
56
68
  'list.empty': '这个工作区里还没有 Markdown 文档。',
69
+ 'list.emptyMedia': '这个工作区里还没有图片或视频。',
57
70
  'list.noMatch': '没有匹配「{query}」的文档。',
58
71
 
72
+ 'media.play': '播放视频',
73
+
74
+ // 「全部」的分区:类型名复用 kind.doc / kind.media,这里只补计数与跳转
75
+ 'section.count': '{shown} / {total}',
76
+ 'section.more': '查看全部 →',
77
+
59
78
  'preview.loading': '正在读取…',
60
79
  'preview.truncated': '(文件较大,仅预览前 512 KB)',
61
80
  'preview.fullscreen': '全屏',
@@ -85,6 +104,8 @@ window.__ModuleLoader__.load({
85
104
  'host.notAFile': '不是普通文件',
86
105
  'host.imageOnly': '只允许图片类型',
87
106
  'host.imageTooLarge': '图片过大',
107
+ 'host.mediaOnly': '仅支持图片或视频类型',
108
+ 'host.mediaTooLarge': '视频过大',
88
109
  'host.readFailed': '读取失败',
89
110
  'host.missingRel': '缺少 rel 参数',
90
111
  'host.internal': '宿主内部错误',
@@ -99,7 +120,14 @@ window.__ModuleLoader__.load({
99
120
 
100
121
  'count': '{n} docs',
101
122
  'count.filtered': '{hit} / {total} docs',
123
+ 'count.media': '{n} media',
124
+ 'count.media.filtered': '{hit} / {total} media',
125
+ 'count.all': '{n} items',
126
+ 'count.all.filtered': '{hit} / {total} items',
102
127
  'action.refresh': 'Refresh',
128
+ 'path.openTitle': 'Open in file manager',
129
+ 'peek.openPanel': 'Click to open the panel',
130
+ 'peek.empty': 'No Markdown documents in this workspace yet.',
103
131
  'action.refreshNow': 'Refresh now',
104
132
 
105
133
  'sort.relevance': 'Relevant',
@@ -107,6 +135,11 @@ window.__ModuleLoader__.load({
107
135
  'sort.relevanceTitle': 'Sort by relevance to the current conversation (local keyword matching, no model call)',
108
136
  'sort.timeTitle': 'Sort by file modified time, newest first',
109
137
 
138
+ 'kind.all': 'All',
139
+ 'kind.doc': 'Docs',
140
+ 'kind.media': 'Images & video',
141
+ 'kind.title': 'Switch which artifacts are listed',
142
+
110
143
  'filter.placeholder': 'Filter title / summary / path',
111
144
  'filter.aria': 'Filter documents',
112
145
 
@@ -122,8 +155,15 @@ window.__ModuleLoader__.load({
122
155
  'list.failed': 'Failed to read: {error}',
123
156
  'list.failedHint': 'Make sure the plugin’s host half is loaded.',
124
157
  'list.empty': 'No Markdown documents in this workspace yet.',
158
+ 'list.emptyMedia': 'No images or videos in this workspace yet.',
125
159
  'list.noMatch': 'No documents match “{query}”.',
126
160
 
161
+ 'media.play': 'Play video',
162
+
163
+ // "All" sections: titles reuse kind.doc / kind.media, only count + jump live here
164
+ 'section.count': '{shown} / {total}',
165
+ 'section.more': 'View all →',
166
+
127
167
  'preview.loading': 'Loading…',
128
168
  'preview.truncated': '(large file — showing the first 512 KB)',
129
169
  'preview.fullscreen': 'Fullscreen',
@@ -153,6 +193,8 @@ window.__ModuleLoader__.load({
153
193
  'host.notAFile': 'Not a regular file',
154
194
  'host.imageOnly': 'Images only',
155
195
  'host.imageTooLarge': 'Image too large',
196
+ 'host.mediaOnly': 'Images or videos only',
197
+ 'host.mediaTooLarge': 'Video too large',
156
198
  'host.readFailed': 'Read failed',
157
199
  'host.missingRel': 'Missing the rel parameter',
158
200
  'host.internal': 'Internal host error',
@@ -190,6 +232,8 @@ window.__ModuleLoader__.load({
190
232
  'knit/not-a-file': 'host.notAFile',
191
233
  'knit/image-only': 'host.imageOnly',
192
234
  'knit/image-too-large': 'host.imageTooLarge',
235
+ 'knit/media-only': 'host.mediaOnly',
236
+ 'knit/media-too-large': 'host.mediaTooLarge',
193
237
  'knit/read-failed': 'host.readFailed',
194
238
  'knit/missing-rel': 'host.missingRel',
195
239
  'knit/internal': 'host.internal',
@@ -245,23 +289,119 @@ window.__ModuleLoader__.load({
245
289
  /** 多久之内算「新」,打 🆕 标记。 */
246
290
  const NEW_WINDOW_MS = 2 * 60 * 1000
247
291
 
292
+ /** 悬停偷看:进入后延迟显示,离开后延迟收起(避免误触与闪烁)。 */
293
+ const PEEK_SHOW_DELAY = 250
294
+ const PEEK_HIDE_DELAY = 200
295
+ /** 悬停浮层里最多列几篇。 */
296
+ const PEEK_LIMIT = 5
297
+
248
298
  /** 用户偏好(选了就记住)。 */
249
299
  const SORT_KEY = 'dsh-knit:sort'
250
300
  const RATIO_KEY = 'dsh-knit:preview-ratio'
301
+ const KIND_KEY = 'dsh-knit:kind'
302
+
303
+ /** 列表类型:仅文档 / 仅图片视频 / 全部混排。默认 doc,与旧版体验一致。 */
304
+ const KIND_DOC = 'doc'
305
+ const KIND_MEDIA = 'media'
306
+ const KIND_ALL = 'all'
251
307
 
252
308
  /** 预览面板高度的上下限:任何一端都不把对方挤没。 */
253
309
  const MIN_RATIO = 0.2
254
310
  const MAX_RATIO = 0.8
255
311
  const DEFAULT_RATIO = 0.46
256
312
 
313
+ /** 「全部」视图里文档区的固定上限。 */
314
+ const ALL_DOC_CAP = 4
315
+ /**
316
+ * 媒体网格一屏最多摆几个(4 列 × 2 行)。
317
+ * 超出不再隐藏,而是整块等比缩小 —— 见 mediaLayoutFor 的 scaled 分支。
318
+ */
319
+ const MEDIA_MAX_ITEMS = 8
320
+ /**
321
+ * 媒体格子(缩略图)的最小边长。低于这个值再缩就看不清了,用户明确说过
322
+ * 「64×64 就够了」。与 CSS 里的 --knit-media-min 同一套算术 —— 改一处必须改另一处。
323
+ */
324
+ const MEDIA_MIN_PX = 64
325
+ /** 媒体视图(独立一档)一屏最多铺几行,再多就滚动 —— 免得面板被一个媒体墙顶爆。 */
326
+ const MEDIA_VIEW_ROWS = 3
327
+ /** 媒体网格的列数下限:面板再窄、媒体再少,也保持 3 列的观感(用户明确要求)。 */
328
+ const MEDIA_MIN_COLS = 3
329
+ const MEDIA_GAP_PX = 10
330
+ /** 网格左右内边距合计(.knit-media-grid 的 padding:0 12px / 8px 12px 16px)。 */
331
+ const MEDIA_GRID_PAD_X = 24
332
+ /** `.knit-list` 自己的左右内边距(padding:8px)—— 量到的是它,算格子要先扣掉。 */
333
+ const LIST_PAD_X = 16
334
+
335
+ /**
336
+ * 算媒体网格的列数、格子边长与是否进入「等比缩小」态。
337
+ *
338
+ * 规则来自用户:
339
+ *
340
+ * 1. **最少 3 列** —— 面板再窄也不掉到 1~2 列那种「一列一个」的观感;宽了才加列。
341
+ * 2. **一屏 8 个(4 列 × 2 行)是基准** —— 超过 8 个不再隐藏、也不再多铺行,
342
+ * 而是让整块网格**等比缩小**把这一屏塞满(所以格子会小于 64px,这是有意的)。
343
+ * 3. 不超过 8 个时以 64px 为基准、4 列满宽为上限;宽度不够就先让出一行
344
+ * (列数降到 3)把格子撑回 64px。
345
+ *
346
+ * 任何情况下 `columns*cell + gap` 都装得进可用宽度 —— 宁可格子小一点,也不能横向溢出。
347
+ *
348
+ * @param {number} width - 网格可用宽度(px,不含左右内边距)
349
+ * @param {number} [count] - 实际要摆几个;缺省按一屏基准(8)算
350
+ * @returns {{columns:number, cell:number, scaled:boolean, maxHeight:number|null}}
351
+ * 列数、格子边长(px,取整)、是否处于「等比缩小」态(此时卡片文字让位给缩略图)、
352
+ * 以及网格自身最大高度(null = 不限制,交给外层滚动)
353
+ */
354
+ function mediaLayoutFor(width, count) {
355
+ const n = Number.isFinite(count) && count > 0 ? Math.floor(count) : MEDIA_MAX_ITEMS
356
+ const w = Number(width)
357
+ const usable = Number.isFinite(w) && w > 0 ? w : 632 // 量不到就按默认右侧栏的几何算
358
+ const cellFor = (cols) => Math.floor((usable - (cols - 1) * MEDIA_GAP_PX) / cols)
359
+
360
+ /** 让格子长得下 64px 时最多能排几列(所以「格子大小」和「列数」是同一个约束)。 */
361
+ const colsAtMinCell = () => {
362
+ for (let cols = 8; cols > MEDIA_MIN_COLS; cols -= 1) {
363
+ if (cellFor(cols) >= MEDIA_MIN_PX) return cols
364
+ }
365
+ return MEDIA_MIN_COLS // 连 3 列 64px 都放不下:保住 3 列,允许极窄时轻微横溢
366
+ }
367
+
368
+ if (n <= MEDIA_MAX_ITEMS) {
369
+ // 不超一屏:宽度够就是 4 列满宽;媒体少于 4 个也不缩列(否则一个缩略图独占半屏)。
370
+ // 面板窄到 4 列放不下 64px 时按能放下的列数走,但**永远不减到 3 列以下**。
371
+ const fit = Math.min(4, colsAtMinCell()) // 64px 装得下时想要 4 列满宽
372
+ const cols = Math.max(fit, MEDIA_MIN_COLS)
373
+ const cell = Math.max(MEDIA_MIN_PX, cellFor(cols))
374
+ return { columns: cols, cell, scaled: cell < 96, maxHeight: null }
375
+ }
376
+
377
+ // 超过一屏:加列 + 等比缩小,两行装下(上限 8 列)。此时格子允许小于 64px ——
378
+ // 「超过就等比缩小」是用户明确要的行为,宁可小也不多铺行。
379
+ const cols = Math.min(8, Math.max(MEDIA_MIN_COLS, Math.ceil(n / 2)))
380
+ const cell = cellFor(cols)
381
+ return { columns: cols, cell, scaled: true, maxHeight: cell * 2 + MEDIA_GAP_PX }
382
+ }
383
+
257
384
  /* ── 样式:跟随 DSH 主题令牌,深浅色自适应 ───────────────── */
258
385
  const STYLE_ID = 'dsh-knit-style'
259
386
  const CSS = `
260
- .knit-root{display:flex;flex-direction:column;height:100%;min-height:0;
387
+ .knit-root{
388
+ /* 交互强调色统一走 DSH 品牌令牌:浅色 #4176e6 / 暗色 #5686fe,随主题切换。
389
+ 这里曾经硬编码过一套紫与另一套蓝,两套都不跟主题,深色下尤其突兀。
390
+ 填充改用 DSH 选中态的半透明令牌,不自己混色 —— color-mix 在旧内核上
391
+ 会让整条声明失效(invalid at computed-value time),不是渐进增强。 */
392
+ --knit-accent:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6);
393
+ /* 选中态的灰底一律直接用 DSH 的中性令牌(列表行、类型切换、排序切换共用一套),
394
+ 所以这里不再需要自备一个 accent 填充令牌。 */
395
+ display:flex;flex-direction:column;height:100%;min-height:0;
261
396
  color:var(--dsw-alias-label-primary,#e8eaed);font-size:13px}
262
397
  .knit-head{display:flex;align-items:center;gap:8px;padding:10px 12px 8px;flex:none}
263
398
  .knit-head .knit-root-path{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;
264
- white-space:nowrap;font-size:11px;color:var(--dsw-alias-label-caption,#80868b)}
399
+ white-space:nowrap;font-size:11px;color:var(--dsw-alias-label-caption,#80868b);
400
+ background:transparent;border:none;padding:0;text-align:left;font-family:inherit;
401
+ cursor:pointer}
402
+ .knit-head .knit-root-path:hover{color:var(--dsw-alias-label-primary,#e8eaed);
403
+ text-decoration:underline}
404
+ .knit-head .knit-root-path:disabled{cursor:default;text-decoration:none}
265
405
  .knit-count{font-size:11px;color:var(--dsw-alias-label-caption,#80868b);flex:none}
266
406
  .knit-btn{flex:none;display:inline-flex;align-items:center;justify-content:center;
267
407
  height:24px;padding:0 9px;border-radius:6px;cursor:pointer;
@@ -280,14 +420,14 @@ window.__ModuleLoader__.load({
280
420
  .knit-filter{flex:1;min-width:0;height:24px;padding:0 9px;border-radius:7px;font-size:11px;
281
421
  background:transparent;color:var(--dsw-alias-label-primary,#e8eaed);
282
422
  border:.5px solid var(--dsw-alias-border-l4,rgba(255,255,255,.1));outline:none}
283
- .knit-filter:focus{border-color:rgba(79,140,255,.5)}
423
+ .knit-filter:focus{border-color:var(--knit-accent)}
284
424
  .knit-filter::placeholder{color:var(--dsw-alias-label-caption,#80868b)}
285
425
  .knit-topic{flex:none;padding:0 12px 8px;font-size:10.5px;line-height:1.4;
286
426
  color:var(--dsw-alias-label-caption,#80868b);
287
427
  border-bottom:.5px solid var(--dsw-alias-border-l4,rgba(255,255,255,.08));
288
428
  overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
289
429
  .knit-list{flex:1 1 auto;min-height:0;overflow-y:auto;padding:8px;display:flex;flex-direction:column;gap:6px;outline:none}
290
- .knit-list:focus-visible{box-shadow:inset 0 0 0 1px rgba(79,140,255,.35)}
430
+ .knit-list:focus-visible{box-shadow:inset 0 0 0 1px var(--knit-accent)}
291
431
  .knit-list::-webkit-scrollbar{width:6px}
292
432
  .knit-list::-webkit-scrollbar-thumb{background:rgba(255,255,255,.14);border-radius:3px}
293
433
  .knit-doc{padding:10px 11px;border-radius:10px;cursor:pointer;
@@ -295,7 +435,8 @@ window.__ModuleLoader__.load({
295
435
  transition:background .18s,border-color .18s,transform .18s,opacity .18s}
296
436
  .knit-doc:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06));
297
437
  border-color:var(--dsw-alias-border-l4,rgba(255,255,255,.1));transform:translateX(-2px)}
298
- .knit-doc.active{border-color:rgba(79,140,255,.55);background:rgba(79,140,255,.10)}
438
+ .knit-doc.active{border-color:var(--knit-accent);
439
+ background:var(--dsw-alias-interactive-bg-active,rgba(255,255,255,.1))}
299
440
  /* .knit-doc.cursor 故意不设样式:键盘焦点靠「移动即预览」的预览面板表达,
300
441
  再加描边会与 .active 的整块蓝色背景重复,显得突兀 */
301
442
  .knit-row1{display:flex;align-items:center;gap:8px;margin-bottom:5px}
@@ -320,7 +461,7 @@ window.__ModuleLoader__.load({
320
461
  .knit-resize{flex:none;height:7px;cursor:ns-resize;background:transparent;position:relative}
321
462
  .knit-resize::after{content:'';position:absolute;left:50%;top:2px;transform:translateX(-50%);
322
463
  width:34px;height:3px;border-radius:2px;background:var(--dsw-alias-border-l4,rgba(255,255,255,.14))}
323
- .knit-resize:hover::after{background:rgba(79,140,255,.6)}
464
+ .knit-resize:hover::after{background:var(--knit-accent)}
324
465
  .knit-preview-head{display:flex;align-items:center;gap:8px;padding:6px 12px 8px;flex:none;
325
466
  border-bottom:.5px solid var(--dsw-alias-border-l4,rgba(255,255,255,.06))}
326
467
  .knit-preview-title{flex:1;min-width:0;font-size:12px;font-weight:600;
@@ -337,12 +478,106 @@ window.__ModuleLoader__.load({
337
478
  color:var(--dsw-alias-label-secondary,#9aa0a6);font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
338
479
  .knit-preview-note{font-size:11px;color:var(--dsw-alias-label-caption,#80868b);padding:2px 0 8px}
339
480
 
481
+ /* ── 类型切换(文档 / 图片与视频 / 全部)────────────── */
482
+ /* 选中态与下面的列表行、上面的排序切换共用一套中性灰填充,**不要品牌色描边**:
483
+ 用户的原话是「选中的时候不用加绿色、蓝色的描边,就跟下面列表一样,
484
+ 选中填充背景灰就可以」。所以这里不许再用 --knit-accent / --knit-accent-fill。 */
485
+ .knit-types{display:flex;gap:5px;padding:1px 12px 7px;flex:none}
486
+ .knit-type-btn{flex:1;height:24px;padding:0 6px;border-radius:6px;cursor:pointer;
487
+ border:.5px solid transparent;background:transparent;
488
+ color:var(--dsw-alias-label-secondary,#9aa0a6);font-family:inherit;font-size:11px;
489
+ white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
490
+ transition:background .15s,color .15s}
491
+ .knit-type-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08));
492
+ color:var(--dsw-alias-label-primary,#e8eaed)}
493
+ .knit-type-btn.active{background:var(--dsw-alias-interactive-bg-active,rgba(255,255,255,.1));
494
+ color:var(--dsw-alias-label-primary,#e8eaed);font-weight:600}
495
+
496
+ /* ── 图片与视频:方形缩略图网格 ─────────────────────
497
+ 列数与格子边长由 client.js 的 mediaLayoutFor 算好后用 CSS 变量传进来
498
+ (--knit-media-cols / --knit-media-cell),这里只留一个 3 列的兜底,
499
+ 保证「最少 3 列」这条规则在 JS 没跑起来时也成立。
500
+ fallback 那一行是给不认 repeat(变量, ...) 的旧内核用的,必须写在前面。 */
501
+ .knit-media-grid{display:grid;gap:${MEDIA_GAP_PX}px;
502
+ --knit-media-label:block;
503
+ grid-template-columns:repeat(3,1fr);
504
+ grid-template-columns:repeat(var(--knit-media-cols,3),minmax(0,1fr));
505
+ padding:8px 12px 16px;align-content:start;min-height:0;overflow-y:auto}
506
+ /* 分区里的网格:滚动交给 .knit-list 统一管,自己不留内边距 */
507
+ .knit-media-grid.in-section{padding:0;overflow:visible}
508
+ .knit-media-card{min-width:0;cursor:pointer;border-radius:10px}
509
+ .knit-media-thumbbox{position:relative;width:100%;height:var(--knit-media-cell,auto);aspect-ratio:1/1;
510
+ border-radius:9px;overflow:hidden;
511
+ background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06));
512
+ border:.5px solid var(--dsw-alias-border-l2,rgba(255,255,255,.1));
513
+ transition:border-color .15s,box-shadow .15s}
514
+ .knit-media-card:hover .knit-media-thumbbox{border-color:var(--dsw-alias-border-l4,rgba(255,255,255,.22))}
515
+ /* 正在预览 → 品牌色描边;键盘移动 → 只有中性描边,别让它看起来像「选中了」 */
516
+ .knit-media-card.active .knit-media-thumbbox{
517
+ border-color:var(--knit-accent);box-shadow:0 0 0 1.5px var(--knit-accent)}
518
+ .knit-media-card.cursor .knit-media-thumbbox{
519
+ border-color:var(--dsw-alias-border-l4,rgba(255,255,255,.22));
520
+ box-shadow:0 0 0 1.5px var(--dsw-alias-interactive-bg-active,rgba(255,255,255,.1))}
521
+ /* 等比缩小态(一屏硬塞 8 个以上)下格子太小,文件名与时间会挤成一团 —— 整块让位给缩略图 */
522
+ .knit-media-meta{margin-top:5px;display:var(--knit-media-label,block)}
523
+ .knit-media-name{display:flex;align-items:center;gap:3px;font-size:11.5px;line-height:1.3;
524
+ color:var(--dsw-alias-label-primary,#e8eaed);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
525
+ .knit-media-time{margin-top:1px;padding:0 1px;font-size:10px;color:var(--dsw-alias-label-caption,#80868b)}
526
+
527
+ /* ── 缩略图本体(图片 / 视频首帧 + 播放三角 + 时长)── */
528
+ .knit-thumb{position:absolute;inset:0}
529
+ .knit-thumb img,.knit-thumb video{width:100%;height:100%;object-fit:cover;display:block;background:#000}
530
+ .knit-thumb-play{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;
531
+ color:#fff;pointer-events:none}
532
+ .knit-thumb-play svg{width:32%;height:32%;fill:currentColor;opacity:.95;
533
+ filter:drop-shadow(0 1px 4px rgba(0,0,0,.65))}
534
+ .knit-thumb-dur{position:absolute;right:5px;bottom:5px;padding:1px 5px;border-radius:5px;
535
+ background:rgba(0,0,0,.7);color:#fff;font-size:10px;line-height:1.5;font-variant-numeric:tabular-nums;
536
+ pointer-events:none}
537
+
538
+ /* ── 「全部」按类型分上下两区(文档 / 图片与视频)──── */
539
+ .knit-section{display:flex;flex-direction:column;gap:6px}
540
+ .knit-section-head{display:flex;align-items:center;gap:6px;padding:0 2px}
541
+ .knit-section-title{font-size:11px;font-weight:600;color:var(--dsw-alias-label-secondary,#9aa0a6)}
542
+ .knit-section-count{font-size:10.5px;color:var(--dsw-alias-label-caption,#80868b);
543
+ font-variant-numeric:tabular-nums}
544
+ .knit-section-more{margin-left:auto;flex:none;padding:0;border:none;background:transparent;
545
+ cursor:pointer;font-family:inherit;font-size:10.5px;color:var(--knit-accent)}
546
+ .knit-section-more:hover{text-decoration:underline}
547
+
548
+ /* ── 预览面板里的图片 / 视频 ───────────────────────── */
549
+ .knit-preview-body.is-media{display:flex;align-items:center;justify-content:center;
550
+ padding:12px;background:rgba(0,0,0,.22)}
551
+ .knit-preview-media{max-width:100%;max-height:100%;object-fit:contain;border-radius:6px}
552
+ video.knit-preview-media{width:100%;background:#000}
553
+
340
554
  /* Knit 图标:不跟随文本色,浅色模式纯黑、暗色模式纯白。
341
555
  DSH 的暗色信号是 body[data-ds-dark-theme](官方 CSS 用的就是这个)。 */
342
556
  .knit-icon{color:#000}
343
557
  body[data-ds-dark-theme] .knit-icon{color:#fff}
344
558
 
345
559
  /* 入口按钮:挂在会话头部右侧与输入框工具行两处 list 座位上 */
560
+ /* 悬停偷看浮层:自己画的,不碰框架(所以不会推开右侧栏) */
561
+ .knit-peek-anchor{display:inline-flex;position:relative}
562
+ .knit-peek{position:fixed;z-index:60;display:flex;flex-direction:column;max-height:60vh;
563
+ padding:5px;border-radius:12px;box-shadow:0 12px 32px rgba(0,0,0,.32);
564
+ background:var(--dsw-alias-bg-layer-2,#2c2c2e);
565
+ border:.5px solid var(--dsw-alias-border-l4,rgba(255,255,255,.12));
566
+ color:var(--dsw-alias-label-primary,#e8eaed)}
567
+ .knit-peek-head{display:flex;align-items:center;gap:7px;padding:5px 7px 7px;
568
+ font-size:11px;color:var(--dsw-alias-label-caption,#80868b)}
569
+ .knit-peek-list{display:flex;flex-direction:column;gap:1px;min-height:0;overflow-y:auto}
570
+ .knit-peek-doc{display:flex;align-items:baseline;gap:8px;width:100%;padding:7px 8px;
571
+ border:none;border-radius:8px;cursor:pointer;text-align:left;font-family:inherit;
572
+ background:transparent;color:inherit}
573
+ .knit-peek-doc:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08))}
574
+ .knit-peek-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}
575
+ .knit-peek-time{flex:none;font-size:10.5px;color:var(--dsw-alias-label-caption,#80868b)}
576
+ .knit-peek .knit-peek-hint{padding:7px;font-size:10.5px;
577
+ color:var(--dsw-alias-label-caption,#80868b)}
578
+ .knit-peek-list + .knit-peek-hint{margin-top:4px;padding-top:8px;
579
+ border-top:.5px solid var(--dsw-alias-border-l4,rgba(255,255,255,.08))}
580
+
346
581
  .knit-entry{display:inline-flex;align-items:center;justify-content:center;flex:none;
347
582
  width:28px;height:28px;padding:0;border:none;border-radius:8px;cursor:pointer;
348
583
  background:transparent;color:var(--dsw-alias-label-secondary,#9aa0a6);
@@ -353,6 +588,7 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
353
588
  /* 全屏阅读:藏掉头部与列表,只留预览 */
354
589
  .knit-root.fullscreen .knit-head,
355
590
  .knit-root.fullscreen .knit-bar,
591
+ .knit-root.fullscreen .knit-types,
356
592
  .knit-root.fullscreen .knit-topic,
357
593
  .knit-root.fullscreen .knit-list{display:none}
358
594
  .knit-root.fullscreen .knit-preview{flex:1 1 auto;max-height:none}
@@ -404,6 +640,15 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
404
640
  return readPref(SORT_KEY) === 'time' ? 'time' : 'relevance'
405
641
  }
406
642
 
643
+ /**
644
+ * 读上次选择的列表类型,非法值回落到 doc。
645
+ * @returns {'doc'|'media'|'all'} 类型
646
+ */
647
+ function readKindPref() {
648
+ const v = readPref(KIND_KEY)
649
+ return v === KIND_MEDIA || v === KIND_ALL ? v : KIND_DOC
650
+ }
651
+
407
652
  /**
408
653
  * 把预览高度比例夹到合法区间。
409
654
  * @param {number} value - 原始比例
@@ -520,6 +765,35 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
520
765
  return `${d.getMonth() + 1}月${d.getDate()}日`
521
766
  }
522
767
 
768
+ /**
769
+ * 拼媒体文件的同源原始字节地址(缩略图与就地预览都走它,宿主支持 Range)。
770
+ * @param {string} sessionId - 会话 id
771
+ * @param {string} rel - 工作区相对路径
772
+ * @returns {string} `/knit/api/raw?...`
773
+ */
774
+ function mediaUrl(sessionId, rel) {
775
+ return `${RAW_API}?sessionId=${encodeURIComponent(sessionId)}&rel=${encodeURIComponent(rel)}`
776
+ }
777
+
778
+ /**
779
+ * 秒 → `m:ss` / `h:mm:ss`,用于视频时长角标。
780
+ * @param {number} seconds - 秒
781
+ * @returns {string} 时长文本
782
+ */
783
+ function fmtDuration(seconds) {
784
+ const total = Math.max(0, Math.round(Number(seconds) || 0))
785
+ const h = Math.floor(total / 3600)
786
+ const m = Math.floor((total % 3600) / 60)
787
+ const s = total % 60
788
+ const pad = (n) => String(n).padStart(2, '0')
789
+ return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`
790
+ }
791
+
792
+ /** 条目是不是图片/视频。 */
793
+ function isMedia(doc) {
794
+ return !!doc && (doc.kind === 'image' || doc.kind === 'video')
795
+ }
796
+
523
797
  /* ── 组件 ───────────────────────────────────────── */
524
798
 
525
799
  /**
@@ -556,27 +830,107 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
556
830
  h('div', { className: 'knit-meta' }, doc.rel))
557
831
  }
558
832
 
833
+ /**
834
+ * 视频缩略图。
835
+ *
836
+ * 用 `<video preload="metadata" src#t=0.5>` 让浏览器直接解出首帧当海报,
837
+ * 中央叠播放三角、右下角叠时长 —— 零依赖、零 ffmpeg、宿主也不必解析容器。
838
+ * 时长在 loadedmetadata 后填,拿不到就不显示角标。
839
+ *
840
+ * 每张缩略图都会发一次 Range 请求取首帧,所以在媒体视图(无上限)里
841
+ * 视频多的目录会比较费;「全部」里媒体区限 2 行,已经把这个量压住了。
842
+ *
843
+ * @param {{src:string}} props - 视频字节地址
844
+ * @returns {import('react').ReactElement} 元素
845
+ */
846
+ function VideoThumb({ src }) {
847
+ const [duration, setDuration] = React.useState(null)
848
+ return h('div', { className: 'knit-thumb' },
849
+ h('video', {
850
+ preload: 'metadata',
851
+ muted: true,
852
+ playsInline: true,
853
+ src: `${src}#t=0.5`,
854
+ onLoadedMetadata(event) {
855
+ const v = event && event.target
856
+ if (v && Number.isFinite(v.duration) && v.duration > 0) setDuration(v.duration)
857
+ },
858
+ }),
859
+ h('span', { className: 'knit-thumb-play', 'aria-hidden': true },
860
+ h('svg', { viewBox: '0 0 24 24', focusable: false },
861
+ h('path', { d: 'M8 5v14l11-7z' }))),
862
+ duration ? h('span', { className: 'knit-thumb-dur' }, fmtDuration(duration)) : null)
863
+ }
864
+
865
+ /**
866
+ * 缩略图本体:图片走懒加载 `<img>`,视频走首帧 VideoThumb。
867
+ * @param {{doc:object,src:string}} props - 条目与字节地址
868
+ * @returns {import('react').ReactElement} 元素
869
+ */
870
+ function MediaThumb({ doc, src }) {
871
+ if (doc.kind === 'video') return h(VideoThumb, { src })
872
+ return h('div', { className: 'knit-thumb' },
873
+ h('img', { loading: 'lazy', src, alt: doc.name || '', draggable: false }))
874
+ }
875
+
876
+ /**
877
+ * 媒体网格卡片(图片与视频视图):方形缩略图 + 文件名 + 相对时间。
878
+ * @param {object} props - 与 DocRow 同构,外加 src
879
+ * @returns {import('react').ReactElement} 元素
880
+ */
881
+ function MediaCard({ doc, now, active, cursor, src, onSelect, onOpenTab }) {
882
+ const fresh = now - doc.mtimeMs < NEW_WINDOW_MS
883
+ return h('div', {
884
+ className: `knit-media-card${active ? ' active' : ''}${cursor ? ' cursor' : ''}${fresh ? ' fresh' : ''}`,
885
+ 'data-knit-rel': doc.rel,
886
+ title: t('row.tooltip', { path: doc.rel }),
887
+ onClick: () => onSelect(doc),
888
+ onDoubleClick: () => onOpenTab(doc),
889
+ },
890
+ h('div', { className: 'knit-media-thumbbox' }, h(MediaThumb, { doc, src })),
891
+ h('div', { className: 'knit-media-meta' },
892
+ h('div', { className: 'knit-media-name', title: doc.name },
893
+ fresh ? h('span', { className: 'knit-badge' }, '🆕') : null,
894
+ doc.name),
895
+ h('div', { className: 'knit-media-time' }, relTime(doc.mtimeMs, now))))
896
+ }
897
+
559
898
  /**
560
899
  * 列表下方的预览面板。
561
900
  * @param {{preview:object,pathImages:object|null,fullscreen:boolean,onClose:Function,onOpenTab:Function,onToggleFullscreen:Function,onResizeStart:Function}} props - 渲染入参
562
901
  * @returns {import('react').ReactElement} 元素
563
902
  */
564
903
  function PreviewPanel({ preview, pathImages, fullscreen, ratio, onClose, onOpenTab, onToggleFullscreen, onResizeStart }) {
904
+ const isMedia = preview.kind === 'image' || preview.kind === 'video'
905
+
906
+ // 图片/视频不读正文,直接用同源字节地址渲染;Markdown 才走加载 / MarkdownText / 降级。
565
907
  const body = preview.status === 'loading'
566
908
  ? h('div', { className: 'knit-preview-note' }, t('preview.loading'))
567
909
  : preview.status === 'error'
568
910
  ? h('div', { className: 'knit-preview-note' }, t('list.failed', { error: preview.error }))
569
- : MarkdownText
570
- ? h(MarkdownText, {
571
- text: preview.text,
572
- labels: { code: { copyLabel: t('code.copy'), copiedLabel: t('code.copied') }, footnotes: '' },
573
- pathImages: pathImages || undefined,
574
- })
575
- // 降级必须说出来 —— 静默退回纯文本会让人以为是渲染坏了(真实踩过的坑)
576
- : h('div', null,
577
- h('div', { className: 'knit-preview-note' },
578
- t('preview.rawFallback')),
579
- h('pre', { className: 'knit-raw' }, preview.text))
911
+ : preview.kind === 'image'
912
+ ? h('img', { className: 'knit-preview-media', src: preview.src, alt: preview.title || preview.rel })
913
+ : preview.kind === 'video'
914
+ ? h('video', {
915
+ className: 'knit-preview-media',
916
+ src: preview.src,
917
+ controls: true,
918
+ autoPlay: true,
919
+ muted: true,
920
+ playsInline: true,
921
+ 'aria-label': t('media.play'),
922
+ })
923
+ : MarkdownText
924
+ ? h(MarkdownText, {
925
+ text: preview.text,
926
+ labels: { code: { copyLabel: t('code.copy'), copiedLabel: t('code.copied') }, footnotes: '' },
927
+ pathImages: pathImages || undefined,
928
+ })
929
+ // 降级必须说出来 —— 静默退回纯文本会让人以为是渲染坏了(真实踩过的坑)
930
+ : h('div', null,
931
+ h('div', { className: 'knit-preview-note' },
932
+ t('preview.rawFallback')),
933
+ h('pre', { className: 'knit-raw' }, preview.text))
580
934
 
581
935
  return h('div', {
582
936
  className: 'knit-preview',
@@ -592,8 +946,8 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
592
946
  }, fullscreen ? t('preview.exitFullscreen') : t('preview.fullscreen')),
593
947
  h('button', { className: 'knit-btn', onClick: onOpenTab, title: t('preview.newTabTitle') }, t('preview.newTab')),
594
948
  h('button', { className: 'knit-preview-close', onClick: onClose, title: t('preview.close') }, '✕')),
595
- h('div', { className: 'knit-preview-body' },
596
- preview.truncated ? h('div', { className: 'knit-preview-note' }, t('preview.truncated')) : null,
949
+ h('div', { className: `knit-preview-body${isMedia ? ' is-media' : ''}` },
950
+ !isMedia && preview.truncated ? h('div', { className: 'knit-preview-note' }, t('preview.truncated')) : null,
597
951
  body))
598
952
  }
599
953
 
@@ -609,6 +963,8 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
609
963
 
610
964
  const [notice, setNotice] = React.useState('')
611
965
  const [sort, setSort] = React.useState(readSortPref)
966
+ // 紧跟 sort:测试按 hook 顺序预置前两位(notice/sort),kind 放第三位不影响老用例。
967
+ const [kind, setKind] = React.useState(readKindPref)
612
968
  const [state, setState] = React.useState({
613
969
  status: 'loading', docs: [], root: '', total: 0, error: '', mode: 'time', topic: '',
614
970
  })
@@ -622,13 +978,30 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
622
978
  const listRef = React.useRef(null)
623
979
  const rootRef = React.useRef(null)
624
980
 
981
+ // 「全部」的媒体区只给两行,所以列数得跟着面板宽度走(量不到就按默认 3 列)。
982
+ // 放在 fullscreen 之后,保持前几个 hook 的顺序不变 —— 测试按顺序预置状态。
983
+ const [listWidth, setListWidth] = React.useState(0)
984
+
985
+ React.useEffect(() => {
986
+ const host = listRef.current
987
+ if (!host || typeof ResizeObserver === 'undefined') return undefined
988
+ const observer = new ResizeObserver((entries) => {
989
+ const width = entries && entries[0] && entries[0].contentRect
990
+ ? entries[0].contentRect.width
991
+ : 0
992
+ if (width) setListWidth(width)
993
+ })
994
+ observer.observe(host)
995
+ return () => observer.disconnect()
996
+ }, [])
997
+
625
998
  const load = React.useCallback(async () => {
626
999
  if (!sessionId) {
627
1000
  setState({ status: 'error', docs: [], root: '', total: 0, error: t('error.noSession'), mode: 'time', topic: '' })
628
1001
  return
629
1002
  }
630
1003
  try {
631
- const url = `${LIST_API}?sessionId=${encodeURIComponent(sessionId)}&limit=40&sort=${sort}`
1004
+ const url = `${LIST_API}?sessionId=${encodeURIComponent(sessionId)}&limit=40&sort=${sort}&kind=${kind}`
632
1005
  const res = await fetch(url, { headers: { accept: 'application/json' }, cache: 'no-store' })
633
1006
  const data = await res.json()
634
1007
  if (data && data.ok) {
@@ -641,6 +1014,7 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
641
1014
  mode: data.mode || 'time',
642
1015
  topic: data.topic || '',
643
1016
  })
1017
+
644
1018
  } else {
645
1019
  setState({ status: 'error', docs: [], root: '', total: 0, error: hostMessage(data), mode: 'time', topic: '' })
646
1020
  }
@@ -648,7 +1022,7 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
648
1022
  setState({ status: 'error', docs: [], root: '', total: 0, error: String((error && error.message) || error), mode: 'time', topic: '' })
649
1023
  }
650
1024
  setTick(Date.now())
651
- }, [sessionId, sort])
1025
+ }, [sessionId, sort, kind])
652
1026
 
653
1027
  React.useEffect(() => {
654
1028
  let alive = true
@@ -663,22 +1037,50 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
663
1037
 
664
1038
  /* ── 过滤:纯客户端,不重新请求宿主 ─────────────── */
665
1039
  const visibleDocs = React.useMemo(() => {
1040
+ const all = Array.isArray(state.docs) ? state.docs : []
666
1041
  const q = query.trim().toLowerCase()
667
- if (!q) return state.docs
668
- return state.docs.filter((doc) =>
1042
+ if (!q) return all
1043
+ return all.filter((doc) =>
669
1044
  String(doc.title || '').toLowerCase().includes(q)
670
1045
  || String(doc.summary || '').toLowerCase().includes(q)
671
1046
  || String(doc.rel || '').toLowerCase().includes(q))
672
1047
  }, [state.docs, query])
673
1048
 
674
- // cursor 消失(被过滤掉 / 列表刷新)时落回第一项
1049
+ /* ── 「全部」:按类型分上下两区 ─────────────────────
1050
+ 文档区固定 4 条,多余的在分区标题给「查看全部」;
1051
+ 媒体区**不截断** —— 超过一屏基准(8 个)就整块等比缩小,而不是把剩下的藏起来。 */
1052
+ const docItems = kind === KIND_ALL ? visibleDocs.filter((doc) => !isMedia(doc)) : []
1053
+ const mediaItems = kind === KIND_ALL ? visibleDocs.filter(isMedia) : []
1054
+ const shownDocs = docItems.slice(0, ALL_DOC_CAP)
1055
+ // ResizeObserver 量到的是 .knit-list(它自己也有左右内边距),
1056
+ // 网格的可用宽度 = 列表宽度 − 列表内边距 − 网格内边距
1057
+ const mediaLayout = mediaLayoutFor(
1058
+ Math.max(0, listWidth - LIST_PAD_X - MEDIA_GRID_PAD_X),
1059
+ kind === KIND_ALL ? mediaItems.length : Math.min(visibleDocs.length, MEDIA_MAX_ITEMS))
1060
+
1061
+ /** 媒体网格:列数与格子边长都由 mediaLayout 决定(CSS 只提供变量名)。 */
1062
+ const mediaGrid = (docs, inSection) => h('div', {
1063
+ className: `knit-media-grid${inSection ? ' in-section' : ''}`,
1064
+ role: 'group',
1065
+ style: {
1066
+ '--knit-media-cols': String(mediaLayout.columns),
1067
+ '--knit-media-cell': `${mediaLayout.cell}px`,
1068
+ ...(mediaLayout.scaled ? { '--knit-media-label': 'none' } : {}),
1069
+ ...(mediaLayout.maxHeight ? { maxHeight: `${mediaLayout.maxHeight}px` } : {}),
1070
+ },
1071
+ }, docs.map(renderEntry))
1072
+
1073
+ /** 键盘与 cursor 真正能到达的条目:「全部」里文档只到上限,媒体全部可达。 */
1074
+ const navDocs = kind === KIND_ALL ? shownDocs.concat(mediaItems) : visibleDocs
1075
+
1076
+ // cursor 消失(被过滤掉 / 被上限截断 / 列表刷新)时落回第一项
675
1077
  React.useEffect(() => {
676
- if (visibleDocs.length === 0) {
1078
+ if (navDocs.length === 0) {
677
1079
  if (cursor !== '') setCursor('')
678
1080
  return
679
1081
  }
680
- if (!visibleDocs.some((doc) => doc.rel === cursor)) setCursor(visibleDocs[0].rel)
681
- }, [visibleDocs, cursor])
1082
+ if (!navDocs.some((doc) => doc.rel === cursor)) setCursor(navDocs[0].rel)
1083
+ }, [navDocs, cursor])
682
1084
 
683
1085
  // 键盘焦点跟手滚进视口(测试环境没有 DOM,静默跳过)
684
1086
  React.useEffect(() => {
@@ -693,11 +1095,23 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
693
1095
  // 预览高度:拖完就记住
694
1096
  React.useEffect(() => { writePref(RATIO_KEY, String(ratio)) }, [ratio])
695
1097
 
1098
+ /**
1099
+ * 为一个条目造预览状态:图片/视频直接 ready(字节地址交给 <img>/<video>),
1100
+ * Markdown 才进 loading 去拉正文。
1101
+ */
1102
+ const previewFor = React.useCallback((doc) => {
1103
+ const base = { rel: doc.rel, title: doc.title || doc.name, text: '', truncated: false }
1104
+ if (isMedia(doc)) {
1105
+ return { ...base, kind: doc.kind, src: mediaUrl(sessionId, doc.rel), status: 'ready' }
1106
+ }
1107
+ return { ...base, kind: KIND_DOC, status: 'loading' }
1108
+ }, [sessionId])
1109
+
696
1110
  /** 打开(不切换)某篇的预览。 */
697
1111
  const openPreview = React.useCallback((doc) => {
698
1112
  setNotice('')
699
- setPreview({ rel: doc.rel, title: doc.title || doc.name, status: 'loading', text: '', truncated: false })
700
- }, [])
1113
+ setPreview(previewFor(doc))
1114
+ }, [previewFor])
701
1115
 
702
1116
  /** 单击 / Enter:切换某篇的预览开与关。 */
703
1117
  const togglePreview = React.useCallback((doc) => {
@@ -705,9 +1119,9 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
705
1119
  setCursor(doc.rel)
706
1120
  setPreview((current) => {
707
1121
  if (current && current.rel === doc.rel && current.status !== 'error') return null
708
- return { rel: doc.rel, title: doc.title || doc.name, status: 'loading', text: '', truncated: false }
1122
+ return previewFor(doc)
709
1123
  })
710
- }, [])
1124
+ }, [previewFor])
711
1125
 
712
1126
  /** 收起预览;全屏时顺带退出全屏。 */
713
1127
  const closePreview = React.useCallback(() => {
@@ -717,21 +1131,21 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
717
1131
 
718
1132
  /** 键盘导航:↑↓ 移动即预览,Enter 切换,Esc 收起。 */
719
1133
  const onListKeyDown = React.useCallback((event) => {
720
- if (visibleDocs.length === 0) return
721
- const index = visibleDocs.findIndex((doc) => doc.rel === cursor)
1134
+ if (navDocs.length === 0) return
1135
+ const index = navDocs.findIndex((doc) => doc.rel === cursor)
722
1136
 
723
1137
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
724
1138
  event.preventDefault()
725
1139
  const next = event.key === 'ArrowDown'
726
- ? Math.min(visibleDocs.length - 1, index < 0 ? 0 : index + 1)
1140
+ ? Math.min(navDocs.length - 1, index < 0 ? 0 : index + 1)
727
1141
  : Math.max(0, index < 0 ? 0 : index - 1)
728
- const doc = visibleDocs[next]
1142
+ const doc = navDocs[next]
729
1143
  if (doc) { setCursor(doc.rel); openPreview(doc) }
730
1144
  return
731
1145
  }
732
1146
  if (event.key === 'Enter') {
733
1147
  event.preventDefault()
734
- const doc = visibleDocs.find((d) => d.rel === cursor) || visibleDocs[0]
1148
+ const doc = navDocs.find((d) => d.rel === cursor) || navDocs[0]
735
1149
  if (doc) togglePreview(doc)
736
1150
  return
737
1151
  }
@@ -740,7 +1154,7 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
740
1154
  if (fullscreen) setFullscreen(false)
741
1155
  else closePreview()
742
1156
  }
743
- }, [visibleDocs, cursor, fullscreen, openPreview, togglePreview, closePreview])
1157
+ }, [navDocs, cursor, fullscreen, openPreview, togglePreview, closePreview])
744
1158
 
745
1159
  /** 拖拽预览面板上缘改变高度。 */
746
1160
  const onResizeStart = React.useCallback((event) => {
@@ -763,6 +1177,27 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
763
1177
  window.addEventListener('pointerup', onUp)
764
1178
  }, [ratio])
765
1179
 
1180
+ // 悬停浮层点了某一篇 → **立刻**展开预览,不等列表、不等轮询。
1181
+ // 挂载时先取一次可能已挂起的目标,之后靠订阅实时收。
1182
+ React.useEffect(() => {
1183
+ /**
1184
+ * 把一次预览请求落到状态上。
1185
+ * @param {{rel:string, title:string}} target - 目标
1186
+ * @returns {void}
1187
+ */
1188
+ const apply = (target) => {
1189
+ setNotice('')
1190
+ // 悬停浮层只列 Markdown,这里固定按文档走 loading→拉正文。
1191
+ setPreview({ rel: target.rel, title: target.title, kind: KIND_DOC, status: 'loading', text: '', truncated: false })
1192
+ }
1193
+ if (pendingPreview) {
1194
+ const queued = pendingPreview
1195
+ pendingPreview = null
1196
+ apply(queued)
1197
+ }
1198
+ return subscribePreview(apply)
1199
+ }, [])
1200
+
766
1201
  // 预览进入 loading 时去宿主取正文
767
1202
  const previewRel = preview && preview.rel
768
1203
  const previewStatus = preview && preview.status
@@ -816,42 +1251,110 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
816
1251
  setSort(value)
817
1252
  }, [])
818
1253
 
1254
+ /** 媒体条目的同源字节地址(缩略图 / 就地预览)。 */
1255
+ const srcFor = React.useCallback((doc) => mediaUrl(sessionId, doc.rel), [sessionId])
1256
+
1257
+ /** 切换列表类型并记住偏好;同时收起上一类型的预览。 */
1258
+ const pickKind = React.useCallback((value) => {
1259
+ writePref(KIND_KEY, value)
1260
+ setKind(value)
1261
+ setPreview(null)
1262
+ setFullscreen(false)
1263
+ }, [])
1264
+
819
1265
  const relevance = state.mode === 'relevance'
820
1266
  const filtering = query.trim().length > 0
821
1267
 
1268
+ /** 渲染一个条目:媒体一律出方形卡片(媒体视图与「全部」的媒体区共用),其余出文档行。 */
1269
+ const renderEntry = (doc) => {
1270
+ const common = {
1271
+ key: doc.path || doc.rel,
1272
+ doc,
1273
+ now: tick,
1274
+ active: Boolean(preview && preview.rel === doc.rel),
1275
+ cursor: doc.rel === cursor,
1276
+ onSelect: togglePreview,
1277
+ onOpenTab,
1278
+ }
1279
+ if (isMedia(doc)) return h(MediaCard, { ...common, src: srcFor(doc) })
1280
+ return h(DocRow, { ...common, relevance })
1281
+ }
1282
+
1283
+ /** 「全部」的分区标题:类型名 + 「已显示 / 总数」+ 被截断时的「查看全部」。 */
1284
+ const sectionHead = (labelKey, shownCount, totalCount, targetKind) =>
1285
+ h('div', { className: 'knit-section-head' },
1286
+ h('span', { className: 'knit-section-title' }, t(labelKey)),
1287
+ h('span', { className: 'knit-section-count' },
1288
+ t('section.count', { shown: shownCount, total: totalCount })),
1289
+ totalCount > shownCount
1290
+ ? h('button', {
1291
+ type: 'button',
1292
+ className: 'knit-section-more',
1293
+ title: t('section.more'),
1294
+ onClick: () => pickKind(targetKind),
1295
+ }, t('section.more'))
1296
+ : null)
1297
+
1298
+ /** 「全部」的上下两区:空的一区整个不渲染,免得只剩一个空标题。 */
1299
+ const allSections = [
1300
+ docItems.length === 0 ? null : h('div', { className: 'knit-section', key: 'docs' },
1301
+ sectionHead('kind.doc', shownDocs.length, docItems.length, KIND_DOC),
1302
+ shownDocs.map(renderEntry)),
1303
+ mediaItems.length === 0 ? null : h('div', { className: 'knit-section', key: 'media' },
1304
+ // 媒体不截断,所以只给一个标题,不给「已显示 / 总数」和「查看全部」
1305
+ h('div', { className: 'knit-section-head' },
1306
+ h('span', { className: 'knit-section-title' }, t('kind.media')),
1307
+ h('span', { className: 'knit-section-count' }, String(mediaItems.length))),
1308
+ mediaGrid(mediaItems, true)),
1309
+ ]
1310
+
1311
+ // 媒体视图一屏最多铺 MEDIA_VIEW_ROWS 行,再多就交给滚动 —— 不让面板被媒体墙顶爆
1312
+ const mediaViewLimit = Math.max(1, mediaLayout.columns * MEDIA_VIEW_ROWS)
1313
+
1314
+ const emptyText = kind === KIND_MEDIA ? t('list.emptyMedia') : t('list.empty')
822
1315
  const body = state.status === 'loading' && state.docs.length === 0
823
1316
  ? h('div', { className: 'knit-msg' }, t('list.scanning'))
824
1317
  : state.status === 'error'
825
1318
  ? h('div', { className: 'knit-msg' }, t('list.failed', { error: state.error }), h('br'), t('list.failedHint'))
826
1319
  : state.docs.length === 0
827
- ? h('div', { className: 'knit-msg' }, t('list.empty'))
1320
+ ? h('div', { className: 'knit-msg' }, emptyText)
828
1321
  : visibleDocs.length === 0
829
1322
  ? h('div', { className: 'knit-msg' }, t('list.noMatch', { query: query.trim() }))
830
- : visibleDocs.map((doc) => h(DocRow, {
831
- key: doc.path,
832
- doc,
833
- now: tick,
834
- active: Boolean(preview && preview.rel === doc.rel),
835
- cursor: doc.rel === cursor,
836
- relevance,
837
- onSelect: togglePreview,
838
- onOpenTab,
839
- }))
1323
+ : kind === KIND_MEDIA
1324
+ ? mediaGrid(visibleDocs.slice(0, mediaViewLimit), false)
1325
+ : kind === KIND_ALL
1326
+ ? allSections
1327
+ : visibleDocs.map(renderEntry)
840
1328
 
841
1329
  const topicText = relevance
842
1330
  ? (state.topic ? t('topic.relevance', { topic: state.topic }) : t('topic.relevancePlain'))
843
1331
  : (sort === 'relevance' ? t('topic.needsConversation') : t('topic.time'))
844
1332
 
1333
+ // 不同类型用不同量词:文档「篇」、媒体「个」、混排「项」。
1334
+ const countKey = kind === KIND_MEDIA
1335
+ ? (filtering ? 'count.media.filtered' : 'count.media')
1336
+ : kind === KIND_ALL
1337
+ ? (filtering ? 'count.all.filtered' : 'count.all')
1338
+ : (filtering ? 'count.filtered' : 'count')
845
1339
  const countText = filtering
846
- ? t('count.filtered', { hit: visibleDocs.length, total: state.total })
847
- : t('count', { n: state.total })
1340
+ ? t(countKey, { hit: visibleDocs.length, total: state.total })
1341
+ : t(countKey, { n: state.total })
848
1342
 
849
1343
  return h('div', {
850
1344
  className: `knit-root${fullscreen ? ' fullscreen' : ''}`,
851
1345
  ref: rootRef,
852
1346
  },
853
1347
  h('div', { className: 'knit-head' },
854
- h('div', { className: 'knit-root-path', title: state.root }, state.root || '—'),
1348
+ h('button', {
1349
+ type: 'button',
1350
+ className: 'knit-root-path',
1351
+ // 有工作目录才可点;悬停提示说明点了会发生什么
1352
+ title: state.root ? t('path.openTitle') : '',
1353
+ disabled: !state.root,
1354
+ onClick: async () => {
1355
+ setNotice((await openLocalPath(state.root)) || '')
1356
+ },
1357
+ }, state.root || '—'),
855
1358
  h('div', { className: 'knit-count' }, countText),
856
1359
  h('button', { className: 'knit-btn', onClick: load, title: t('action.refreshNow') }, t('action.refresh'))),
857
1360
  h('div', { className: 'knit-bar' },
@@ -876,6 +1379,17 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
876
1379
  if (event.key === 'Escape') { event.stopPropagation(); setQuery('') }
877
1380
  },
878
1381
  })),
1382
+ h('div', { className: 'knit-types', role: 'tablist', 'aria-label': t('kind.title') },
1383
+ [[KIND_DOC, 'kind.doc'], [KIND_MEDIA, 'kind.media'], [KIND_ALL, 'kind.all']].map(([value, labelKey]) =>
1384
+ h('button', {
1385
+ type: 'button',
1386
+ key: value,
1387
+ role: 'tab',
1388
+ 'aria-selected': kind === value,
1389
+ className: `knit-type-btn${kind === value ? ' active' : ''}`,
1390
+ title: t('kind.title'),
1391
+ onClick: () => pickKind(value),
1392
+ }, t(labelKey)))),
879
1393
  h('div', { className: 'knit-topic', title: topicText }, topicText),
880
1394
  notice ? h('div', { className: 'knit-notice' }, notice) : null,
881
1395
  h('div', {
@@ -945,9 +1459,136 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
945
1459
  * @param {Function} onOpen - 点击时的动作,返回是否有宿主接住
946
1460
  * @returns {Function} 组件
947
1461
  */
1462
+ /**
1463
+ * 取当前会话 id(悬停浮层要用它拉列表)。
1464
+ *
1465
+ * 入口按钮坐在 list 座位上,座位不给任何 owner 参数,所以只能从
1466
+ * sessions 列表里读「当前会话」——与聊天视图解析 cwd 用的是同一条路。
1467
+ *
1468
+ * @returns {string} 会话 id,取不到为空串
1469
+ */
1470
+ function currentSessionId() {
1471
+ try {
1472
+ const sessions = rootCtx && typeof rootCtx.get === 'function' ? rootCtx.get('sessions') : null
1473
+ const snapshot = sessions && sessions.list && typeof sessions.list.getSnapshot === 'function'
1474
+ ? sessions.list.getSnapshot()
1475
+ : null
1476
+ return (snapshot && snapshot.current) || ''
1477
+ } catch {
1478
+ return ''
1479
+ }
1480
+ }
1481
+
1482
+ /**
1483
+ * 悬停浮层。只读预览:列出最近几篇,点哪篇就开面板并直接预览哪篇。
1484
+ *
1485
+ * @param {{rect:object|null, status:string, docs:object[], total:number, now:number,
1486
+ * onOpenDoc:Function, onOpenPanel:Function, onEnter:Function, onLeave:Function}} props - 渲染入参
1487
+ * @returns {import('react').ReactElement} 元素
1488
+ */
1489
+ function KnitPeek({ rect, status, docs, total, now, onOpenDoc, onOpenPanel, onEnter, onLeave }) {
1490
+ // 锚在按钮右下方;拿不到 rect(无 DOM / 测试)时给个兜底位置
1491
+ const width = 300
1492
+ const viewportWidth = typeof window !== 'undefined' && window.innerWidth ? window.innerWidth : 1200
1493
+ const right = rect ? Math.max(8, viewportWidth - rect.right) : 16
1494
+ const top = rect ? rect.bottom + 6 : 56
1495
+ const style = { position: 'fixed', top: `${Math.round(top)}px`, right: `${Math.round(right)}px`, width: `${width}px` }
1496
+
1497
+ const body = status === 'loading'
1498
+ ? h('div', { className: 'knit-peek-hint' }, t('preview.loading'))
1499
+ : docs.length === 0
1500
+ ? h('div', { className: 'knit-peek-hint' }, t('peek.empty'))
1501
+ : docs.map((doc) => h('button', {
1502
+ key: doc.path || doc.rel,
1503
+ type: 'button',
1504
+ className: 'knit-peek-doc',
1505
+ title: doc.rel,
1506
+ onClick: () => onOpenDoc(doc),
1507
+ },
1508
+ h('span', { className: 'knit-peek-name' }, doc.title || doc.name || doc.rel),
1509
+ h('span', { className: 'knit-peek-time' }, relTime(doc.mtimeMs, now))))
1510
+
1511
+ return h('div', {
1512
+ className: 'knit-peek',
1513
+ style,
1514
+ onMouseEnter: onEnter,
1515
+ onMouseLeave: onLeave,
1516
+ },
1517
+ h('div', { className: 'knit-peek-head' },
1518
+ h(KnitGlyph, { size: 13 }),
1519
+ h('span', null, t('count', { n: total }))),
1520
+ h('div', { className: 'knit-peek-list' }, body),
1521
+ h('div', { className: 'knit-peek-hint' }, t('peek.openPanel')))
1522
+ }
1523
+
1524
+ /**
1525
+ * 造一个入口按钮组件:**悬停偷看,点击进右边栏**。
1526
+ *
1527
+ * 悬停不碰任何框架 API —— 浮层是我们自己画的,所以不会展开右侧栏、
1528
+ * 不会引发布局变化。(框架的 `sidebarRight.float` 做不到这一点:
1529
+ * `openTab` 一定会展开面板,`float` 又要求 tab 已经停靠。)
1530
+ *
1531
+ * 官方原组件一像素不动,我们只是往 list 座位里追加一项。
1532
+ *
1533
+ * @param {Function} onOpen - 点击时的动作,返回是否有宿主接住
1534
+ * @returns {Function} 组件
1535
+ */
948
1536
  function makeEntryButton(onOpen) {
949
1537
  return function KnitEntryButton() {
950
- return h('button', {
1538
+ const [peek, setPeek] = React.useState(null)
1539
+ const btnRef = React.useRef(null)
1540
+ const showTimer = React.useRef(null)
1541
+ const hideTimer = React.useRef(null)
1542
+
1543
+ /** 清掉两个定时器。 */
1544
+ const clearTimers = () => {
1545
+ if (showTimer.current) { clearTimeout(showTimer.current); showTimer.current = null }
1546
+ if (hideTimer.current) { clearTimeout(hideTimer.current); hideTimer.current = null }
1547
+ }
1548
+
1549
+ /** 拉浮层要显示的那几篇。 */
1550
+ const loadPeek = async () => {
1551
+ const sessionId = currentSessionId()
1552
+ if (!sessionId) {
1553
+ setPeek((cur) => (cur ? { ...cur, status: 'ready', docs: [], total: 0 } : cur))
1554
+ return
1555
+ }
1556
+ try {
1557
+ const url = `${LIST_API}?sessionId=${encodeURIComponent(sessionId)}&limit=${PEEK_LIMIT}&sort=${readSortPref()}`
1558
+ const res = await fetch(url, { headers: { accept: 'application/json' }, cache: 'no-store' })
1559
+ const data = await res.json()
1560
+ setPeek((cur) => (cur
1561
+ ? { ...cur, status: 'ready', docs: (data && data.docs) || [], total: (data && data.total) || 0 }
1562
+ : cur))
1563
+ } catch {
1564
+ setPeek((cur) => (cur ? { ...cur, status: 'ready', docs: [], total: 0 } : cur))
1565
+ }
1566
+ }
1567
+
1568
+ /** 进入:延迟一点再显示,避免鼠标扫过就弹。 */
1569
+ const scheduleShow = () => {
1570
+ clearTimers()
1571
+ showTimer.current = setTimeout(() => {
1572
+ const node = btnRef.current
1573
+ const rect = node && typeof node.getBoundingClientRect === 'function' ? node.getBoundingClientRect() : null
1574
+ setPeek({ rect, status: 'loading', docs: [], total: 0, now: Date.now() })
1575
+ loadPeek()
1576
+ }, PEEK_SHOW_DELAY)
1577
+ }
1578
+
1579
+ /** 离开:延迟一点再收起,给鼠标从按钮移到浮层的时间。 */
1580
+ const scheduleHide = () => {
1581
+ clearTimers()
1582
+ hideTimer.current = setTimeout(() => setPeek(null), PEEK_HIDE_DELAY)
1583
+ }
1584
+
1585
+ return h('span', {
1586
+ className: 'knit-peek-anchor',
1587
+ onMouseEnter: scheduleShow,
1588
+ onMouseLeave: scheduleHide,
1589
+ },
1590
+ h('button', {
1591
+ ref: btnRef,
951
1592
  type: 'button',
952
1593
  className: 'knit-entry',
953
1594
  title: t('entry.label'),
@@ -955,9 +1596,31 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
955
1596
  onClick: (event) => {
956
1597
  if (event && typeof event.preventDefault === 'function') event.preventDefault()
957
1598
  if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1599
+ clearTimers()
1600
+ setPeek(null)
958
1601
  if (!onOpen()) console.warn('[knit] no sidebar host available — the entry button cannot open the panel')
959
1602
  },
960
- }, h(KnitGlyph, { size: 16 }))
1603
+ }, h(KnitGlyph, { size: 16 })),
1604
+ peek ? h(KnitPeek, {
1605
+ ...peek,
1606
+ now: peek.now || Date.now(),
1607
+ // 鼠标移进浮层就取消收起;移出去再计时
1608
+ onEnter: clearTimers,
1609
+ onLeave: scheduleHide,
1610
+ onOpenDoc: (doc) => {
1611
+ // 先发信号再开面板:面板还没挂时它会留成挂起值,
1612
+ // 挂载后第一帧就取走 —— 两种情况都不用等列表
1613
+ requestPreview(doc)
1614
+ clearTimers()
1615
+ setPeek(null)
1616
+ onOpen()
1617
+ },
1618
+ onOpenPanel: () => {
1619
+ clearTimers()
1620
+ setPeek(null)
1621
+ onOpen()
1622
+ },
1623
+ }) : null)
961
1624
  }
962
1625
  }
963
1626
 
@@ -1077,8 +1740,85 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
1077
1740
 
1078
1741
  /* ── 注册 ───────────────────────────────────────── */
1079
1742
 
1743
+ /**
1744
+ * 插件根上下文。apply 时赋值,供「打开本地文件夹」在点击时解析 remote 服务。
1745
+ *
1746
+ * 用「点击时解析」而不是注册时绑定:`remote.session` 可能后到,
1747
+ * 而且宿主可能被换掉(与 openKnitPanel 同一个理由)。
1748
+ */
1749
+ let rootCtx = null
1750
+
1751
+ /**
1752
+ * 「点浮层里的某一篇 → 在面板里直接打开它」的即时信号。
1753
+ *
1754
+ * 为什么不用「挂在某个变量上、等列表拉回来再消费」:
1755
+ * KnitBody 的 load() 是**挂载时一次 + 之后每 5 秒一次**,
1756
+ * 面板已经开着时那样做要等下一次轮询(最长 5 秒才响应)。
1757
+ * 而且列表接口要扫整个工作区(最慢 4 秒),**预览根本不需要等它** ——
1758
+ * 浮层里已经有 rel 和 title 了。
1759
+ *
1760
+ * 所以改成订阅制:面板挂着就立刻送达,没挂就留一份挂起值给挂载时取。
1761
+ */
1762
+ let pendingPreview = null
1763
+ /** @type {Set<Function>} */
1764
+ const previewSubscribers = new Set()
1765
+
1766
+ /**
1767
+ * 请求在面板里打开某一篇。面板挂着就立刻生效,没挂就留一份挂起。
1768
+ * @param {{rel:string, title?:string, name?:string}} doc - 目标文档
1769
+ * @returns {void}
1770
+ */
1771
+ function requestPreview(doc) {
1772
+ if (!doc || !doc.rel) return
1773
+ const target = { rel: doc.rel, title: doc.title || doc.name || doc.rel }
1774
+ if (previewSubscribers.size === 0) {
1775
+ pendingPreview = target
1776
+ return
1777
+ }
1778
+ previewSubscribers.forEach((notify) => notify(target))
1779
+ }
1780
+
1781
+ /**
1782
+ * 订阅预览请求。
1783
+ * @param {Function} notify - 收到目标时调用
1784
+ * @returns {Function} 退订
1785
+ */
1786
+ function subscribePreview(notify) {
1787
+ previewSubscribers.add(notify)
1788
+ return () => previewSubscribers.delete(notify)
1789
+ }
1790
+
1791
+ /**
1792
+ * 用操作系统的文件管理器打开一个本地路径。
1793
+ *
1794
+ * 走官方 Remote:`ctx.remote.session.openWorkspacePath({ path })`。
1795
+ * 它把业务值折进一个信封(`{ ok: true, value } | { ok: false, error }`),
1796
+ * 所以这里要拆信封而不是直接 await 出结果。
1797
+ *
1798
+ * @param {string} path - 绝对路径
1799
+ * @returns {Promise<string>} 空串表示成功,否则是失败原因
1800
+ */
1801
+ async function openLocalPath(path) {
1802
+ if (!path) return t('error.hostFailed')
1803
+ const services = rootCtx && typeof rootCtx.get === 'function' ? rootCtx.get('remote.session') : null
1804
+ if (!services || typeof services.openWorkspacePath !== 'function') {
1805
+ return t('error.noHostTab')
1806
+ }
1807
+ try {
1808
+ const result = await services.openWorkspacePath({ path })
1809
+ if (result && result.ok === false) {
1810
+ const detail = result.error && (result.error.message || result.error.code)
1811
+ return t('error.openFailed', { error: String(detail || 'unknown') })
1812
+ }
1813
+ return ''
1814
+ } catch (error) {
1815
+ return t('error.openFailed', { error: String((error && error.message) || error) })
1816
+ }
1817
+ }
1818
+
1080
1819
  module.exports.inject = ['slots', 'locale']
1081
1820
  module.exports.apply = (ctx) => {
1821
+ rootCtx = ctx
1082
1822
  // ⓪ 国际化:注册双语词典,再把 t 绑到当前活动语言。
1083
1823
  // bind 返回的函数身份稳定、**按调用时读取活动语言**,所以可以长期持有;
1084
1824
  // DSH 切换语言时 locale 会 bump revision,插座运行时据此重渲染,