@nsnanocat/preference-panes 1.0.0 → 1.1.1

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.
@@ -1,490 +1,501 @@
1
1
  import { ActionMenu } from "./ActionMenu.mjs";
2
2
  import { validValue } from "./boxjs.mjs";
3
- import { createPreferencesClient } from "./client.mjs";
3
+ import { PreferencesClient } from "./client.mjs";
4
4
  import { fieldControl, element as node, requestConfirmation, resourceURL, settingRow, statusView } from "./components.mjs";
5
5
  import { Navigation } from "./Navigation.mjs";
6
6
 
7
7
  /**
8
- * 挂载 API 返回的模块模型表单和短暂通知。
9
- * Mount the module model returned by the API and transient notifications.
10
- * @param {HTMLElement} root 包内挂载元素 / Internal mount element.
11
- * @param {import("../index.js").ModuleModel} model API 返回的模块模型 / Module model returned by the API.
12
- * @returns {import("./index.js").MountedPreferences} 面板生命周期句柄 / Panel lifecycle handle.
8
+ * 管理模块表单、导航、操作队列和短暂通知。
9
+ * Manage the module form, navigation, operation queue, and transient notifications.
13
10
  */
14
- export function mountPanel(root, model) {
15
- const { definition } = model;
16
- const title = definition.metadata?.name ?? definition.module;
17
- const document = root.ownerDocument;
18
- const window = document.defaultView;
19
- const shell = node("div", "pp-panel");
20
- shell.dataset.module = definition.module;
21
- const header = node("header", "pp-header");
22
- const back = node("button", "pp-back", "‹");
23
- back.setAttribute("aria-label", "返回");
24
- back.type = "button";
25
- const heading = node("h1", "pp-title", title);
26
- const handlers = new Map();
27
- const menuItems = [
28
- { id: "viewSettings", label: "查看设置" },
29
- { id: "viewCaches", label: "查看缓存" },
30
- { id: "clearCaches", label: "清空缓存", destructive: true },
31
- { id: "reset", label: "重置设置", destructive: true },
32
- ];
33
- const menu = new ActionMenu(id => runAction(id));
34
- const trailing = node("span", "pp-nav-spacer");
35
- trailing.append(menu.element);
36
- const viewport = node("div", "pp-viewport");
37
- let toast;
38
- header.append(back, heading, trailing);
39
- shell.append(header, viewport);
40
- root.append(shell);
41
- // 嵌入模式向宿主发布导航状态,宿主不读取或修改模块内部 DOM。
42
- // Embedded mode publishes navigation state without host reads or mutations of the module DOM.
43
- const publishNavigation = () => {
44
- const actions = handlers.size ? menuItems : [];
45
- menu.update(actions, saving);
46
- const frame = window.frameElement;
47
- if (!frame?.dataset.preferencePanes) return;
48
- frame.dispatchEvent(
49
- new frame.ownerDocument.defaultView.CustomEvent("preferencepanes:change", {
50
- detail: { title: heading.textContent, module: definition.module, busy: saving, canGoBack: !back.disabled, actions },
51
- }),
52
- );
53
- };
54
- const onAction = event => {
55
- if (!saving && handlers.has(event.detail)) runAction(event.detail);
56
- };
57
- window.frameElement?.addEventListener("preferencepanes:action", onAction);
58
- let timer,
59
- navigation,
60
- generation = 0,
61
- active = null,
62
- saving = false,
63
- destroyed = false;
64
- /**
65
- * 展示短暂通知,不刷新设置数据。
66
- * Display a transient notification without refreshing settings.
67
- * @param {{kind: "success" | "error", operation?: "write" | "delete" | "clearCaches" | "reset", message?: string}} event 操作结果 / Operation result.
68
- * @returns {void} 无返回值 / No return value.
69
- */
70
- const notify = event => {
71
- if (destroyed) return;
72
- let message;
73
- switch (true) {
74
- case event.kind === "error":
75
- message = `操作失败:${event.message}`;
76
- break;
77
- case event.operation === "delete":
78
- message = "删除成功";
79
- break;
80
- case event.operation === "clearCaches":
81
- message = "Caches 已清空";
82
- break;
83
- case event.operation === "reset":
84
- message = "设置已重置";
85
- break;
86
- default:
87
- message = "修改成功";
88
- break;
89
- }
90
- // 宿主接管时不创建网页 Toast,也不运行其计时器。
91
- // A host-owned notice creates no web Toast and starts no local timer.
92
- const frame = window.frameElement;
93
- if (frame && !frame.dispatchEvent(new frame.ownerDocument.defaultView.CustomEvent("preferencepanes:notice", { cancelable: true, detail: { kind: event.kind, message } }))) return;
94
- if (!toast) {
95
- toast = node("div", "pp-toast");
96
- toast.setAttribute("role", "status");
97
- shell.append(toast);
98
- }
99
- toast.textContent = message;
100
- toast.dataset.kind = event.kind;
101
- toast.hidden = false;
102
- clearTimeout(timer);
103
- timer = setTimeout(() => {
104
- toast.hidden = true;
105
- }, 2400);
106
- };
107
- const client = createPreferencesClient({ model, definition, notify });
108
- /**
109
- * 两种菜单入口共用异步错误处理,包含宿主确认框错误。
110
- * Share async error handling between both menus, including host-dialog errors.
111
- * @param {string} id 操作标识 / Action identifier.
112
- * @returns {Promise<void>} 操作已处理 / Action handled.
113
- */
114
- async function runAction(id) {
115
- try {
116
- await handlers.get(id)();
117
- } catch (error) {
118
- notify({ kind: "error", message: error.message });
119
- }
120
- }
11
+ export class PreferencesPanel {
12
+ #release;
13
+
121
14
  /**
122
- * 打开模块并忽略已过期的异步结果。
123
- * Open a module and ignore stale asynchronous results.
124
- * @param {string} module 模块标识 / Module identifier.
125
- * @returns {Promise<void>} 视图加载完成,失败显示错误视图 / View load completion; failures display an error view.
15
+ * 挂载 BoxJS 定义对应的模块表单。
16
+ * Mount the module form described by a BoxJS definition.
17
+ * @param {HTMLElement} root 包内挂载元素 / Internal mount element.
18
+ * @param {import("../index.js").ModuleDefinition} definition 已规范化字段定义 / Normalized field definition.
126
19
  */
127
- async function open(module) {
128
- const version = ++generation;
129
- active = module;
130
- back.disabled = window.history.length <= 1;
131
- heading.textContent = module;
132
- publishNavigation();
133
- viewport.replaceChildren(statusView("读取设置…"));
134
- try {
135
- if (version === generation) controls();
136
- } catch (error) {
137
- if (version !== generation) return;
138
- viewport.replaceChildren(statusView(`加载失败:${error.message}`, () => open(module)));
139
- publishNavigation();
140
- }
20
+ constructor(root, definition) {
21
+ this.#release = this.#mount(root, definition);
141
22
  }
23
+
142
24
  /**
143
- * 从会话快照创建控件与操作按钮,不重新读取网络配置。
144
- * Build controls and actions from the session snapshot without fetching config again.
145
- * @returns {void} 无返回值 / No return value.
25
+ * 建立面板 DOM、交互和会话,并返回其释放操作。
26
+ * Build panel DOM, interactions, and session, then return its release operation.
27
+ * @param {HTMLElement} root 包内挂载元素 / Internal mount element.
28
+ * @param {import("../index.js").ModuleDefinition} definition 已规范化字段定义 / Normalized field definition.
29
+ * @returns {() => void} 释放操作 / Release operation.
146
30
  */
147
- function controls() {
148
- const { definition, values } = client.snapshot();
149
- heading.textContent = definition.metadata?.name || active;
150
- const view = node("section", "pp-fields");
151
- /**
152
- * 挂载后执行的多行高度更新
153
- * Textarea sizing callbacks run after mounting.
154
- * @type {Array<() => void>}
155
- */
156
- const growingInputs = [];
157
- const editors = new Map();
158
- const summaries = [];
159
- const groups = new Map();
160
- let queue = Promise.resolve(),
161
- pendingWrites = 0;
31
+ #mount(root, definition) {
32
+ const title = definition.metadata?.name ?? definition.module;
33
+ const document = root.ownerDocument;
34
+ const window = document.defaultView;
35
+ const shell = node("div", "pp-panel");
36
+ shell.dataset.module = definition.module;
37
+ const header = node("header", "pp-header");
38
+ const back = node("button", "pp-back", "‹");
39
+ back.setAttribute("aria-label", "返回");
40
+ back.type = "button";
41
+ const heading = node("h1", "pp-title", title);
42
+ const handlers = new Map();
43
+ const menuItems = [
44
+ { id: "viewSettings", label: "查看设置" },
45
+ { id: "viewCaches", label: "查看缓存" },
46
+ { id: "clearCaches", label: "清空缓存", destructive: true },
47
+ { id: "reset", label: "重置设置", destructive: true },
48
+ ];
49
+ const menu = new ActionMenu(id => runAction(id));
50
+ const trailing = node("span", "pp-nav-spacer");
51
+ trailing.append(menu.element);
52
+ const viewport = node("div", "pp-viewport");
53
+ let toast;
54
+ header.append(back, heading, trailing);
55
+ shell.append(header, viewport);
56
+ root.append(shell);
57
+ // 嵌入模式向宿主发布导航状态,宿主不读取或修改模块内部 DOM。
58
+ // Embedded mode publishes navigation state without host reads or mutations of the module DOM.
59
+ const publishNavigation = () => {
60
+ const actions = handlers.size ? menuItems : [];
61
+ menu.update(actions, saving);
62
+ const frame = window.frameElement;
63
+ if (!frame?.dataset.preferencePanes) return;
64
+ frame.dispatchEvent(
65
+ new frame.ownerDocument.defaultView.CustomEvent("preferencepanes:change", {
66
+ detail: { title: heading.textContent, module: definition.module, busy: saving, canGoBack: !back.disabled, actions },
67
+ }),
68
+ );
69
+ };
70
+ const onAction = event => {
71
+ if (!saving && handlers.has(event.detail)) runAction(event.detail);
72
+ };
73
+ window.frameElement?.addEventListener("preferencepanes:action", onAction);
74
+ let timer,
75
+ navigation,
76
+ generation = 0,
77
+ active = null,
78
+ saving = false,
79
+ destroyed = false;
162
80
  /**
163
- * 导航组件处理页面切换,表单只更新当前标题与返回按钮。
164
- * Let navigation own transitions; the form only updates the title and back button.
81
+ * 展示短暂通知,不刷新设置数据。
82
+ * Display a transient notification without refreshing settings.
83
+ * @param {{kind: "success" | "error", operation?: "write" | "delete" | "clearCaches" | "reset", message?: string}} event 操作结果 / Operation result.
165
84
  * @returns {void} 无返回值 / No return value.
166
85
  */
167
- const updateNavigation = () => {
168
- const editor = editors.get(navigation.current);
169
- heading.textContent = editor?.title ?? definition.metadata?.name ?? active;
170
- back.disabled = saving || !navigation.canGoBack;
171
- publishNavigation();
86
+ const notify = event => {
87
+ if (destroyed) return;
88
+ let message;
89
+ switch (true) {
90
+ case event.kind === "error":
91
+ message = `操作失败:${event.message}`;
92
+ break;
93
+ case event.operation === "delete":
94
+ message = "删除成功";
95
+ break;
96
+ case event.operation === "clearCaches":
97
+ message = "Caches 已清空";
98
+ break;
99
+ case event.operation === "reset":
100
+ message = "设置已重置";
101
+ break;
102
+ default:
103
+ message = "修改成功";
104
+ break;
105
+ }
106
+ // 宿主接管时不创建网页 Toast,也不运行其计时器。
107
+ // A host-owned notice creates no web Toast and starts no local timer.
108
+ const frame = window.frameElement;
109
+ if (frame && !frame.dispatchEvent(new frame.ownerDocument.defaultView.CustomEvent("preferencepanes:notice", { cancelable: true, detail: { kind: event.kind, message } }))) return;
110
+ if (!toast) {
111
+ toast = node("div", "pp-toast");
112
+ toast.setAttribute("role", "status");
113
+ shell.append(toast);
114
+ }
115
+ toast.textContent = message;
116
+ toast.dataset.kind = event.kind;
117
+ toast.hidden = false;
118
+ clearTimeout(timer);
119
+ timer = setTimeout(() => {
120
+ toast.hidden = true;
121
+ }, 2400);
172
122
  };
123
+ const client = new PreferencesClient({ definition, notify });
173
124
  /**
174
- * 串行执行模块操作,保持输入可编辑。
175
- * Serialize module actions while keeping inputs editable.
176
- * @param {() => Promise<void>} action 请求或写入 / Request or mutation.
177
- * @param {() => void} success 成功后的局部更新 / Local update after success.
178
- * @param {() => void} [failure] 失败后恢复当前输入 / Restore the current input on failure.
179
- * @returns {Promise<void>} 操作完成 / Operation completion.
125
+ * 两种菜单入口共用异步错误处理,包含宿主确认框错误。
126
+ * Share async error handling between both menus, including host-dialog errors.
127
+ * @param {string} id 操作标识 / Action identifier.
128
+ * @returns {Promise<void>} 操作已处理 / Action handled.
180
129
  */
181
- function perform(action, success, failure = () => {}) {
182
- pendingWrites++;
183
- saving = true;
184
- back.disabled = true;
185
- publishNavigation();
186
- queue = queue
187
- .then(action)
188
- .then(() => {
189
- if (!destroyed) success();
190
- })
191
- .catch(() => {
192
- /* 请求层已通知错误。
193
- * The request layer has already reported the error. */
194
- if (!destroyed) failure();
195
- })
196
- .finally(() => {
197
- pendingWrites--;
198
- saving = pendingWrites > 0;
199
- if (destroyed && !saving) client.leave();
200
- back.disabled = saving || !navigation.canGoBack;
201
- publishNavigation();
202
- });
203
- return queue;
204
- }
205
- const metadata = definition.metadata;
206
- if (metadata) {
207
- const info = node("div", "pp-module-info");
208
- const details = node("div", "pp-module-details");
209
- for (const description of [metadata.author, metadata.desc ?? metadata.description, ...(metadata.descs ?? [])]) if (description) details.append(node("p", "pp-description", description));
210
- if (metadata.repo) {
211
- const link = node("a", "pp-module-source", "项目主页");
212
- link.href = resourceURL(metadata.repo);
213
- link.target = "_blank";
214
- link.rel = "noopener noreferrer";
215
- details.append(link);
130
+ async function runAction(id) {
131
+ try {
132
+ await handlers.get(id)();
133
+ } catch (error) {
134
+ notify({ kind: "error", message: error.message });
216
135
  }
217
- info.append(details);
218
- view.append(info);
219
136
  }
220
- for (const field of definition.fields) {
221
- const match = /^\[([^\]]+)\]\s*(.*)$/.exec(field.name);
222
- const group = match?.[1] ?? "通用";
223
- if (!groups.has(group)) {
224
- const section = node("section", "pp-group");
225
- const rows = node("div", "pp-rows");
226
- section.append(node("h2", "pp-group-title", group), rows);
227
- groups.set(group, rows);
228
- view.append(section);
137
+ /**
138
+ * 打开模块并忽略已过期的异步结果。
139
+ * Open a module and ignore stale asynchronous results.
140
+ * @param {string} module 模块标识 / Module identifier.
141
+ * @returns {Promise<void>} 视图加载完成,失败显示错误视图 / View load completion; failures display an error view.
142
+ */
143
+ async function open(module) {
144
+ const version = ++generation;
145
+ active = module;
146
+ back.disabled = window.history.length <= 1;
147
+ heading.textContent = module;
148
+ publishNavigation();
149
+ viewport.replaceChildren(statusView("读取设置…"));
150
+ try {
151
+ await client.open();
152
+ if (version === generation) controls();
153
+ } catch (error) {
154
+ if (version !== generation) return;
155
+ viewport.replaceChildren(statusView(`加载失败:${error.message}`, () => open(module)));
156
+ publishNavigation();
229
157
  }
230
- const row = settingRow("div");
231
- row.classList.add("pp-field");
232
- const label = node("div", "pp-label");
233
- label.append(node("span", "pp-field-name", match?.[2] ?? field.name));
234
- if (field.description) label.append(node("span", "pp-field-description", field.description));
235
- row.append(label);
236
- const value = values[field.key];
158
+ }
159
+ /**
160
+ * 从会话快照创建控件与操作按钮,不重新读取网络配置。
161
+ * Build controls and actions from the session snapshot without fetching config again.
162
+ * @returns {void} 无返回值 / No return value.
163
+ */
164
+ function controls() {
165
+ const { definition, values } = client.snapshot();
166
+ heading.textContent = definition.metadata?.name || active;
167
+ const view = node("section", "pp-fields");
237
168
  /**
238
- * 读取尚未保存的输入
239
- * Read the unsaved input.
240
- * @type {() => unknown}
169
+ * 挂载后执行的多行高度更新
170
+ * Textarea sizing callbacks run after mounting.
171
+ * @type {Array<() => void>}
241
172
  */
242
- let read;
173
+ const growingInputs = [];
174
+ const editors = new Map();
175
+ const summaries = [];
176
+ const groups = new Map();
177
+ let queue = Promise.resolve(),
178
+ pendingWrites = 0;
243
179
  /**
244
- * 更新当前控件
245
- * Update the current control.
246
- * @type {(value: unknown) => void}
180
+ * 导航组件处理页面切换,表单只更新当前标题与返回按钮。
181
+ * Let navigation own transitions; the form only updates the title and back button.
182
+ * @returns {void} 无返回值 / No return value.
247
183
  */
248
- let write;
249
- let inputContainer = row;
250
- let eventName = "change";
251
- switch (true) {
252
- case Boolean(field.options) && field.type !== "array": {
253
- const select = node("select", "");
254
- select.setAttribute("aria-label", field.name);
255
- field.options.forEach((option, index) => {
256
- const item = node("option", "", option.label);
257
- item.value = String(index);
258
- select.append(item);
259
- });
260
- write = value => {
261
- select.selectedIndex = field.options.findIndex(option => option.key === value);
262
- };
263
- row.append(fieldControl(select));
264
- read = () => field.options[select.selectedIndex]?.key;
265
- break;
266
- }
267
- case field.type === "array" && Boolean(field.options): {
268
- const page = node("section", "pp-choice-page");
269
- if (field.description) page.append(node("p", "pp-description", field.description));
270
- const choices = node("div", "pp-rows");
271
- page.append(choices);
272
- inputContainer = choices;
273
- editors.set(field.key, { node: page, title: match?.[2] ?? field.name });
274
- const summary = node("span", "pp-summary");
275
- const link = node("button", "pp-choice-link");
276
- link.type = "button";
277
- link.setAttribute("aria-label", field.name);
278
- link.append(summary, node("span", "pp-chevron", "›"));
279
- row.append(link);
280
- const refresh = () => {
281
- const value = client.snapshot().values[field.key];
282
- summary.textContent =
283
- field.options
284
- .filter(option => Array.isArray(value) && value.includes(option.key))
285
- .map(option => option.label)
286
- .join("、") || "未选择";
287
- };
288
- summaries.push(refresh);
289
- refresh();
290
- link.onclick = () => navigation.open(field.key);
291
- row.addEventListener("click", event => {
292
- if (!link.contains(event.target)) link.click();
293
- });
294
- const inputs = field.options.map(option => {
295
- const label = settingRow("label");
296
- label.classList.add("pp-choice");
297
- label.textContent = option.label;
298
- const input = node("input", "");
299
- input.type = "checkbox";
300
- input.setAttribute("aria-label", option.label);
301
- label.append(input);
302
- choices.append(label);
303
- return { input, key: option.key };
184
+ const updateNavigation = () => {
185
+ const editor = editors.get(navigation.current);
186
+ heading.textContent = editor?.title ?? definition.metadata?.name ?? active;
187
+ back.disabled = saving || !navigation.canGoBack;
188
+ publishNavigation();
189
+ };
190
+ /**
191
+ * 串行执行模块操作,保持输入可编辑。
192
+ * Serialize module actions while keeping inputs editable.
193
+ * @param {() => Promise<void>} action 请求或写入 / Request or mutation.
194
+ * @param {() => void} success 成功后的局部更新 / Local update after success.
195
+ * @param {() => void} [failure] 失败后恢复当前输入 / Restore the current input on failure.
196
+ * @returns {Promise<void>} 操作完成 / Operation completion.
197
+ */
198
+ function perform(action, success, failure = () => {}) {
199
+ pendingWrites++;
200
+ saving = true;
201
+ back.disabled = true;
202
+ publishNavigation();
203
+ queue = queue
204
+ .then(action)
205
+ .then(() => {
206
+ if (!destroyed) success();
207
+ })
208
+ .catch(() => {
209
+ /* 请求层已通知错误。
210
+ * The request layer has already reported the error. */
211
+ if (!destroyed) failure();
212
+ })
213
+ .finally(() => {
214
+ pendingWrites--;
215
+ saving = pendingWrites > 0;
216
+ if (destroyed && !saving) client.leave();
217
+ back.disabled = saving || !navigation.canGoBack;
218
+ publishNavigation();
304
219
  });
305
- read = () => inputs.filter(option => option.input.checked).map(option => option.key);
306
- write = value => {
307
- for (const option of inputs) option.input.checked = Array.isArray(value) && value.includes(option.key);
308
- };
309
- break;
220
+ return queue;
221
+ }
222
+ const metadata = definition.metadata;
223
+ if (metadata) {
224
+ const info = node("div", "pp-module-info");
225
+ const details = node("div", "pp-module-details");
226
+ for (const description of [metadata.author, metadata.desc ?? metadata.description, ...(metadata.descs ?? [])]) if (description) details.append(node("p", "pp-description", description));
227
+ if (metadata.repo) {
228
+ const link = node("a", "pp-module-source", "项目主页");
229
+ link.href = resourceURL(metadata.repo);
230
+ link.target = "_blank";
231
+ link.rel = "noopener noreferrer";
232
+ details.append(link);
310
233
  }
311
- case field.type === "boolean": {
312
- const toggle = node("input", "pp-switch");
313
- toggle.type = "checkbox";
314
- toggle.setAttribute("switch", "");
315
- toggle.setAttribute("role", "switch");
316
- toggle.setAttribute("aria-label", field.name);
317
- write = value => {
318
- toggle.checked = value === true;
319
- };
320
- read = () => toggle.checked;
321
- row.append(toggle);
322
- break;
234
+ info.append(details);
235
+ view.append(info);
236
+ }
237
+ for (const field of definition.fields) {
238
+ const match = /^\[([^\]]+)\]\s*(.*)$/.exec(field.name);
239
+ const group = match?.[1] ?? "通用";
240
+ if (!groups.has(group)) {
241
+ const section = node("section", "pp-group");
242
+ const rows = node("div", "pp-rows");
243
+ section.append(node("h2", "pp-group-title", group), rows);
244
+ groups.set(group, rows);
245
+ view.append(section);
323
246
  }
324
- default: {
325
- const multiline = field.control === "textarea" || field.type === "array";
326
- const input = node(multiline ? "textarea" : "input", "");
327
- if (multiline) row.classList.add("pp-multiline");
328
- input.setAttribute("aria-label", field.name);
329
- if (field.placeholder) input.placeholder = field.placeholder;
330
- if (multiline && field.rows) input.rows = field.rows;
331
- /**
332
- * 在挂载后根据内容调整高度,同时保留基础行数。
333
- * Size mounted textareas to their contents while retaining baseline rows.
334
- * @returns {void} 无返回值 / No return value.
335
- */
336
- const grow = () => {
337
- if (!multiline || !field.autoGrow || !input.isConnected) return;
338
- input.style.height = "auto";
339
- const baseline = input.getBoundingClientRect().height;
340
- const style = window.getComputedStyle(input);
341
- const borders = Number.parseFloat(style.borderTopWidth) + Number.parseFloat(style.borderBottomWidth);
342
- input.style.height = `${Math.max(baseline, input.scrollHeight + borders)}px`;
343
- };
344
- if (multiline && field.autoGrow) {
345
- input.addEventListener("input", grow);
346
- growingInputs.push(grow);
247
+ const row = settingRow("div");
248
+ row.classList.add("pp-field");
249
+ const label = node("div", "pp-label");
250
+ label.append(node("span", "pp-field-name", match?.[2] ?? field.name));
251
+ if (field.description) label.append(node("span", "pp-field-description", field.description));
252
+ row.append(label);
253
+ const value = values[field.key];
254
+ /**
255
+ * 读取尚未保存的输入
256
+ * Read the unsaved input.
257
+ * @type {() => unknown}
258
+ */
259
+ let read;
260
+ /**
261
+ * 更新当前控件
262
+ * Update the current control.
263
+ * @type {(value: unknown) => void}
264
+ */
265
+ let write;
266
+ let inputContainer = row;
267
+ let eventName = "change";
268
+ switch (true) {
269
+ case Boolean(field.options) && field.type !== "array": {
270
+ const select = node("select", "");
271
+ select.setAttribute("aria-label", field.name);
272
+ field.options.forEach((option, index) => {
273
+ const item = node("option", "", option.label);
274
+ item.value = String(index);
275
+ select.append(item);
276
+ });
277
+ write = value => {
278
+ select.selectedIndex = field.options.findIndex(option => option.key === value);
279
+ };
280
+ row.append(fieldControl(select));
281
+ read = () => field.options[select.selectedIndex]?.key;
282
+ break;
347
283
  }
348
- eventName = "input";
349
- if (!multiline) input.type = field.type === "number" ? "number" : "text";
350
- write = value => {
351
- input.value = field.type === "array" ? JSON.stringify(value ?? []) : (value ?? "");
352
- grow();
353
- };
354
- read = () => {
355
- switch (field.type) {
356
- case "array":
357
- return JSON.parse(input.value);
358
- case "number":
359
- return input.value === "" ? Number.NaN : Number(input.value);
360
- default:
361
- return input.value;
284
+ case field.type === "array" && Boolean(field.options): {
285
+ const page = node("section", "pp-choice-page");
286
+ if (field.description) page.append(node("p", "pp-description", field.description));
287
+ const choices = node("div", "pp-rows");
288
+ page.append(choices);
289
+ inputContainer = choices;
290
+ editors.set(field.key, { node: page, title: match?.[2] ?? field.name });
291
+ const summary = node("span", "pp-summary");
292
+ const link = node("button", "pp-choice-link");
293
+ link.type = "button";
294
+ link.setAttribute("aria-label", field.name);
295
+ link.append(summary, node("span", "pp-chevron", "›"));
296
+ row.append(link);
297
+ const refresh = () => {
298
+ const value = client.snapshot().values[field.key];
299
+ summary.textContent =
300
+ field.options
301
+ .filter(option => Array.isArray(value) && value.includes(option.key))
302
+ .map(option => option.label)
303
+ .join("、") || "未选择";
304
+ };
305
+ summaries.push(refresh);
306
+ refresh();
307
+ link.onclick = () => navigation.open(field.key);
308
+ row.addEventListener("click", event => {
309
+ if (!link.contains(event.target)) link.click();
310
+ });
311
+ const inputs = field.options.map(option => {
312
+ const label = settingRow("label");
313
+ label.classList.add("pp-choice");
314
+ label.textContent = option.label;
315
+ const input = node("input", "");
316
+ input.type = "checkbox";
317
+ input.setAttribute("aria-label", option.label);
318
+ label.append(input);
319
+ choices.append(label);
320
+ return { input, key: option.key };
321
+ });
322
+ read = () => inputs.filter(option => option.input.checked).map(option => option.key);
323
+ write = value => {
324
+ for (const option of inputs) option.input.checked = Array.isArray(value) && value.includes(option.key);
325
+ };
326
+ break;
327
+ }
328
+ case field.type === "boolean": {
329
+ const toggle = node("input", "pp-switch");
330
+ toggle.type = "checkbox";
331
+ toggle.setAttribute("switch", "");
332
+ toggle.setAttribute("role", "switch");
333
+ toggle.setAttribute("aria-label", field.name);
334
+ write = value => {
335
+ toggle.checked = value === true;
336
+ };
337
+ read = () => toggle.checked;
338
+ row.append(toggle);
339
+ break;
340
+ }
341
+ default: {
342
+ const multiline = field.control === "textarea" || field.type === "array";
343
+ const input = node(multiline ? "textarea" : "input", "");
344
+ if (multiline) row.classList.add("pp-multiline");
345
+ input.setAttribute("aria-label", field.name);
346
+ if (field.placeholder) input.placeholder = field.placeholder;
347
+ if (multiline && field.rows) input.rows = field.rows;
348
+ /**
349
+ * 在挂载后根据内容调整高度,同时保留基础行数。
350
+ * Size mounted textareas to their contents while retaining baseline rows.
351
+ * @returns {void} 无返回值 / No return value.
352
+ */
353
+ const grow = () => {
354
+ if (!multiline || !field.autoGrow || !input.isConnected) return;
355
+ input.style.height = "auto";
356
+ const baseline = input.getBoundingClientRect().height;
357
+ const style = window.getComputedStyle(input);
358
+ const borders = Number.parseFloat(style.borderTopWidth) + Number.parseFloat(style.borderBottomWidth);
359
+ input.style.height = `${Math.max(baseline, input.scrollHeight + borders)}px`;
360
+ };
361
+ if (multiline && field.autoGrow) {
362
+ input.addEventListener("input", grow);
363
+ growingInputs.push(grow);
362
364
  }
363
- };
364
- row.append(fieldControl(input));
365
- break;
365
+ eventName = "input";
366
+ if (!multiline) input.type = field.type === "number" ? "number" : "text";
367
+ write = value => {
368
+ input.value = field.type === "array" ? JSON.stringify(value ?? []) : (value ?? "");
369
+ grow();
370
+ };
371
+ read = () => {
372
+ switch (field.type) {
373
+ case "array":
374
+ return JSON.parse(input.value);
375
+ case "number":
376
+ return input.value === "" ? Number.NaN : Number(input.value);
377
+ default:
378
+ return input.value;
379
+ }
380
+ };
381
+ row.append(fieldControl(input));
382
+ break;
383
+ }
366
384
  }
385
+ write(value);
386
+ let inputVersion = 0;
387
+ inputContainer.addEventListener(eventName, event => {
388
+ if (event.isComposing) return;
389
+ const version = ++inputVersion,
390
+ module = active;
391
+ let value;
392
+ try {
393
+ value = read();
394
+ } catch (error) {
395
+ notify({ kind: "error", message: error.message });
396
+ return;
397
+ }
398
+ const restore = () => {
399
+ if (version === inputVersion) write(client.snapshot().values[field.key]);
400
+ };
401
+ perform(
402
+ () => {
403
+ if (!validValue(field, value)) {
404
+ const error = new TypeError("Invalid setting value");
405
+ notify({ kind: "error", operation: "write", module, key: field.key, message: error.message });
406
+ throw error;
407
+ }
408
+ return client.set(field.key, value);
409
+ },
410
+ () => {
411
+ for (const refresh of summaries) refresh();
412
+ },
413
+ restore,
414
+ );
415
+ });
416
+ if (eventName === "input") inputContainer.addEventListener("compositionend", event => event.target.dispatchEvent(new window.Event("input", { bubbles: true })));
417
+ groups.get(group).append(row);
367
418
  }
368
- write(value);
369
- let inputVersion = 0;
370
- inputContainer.addEventListener(eventName, event => {
371
- if (event.isComposing) return;
372
- const version = ++inputVersion,
373
- module = active;
419
+ const settingsPage = node("section", "pp-settings-page");
420
+ const settingsOutput = node("pre", "pp-cache");
421
+ settingsOutput.setAttribute("aria-label", "Settings 内容");
422
+ settingsPage.append(settingsOutput);
423
+ editors.set("$settings", { node: settingsPage, title: "设置" });
424
+ handlers.set("viewSettings", () => {
425
+ if (saving) return;
374
426
  let value;
375
- try {
376
- value = read();
377
- } catch (error) {
378
- notify({ kind: "error", message: error.message });
379
- return;
380
- }
381
- const restore = () => {
382
- if (version === inputVersion) write(client.snapshot().values[field.key]);
383
- };
384
- perform(
427
+ return perform(
428
+ async () => {
429
+ try {
430
+ value = await client.readSettings();
431
+ } catch (error) {
432
+ notify({ kind: "error", message: error.message });
433
+ throw error;
434
+ }
435
+ },
385
436
  () => {
386
- if (!validValue(field, value)) {
387
- const error = new TypeError("Invalid setting value");
388
- notify({ kind: "error", operation: "write", module, key: field.key, message: error.message });
437
+ settingsOutput.textContent = value === undefined ? "暂无设置" : JSON.stringify(value, null, 2);
438
+ navigation.open("$settings");
439
+ },
440
+ );
441
+ });
442
+ const cachePage = node("section", "pp-cache-page");
443
+ const output = node("pre", "pp-cache");
444
+ output.textContent = "暂无缓存";
445
+ output.setAttribute("aria-label", "Caches 内容");
446
+ cachePage.append(output);
447
+ editors.set("$caches", { node: cachePage, title: "缓存" });
448
+ handlers.set("viewCaches", () => {
449
+ if (saving) return;
450
+ let value;
451
+ return perform(
452
+ async () => {
453
+ try {
454
+ value = await client.readCaches();
455
+ } catch (error) {
456
+ notify({ kind: "error", message: error.message });
389
457
  throw error;
390
458
  }
391
- return client.set(field.key, value);
392
459
  },
393
460
  () => {
394
- for (const refresh of summaries) refresh();
461
+ output.textContent = value === undefined ? "暂无缓存" : JSON.stringify(value, null, 2);
462
+ navigation.open("$caches");
395
463
  },
396
- restore,
397
464
  );
398
465
  });
399
- if (eventName === "input") inputContainer.addEventListener("compositionend", event => event.target.dispatchEvent(new window.Event("input", { bubbles: true })));
400
- groups.get(group).append(row);
466
+ handlers.set("clearCaches", async () => {
467
+ if (saving) return;
468
+ if (!(await requestConfirmation(window, `清空 ${active} 的全部 Caches?`)) || destroyed || saving) return;
469
+ return perform(
470
+ () => client.clearCaches(),
471
+ () => {
472
+ output.textContent = "暂无缓存";
473
+ },
474
+ );
475
+ });
476
+ handlers.set("reset", async () => {
477
+ if (saving) return;
478
+ if (!(await requestConfirmation(window, `重置 ${active} 的设置?这将删除该模块的 Settings、Caches 和其它持久化数据。`)) || destroyed || saving) return;
479
+ return perform(() => client.reset(), controls);
480
+ });
481
+ navigation?.destroy();
482
+ navigation = new Navigation(viewport, view, key => editors.get(key)?.node);
483
+ navigation.addEventListener("change", updateNavigation);
484
+ for (const grow of growingInputs) grow();
485
+ updateNavigation();
401
486
  }
402
- const settingsPage = node("section", "pp-settings-page");
403
- const settingsOutput = node("pre", "pp-cache");
404
- settingsOutput.setAttribute("aria-label", "Settings 内容");
405
- settingsPage.append(settingsOutput);
406
- editors.set("$settings", { node: settingsPage, title: "设置" });
407
- handlers.set("viewSettings", () => {
408
- if (saving) return;
409
- let value;
410
- return perform(
411
- async () => {
412
- try {
413
- value = await client.readSettings();
414
- } catch (error) {
415
- notify({ kind: "error", message: error.message });
416
- throw error;
417
- }
418
- },
419
- () => {
420
- settingsOutput.textContent = value === undefined ? "暂无设置" : JSON.stringify(value, null, 2);
421
- navigation.open("$settings");
422
- },
423
- );
424
- });
425
- const cachePage = node("section", "pp-cache-page");
426
- const output = node("pre", "pp-cache");
427
- output.textContent = "暂无缓存";
428
- output.setAttribute("aria-label", "Caches 内容");
429
- cachePage.append(output);
430
- editors.set("$caches", { node: cachePage, title: "缓存" });
431
- handlers.set("viewCaches", () => {
432
- if (saving) return;
433
- let value;
434
- return perform(
435
- async () => {
436
- try {
437
- value = await client.readCaches();
438
- } catch (error) {
439
- notify({ kind: "error", message: error.message });
440
- throw error;
441
- }
442
- },
443
- () => {
444
- output.textContent = value === undefined ? "暂无缓存" : JSON.stringify(value, null, 2);
445
- navigation.open("$caches");
446
- },
447
- );
448
- });
449
- handlers.set("clearCaches", async () => {
450
- if (saving) return;
451
- if (!(await requestConfirmation(window, `清空 ${active} 的全部 Caches?`)) || destroyed || saving) return;
452
- return perform(
453
- () => client.clearCaches(),
454
- () => {
455
- output.textContent = "暂无缓存";
456
- },
457
- );
458
- });
459
- handlers.set("reset", async () => {
460
- if (saving) return;
461
- if (!(await requestConfirmation(window, `重置 ${active} 的设置?这将删除该模块的 Settings、Caches 和其它持久化数据。`)) || destroyed || saving) return;
462
- return perform(() => client.reset(), controls);
463
- });
464
- navigation?.destroy();
465
- navigation = new Navigation(viewport, view, key => editors.get(key)?.node);
466
- navigation.addEventListener("change", updateNavigation);
467
- for (const grow of growingInputs) grow();
468
- updateNavigation();
469
- }
470
- /**
471
- * 已加载的表单交由导航组件返回;加载阶段可以返回先前文档。
472
- * Loaded forms delegate back to navigation; loading views can return to the previous document.
473
- * @returns {void} 无返回值 / No return value.
474
- */
475
- back.onclick = () => {
476
- if (saving) return;
477
- if (navigation) navigation.back();
478
- else window.history.back();
479
- };
480
- open(definition.module);
481
- return {
482
487
  /**
483
- * 移除监听器、定时器、会话和挂载内容。
484
- * Remove listeners, timers, session and mounted content.
488
+ * 已加载的表单交由导航组件返回;加载阶段可以返回先前文档。
489
+ * Loaded forms delegate back to navigation; loading views can return to the previous document.
485
490
  * @returns {void} 无返回值 / No return value.
486
491
  */
487
- destroy() {
492
+ back.onclick = () => {
493
+ if (saving) return;
494
+ if (navigation) navigation.back();
495
+ else window.history.back();
496
+ };
497
+ open(definition.module);
498
+ return () => {
488
499
  destroyed = true;
489
500
  menu.destroy();
490
501
  window.frameElement?.removeEventListener("preferencepanes:action", onAction);
@@ -493,6 +504,15 @@ export function mountPanel(root, model) {
493
504
  if (active && !saving) client.leave();
494
505
  clearTimeout(timer);
495
506
  shell.remove();
496
- },
497
- };
507
+ };
508
+ }
509
+
510
+ /**
511
+ * 移除监听器、定时器、会话和挂载内容。
512
+ * Remove listeners, timers, session, and mounted content.
513
+ * @returns {void} 无返回值 / No return value.
514
+ */
515
+ destroy() {
516
+ this.#release();
517
+ }
498
518
  }