@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,21 +1,3 @@
1
- /**
2
- * 统一解析模块页的资源地址:Header 优先于查询参数,再使用模块约定。
3
- * Resolve module resource locations: headers override query parameters and module conventions.
4
- * @param {URL} url 已解析的页面请求地址 / Parsed page request URL.
5
- * @param {Record<string, string | undefined>} [headers] 请求头,名称不区分大小写 / Case-insensitive request headers.
6
- * @returns {{url: string, module: string, json: string, css: string}} 页面上下文与两个资源输入 / Page context and two resource inputs.
7
- */
8
- function pageInputs(url, headers = {}) {
9
- const match = /^\/settings\/([a-zA-Z0-9_-]+)\/?$/.exec(url.pathname);
10
- if (!match) throw new TypeError("Open a concrete module URL");
11
- const module = match[1];
12
- const values = Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
13
- const json = values["x-preferencepanes-json"] ?? url.searchParams.get("json") ?? `/configs/${module}`;
14
- const css = values["x-preferencepanes-css"] ?? url.searchParams.get("css") ?? "";
15
- if (!json.trim()) throw new TypeError("JSON resource URL is required");
16
- return { url: url.href, module, json, css };
17
- }
18
-
19
1
  /**
20
2
  * 创建元素,所有展示文本通过 textContent 写入。
21
3
  * Create elements and assign display text through textContent only.
@@ -154,8 +136,8 @@ function normalizeBoxJs(config, module) {
154
136
  target.owners.add(app);
155
137
  }
156
138
  }
157
- if (module === undefined && modules.size !== 1) throw new TypeError("Import BoxJS JSON for exactly one module");
158
- const target = module === undefined ? modules.values().next().value : modules.get(module);
139
+ if (modules.size !== 1) throw new TypeError("Import BoxJS JSON for exactly one module");
140
+ const target = modules.values().next().value ;
159
141
  if (!target) throw new TypeError(`No BoxJS settings for module: ${module}`);
160
142
  const metadata = normalizeMetadata(target.owners.size === 1 ? presentation([...target.owners][0]) : {});
161
143
  const fields = [];
@@ -441,16 +423,133 @@ class ActionMenu {
441
423
  }
442
424
 
443
425
  /**
444
- * 创建单模块页面客户端;只调用模块 API,不读取或解析 BoxJS。
445
- * Create a single-module page client that only calls the module API and never reads or parses BoxJS.
446
- * @param {import("./client.mjs").PreferencesClientOptions} options API 模型、请求与通知 / API model, requests and notifications.
447
- * @returns {import("./client.mjs").PreferencesClient} 页面客户端 / Page client.
426
+ * 管理单模块页面的 API 请求、值快照和会话终止。
427
+ * Manage API requests, value snapshots, and session termination for one module page.
448
428
  */
449
- function createPreferencesClient({ model, definition, fetch: request = globalThis.fetch.bind(globalThis), notify = () => {}, timeout = 10000 }) {
450
- const { module, configURL } = model;
451
- const session = new AbortController();
452
- const values = structuredClone(model.values);
453
- let saving = false;
429
+ class PreferencesClient {
430
+ #module;
431
+ #definition;
432
+ #request;
433
+ #notify;
434
+ #timeout;
435
+ #session = new AbortController();
436
+ #values = {};
437
+ #saving = false;
438
+
439
+ /**
440
+ * 创建从 BoxJS 定义读取和持久化设置的页面客户端。
441
+ * Create a page client that reads and persists settings from a BoxJS definition.
442
+ * @param {import("./client.mjs").PreferencesClientOptions} options 字段定义、请求与通知 / Field definition, requests, and notifications.
443
+ */
444
+ constructor({ definition, fetch: request = globalThis.fetch.bind(globalThis), notify = () => {}, timeout = 10000 }) {
445
+ this.#module = definition.module;
446
+ this.#definition = definition;
447
+ this.#request = request;
448
+ this.#notify = notify;
449
+ this.#timeout = timeout;
450
+ }
451
+
452
+ /**
453
+ * 读取一次 Settings 子树并建立页面值快照。
454
+ * Read the Settings subtree once and establish the page value snapshot.
455
+ * @returns {Promise<import("./client.mjs").ModuleSnapshot>} 页面快照 / Page snapshot.
456
+ */
457
+ async open() {
458
+ let subtree = await this.readSettings();
459
+ if (subtree === undefined) subtree = {};
460
+ if (typeof subtree === "string") subtree = JSON.parse(subtree);
461
+ if (!subtree || typeof subtree !== "object" || Array.isArray(subtree)) throw new TypeError("Expected a settings subtree object");
462
+ const values = {};
463
+ for (const field of this.#definition.fields) {
464
+ const stored = field.key
465
+ .split(".")
466
+ .slice(this.#definition.settingsPath.length)
467
+ .reduce((parent, part) => Object(parent)[part], subtree);
468
+ const value = normalizeStoredValue(field, stored === undefined ? field.defaultValue : stored);
469
+ if (value === undefined) continue;
470
+ if (!validValue(field, value)) throw new TypeError(`Invalid stored value: ${field.key}`);
471
+ values[field.key] = value;
472
+ }
473
+ this.#values = values;
474
+ return this.snapshot();
475
+ }
476
+
477
+ /**
478
+ * 获取当前字段定义和值的深拷贝,不发起网络请求。
479
+ * Return a deep copy of the current field definition and values without a network request.
480
+ * @returns {import("./client.mjs").ModuleSnapshot} 会话快照 / Session snapshot.
481
+ */
482
+ snapshot() {
483
+ return structuredClone({ definition: this.#definition, values: this.#values });
484
+ }
485
+
486
+ /**
487
+ * 读取 Settings 子树。
488
+ * Read the Settings subtree.
489
+ * @returns {Promise<unknown>} Settings 内容或 undefined / Settings content or undefined.
490
+ */
491
+ async readSettings() {
492
+ const response = await this.#send("get", { scope: "settings" });
493
+ return response.status === 404 ? undefined : response.json();
494
+ }
495
+
496
+ /**
497
+ * 读取 Caches 子树。
498
+ * Read the Caches subtree.
499
+ * @returns {Promise<unknown>} Caches 内容或 undefined / Caches content or undefined.
500
+ */
501
+ async readCaches() {
502
+ const response = await this.#send("get", { scope: "caches" });
503
+ return response.status === 404 ? undefined : response.json();
504
+ }
505
+
506
+ /**
507
+ * 删除当前模块的 Caches 子树。
508
+ * Delete the current module Caches subtree.
509
+ * @returns {Promise<void>} 操作完成 / Operation completion.
510
+ */
511
+ clearCaches() {
512
+ return this.#change("delete", { scope: "caches" }, "clearCaches");
513
+ }
514
+
515
+ /**
516
+ * 删除当前模块数据并恢复页面默认值。
517
+ * Delete current module data and restore page defaults.
518
+ * @returns {Promise<void>} 操作完成 / Operation completion.
519
+ */
520
+ reset() {
521
+ return this.#change("delete", { scope: "module" }, "reset");
522
+ }
523
+
524
+ /**
525
+ * 终止当前页面仍在进行的请求。
526
+ * Abort requests still owned by the current page.
527
+ * @returns {void} 无返回值 / No return value.
528
+ */
529
+ leave() {
530
+ this.#session.abort();
531
+ }
532
+
533
+ /**
534
+ * 写入单个字段。
535
+ * Write one field.
536
+ * @param {string} key 字段路径 / Field path.
537
+ * @param {unknown} value 已校验值 / Validated value.
538
+ * @returns {Promise<void>} 操作完成 / Operation completion.
539
+ */
540
+ set(key, value) {
541
+ return this.#change("set", { key, value }, "write", key);
542
+ }
543
+
544
+ /**
545
+ * 删除单个字段覆盖值。
546
+ * Delete one field override.
547
+ * @param {string} key 字段路径 / Field path.
548
+ * @returns {Promise<void>} 操作完成 / Operation completion.
549
+ */
550
+ remove(key) {
551
+ return this.#change("delete", { key }, "delete", key);
552
+ }
454
553
 
455
554
  /**
456
555
  * 向模块 API 发送 JSON 动作。
@@ -459,26 +558,26 @@ function createPreferencesClient({ model, definition, fetch: request = globalThi
459
558
  * @param {unknown} payload JSON 请求体 / JSON request body.
460
559
  * @returns {Promise<Response>} 原始响应 / Raw response.
461
560
  */
462
- async function send(action, payload) {
561
+ async #send(action, payload) {
463
562
  const controller = new AbortController();
464
563
  const abort = () => controller.abort();
465
- if (session.signal.aborted) abort();
466
- session.signal.addEventListener("abort", abort, { once: true });
467
- const timer = setTimeout(abort, timeout);
564
+ if (this.#session.signal.aborted) abort();
565
+ this.#session.signal.addEventListener("abort", abort, { once: true });
566
+ const timer = setTimeout(abort, this.#timeout);
468
567
  try {
469
- const response = await request(`/api/${encodeURIComponent(module)}/${action}`, {
568
+ const response = await this.#request(`/api/${encodeURIComponent(this.#module)}/${action}`, {
470
569
  method: "POST",
471
570
  credentials: "omit",
472
571
  cache: "no-store",
473
572
  signal: controller.signal,
474
- headers: { "Content-Type": "application/json", "X-PreferencePanes-JSON": configURL },
573
+ headers: { "Content-Type": "application/json" },
475
574
  body: JSON.stringify(payload),
476
575
  });
477
576
  if (response.status !== 200 && !(action === "get" && response.status === 404)) throw new Error(`HTTP ${response.status}`);
478
577
  return response;
479
578
  } finally {
480
579
  clearTimeout(timer);
481
- session.signal.removeEventListener("abort", abort);
580
+ this.#session.signal.removeEventListener("abort", abort);
482
581
  }
483
582
  }
484
583
 
@@ -486,60 +585,47 @@ function createPreferencesClient({ model, definition, fetch: request = globalThi
486
585
  * 执行写入动作;成功后只更新当前页面值。
487
586
  * Execute a mutation and update only the current page values after success.
488
587
  * @param {"set" | "delete"} action API 动作 / API action.
489
- * @param {unknown} payload JSON 请求体 / JSON request body.
588
+ * @param {Record<string, unknown>} payload JSON 请求体 / JSON request body.
490
589
  * @param {"write" | "delete" | "clearCaches" | "reset"} operation 通知操作 / Notification operation.
491
590
  * @param {string} [key] 字段路径 / Field path.
492
591
  * @returns {Promise<void>} 操作完成 / Operation completion.
493
592
  */
494
- async function change(action, payload, operation, key) {
495
- if (saving) throw new Error("A settings write is already in progress");
496
- saving = true;
593
+ async #change(action, payload, operation, key) {
594
+ if (this.#saving) throw new Error("A settings write is already in progress");
595
+ this.#saving = true;
497
596
  try {
498
- await send(action, payload);
597
+ if (operation === "write") {
598
+ const field = this.#definition.fields.find(candidate => candidate.key === key);
599
+ if (!field || !validValue(field, payload.value)) throw new TypeError("Invalid setting value");
600
+ }
601
+ await this.#send(action, payload);
499
602
  switch (operation) {
500
603
  case "write":
501
- values[key] = structuredClone(payload.value);
604
+ this.#values[key] = structuredClone(payload.value);
502
605
  break;
503
606
  case "delete": {
504
- const field = definition.fields.find(candidate => candidate.key === key);
505
- delete values[key];
506
- if (field && Object.hasOwn(field, "defaultValue")) values[key] = structuredClone(field.defaultValue);
607
+ const field = this.#definition.fields.find(candidate => candidate.key === key);
608
+ delete this.#values[key];
609
+ if (field && Object.hasOwn(field, "defaultValue")) this.#values[key] = structuredClone(field.defaultValue);
507
610
  break;
508
611
  }
509
612
  case "clearCaches":
510
613
  break;
511
614
  case "reset":
512
- for (const field of definition.fields) {
513
- delete values[field.key];
514
- if (Object.hasOwn(field, "defaultValue")) values[field.key] = structuredClone(field.defaultValue);
615
+ for (const field of this.#definition.fields) {
616
+ delete this.#values[field.key];
617
+ if (Object.hasOwn(field, "defaultValue")) this.#values[field.key] = structuredClone(field.defaultValue);
515
618
  }
516
619
  break;
517
620
  }
518
- notify({ kind: "success", operation, module, key });
621
+ this.#notify({ kind: "success", operation, module: this.#module, key });
519
622
  } catch (error) {
520
- notify({ kind: "error", operation, module, key, message: error.message });
623
+ this.#notify({ kind: "error", operation, module: this.#module, key, message: error.message });
521
624
  throw error;
522
625
  } finally {
523
- saving = false;
626
+ this.#saving = false;
524
627
  }
525
628
  }
526
-
527
- return {
528
- snapshot: () => structuredClone({ definition, values }),
529
- async readSettings() {
530
- const response = await send("get", { scope: "settings" });
531
- return response.status === 404 ? undefined : response.json();
532
- },
533
- async readCaches() {
534
- const response = await send("get", { scope: "caches" });
535
- return response.status === 404 ? undefined : response.json();
536
- },
537
- clearCaches: () => change("delete", { scope: "caches" }, "clearCaches"),
538
- reset: () => change("delete", { scope: "module" }, "reset"),
539
- leave: () => session.abort(),
540
- set: (key, value) => change("set", { key, value }, "write", key),
541
- remove: key => change("delete", { key }, "delete", key),
542
- };
543
629
  }
544
630
 
545
631
  /**
@@ -702,485 +788,496 @@ class Navigation extends EventTarget {
702
788
  }
703
789
 
704
790
  /**
705
- * 挂载 API 返回的模块模型表单和短暂通知。
706
- * Mount the module model returned by the API and transient notifications.
707
- * @param {HTMLElement} root 包内挂载元素 / Internal mount element.
708
- * @param {import("../index.js").ModuleModel} model API 返回的模块模型 / Module model returned by the API.
709
- * @returns {import("./index.js").MountedPreferences} 面板生命周期句柄 / Panel lifecycle handle.
791
+ * 管理模块表单、导航、操作队列和短暂通知。
792
+ * Manage the module form, navigation, operation queue, and transient notifications.
710
793
  */
711
- function mountPanel(root, model) {
712
- const { definition } = model;
713
- const title = definition.metadata?.name ?? definition.module;
714
- const document = root.ownerDocument;
715
- const window = document.defaultView;
716
- const shell = element("div", "pp-panel");
717
- shell.dataset.module = definition.module;
718
- const header = element("header", "pp-header");
719
- const back = element("button", "pp-back", "‹");
720
- back.setAttribute("aria-label", "返回");
721
- back.type = "button";
722
- const heading = element("h1", "pp-title", title);
723
- const handlers = new Map();
724
- const menuItems = [
725
- { id: "viewSettings", label: "查看设置" },
726
- { id: "viewCaches", label: "查看缓存" },
727
- { id: "clearCaches", label: "清空缓存", destructive: true },
728
- { id: "reset", label: "重置设置", destructive: true },
729
- ];
730
- const menu = new ActionMenu(id => runAction(id));
731
- const trailing = element("span", "pp-nav-spacer");
732
- trailing.append(menu.element);
733
- const viewport = element("div", "pp-viewport");
734
- let toast;
735
- header.append(back, heading, trailing);
736
- shell.append(header, viewport);
737
- root.append(shell);
738
- // 嵌入模式向宿主发布导航状态,宿主不读取或修改模块内部 DOM。
739
- // Embedded mode publishes navigation state without host reads or mutations of the module DOM.
740
- const publishNavigation = () => {
741
- const actions = handlers.size ? menuItems : [];
742
- menu.update(actions, saving);
743
- const frame = window.frameElement;
744
- if (!frame?.dataset.preferencePanes) return;
745
- frame.dispatchEvent(
746
- new frame.ownerDocument.defaultView.CustomEvent("preferencepanes:change", {
747
- detail: { title: heading.textContent, module: definition.module, busy: saving, canGoBack: !back.disabled, actions },
748
- }),
749
- );
750
- };
751
- const onAction = event => {
752
- if (!saving && handlers.has(event.detail)) runAction(event.detail);
753
- };
754
- window.frameElement?.addEventListener("preferencepanes:action", onAction);
755
- let timer,
756
- navigation,
757
- generation = 0,
758
- active = null,
759
- saving = false,
760
- destroyed = false;
761
- /**
762
- * 展示短暂通知,不刷新设置数据。
763
- * Display a transient notification without refreshing settings.
764
- * @param {{kind: "success" | "error", operation?: "write" | "delete" | "clearCaches" | "reset", message?: string}} event 操作结果 / Operation result.
765
- * @returns {void} 无返回值 / No return value.
766
- */
767
- const notify = event => {
768
- if (destroyed) return;
769
- let message;
770
- switch (true) {
771
- case event.kind === "error":
772
- message = `操作失败:${event.message}`;
773
- break;
774
- case event.operation === "delete":
775
- message = "删除成功";
776
- break;
777
- case event.operation === "clearCaches":
778
- message = "Caches 已清空";
779
- break;
780
- case event.operation === "reset":
781
- message = "设置已重置";
782
- break;
783
- default:
784
- message = "修改成功";
785
- break;
786
- }
787
- // 宿主接管时不创建网页 Toast,也不运行其计时器。
788
- // A host-owned notice creates no web Toast and starts no local timer.
789
- const frame = window.frameElement;
790
- if (frame && !frame.dispatchEvent(new frame.ownerDocument.defaultView.CustomEvent("preferencepanes:notice", { cancelable: true, detail: { kind: event.kind, message } }))) return;
791
- if (!toast) {
792
- toast = element("div", "pp-toast");
793
- toast.setAttribute("role", "status");
794
- shell.append(toast);
795
- }
796
- toast.textContent = message;
797
- toast.dataset.kind = event.kind;
798
- toast.hidden = false;
799
- clearTimeout(timer);
800
- timer = setTimeout(() => {
801
- toast.hidden = true;
802
- }, 2400);
803
- };
804
- const client = createPreferencesClient({ model, definition, notify });
794
+ class PreferencesPanel {
795
+ #release;
796
+
805
797
  /**
806
- * 两种菜单入口共用异步错误处理,包含宿主确认框错误。
807
- * Share async error handling between both menus, including host-dialog errors.
808
- * @param {string} id 操作标识 / Action identifier.
809
- * @returns {Promise<void>} 操作已处理 / Action handled.
798
+ * 挂载 BoxJS 定义对应的模块表单。
799
+ * Mount the module form described by a BoxJS definition.
800
+ * @param {HTMLElement} root 包内挂载元素 / Internal mount element.
801
+ * @param {import("../index.js").ModuleDefinition} definition 已规范化字段定义 / Normalized field definition.
810
802
  */
811
- async function runAction(id) {
812
- try {
813
- await handlers.get(id)();
814
- } catch (error) {
815
- notify({ kind: "error", message: error.message });
816
- }
817
- }
818
- /**
819
- * 打开模块并忽略已过期的异步结果。
820
- * Open a module and ignore stale asynchronous results.
821
- * @param {string} module 模块标识 / Module identifier.
822
- * @returns {Promise<void>} 视图加载完成,失败显示错误视图 / View load completion; failures display an error view.
823
- */
824
- async function open(module) {
825
- const version = ++generation;
826
- active = module;
827
- back.disabled = window.history.length <= 1;
828
- heading.textContent = module;
829
- publishNavigation();
830
- viewport.replaceChildren(statusView("读取设置…"));
831
- try {
832
- if (version === generation) controls();
833
- } catch (error) {
834
- if (version !== generation) return;
835
- viewport.replaceChildren(statusView(`加载失败:${error.message}`, () => open(module)));
836
- publishNavigation();
837
- }
803
+ constructor(root, definition) {
804
+ this.#release = this.#mount(root, definition);
838
805
  }
806
+
839
807
  /**
840
- * 从会话快照创建控件与操作按钮,不重新读取网络配置。
841
- * Build controls and actions from the session snapshot without fetching config again.
842
- * @returns {void} 无返回值 / No return value.
808
+ * 建立面板 DOM、交互和会话,并返回其释放操作。
809
+ * Build panel DOM, interactions, and session, then return its release operation.
810
+ * @param {HTMLElement} root 包内挂载元素 / Internal mount element.
811
+ * @param {import("../index.js").ModuleDefinition} definition 已规范化字段定义 / Normalized field definition.
812
+ * @returns {() => void} 释放操作 / Release operation.
843
813
  */
844
- function controls() {
845
- const { definition, values } = client.snapshot();
846
- heading.textContent = definition.metadata?.name || active;
847
- const view = element("section", "pp-fields");
848
- /**
849
- * 挂载后执行的多行高度更新
850
- * Textarea sizing callbacks run after mounting.
851
- * @type {Array<() => void>}
852
- */
853
- const growingInputs = [];
854
- const editors = new Map();
855
- const summaries = [];
856
- const groups = new Map();
857
- let queue = Promise.resolve(),
858
- pendingWrites = 0;
814
+ #mount(root, definition) {
815
+ const title = definition.metadata?.name ?? definition.module;
816
+ const document = root.ownerDocument;
817
+ const window = document.defaultView;
818
+ const shell = element("div", "pp-panel");
819
+ shell.dataset.module = definition.module;
820
+ const header = element("header", "pp-header");
821
+ const back = element("button", "pp-back", "‹");
822
+ back.setAttribute("aria-label", "返回");
823
+ back.type = "button";
824
+ const heading = element("h1", "pp-title", title);
825
+ const handlers = new Map();
826
+ const menuItems = [
827
+ { id: "viewSettings", label: "查看设置" },
828
+ { id: "viewCaches", label: "查看缓存" },
829
+ { id: "clearCaches", label: "清空缓存", destructive: true },
830
+ { id: "reset", label: "重置设置", destructive: true },
831
+ ];
832
+ const menu = new ActionMenu(id => runAction(id));
833
+ const trailing = element("span", "pp-nav-spacer");
834
+ trailing.append(menu.element);
835
+ const viewport = element("div", "pp-viewport");
836
+ let toast;
837
+ header.append(back, heading, trailing);
838
+ shell.append(header, viewport);
839
+ root.append(shell);
840
+ // 嵌入模式向宿主发布导航状态,宿主不读取或修改模块内部 DOM。
841
+ // Embedded mode publishes navigation state without host reads or mutations of the module DOM.
842
+ const publishNavigation = () => {
843
+ const actions = handlers.size ? menuItems : [];
844
+ menu.update(actions, saving);
845
+ const frame = window.frameElement;
846
+ if (!frame?.dataset.preferencePanes) return;
847
+ frame.dispatchEvent(
848
+ new frame.ownerDocument.defaultView.CustomEvent("preferencepanes:change", {
849
+ detail: { title: heading.textContent, module: definition.module, busy: saving, canGoBack: !back.disabled, actions },
850
+ }),
851
+ );
852
+ };
853
+ const onAction = event => {
854
+ if (!saving && handlers.has(event.detail)) runAction(event.detail);
855
+ };
856
+ window.frameElement?.addEventListener("preferencepanes:action", onAction);
857
+ let timer,
858
+ navigation,
859
+ generation = 0,
860
+ active = null,
861
+ saving = false,
862
+ destroyed = false;
859
863
  /**
860
- * 导航组件处理页面切换,表单只更新当前标题与返回按钮。
861
- * Let navigation own transitions; the form only updates the title and back button.
864
+ * 展示短暂通知,不刷新设置数据。
865
+ * Display a transient notification without refreshing settings.
866
+ * @param {{kind: "success" | "error", operation?: "write" | "delete" | "clearCaches" | "reset", message?: string}} event 操作结果 / Operation result.
862
867
  * @returns {void} 无返回值 / No return value.
863
868
  */
864
- const updateNavigation = () => {
865
- const editor = editors.get(navigation.current);
866
- heading.textContent = editor?.title ?? definition.metadata?.name ?? active;
867
- back.disabled = saving || !navigation.canGoBack;
868
- publishNavigation();
869
+ const notify = event => {
870
+ if (destroyed) return;
871
+ let message;
872
+ switch (true) {
873
+ case event.kind === "error":
874
+ message = `操作失败:${event.message}`;
875
+ break;
876
+ case event.operation === "delete":
877
+ message = "删除成功";
878
+ break;
879
+ case event.operation === "clearCaches":
880
+ message = "Caches 已清空";
881
+ break;
882
+ case event.operation === "reset":
883
+ message = "设置已重置";
884
+ break;
885
+ default:
886
+ message = "修改成功";
887
+ break;
888
+ }
889
+ // 宿主接管时不创建网页 Toast,也不运行其计时器。
890
+ // A host-owned notice creates no web Toast and starts no local timer.
891
+ const frame = window.frameElement;
892
+ if (frame && !frame.dispatchEvent(new frame.ownerDocument.defaultView.CustomEvent("preferencepanes:notice", { cancelable: true, detail: { kind: event.kind, message } }))) return;
893
+ if (!toast) {
894
+ toast = element("div", "pp-toast");
895
+ toast.setAttribute("role", "status");
896
+ shell.append(toast);
897
+ }
898
+ toast.textContent = message;
899
+ toast.dataset.kind = event.kind;
900
+ toast.hidden = false;
901
+ clearTimeout(timer);
902
+ timer = setTimeout(() => {
903
+ toast.hidden = true;
904
+ }, 2400);
869
905
  };
906
+ const client = new PreferencesClient({ definition, notify });
870
907
  /**
871
- * 串行执行模块操作,保持输入可编辑。
872
- * Serialize module actions while keeping inputs editable.
873
- * @param {() => Promise<void>} action 请求或写入 / Request or mutation.
874
- * @param {() => void} success 成功后的局部更新 / Local update after success.
875
- * @param {() => void} [failure] 失败后恢复当前输入 / Restore the current input on failure.
876
- * @returns {Promise<void>} 操作完成 / Operation completion.
908
+ * 两种菜单入口共用异步错误处理,包含宿主确认框错误。
909
+ * Share async error handling between both menus, including host-dialog errors.
910
+ * @param {string} id 操作标识 / Action identifier.
911
+ * @returns {Promise<void>} 操作已处理 / Action handled.
877
912
  */
878
- function perform(action, success, failure = () => {}) {
879
- pendingWrites++;
880
- saving = true;
881
- back.disabled = true;
882
- publishNavigation();
883
- queue = queue
884
- .then(action)
885
- .then(() => {
886
- if (!destroyed) success();
887
- })
888
- .catch(() => {
889
- /* 请求层已通知错误。
890
- * The request layer has already reported the error. */
891
- if (!destroyed) failure();
892
- })
893
- .finally(() => {
894
- pendingWrites--;
895
- saving = pendingWrites > 0;
896
- if (destroyed && !saving) client.leave();
897
- back.disabled = saving || !navigation.canGoBack;
898
- publishNavigation();
899
- });
900
- return queue;
901
- }
902
- const metadata = definition.metadata;
903
- if (metadata) {
904
- const info = element("div", "pp-module-info");
905
- const details = element("div", "pp-module-details");
906
- for (const description of [metadata.author, metadata.desc ?? metadata.description, ...(metadata.descs ?? [])]) if (description) details.append(element("p", "pp-description", description));
907
- if (metadata.repo) {
908
- const link = element("a", "pp-module-source", "项目主页");
909
- link.href = resourceURL(metadata.repo);
910
- link.target = "_blank";
911
- link.rel = "noopener noreferrer";
912
- details.append(link);
913
+ async function runAction(id) {
914
+ try {
915
+ await handlers.get(id)();
916
+ } catch (error) {
917
+ notify({ kind: "error", message: error.message });
913
918
  }
914
- info.append(details);
915
- view.append(info);
916
919
  }
917
- for (const field of definition.fields) {
918
- const match = /^\[([^\]]+)\]\s*(.*)$/.exec(field.name);
919
- const group = match?.[1] ?? "通用";
920
- if (!groups.has(group)) {
921
- const section = element("section", "pp-group");
922
- const rows = element("div", "pp-rows");
923
- section.append(element("h2", "pp-group-title", group), rows);
924
- groups.set(group, rows);
925
- view.append(section);
920
+ /**
921
+ * 打开模块并忽略已过期的异步结果。
922
+ * Open a module and ignore stale asynchronous results.
923
+ * @param {string} module 模块标识 / Module identifier.
924
+ * @returns {Promise<void>} 视图加载完成,失败显示错误视图 / View load completion; failures display an error view.
925
+ */
926
+ async function open(module) {
927
+ const version = ++generation;
928
+ active = module;
929
+ back.disabled = window.history.length <= 1;
930
+ heading.textContent = module;
931
+ publishNavigation();
932
+ viewport.replaceChildren(statusView("读取设置…"));
933
+ try {
934
+ await client.open();
935
+ if (version === generation) controls();
936
+ } catch (error) {
937
+ if (version !== generation) return;
938
+ viewport.replaceChildren(statusView(`加载失败:${error.message}`, () => open(module)));
939
+ publishNavigation();
926
940
  }
927
- const row = settingRow("div");
928
- row.classList.add("pp-field");
929
- const label = element("div", "pp-label");
930
- label.append(element("span", "pp-field-name", match?.[2] ?? field.name));
931
- if (field.description) label.append(element("span", "pp-field-description", field.description));
932
- row.append(label);
933
- const value = values[field.key];
941
+ }
942
+ /**
943
+ * 从会话快照创建控件与操作按钮,不重新读取网络配置。
944
+ * Build controls and actions from the session snapshot without fetching config again.
945
+ * @returns {void} 无返回值 / No return value.
946
+ */
947
+ function controls() {
948
+ const { definition, values } = client.snapshot();
949
+ heading.textContent = definition.metadata?.name || active;
950
+ const view = element("section", "pp-fields");
934
951
  /**
935
- * 读取尚未保存的输入
936
- * Read the unsaved input.
937
- * @type {() => unknown}
952
+ * 挂载后执行的多行高度更新
953
+ * Textarea sizing callbacks run after mounting.
954
+ * @type {Array<() => void>}
938
955
  */
939
- let read;
956
+ const growingInputs = [];
957
+ const editors = new Map();
958
+ const summaries = [];
959
+ const groups = new Map();
960
+ let queue = Promise.resolve(),
961
+ pendingWrites = 0;
940
962
  /**
941
- * 更新当前控件
942
- * Update the current control.
943
- * @type {(value: unknown) => void}
963
+ * 导航组件处理页面切换,表单只更新当前标题与返回按钮。
964
+ * Let navigation own transitions; the form only updates the title and back button.
965
+ * @returns {void} 无返回值 / No return value.
944
966
  */
945
- let write;
946
- let inputContainer = row;
947
- let eventName = "change";
948
- switch (true) {
949
- case Boolean(field.options) && field.type !== "array": {
950
- const select = element("select", "");
951
- select.setAttribute("aria-label", field.name);
952
- field.options.forEach((option, index) => {
953
- const item = element("option", "", option.label);
954
- item.value = String(index);
955
- select.append(item);
956
- });
957
- write = value => {
958
- select.selectedIndex = field.options.findIndex(option => option.key === value);
959
- };
960
- row.append(fieldControl(select));
961
- read = () => field.options[select.selectedIndex]?.key;
962
- break;
963
- }
964
- case field.type === "array" && Boolean(field.options): {
965
- const page = element("section", "pp-choice-page");
966
- if (field.description) page.append(element("p", "pp-description", field.description));
967
- const choices = element("div", "pp-rows");
968
- page.append(choices);
969
- inputContainer = choices;
970
- editors.set(field.key, { node: page, title: match?.[2] ?? field.name });
971
- const summary = element("span", "pp-summary");
972
- const link = element("button", "pp-choice-link");
973
- link.type = "button";
974
- link.setAttribute("aria-label", field.name);
975
- link.append(summary, element("span", "pp-chevron", "›"));
976
- row.append(link);
977
- const refresh = () => {
978
- const value = client.snapshot().values[field.key];
979
- summary.textContent =
980
- field.options
981
- .filter(option => Array.isArray(value) && value.includes(option.key))
982
- .map(option => option.label)
983
- .join("、") || "未选择";
984
- };
985
- summaries.push(refresh);
986
- refresh();
987
- link.onclick = () => navigation.open(field.key);
988
- row.addEventListener("click", event => {
989
- if (!link.contains(event.target)) link.click();
990
- });
991
- const inputs = field.options.map(option => {
992
- const label = settingRow("label");
993
- label.classList.add("pp-choice");
994
- label.textContent = option.label;
995
- const input = element("input", "");
996
- input.type = "checkbox";
997
- input.setAttribute("aria-label", option.label);
998
- label.append(input);
999
- choices.append(label);
1000
- return { input, key: option.key };
967
+ const updateNavigation = () => {
968
+ const editor = editors.get(navigation.current);
969
+ heading.textContent = editor?.title ?? definition.metadata?.name ?? active;
970
+ back.disabled = saving || !navigation.canGoBack;
971
+ publishNavigation();
972
+ };
973
+ /**
974
+ * 串行执行模块操作,保持输入可编辑。
975
+ * Serialize module actions while keeping inputs editable.
976
+ * @param {() => Promise<void>} action 请求或写入 / Request or mutation.
977
+ * @param {() => void} success 成功后的局部更新 / Local update after success.
978
+ * @param {() => void} [failure] 失败后恢复当前输入 / Restore the current input on failure.
979
+ * @returns {Promise<void>} 操作完成 / Operation completion.
980
+ */
981
+ function perform(action, success, failure = () => {}) {
982
+ pendingWrites++;
983
+ saving = true;
984
+ back.disabled = true;
985
+ publishNavigation();
986
+ queue = queue
987
+ .then(action)
988
+ .then(() => {
989
+ if (!destroyed) success();
990
+ })
991
+ .catch(() => {
992
+ /* 请求层已通知错误。
993
+ * The request layer has already reported the error. */
994
+ if (!destroyed) failure();
995
+ })
996
+ .finally(() => {
997
+ pendingWrites--;
998
+ saving = pendingWrites > 0;
999
+ if (destroyed && !saving) client.leave();
1000
+ back.disabled = saving || !navigation.canGoBack;
1001
+ publishNavigation();
1001
1002
  });
1002
- read = () => inputs.filter(option => option.input.checked).map(option => option.key);
1003
- write = value => {
1004
- for (const option of inputs) option.input.checked = Array.isArray(value) && value.includes(option.key);
1005
- };
1006
- break;
1003
+ return queue;
1004
+ }
1005
+ const metadata = definition.metadata;
1006
+ if (metadata) {
1007
+ const info = element("div", "pp-module-info");
1008
+ const details = element("div", "pp-module-details");
1009
+ for (const description of [metadata.author, metadata.desc ?? metadata.description, ...(metadata.descs ?? [])]) if (description) details.append(element("p", "pp-description", description));
1010
+ if (metadata.repo) {
1011
+ const link = element("a", "pp-module-source", "项目主页");
1012
+ link.href = resourceURL(metadata.repo);
1013
+ link.target = "_blank";
1014
+ link.rel = "noopener noreferrer";
1015
+ details.append(link);
1007
1016
  }
1008
- case field.type === "boolean": {
1009
- const toggle = element("input", "pp-switch");
1010
- toggle.type = "checkbox";
1011
- toggle.setAttribute("switch", "");
1012
- toggle.setAttribute("role", "switch");
1013
- toggle.setAttribute("aria-label", field.name);
1014
- write = value => {
1015
- toggle.checked = value === true;
1016
- };
1017
- read = () => toggle.checked;
1018
- row.append(toggle);
1019
- break;
1017
+ info.append(details);
1018
+ view.append(info);
1019
+ }
1020
+ for (const field of definition.fields) {
1021
+ const match = /^\[([^\]]+)\]\s*(.*)$/.exec(field.name);
1022
+ const group = match?.[1] ?? "通用";
1023
+ if (!groups.has(group)) {
1024
+ const section = element("section", "pp-group");
1025
+ const rows = element("div", "pp-rows");
1026
+ section.append(element("h2", "pp-group-title", group), rows);
1027
+ groups.set(group, rows);
1028
+ view.append(section);
1020
1029
  }
1021
- default: {
1022
- const multiline = field.control === "textarea" || field.type === "array";
1023
- const input = element(multiline ? "textarea" : "input", "");
1024
- if (multiline) row.classList.add("pp-multiline");
1025
- input.setAttribute("aria-label", field.name);
1026
- if (field.placeholder) input.placeholder = field.placeholder;
1027
- if (multiline && field.rows) input.rows = field.rows;
1028
- /**
1029
- * 在挂载后根据内容调整高度,同时保留基础行数。
1030
- * Size mounted textareas to their contents while retaining baseline rows.
1031
- * @returns {void} 无返回值 / No return value.
1032
- */
1033
- const grow = () => {
1034
- if (!multiline || !field.autoGrow || !input.isConnected) return;
1035
- input.style.height = "auto";
1036
- const baseline = input.getBoundingClientRect().height;
1037
- const style = window.getComputedStyle(input);
1038
- const borders = Number.parseFloat(style.borderTopWidth) + Number.parseFloat(style.borderBottomWidth);
1039
- input.style.height = `${Math.max(baseline, input.scrollHeight + borders)}px`;
1040
- };
1041
- if (multiline && field.autoGrow) {
1042
- input.addEventListener("input", grow);
1043
- growingInputs.push(grow);
1030
+ const row = settingRow("div");
1031
+ row.classList.add("pp-field");
1032
+ const label = element("div", "pp-label");
1033
+ label.append(element("span", "pp-field-name", match?.[2] ?? field.name));
1034
+ if (field.description) label.append(element("span", "pp-field-description", field.description));
1035
+ row.append(label);
1036
+ const value = values[field.key];
1037
+ /**
1038
+ * 读取尚未保存的输入
1039
+ * Read the unsaved input.
1040
+ * @type {() => unknown}
1041
+ */
1042
+ let read;
1043
+ /**
1044
+ * 更新当前控件
1045
+ * Update the current control.
1046
+ * @type {(value: unknown) => void}
1047
+ */
1048
+ let write;
1049
+ let inputContainer = row;
1050
+ let eventName = "change";
1051
+ switch (true) {
1052
+ case Boolean(field.options) && field.type !== "array": {
1053
+ const select = element("select", "");
1054
+ select.setAttribute("aria-label", field.name);
1055
+ field.options.forEach((option, index) => {
1056
+ const item = element("option", "", option.label);
1057
+ item.value = String(index);
1058
+ select.append(item);
1059
+ });
1060
+ write = value => {
1061
+ select.selectedIndex = field.options.findIndex(option => option.key === value);
1062
+ };
1063
+ row.append(fieldControl(select));
1064
+ read = () => field.options[select.selectedIndex]?.key;
1065
+ break;
1044
1066
  }
1045
- eventName = "input";
1046
- if (!multiline) input.type = field.type === "number" ? "number" : "text";
1047
- write = value => {
1048
- input.value = field.type === "array" ? JSON.stringify(value ?? []) : (value ?? "");
1049
- grow();
1050
- };
1051
- read = () => {
1052
- switch (field.type) {
1053
- case "array":
1054
- return JSON.parse(input.value);
1055
- case "number":
1056
- return input.value === "" ? Number.NaN : Number(input.value);
1057
- default:
1058
- return input.value;
1067
+ case field.type === "array" && Boolean(field.options): {
1068
+ const page = element("section", "pp-choice-page");
1069
+ if (field.description) page.append(element("p", "pp-description", field.description));
1070
+ const choices = element("div", "pp-rows");
1071
+ page.append(choices);
1072
+ inputContainer = choices;
1073
+ editors.set(field.key, { node: page, title: match?.[2] ?? field.name });
1074
+ const summary = element("span", "pp-summary");
1075
+ const link = element("button", "pp-choice-link");
1076
+ link.type = "button";
1077
+ link.setAttribute("aria-label", field.name);
1078
+ link.append(summary, element("span", "pp-chevron", "›"));
1079
+ row.append(link);
1080
+ const refresh = () => {
1081
+ const value = client.snapshot().values[field.key];
1082
+ summary.textContent =
1083
+ field.options
1084
+ .filter(option => Array.isArray(value) && value.includes(option.key))
1085
+ .map(option => option.label)
1086
+ .join("、") || "未选择";
1087
+ };
1088
+ summaries.push(refresh);
1089
+ refresh();
1090
+ link.onclick = () => navigation.open(field.key);
1091
+ row.addEventListener("click", event => {
1092
+ if (!link.contains(event.target)) link.click();
1093
+ });
1094
+ const inputs = field.options.map(option => {
1095
+ const label = settingRow("label");
1096
+ label.classList.add("pp-choice");
1097
+ label.textContent = option.label;
1098
+ const input = element("input", "");
1099
+ input.type = "checkbox";
1100
+ input.setAttribute("aria-label", option.label);
1101
+ label.append(input);
1102
+ choices.append(label);
1103
+ return { input, key: option.key };
1104
+ });
1105
+ read = () => inputs.filter(option => option.input.checked).map(option => option.key);
1106
+ write = value => {
1107
+ for (const option of inputs) option.input.checked = Array.isArray(value) && value.includes(option.key);
1108
+ };
1109
+ break;
1110
+ }
1111
+ case field.type === "boolean": {
1112
+ const toggle = element("input", "pp-switch");
1113
+ toggle.type = "checkbox";
1114
+ toggle.setAttribute("switch", "");
1115
+ toggle.setAttribute("role", "switch");
1116
+ toggle.setAttribute("aria-label", field.name);
1117
+ write = value => {
1118
+ toggle.checked = value === true;
1119
+ };
1120
+ read = () => toggle.checked;
1121
+ row.append(toggle);
1122
+ break;
1123
+ }
1124
+ default: {
1125
+ const multiline = field.control === "textarea" || field.type === "array";
1126
+ const input = element(multiline ? "textarea" : "input", "");
1127
+ if (multiline) row.classList.add("pp-multiline");
1128
+ input.setAttribute("aria-label", field.name);
1129
+ if (field.placeholder) input.placeholder = field.placeholder;
1130
+ if (multiline && field.rows) input.rows = field.rows;
1131
+ /**
1132
+ * 在挂载后根据内容调整高度,同时保留基础行数。
1133
+ * Size mounted textareas to their contents while retaining baseline rows.
1134
+ * @returns {void} 无返回值 / No return value.
1135
+ */
1136
+ const grow = () => {
1137
+ if (!multiline || !field.autoGrow || !input.isConnected) return;
1138
+ input.style.height = "auto";
1139
+ const baseline = input.getBoundingClientRect().height;
1140
+ const style = window.getComputedStyle(input);
1141
+ const borders = Number.parseFloat(style.borderTopWidth) + Number.parseFloat(style.borderBottomWidth);
1142
+ input.style.height = `${Math.max(baseline, input.scrollHeight + borders)}px`;
1143
+ };
1144
+ if (multiline && field.autoGrow) {
1145
+ input.addEventListener("input", grow);
1146
+ growingInputs.push(grow);
1059
1147
  }
1060
- };
1061
- row.append(fieldControl(input));
1062
- break;
1148
+ eventName = "input";
1149
+ if (!multiline) input.type = field.type === "number" ? "number" : "text";
1150
+ write = value => {
1151
+ input.value = field.type === "array" ? JSON.stringify(value ?? []) : (value ?? "");
1152
+ grow();
1153
+ };
1154
+ read = () => {
1155
+ switch (field.type) {
1156
+ case "array":
1157
+ return JSON.parse(input.value);
1158
+ case "number":
1159
+ return input.value === "" ? Number.NaN : Number(input.value);
1160
+ default:
1161
+ return input.value;
1162
+ }
1163
+ };
1164
+ row.append(fieldControl(input));
1165
+ break;
1166
+ }
1063
1167
  }
1168
+ write(value);
1169
+ let inputVersion = 0;
1170
+ inputContainer.addEventListener(eventName, event => {
1171
+ if (event.isComposing) return;
1172
+ const version = ++inputVersion;
1173
+ let value;
1174
+ try {
1175
+ value = read();
1176
+ } catch (error) {
1177
+ notify({ kind: "error", message: error.message });
1178
+ return;
1179
+ }
1180
+ const restore = () => {
1181
+ if (version === inputVersion) write(client.snapshot().values[field.key]);
1182
+ };
1183
+ perform(
1184
+ () => {
1185
+ if (!validValue(field, value)) {
1186
+ const error = new TypeError("Invalid setting value");
1187
+ notify({ kind: "error", operation: "write", key: field.key, message: error.message });
1188
+ throw error;
1189
+ }
1190
+ return client.set(field.key, value);
1191
+ },
1192
+ () => {
1193
+ for (const refresh of summaries) refresh();
1194
+ },
1195
+ restore,
1196
+ );
1197
+ });
1198
+ if (eventName === "input") inputContainer.addEventListener("compositionend", event => event.target.dispatchEvent(new window.Event("input", { bubbles: true })));
1199
+ groups.get(group).append(row);
1064
1200
  }
1065
- write(value);
1066
- let inputVersion = 0;
1067
- inputContainer.addEventListener(eventName, event => {
1068
- if (event.isComposing) return;
1069
- const version = ++inputVersion;
1201
+ const settingsPage = element("section", "pp-settings-page");
1202
+ const settingsOutput = element("pre", "pp-cache");
1203
+ settingsOutput.setAttribute("aria-label", "Settings 内容");
1204
+ settingsPage.append(settingsOutput);
1205
+ editors.set("$settings", { node: settingsPage, title: "设置" });
1206
+ handlers.set("viewSettings", () => {
1207
+ if (saving) return;
1070
1208
  let value;
1071
- try {
1072
- value = read();
1073
- } catch (error) {
1074
- notify({ kind: "error", message: error.message });
1075
- return;
1076
- }
1077
- const restore = () => {
1078
- if (version === inputVersion) write(client.snapshot().values[field.key]);
1079
- };
1080
- perform(
1209
+ return perform(
1210
+ async () => {
1211
+ try {
1212
+ value = await client.readSettings();
1213
+ } catch (error) {
1214
+ notify({ kind: "error", message: error.message });
1215
+ throw error;
1216
+ }
1217
+ },
1081
1218
  () => {
1082
- if (!validValue(field, value)) {
1083
- const error = new TypeError("Invalid setting value");
1084
- notify({ kind: "error", operation: "write", key: field.key, message: error.message });
1219
+ settingsOutput.textContent = value === undefined ? "暂无设置" : JSON.stringify(value, null, 2);
1220
+ navigation.open("$settings");
1221
+ },
1222
+ );
1223
+ });
1224
+ const cachePage = element("section", "pp-cache-page");
1225
+ const output = element("pre", "pp-cache");
1226
+ output.textContent = "暂无缓存";
1227
+ output.setAttribute("aria-label", "Caches 内容");
1228
+ cachePage.append(output);
1229
+ editors.set("$caches", { node: cachePage, title: "缓存" });
1230
+ handlers.set("viewCaches", () => {
1231
+ if (saving) return;
1232
+ let value;
1233
+ return perform(
1234
+ async () => {
1235
+ try {
1236
+ value = await client.readCaches();
1237
+ } catch (error) {
1238
+ notify({ kind: "error", message: error.message });
1085
1239
  throw error;
1086
1240
  }
1087
- return client.set(field.key, value);
1088
1241
  },
1089
1242
  () => {
1090
- for (const refresh of summaries) refresh();
1243
+ output.textContent = value === undefined ? "暂无缓存" : JSON.stringify(value, null, 2);
1244
+ navigation.open("$caches");
1091
1245
  },
1092
- restore,
1093
1246
  );
1094
1247
  });
1095
- if (eventName === "input") inputContainer.addEventListener("compositionend", event => event.target.dispatchEvent(new window.Event("input", { bubbles: true })));
1096
- groups.get(group).append(row);
1248
+ handlers.set("clearCaches", async () => {
1249
+ if (saving) return;
1250
+ if (!(await requestConfirmation(window, `清空 ${active} 的全部 Caches?`)) || destroyed || saving) return;
1251
+ return perform(
1252
+ () => client.clearCaches(),
1253
+ () => {
1254
+ output.textContent = "暂无缓存";
1255
+ },
1256
+ );
1257
+ });
1258
+ handlers.set("reset", async () => {
1259
+ if (saving) return;
1260
+ if (!(await requestConfirmation(window, `重置 ${active} 的设置?这将删除该模块的 Settings、Caches 和其它持久化数据。`)) || destroyed || saving) return;
1261
+ return perform(() => client.reset(), controls);
1262
+ });
1263
+ navigation?.destroy();
1264
+ navigation = new Navigation(viewport, view, key => editors.get(key)?.node);
1265
+ navigation.addEventListener("change", updateNavigation);
1266
+ for (const grow of growingInputs) grow();
1267
+ updateNavigation();
1097
1268
  }
1098
- const settingsPage = element("section", "pp-settings-page");
1099
- const settingsOutput = element("pre", "pp-cache");
1100
- settingsOutput.setAttribute("aria-label", "Settings 内容");
1101
- settingsPage.append(settingsOutput);
1102
- editors.set("$settings", { node: settingsPage, title: "设置" });
1103
- handlers.set("viewSettings", () => {
1104
- if (saving) return;
1105
- let value;
1106
- return perform(
1107
- async () => {
1108
- try {
1109
- value = await client.readSettings();
1110
- } catch (error) {
1111
- notify({ kind: "error", message: error.message });
1112
- throw error;
1113
- }
1114
- },
1115
- () => {
1116
- settingsOutput.textContent = value === undefined ? "暂无设置" : JSON.stringify(value, null, 2);
1117
- navigation.open("$settings");
1118
- },
1119
- );
1120
- });
1121
- const cachePage = element("section", "pp-cache-page");
1122
- const output = element("pre", "pp-cache");
1123
- output.textContent = "暂无缓存";
1124
- output.setAttribute("aria-label", "Caches 内容");
1125
- cachePage.append(output);
1126
- editors.set("$caches", { node: cachePage, title: "缓存" });
1127
- handlers.set("viewCaches", () => {
1128
- if (saving) return;
1129
- let value;
1130
- return perform(
1131
- async () => {
1132
- try {
1133
- value = await client.readCaches();
1134
- } catch (error) {
1135
- notify({ kind: "error", message: error.message });
1136
- throw error;
1137
- }
1138
- },
1139
- () => {
1140
- output.textContent = value === undefined ? "暂无缓存" : JSON.stringify(value, null, 2);
1141
- navigation.open("$caches");
1142
- },
1143
- );
1144
- });
1145
- handlers.set("clearCaches", async () => {
1146
- if (saving) return;
1147
- if (!(await requestConfirmation(window, `清空 ${active} 的全部 Caches?`)) || destroyed || saving) return;
1148
- return perform(
1149
- () => client.clearCaches(),
1150
- () => {
1151
- output.textContent = "暂无缓存";
1152
- },
1153
- );
1154
- });
1155
- handlers.set("reset", async () => {
1156
- if (saving) return;
1157
- if (!(await requestConfirmation(window, `重置 ${active} 的设置?这将删除该模块的 Settings、Caches 和其它持久化数据。`)) || destroyed || saving) return;
1158
- return perform(() => client.reset(), controls);
1159
- });
1160
- navigation?.destroy();
1161
- navigation = new Navigation(viewport, view, key => editors.get(key)?.node);
1162
- navigation.addEventListener("change", updateNavigation);
1163
- for (const grow of growingInputs) grow();
1164
- updateNavigation();
1165
- }
1166
- /**
1167
- * 已加载的表单交由导航组件返回;加载阶段可以返回先前文档。
1168
- * Loaded forms delegate back to navigation; loading views can return to the previous document.
1169
- * @returns {void} 无返回值 / No return value.
1170
- */
1171
- back.onclick = () => {
1172
- if (saving) return;
1173
- if (navigation) navigation.back();
1174
- else window.history.back();
1175
- };
1176
- open(definition.module);
1177
- return {
1178
1269
  /**
1179
- * 移除监听器、定时器、会话和挂载内容。
1180
- * Remove listeners, timers, session and mounted content.
1270
+ * 已加载的表单交由导航组件返回;加载阶段可以返回先前文档。
1271
+ * Loaded forms delegate back to navigation; loading views can return to the previous document.
1181
1272
  * @returns {void} 无返回值 / No return value.
1182
1273
  */
1183
- destroy() {
1274
+ back.onclick = () => {
1275
+ if (saving) return;
1276
+ if (navigation) navigation.back();
1277
+ else window.history.back();
1278
+ };
1279
+ open(definition.module);
1280
+ return () => {
1184
1281
  destroyed = true;
1185
1282
  menu.destroy();
1186
1283
  window.frameElement?.removeEventListener("preferencepanes:action", onAction);
@@ -1189,8 +1286,17 @@ function mountPanel(root, model) {
1189
1286
  if (active && !saving) client.leave();
1190
1287
  clearTimeout(timer);
1191
1288
  shell.remove();
1192
- },
1193
- };
1289
+ };
1290
+ }
1291
+
1292
+ /**
1293
+ * 移除监听器、定时器、会话和挂载内容。
1294
+ * Remove listeners, timers, session, and mounted content.
1295
+ * @returns {void} 无返回值 / No return value.
1296
+ */
1297
+ destroy() {
1298
+ this.#release();
1299
+ }
1194
1300
  }
1195
1301
 
1196
1302
  var defaults = "/* 通用默认样式只使用 pp 命名空间;项目可通过 CSS 输入覆盖变量和组件。\n * Generic defaults use only the pp namespace; projects may override variables and components through CSS input. */\n.pp-panel {\n --pp-text: #18191c;\n --pp-background: #f6f7f8;\n --pp-surface: #fff;\n --pp-field: #f1f2f3;\n --pp-border: #e3e5e7;\n --pp-muted: #797f87;\n --pp-accent: #1677ff;\n font:\n 15px / 1.5 -apple-system,\n BlinkMacSystemFont,\n \"Segoe UI\",\n sans-serif;\n color: var(--pp-text);\n background: var(--pp-background);\n position: relative;\n display: flex;\n flex-direction: column;\n width: 100%;\n max-width: 100vw;\n min-width: 0;\n height: 100vh;\n overflow: hidden;\n}\n\n:root[data-theme=\"dark\"] .pp-panel {\n --pp-text: #f1f2f3;\n --pp-background: #0d0e0f;\n --pp-surface: #18191c;\n --pp-field: #2f3238;\n --pp-border: #2f3238;\n --pp-muted: #9499a0;\n}\n.pp-panel * {\n box-sizing: border-box;\n letter-spacing: 0;\n}\n.pp-header {\n flex: none;\n height: calc(52px + env(safe-area-inset-top));\n padding: env(safe-area-inset-top) 12px 0;\n display: flex;\n align-items: center;\n background: var(--pp-surface);\n border-bottom: 1px solid var(--pp-border);\n position: relative;\n z-index: 2;\n}\n.pp-title {\n flex: 1;\n text-align: center;\n font-size: 17px;\n font-weight: 500;\n margin: 0;\n min-width: 0;\n overflow-wrap: anywhere;\n}\n.pp-nav-spacer {\n width: 44px;\n flex: none;\n}\n.pp-panel button {\n font: inherit;\n cursor: pointer;\n border: 0;\n background: none;\n color: inherit;\n}\n.pp-panel .pp-back {\n width: 44px;\n height: 44px;\n flex: none;\n font-size: 34px;\n line-height: 32px;\n padding: 0;\n}\n.pp-panel button:disabled {\n opacity: 0.5;\n cursor: wait;\n}\n.pp-viewport {\n position: relative;\n flex: 1;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n}\n:root[data-preference-panes-embedded] .pp-header {\n display: none;\n}\n@supports (height: 100dvh) {\n .pp-panel {\n height: 100dvh;\n }\n}\n.pp-fields,\n.pp-choice-page,\n.pp-settings-page,\n.pp-cache-page {\n position: absolute;\n inset: 0;\n min-width: 0;\n overflow-x: hidden;\n overflow-y: auto;\n padding: 12px max(16px, calc((100% - 688px) / 2)) calc(28px + env(safe-area-inset-bottom) + var(--pp-keyboard-height, 0px));\n scroll-padding-bottom: var(--pp-keyboard-height, 0px);\n background: var(--pp-background);\n}\n.pp-choice-link {\n display: flex;\n align-items: center;\n justify-content: flex-end;\n gap: 8px;\n max-width: 45%;\n min-width: 44px;\n min-height: 44px;\n padding: 0;\n text-align: right;\n flex: 1;\n}\n.pp-summary {\n color: var(--pp-muted);\n font-size: 13px;\n line-height: 18px;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n overflow-wrap: anywhere;\n}\n.pp-chevron {\n color: var(--pp-muted);\n font-size: 22px;\n flex: none;\n}\n.pp-editor {\n flex: none;\n width: 45%;\n min-width: 0;\n min-height: 36px;\n padding: 8px 10px;\n font: inherit;\n color: var(--pp-text);\n background: var(--pp-field);\n border: 0;\n border-radius: 6px;\n}\n.pp-panel .pp-multiline {\n display: block;\n}\n.pp-multiline .pp-editor {\n width: 100%;\n margin-top: 10px;\n}\n.pp-panel [hidden] {\n display: none !important;\n}\n.pp-label {\n flex: 1;\n min-width: 0;\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n margin-right: 16px;\n}\n.pp-field-name {\n color: var(--pp-text);\n font-size: 15px;\n}\n.pp-field-description {\n margin-top: 2px;\n color: var(--pp-muted);\n font-size: 12px;\n}\n.pp-group {\n margin-top: 16px;\n}\n.pp-group-title {\n margin: 0 0 8px;\n color: var(--pp-muted);\n font-size: 15px;\n font-weight: 400;\n}\n.pp-row {\n min-width: 0;\n min-height: 48px;\n padding: 16px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n background: var(--pp-surface);\n border-bottom: 1px solid var(--pp-border);\n}\n.pp-rows > :last-child {\n border-bottom: 0 !important;\n}\n.pp-switch {\n flex: none;\n accent-color: var(--pp-accent);\n}\n.pp-choice {\n justify-content: space-between;\n cursor: pointer;\n}\n.pp-choice input {\n width: 20px;\n height: 20px;\n flex: none;\n accent-color: var(--pp-accent);\n margin: 0;\n}\n.pp-description {\n font-size: 12px;\n line-height: 1.6;\n color: var(--pp-muted);\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n}\n.pp-module-info {\n display: flex;\n gap: 12px;\n margin: 12px 0;\n}\n.pp-module-details {\n min-width: 0;\n overflow-wrap: anywhere;\n}\n.pp-module-source {\n color: inherit;\n text-decoration: underline;\n}\n.pp-status {\n position: fixed;\n inset: 0;\n display: grid;\n place-content: center;\n justify-items: center;\n gap: 12px;\n min-width: 0;\n min-height: 0;\n margin: 0;\n padding: 24px;\n color: var(--pp-muted, GrayText);\n text-align: center;\n background: var(--pp-background, Canvas);\n}\n.pp-viewport > .pp-status {\n position: absolute;\n}\n.pp-status-spinner {\n box-sizing: border-box;\n width: 28px;\n height: 28px;\n border: 3px solid color-mix(in srgb, currentColor 25%, transparent);\n border-top-color: var(--pp-accent, AccentColor);\n border-radius: 50%;\n animation: pp-status-spin 0.8s linear infinite;\n}\n.pp-status-message {\n max-width: 100%;\n margin: 0;\n overflow-wrap: anywhere;\n}\n.pp-status-action {\n min-width: 96px;\n min-height: 44px;\n padding: 8px 16px;\n border: 0;\n border-radius: 6px;\n color: var(--pp-text, ButtonText);\n font: inherit;\n cursor: pointer;\n background: var(--pp-surface, ButtonFace);\n}\n@keyframes pp-status-spin {\n to {\n transform: rotate(1turn);\n }\n}\n.pp-cache {\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n}\n.pp-toast {\n pointer-events: none;\n position: fixed;\n bottom: calc(30px + env(safe-area-inset-bottom));\n left: 50%;\n transform: translateX(-50%);\n max-width: 90vw;\n padding: 10px 16px;\n border-radius: 8px;\n background: #333e;\n color: white;\n font-size: 13px;\n z-index: 20;\n}\n.pp-toast[data-kind=\"error\"] {\n background: #8d2424;\n}\n.pp-panel :focus-visible {\n outline: 2px solid var(--pp-accent);\n outline-offset: -2px;\n}\n";
@@ -1214,132 +1320,167 @@ function installDefaultStyles(document) {
1214
1320
  }
1215
1321
 
1216
1322
  /**
1217
- * 挂载模块设置页;默认样式由包提供,可选 CSS 仅作用于当前模块。
1218
- * Mount a module page with package defaults and optional module-scoped CSS.
1219
- * @param {import("../index.js").ModuleModel} model API 返回的模块模型 / Module model returned by the API.
1220
- * @param {string} [css] 可选 CSS 正文 / Optional CSS text.
1221
- * @returns {import("./index.js").MountedPreferences} 模块生命周期句柄 / Module lifecycle handle.
1323
+ * 管理 BoxJS 规范化、主题同步和面板生命周期。
1324
+ * Manage BoxJS normalization, theme synchronization, and panel lifecycle.
1222
1325
  */
1223
- function mount(model, css = "") {
1224
- if (typeof css !== "string") throw new TypeError("CSS must be a string");
1225
- const definition = normalizeBoxJs(model.boxjs, model.module);
1226
- const values = { ...model.values };
1227
- for (const field of definition.fields) {
1228
- if (values[field.key] === undefined) continue;
1229
- values[field.key] = normalizeStoredValue(field, values[field.key]);
1230
- if (!validValue(field, values[field.key])) throw new TypeError(`Invalid stored value: ${field.key}`);
1231
- }
1232
- for (const field of definition.fields) if (values[field.key] === undefined && Object.hasOwn(field, "defaultValue")) values[field.key] = structuredClone(field.defaultValue);
1233
- const rendered = { ...model, definition, values };
1234
- const metadata = definition.metadata ?? {};
1235
- const image = metadata.icon || metadata.icons?.[1] || metadata.icons?.[0];
1236
- if (image) resourceURL(image);
1237
- if (metadata.repo) resourceURL(metadata.repo);
1238
- const existing = document.querySelector("#preferences");
1239
- const root = existing ?? element("main", "");
1240
- if (!existing) {
1241
- root.id = "preferences";
1242
- document.body.append(root);
1326
+ class PreferencesView {
1327
+ #existing;
1328
+ #root;
1329
+ #base;
1330
+ #ownsBase;
1331
+ #previousTitle;
1332
+ #previousTheme;
1333
+ #systemTheme;
1334
+ #previousKeyboard;
1335
+ #host;
1336
+ #observer;
1337
+ #panel;
1338
+
1339
+ /**
1340
+ * 使用原始 BoxJS JSON 挂载设置页。
1341
+ * Mount a settings page from raw BoxJS JSON.
1342
+ * @param {import("../index.js").BoxJSInput} boxjs 单模块 BoxJS JSON / Single-module BoxJS JSON.
1343
+ */
1344
+ constructor(boxjs) {
1345
+ const definition = normalizeBoxJs(boxjs);
1346
+ const metadata = definition.metadata ?? {};
1347
+ const image = metadata.icon || metadata.icons?.[1] || metadata.icons?.[0];
1348
+ if (image) resourceURL(image);
1349
+ if (metadata.repo) resourceURL(metadata.repo);
1350
+
1351
+ this.#existing = document.querySelector("#preferences");
1352
+ this.#root = this.#existing ?? element("main", "");
1353
+ if (!this.#existing) {
1354
+ this.#root.id = "preferences";
1355
+ document.body.append(this.#root);
1356
+ }
1357
+ const styles = installDefaultStyles(document);
1358
+ this.#base = styles.element;
1359
+ this.#ownsBase = styles.owned;
1360
+ this.#previousTitle = document.title;
1361
+ this.#previousTheme = document.documentElement.dataset.theme;
1362
+ this.#systemTheme = window.matchMedia("(prefers-color-scheme: dark)");
1363
+ this.#previousKeyboard = document.documentElement.style.getPropertyValue("--pp-keyboard-height");
1364
+ this.#host = window.frameElement?.ownerDocument.documentElement;
1365
+ this.#syncAppearance();
1366
+ this.#systemTheme.addEventListener("change", this.#syncAppearance);
1367
+ if (this.#host) {
1368
+ this.#observer = new MutationObserver(this.#syncAppearance);
1369
+ this.#observer.observe(this.#host, { attributes: true, attributeFilter: ["data-theme", "style"] });
1370
+ }
1371
+ document.title = metadata.name ?? definition.module;
1372
+ try {
1373
+ this.#root.replaceChildren();
1374
+ this.#panel = new PreferencesPanel(this.#root, definition);
1375
+ } catch (error) {
1376
+ this.destroy();
1377
+ throw error;
1378
+ }
1243
1379
  }
1244
- const { element: base, owned: ownsBase } = installDefaultStyles(document);
1245
- const custom = element("style", "");
1246
- custom.textContent = css;
1247
- document.head.append(custom);
1248
- const previousTitle = document.title;
1249
- const previousTheme = document.documentElement.dataset.theme;
1250
- const systemTheme = window.matchMedia("(prefers-color-scheme: dark)");
1251
- const previousKeyboard = document.documentElement.style.getPropertyValue("--pp-keyboard-height");
1252
- const host = window.frameElement?.ownerDocument.documentElement;
1380
+
1253
1381
  /**
1254
1382
  * 跟随嵌入宿主的通用环境状态,不识别业务 App 或解析其 UA。
1255
- * Follow generic host appearance without detecting a business app or parsing its user agent.
1383
+ * Follow generic host appearance without detecting a business App or parsing its UA.
1256
1384
  * @returns {void} 已同步主题与键盘避让 / Theme and keyboard clearance synchronized.
1257
1385
  */
1258
- const syncAppearance = () => {
1259
- const theme = host?.dataset.theme ?? previousTheme ?? (systemTheme.matches ? "dark" : "light");
1386
+ #syncAppearance = () => {
1387
+ const theme = this.#host?.dataset.theme ?? this.#previousTheme ?? (this.#systemTheme.matches ? "dark" : "light");
1260
1388
  document.documentElement.dataset.theme = theme;
1261
- if (host) document.documentElement.style.setProperty("--pp-keyboard-height", host.style.getPropertyValue("--pp-keyboard-height"));
1262
- };
1263
- let observer;
1264
- syncAppearance();
1265
- systemTheme.addEventListener("change", syncAppearance);
1266
- if (host) {
1267
- observer = new MutationObserver(syncAppearance);
1268
- observer.observe(host, { attributes: true, attributeFilter: ["data-theme", "style"] });
1269
- }
1270
- document.title = metadata.name ?? definition.module;
1271
- let panel;
1272
- const view = {
1273
- /**
1274
- * 释放模块视图、样式与会话,不操作项目入口页。
1275
- * Release the module view, styles and session without operating a project landing page.
1276
- * @returns {void} 无返回值 / No return value.
1277
- */
1278
- destroy() {
1279
- observer?.disconnect();
1280
- systemTheme.removeEventListener("change", syncAppearance);
1281
- panel?.destroy();
1282
- if (ownsBase) base.remove();
1283
- custom.remove();
1284
- if (existing) root.replaceChildren();
1285
- else root.remove();
1286
- document.title = previousTitle;
1287
- if (previousTheme === undefined) delete document.documentElement.dataset.theme;
1288
- else document.documentElement.dataset.theme = previousTheme;
1289
- document.documentElement.style.setProperty("--pp-keyboard-height", previousKeyboard);
1290
- },
1389
+ if (this.#host) document.documentElement.style.setProperty("--pp-keyboard-height", this.#host.style.getPropertyValue("--pp-keyboard-height"));
1291
1390
  };
1292
- try {
1293
- root.replaceChildren();
1294
- panel = mountPanel(root, rendered);
1295
- return view;
1296
- } catch (error) {
1297
- view.destroy();
1298
- throw error;
1391
+
1392
+ /**
1393
+ * 释放模块视图、样式与会话,不操作项目入口页。
1394
+ * Release the module view, styles, and session without operating a project landing page.
1395
+ * @returns {void} 无返回值 / No return value.
1396
+ */
1397
+ destroy() {
1398
+ this.#observer?.disconnect();
1399
+ this.#systemTheme.removeEventListener("change", this.#syncAppearance);
1400
+ this.#panel?.destroy();
1401
+ if (this.#ownsBase) this.#base.remove();
1402
+ if (this.#existing) this.#root.replaceChildren();
1403
+ else this.#root.remove();
1404
+ document.title = this.#previousTitle;
1405
+ if (this.#previousTheme === undefined) delete document.documentElement.dataset.theme;
1406
+ else document.documentElement.dataset.theme = this.#previousTheme;
1407
+ document.documentElement.style.setProperty("--pp-keyboard-height", this.#previousKeyboard);
1299
1408
  }
1300
1409
  }
1301
1410
 
1302
- installDefaultStyles(document);
1303
- let view;
1304
1411
  /**
1305
- * URL 或代理传递的 Header 导入 JSON/CSS,支持独立文档与 srcdoc。
1306
- * Import JSON/CSS from the URL or proxy-carried headers in standalone and srcdoc documents.
1307
- * @returns {Promise<void>} 启动完成 / Startup completion.
1412
+ * 使用原始 BoxJS JSON 挂载设置页。
1413
+ * Mount a settings page from raw BoxJS JSON.
1414
+ * @param {import("../index.js").BoxJSInput} boxjs 单模块 BoxJS JSON / Single-module BoxJS JSON.
1415
+ * @returns {import("./index.js").MountedPreferences} 模块视图 / Module view.
1308
1416
  */
1309
- async function start() {
1310
- try {
1311
- view?.destroy();
1312
- view = undefined;
1313
- document.querySelector("#preferences").replaceChildren(statusView("读取设置…"));
1314
- const context = document.querySelector('meta[name="preference-panes-inputs"]');
1315
- const embedded = window.frameElement?.dataset.preferencePanes;
1316
- let inputs;
1317
- switch (true) {
1318
- case embedded !== undefined:
1319
- inputs = JSON.parse(embedded);
1320
- document.documentElement.dataset.preferencePanesEmbedded = "";
1321
- break;
1322
- case context !== null:
1323
- inputs = JSON.parse(decodeURIComponent(context.content));
1324
- break;
1325
- default:
1326
- inputs = pageInputs(new URL(location.href));
1417
+ function mount(boxjs) {
1418
+ return new PreferencesView(boxjs);
1419
+ }
1420
+
1421
+ /**
1422
+ * 管理模块文档的配置请求、重载和错误状态。
1423
+ * Manage configuration requests, reloads, and error states for a module document.
1424
+ */
1425
+ class ModulePage {
1426
+ #window;
1427
+ #root;
1428
+ #view;
1429
+
1430
+ /**
1431
+ * 创建模块页面控制器并安装基础样式。
1432
+ * Create the module page controller and install base styles.
1433
+ * @param {Document} document 模块文档 / Module document.
1434
+ */
1435
+ constructor(document) {
1436
+ this.#window = document.defaultView;
1437
+ this.#root = document.querySelector("#preferences");
1438
+ installDefaultStyles(document);
1439
+ this.#window.addEventListener("pageshow", this.#show);
1440
+ }
1441
+
1442
+ /**
1443
+ * 从规范模块路径读取 BoxJS JSON 并挂载通用前端。
1444
+ * Read BoxJS JSON from the conventional module path and mount the generic frontend.
1445
+ * @returns {Promise<void>} 启动完成 / Startup completion.
1446
+ */
1447
+ async start() {
1448
+ try {
1449
+ this.#view?.destroy();
1450
+ this.#view = undefined;
1451
+ this.#root.replaceChildren(statusView("读取设置…"));
1452
+ const embedded = this.#window.frameElement?.dataset.preferencePanesModule;
1453
+ const match = /^\/settings\/([a-zA-Z0-9_-]+)\/?$/.exec(this.#window.location.pathname);
1454
+ const module = embedded ?? match?.[1];
1455
+ if (!module) throw new TypeError("Open a concrete module URL");
1456
+ const response = await fetch(`/configs/${encodeURIComponent(module)}`, { cache: "no-store", credentials: "omit", headers: { Accept: "application/json" } });
1457
+ if (response.status !== 200) throw new Error(`HTTP ${response.status}`);
1458
+ this.#view = mount(await response.json());
1459
+ } catch (error) {
1460
+ this.#root.replaceChildren(statusView(`加载失败:${error.message}`, () => this.start()));
1327
1461
  }
1328
- const apiURL = new URL(`/api/${encodeURIComponent(inputs.module)}`, inputs.url).href;
1329
- const resources = [inputs.css].map(source => {
1330
- if (!source) return null;
1331
- const url = new URL(source, inputs.url);
1332
- if (!["http:", "https:"].includes(url.protocol)) throw new TypeError("Resources must use HTTP(S) URLs");
1333
- return url.href;
1334
- });
1335
- const [style, modelResponse] = await Promise.all([...resources.map(url => (url ? fetch(url, { cache: "no-store", credentials: "omit" }) : null)), fetch(apiURL, { cache: "no-store", credentials: "omit", headers: { Accept: "application/json", "X-PreferencePanes-JSON": inputs.json } })]);
1336
- if ((style && style.status !== 200) || modelResponse.status !== 200) throw new Error(`HTTP ${modelResponse.status !== 200 ? modelResponse.status : style.status}`);
1337
- view = mount(await modelResponse.json(), style ? await style.text() : "");
1338
- } catch (error) {
1339
- document.querySelector("#preferences").replaceChildren(statusView(`加载失败:${error.message}`, start));
1340
1462
  }
1463
+
1464
+ /**
1465
+ * 释放页面视图和页面级监听器。
1466
+ * Release the page view and page-level listener.
1467
+ * @returns {void} 无返回值 / No return value.
1468
+ */
1469
+ destroy() {
1470
+ this.#window.removeEventListener("pageshow", this.#show);
1471
+ this.#view?.destroy();
1472
+ this.#view = undefined;
1473
+ }
1474
+
1475
+ /**
1476
+ * 从前进后退缓存恢复时重新加载模块。
1477
+ * Reload the module when restored from the back-forward cache.
1478
+ * @param {PageTransitionEvent} event 页面显示事件 / Page show event.
1479
+ * @returns {void} 无返回值 / No return value.
1480
+ */
1481
+ #show = event => {
1482
+ if (event.persisted) this.start();
1483
+ };
1341
1484
  }
1342
- start();
1343
- window.addEventListener("pageshow", event => {
1344
- if (event.persisted) start();
1345
- });
1485
+
1486
+ new ModulePage(document).start();