dsh-tiddlywiki 0.28.7 → 0.28.8

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.
Files changed (52) hide show
  1. package/README.md +1 -0
  2. package/docs/CHANGELOG.md +1 -0
  3. package/docs/features.md +4 -0
  4. package/docs/usage.md +13 -3
  5. package/lib/client.js +63 -27
  6. package/lib/index.js +10655 -10188
  7. package/lib/index.js.map +1 -1
  8. package/package.json +2 -2
  9. package/src/client/dom.ts +26 -0
  10. package/src/client/index.ts +14 -0
  11. package/src/client/note-widget-draft.ts +154 -0
  12. package/src/client/note-widget-tags.ts +184 -0
  13. package/src/client/note-widget-upload.ts +50 -0
  14. package/src/client/note-widget.ts +19 -348
  15. package/src/client/panel.ts +12 -3
  16. package/src/client/render-fetch.ts +11 -4
  17. package/src/client/scope-seat.ts +117 -0
  18. package/src/client/session-summary.ts +29 -7
  19. package/src/client/settings-icon-picker.ts +238 -0
  20. package/src/client/settings-page-catalog.ts +578 -0
  21. package/src/client/settings-page-config.ts +445 -0
  22. package/src/client/settings-page-runtime.ts +149 -0
  23. package/src/client/settings-page-wikis.ts +432 -0
  24. package/src/client/settings-page.ts +127 -1425
  25. package/src/client/styles.ts +36 -0
  26. package/src/client/tool-views.ts +170 -36
  27. package/src/client/wiki-icon.generated.ts +97 -0
  28. package/src/client/wiki-icon.ts +50 -15
  29. package/src/client/wiki-scope-dock.ts +56 -2
  30. package/src/client/wiki-scope.ts +98 -0
  31. package/src/host/admin-catalog.ts +488 -0
  32. package/src/host/admin-routes.ts +670 -0
  33. package/src/host/admin-secrets.ts +119 -0
  34. package/src/host/admin.ts +3 -1244
  35. package/src/host/clip-bridge.ts +24 -1
  36. package/src/host/config.ts +10 -2
  37. package/src/host/routes-session.ts +617 -0
  38. package/src/host/routes-tw-proxy.ts +390 -0
  39. package/src/host/routes.ts +77 -829
  40. package/src/host/tools-attach.ts +151 -0
  41. package/src/host/tools-git.ts +213 -0
  42. package/src/host/tools-notes.ts +672 -0
  43. package/src/host/tools-read.ts +421 -0
  44. package/src/host/tools-support.ts +513 -0
  45. package/src/host/tools.ts +33 -1814
  46. package/src/host/wiki-registry.ts +25 -4
  47. package/src/host/wiki.ts +55 -5
  48. package/src/index-clip.ts +142 -0
  49. package/src/index-git.ts +196 -0
  50. package/src/index-prompt.ts +139 -0
  51. package/src/index-wikis.ts +353 -0
  52. package/src/index.ts +89 -429
@@ -0,0 +1,445 @@
1
+ /**
2
+ * 常规配置 + 系统提示词 section of the settings page (v0.28.8 split).
3
+ *
4
+ * One concern, one very long function: the form that reads the effective config
5
+ * and saves only what changed. The field builders (text / token / check / num /
6
+ * select / area) stay next to the fields they build, because they encode rules
7
+ * that only make sense together with the save path:
8
+ * - numeric fields keep the user's illegal input and REFUSE to submit it
9
+ * (the host silently clamps out-of-range values, so submitting would make
10
+ * "what the page shows" and "what is in effect" diverge again);
11
+ * - `ui.sidebarLabel` is rendered ONLY in single-wiki mode (multi mode gives
12
+ * every wiki its own label in the registry, so the field would be a fake
13
+ * setting that "saves but does nothing").
14
+ *
15
+ * @module dsh-tiddlywiki/client/settings-page-config
16
+ */
17
+ import { toast } from './toast.ts'
18
+ import { invalidateUiConfig } from './ui-config.ts'
19
+ import { make } from './dom.ts'
20
+ import {
21
+ ADMIN_CONFIG_ENDPOINT as CONFIG_ENDPOINT,
22
+ ADMIN_PROMPT_ENDPOINT as PROMPT_ENDPOINT,
23
+ ADMIN_WIKIS_ENDPOINT as WIKI_LIST_ENDPOINT,
24
+ } from './endpoints.ts'
25
+ import { fetchJson, makeErrorBanner, withWiki } from './settings-page-runtime.ts'
26
+ import type { WikisView } from './settings-page-runtime.ts'
27
+
28
+ /** Form controls registry for the config section (changed-only patch). */
29
+ export interface ConfigField {
30
+ key: string
31
+ initial: string | boolean | number
32
+ read: () => string | boolean | number
33
+ changed: () => boolean
34
+ /**
35
+ * 数值字段专用:返回「当前输入不能提交」的原因,`undefined` = 可用。
36
+ * 保存前用它拦截 —— 宿主对越界/非数字是静默回落(bridge.port 掉回 8618、
37
+ * readyTimeoutMs 夹到 5000–600000),提交等于让页面显示值与真正生效值分家。
38
+ */
39
+ invalid?: () => string | undefined
40
+ }
41
+
42
+ /** Per-mount memory of the config section: the DOM plus the server-side config
43
+ * signature it was built from, so an unchanged refresh never rebuilds the
44
+ * inputs (and never discards the user's unsaved edits). */
45
+ export interface ConfigRenderState {
46
+ signature?: string
47
+ host?: HTMLElement
48
+ /**
49
+ * 最近一次保存失败的文案。保存失败后要 refresh()(顶部可能因此出现 configError
50
+ * 横幅),而 refresh() 可能按新签名重建配置区 —— 错误提示存在这里才不会随局部
51
+ * DOM 一起消失;保存成功时清空。
52
+ */
53
+ saveError?: string
54
+ /**
55
+ * 「表单里有未保存的改动」(v0.25.0)。用于防另一种静默丢改动:配置在**别处**
56
+ * 被改过(另一个标签页保存、语言管理顺带写 uiLanguage)时 refresh() 会让签名
57
+ * 变化 → 重建表单 → 用户刚敲的内容消失。有脏值就保留表单并给出显式提示。
58
+ */
59
+ isDirty?: () => boolean
60
+ }
61
+
62
+ /** Config section: fields bound to effective config, changed-only save. */
63
+ export function renderConfigSection(body: HTMLElement, config: Record<string, unknown>, refresh: () => Promise<void>, configState: ConfigRenderState, rosterMode?: string, isDisposed: () => boolean = () => false): void {
64
+ const section = make('section', 'dsh-tw-settings-section')
65
+ section.append(make('h3', 'dsh-tw-settings-h', '常规配置'))
66
+ const note = (config.note ?? {}) as Record<string, unknown>
67
+ const git = (config.git ?? {}) as Record<string, unknown>
68
+ const ui = (config.ui ?? {}) as Record<string, unknown>
69
+ const fields: ConfigField[] = []
70
+
71
+ const textField = (key: string, label: string, initial: string): void => {
72
+ const input = make('input', 'dsh-tw-settings-input')
73
+ // autocomplete=off(v0.26.4):浏览器常把 URL 类配置框(ui.sendToAgent.endpoint、
74
+ // git.remote、wechat.dsn 等)当账号/URL 字段自动填充,用户一保存就把垃圾值写进 config
75
+ // (实测 ui.sendToAgent.endpoint 被填成 /dsh-tiddlywiki/tw/root,send-to-agent 请求拼成
76
+ // /tw/root/agent/sessions → 404)。tokenField 已有此属性,这里补到所有普通文本框。
77
+ input.autocomplete = 'off'
78
+ input.value = initial
79
+ const wrap = make('label', 'dsh-tw-settings-field')
80
+ wrap.append(make('span', 'dsh-tw-settings-label', label), input)
81
+ fields.push({ key, initial, read: () => input.value.trim(), changed: () => input.value.trim() !== initial })
82
+ section.append(wrap)
83
+ }
84
+ /**
85
+ * 共享口令输入(v0.24.x):`type=password` + 👁 显隐切换。
86
+ * 为什么不能沿用 textField:token 的 ******** mask 只防「保存时把密文覆盖成星号」,
87
+ * 不防「屏幕共享 / 录屏 / 背后有人时明文可见」—— 掩码值本身仍然是个可见的明文输入框。
88
+ */
89
+ const tokenField = (key: string, label: string, initial: string): void => {
90
+ const input = make('input', 'dsh-tw-settings-input')
91
+ input.type = 'password'
92
+ input.value = initial
93
+ input.autocomplete = 'off'
94
+ const toggle = make('button', 'dsh-tw-settings-btn dsh-tw-settings-chipbtn', '👁')
95
+ toggle.type = 'button'
96
+ toggle.title = '显示 / 隐藏'
97
+ toggle.setAttribute('aria-label', '显示 / 隐藏')
98
+ toggle.addEventListener('click', (event) => {
99
+ // 按钮位于 <label> 内:阻断 label 的默认「转发点击给控件」,避免切明文时输入框被重聚焦。
100
+ event.preventDefault()
101
+ const hidden = input.type === 'password'
102
+ input.type = hidden ? 'text' : 'password'
103
+ toggle.textContent = hidden ? '🙈' : '👁'
104
+ })
105
+ const wrap = make('label', 'dsh-tw-settings-field')
106
+ wrap.append(make('span', 'dsh-tw-settings-label', label), input, toggle)
107
+ fields.push({ key, initial, read: () => input.value.trim(), changed: () => input.value.trim() !== initial })
108
+ section.append(wrap)
109
+ }
110
+ const checkField = (key: string, label: string, initial: boolean): HTMLInputElement => {
111
+ const input = make('input', 'dsh-tw-settings-check')
112
+ input.type = 'checkbox'
113
+ input.checked = initial
114
+ const wrap = make('label', 'dsh-tw-settings-field dsh-tw-settings-field-check')
115
+ wrap.append(input, make('span', 'dsh-tw-settings-label', label))
116
+ fields.push({ key, initial, read: () => input.checked, changed: () => input.checked !== initial })
117
+ section.append(wrap)
118
+ return input
119
+ }
120
+ /**
121
+ * 数值字段(v0.24.x:加范围校验 + 字段旁提示)。
122
+ *
123
+ * 旧写法把非法输入静默回落成 `initial`,于是 `changed()` 变 false —— 用户看到自己填的
124
+ * 值还在框里,以为保存了,其实一个字节都没提交;而越界值(宿主只做夹取/回落:bridge.port
125
+ * 掉回 8618、readyTimeoutMs 夹到 5000–600000)即使提交了,页面回显也与真正生效值不符。
126
+ * 现在:非法输入原样留着 + 红字提示,`invalid` 让保存直接拒绝(见保存按钮)。
127
+ */
128
+ const numField = (key: string, label: string, initial: number, range?: { min?: number; max?: number; step?: number; integer?: boolean }): void => {
129
+ const input = make('input', 'dsh-tw-settings-input')
130
+ input.type = 'number'
131
+ input.value = String(initial)
132
+ // 与下面校验同一组边界的浏览器侧约束:数字框的上下箭头不会越界。
133
+ if (range?.min !== undefined) input.min = String(range.min)
134
+ if (range?.max !== undefined) input.max = String(range.max)
135
+ if (range?.step !== undefined) input.step = String(range.step)
136
+ const hint = make('div', 'dsh-tw-settings-error')
137
+ hint.hidden = true
138
+ const violation = (): string | undefined => {
139
+ const raw = input.value.trim()
140
+ if (raw.length === 0) return '不能为空'
141
+ const parsed = Number(raw)
142
+ if (!Number.isFinite(parsed)) return '请输入数字'
143
+ if (range?.integer === true && !Number.isInteger(parsed)) return '必须是整数'
144
+ if (range?.min !== undefined && parsed < range.min) return `不能小于 ${range.min}`
145
+ if (range?.max !== undefined && parsed > range.max) return `不能大于 ${range.max}`
146
+ return undefined
147
+ }
148
+ const sync = (): void => {
149
+ const bad = violation()
150
+ hint.textContent = bad === undefined ? '' : `⚠️ ${bad}(保存会被拒绝)`
151
+ hint.hidden = bad === undefined
152
+ if (bad === undefined) input.removeAttribute('aria-invalid')
153
+ else input.setAttribute('aria-invalid', 'true')
154
+ }
155
+ input.addEventListener('input', sync)
156
+ // 非法时原样回传字符串(而不是 initial):不静默改掉用户在框里看到的东西;
157
+ // 真要落盘也会先被 invalid() 拦下,不会发出去。
158
+ const read = (): number | string => {
159
+ const raw = input.value.trim()
160
+ const parsed = Number(raw)
161
+ return raw.length === 0 || !Number.isFinite(parsed) ? raw : parsed
162
+ }
163
+ const wrap = make('label', 'dsh-tw-settings-field')
164
+ wrap.append(make('span', 'dsh-tw-settings-label', label), input, hint)
165
+ fields.push({ key, initial, read, changed: () => read() !== initial, invalid: violation })
166
+ // 先跑一次:config tiddler 里本来就存着越界值(宿主已静默夹取)时,进页面就该看见
167
+ // 提示,而不是等用户改动过才亮。
168
+ sync()
169
+ section.append(wrap)
170
+ }
171
+ const selectField = (key: string, label: string, initial: string, options: Array<{ value: string; label: string }>): HTMLSelectElement => {
172
+ const select = make('select', 'dsh-tw-settings-input')
173
+ for (const opt of options) {
174
+ const option = document.createElement('option')
175
+ option.value = opt.value
176
+ option.textContent = opt.label
177
+ if (opt.value === initial) option.selected = true
178
+ select.append(option)
179
+ }
180
+ const wrap = make('label', 'dsh-tw-settings-field')
181
+ wrap.append(make('span', 'dsh-tw-settings-label', label), select)
182
+ fields.push({ key, initial, read: () => select.value, changed: () => select.value !== initial })
183
+ section.append(wrap)
184
+ return select
185
+ }
186
+ /**
187
+ * Multi-line free text (v0.21.0: `prompt.extra` / `prompt.override`).
188
+ * The DOM value keeps the user's newlines; only the OUTER whitespace is
189
+ * trimmed by `read()` (that is what the host stores), so "unchanged" stays
190
+ * stable across a refresh that re-renders from the server round-trip.
191
+ */
192
+ const areaField = (key: string, label: string, initial: string, rows: number): HTMLTextAreaElement => {
193
+ const input = make('textarea', 'dsh-tw-settings-input dsh-tw-settings-area')
194
+ input.rows = rows
195
+ input.value = initial
196
+ const wrap = make('label', 'dsh-tw-settings-field dsh-tw-settings-field-area')
197
+ wrap.append(make('span', 'dsh-tw-settings-label', label), input)
198
+ fields.push({ key, initial, read: () => input.value.trim(), changed: () => input.value.trim() !== initial })
199
+ section.append(wrap)
200
+ return input
201
+ }
202
+
203
+ textField('note.tag', '快速笔记默认 tag', typeof note.tag === 'string' ? note.tag : 'inbox')
204
+ // 工作区标记(v0.24.0):新建笔记自动带 ws/<项目名> 标签 + workspace 字段,
205
+ // 项目名取自会话工作目录。关掉只是不做标记,不影响任何写入。
206
+ checkField('note.workspaceMark', '新建笔记自动标工作区(ws/<项目名> 标签 + workspace 字段,取自当前会话工作目录)', note.workspaceMark !== false)
207
+ checkField('git.autoCommit', '自动 commit(防抖)', git.autoCommit !== false)
208
+ // v0.25.0:范围与宿主 config.ts 的 NUMBER_CONFIG_RANGES 对齐(超范围的补丁会被
209
+ // 宿主夹取,页面必须让用户看见真实边界,别再出现「回显 ≠ 生效」)。
210
+ numField('git.debounceMs', '自动 commit 防抖(ms;范围 0–3600000)', typeof git.debounceMs === 'number' ? git.debounceMs : 60_000, { min: 0, max: 3_600_000, step: 1_000, integer: true })
211
+ textField('git.remote', 'git 远端(空=仅本地;保存后即时生效,但**清空不会删除已配置的 origin**,需要时请用 git 命令处理)', typeof git.remote === 'string' ? git.remote : '')
212
+ textField('git.branch', 'git 分支(**只在仓库首次初始化时生效**;已有仓库请用 git 命令改分支——上面的状态行显示的是真实分支)', typeof git.branch === 'string' ? git.branch : 'main')
213
+ // 启动就绪窗口(v0.22.5):大知识库冷启动(数千条目)可能 40s+。窗口内只等,
214
+ // 超过它只写日志,硬上限 = 3× 仍无响应才判失败。改动对下一次启动/重启生效。
215
+ const startup = (config.startup ?? {}) as Record<string, unknown>
216
+ numField('startup.readyTimeoutMs', 'TW 启动就绪等待(ms;默认 60000,范围 5000–600000,超时上限为其 3 倍,对下次启动/重启生效)', typeof startup.readyTimeoutMs === 'number' && startup.readyTimeoutMs > 0 ? startup.readyTimeoutMs : 60_000, { min: 5_000, max: 600_000, step: 1_000 })
217
+ checkField('ui.showQuickNote', '显示「知识库」按钮里的「快速笔记」入口', ui.showQuickNote !== false)
218
+ checkField('ui.showQuickNoteDock', '显示聊天输入框上方的「快速笔记」快捷按钮', ui.showQuickNoteDock !== false)
219
+ selectField('ui.quickNoteMode', '点击「快速笔记」的打开方式', typeof ui.quickNoteMode === 'string' && ui.quickNoteMode === 'card' ? 'card' : 'native', [
220
+ { value: 'native', label: '原生编辑器:直接弹出 TW 原生编辑页(新建/恢复草稿)' },
221
+ { value: 'card', label: 'Markdown 卡片:弹出现有快速笔记卡片(CodeMirror 编辑器)' },
222
+ ])
223
+ // 「侧边栏 TW 入口显示名称」只在**单库**模式有意义(v0.28.7)。多库时侧边栏是每个库
224
+ // 各占一行、各用自己 `wikis.json` 里的 label,这个字段改不动任何东西——留着只会让人
225
+ // 「改了没生效」。所以多库时**不渲染这个字段**(连字段带保存都不参与),只留一行说明
226
+ // 该去哪儿改。判定用的模式来自 mountSettingsPage 的探测(读不到按单库,见那里的注释)。
227
+ if (rosterMode === 'multi') {
228
+ section.append(make('div', 'dsh-tw-settings-muted', '侧边栏入口:多库模式下每个知识库各占一行、各用自己的「显示名」(在「知识库列表」里改),不再是统一的一个名称,所以这里没有对应配置项。'))
229
+ } else {
230
+ textField('ui.sidebarLabel', '侧边栏 TW 入口显示名称', typeof ui.sidebarLabel === 'string' && ui.sidebarLabel.trim().length > 0 ? ui.sidebarLabel.trim() : 'TiddlyWiki')
231
+ }
232
+ checkField('ui.showPanelStatus', '显示「知识库」按钮里的 TW 面板/重载入口与状态行', ui.showPanelStatus !== false)
233
+ checkField('ui.showSyncButton', '显示「知识库」按钮里的「同步」入口与 git 状态点', ui.showSyncButton !== false)
234
+ checkField('ui.followDshTheme', '嵌入式 TW 跟随 DSH 深浅主题(暗色时自动切深色 palette,不写回 wiki)', ui.followDshTheme !== false)
235
+ textField('ui.darkPalette', '暗色时 TW palette(tiddler 标题)', typeof ui.darkPalette === 'string' && ui.darkPalette.trim().length > 0 ? ui.darkPalette.trim() : '$:/palettes/CupertinoDark')
236
+ textField('ui.tabLabel', '会话顶部「知识库」Tab 名称', typeof ui.tabLabel === 'string' && ui.tabLabel.trim().length > 0 ? ui.tabLabel.trim() : '知识库')
237
+ checkField('ui.showSessionTab', '显示会话顶部「知识库」Tab(本会话相关 wiki 笔记汇总)', ui.showSessionTab !== false)
238
+ checkField('ui.showRightbarTab', '在 DSH 右侧边栏提供 TiddlyWiki 入口/Tab(与聊天并排)', ui.showRightbarTab !== false)
239
+ const sendToAgent = (ui.sendToAgent ?? {}) as Record<string, unknown>
240
+ checkField('ui.sendToAgent.enabled', '启用「发送给 Agent」(TW 笔记 → DSH 会话注入)', sendToAgent.enabled !== false)
241
+ textField('ui.sendToAgent.endpoint', 'TW 端请求基址(空=自动取当前 DSH origin)', typeof sendToAgent.endpoint === 'string' ? sendToAgent.endpoint : '')
242
+ tokenField('ui.sendToAgent.token', '共享 token(非空时路由校验 x-send-to-agent-token 头;已设置时显示为 ********,原样保存=不改,清空=删除)', typeof sendToAgent.token === 'string' ? sendToAgent.token : '')
243
+ const allArticles = (ui.allArticles ?? {}) as Record<string, unknown>
244
+ // 1–200 是「所有文章」分页的有效范围(超出后分页会失序),宿主不会替我们夹取,所以在这里挡住。
245
+ numField('ui.allArticles.pageSize', '「所有文章」每页条数(1–200)', typeof allArticles.pageSize === 'number' ? allArticles.pageSize : 10, { min: 1, max: 200, step: 1, integer: true })
246
+
247
+ // ── 可选功能:微信公众号发布(v0.23.0)────────────────────────────────────
248
+ // 默认关闭:这项能力需要**额外安装**(opencli + 浏览器扩展,见
249
+ // docs/wechat-publish-setup.md),插件本体不含它。关闭时不注入任何发布相关
250
+ // 提示词、也不自动写「发布元数据规范」文档,避免打扰不用它的用户。
251
+ section.append(make('h3', 'dsh-tw-settings-h', '可选功能:微信公众号发布'))
252
+ section.append(make(
253
+ 'div',
254
+ 'dsh-tw-settings-muted',
255
+ '把 wiki 笔记一键发到公众号草稿箱(可选点发表)。**需要额外安装**:opencli 与 Browser Bridge 浏览器扩展,'
256
+ + '并让浏览器登录 mp.weixin.qq.com;adapter 在本仓库 tools/wechat/,安装与排错见 docs/wechat-publish-setup.md。'
257
+ + '不安装/不开启它,插件其他功能完全不受影响。开启后:注入提示词会多一条「发布前先读发布元数据规范」的约定,'
258
+ + '并在启动时把「发布元数据规范」与「微信公众号发布指南」(安装/换机还原步骤,等于仓库 docs/wechat-publish-setup.md)'
259
+ + '两篇文档写进 wiki(同名不覆盖)。',
260
+ ))
261
+ const wechat = (config.wechat ?? {}) as Record<string, unknown>
262
+ const wechatEnabled = checkField('wechat.enabled', '启用微信公众号发布(默认关;需先按 docs/wechat-publish-setup.md 安装 opencli + 浏览器扩展)', wechat.enabled === true)
263
+ // 以下四项 v0.23.3 宿主就支持,但设置页此前只暴露了 enabled —— 于是 token 这个安全开关
264
+ // 只能手改 wiki 里的 config tiddler。token 非空时 `/wechat/*` 要求 x-wechat-publish-token
265
+ // 头,防的是「任何能打开 DSH Web UI 的人都能用你本机 Chrome 对外发文」。
266
+ textField('wechat.command', 'opencli 命令(默认 opencli;用别名或绝对路径时填这里。仅在启用微信发布时生效)', typeof wechat.command === 'string' && wechat.command.trim().length > 0 ? wechat.command.trim() : 'opencli')
267
+ selectField('wechat.adapter', '发布适配器(仅在启用微信发布时生效)', wechat.adapter === 'publish-note-imgs' ? 'publish-note-imgs' : 'publish-note', [
268
+ { value: 'publish-note', label: 'publish-note(默认):图文排版,封面单图' },
269
+ { value: 'publish-note-imgs', label: 'publish-note-imgs:正文内嵌图全部上传 CDN(需先重跑 install-wechat-adapters.mjs)' },
270
+ ])
271
+ tokenField('wechat.token', '发布 token(非空时 /wechat/* 校验 x-wechat-publish-token 头,强烈建议设置,否则任何能打开本页的人都能替你发文;已设置时显示为 ********,原样保存=不改,清空=删除。仅在启用微信发布时生效)', typeof wechat.token === 'string' ? wechat.token : '')
272
+ textField('wechat.dsn', '渲染基址 dsn(adapter 回连 DSH 用,形如 http://127.0.0.1:<端口>/dsh-tiddlywiki;留空=按请求自动推导。仅在启用微信发布时生效)', typeof wechat.dsn === 'string' ? wechat.dsn : '')
273
+
274
+ // ── 系统提示词(v0.21.0;草稿预览 v0.22.7)────────────────────────────────
275
+ const prompt = (config.prompt ?? {}) as Record<string, unknown>
276
+ section.append(make('h3', 'dsh-tw-settings-h', '系统提示词(注入每个会话)'))
277
+ section.append(make('div', 'dsh-tw-settings-muted', '插件把自己的约定(同步纪律 / 标签约定 / 链接格式等)注入每个会话的系统提示词。保存后**无需重启 dsh web**:section 会即时重新注册,当前会话从下一步起就使用新文本。'))
278
+ const promptEnabled = checkField('prompt.enabled', '注入 TiddlyWiki 提示词(关闭后本插件不再注入任何文本)', prompt.enabled !== false)
279
+ const promptMode = selectField('prompt.mode', '内置文本形态', prompt.mode === 'full' ? 'full' : 'slim', [
280
+ { value: 'slim', label: '精简(默认):只保留工具 schema 表达不了的约定' },
281
+ { value: 'full', label: '完整:额外附一份由工具注册表实时生成的参数索引' },
282
+ ])
283
+ const promptExtra = areaField('prompt.extra', '附加说明(永远追加在末尾,可放团队/个人规范)', typeof prompt.extra === 'string' ? prompt.extra : '', 5)
284
+ const promptOverride = areaField('prompt.override', '整段替换(非空时取代上面的内置文本,附加说明仍会追加)', typeof prompt.override === 'string' ? prompt.override : '', 8)
285
+ /** Any prompt.* field (or the gating wechat.enabled) differs from saved. */
286
+ const promptDirty = (): boolean =>
287
+ fields.some((f) => (f.key.startsWith('prompt.') || f.key === 'wechat.enabled') && f.changed())
288
+ const preview = make('button', 'dsh-tw-settings-btn', '预览注入文本(按表单当前值)')
289
+ preview.type = 'button'
290
+ preview.title = '按表单当前值渲染注入文本(不用先保存);点「保存配置」后这就是实际注入的内容'
291
+ const previewOut = make('pre', 'dsh-tw-settings-prompt-preview')
292
+ previewOut.hidden = true
293
+ preview.addEventListener('click', () => {
294
+ if (!previewOut.hidden) {
295
+ previewOut.hidden = true
296
+ previewOut.textContent = ''
297
+ return
298
+ }
299
+ preview.disabled = true
300
+ void (async () => {
301
+ try {
302
+ // Send the DRAFT (v0.22.7): the host builds the text from these values
303
+ // without saving them, so the preview follows the dropdown immediately
304
+ // instead of showing the still-saved mode until 保存配置 is clicked.
305
+ const data = await fetchJson<{ ok?: boolean; draft?: boolean; enabled?: boolean; mode?: string; length?: number; text?: string; error?: string }>(withWiki(PROMPT_ENDPOINT), {
306
+ method: 'POST',
307
+ headers: { 'content-type': 'application/json' },
308
+ body: JSON.stringify({
309
+ enabled: promptEnabled.checked,
310
+ mode: promptMode.value,
311
+ extra: promptExtra.value,
312
+ override: promptOverride.value,
313
+ // 可选功能的开关也会改变注入文本(是否含发布约定),所以一并送草稿
314
+ // (v0.23.0;否则勾选它再预览会看到旧文本)。
315
+ wechat: wechatEnabled.checked,
316
+ }),
317
+ })
318
+ if (data.ok !== true) throw new Error(data.error ?? '获取失败')
319
+ previewOut.textContent = data.enabled === false
320
+ ? '(已关闭:不会注入任何提示词)'
321
+ : `# 形态 ${data.mode ?? ''} · ${data.length ?? 0} 字符${promptDirty() ? '(含未保存的修改,保存后才真正注入)' : ''}\n\n${data.text ?? ''}`
322
+ previewOut.hidden = false
323
+ } catch (err) {
324
+ toast(`读取提示词失败:${err instanceof Error ? err.message : String(err)}`)
325
+ } finally {
326
+ preview.disabled = false
327
+ }
328
+ })()
329
+ })
330
+ section.append(preview, previewOut)
331
+
332
+ const bridge = (config.bridge ?? {}) as Record<string, unknown>
333
+ checkField('bridge.enabled', '启用「本地剪藏桥」(书签小工具后端监听 127.0.0.1 端口,保存后立即生效)', bridge.enabled === true)
334
+ // 宿主的真实规则(index.ts effectiveBridge):必须是 1–65535 的整数,否则静默用默认 8618 ——
335
+ // 这里不拦,用户会以为端口改了,其实监听还在 8618。
336
+ numField('bridge.port', '剪藏桥端口(整数 1–65535;改端口需重启 dsh web 生效)', typeof bridge.port === 'number' && bridge.port > 0 ? bridge.port : 8618, { min: 1, max: 65_535, step: 1, integer: true })
337
+ tokenField('bridge.token', '剪藏桥 token(非空时校验书签的 x-clip-token 头;强烈建议设置。已设置时显示为 ********,原样保存=不改,清空=删除)', typeof bridge.token === 'string' ? bridge.token : '')
338
+ textField('bridge.tag', '剪藏笔记默认 tag', typeof bridge.tag === 'string' && bridge.tag.trim().length > 0 ? bridge.tag.trim() : 'clip')
339
+ // 剪藏目标库(v0.28.8):剪藏桥自建 loopback 服务,请求走不到宿主的 `?wiki=` 解析,
340
+ // 所以多库下**必须**在这里显式选一次,否则永远剪进默认库。选项要等 /admin/wikis
341
+ // 回来才知道,所以先渲染一个只有「默认库」的 select,拿到列表后再补全;用户已选的值
342
+ // 若不在列表里(库被移出清单)也保留一行,免得下拉把它静默抹掉。
343
+ const clipWiki = selectField('bridge.wiki', '剪藏写入的知识库(默认库=不指定;多库时可指定某个库)', typeof bridge.wiki === 'string' ? bridge.wiki.trim() : '', [{ value: '', label: '默认库' }])
344
+ void (async () => {
345
+ try {
346
+ const view = await fetchJson<WikisView>(WIKI_LIST_ENDPOINT)
347
+ if (isDisposed()) return
348
+ const items = Array.isArray(view.wikis) ? view.wikis : []
349
+ const current = clipWiki.value
350
+ for (const wiki of items) {
351
+ const option = document.createElement('option')
352
+ option.value = wiki.id
353
+ option.textContent = `${wiki.label}(${wiki.id})${wiki.running ? '' : ' · 未运行'}`
354
+ clipWiki.append(option)
355
+ }
356
+ // 当前值不在清单里(已移出):补一行,避免下拉静默把它抹成默认库。
357
+ if (current.length > 0 && !items.some((wiki) => wiki.id === current)) {
358
+ const option = document.createElement('option')
359
+ option.value = current
360
+ option.textContent = `${current}(不在清单里,保存后回落默认库)`
361
+ clipWiki.append(option)
362
+ }
363
+ clipWiki.value = current
364
+ } catch {
365
+ /* 读不到清单:只有「默认库」一项,单库安装本来就是这种形态 */
366
+ }
367
+ })()
368
+ // 界面语言在下方「语言管理」区块设置(config 的 uiLanguage 仅供启动时自动应用)。
369
+ // 注意:uiLanguage 目前只影响 TW 侧语言,客户端插件文案(FAB/快速笔记/侧边栏/本页)
370
+ // 暂为中文,尚无 i18n 分支。
371
+
372
+ // 保存失败的解释性横幅(v0.24.x):文案存在 mount 级 configState 里,因为 refresh()
373
+ // 可能按新签名重建整个配置区 —— 局部 DOM 连同这里刚写的节点会一起消失,重建后要从
374
+ // configState 里把「最近一次保存错误」再渲染回来。
375
+ const saveErrorBanner = makeErrorBanner(configState.saveError ?? '')
376
+ saveErrorBanner.hidden = configState.saveError === undefined
377
+
378
+ const save = make('button', 'dsh-tw-settings-btn dsh-tw-settings-primary', '保存配置')
379
+ save.type = 'button'
380
+ save.addEventListener('click', () => {
381
+ save.disabled = true
382
+ void (async () => {
383
+ // 数值字段非法就直接拒绝提交:宿主对越界值只会静默夹取/回落,提交它等于把
384
+ // 「页面显示的值」和「真正生效的值」再次分开 —— 那正是这轮要修的 bug。
385
+ const invalidFields = fields.filter((field) => field.invalid?.() !== undefined)
386
+ if (invalidFields.length > 0) {
387
+ toast(`有 ${invalidFields.length} 个字段填得不对(见字段旁的红色提示),未保存`)
388
+ save.disabled = false
389
+ return
390
+ }
391
+ const patch: Record<string, unknown> = {}
392
+ for (const field of fields) {
393
+ if (!field.changed()) continue
394
+ // Build nested paths like note.tag → {note:{tag}} and
395
+ // ui.allArticles.pageSize → {ui:{allArticles:{pageSize}}}.
396
+ const parts = field.key.split('.')
397
+ let node = patch
398
+ for (let i = 0; i < parts.length; i++) {
399
+ const part = parts[i]
400
+ if (part === undefined) break
401
+ if (i === parts.length - 1) {
402
+ node[part] = field.read()
403
+ } else {
404
+ const child = (node[part] ?? {}) as Record<string, unknown>
405
+ node[part] = child
406
+ node = child
407
+ }
408
+ }
409
+ }
410
+ // 没有任何改动就别发请求:宿主收到空 patch 也会整体重写 config tiddler 并刷新
411
+ // modified —— 白白给 git 造 diff(两台机器各点一次「保存」就会在 .meta 上冲突)。
412
+ if (Object.keys(patch).length === 0) {
413
+ toast('没有改动')
414
+ save.disabled = false
415
+ return
416
+ }
417
+ try {
418
+ await fetchJson(withWiki(CONFIG_ENDPOINT), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(patch) })
419
+ // ui.* 已落盘:清掉客户端缓存,下一次读取立即拿到新值(否则最长 15s 才生效)。
420
+ invalidateUiConfig()
421
+ configState.saveError = undefined
422
+ saveErrorBanner.hidden = true
423
+ saveErrorBanner.textContent = ''
424
+ toast('配置已保存')
425
+ void refresh()
426
+ } catch (err) {
427
+ const message = err instanceof Error ? err.message : String(err)
428
+ // 不能只 toast:失败原因(典型是 409「配置 tiddler 不是合法 JSON,保存已被拒绝」)
429
+ // 需要持久可见,否则用户看到的就是「点了保存但什么都没发生」。
430
+ configState.saveError = `保存失败:${message}`
431
+ saveErrorBanner.textContent = configState.saveError
432
+ saveErrorBanner.hidden = false
433
+ // 顺带刷一次:宿主可能因此在顶部给出「配置未生效」横幅(state.configError)。
434
+ void refresh()
435
+ } finally {
436
+ save.disabled = false
437
+ }
438
+ })()
439
+ })
440
+ // 暴露「有未保存改动」给 renderMain:签名变化时据此决定要不要重建表单(见
441
+ // ConfigRenderState.isDirty)。
442
+ configState.isDirty = () => fields.some((field) => field.changed())
443
+ section.append(saveErrorBanner, save)
444
+ body.append(section)
445
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Shared runtime of the settings page (v0.28.8 split).
3
+ *
4
+ * Everything the settings sections have in common and that is NOT itself a
5
+ * section: the same-origin JSON fetch with its caller-wins timeout, the red
6
+ * explanation banner, the knowledge-base roster shape (`GET /admin/wikis`) and
7
+ * the "which wiki am I editing" scope every per-wiki admin call must carry.
8
+ *
9
+ * Keeping these four together is deliberate: they are the rules a section can
10
+ * get WRONG in a way nobody notices (a dropped `?wiki=` silently edits the
11
+ * default wiki; a hardcoded timeout reports failure while the host kept going).
12
+ * They live here, once, and the sections import them.
13
+ *
14
+ * @module dsh-tiddlywiki/client/settings-page-runtime
15
+ */
16
+ import { make } from './dom.ts'
17
+
18
+ /**
19
+ * 红色解释横幅。页面里没有对应 CSS 类(host 注入的样式表不归本文件管),内联样式
20
+ * 是与宿主既定的视觉约定;抽成函数是为了两处横幅(配置未生效 / 保存被拒)长得一致。
21
+ */
22
+ export function makeErrorBanner(text: string): HTMLDivElement {
23
+ const banner = make('div', 'dsh-tw-settings-banner')
24
+ banner.dataset.tone = 'error'
25
+ banner.setAttribute('style', 'border:1px solid #c0392b;background:#fdecea;color:#8c1c13;border-radius:6px;padding:10px 12px;margin:0 0 12px;font-size:12px;line-height:1.6;white-space:pre-wrap;')
26
+ banner.textContent = text
27
+ return banner
28
+ }
29
+
30
+ /**
31
+ * Same-origin JSON fetch with a default timeout and a JSON error body.
32
+ *
33
+ * ⚠️ The caller's `signal` must WIN (v0.22.8). This used to be
34
+ * `fetch(url, { ...init, signal: AbortSignal.timeout(15_000) })` — spreading
35
+ * `init` first and then hardcoding the signal, so every caller-supplied budget
36
+ * was silently discarded. 知识库切换 / 恢复默认 pass 120s (the host stops TW,
37
+ * may `--init server`, bootstraps and restarts it — v0.22.5 documents 44s+
38
+ * cold starts), so the browser aborted at 15s and toasted「切换失败」 while the
39
+ * host kept going and DID switch; the same 15s cap hit the 重启 TW button.
40
+ */
41
+ export async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
42
+ const res = await fetch(url, { ...init, signal: init?.signal ?? AbortSignal.timeout(15_000) })
43
+ const data = (await res.json().catch(() => ({}))) as T
44
+ if (!res.ok) {
45
+ const err = (data as { error?: string }).error ?? `HTTP ${res.status}`
46
+ throw new Error(err)
47
+ }
48
+ return data
49
+ }
50
+
51
+ /** One knowledge base as `GET /admin/wikis` reports it (v0.28.0). */
52
+ export interface WikiListItemView {
53
+ id: string
54
+ label: string
55
+ root: string
56
+ name: string
57
+ path: string
58
+ agentVisible: boolean
59
+ autostart: boolean
60
+ running: boolean
61
+ status: string
62
+ /** Per-wiki entry icon (v0.28.4): a curated name or a short emoji. */
63
+ icon?: string
64
+ }
65
+
66
+
67
+ /** `GET`/`POST` /dsh-tiddlywiki/admin/wikis` payload (v0.28.0). */
68
+ export interface WikisView {
69
+ ok?: boolean
70
+ error?: string
71
+ mode?: string
72
+ defaultId?: string
73
+ source?: string
74
+ registryFile?: string
75
+ warnings?: string[]
76
+ wikis?: WikiListItemView[]
77
+ change?: { started?: string[]; stopped?: string[]; updated?: string[]; errors?: Array<{ id: string; message: string }> }
78
+ }
79
+
80
+ /**
81
+ * WHICH knowledge base the config block is editing (v0.28.0).
82
+ *
83
+ * Every per-wiki setting lives in that wiki's OWN
84
+ * `$:/plugins/dsh-tiddlywiki/config` tiddler, so `/admin/state`, `/admin/config`
85
+ * and `/admin/prompt` must be told which one. Without this, configuring the books
86
+ * wiki would silently edit the DEFAULT wiki — a user would set `git.remote`, see
87
+ * it saved, and never learn why pushes still went to the other repository.
88
+ *
89
+ * `undefined` = the default wiki, which is exactly what every route did before
90
+ * this existed (and what a single-wiki install always gets).
91
+ */
92
+ export let editingWiki: string | undefined
93
+
94
+ /** Set the wiki the per-wiki sections edit (the wiki list's 「配置」 toggle). */
95
+ export function setEditingWiki(id: string | undefined): void {
96
+ editingWiki = id
97
+ }
98
+
99
+ /**
100
+ * 当前设置页分页(`overview` / `library` / `global`,v0.28.8)。
101
+ *
102
+ * It lives here rather than in `settings-page.ts` for the same reason
103
+ * `editingWiki` does: the wiki list's 「配置」 button must ALSO switch the tab
104
+ * ("点配置就看本库配置"), and that button is rendered by a section module — which
105
+ * must not import the assembly file back (that would be a cycle).
106
+ *
107
+ * It is `let` and exported directly (not only through the setter) because
108
+ * `renderMain` reads it as the same `activeTab` name the pre-split file used;
109
+ * a rename here would silently change what the guards assert on.
110
+ */
111
+ export type SettingsTab = 'overview' | 'library' | 'global'
112
+
113
+ /** 当前 Tab。模块级(与 editingWiki 同级):切换 Tab 不重建配置表单。 */
114
+ export let activeTab: SettingsTab = 'overview'
115
+
116
+ /** Read the current tab (the scope bar / render order use it). */
117
+ export function currentTab(): SettingsTab {
118
+ return activeTab
119
+ }
120
+
121
+ /** Switch the tab WITHOUT re-rendering (callers `refresh()` themselves). */
122
+ export function setActiveTab(tab: SettingsTab): void {
123
+ activeTab = tab
124
+ }
125
+
126
+ /**
127
+ * 「点某个库的『配置』」= 把作用域切到那个库 + 跳到「本库配置」那一页(v0.28.8)。
128
+ *
129
+ * The two halves are ONE user action and must stay together: the wiki list lives
130
+ * in a section module and cannot assign the imported `activeTab` binding, so the
131
+ * pair is applied here, in the module that owns both variables. The `if` guard
132
+ * (rather than an unconditional assignment) mirrors the button's own toggle —
133
+ * the caller only reaches this path when the wiki is NOT already being
134
+ * configured, and keeping the condition visible is what the guard script reads.
135
+ */
136
+ export function enterWikiScope(id: string, configuring: boolean): void {
137
+ editingWiki = id
138
+ if (!configuring) activeTab = 'library'
139
+ }
140
+
141
+ /** 退出配置 = 回到默认库的作用域(不改 Tab:用户可能仍在「本库配置」页看别的)。 */
142
+ export function exitWikiScope(): void {
143
+ editingWiki = undefined
144
+ }
145
+
146
+ /** Append the editing scope to a per-wiki admin URL. */
147
+ export function withWiki(url: string): string {
148
+ return editingWiki === undefined ? url : `${url}?wiki=${encodeURIComponent(editingWiki)}`
149
+ }