dsh-knit 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +178 -0
- package/README.md +167 -0
- package/assets/knit-icon-24-mono-4px.svg +1 -0
- package/cordis.patch.yml +8 -0
- package/package.json +63 -0
- package/src/client/client.js +1170 -0
- package/src/host/index.js +653 -0
- package/src/host/relevance.js +236 -0
- package/test/client.test.mjs +500 -0
- package/test/entry.test.mjs +232 -0
- package/test/harness.mjs +235 -0
- package/test/host.test.mjs +249 -0
- package/test/i18n.test.mjs +344 -0
- package/test/icon.test.mjs +153 -0
- package/test/tier1.test.mjs +443 -0
|
@@ -0,0 +1,1170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Knit · 浏览器半边
|
|
3
|
+
*
|
|
4
|
+
* 在两个宿主上注册同一个「最近文档」面板:
|
|
5
|
+
* 1. DSH 自带右侧栏(@deepseek-ai/dsh-client-ui-sidebar-right)—— 主路径
|
|
6
|
+
* 2. dsh-better-sidebar 的 ctx.betterSidebar.registerTab —— 可选,吃到它那批用户
|
|
7
|
+
*
|
|
8
|
+
* 面板本身:列表(相关性或 mtime 排序 + 过滤 + 键盘导航)+ 列表下方的就地预览。
|
|
9
|
+
* 两个宿主共用同一个 KnitBody,只在「怎么开新标签页」上用适配器分叉。
|
|
10
|
+
*
|
|
11
|
+
* 构建:无。手写脚本,由 __ModuleLoader__ 直接装载,用 React.createElement 而非 JSX。
|
|
12
|
+
*/
|
|
13
|
+
window.__ModuleLoader__.load({
|
|
14
|
+
id: 'dsh-knit',
|
|
15
|
+
factory: (require) => {
|
|
16
|
+
const module = { exports: {} }
|
|
17
|
+
const React = require('react')
|
|
18
|
+
const h = React.createElement
|
|
19
|
+
|
|
20
|
+
/* ── 国际化(DSH 官方 ctx.locale)─────────────────── */
|
|
21
|
+
|
|
22
|
+
/** 本插件在 DSH locale 注册表里的命名空间。 */
|
|
23
|
+
const NS = 'knit'
|
|
24
|
+
|
|
25
|
+
/** 中文词典(源语言)。 */
|
|
26
|
+
const ZH = {
|
|
27
|
+
'type.label': 'Knit',
|
|
28
|
+
'guide.title': 'Knit 最近文档',
|
|
29
|
+
'guide.description': '按对话相关性排序,点开就地预览',
|
|
30
|
+
'entry.label': 'Knit 最近文档',
|
|
31
|
+
|
|
32
|
+
'count': '{n} 篇',
|
|
33
|
+
'count.filtered': '{hit} / {total} 篇',
|
|
34
|
+
'action.refresh': '刷新',
|
|
35
|
+
'action.refreshNow': '立即刷新',
|
|
36
|
+
|
|
37
|
+
'sort.relevance': '相关',
|
|
38
|
+
'sort.time': '最新',
|
|
39
|
+
'sort.relevanceTitle': '按与当前对话的相关性排序(纯本地关键词匹配,不调模型)',
|
|
40
|
+
'sort.timeTitle': '按文件修改时间倒序',
|
|
41
|
+
|
|
42
|
+
'filter.placeholder': '过滤标题 / 摘要 / 路径',
|
|
43
|
+
'filter.aria': '过滤文档',
|
|
44
|
+
|
|
45
|
+
'topic.relevance': '🤖 按「{topic}」排序',
|
|
46
|
+
'topic.relevancePlain': '🤖 相关性排序',
|
|
47
|
+
'topic.needsConversation': '对话内容还不足,暂按最新排序',
|
|
48
|
+
'topic.time': '按修改时间倒序',
|
|
49
|
+
|
|
50
|
+
'row.tooltip': '{path}\n单击就地预览 · 双击在新标签页打开',
|
|
51
|
+
'summary.empty': '(没有正文摘要)',
|
|
52
|
+
|
|
53
|
+
'list.scanning': '正在扫描工作区…',
|
|
54
|
+
'list.failed': '读取失败:{error}',
|
|
55
|
+
'list.failedHint': '确认插件宿主半边已加载。',
|
|
56
|
+
'list.empty': '这个工作区里还没有 Markdown 文档。',
|
|
57
|
+
'list.noMatch': '没有匹配「{query}」的文档。',
|
|
58
|
+
|
|
59
|
+
'preview.loading': '正在读取…',
|
|
60
|
+
'preview.truncated': '(文件较大,仅预览前 512 KB)',
|
|
61
|
+
'preview.fullscreen': '全屏',
|
|
62
|
+
'preview.exitFullscreen': '退出全屏',
|
|
63
|
+
'preview.fullscreenTitle': '全屏阅读',
|
|
64
|
+
'preview.exitFullscreenTitle': '退出全屏(Esc)',
|
|
65
|
+
'preview.newTab': '新标签页',
|
|
66
|
+
'preview.newTabTitle': '在新标签页打开',
|
|
67
|
+
'preview.close': '收起预览',
|
|
68
|
+
'preview.resizeTitle': '拖动调整高度',
|
|
69
|
+
'preview.rawFallback': '原生 Markdown 渲染不可用,下面是纯文本。请看控制台的 [knit] 日志。',
|
|
70
|
+
'code.copy': '复制',
|
|
71
|
+
'code.copied': '已复制',
|
|
72
|
+
|
|
73
|
+
'error.noSession': '当前 tab 没有 sessionId',
|
|
74
|
+
'error.hostFailed': '宿主返回失败',
|
|
75
|
+
'error.noHostTab': '当前宿主没有提供「在新标签页打开」',
|
|
76
|
+
'error.noOpenResource': '座位没有提供 tab.actions.openResource',
|
|
77
|
+
'error.openFailed': '打开失败:{error}',
|
|
78
|
+
'error.bsNoContext': 'better-sidebar 上下文不可用',
|
|
79
|
+
'error.bsNoService': 'betterSidebar 服务不可用',
|
|
80
|
+
'error.bsEditorDisabled': 'better-sidebar 的「编辑器」标签页被禁用了(设置 → 侧边卡片)',
|
|
81
|
+
|
|
82
|
+
'host.outsideWorkspace': '路径越出工作区',
|
|
83
|
+
'host.markdownOnly': '只支持 Markdown',
|
|
84
|
+
'host.notFound': '文件不存在',
|
|
85
|
+
'host.notAFile': '不是普通文件',
|
|
86
|
+
'host.imageOnly': '只允许图片类型',
|
|
87
|
+
'host.imageTooLarge': '图片过大',
|
|
88
|
+
'host.readFailed': '读取失败',
|
|
89
|
+
'host.missingRel': '缺少 rel 参数',
|
|
90
|
+
'host.internal': '宿主内部错误',
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 英文词典。键必须与 ZH 完全一致(有测试守着)。 */
|
|
94
|
+
const EN = {
|
|
95
|
+
'type.label': 'Knit',
|
|
96
|
+
'guide.title': 'Knit — recent documents',
|
|
97
|
+
'guide.description': 'Relevance-sorted, click to preview in place',
|
|
98
|
+
'entry.label': 'Knit — recent documents',
|
|
99
|
+
|
|
100
|
+
'count': '{n} docs',
|
|
101
|
+
'count.filtered': '{hit} / {total} docs',
|
|
102
|
+
'action.refresh': 'Refresh',
|
|
103
|
+
'action.refreshNow': 'Refresh now',
|
|
104
|
+
|
|
105
|
+
'sort.relevance': 'Relevant',
|
|
106
|
+
'sort.time': 'Recent',
|
|
107
|
+
'sort.relevanceTitle': 'Sort by relevance to the current conversation (local keyword matching, no model call)',
|
|
108
|
+
'sort.timeTitle': 'Sort by file modified time, newest first',
|
|
109
|
+
|
|
110
|
+
'filter.placeholder': 'Filter title / summary / path',
|
|
111
|
+
'filter.aria': 'Filter documents',
|
|
112
|
+
|
|
113
|
+
'topic.relevance': '🤖 Sorted by “{topic}”',
|
|
114
|
+
'topic.relevancePlain': '🤖 Sorted by relevance',
|
|
115
|
+
'topic.needsConversation': 'Not enough conversation yet — sorted by time',
|
|
116
|
+
'topic.time': 'Sorted by modified time',
|
|
117
|
+
|
|
118
|
+
'row.tooltip': '{path}\nClick to preview here · double-click to open in a new tab',
|
|
119
|
+
'summary.empty': '(no summary)',
|
|
120
|
+
|
|
121
|
+
'list.scanning': 'Scanning the workspace…',
|
|
122
|
+
'list.failed': 'Failed to read: {error}',
|
|
123
|
+
'list.failedHint': 'Make sure the plugin’s host half is loaded.',
|
|
124
|
+
'list.empty': 'No Markdown documents in this workspace yet.',
|
|
125
|
+
'list.noMatch': 'No documents match “{query}”.',
|
|
126
|
+
|
|
127
|
+
'preview.loading': 'Loading…',
|
|
128
|
+
'preview.truncated': '(large file — showing the first 512 KB)',
|
|
129
|
+
'preview.fullscreen': 'Fullscreen',
|
|
130
|
+
'preview.exitFullscreen': 'Exit fullscreen',
|
|
131
|
+
'preview.fullscreenTitle': 'Read fullscreen',
|
|
132
|
+
'preview.exitFullscreenTitle': 'Exit fullscreen (Esc)',
|
|
133
|
+
'preview.newTab': 'New tab',
|
|
134
|
+
'preview.newTabTitle': 'Open in a new tab',
|
|
135
|
+
'preview.close': 'Close preview',
|
|
136
|
+
'preview.resizeTitle': 'Drag to resize',
|
|
137
|
+
'preview.rawFallback': 'Native Markdown rendering is unavailable — showing plain text. Check the [knit] logs in the console.',
|
|
138
|
+
'code.copy': 'Copy',
|
|
139
|
+
'code.copied': 'Copied',
|
|
140
|
+
|
|
141
|
+
'error.noSession': 'This tab has no sessionId',
|
|
142
|
+
'error.hostFailed': 'The host returned a failure',
|
|
143
|
+
'error.noHostTab': 'This host cannot open a new tab',
|
|
144
|
+
'error.noOpenResource': 'The seat did not provide tab.actions.openResource',
|
|
145
|
+
'error.openFailed': 'Open failed: {error}',
|
|
146
|
+
'error.bsNoContext': 'better-sidebar context is unavailable',
|
|
147
|
+
'error.bsNoService': 'The betterSidebar service is unavailable',
|
|
148
|
+
'error.bsEditorDisabled': 'better-sidebar’s Editor tab is disabled (Settings → Side card)',
|
|
149
|
+
|
|
150
|
+
'host.outsideWorkspace': 'Path escapes the workspace',
|
|
151
|
+
'host.markdownOnly': 'Markdown only',
|
|
152
|
+
'host.notFound': 'File not found',
|
|
153
|
+
'host.notAFile': 'Not a regular file',
|
|
154
|
+
'host.imageOnly': 'Images only',
|
|
155
|
+
'host.imageTooLarge': 'Image too large',
|
|
156
|
+
'host.readFailed': 'Read failed',
|
|
157
|
+
'host.missingRel': 'Missing the rel parameter',
|
|
158
|
+
'host.internal': 'Internal host error',
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 把 `{name}` 占位符换成实参。
|
|
163
|
+
* @param {string} template - 模板串
|
|
164
|
+
* @param {object} [params] - 实参
|
|
165
|
+
* @returns {string} 结果
|
|
166
|
+
*/
|
|
167
|
+
function format(template, params) {
|
|
168
|
+
if (!params) return template
|
|
169
|
+
return template.replace(/\{(\w+)\}/g, (whole, key) => (
|
|
170
|
+
Object.prototype.hasOwnProperty.call(params, key) ? String(params[key]) : whole
|
|
171
|
+
))
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* 当前翻译函数。`apply` 时绑到 ctx.locale;未绑定时退回中文词典,
|
|
176
|
+
* 这样单测里不装 locale 也能直接渲染(真实运行时一定会绑)。
|
|
177
|
+
*/
|
|
178
|
+
let t = (key, params) => format(ZH[key] !== undefined ? ZH[key] : key, params)
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 宿主错误码 → 词典键。
|
|
182
|
+
*
|
|
183
|
+
* 宿主只返回机器可读的码,文案在这里翻译 —— 这样宿主与 UI 语言解耦。
|
|
184
|
+
* 未登记的码原样显示(便于发现宿主新增了码但忘了翻译)。
|
|
185
|
+
*/
|
|
186
|
+
const HOST_ERROR_KEY = {
|
|
187
|
+
'knit/outside-workspace': 'host.outsideWorkspace',
|
|
188
|
+
'knit/markdown-only': 'host.markdownOnly',
|
|
189
|
+
'knit/not-found': 'host.notFound',
|
|
190
|
+
'knit/not-a-file': 'host.notAFile',
|
|
191
|
+
'knit/image-only': 'host.imageOnly',
|
|
192
|
+
'knit/image-too-large': 'host.imageTooLarge',
|
|
193
|
+
'knit/read-failed': 'host.readFailed',
|
|
194
|
+
'knit/missing-rel': 'host.missingRel',
|
|
195
|
+
'knit/internal': 'host.internal',
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* 把一个失败的宿主响应翻成当前语言的文案。
|
|
200
|
+
* @param {object} data - 宿主载荷
|
|
201
|
+
* @returns {string} 文案
|
|
202
|
+
*/
|
|
203
|
+
function hostMessage(data) {
|
|
204
|
+
const code = data && data.code
|
|
205
|
+
if (!code) return t('error.hostFailed')
|
|
206
|
+
const key = HOST_ERROR_KEY[code]
|
|
207
|
+
return key ? t(key) : code
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* DSH 共享的 Markdown 渲染器(@deepseek-ai/dsh-client-ui-primitives 的 MarkdownText,
|
|
212
|
+
* 官方 ui-sidebar-documentpreview 与 dsh-better-sidebar 用的是同一个)。
|
|
213
|
+
*
|
|
214
|
+
* ⚠️ 它由 `React.memo()` 包出来,值是**对象**不是函数
|
|
215
|
+
* (`{ $$typeof: Symbol(react.memo), type: fn }`)。所以这里只能判空,
|
|
216
|
+
* 不能用 `typeof === 'function'` —— 那样会把可用的渲染器误判成不可用,
|
|
217
|
+
* 一路静默降级成纯文本(真实踩过的坑)。React 认这个对象形态,直接交给
|
|
218
|
+
* createElement 渲染即可。
|
|
219
|
+
*/
|
|
220
|
+
let MarkdownText = null
|
|
221
|
+
try {
|
|
222
|
+
const primitives = require('@deepseek-ai/dsh-client-ui-primitives')
|
|
223
|
+
const candidate = primitives && primitives.MarkdownText
|
|
224
|
+
if (candidate !== undefined && candidate !== null) MarkdownText = candidate
|
|
225
|
+
else console.warn('[knit] ui-primitives does not export MarkdownText — preview falls back to plain text')
|
|
226
|
+
} catch (error) {
|
|
227
|
+
console.warn('[knit] could not load ui-primitives.MarkdownText — preview falls back to plain text', error)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/* ── 常量 ───────────────────────────────────────── */
|
|
231
|
+
|
|
232
|
+
/** 官方右侧栏 tab 的身份,也是 body/title 注册用的 key。 */
|
|
233
|
+
const TAB_ID = 'dsh-knit:recent'
|
|
234
|
+
/** page 类型判别符;openTab('knit') 用它。 */
|
|
235
|
+
const KIND = 'knit'
|
|
236
|
+
/** better-sidebar 里这个 tab 的 id。 */
|
|
237
|
+
const BS_TAB_ID = 'knit:recent'
|
|
238
|
+
|
|
239
|
+
const LIST_API = '/knit/api/recent'
|
|
240
|
+
const DOC_API = '/knit/api/doc'
|
|
241
|
+
const RAW_API = '/knit/api/raw'
|
|
242
|
+
|
|
243
|
+
/** 轮询间隔。 */
|
|
244
|
+
const POLL_MS = 5000
|
|
245
|
+
/** 多久之内算「新」,打 🆕 标记。 */
|
|
246
|
+
const NEW_WINDOW_MS = 2 * 60 * 1000
|
|
247
|
+
|
|
248
|
+
/** 用户偏好(选了就记住)。 */
|
|
249
|
+
const SORT_KEY = 'dsh-knit:sort'
|
|
250
|
+
const RATIO_KEY = 'dsh-knit:preview-ratio'
|
|
251
|
+
|
|
252
|
+
/** 预览面板高度的上下限:任何一端都不把对方挤没。 */
|
|
253
|
+
const MIN_RATIO = 0.2
|
|
254
|
+
const MAX_RATIO = 0.8
|
|
255
|
+
const DEFAULT_RATIO = 0.46
|
|
256
|
+
|
|
257
|
+
/* ── 样式:跟随 DSH 主题令牌,深浅色自适应 ───────────────── */
|
|
258
|
+
const STYLE_ID = 'dsh-knit-style'
|
|
259
|
+
const CSS = `
|
|
260
|
+
.knit-root{display:flex;flex-direction:column;height:100%;min-height:0;
|
|
261
|
+
color:var(--dsw-alias-label-primary,#e8eaed);font-size:13px}
|
|
262
|
+
.knit-head{display:flex;align-items:center;gap:8px;padding:10px 12px 8px;flex:none}
|
|
263
|
+
.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)}
|
|
265
|
+
.knit-count{font-size:11px;color:var(--dsw-alias-label-caption,#80868b);flex:none}
|
|
266
|
+
.knit-btn{flex:none;display:inline-flex;align-items:center;justify-content:center;
|
|
267
|
+
height:24px;padding:0 9px;border-radius:6px;cursor:pointer;
|
|
268
|
+
background:transparent;color:var(--dsw-alias-label-secondary,#9aa0a6);
|
|
269
|
+
border:.5px solid var(--dsw-alias-border-l4,rgba(255,255,255,.08));font-size:11px}
|
|
270
|
+
.knit-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06));
|
|
271
|
+
color:var(--dsw-alias-label-primary,#e8eaed)}
|
|
272
|
+
.knit-bar{display:flex;align-items:center;gap:8px;padding:0 12px 8px;flex:none}
|
|
273
|
+
.knit-seg{display:inline-flex;flex:none;border-radius:7px;overflow:hidden;
|
|
274
|
+
border:.5px solid var(--dsw-alias-border-l4,rgba(255,255,255,.1))}
|
|
275
|
+
.knit-seg-btn{height:22px;padding:0 10px;cursor:pointer;font-size:11px;border:none;
|
|
276
|
+
background:transparent;color:var(--dsw-alias-label-secondary,#9aa0a6)}
|
|
277
|
+
.knit-seg-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06))}
|
|
278
|
+
.knit-seg-btn.active{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.1));
|
|
279
|
+
color:var(--dsw-alias-label-primary,#e8eaed);font-weight:600}
|
|
280
|
+
.knit-filter{flex:1;min-width:0;height:24px;padding:0 9px;border-radius:7px;font-size:11px;
|
|
281
|
+
background:transparent;color:var(--dsw-alias-label-primary,#e8eaed);
|
|
282
|
+
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)}
|
|
284
|
+
.knit-filter::placeholder{color:var(--dsw-alias-label-caption,#80868b)}
|
|
285
|
+
.knit-topic{flex:none;padding:0 12px 8px;font-size:10.5px;line-height:1.4;
|
|
286
|
+
color:var(--dsw-alias-label-caption,#80868b);
|
|
287
|
+
border-bottom:.5px solid var(--dsw-alias-border-l4,rgba(255,255,255,.08));
|
|
288
|
+
overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
289
|
+
.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)}
|
|
291
|
+
.knit-list::-webkit-scrollbar{width:6px}
|
|
292
|
+
.knit-list::-webkit-scrollbar-thumb{background:rgba(255,255,255,.14);border-radius:3px}
|
|
293
|
+
.knit-doc{padding:10px 11px;border-radius:10px;cursor:pointer;
|
|
294
|
+
border:.5px solid transparent;background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.03));
|
|
295
|
+
transition:background .18s,border-color .18s,transform .18s,opacity .18s}
|
|
296
|
+
.knit-doc:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06));
|
|
297
|
+
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)}
|
|
299
|
+
/* .knit-doc.cursor 故意不设样式:键盘焦点靠「移动即预览」的预览面板表达,
|
|
300
|
+
再加描边会与 .active 的整块蓝色背景重复,显得突兀 */
|
|
301
|
+
.knit-row1{display:flex;align-items:center;gap:8px;margin-bottom:5px}
|
|
302
|
+
.knit-title{flex:1;min-width:0;font-weight:600;font-size:12.5px;line-height:1.4;
|
|
303
|
+
overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
304
|
+
.knit-time{flex:none;font-size:10.5px;color:var(--dsw-alias-label-caption,#80868b)}
|
|
305
|
+
.knit-sum{font-size:11.5px;line-height:1.55;color:var(--dsw-alias-label-secondary,#9aa0a6);
|
|
306
|
+
display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
|
|
307
|
+
.knit-sum.empty{font-style:italic;color:var(--dsw-alias-label-caption,#80868b)}
|
|
308
|
+
.knit-meta{margin-top:6px;font-size:10px;color:var(--dsw-alias-label-caption,#80868b);
|
|
309
|
+
overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
310
|
+
.knit-msg{padding:24px 16px;text-align:center;font-size:12px;
|
|
311
|
+
color:var(--dsw-alias-label-caption,#80868b);line-height:1.7}
|
|
312
|
+
.knit-notice{margin:6px 8px 0;padding:7px 10px;border-radius:7px;font-size:11px;line-height:1.5;
|
|
313
|
+
background:rgba(255,120,120,.12);border:.5px solid rgba(255,120,120,.3);color:#ffb4b4}
|
|
314
|
+
.knit-badge{font-size:10px;margin-right:3px}
|
|
315
|
+
|
|
316
|
+
/* ── 列表下方的预览面板 ─────────────────────────────── */
|
|
317
|
+
.knit-preview{flex:none;display:flex;flex-direction:column;min-height:0;
|
|
318
|
+
border-top:.5px solid var(--dsw-alias-border-l4,rgba(255,255,255,.1));
|
|
319
|
+
background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.02))}
|
|
320
|
+
.knit-resize{flex:none;height:7px;cursor:ns-resize;background:transparent;position:relative}
|
|
321
|
+
.knit-resize::after{content:'';position:absolute;left:50%;top:2px;transform:translateX(-50%);
|
|
322
|
+
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)}
|
|
324
|
+
.knit-preview-head{display:flex;align-items:center;gap:8px;padding:6px 12px 8px;flex:none;
|
|
325
|
+
border-bottom:.5px solid var(--dsw-alias-border-l4,rgba(255,255,255,.06))}
|
|
326
|
+
.knit-preview-title{flex:1;min-width:0;font-size:12px;font-weight:600;
|
|
327
|
+
overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
328
|
+
.knit-preview-body{flex:1;min-height:0;overflow-y:auto;padding:10px 14px 16px;font-size:12.5px}
|
|
329
|
+
.knit-preview-body::-webkit-scrollbar{width:6px}
|
|
330
|
+
.knit-preview-body::-webkit-scrollbar-thumb{background:rgba(255,255,255,.14);border-radius:3px}
|
|
331
|
+
.knit-preview-close{flex:none;width:24px;height:24px;border-radius:6px;cursor:pointer;
|
|
332
|
+
display:inline-flex;align-items:center;justify-content:center;font-size:13px;
|
|
333
|
+
background:transparent;border:none;color:var(--dsw-alias-label-secondary,#9aa0a6)}
|
|
334
|
+
.knit-preview-close:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08));
|
|
335
|
+
color:var(--dsw-alias-label-primary,#e8eaed)}
|
|
336
|
+
.knit-raw{margin:0;white-space:pre-wrap;word-break:break-word;font-size:11.5px;line-height:1.6;
|
|
337
|
+
color:var(--dsw-alias-label-secondary,#9aa0a6);font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
338
|
+
.knit-preview-note{font-size:11px;color:var(--dsw-alias-label-caption,#80868b);padding:2px 0 8px}
|
|
339
|
+
|
|
340
|
+
/* Knit 图标:不跟随文本色,浅色模式纯黑、暗色模式纯白。
|
|
341
|
+
DSH 的暗色信号是 body[data-ds-dark-theme](官方 CSS 用的就是这个)。 */
|
|
342
|
+
.knit-icon{color:#000}
|
|
343
|
+
body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
344
|
+
|
|
345
|
+
/* 入口按钮:挂在会话头部右侧与输入框工具行两处 list 座位上 */
|
|
346
|
+
.knit-entry{display:inline-flex;align-items:center;justify-content:center;flex:none;
|
|
347
|
+
width:28px;height:28px;padding:0;border:none;border-radius:8px;cursor:pointer;
|
|
348
|
+
background:transparent;color:var(--dsw-alias-label-secondary,#9aa0a6);
|
|
349
|
+
transition:background .15s}
|
|
350
|
+
.knit-entry:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08))}
|
|
351
|
+
.knit-entry:active{transform:scale(.94)}
|
|
352
|
+
|
|
353
|
+
/* 全屏阅读:藏掉头部与列表,只留预览 */
|
|
354
|
+
.knit-root.fullscreen .knit-head,
|
|
355
|
+
.knit-root.fullscreen .knit-bar,
|
|
356
|
+
.knit-root.fullscreen .knit-topic,
|
|
357
|
+
.knit-root.fullscreen .knit-list{display:none}
|
|
358
|
+
.knit-root.fullscreen .knit-preview{flex:1 1 auto;max-height:none}
|
|
359
|
+
`
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* 把样式表插进文档一次。
|
|
363
|
+
* @returns {void}
|
|
364
|
+
*/
|
|
365
|
+
function ensureStyle() {
|
|
366
|
+
if (typeof document === 'undefined') return
|
|
367
|
+
if (document.getElementById(STYLE_ID)) return
|
|
368
|
+
const el = document.createElement('style')
|
|
369
|
+
el.id = STYLE_ID
|
|
370
|
+
el.textContent = CSS
|
|
371
|
+
document.head.appendChild(el)
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/* ── 用户偏好 ───────────────────────────────────── */
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* 读一个 localStorage 偏好。
|
|
378
|
+
* @param {string} key - 键
|
|
379
|
+
* @returns {string|null} 值
|
|
380
|
+
*/
|
|
381
|
+
function readPref(key) {
|
|
382
|
+
try {
|
|
383
|
+
return window.localStorage.getItem(key)
|
|
384
|
+
} catch {
|
|
385
|
+
return null
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* 写一个 localStorage 偏好。
|
|
391
|
+
* @param {string} key - 键
|
|
392
|
+
* @param {string} value - 值
|
|
393
|
+
* @returns {void}
|
|
394
|
+
*/
|
|
395
|
+
function writePref(key, value) {
|
|
396
|
+
try { window.localStorage.setItem(key, value) } catch { /* 隐私模式忽略 */ }
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* 读用户上次选的排序方式。
|
|
401
|
+
* @returns {'relevance'|'time'} 排序方式
|
|
402
|
+
*/
|
|
403
|
+
function readSortPref() {
|
|
404
|
+
return readPref(SORT_KEY) === 'time' ? 'time' : 'relevance'
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* 把预览高度比例夹到合法区间。
|
|
409
|
+
* @param {number} value - 原始比例
|
|
410
|
+
* @returns {number} 夹紧后的比例
|
|
411
|
+
*/
|
|
412
|
+
function clampRatio(value) {
|
|
413
|
+
const n = Number(value)
|
|
414
|
+
if (!Number.isFinite(n)) return DEFAULT_RATIO
|
|
415
|
+
return Math.min(MAX_RATIO, Math.max(MIN_RATIO, n))
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* 读用户上次拖的预览高度。
|
|
420
|
+
* @returns {number} 0.2–0.8
|
|
421
|
+
*/
|
|
422
|
+
function readRatioPref() {
|
|
423
|
+
const raw = readPref(RATIO_KEY)
|
|
424
|
+
return raw === null ? DEFAULT_RATIO : clampRatio(Number(raw))
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/* ── 路径处理 ───────────────────────────────────── */
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* 组件级编码一个地址段:`:` 保持字面量(盘符要按原样读)。
|
|
431
|
+
* @param {string} seg - 段
|
|
432
|
+
* @returns {string} 编码后的段
|
|
433
|
+
*/
|
|
434
|
+
function encodeSegment(seg) {
|
|
435
|
+
return encodeURIComponent(seg).replace(/%3A/gi, ':')
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* 拼一个 `dsh-resource://file/session/<id>/<path>` 地址,交给官方预览认领。
|
|
440
|
+
* 归一化规则与官方 sessionFileAddress 一致。
|
|
441
|
+
* @param {string} sessionId - 会话 id
|
|
442
|
+
* @param {string} relPath - 相对工作区根的 `/` 分隔路径
|
|
443
|
+
* @returns {string} 资源地址
|
|
444
|
+
*/
|
|
445
|
+
function sessionFileAddress(sessionId, relPath) {
|
|
446
|
+
const norm = String(relPath || '')
|
|
447
|
+
.replace(/\\/g, '/')
|
|
448
|
+
.replace(/^(?:\.\/)+/, '')
|
|
449
|
+
const tail = norm.split('/').filter(Boolean).map(encodeSegment).join('/')
|
|
450
|
+
return `dsh-resource://file/session/${encodeSegment(sessionId)}/${tail}`
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* 把 Markdown 里的相对图片地址解析成工作区相对路径。
|
|
455
|
+
*
|
|
456
|
+
* 带协议的(http: / data: / file:…)与页内锚点一律返回空串 —— 那些交给 MarkdownText 自己处理。
|
|
457
|
+
*
|
|
458
|
+
* @param {string} docRel - 当前文档的工作区相对路径
|
|
459
|
+
* @param {string} src - Markdown 里写的原始地址
|
|
460
|
+
* @returns {string} 工作区相对路径;不适用时为空串
|
|
461
|
+
*/
|
|
462
|
+
function resolveRelative(docRel, src) {
|
|
463
|
+
const clean = String(src || '').trim()
|
|
464
|
+
if (!clean) return ''
|
|
465
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(clean)) return ''
|
|
466
|
+
if (clean.startsWith('#') || clean.startsWith('//')) return ''
|
|
467
|
+
|
|
468
|
+
const cut = clean.search(/[?#]/)
|
|
469
|
+
const pathOnly = cut === -1 ? clean : clean.slice(0, cut)
|
|
470
|
+
const dir = docRel.includes('/') ? docRel.slice(0, docRel.lastIndexOf('/')) : ''
|
|
471
|
+
const segments = (dir ? `${dir}/${pathOnly}` : pathOnly).split('/')
|
|
472
|
+
|
|
473
|
+
const out = []
|
|
474
|
+
for (const seg of segments) {
|
|
475
|
+
if (!seg || seg === '.') continue
|
|
476
|
+
if (seg === '..') { out.pop(); continue }
|
|
477
|
+
out.push(seg)
|
|
478
|
+
}
|
|
479
|
+
return out.join('/')
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* 给 MarkdownText 的相对路径图片解析器。
|
|
484
|
+
*
|
|
485
|
+
* 契约(从 ui-primitives 实现反推):返回的对象要有 `resolve(src)`,
|
|
486
|
+
* 返回值最终会被 `new URL(v)` 解析并只接受 http/https/blob/data —— 所以
|
|
487
|
+
* 返回同源相对地址(`/knit/api/raw?...`)是合法的。
|
|
488
|
+
*
|
|
489
|
+
* @param {string} sessionId - 会话 id
|
|
490
|
+
* @param {string} docRel - 当前文档的工作区相对路径
|
|
491
|
+
* @returns {{resolve: (src: string) => (string|undefined)}} 解析器
|
|
492
|
+
*/
|
|
493
|
+
function pathImagesFor(sessionId, docRel) {
|
|
494
|
+
return {
|
|
495
|
+
resolve(src) {
|
|
496
|
+
const rel = resolveRelative(docRel, src)
|
|
497
|
+
if (!rel) return undefined
|
|
498
|
+
return `${RAW_API}?sessionId=${encodeURIComponent(sessionId)}&rel=${encodeURIComponent(rel)}`
|
|
499
|
+
},
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* 人类可读的相对时间。
|
|
505
|
+
* @param {number} ms - 文件 mtime(epoch ms)
|
|
506
|
+
* @param {number} now - 当前时间
|
|
507
|
+
* @returns {string} 刚刚 / X分钟前 / X小时前 / 昨天 / X天前 / 月日
|
|
508
|
+
*/
|
|
509
|
+
function relTime(ms, now) {
|
|
510
|
+
const diff = Math.max(0, now - ms)
|
|
511
|
+
const min = Math.floor(diff / 60000)
|
|
512
|
+
if (min < 1) return '刚刚'
|
|
513
|
+
if (min < 60) return `${min}分钟前`
|
|
514
|
+
const hour = Math.floor(min / 60)
|
|
515
|
+
if (hour < 24) return `${hour}小时前`
|
|
516
|
+
const day = Math.floor(hour / 24)
|
|
517
|
+
if (day === 1) return '昨天'
|
|
518
|
+
if (day < 30) return `${day}天前`
|
|
519
|
+
const d = new Date(ms)
|
|
520
|
+
return `${d.getMonth() + 1}月${d.getDate()}日`
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/* ── 组件 ───────────────────────────────────────── */
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* 一条文档卡片。
|
|
527
|
+
*
|
|
528
|
+
* 相关性**不做任何可视化**:排序本身已经表达了相关度,名次就是答案。
|
|
529
|
+
* 曾经加过百分比数字和长条,实测都是噪音 —— 数字会被误读成绝对概率,
|
|
530
|
+
* 长条对「找到那篇文档」这件事没有帮助。
|
|
531
|
+
*
|
|
532
|
+
* `cursor` 这个 class 保留在 DOM 上(键盘焦点位置,可观测、也给测试用),
|
|
533
|
+
* 但**不配任何样式**:既然是「移动即预览」,预览面板本身就是焦点指示。
|
|
534
|
+
*
|
|
535
|
+
* @param {{doc:object,now:number,active:boolean,cursor:boolean,relevance:boolean,onSelect:Function,onOpenTab:Function}} props - 渲染入参
|
|
536
|
+
* @returns {import('react').ReactElement} 元素
|
|
537
|
+
*/
|
|
538
|
+
function DocRow({ doc, now, active, cursor, relevance, onSelect, onOpenTab }) {
|
|
539
|
+
const fresh = now - doc.mtimeMs < NEW_WINDOW_MS
|
|
540
|
+
|
|
541
|
+
return h('div', {
|
|
542
|
+
className: `knit-doc${active ? ' active' : ''}${cursor ? ' cursor' : ''}${fresh ? ' fresh' : ''}`,
|
|
543
|
+
'data-knit-rel': doc.rel,
|
|
544
|
+
title: t('row.tooltip', { path: doc.rel }),
|
|
545
|
+
onClick: () => onSelect(doc),
|
|
546
|
+
onDoubleClick: () => onOpenTab(doc),
|
|
547
|
+
},
|
|
548
|
+
h('div', { className: 'knit-row1' },
|
|
549
|
+
h('div', { className: 'knit-title' },
|
|
550
|
+
fresh ? h('span', { className: 'knit-badge' }, '🆕') : null,
|
|
551
|
+
doc.title || doc.name),
|
|
552
|
+
h('div', { className: 'knit-time' }, relTime(doc.mtimeMs, now))),
|
|
553
|
+
doc.summary
|
|
554
|
+
? h('div', { className: 'knit-sum' }, doc.summary)
|
|
555
|
+
: h('div', { className: 'knit-sum empty' }, t('summary.empty')),
|
|
556
|
+
h('div', { className: 'knit-meta' }, doc.rel))
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* 列表下方的预览面板。
|
|
561
|
+
* @param {{preview:object,pathImages:object|null,fullscreen:boolean,onClose:Function,onOpenTab:Function,onToggleFullscreen:Function,onResizeStart:Function}} props - 渲染入参
|
|
562
|
+
* @returns {import('react').ReactElement} 元素
|
|
563
|
+
*/
|
|
564
|
+
function PreviewPanel({ preview, pathImages, fullscreen, ratio, onClose, onOpenTab, onToggleFullscreen, onResizeStart }) {
|
|
565
|
+
const body = preview.status === 'loading'
|
|
566
|
+
? h('div', { className: 'knit-preview-note' }, t('preview.loading'))
|
|
567
|
+
: preview.status === 'error'
|
|
568
|
+
? 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))
|
|
580
|
+
|
|
581
|
+
return h('div', {
|
|
582
|
+
className: 'knit-preview',
|
|
583
|
+
style: fullscreen ? undefined : { maxHeight: `${Math.round(ratio * 100)}%` },
|
|
584
|
+
},
|
|
585
|
+
fullscreen ? null : h('div', { className: 'knit-resize', onPointerDown: onResizeStart, title: t('preview.resizeTitle') }),
|
|
586
|
+
h('div', { className: 'knit-preview-head' },
|
|
587
|
+
h('div', { className: 'knit-preview-title', title: preview.rel }, preview.title || preview.rel),
|
|
588
|
+
h('button', {
|
|
589
|
+
className: 'knit-btn',
|
|
590
|
+
onClick: onToggleFullscreen,
|
|
591
|
+
title: fullscreen ? t('preview.exitFullscreenTitle') : t('preview.fullscreenTitle'),
|
|
592
|
+
}, fullscreen ? t('preview.exitFullscreen') : t('preview.fullscreen')),
|
|
593
|
+
h('button', { className: 'knit-btn', onClick: onOpenTab, title: t('preview.newTabTitle') }, t('preview.newTab')),
|
|
594
|
+
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,
|
|
597
|
+
body))
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* 面板主体。两个宿主共用。
|
|
602
|
+
*
|
|
603
|
+
* @param {{sessionId?:string, openInTab?:Function}} props - 渲染入参。
|
|
604
|
+
* `openInTab(doc)` 返回空串表示成功,返回文案表示失败原因。
|
|
605
|
+
* @returns {import('react').ReactElement} 元素
|
|
606
|
+
*/
|
|
607
|
+
function KnitBody({ sessionId, openInTab }) {
|
|
608
|
+
ensureStyle()
|
|
609
|
+
|
|
610
|
+
const [notice, setNotice] = React.useState('')
|
|
611
|
+
const [sort, setSort] = React.useState(readSortPref)
|
|
612
|
+
const [state, setState] = React.useState({
|
|
613
|
+
status: 'loading', docs: [], root: '', total: 0, error: '', mode: 'time', topic: '',
|
|
614
|
+
})
|
|
615
|
+
const [preview, setPreview] = React.useState(null)
|
|
616
|
+
const [tick, setTick] = React.useState(() => Date.now())
|
|
617
|
+
const [cursor, setCursor] = React.useState('')
|
|
618
|
+
const [query, setQuery] = React.useState('')
|
|
619
|
+
const [ratio, setRatio] = React.useState(readRatioPref)
|
|
620
|
+
const [fullscreen, setFullscreen] = React.useState(false)
|
|
621
|
+
|
|
622
|
+
const listRef = React.useRef(null)
|
|
623
|
+
const rootRef = React.useRef(null)
|
|
624
|
+
|
|
625
|
+
const load = React.useCallback(async () => {
|
|
626
|
+
if (!sessionId) {
|
|
627
|
+
setState({ status: 'error', docs: [], root: '', total: 0, error: t('error.noSession'), mode: 'time', topic: '' })
|
|
628
|
+
return
|
|
629
|
+
}
|
|
630
|
+
try {
|
|
631
|
+
const url = `${LIST_API}?sessionId=${encodeURIComponent(sessionId)}&limit=40&sort=${sort}`
|
|
632
|
+
const res = await fetch(url, { headers: { accept: 'application/json' }, cache: 'no-store' })
|
|
633
|
+
const data = await res.json()
|
|
634
|
+
if (data && data.ok) {
|
|
635
|
+
setState({
|
|
636
|
+
status: 'ready',
|
|
637
|
+
docs: data.docs || [],
|
|
638
|
+
root: data.root || '',
|
|
639
|
+
total: data.total || 0,
|
|
640
|
+
error: '',
|
|
641
|
+
mode: data.mode || 'time',
|
|
642
|
+
topic: data.topic || '',
|
|
643
|
+
})
|
|
644
|
+
} else {
|
|
645
|
+
setState({ status: 'error', docs: [], root: '', total: 0, error: hostMessage(data), mode: 'time', topic: '' })
|
|
646
|
+
}
|
|
647
|
+
} catch (error) {
|
|
648
|
+
setState({ status: 'error', docs: [], root: '', total: 0, error: String((error && error.message) || error), mode: 'time', topic: '' })
|
|
649
|
+
}
|
|
650
|
+
setTick(Date.now())
|
|
651
|
+
}, [sessionId, sort])
|
|
652
|
+
|
|
653
|
+
React.useEffect(() => {
|
|
654
|
+
let alive = true
|
|
655
|
+
let timer = null
|
|
656
|
+
const run = async () => {
|
|
657
|
+
await load()
|
|
658
|
+
if (alive) timer = setTimeout(run, POLL_MS)
|
|
659
|
+
}
|
|
660
|
+
run()
|
|
661
|
+
return () => { alive = false; if (timer) clearTimeout(timer) }
|
|
662
|
+
}, [load])
|
|
663
|
+
|
|
664
|
+
/* ── 过滤:纯客户端,不重新请求宿主 ─────────────── */
|
|
665
|
+
const visibleDocs = React.useMemo(() => {
|
|
666
|
+
const q = query.trim().toLowerCase()
|
|
667
|
+
if (!q) return state.docs
|
|
668
|
+
return state.docs.filter((doc) =>
|
|
669
|
+
String(doc.title || '').toLowerCase().includes(q)
|
|
670
|
+
|| String(doc.summary || '').toLowerCase().includes(q)
|
|
671
|
+
|| String(doc.rel || '').toLowerCase().includes(q))
|
|
672
|
+
}, [state.docs, query])
|
|
673
|
+
|
|
674
|
+
// cursor 消失(被过滤掉 / 列表刷新)时落回第一项
|
|
675
|
+
React.useEffect(() => {
|
|
676
|
+
if (visibleDocs.length === 0) {
|
|
677
|
+
if (cursor !== '') setCursor('')
|
|
678
|
+
return
|
|
679
|
+
}
|
|
680
|
+
if (!visibleDocs.some((doc) => doc.rel === cursor)) setCursor(visibleDocs[0].rel)
|
|
681
|
+
}, [visibleDocs, cursor])
|
|
682
|
+
|
|
683
|
+
// 键盘焦点跟手滚进视口(测试环境没有 DOM,静默跳过)
|
|
684
|
+
React.useEffect(() => {
|
|
685
|
+
if (!cursor || typeof document === 'undefined') return
|
|
686
|
+
const host = listRef.current
|
|
687
|
+
if (!host || typeof host.querySelector !== 'function') return
|
|
688
|
+
const escaped = typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(cursor) : cursor
|
|
689
|
+
const el = host.querySelector(`[data-knit-rel="${escaped}"]`)
|
|
690
|
+
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ block: 'nearest' })
|
|
691
|
+
}, [cursor, query, state.docs])
|
|
692
|
+
|
|
693
|
+
// 预览高度:拖完就记住
|
|
694
|
+
React.useEffect(() => { writePref(RATIO_KEY, String(ratio)) }, [ratio])
|
|
695
|
+
|
|
696
|
+
/** 打开(不切换)某篇的预览。 */
|
|
697
|
+
const openPreview = React.useCallback((doc) => {
|
|
698
|
+
setNotice('')
|
|
699
|
+
setPreview({ rel: doc.rel, title: doc.title || doc.name, status: 'loading', text: '', truncated: false })
|
|
700
|
+
}, [])
|
|
701
|
+
|
|
702
|
+
/** 单击 / Enter:切换某篇的预览开与关。 */
|
|
703
|
+
const togglePreview = React.useCallback((doc) => {
|
|
704
|
+
setNotice('')
|
|
705
|
+
setCursor(doc.rel)
|
|
706
|
+
setPreview((current) => {
|
|
707
|
+
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 }
|
|
709
|
+
})
|
|
710
|
+
}, [])
|
|
711
|
+
|
|
712
|
+
/** 收起预览;全屏时顺带退出全屏。 */
|
|
713
|
+
const closePreview = React.useCallback(() => {
|
|
714
|
+
setPreview(null)
|
|
715
|
+
setFullscreen(false)
|
|
716
|
+
}, [])
|
|
717
|
+
|
|
718
|
+
/** 键盘导航:↑↓ 移动即预览,Enter 切换,Esc 收起。 */
|
|
719
|
+
const onListKeyDown = React.useCallback((event) => {
|
|
720
|
+
if (visibleDocs.length === 0) return
|
|
721
|
+
const index = visibleDocs.findIndex((doc) => doc.rel === cursor)
|
|
722
|
+
|
|
723
|
+
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
|
724
|
+
event.preventDefault()
|
|
725
|
+
const next = event.key === 'ArrowDown'
|
|
726
|
+
? Math.min(visibleDocs.length - 1, index < 0 ? 0 : index + 1)
|
|
727
|
+
: Math.max(0, index < 0 ? 0 : index - 1)
|
|
728
|
+
const doc = visibleDocs[next]
|
|
729
|
+
if (doc) { setCursor(doc.rel); openPreview(doc) }
|
|
730
|
+
return
|
|
731
|
+
}
|
|
732
|
+
if (event.key === 'Enter') {
|
|
733
|
+
event.preventDefault()
|
|
734
|
+
const doc = visibleDocs.find((d) => d.rel === cursor) || visibleDocs[0]
|
|
735
|
+
if (doc) togglePreview(doc)
|
|
736
|
+
return
|
|
737
|
+
}
|
|
738
|
+
if (event.key === 'Escape') {
|
|
739
|
+
event.preventDefault()
|
|
740
|
+
if (fullscreen) setFullscreen(false)
|
|
741
|
+
else closePreview()
|
|
742
|
+
}
|
|
743
|
+
}, [visibleDocs, cursor, fullscreen, openPreview, togglePreview, closePreview])
|
|
744
|
+
|
|
745
|
+
/** 拖拽预览面板上缘改变高度。 */
|
|
746
|
+
const onResizeStart = React.useCallback((event) => {
|
|
747
|
+
if (typeof window === 'undefined' || !event || typeof event.preventDefault !== 'function') return
|
|
748
|
+
event.preventDefault()
|
|
749
|
+
const host = rootRef.current
|
|
750
|
+
const total = host && typeof host.getBoundingClientRect === 'function'
|
|
751
|
+
? host.getBoundingClientRect().height
|
|
752
|
+
: (typeof window.innerHeight === 'number' ? window.innerHeight : 600)
|
|
753
|
+
const span = total > 0 ? total : 600
|
|
754
|
+
const startY = event.clientY
|
|
755
|
+
const startRatio = ratio
|
|
756
|
+
|
|
757
|
+
const onMove = (moveEvent) => setRatio(clampRatio(startRatio + (startY - moveEvent.clientY) / span))
|
|
758
|
+
const onUp = () => {
|
|
759
|
+
window.removeEventListener('pointermove', onMove)
|
|
760
|
+
window.removeEventListener('pointerup', onUp)
|
|
761
|
+
}
|
|
762
|
+
window.addEventListener('pointermove', onMove)
|
|
763
|
+
window.addEventListener('pointerup', onUp)
|
|
764
|
+
}, [ratio])
|
|
765
|
+
|
|
766
|
+
// 预览进入 loading 时去宿主取正文
|
|
767
|
+
const previewRel = preview && preview.rel
|
|
768
|
+
const previewStatus = preview && preview.status
|
|
769
|
+
React.useEffect(() => {
|
|
770
|
+
if (!previewRel || previewStatus !== 'loading') return undefined
|
|
771
|
+
let alive = true
|
|
772
|
+
const run = async () => {
|
|
773
|
+
try {
|
|
774
|
+
const url = `${DOC_API}?sessionId=${encodeURIComponent(sessionId)}&rel=${encodeURIComponent(previewRel)}`
|
|
775
|
+
const res = await fetch(url, { headers: { accept: 'application/json' }, cache: 'no-store' })
|
|
776
|
+
const data = await res.json()
|
|
777
|
+
if (!alive) return
|
|
778
|
+
setPreview((cur) => {
|
|
779
|
+
if (!cur || cur.rel !== previewRel) return cur
|
|
780
|
+
return data && data.ok
|
|
781
|
+
? { ...cur, status: 'ready', text: data.text || '', truncated: Boolean(data.truncated) }
|
|
782
|
+
: { ...cur, status: 'error', error: hostMessage(data) }
|
|
783
|
+
})
|
|
784
|
+
} catch (error) {
|
|
785
|
+
if (!alive) return
|
|
786
|
+
setPreview((cur) => (cur && cur.rel === previewRel
|
|
787
|
+
? { ...cur, status: 'error', error: String((error && error.message) || error) }
|
|
788
|
+
: cur))
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
run()
|
|
792
|
+
return () => { alive = false }
|
|
793
|
+
}, [previewRel, previewStatus, sessionId])
|
|
794
|
+
|
|
795
|
+
// 相对路径图片解析器:按当前文档所在目录解析。MarkdownText 按引用身份 memo,
|
|
796
|
+
// 所以必须 useMemo 住,否则每帧都会重解析整篇 markdown。
|
|
797
|
+
const pathImages = React.useMemo(
|
|
798
|
+
() => (previewRel ? pathImagesFor(sessionId, previewRel) : null),
|
|
799
|
+
[sessionId, previewRel],
|
|
800
|
+
)
|
|
801
|
+
|
|
802
|
+
/** 次动作:双击 / 面板按钮 → 交给宿主的「开新标签页」能力。 */
|
|
803
|
+
const onOpenTab = React.useCallback((doc) => {
|
|
804
|
+
const target = doc && doc.rel ? doc : preview
|
|
805
|
+
if (!target) return
|
|
806
|
+
if (typeof openInTab !== 'function') {
|
|
807
|
+
setNotice(t('error.noHostTab'))
|
|
808
|
+
return
|
|
809
|
+
}
|
|
810
|
+
setNotice(openInTab(target) || '')
|
|
811
|
+
}, [openInTab, preview])
|
|
812
|
+
|
|
813
|
+
/** 切换排序方式,并记住偏好。 */
|
|
814
|
+
const pickSort = React.useCallback((value) => {
|
|
815
|
+
writePref(SORT_KEY, value)
|
|
816
|
+
setSort(value)
|
|
817
|
+
}, [])
|
|
818
|
+
|
|
819
|
+
const relevance = state.mode === 'relevance'
|
|
820
|
+
const filtering = query.trim().length > 0
|
|
821
|
+
|
|
822
|
+
const body = state.status === 'loading' && state.docs.length === 0
|
|
823
|
+
? h('div', { className: 'knit-msg' }, t('list.scanning'))
|
|
824
|
+
: state.status === 'error'
|
|
825
|
+
? h('div', { className: 'knit-msg' }, t('list.failed', { error: state.error }), h('br'), t('list.failedHint'))
|
|
826
|
+
: state.docs.length === 0
|
|
827
|
+
? h('div', { className: 'knit-msg' }, t('list.empty'))
|
|
828
|
+
: visibleDocs.length === 0
|
|
829
|
+
? 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
|
+
}))
|
|
840
|
+
|
|
841
|
+
const topicText = relevance
|
|
842
|
+
? (state.topic ? t('topic.relevance', { topic: state.topic }) : t('topic.relevancePlain'))
|
|
843
|
+
: (sort === 'relevance' ? t('topic.needsConversation') : t('topic.time'))
|
|
844
|
+
|
|
845
|
+
const countText = filtering
|
|
846
|
+
? t('count.filtered', { hit: visibleDocs.length, total: state.total })
|
|
847
|
+
: t('count', { n: state.total })
|
|
848
|
+
|
|
849
|
+
return h('div', {
|
|
850
|
+
className: `knit-root${fullscreen ? ' fullscreen' : ''}`,
|
|
851
|
+
ref: rootRef,
|
|
852
|
+
},
|
|
853
|
+
h('div', { className: 'knit-head' },
|
|
854
|
+
h('div', { className: 'knit-root-path', title: state.root }, state.root || '—'),
|
|
855
|
+
h('div', { className: 'knit-count' }, countText),
|
|
856
|
+
h('button', { className: 'knit-btn', onClick: load, title: t('action.refreshNow') }, t('action.refresh'))),
|
|
857
|
+
h('div', { className: 'knit-bar' },
|
|
858
|
+
h('div', { className: 'knit-seg' },
|
|
859
|
+
h('button', {
|
|
860
|
+
className: `knit-seg-btn${sort === 'relevance' ? ' active' : ''}`,
|
|
861
|
+
onClick: () => pickSort('relevance'),
|
|
862
|
+
title: t('sort.relevanceTitle'),
|
|
863
|
+
}, t('sort.relevance')),
|
|
864
|
+
h('button', {
|
|
865
|
+
className: `knit-seg-btn${sort === 'time' ? ' active' : ''}`,
|
|
866
|
+
onClick: () => pickSort('time'),
|
|
867
|
+
title: t('sort.timeTitle'),
|
|
868
|
+
}, t('sort.time'))),
|
|
869
|
+
h('input', {
|
|
870
|
+
className: 'knit-filter',
|
|
871
|
+
value: query,
|
|
872
|
+
placeholder: t('filter.placeholder'),
|
|
873
|
+
'aria-label': t('filter.aria'),
|
|
874
|
+
onChange: (event) => setQuery(event.target.value),
|
|
875
|
+
onKeyDown: (event) => {
|
|
876
|
+
if (event.key === 'Escape') { event.stopPropagation(); setQuery('') }
|
|
877
|
+
},
|
|
878
|
+
})),
|
|
879
|
+
h('div', { className: 'knit-topic', title: topicText }, topicText),
|
|
880
|
+
notice ? h('div', { className: 'knit-notice' }, notice) : null,
|
|
881
|
+
h('div', {
|
|
882
|
+
className: 'knit-list',
|
|
883
|
+
ref: listRef,
|
|
884
|
+
tabIndex: 0,
|
|
885
|
+
onKeyDown: onListKeyDown,
|
|
886
|
+
role: 'listbox',
|
|
887
|
+
'aria-label': '最近文档',
|
|
888
|
+
}, body),
|
|
889
|
+
preview ? h(PreviewPanel, {
|
|
890
|
+
preview,
|
|
891
|
+
pathImages,
|
|
892
|
+
fullscreen,
|
|
893
|
+
ratio,
|
|
894
|
+
onClose: closePreview,
|
|
895
|
+
onOpenTab: () => onOpenTab(null),
|
|
896
|
+
onToggleFullscreen: () => setFullscreen((v) => !v),
|
|
897
|
+
onResizeStart,
|
|
898
|
+
}) : null)
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/* ── 会话入口按钮 ───────────────────────────────── */
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* 打开 Knit 面板:先试官方右侧栏,再试 better-sidebar。
|
|
905
|
+
*
|
|
906
|
+
* 一个按钮要同时服务两个宿主,所以宿主在**点击时**解析,
|
|
907
|
+
* 而不是在注册时绑定 —— 宿主可能后装、可能被禁用。
|
|
908
|
+
*
|
|
909
|
+
* @param {object} ctx - 客户端根上下文
|
|
910
|
+
* @returns {boolean} 是否有宿主接住了这次打开
|
|
911
|
+
*/
|
|
912
|
+
function openKnitPanel(ctx) {
|
|
913
|
+
if (!ctx || typeof ctx.get !== 'function') return false
|
|
914
|
+
|
|
915
|
+
const sidebarRight = ctx.get('sidebarRight')
|
|
916
|
+
if (sidebarRight && typeof sidebarRight.openTab === 'function') {
|
|
917
|
+
try {
|
|
918
|
+
// openTab 会顺带展开面板:用户看不见的内容不叫「打开」
|
|
919
|
+
sidebarRight.openTab(KIND)
|
|
920
|
+
return true
|
|
921
|
+
} catch (error) {
|
|
922
|
+
console.warn('[knit] sidebarRight.openTab failed', error)
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
const betterSidebar = ctx.get('betterSidebar')
|
|
927
|
+
if (betterSidebar && typeof betterSidebar.openTab === 'function') {
|
|
928
|
+
try {
|
|
929
|
+
betterSidebar.openTab({ type: BS_TAB_ID })
|
|
930
|
+
return true
|
|
931
|
+
} catch (error) {
|
|
932
|
+
console.warn('[knit] betterSidebar.openTab failed', error)
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
return false
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
/**
|
|
940
|
+
* 造一个入口按钮组件。
|
|
941
|
+
*
|
|
942
|
+
* 两处座位(会话头部右侧、输入框工具行)共用同一个组件,
|
|
943
|
+
* 官方原组件一像素不动,我们只是往 list 座位里追加一项。
|
|
944
|
+
*
|
|
945
|
+
* @param {Function} onOpen - 点击时的动作,返回是否有宿主接住
|
|
946
|
+
* @returns {Function} 组件
|
|
947
|
+
*/
|
|
948
|
+
function makeEntryButton(onOpen) {
|
|
949
|
+
return function KnitEntryButton() {
|
|
950
|
+
return h('button', {
|
|
951
|
+
type: 'button',
|
|
952
|
+
className: 'knit-entry',
|
|
953
|
+
title: t('entry.label'),
|
|
954
|
+
'aria-label': t('entry.label'),
|
|
955
|
+
onClick: (event) => {
|
|
956
|
+
if (event && typeof event.preventDefault === 'function') event.preventDefault()
|
|
957
|
+
if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
|
|
958
|
+
if (!onOpen()) console.warn('[knit] no sidebar host available — the entry button cannot open the panel')
|
|
959
|
+
},
|
|
960
|
+
}, h(KnitGlyph, { size: 16 }))
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
/* ── 宿主适配层 ─────────────────────────────────── */
|
|
965
|
+
|
|
966
|
+
/**
|
|
967
|
+
* 官方右侧栏的座位适配:`tab.actions` 只能从框架注入的 `useTabInfo()` 拿。
|
|
968
|
+
* @param {object} tabProps - 座位入参
|
|
969
|
+
* @returns {import('react').ReactElement} 元素
|
|
970
|
+
*/
|
|
971
|
+
function OfficialTabBody(tabProps) {
|
|
972
|
+
const sessionId = tabProps && tabProps.sessionId
|
|
973
|
+
|
|
974
|
+
// 官方写法(ui-sidebar-files):const { tab } = useTabInfo()
|
|
975
|
+
// 该 prop 由座位契约保证恒定存在,条件调用不破坏 hooks 顺序。
|
|
976
|
+
const useTabInfo = tabProps && tabProps.useTabInfo
|
|
977
|
+
const tabInfo = typeof useTabInfo === 'function' ? useTabInfo() : null
|
|
978
|
+
const actions = tabInfo && tabInfo.tab ? tabInfo.tab.actions : null
|
|
979
|
+
|
|
980
|
+
const openInTab = React.useCallback((doc) => {
|
|
981
|
+
if (!actions || typeof actions.openResource !== 'function') {
|
|
982
|
+
return t('error.noOpenResource')
|
|
983
|
+
}
|
|
984
|
+
try {
|
|
985
|
+
actions.openResource(sessionFileAddress(sessionId, doc.rel))
|
|
986
|
+
return ''
|
|
987
|
+
} catch (error) {
|
|
988
|
+
return t('error.openFailed', { error: String((error && error.message) || error) })
|
|
989
|
+
}
|
|
990
|
+
}, [actions, sessionId])
|
|
991
|
+
|
|
992
|
+
return h(KnitBody, { sessionId, openInTab })
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/**
|
|
996
|
+
* better-sidebar 的 tab 适配:走 `ctx.betterSidebar.openTab({type:'editor'})`。
|
|
997
|
+
* 编辑器 tab 被用户关掉时不硬闯,直接把原因交给面板提示。
|
|
998
|
+
* @param {object} bsProps - better-sidebar 的 TabComponentProps
|
|
999
|
+
* @returns {import('react').ReactElement} 元素
|
|
1000
|
+
*/
|
|
1001
|
+
function BetterSidebarTabBody(bsProps) {
|
|
1002
|
+
const sessionId = bsProps && bsProps.scope ? bsProps.scope.sessionId : undefined
|
|
1003
|
+
const ctx = bsProps && bsProps.ctx
|
|
1004
|
+
|
|
1005
|
+
const openInTab = React.useCallback((doc) => {
|
|
1006
|
+
if (!ctx || typeof ctx.get !== 'function') return t('error.bsNoContext')
|
|
1007
|
+
const bs = ctx.get('betterSidebar')
|
|
1008
|
+
if (!bs || typeof bs.openTab !== 'function') return t('error.bsNoService')
|
|
1009
|
+
if (typeof bs.isTabEnabled === 'function' && !bs.isTabEnabled('editor')) {
|
|
1010
|
+
return t('error.bsEditorDisabled')
|
|
1011
|
+
}
|
|
1012
|
+
try {
|
|
1013
|
+
bs.openTab({ type: 'editor', path: doc.path, title: doc.name })
|
|
1014
|
+
return ''
|
|
1015
|
+
} catch (error) {
|
|
1016
|
+
return t('error.openFailed', { error: String((error && error.message) || error) })
|
|
1017
|
+
}
|
|
1018
|
+
}, [ctx])
|
|
1019
|
+
|
|
1020
|
+
return h(KnitBody, { sessionId, openInTab })
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/* ── 图标 ───────────────────────────────────────── */
|
|
1024
|
+
|
|
1025
|
+
/**
|
|
1026
|
+
* Knit 的 mono 图标路径(24×24,viewBox 0 0 100 100,4px 描边)。
|
|
1027
|
+
*
|
|
1028
|
+
* **为什么内联在代码里**:客户端半边没有构建步骤,加载期也不能读文件
|
|
1029
|
+
* (`__ModuleLoader__` 直接装载这个脚本),path 只能作为字面量存在。
|
|
1030
|
+
* 源文件在 `assets/knit-icon-24-mono-4px.svg` —— **改图标时两处一起改**。
|
|
1031
|
+
*
|
|
1032
|
+
* 用 `stroke="currentColor"`,颜色由 `.knit-icon` 那条 CSS 定死:
|
|
1033
|
+
* **浅色模式纯黑、暗色模式纯白**(暗色信号是 DSH 的 `body[data-ds-dark-theme]`)。
|
|
1034
|
+
*/
|
|
1035
|
+
const KNIT_ICON_PATH = 'M78.73 31.92L78.44 31.53L78.12 31.16L77.79 30.80L77.44 30.45L77.07 30.11L76.69 29.79L76.30 29.48L75.89 29.19L75.46 28.91L75.02 28.64L74.57 28.39L74.10 28.16L73.62 27.94L73.13 27.74L72.62 27.55L72.11 27.38L71.58 27.23L71.04 27.09L70.49 26.97L69.93 26.87L69.36 26.79L68.78 26.72L68.20 26.67L67.60 26.64L67.00 26.63L66.39 26.63L65.78 26.65L65.16 26.70L64.53 26.76L63.90 26.83L63.26 26.93L62.62 27.05L61.98 27.18L61.33 27.33L60.68 27.50L60.03 27.69L59.38 27.90L58.73 28.13L58.08 28.37L57.43 28.64L56.78 28.92L56.13 29.21L55.48 29.53L54.83 29.86L54.19 30.22L53.55 30.58L52.91 30.97L52.28 31.37L51.66 31.79L51.04 32.23L50.42 32.68L49.82 33.14L49.21 33.63L48.62 34.12L48.03 34.64L47.46 35.16L46.89 35.71L46.33 36.26L45.78 36.83L45.23 37.41L44.70 38.01L44.18 38.61L43.68 39.23L43.18 39.86L42.69 40.51M51.45 83.91L51.94 83.83L52.42 83.74L52.90 83.63L53.37 83.49L53.84 83.34L54.31 83.16L54.77 82.97L55.23 82.75L55.68 82.52L56.13 82.26L56.57 81.99L57.01 81.69L57.43 81.38L57.85 81.05L58.26 80.70L58.67 80.33L59.06 79.94L59.45 79.54L59.82 79.12L60.19 78.68L60.54 78.22L60.88 77.75L61.21 77.26L61.54 76.76L61.84 76.24L62.14 75.70L62.42 75.15L62.69 74.59L62.95 74.01L63.19 73.42L63.42 72.82L63.64 72.20L63.84 71.57L64.02 70.93L64.19 70.28L64.35 69.62L64.49 68.95L64.62 68.27L64.73 67.58L64.82 66.88L64.90 66.17L64.96 65.46L65.00 64.74L65.03 64.01L65.04 63.27L65.04 62.54L65.01 61.79L64.98 61.04L64.92 60.29L64.85 59.53L64.76 58.77L64.65 58.01L64.53 57.25L64.39 56.49L64.23 55.72L64.06 54.96L63.87 54.20L63.66 53.43L63.44 52.67L63.20 51.91L62.95 51.16L62.68 50.41L62.39 49.66L62.09 48.91L61.77 48.17M19.85 34.46L19.68 34.91L19.52 35.38L19.39 35.85L19.27 36.33L19.18 36.82L19.10 37.32L19.05 37.82L19.01 38.32L19.00 38.84L19.00 39.35L19.02 39.87L19.07 40.40L19.13 40.92L19.22 41.45L19.32 41.99L19.44 42.52L19.59 43.05L19.75 43.59L19.94 44.13L20.14 44.66L20.37 45.19L20.61 45.73L20.87 46.26L21.16 46.79L21.46 47.31L21.78 47.84L22.12 48.35L22.48 48.87L22.86 49.38L23.25 49.88L23.67 50.38L24.10 50.87L24.55 51.36L25.02 51.84L25.50 52.31L26.00 52.77L26.52 53.23L27.05 53.67L27.60 54.11L28.16 54.53L28.74 54.95L29.33 55.36L29.94 55.75L30.56 56.14L31.20 56.51L31.84 56.87L32.50 57.22L33.17 57.56L33.86 57.88L34.55 58.19L35.26 58.49L35.97 58.78L36.70 59.05L37.43 59.30L38.17 59.54L38.93 59.77L39.68 59.98L40.45 60.18L41.22 60.36L42.00 60.53L42.79 60.68L43.57 60.82L44.37 60.94L45.16 61.04'
|
|
1036
|
+
|
|
1037
|
+
/**
|
|
1038
|
+
* Knit 图标。guide 页入口胶囊、tab 芯片标题、better-sidebar tab 都用它。
|
|
1039
|
+
*
|
|
1040
|
+
* @param {{size?:number, className?:string}} props - 尺寸与附加 class
|
|
1041
|
+
* @returns {import('react').ReactElement} 元素
|
|
1042
|
+
*/
|
|
1043
|
+
function KnitGlyph({ size, className }) {
|
|
1044
|
+
// 图标可能在 KnitBody 之前渲染(guide 胶囊、tab 芯片),
|
|
1045
|
+
// 所以样式表由图标自己保证注入,不依赖面板先渲染。
|
|
1046
|
+
ensureStyle()
|
|
1047
|
+
|
|
1048
|
+
const s = size || 16
|
|
1049
|
+
return h('svg', {
|
|
1050
|
+
width: s,
|
|
1051
|
+
height: s,
|
|
1052
|
+
viewBox: '0 0 100 100',
|
|
1053
|
+
fill: 'none',
|
|
1054
|
+
stroke: 'currentColor',
|
|
1055
|
+
strokeWidth: 16.67,
|
|
1056
|
+
strokeLinecap: 'round',
|
|
1057
|
+
strokeLinejoin: 'round',
|
|
1058
|
+
className: className ? `knit-icon ${className}` : 'knit-icon',
|
|
1059
|
+
'aria-hidden': 'true',
|
|
1060
|
+
focusable: 'false',
|
|
1061
|
+
}, h('path', { d: KNIT_ICON_PATH }))
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
/**
|
|
1065
|
+
* tab 芯片上的标题:图标 + 名称。
|
|
1066
|
+
*
|
|
1067
|
+
* 用内联样式而不是 class —— 芯片标题可能在 KnitBody 之前渲染,
|
|
1068
|
+
* 那时 ensureStyle() 还没跑,样式表还不存在。
|
|
1069
|
+
*
|
|
1070
|
+
* @returns {import('react').ReactElement} 元素
|
|
1071
|
+
*/
|
|
1072
|
+
function KnitTitle() {
|
|
1073
|
+
return h('span', {
|
|
1074
|
+
style: { display: 'inline-flex', alignItems: 'center', gap: '5px', minWidth: 0 },
|
|
1075
|
+
}, h(KnitGlyph, { size: 16 }), t('type.label'))
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
/* ── 注册 ───────────────────────────────────────── */
|
|
1079
|
+
|
|
1080
|
+
module.exports.inject = ['slots', 'locale']
|
|
1081
|
+
module.exports.apply = (ctx) => {
|
|
1082
|
+
// ⓪ 国际化:注册双语词典,再把 t 绑到当前活动语言。
|
|
1083
|
+
// bind 返回的函数身份稳定、**按调用时读取活动语言**,所以可以长期持有;
|
|
1084
|
+
// DSH 切换语言时 locale 会 bump revision,插座运行时据此重渲染,
|
|
1085
|
+
// 文案随之更新(无需重新注册)。
|
|
1086
|
+
ctx.effect(() => ctx.locale.register(NS, { zh: ZH, en: EN }), 'dsh-knit: dictionaries')
|
|
1087
|
+
t = ctx.locale.bind(NS)
|
|
1088
|
+
|
|
1089
|
+
// ① 会话入口按钮:一个官方 list 座位(追加,不动官方组件)
|
|
1090
|
+
//
|
|
1091
|
+
// 为什么放这里而不是产物卡片的下拉菜单:
|
|
1092
|
+
// 那个菜单的 items 是官方组件里硬编码的两项数组、onSelect 只认
|
|
1093
|
+
// 'open' | 'reveal',deliverables 包声明了 0 个座位 —— 加不了第三项。
|
|
1094
|
+
// 而「入口太深」这个真实痛点,官方本来就留了 list 座位给入口按钮。
|
|
1095
|
+
//
|
|
1096
|
+
// 只挂会话头部右侧一处:输入框工具行那处实测「太刻意」,去掉了。
|
|
1097
|
+
// 头部这处紧挨右侧栏展开按钮,是「开侧边面板」的天然位置。
|
|
1098
|
+
//
|
|
1099
|
+
// 宿主在点击时才解析(openKnitPanel 内部 ctx.get),所以宿主后装 /
|
|
1100
|
+
// 被禁用 / 换成 better-sidebar 都不影响这个按钮的存在。
|
|
1101
|
+
const EntryButton = makeEntryButton(() => openKnitPanel(ctx))
|
|
1102
|
+
|
|
1103
|
+
ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({
|
|
1104
|
+
name: 'conversation.session.header.utilities',
|
|
1105
|
+
id: 'knit:entry',
|
|
1106
|
+
order: 40,
|
|
1107
|
+
locale: NS,
|
|
1108
|
+
}, EntryButton))
|
|
1109
|
+
|
|
1110
|
+
// ① DSH 自带右侧栏(主路径)
|
|
1111
|
+
// 可选依赖:不在顶层 inject 里,缺失时子 fiber 只等待、不报错。
|
|
1112
|
+
ctx.inject(['sidebarRightTabs'], (srCtx) => {
|
|
1113
|
+
const tabs = srCtx.sidebarRightTabs
|
|
1114
|
+
if (!tabs || typeof tabs.register !== 'function') {
|
|
1115
|
+
console.info('[knit] official right sidebar unavailable — skipping tab registration')
|
|
1116
|
+
return
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
// 类型:page 类型(无 patterns),靠 guide 入口 / openTab('knit') 打开
|
|
1120
|
+
srCtx.effect(() => tabs.register({
|
|
1121
|
+
id: TAB_ID,
|
|
1122
|
+
kind: KIND,
|
|
1123
|
+
priority: 'extension',
|
|
1124
|
+
title: () => t('type.label'),
|
|
1125
|
+
guide: [{
|
|
1126
|
+
order: 30,
|
|
1127
|
+
title: () => t('guide.title'),
|
|
1128
|
+
description: () => t('guide.description'),
|
|
1129
|
+
icon: KnitGlyph,
|
|
1130
|
+
}],
|
|
1131
|
+
}), 'dsh-knit: sidebar-right type')
|
|
1132
|
+
|
|
1133
|
+
srCtx.effect(() => srCtx.slots.inject('sidebar.right.pane.tab', () => srCtx.slots.register({
|
|
1134
|
+
name: 'sidebar.right.pane.tab',
|
|
1135
|
+
key: TAB_ID,
|
|
1136
|
+
}, OfficialTabBody)), 'dsh-knit: sidebar-right body')
|
|
1137
|
+
|
|
1138
|
+
srCtx.effect(() => srCtx.slots.inject('sidebar.right.pane.tab.title', () => srCtx.slots.register({
|
|
1139
|
+
name: 'sidebar.right.pane.tab.title',
|
|
1140
|
+
key: TAB_ID,
|
|
1141
|
+
}, KnitTitle)), 'dsh-knit: sidebar.right title')
|
|
1142
|
+
|
|
1143
|
+
console.log('[knit] registered on the official right sidebar: kind =', KIND)
|
|
1144
|
+
})
|
|
1145
|
+
|
|
1146
|
+
// ② dsh-better-sidebar(可选宿主)
|
|
1147
|
+
// 同样走 ctx.inject 子 fiber:没装 / 被禁用时静默等待,不影响 ①。
|
|
1148
|
+
ctx.inject(['betterSidebar'], (bsCtx) => {
|
|
1149
|
+
const bs = bsCtx.betterSidebar
|
|
1150
|
+
if (!bs || typeof bs.registerTab !== 'function') {
|
|
1151
|
+
console.info('[knit] betterSidebar service not present — skipping tab registration')
|
|
1152
|
+
return
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
bsCtx.effect(() => bs.registerTab({
|
|
1156
|
+
id: BS_TAB_ID,
|
|
1157
|
+
title: () => 'Knit 最近文档',
|
|
1158
|
+
icon: KnitGlyph,
|
|
1159
|
+
order: 30,
|
|
1160
|
+
single: true, // 同类型只开一个
|
|
1161
|
+
component: (props) => h(BetterSidebarTabBody, props),
|
|
1162
|
+
}), 'dsh-knit: better-sidebar tab')
|
|
1163
|
+
|
|
1164
|
+
console.log('[knit] registered on dsh-better-sidebar: ', BS_TAB_ID)
|
|
1165
|
+
})
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
return module.exports
|
|
1169
|
+
},
|
|
1170
|
+
})
|