An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve user preference persistence https://github.com/siyuan-note/siyuan/issues/20685
Daniela2dcd8cdde31
diff --git a/AGENTS.md b/AGENTS.mdindex e12ac1aa75..16d76b915a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -170,8 +170,10 @@ Unambiguous mechanical edits with no behavioral or compatibility impact need no- Define custom attribute name constants in `app/src/constants.ts`, alongside similar constants in `Constants`, rather than in individual feature modules9. **Frontend preference storage:** Do not use browser `localStorage` directly, including `window.localStorage` and `globalThis.localStorage`- - Read preferences from `window.siyuan.storage`; when changing a preference, update its in-memory value and persist it with `setStorageVal` from `app/src/protyle/util/compatibility.ts`- - SiYuan persists these values in the workspace's `data/storage/local.json`; do not use browser `storage` events to observe changes to this store+ - New user-facing preferences, including settings switches and explicit reader or panel preferences, default to `conf.json`; define them in the corresponding configuration namespace, normalize them in the kernel, and write through `createConfigNamespaceApi().patch`+ - Reserve `local.json` for growing mappings keyed by document, view, or transaction IDs; transient or session state such as scroll positions, dialog geometry, and restored tabs; usage history and reading positions; and plugin runtime state+ - Writing frequency does not determine storage: `uiLayout` is already a frequently updated configuration namespace with silent notifications. Neither `conf.json` nor `local.json` participates in data sync; configuration export includes `conf.json`+ - Read local state from `window.siyuan.storage`; when changing it, update its in-memory value and persist it with `setStorageVal` from `app/src/protyle/util/compatibility.ts`. SiYuan persists these values in the workspace's `data/storage/local.json`; do not use browser `storage` events to observe changes to this store10. **Frontend platform identification:**- Use the mutually exclusive `body` class names written by `applyPlatformClasses()` in `app/src/protyle/util/compatibility.ts`: `body--mac`, `body--windows`, `body--linux`, `body--ios`, `body--android`, and `body--harmony`diff --git a/app/src/asset/anno.ts b/app/src/asset/anno.tsindex f399d2f8b9..bd4384fd60 100644--- a/app/src/asset/anno.ts+++ b/app/src/asset/anno.ts@@ -1,7 +1,8 @@import {fetchPost} from "../util/fetch";import {setPosition} from "../util/setPosition";import {hasClosestByAttribute, hasClosestByClassName} from "../protyle/util/hasClosest";-import {readText, setStorageVal, writeText} from "../protyle/util/compatibility";+import {readText, writeText} from "../protyle/util/compatibility";+import {patchAppearancePreference} from "../config/tabs/appearancePreferences";import {getAllModels} from "../layout/getAll";import {focusByRange} from "../protyle/util/selectionOffsets";import {Constants} from "../constants";@@ -173,7 +174,7 @@ export const initAnno = (element: HTMLElement, pdf: any) => {document.onselect = null;stopRectCreation();- const coords = getHightlightCoordsByRect(pdf, window.siyuan.storage[Constants.LOCAL_PDFTHEME].annoColor || "var(--b3-pdf-background1)", rectResizeElement,+ const coords = getHightlightCoordsByRect(pdf, window.siyuan.config.appearance.pdfTheme.annoColor || "var(--b3-pdf-background1)", rectResizeElement,rectResizeElement.style.backgroundColor ? "text" : "border");rectResizeElement.classList.add("fn__none");if (coords) {@@ -388,11 +389,11 @@ export const initAnno = (element: HTMLElement, pdf: any) => {return;}if (typeof event.detail === "string") {- window.siyuan.storage[Constants.LOCAL_PDFTHEME].annoColor = event.detail === "0" ?- (window.siyuan.storage[Constants.LOCAL_PDFTHEME].annoColor || "var(--b3-pdf-background1)")+ const annoColor = event.detail === "0" ?+ (window.siyuan.config.appearance.pdfTheme.annoColor || "var(--b3-pdf-background1)"): `var(--b3-pdf-background${event.detail})`;- setStorageVal(Constants.LOCAL_PDFTHEME, window.siyuan.storage[Constants.LOCAL_PDFTHEME]);- const coords = getHightlightCoordsByRange(pdf, window.siyuan.storage[Constants.LOCAL_PDFTHEME].annoColor);+ void patchAppearancePreference("pdfTheme.annoColor", annoColor);+ const coords = getHightlightCoordsByRange(pdf, annoColor);if (coords) {coords.forEach((item, index) => {const newElement = showHighlight(item, pdf);@@ -411,8 +412,7 @@ export const initAnno = (element: HTMLElement, pdf: any) => {const type = target.getAttribute("data-type");if (target.classList.contains("color__square")) {const color = target.style.backgroundColor;- window.siyuan.storage[Constants.LOCAL_PDFTHEME].annoColor = color;- setStorageVal(Constants.LOCAL_PDFTHEME, window.siyuan.storage[Constants.LOCAL_PDFTHEME]);+ void patchAppearancePreference("pdfTheme.annoColor", color);if (rectElement) {const config = getConfig(pdf);const annoItem = config[rectElement.getAttribute("data-node-id")];diff --git a/app/src/asset/index.ts b/app/src/asset/index.tsindex ab17745090..cf0754bc5e 100644--- a/app/src/asset/index.ts+++ b/app/src/asset/index.ts@@ -13,7 +13,7 @@ import {webViewerLoad} from "./pdf/viewer";import {onPageNumberChanged} from "./pdf/app";/// #endifimport {fetchPost} from "../util/fetch";-import {setStorageVal} from "../protyle/util/compatibility";+import {bindPdfTheme} from "./pdfViewer";import type {App} from "../index";import {clearOBG} from "../layout/dock/util";import {getDisplayName} from "../util/pathName";@@ -121,40 +121,7 @@ export class Asset extends Model {} else if (type === ".pdf") {/// #if !MOBILEthis.element.innerHTML = getPdfViewerHTML();- const localPDF = window.siyuan.storage[Constants.LOCAL_PDFTHEME];- const pdfTheme = window.siyuan.config.appearance.mode === 0 ? localPDF.light : localPDF.dark;- const darkElement = this.element.querySelector("#pdfDark");- const lightElement = this.element.querySelector("#pdfLight");- if (pdfTheme === "dark") {- this.element.firstElementChild.classList.add("pdf__outer--dark");- lightElement.classList.remove("toggled");- darkElement.classList.add("toggled");- } else {- lightElement.classList.add("toggled");- darkElement.classList.remove("toggled");- }- lightElement.addEventListener("click", () => {- if (window.siyuan.config.appearance.mode === 0) {- localPDF.light = "light";- } else {- localPDF.dark = "light";- }- this.element.firstElementChild.classList.remove("pdf__outer--dark");- lightElement.classList.add("toggled");- darkElement.classList.remove("toggled");- setStorageVal(Constants.LOCAL_PDFTHEME, window.siyuan.storage[Constants.LOCAL_PDFTHEME]);- });- darkElement.addEventListener("click", () => {- if (window.siyuan.config.appearance.mode === 0) {- localPDF.light = "dark";- } else {- localPDF.dark = "dark";- }- this.element.firstElementChild.classList.add("pdf__outer--dark");- lightElement.classList.remove("toggled");- darkElement.classList.add("toggled");- setStorageVal(Constants.LOCAL_PDFTHEME, window.siyuan.storage[Constants.LOCAL_PDFTHEME]);- });+ bindPdfTheme(this.element);// 初始化完成后需等待页签是否显示设置完成,才可以判断 pdf 是否能进行渲染this.pdfLoadState.setTimeout(window.setTimeout(() => {if (!this.pdfLoadState.consumeTimeout() || !this.element.isConnected) {diff --git a/app/src/asset/pdf/secondary_toolbar.js b/app/src/asset/pdf/secondary_toolbar.jsindex 9d6750fb7c..b1126c1cd8 100644--- a/app/src/asset/pdf/secondary_toolbar.js+++ b/app/src/asset/pdf/secondary_toolbar.js@@ -173,7 +173,7 @@ class SecondaryToolbar {this.#bindListeners(buttons);if (!isMobile()) {this.#resetMouseScroll = bindMenuMouseScroll(options.toolbar, () =>- !isInMobileApp() && window.siyuan.storage?.[Constants.LOCAL_MENU_MOUSE_SCROLL] === true);+ !isInMobileApp() && window.siyuan.config.appearance?.menuMouseScroll === true);}this.reset();diff --git a/app/src/asset/pdfTheme.test.ts b/app/src/asset/pdfTheme.test.tsnew file mode 100644index 0000000000..83e9f7c420--- /dev/null+++ b/app/src/asset/pdfTheme.test.ts@@ -0,0 +1,38 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, transpileModule} from "typescript";++test("PDF theme changes patch only the selected mode and never mutate a stale captured configuration", () => {+ const captured = {light: "light", dark: "dark", annoColor: "red"};+ const appearance = {mode: 0, pdfTheme: captured};+ const siyuan = {config: {appearance, readonly: false}, isPublish: false};+ const saved: unknown[][] = [];+ const button = () => ({classList: {toggle() {}}, click: () => {},+ addEventListener(_event: string, listener: () => void) { this.click = listener; }});+ const light = button();+ const dark = button();+ const outer = {classList: {toggle() {}}};+ const exports = {} as typeof import("./pdfViewer");+ runInNewContext(transpileModule(readFileSync("src/asset/pdfViewer.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS},+ }).outputText, {exports, window: {siyuan}, require: () => ({+ patchAppearancePreference: (...args: unknown[]) => {saved.push(args);},+ })});+ exports.bindPdfTheme({firstElementChild: outer, querySelector: (selector: string) =>+ selector === "#pdfLight" ? light : dark} as unknown as HTMLElement);+ appearance.pdfTheme = {light: "light", dark: "light", annoColor: "blue"};+ dark.click();+ appearance.mode = 1;+ light.click();+ assert.deepEqual(saved, [["pdfTheme.light", "dark"], ["pdfTheme.dark", "light"]]);+ assert.deepEqual(captured, {light: "light", dark: "dark", annoColor: "red"});+ assert.equal(appearance.pdfTheme.annoColor, "blue");+ siyuan.config.readonly = true;+ dark.click();+ siyuan.config.readonly = false;+ siyuan.isPublish = true;+ light.click();+ assert.equal(saved.length, 2);+});diff --git a/app/src/asset/pdfViewer.ts b/app/src/asset/pdfViewer.tsindex 09333e7117..ab0a0f8d17 100644--- a/app/src/asset/pdfViewer.ts+++ b/app/src/asset/pdfViewer.ts@@ -1,5 +1,5 @@import {Constants} from "../constants";-import {setStorageVal} from "../protyle/util/compatibility";+import {patchAppearancePreference} from "../config/tabs/appearancePreferences";const PDF_JS_VERSION = "6.4.299-siyuan.1";@@ -67,21 +67,17 @@ export const loadPdfViewerModule = () => {};export const bindPdfTheme = (element: HTMLElement) => {- const localPDF = window.siyuan.storage[Constants.LOCAL_PDFTHEME];+ const localPDF = window.siyuan.config.appearance.pdfTheme;const darkElement = element.querySelector("#pdfDark") as HTMLElement;const lightElement = element.querySelector("#pdfLight") as HTMLElement;const outerElement = element.firstElementChild;const pdfTheme = window.siyuan.config.appearance.mode === 0 ? localPDF.light : localPDF.dark;const setTheme = (theme: "light" | "dark") => {- if (window.siyuan.config.appearance.mode === 0) {- localPDF.light = theme;- } else {- localPDF.dark = theme;- }+ if (window.siyuan.config.readonly || window.siyuan.isPublish) return;outerElement.classList.toggle("pdf__outer--dark", theme === "dark");lightElement.classList.toggle("toggled", theme === "light");darkElement.classList.toggle("toggled", theme === "dark");- setStorageVal(Constants.LOCAL_PDFTHEME, localPDF);+ void patchAppearancePreference(`pdfTheme.${window.siyuan.config.appearance.mode === 0 ? "light" : "dark"}`, theme);};outerElement.classList.toggle("pdf__outer--dark", pdfTheme === "dark");lightElement.classList.toggle("toggled", pdfTheme !== "dark");diff --git a/app/src/business/openRecentDocs.ts b/app/src/business/openRecentDocs.tsindex f809cd50b1..47bfc5e106 100644--- a/app/src/business/openRecentDocs.ts+++ b/app/src/business/openRecentDocs.ts@@ -1,9 +1,10 @@+import {fileConfigApi} from "../config/tabs/fileRuntime";import {fetchPost, fetchSyncPost} from "../util/fetch";import {getFileTreeIconHTML} from "../emoji/fileTreeIcon";import {Constants} from "../constants";import {escapeHtml} from "../util/escape";import {isWindow} from "../util/functions";-import {setStorageVal, updateHotkeyTip} from "../protyle/util/compatibility";+import {updateHotkeyTip} from "../protyle/util/compatibility";import {getAllDocks} from "../layout/getAll";import {getDockHotkey} from "../layout/dock/hotkey";import {Dialog} from "../dialog";@@ -104,7 +105,7 @@ export const openRecentDocs = (openOnly = false) => {}return;}- const sortBy = window.siyuan.storage[Constants.LOCAL_RECENT_DOCS].type as TRecentDocsSort;+ const sortBy = window.siyuan.config.fileTree.recentDocsSort as TRecentDocsSort;fetchPost("/api/storage/getRecentDocs", {sortBy}, (response) => {const dialog = new Dialog({positionId: Constants.DIALOG_RECENTDOCS,@@ -167,8 +168,9 @@ export const openRecentDocs = (openOnly = false) => {response = newResponse;renderRecentDocsContent(newResponse.data, dialog.element, searchElement.value);});- window.siyuan.storage[Constants.LOCAL_RECENT_DOCS].type = sortSelect.value;- setStorageVal(Constants.LOCAL_RECENT_DOCS, window.siyuan.storage[Constants.LOCAL_RECENT_DOCS]);+ if (!window.siyuan.config.readonly && !window.siyuan.isPublish) {+ void fileConfigApi.patch("recentDocsSort", sortSelect.value);+ }});renderRecentDocsContent(response.data, dialog.element);diff --git a/app/src/config/setting/sync.ts b/app/src/config/setting/sync.tsindex 463175c6cd..91503b3fbe 100644--- a/app/src/config/setting/sync.ts+++ b/app/src/config/setting/sync.ts@@ -109,7 +109,7 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {const remountTabs = new Set<TSettingTab>();for (const namespace of namespaces.has("*") ? [...simple, "editor", "export", "keymap", "appearance", "ai", "sync"] : namespaces) {const tab = getSettingTabDefs().find(definition => definition.id === (tabs[namespace] || namespace));- if (tab && tab.id !== "ocr") remountTabs.add(tab.id);+ if (tab && tab.id !== "ocr" && tab.id !== "appearance") remountTabs.add(tab.id);}if (accessChanged) remountTabs.add("access");remountTabs.forEach(tab => { void remountOpenSettingTab(tab); });diff --git a/app/src/config/setting/windowRuntime.test.ts b/app/src/config/setting/windowRuntime.test.tsindex 439216832c..ea905dc9ef 100644--- a/app/src/config/setting/windowRuntime.test.ts+++ b/app/src/config/setting/windowRuntime.test.ts@@ -43,19 +43,7 @@ const fixture = (deferSnippetScripts = false) => {},getHostCapabilities: () => ({customAppearance: true}),ensureLute: async () => { calls.push({type: "lute"}); },- onAgentStreamingMarkdownStorageChanged: (key: string) => calls.push({type: "storage", value: key}),- onCompactModeStorageChanged: (key: string) => {- if (key === "compact") calls.push({type: "compact", value: storage[key]});- },- refreshCompactMode: async (guard: () => boolean) => {- if (guard()) calls.push({type: "compact-refresh"});- },- onMenuMouseScrollStorageChanged: (key: string) => {- if (key === "mouse-scroll") calls.push({type: "mouse-scroll", value: storage[key]});- },- refreshMenuMouseScroll: async (guard: () => boolean) => {- if (guard()) calls.push({type: "mouse-scroll-refresh"});- },+ refreshSettingConfig: async () => { calls.push({type: "config-refresh"}); },genNotebookOption: (id: string, _box: string, shorthand: boolean, filter: (notebook: unknown) => boolean) => {calls.push({type: "options", value: {id, shorthand, filter}});return '<option value="">Current</option><option value="a">Renamed</option>';@@ -204,40 +192,13 @@ test("settings receive all zoom storage messages without persistence or owner toassert.equal(f.storage.zoom, undefined);});-test("settings apply compact mode after every storage update and stop refreshing after disposal", async () => {- const f = fixture();- const send = (cmd: string, data: unknown) => f.runtime.handleMessage({cmd, data} as IWebSocketData);- send("setLocalStorageVal", {key: "compact", val: true});- send("removeLocalStorageVal", {key: "compact"});- send("setLocalStorageVals", {keyVals: {compact: false}});- send("removeLocalStorageVals", {keys: ["compact"]});- assert.deepEqual(f.calls.filter(call => call.type === "compact").map(call => call.value),- [true, undefined, false, undefined]);- await f.runtime.reconnect();- assert.equal(f.calls.filter(call => call.type === "compact-refresh").length, 1);- f.setActive(false);- send("setLocalStorageVal", {key: "compact", val: true});- await f.runtime.reconnect();- assert.equal(f.storage.compact, undefined);- assert.equal(f.calls.filter(call => call.type === "compact-refresh").length, 1);-});--test("settings synchronize menu mouse scrolling for single and batch preference changes and reconnects", async () => {+test("settings reconnect refreshes configuration once and stops after disposal", async () => {const f = fixture();- const send = (cmd: string, data: unknown) => f.runtime.handleMessage({cmd, data} as IWebSocketData);- send("setLocalStorageVal", {key: "mouse-scroll", val: true});- send("removeLocalStorageVal", {key: "mouse-scroll"});- send("setLocalStorageVals", {keyVals: {"mouse-scroll": false}});- send("removeLocalStorageVals", {keys: ["mouse-scroll"]});- assert.deepEqual(f.calls.filter(call => call.type === "mouse-scroll").map(call => call.value),- [true, undefined, false, undefined]);await f.runtime.reconnect();- assert.equal(f.calls.filter(call => call.type === "mouse-scroll-refresh").length, 1);+ assert.equal(f.calls.filter(call => call.type === "config-refresh").length, 1);f.setActive(false);- send("setLocalStorageVal", {key: "mouse-scroll", val: true});await f.runtime.reconnect();- assert.equal(f.storage["mouse-scroll"], undefined);- assert.equal(f.calls.filter(call => call.type === "mouse-scroll-refresh").length, 1);+ assert.equal(f.calls.filter(call => call.type === "config-refresh").length, 1);});test("snippets assign configuration first and wait for Lute before rendering JS", async () => {diff --git a/app/src/config/setting/windowRuntime.ts b/app/src/config/setting/windowRuntime.tsindex f864b0fe68..f68081c34f 100644--- a/app/src/config/setting/windowRuntime.ts+++ b/app/src/config/setting/windowRuntime.ts@@ -7,9 +7,7 @@ import {isMac} from "../../protyle/util/compatibility";import {setToolbarLeftMac} from "../../util/functions";import {ensureLute} from "../../protyle/util/lute";import {renderSnippet} from "../util/snippets";-import {onAgentStreamingMarkdownStorageChanged} from "../tabs/ai/agentStreamingMarkdown";-import {onCompactModeStorageChanged, refreshCompactMode} from "../tabs/compactMode";-import {onMenuMouseScrollStorageChanged, refreshMenuMouseScroll} from "../tabs/menuMouseScroll";+import {refreshSettingConfig} from "./sync";import type {ISettingsWindowHost} from "./windowContext";let notebookRefresh = () => Promise.resolve();@@ -177,9 +175,6 @@ export const createSettingsWindowRuntime = (isActive: () => boolean, deferSnippe};const onStorageChanged = (keys: string[]) => {- keys.forEach(onAgentStreamingMarkdownStorageChanged);- keys.forEach(onCompactModeStorageChanged);- keys.forEach(onMenuMouseScrollStorageChanged);if (keys.includes(Constants.LOCAL_ZOOM)) {zoomRevision++;applyZoom();@@ -224,8 +219,7 @@ export const createSettingsWindowRuntime = (isActive: () => boolean, deferSnippeconst reconnect = async () => {if (!isActive()) return;- await Promise.all([refreshNotebooks(), refreshSnippets(true), refreshZoom(), refreshCompactMode(isActive),- refreshMenuMouseScroll(isActive)]);+ await Promise.all([refreshNotebooks(), refreshSnippets(true), refreshZoom(), refreshSettingConfig()]);};return {applyZoom, refreshNotebooks, refreshSnippets, enableSnippetScripts, handleMessage, reconnect};};diff --git a/app/src/config/tabs/ai/agentStreamingMarkdown.test.ts b/app/src/config/tabs/ai/agentStreamingMarkdown.test.tsindex 7352960b50..240ffbbba5 100644--- a/app/src/config/tabs/ai/agentStreamingMarkdown.test.ts+++ b/app/src/config/tabs/ai/agentStreamingMarkdown.test.ts@@ -2,66 +2,54 @@ import * as assert from "node:assert/strict";import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";-import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {ModuleKind, transpileModule} from "typescript";+import {createSectionRuntime} from "../../util/sectionRuntime";-const compiled = transpileModule(readFileSync("src/config/tabs/ai/agentStreamingMarkdown.ts", "utf8"), {- compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},-}).outputText;--const createPreference = (values: Record<string, unknown> = {}, readonly = false) => {- const events: {type: string}[] = [];- const storage = {...values};+test("streaming Markdown uses confirmed AI preferences and preserves readonly protection", async () => {+ const siyuan = {config: {ai: {agent: {streamingMarkdown: false}}, readonly: false}, isPublish: false,+ storage: {"siyuan-agent-streaming-markdown": true}};+ const saved: unknown[][] = [];const exports = {} as typeof import("./agentStreamingMarkdown");- runInNewContext(compiled, {- exports,- require: (id: string) => {- assert.equal(id, "../../../protyle/util/compatibility");- return {setStorageVal: (key: string, value: unknown) => {- if (!readonly) {- values[key] = value;- }- }};- },- CustomEvent: class {- constructor(public type: string) {}- },- window: {- siyuan: {storage},- dispatchEvent: (event: {type: string}) => events.push(event),- },- });- return {...exports, events, values, storage};-};--test("streaming Markdown persists an explicit opt-in through SiYuan storage", () => {- const preference = createPreference();- assert.equal(preference.isAgentStreamingMarkdownEnabled(), false);- for (const value of ["", "false", "true", "1", "invalid", "TRUE", false, 1]) {- preference.storage[preference.AGENT_STREAMING_MARKDOWN_KEY] = value;- assert.equal(preference.isAgentStreamingMarkdownEnabled(), false);- }- preference.setAgentStreamingMarkdownEnabled(true);- assert.equal(preference.isAgentStreamingMarkdownEnabled(), true);- assert.equal(Object.keys(preference.values).length, 1);- assert.equal(createPreference(preference.values).isAgentStreamingMarkdownEnabled(), true);- assert.equal(preference.events[0].type, preference.AGENT_STREAMING_MARKDOWN_CHANGED_EVENT);- preference.setAgentStreamingMarkdownEnabled(false);- assert.equal(createPreference(preference.values).isAgentStreamingMarkdownEnabled(), false);+ runInNewContext(transpileModule(readFileSync("src/config/tabs/ai/agentStreamingMarkdown.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS},+ }).outputText, {exports, window: {siyuan}, require: () => ({aiConfigApi: {+ patch: async (...args: unknown[]) => {saved.push(args);},+ }})});+ assert.equal(exports.isAgentStreamingMarkdownEnabled(), false);+ await exports.setAgentStreamingMarkdownEnabled(true);+ assert.deepEqual(saved, [["agent.streamingMarkdown", true]]);+ assert.equal(exports.isAgentStreamingMarkdownEnabled(), false);+ siyuan.config.ai.agent.streamingMarkdown = true;+ assert.equal(exports.isAgentStreamingMarkdownEnabled(), true);+ siyuan.config.readonly = true;+ await exports.setAgentStreamingMarkdownEnabled(false);+ siyuan.config.readonly = false;+ siyuan.isPublish = true;+ await exports.setAgentStreamingMarkdownEnabled(false);+ assert.equal(saved.length, 1);});-test("readonly mode allows a session-only preference", () => {- const preference = createPreference({}, true);- assert.equal(preference.isAgentStreamingMarkdownEnabled(), false);- preference.setAgentStreamingMarkdownEnabled(true);- assert.equal(preference.isAgentStreamingMarkdownEnabled(), true);- assert.equal(createPreference(preference.values).isAgentStreamingMarkdownEnabled(), false);- preference.setAgentStreamingMarkdownEnabled(false);- assert.equal(preference.isAgentStreamingMarkdownEnabled(), false);-});--test("reads updates made by other windows instead of caching persisted values", () => {- const preference = createPreference();- preference.setAgentStreamingMarkdownEnabled(true);- delete preference.storage[preference.AGENT_STREAMING_MARKDOWN_KEY];- assert.equal(preference.isAgentStreamingMarkdownEnabled(), false);+test("confirmed AI updates notify streaming renderers once per changed preference", async () => {+ const config = {ai: {agent: {streamingMarkdown: false}}};+ const events: string[] = [];+ const exports = {} as typeof import("./aiRuntime");+ runInNewContext(transpileModule(readFileSync("src/config/tabs/ai/aiRuntime.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS},+ }).outputText, {+ exports, window: {siyuan: {config}, dispatchEvent: (event: Event) => events.push(event.type)},+ CustomEvent: class { constructor(public type: string) {} },+ require: () => ({+ AGENT_STREAMING_MARKDOWN_CHANGED_EVENT: "siyuan-agent-streaming-markdown-changed",+ createConfigNamespaceApi: (options: {namespace: string; getConfig: () => typeof config.ai;+ setConfig: (data: typeof config.ai) => void;+ reactions: Parameters<typeof createSectionRuntime<typeof config.ai>>[0]["reactions"]}) =>+ createSectionRuntime({namespace: options.namespace, get: options.getConfig, set: options.setConfig,+ reactions: options.reactions}),+ }),+ });+ await exports.aiConfigApi.apply({agent: {streamingMarkdown: true}} as Config.IAI);+ await exports.aiConfigApi.apply({agent: {streamingMarkdown: true}} as Config.IAI);+ await exports.aiConfigApi.apply({agent: {streamingMarkdown: false}} as Config.IAI);+ assert.equal(events.filter(name => name === "siyuan-agent-streaming-markdown-changed").length, 2);+ assert.equal(config.ai.agent.streamingMarkdown, false);});diff --git a/app/src/config/tabs/ai/agentStreamingMarkdown.ts b/app/src/config/tabs/ai/agentStreamingMarkdown.tsindex dbcbe1d5b5..98b7ee548b 100644--- a/app/src/config/tabs/ai/agentStreamingMarkdown.ts+++ b/app/src/config/tabs/ai/agentStreamingMarkdown.ts@@ -1,20 +1,12 @@-import {setStorageVal} from "../../../protyle/util/compatibility";+import {aiConfigApi} from "./aiRuntime";-export const AGENT_STREAMING_MARKDOWN_KEY = "siyuan-agent-streaming-markdown";export const AGENT_STREAMING_MARKDOWN_CHANGED_EVENT = "siyuan-agent-streaming-markdown-changed";export const isAgentStreamingMarkdownEnabled = (): boolean => {- return window.siyuan.storage[AGENT_STREAMING_MARKDOWN_KEY] === true;+ return window.siyuan.config.ai?.agent?.streamingMarkdown === true;};-export const onAgentStreamingMarkdownStorageChanged = (key: string): void => {- if (key === AGENT_STREAMING_MARKDOWN_KEY) {- window.dispatchEvent(new CustomEvent(AGENT_STREAMING_MARKDOWN_CHANGED_EVENT));- }-};--export const setAgentStreamingMarkdownEnabled = (enabled: boolean): void => {- window.siyuan.storage[AGENT_STREAMING_MARKDOWN_KEY] = enabled;- setStorageVal(AGENT_STREAMING_MARKDOWN_KEY, enabled);- onAgentStreamingMarkdownStorageChanged(AGENT_STREAMING_MARKDOWN_KEY);+export const setAgentStreamingMarkdownEnabled = (enabled: boolean) => {+ if (window.siyuan.config.readonly || window.siyuan.isPublish) return;+ return aiConfigApi.patch("agent.streamingMarkdown", enabled);};diff --git a/app/src/config/tabs/ai/aiRuntime.ts b/app/src/config/tabs/ai/aiRuntime.tsindex a20c014d83..d63f1b087f 100644--- a/app/src/config/tabs/ai/aiRuntime.ts+++ b/app/src/config/tabs/ai/aiRuntime.ts@@ -1,4 +1,5 @@import {createConfigNamespaceApi} from "../../util/namespaceApi";+import {AGENT_STREAMING_MARKDOWN_CHANGED_EVENT} from "./agentStreamingMarkdown";export const AI_CONFIG_CHANGED_EVENT = "siyuan-ai-config-changed";@@ -11,7 +12,10 @@ const aiConfigNamespaceApi = createConfigNamespaceApi<Config.IAI>({setConfig: (data) => {window.siyuan.config.ai = data;},- reactions: [{name: "model-pickers", changed: () => true, apply: () => {+ reactions: [{name: "streaming-markdown", changed: (old, next) =>+ old.agent?.streamingMarkdown !== next.agent?.streamingMarkdown, apply: () => {+ window.dispatchEvent(new CustomEvent(AGENT_STREAMING_MARKDOWN_CHANGED_EVENT));+ }}, {name: "model-pickers", changed: () => true, apply: () => {window.dispatchEvent(new CustomEvent(AI_CONFIG_CHANGED_EVENT));}}],});diff --git a/app/src/config/tabs/appearancePreferences.test.ts b/app/src/config/tabs/appearancePreferences.test.tsnew file mode 100644index 0000000000..f07f647227--- /dev/null+++ b/app/src/config/tabs/appearancePreferences.test.ts@@ -0,0 +1,59 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, transpileModule} from "typescript";++const {parse} = require("ifdef-loader/preprocessor");++for (const mobile of [false, true]) {+ test(`confirmed preferences update open outlines, PDF readers and mobile controls in place (mobile=${mobile})`, async () => {+ const appearance = {mode: 0, outlineKeepCurrentExpand: true, pdfTheme: {light: "dark", dark: "light"}};+ const siyuan = {config: {appearance, readonly: false}, isPublish: false};+ const classes = (initial: string[] = []) => {+ const values = new Set(initial);+ return {contains: (key: string) => values.has(key), toggle: (key: string, enabled: boolean) => {+ if (enabled) values.add(key); else values.delete(key);+ }};+ };+ const outlines = [{classList: classes(["block__icon"])}, {classList: classes(["toolbar__icon"])}];+ const light = {classList: classes()};+ const dark = {classList: classes()};+ const pdf = {classList: classes(), querySelector: (selector: string) => selector === "#pdfLight" ? light : dark};+ const calls: string[] = [];+ const patches: unknown[][] = [];+ const exports = {} as typeof import("./appearancePreferences");+ const source = parse(readFileSync("src/config/tabs/appearancePreferences.ts", "utf8"), {MOBILE: mobile}, false, true);+ runInNewContext(transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText, {+ exports, window: {siyuan}, document: {querySelectorAll: (selector: string) =>+ selector === ".pdf__outer" ? [pdf] : outlines},+ require: () => ({+ applyCompactMode: () => calls.push("compact"), syncMenuMouseScroll: () => calls.push("scroll"),+ syncSidebarSetting: () => calls.push("sidebar"), syncMobileBarsSetting: () => calls.push("bars-controls"),+ updateSidebarButtons: () => calls.push("sidebar-buttons"), showMobileBars: () => calls.push("bars"),+ appearanceConfigApi: {patch: async (...args: unknown[]) => { patches.push(args); }},+ }),+ });+ exports.syncAppearancePreferences();+ assert.equal(outlines[0].classList.contains("block__icon--active"), true);+ assert.equal(outlines[1].classList.contains("toolbar__icon--active"), true);+ assert.equal(pdf.classList.contains("pdf__outer--dark"), true);+ assert.equal(light.classList.contains("toggled"), false);+ assert.equal(dark.classList.contains("toggled"), true);+ assert.equal(calls.includes("sidebar"), mobile);+ assert.equal(calls.includes("bars"), mobile);+ appearance.mode = 1;+ appearance.outlineKeepCurrentExpand = false;+ exports.syncAppearancePreferences();+ assert.equal(outlines[0].classList.contains("block__icon--active"), false);+ assert.equal(outlines[1].classList.contains("toolbar__icon--active"), false);+ assert.equal(pdf.classList.contains("pdf__outer--dark"), false);+ await exports.patchAppearancePreference("pdfTheme.light", "light");+ siyuan.config.readonly = true;+ await exports.patchAppearancePreference("pdfTheme.dark", "dark");+ siyuan.config.readonly = false;+ siyuan.isPublish = true;+ await exports.patchAppearancePreference("mobileBars.autoHide", false);+ assert.deepEqual(patches, [["pdfTheme.light", "light"]]);+ });+}diff --git a/app/src/config/tabs/appearancePreferences.ts b/app/src/config/tabs/appearancePreferences.tsnew file mode 100644index 0000000000..a71edaa3a9--- /dev/null+++ b/app/src/config/tabs/appearancePreferences.ts@@ -0,0 +1,37 @@+import {appearanceConfigApi} from "./appearanceRuntime";+import {applyCompactMode} from "./compactMode";+import {syncMenuMouseScroll} from "./menuMouseScroll";+/// #if MOBILE+import {showMobileBars} from "../../mobile/util/mobileBars";+import {updateSidebarButtons} from "../../mobile/util/sidebarButtons";+import {syncSidebarSetting} from "../../mobile/util/sidebarSetting";+import {syncMobileBarsSetting} from "../../mobile/util/mobileBarsSetting";+/// #endif++export const patchAppearancePreference = (path: string, value: unknown) => {+ if (window.siyuan.config.readonly || window.siyuan.isPublish) return Promise.resolve();+ return appearanceConfigApi.patch(path, value);+};++// 配置确认后原位刷新已打开的面板和控件,保持当前交互与滚动位置。+export const syncAppearancePreferences = () => {+ const appearance = window.siyuan.config.appearance;+ applyCompactMode();+ syncMenuMouseScroll();+ document.querySelectorAll<HTMLElement>('[data-type="keepCurrentExpand"]').forEach(icon => {+ icon.classList.toggle(icon.classList.contains("toolbar__icon") ? "toolbar__icon--active" : "block__icon--active",+ appearance.outlineKeepCurrentExpand);+ });+ const theme = appearance.mode === 0 ? appearance.pdfTheme.light : appearance.pdfTheme.dark;+ document.querySelectorAll<HTMLElement>(".pdf__outer").forEach(outer => {+ outer.classList.toggle("pdf__outer--dark", theme === "dark");+ outer.querySelector("#pdfLight")?.classList.toggle("toggled", theme === "light");+ outer.querySelector("#pdfDark")?.classList.toggle("toggled", theme === "dark");+ });+ /// #if MOBILE+ syncSidebarSetting();+ syncMobileBarsSetting();+ updateSidebarButtons();+ showMobileBars();+ /// #endif+};diff --git a/app/src/config/tabs/appearanceRuntime.test.ts b/app/src/config/tabs/appearanceRuntime.test.tsindex 148a69d8fa..a69fa7e41c 100644--- a/app/src/config/tabs/appearanceRuntime.test.ts+++ b/app/src/config/tabs/appearanceRuntime.test.ts@@ -9,7 +9,7 @@ import {createSectionRuntime} from "../util/sectionRuntime";const {parse} = require("ifdef-loader/preprocessor");for (const mobile of [true, false]) {- for (const change of ["gradient", "duplicate", "theme", "initial", "font", "font-reset"] as const) {+ for (const change of ["gradient", "duplicate", "theme", "initial", "font", "font-reset", "compact", "scroll", "pdf", "outline", "mobile-bars"] as const) {test(`appearance updates preserve gradient controls without skipping theme initialization (${change}, mobile=${mobile})`, async () => {const source = readFileSync(resolve(process.cwd(), "src/config/tabs/appearanceRuntime.ts"), "utf8");const processed = parse(source, {MOBILE: mobile, BROWSER: true}, false, true);@@ -21,6 +21,9 @@ for (const mobile of [true, false]) {const next = change === "initial" ? appearance : {...appearance,mode: change === "theme" ? 1 : 0,+ compactMode: change === "compact", menuMouseScroll: change === "scroll",+ pdfTheme: change === "pdf" ? {light: "dark"} : undefined,+ outlineKeepCurrentExpand: change === "outline", mobileBars: change === "mobile-bars" ? {autoHide: false} : undefined,bodyGradient: {mode: change === "duplicate" ? "auto" : "custom"},globalFontFamilies: change === "font" ? [{family: "Arial", weight: 700}] : [],};@@ -50,7 +53,7 @@ for (const mobile of [true, false]) {moduleExports.appearanceConfigApi.apply(next);await pending;assert.equal(siyuan.config.appearance, next);- const updatesInPlace = change === "gradient" || change === "duplicate";+ const updatesInPlace = ["gradient", "duplicate", "compact", "scroll", "pdf", "outline", "mobile-bars"].includes(change);assert.equal(calls.includes("syncBodyGradient"), updatesInPlace);assert.equal(calls.includes("setBodyHighlight"), updatesInPlace);assert.equal(calls.includes("loadAssets"), !updatesInPlace);diff --git a/app/src/config/tabs/appearanceRuntime.ts b/app/src/config/tabs/appearanceRuntime.tsindex cb6a6fa60d..42c7550457 100644--- a/app/src/config/tabs/appearanceRuntime.ts+++ b/app/src/config/tabs/appearanceRuntime.ts@@ -24,6 +24,7 @@ import {createSectionRuntime} from "../util/sectionRuntime";import {syncBodyGradient} from "./bodyGradient";import {refreshDynamicIcons} from "../../emoji/dynamicIcon";import {closeSettingsWindow, isSettingsWindow} from "../setting/windowContext";+import {syncAppearancePreferences} from "./appearancePreferences";/** 主题模式下拉框初值:合并 mode / modeOS */export const appearanceThemeModeValue = (): number =>@@ -73,17 +74,14 @@ const applyAppearanceConfig = async (data: Config.IAppearance, refresh?: IAppearconst changedPackages = refresh && invalidateAppearancePackages(refresh.themes || [], refresh.icons || [], refresh.revision);const themeChanged = changedPackages?.themes.some(name => name === getCurrentThemeName(prevAppearance) ||name === getCurrentThemeName(data));- // 仅更新背景渐变时原位同步控件,避免整页重建期间的布局变化引起滚动抖动。+ // 阅读和控件偏好原位应用,避免整页重建期间的布局变化引起滚动抖动。// 启动初始化传入当前配置本身,需要完整加载外观资源;重复推送仍使用原位同步。const appearanceKeys = Object.keys({...prevAppearance, ...data}) as Array<keyof Config.IAppearance>;- if (!refresh && prevAppearance !== data &&- appearanceKeys.every(key => key === "bodyGradient" ||- JSON.stringify(prevAppearance[key]) === JSON.stringify(data[key]))) {- window.siyuan.config.appearance = data;- setBodyHighlight(data.bodyGradient);- syncBodyGradient();- return;- }+ const inPlaceKeys = new Set(["bodyGradient", "compactMode", "menuMouseScroll", "pdfTheme",+ "outlineKeepCurrentExpand", "mobileBars"]);+ const inPlace = !refresh && prevAppearance !== data &&+ appearanceKeys.every(key => inPlaceKeys.has(key) ||+ JSON.stringify(prevAppearance[key]) === JSON.stringify(data[key]));const unloadChangedTheme = themeChanged && prevAppearance.themeJS && isCurrentThemeSupported(prevAppearance, getFrontend());if ((unloadChangedTheme || shouldUnloadThemeScript(prevAppearance, data, getFrontend())) && !await unloadThemeScript()) {if (closeSettingsWindow()) return;@@ -101,6 +99,17 @@ const applyAppearanceConfig = async (data: Config.IAppearance, refresh?: IAppearget: () => prevAppearance,set: next => { window.siyuan.config.appearance = next; },reactions: [{+ name: "preferences",+ changed: () => true,+ apply: () => { syncAppearancePreferences(); },+ }, {+ name: "gradient",+ changed: () => inPlace,+ apply: () => {+ setBodyHighlight(data.bodyGradient);+ syncBodyGradient();+ },+ }, {name: "bars",changed: () => true,apply: (old, next) => {@@ -113,7 +122,7 @@ const applyAppearanceConfig = async (data: Config.IAppearance, refresh?: IAppear},}, {name: "appearance-resources",- changed: () => true,+ changed: () => !inPlace,apply: async (old, next) => {await loadAssets(next);if (JSON.stringify(next.globalFontFamilies) !== JSON.stringify(old.globalFontFamilies)) {diff --git a/app/src/config/tabs/compactMode.test.ts b/app/src/config/tabs/compactMode.test.tsindex 1d87da53ac..97aa710b48 100644--- a/app/src/config/tabs/compactMode.test.ts+++ b/app/src/config/tabs/compactMode.test.ts@@ -2,133 +2,59 @@ import * as assert from "node:assert/strict";import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";-import {ModuleKind, ScriptTarget, transpileModule} from "typescript";--const compiled = transpileModule(readFileSync("src/config/tabs/compactMode.ts", "utf8"), {- compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},-}).outputText;+import {ModuleKind, transpileModule} from "typescript";const fixture = (frontend = "desktop", mobileApp = false) => {+ const appearance = {compactMode: false};+ const siyuan = {config: {appearance, readonly: false}, isPublish: false, isReady: true,+ storage: {"local-compact-mode": true, "local-menu-mouse-scroll": true}};const attributes = new Map<string, string>();const input = {checked: false};- const storage: Record<string, unknown> = {};- const config = {readonly: false};const saved: unknown[][] = [];- const requests: ((response: unknown) => void)[] = [];const events: string[] = [];- const siyuan = {storage, config, isPublish: false, isReady: true};const exports = {} as typeof import("./compactMode");- runInNewContext(compiled, {- exports, Event,+ runInNewContext(transpileModule(readFileSync("src/config/tabs/compactMode.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS},+ }).outputText, {exports, Event,window: {siyuan, dispatchEvent: (event: Event) => events.push(event.type)},- document: {- documentElement: {- hasAttribute: (name: string) => attributes.has(name),- setAttribute: (name: string, value: string) => attributes.set(name, value),- removeAttribute: (name: string) => attributes.delete(name),- },- querySelectorAll: () => [input],- },- require: () => ({- Constants: {LOCAL_COMPACT_MODE: "compact", ATTRIBUTE_UI_DENSITY: "data-ui-density"},- getFrontend: () => frontend,- isInMobileApp: () => mobileApp,- setStorageVal: (...args: unknown[]) => saved.push(args),- fetchSyncPost: () => new Promise(resolve => requests.push(resolve)),+ document: {querySelectorAll: () => [input], documentElement: {+ hasAttribute: (key: string) => attributes.has(key),+ setAttribute: (key: string, value: string) => attributes.set(key, value),+ removeAttribute: (key: string) => attributes.delete(key),+ }},+ require: () => ({getFrontend: () => frontend, isInMobileApp: () => mobileApp,+ Constants: {ATTRIBUTE_UI_DENSITY: "data-ui-density"},+ appearanceConfigApi: {patch: async (path: string, value: boolean) => {saved.push([path, value]);}},}),});- return {api: exports, attributes, input, storage, config, saved, requests, events, siyuan};+ return {api: exports, appearance, siyuan, saved, events, input, attributes};};-test("compact mode defaults to off and only accepts an explicit boolean preference", () => {- const f = fixture();- for (const value of [undefined, null, false, "true", 1]) {- f.storage.compact = value;- f.api.applyCompactMode();- assert.equal(f.attributes.has("data-ui-density"), false);- assert.equal(f.input.checked, false);- }- assert.deepEqual(f.events, []);-});--test("compact mode persists through the workspace preference store and updates open controls", () => {+test("compactMode ignores retired KV values and reads confirmed configuration updates", () => {const f = fixture();- f.api.setCompactModeEnabled(true);- assert.deepEqual(f.saved, [["compact", true]]);- assert.equal(f.storage.compact, true);- assert.equal(f.attributes.get("data-ui-density"), "compact");+ f.api.applyCompactMode();+ assert.equal(f.input.checked, false);+ f.appearance.compactMode = true;+ f.api.applyCompactMode();assert.equal(f.input.checked, true);+ f.appearance.compactMode = false;f.api.applyCompactMode();- assert.deepEqual(f.events, ["resize"]);- delete f.storage.compact;- f.api.onCompactModeStorageChanged("compact");- assert.equal(f.attributes.has("data-ui-density"), false);assert.equal(f.input.checked, false);- assert.deepEqual(f.events, ["resize", "resize"]);- f.api.onCompactModeStorageChanged("unrelated");- assert.equal(f.events.length, 2);});-test("mobile frontends and mobile apps retain their density and do not persist desktop changes", async () => {- for (const [frontend, mobileApp] of [["mobile", false], ["browser-mobile", false], ["browser-desktop", true]] as const) {- const f = fixture(frontend, mobileApp);- f.storage.compact = true;- f.api.applyCompactMode();- f.api.setCompactModeEnabled(false);- await f.api.refreshCompactMode();- assert.equal(f.attributes.has("data-ui-density"), false);- assert.equal(f.storage.compact, true);- assert.equal(f.saved.length, 0);- assert.equal(f.requests.length, 0);- }- for (const frontend of ["desktop", "desktop-window", "browser-desktop"]) {- assert.equal(fixture(frontend).api.isCompactModeAvailable(), true);- }-});--test("readonly and published sessions do not change the saved compact preference", () => {- for (const publish of [false, true]) {- const f = fixture();- f.config.readonly = !publish;- f.siyuan.isPublish = publish;- f.api.setCompactModeEnabled(true);- assert.equal(f.saved.length, 0);- assert.equal(f.storage.compact, undefined);- }-});--test("reconnection restores changes made while offline and removes a missing preference", async () => {+test("compactMode saves through the appearance namespace without optimistic config mutation", async () => {const f = fixture();- let refresh = f.api.refreshCompactMode();- f.requests.shift()({code: 0, data: {compact: true}});- await refresh;- assert.equal(f.attributes.get("data-ui-density"), "compact");- refresh = f.api.refreshCompactMode();- f.requests.shift()({code: 0, data: {}});- await refresh;- assert.equal(f.attributes.has("data-ui-density"), false);- assert.equal(f.saved.length, 0);+ await f.api.setCompactModeEnabled(true);+ assert.deepEqual(f.saved, [["compactMode", true]]);+ assert.equal(f.appearance.compactMode, false);});-test("stale reconnection reads cannot overwrite a push, a newer read or a closed window", async () => {- const f = fixture();- const stale = f.api.refreshCompactMode();- f.api.setCompactModeEnabled(true);- f.requests.shift()({code: 0, data: {compact: false}});- await stale;- assert.equal(f.api.isCompactModeEnabled(), true);- const first = f.api.refreshCompactMode();- const second = f.api.refreshCompactMode();- const completeFirst = f.requests.shift();- f.requests.shift()({code: 0, data: {compact: false}});- await second;- completeFirst({code: 0, data: {compact: true}});- await first;- assert.equal(f.api.isCompactModeEnabled(), false);- let active = true;- const closed = f.api.refreshCompactMode(() => active);- active = false;- f.requests.shift()({code: 0, data: {compact: true}});- await closed;- assert.equal(f.api.isCompactModeEnabled(), false);+test("compactMode rejects readonly, published and mobile writes", async () => {+ for (const kind of ["readonly", "publish", "mobile", "browser-mobile", "mobile-app"]) {+ const f = fixture(kind.includes("mobile") && kind !== "mobile-app" ? kind : "desktop", kind === "mobile-app");+ f.siyuan.config.readonly = kind === "readonly";+ f.siyuan.isPublish = kind === "publish";+ await f.api.setCompactModeEnabled(true);+ assert.deepEqual(f.saved, [], kind);+ }});diff --git a/app/src/config/tabs/compactMode.ts b/app/src/config/tabs/compactMode.tsindex 8a52446876..7b37a0635a 100644--- a/app/src/config/tabs/compactMode.ts+++ b/app/src/config/tabs/compactMode.ts@@ -1,15 +1,13 @@import {Constants} from "../../constants";-import {isInMobileApp, setStorageVal} from "../../protyle/util/compatibility";+import {isInMobileApp} from "../../protyle/util/compatibility";import {getFrontend} from "../../util/functions";-import {fetchSyncPost} from "../../util/fetch";--let revision = 0;+import {appearanceConfigApi} from "./appearanceRuntime";export const isCompactModeAvailable = () =>!isInMobileApp() && ["desktop", "desktop-window", "browser-desktop"].includes(getFrontend());export const isCompactModeEnabled = () =>- isCompactModeAvailable() && window.siyuan.storage?.[Constants.LOCAL_COMPACT_MODE] === true;+ isCompactModeAvailable() && window.siyuan.config.appearance?.compactMode === true;export const applyCompactMode = () => {const root = document.documentElement;@@ -29,25 +27,7 @@ export const applyCompactMode = () => {}};-export const onCompactModeStorageChanged = (key: string) => {- if (key !== Constants.LOCAL_COMPACT_MODE) return;- revision++;- applyCompactMode();-};-export const setCompactModeEnabled = (enabled: boolean) => {if (!isCompactModeAvailable() || window.siyuan.config.readonly || window.siyuan.isPublish) return;- window.siyuan.storage[Constants.LOCAL_COMPACT_MODE] = enabled;- onCompactModeStorageChanged(Constants.LOCAL_COMPACT_MODE);- return setStorageVal(Constants.LOCAL_COMPACT_MODE, enabled);-};--// 断线期间可能错过偏好推送;刷新期间的新设置优先于较早请求的结果。-export const refreshCompactMode = async (isActive = () => true) => {- if (!isCompactModeAvailable() || !isActive()) return;- const currentRevision = ++revision;- const response = await fetchSyncPost("/api/storage/getLocalStorage");- if (!isActive() || currentRevision !== revision || response.code !== 0) return;- window.siyuan.storage[Constants.LOCAL_COMPACT_MODE] = response.data[Constants.LOCAL_COMPACT_MODE] === true;- applyCompactMode();+ return appearanceConfigApi.patch("compactMode", enabled);};diff --git a/app/src/config/tabs/menuMouseScroll.test.ts b/app/src/config/tabs/menuMouseScroll.test.tsindex 5341337cd1..70d956e7c3 100644--- a/app/src/config/tabs/menuMouseScroll.test.ts+++ b/app/src/config/tabs/menuMouseScroll.test.ts@@ -2,103 +2,59 @@ import * as assert from "node:assert/strict";import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";-import {ModuleKind, ScriptTarget, transpileModule} from "typescript";--const compiled = transpileModule(readFileSync("src/config/tabs/menuMouseScroll.ts", "utf8"), {- compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},-}).outputText;+import {ModuleKind, transpileModule} from "typescript";const fixture = (frontend = "desktop", mobileApp = false) => {+ const appearance = {menuMouseScroll: false};+ const siyuan = {config: {appearance, readonly: false}, isPublish: false, isReady: true,+ storage: {"local-compact-mode": true, "local-menu-mouse-scroll": true}};+ const attributes = new Map<string, string>();const input = {checked: false};- const storage: Record<string, unknown> = {};- const siyuan = {storage, config: {readonly: false}, isPublish: false};const saved: unknown[][] = [];- const requests: ((response: unknown) => void)[] = [];+ const events: string[] = [];const exports = {} as typeof import("./menuMouseScroll");- runInNewContext(compiled, {- exports,- window: {siyuan},- document: {querySelectorAll: () => [input]},- require: () => ({- Constants: {LOCAL_MENU_MOUSE_SCROLL: "scroll"},- getFrontend: () => frontend,- isInMobileApp: () => mobileApp,- setStorageVal: (...args: unknown[]) => saved.push(args),- fetchSyncPost: () => new Promise(resolve => requests.push(resolve)),+ runInNewContext(transpileModule(readFileSync("src/config/tabs/menuMouseScroll.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS},+ }).outputText, {exports, Event,+ window: {siyuan, dispatchEvent: (event: Event) => events.push(event.type)},+ document: {querySelectorAll: () => [input], documentElement: {+ hasAttribute: (key: string) => attributes.has(key),+ setAttribute: (key: string, value: string) => attributes.set(key, value),+ removeAttribute: (key: string) => attributes.delete(key),+ }},+ require: () => ({getFrontend: () => frontend, isInMobileApp: () => mobileApp,+ Constants: {ATTRIBUTE_UI_DENSITY: "data-ui-density"},+ appearanceConfigApi: {patch: async (path: string, value: boolean) => {saved.push([path, value]);}},}),});- return {api: exports, input, storage, siyuan, saved, requests};+ return {api: exports, appearance, siyuan, saved, events, input, attributes};};-test("existing workspaces keep mouse scrolling off and persist explicit choices through workspace storage", () => {+test("menuMouseScroll ignores retired KV values and reads confirmed configuration updates", () => {const f = fixture();- for (const value of [undefined, null, false, "true", 1]) {- f.storage.scroll = value;- assert.equal(f.api.isMenuMouseScrollEnabled(), false);- }- f.api.setMenuMouseScrollEnabled(true);- assert.deepEqual(f.saved, [["scroll", true]]);+ f.api.syncMenuMouseScroll();+ assert.equal(f.input.checked, false);+ f.appearance.menuMouseScroll = true;+ f.api.syncMenuMouseScroll();assert.equal(f.input.checked, true);- delete f.storage.scroll;- f.api.onMenuMouseScrollStorageChanged("scroll");+ f.appearance.menuMouseScroll = false;+ f.api.syncMenuMouseScroll();assert.equal(f.input.checked, false);- f.api.setMenuMouseScrollEnabled(false);- assert.equal(f.storage.scroll, false);});-test("new workspace defaults supplied by storage enable scrolling and remain subject to the user's choice", async () => {+test("menuMouseScroll saves through the appearance namespace without optimistic config mutation", async () => {const f = fixture();- const refresh = f.api.refreshMenuMouseScroll();- f.requests.shift()({code: 0, data: {scroll: true}});- await refresh;- assert.equal(f.api.isMenuMouseScrollEnabled(), true);- assert.equal(f.input.checked, true);- assert.equal(f.saved.length, 0);- f.api.setMenuMouseScrollEnabled(false);- assert.equal(f.api.isMenuMouseScrollEnabled(), false);- assert.equal(f.input.checked, false);- assert.deepEqual(f.saved, [["scroll", false]]);+ await f.api.setMenuMouseScrollEnabled(true);+ assert.deepEqual(f.saved, [["menuMouseScroll", true]]);+ assert.equal(f.appearance.menuMouseScroll, false);});-test("menu mouse scrolling is available on desktop frontends and preserves mobile and readonly preferences", async () => {- for (const frontend of ["desktop", "desktop-window", "browser-desktop"]) {- assert.equal(fixture(frontend).api.isMenuMouseScrollAvailable(), true);+test("menuMouseScroll rejects readonly, published and mobile writes", async () => {+ for (const kind of ["readonly", "publish", "mobile", "browser-mobile", "mobile-app"]) {+ const f = fixture(kind.includes("mobile") && kind !== "mobile-app" ? kind : "desktop", kind === "mobile-app");+ f.siyuan.config.readonly = kind === "readonly";+ f.siyuan.isPublish = kind === "publish";+ await f.api.setMenuMouseScrollEnabled(true);+ assert.deepEqual(f.saved, [], kind);}- for (const [frontend, mobileApp] of [["mobile", false], ["browser-mobile", false], ["browser-desktop", true]] as const) {- const f = fixture(frontend, mobileApp);- f.storage.scroll = true;- f.api.setMenuMouseScrollEnabled(false);- await f.api.refreshMenuMouseScroll();- assert.equal(f.api.isMenuMouseScrollEnabled(), false);- assert.equal(f.storage.scroll, true);- assert.equal(f.saved.length, 0);- assert.equal(f.requests.length, 0);- }- for (const publish of [false, true]) {- const f = fixture();- f.siyuan.config.readonly = !publish;- f.siyuan.isPublish = publish;- f.api.setMenuMouseScrollEnabled(true);- assert.equal(f.saved.length, 0);- assert.equal(f.storage.scroll, undefined);- }-});--test("reconnection restores the preference without overwriting newer pushes or closed settings windows", async () => {- const f = fixture();- const refresh = f.api.refreshMenuMouseScroll();- f.requests.shift()({code: 0, data: {scroll: true}});- await refresh;- assert.equal(f.api.isMenuMouseScrollEnabled(), true);- const stale = f.api.refreshMenuMouseScroll();- f.api.setMenuMouseScrollEnabled(false);- f.requests.shift()({code: 0, data: {scroll: true}});- await stale;- assert.equal(f.api.isMenuMouseScrollEnabled(), false);- let active = true;- const closed = f.api.refreshMenuMouseScroll(() => active);- active = false;- f.requests.shift()({code: 0, data: {scroll: true}});- await closed;- assert.equal(f.api.isMenuMouseScrollEnabled(), false);});diff --git a/app/src/config/tabs/menuMouseScroll.ts b/app/src/config/tabs/menuMouseScroll.tsindex ea9295b167..9c4dd6feef 100644--- a/app/src/config/tabs/menuMouseScroll.ts+++ b/app/src/config/tabs/menuMouseScroll.ts@@ -1,41 +1,20 @@-import {Constants} from "../../constants";-import {isInMobileApp, setStorageVal} from "../../protyle/util/compatibility";+import {isInMobileApp} from "../../protyle/util/compatibility";import {getFrontend} from "../../util/functions";-import {fetchSyncPost} from "../../util/fetch";--let revision = 0;+import {appearanceConfigApi} from "./appearanceRuntime";export const isMenuMouseScrollAvailable = () =>!isInMobileApp() && ["desktop", "desktop-window", "browser-desktop"].includes(getFrontend());export const isMenuMouseScrollEnabled = () =>- isMenuMouseScrollAvailable() && window.siyuan.storage?.[Constants.LOCAL_MENU_MOUSE_SCROLL] === true;+ isMenuMouseScrollAvailable() && window.siyuan.config.appearance?.menuMouseScroll === true;-const syncControls = () => {+export const syncMenuMouseScroll = () => {document.querySelectorAll<HTMLInputElement>('input[id="menuMouseScroll"]').forEach(input => {input.checked = isMenuMouseScrollEnabled();});};-export const onMenuMouseScrollStorageChanged = (key: string) => {- if (key !== Constants.LOCAL_MENU_MOUSE_SCROLL) return;- revision++;- syncControls();-};-export const setMenuMouseScrollEnabled = (enabled: boolean) => {if (!isMenuMouseScrollAvailable() || window.siyuan.config.readonly || window.siyuan.isPublish) return;- window.siyuan.storage[Constants.LOCAL_MENU_MOUSE_SCROLL] = enabled;- onMenuMouseScrollStorageChanged(Constants.LOCAL_MENU_MOUSE_SCROLL);- return setStorageVal(Constants.LOCAL_MENU_MOUSE_SCROLL, enabled);-};--// 重连时补齐离线期间的偏好变更,保留较新操作和推送的结果。-export const refreshMenuMouseScroll = async (isActive = () => true) => {- if (!isMenuMouseScrollAvailable() || !isActive()) return;- const currentRevision = ++revision;- const response = await fetchSyncPost("/api/storage/getLocalStorage");- if (!isActive() || currentRevision !== revision || response.code !== 0) return;- window.siyuan.storage[Constants.LOCAL_MENU_MOUSE_SCROLL] = response.data[Constants.LOCAL_MENU_MOUSE_SCROLL] === true;- syncControls();+ return appearanceConfigApi.patch("menuMouseScroll", enabled);};diff --git a/app/src/constants.ts b/app/src/constants.tsindex 0f801a9158..8d0ef11018 100644--- a/app/src/constants.ts+++ b/app/src/constants.ts@@ -204,6 +204,7 @@ export abstract class Constants {public static readonly LOCAL_EXPORTIMG = "local-exportimg";public static readonly LOCAL_EXPORTPATH = "local-exportpath";public static readonly LOCAL_BAZAAR = "local-bazaar";+ /** @deprecated 内置偏好改用 config.appearance.pdfTheme,不再读取此旧键 */public static readonly LOCAL_PDFTHEME = "local-pdftheme";public static readonly LOCAL_LAYOUTS = "local-layouts";public static readonly LOCAL_WINDOW_WORKSPACE = "local-window-workspace-";@@ -213,16 +214,20 @@ export abstract class Constants {public static readonly LOCAL_FILESPATHS = "local-filespaths";public static readonly LOCAL_DIALOGPOSITION = "local-dialogposition";public static readonly LOCAL_SESSION_FIRSTLOAD = "local-session-firstload";+ /** @deprecated 内置偏好改用 config.appearance.outlineKeepCurrentExpand,不再读取此旧键 */public static readonly LOCAL_OUTLINE = "local-outline";public static readonly LOCAL_PLUGIN_DOCKS = "local-plugin-docks";public static readonly LOCAL_IMAGES = "local-images";public static readonly LOCAL_EMOJIS = "local-emojis";public static readonly LOCAL_MOVE_PATH = "local-move-path";+ /** @deprecated 内置偏好改用 config.fileTree.recentDocsSort,不再读取此旧键 */public static readonly LOCAL_RECENT_DOCS = "local-recent-docs";public static readonly LOCAL_CLOSED_TABS = "local-closed-tabs";public static readonly LOCAL_AV_CALENDAR_MODES = "local-av-calendar-modes";public static readonly LOCAL_TABS_READING = "local-tabs-reading";+ /** @deprecated 内置偏好改用 config.appearance.compactMode,不再读取此旧键 */public static readonly LOCAL_COMPACT_MODE = "local-compact-mode";+ /** @deprecated 内置偏好改用 config.appearance.menuMouseScroll,不再读取此旧键 */public static readonly LOCAL_MENU_MOUSE_SCROLL = "local-menu-mouse-scroll";// dialogdiff --git a/app/src/editor/outlineNavigation.test.ts b/app/src/editor/outlineNavigation.test.tsindex 7d21a26c46..cbfbc5affe 100644--- a/app/src/editor/outlineNavigation.test.ts+++ b/app/src/editor/outlineNavigation.test.ts@@ -96,7 +96,7 @@ const setupNavigation = (loaded: boolean, action: "focus" | "highlight") => {CB_GET_CONTEXT: "context", CB_GET_ALL: "all", CB_GET_HTML: "html", CB_GET_SETID: "setid",CB_GET_ROOTSCROLL: "root-scroll", CB_GET_SEARCH: "search", LOCAL_OUTLINE: "outlineStorage"}, AbortController,options: {app: {}},- window: {siyuan: {config: {editor: {dynamicLoadBlocks: 64}}, storage: {outlineStorage: {keepCurrentExpand: false}},+ window: {siyuan: {config: {editor: {dynamicLoadBlocks: 64}, appearance: {outlineKeepCurrentExpand: false}},menus: {menu: {remove() {}}}}},getSelection: () => ({rangeCount: 1, getRangeAt: () => selected}),hasClosestByAttribute: (node: typeof old, name: string) => name === "data-node-id" ? node : undefined,diff --git a/app/src/index.ts b/app/src/index.tsindex 8f6c18a466..55f344e805 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -1,8 +1,5 @@import {Constants} from "./constants";import {refreshSettingConfig} from "./config/setting/sync";-import {onAgentStreamingMarkdownStorageChanged} from "./config/tabs/ai/agentStreamingMarkdown";-import {onCompactModeStorageChanged, refreshCompactMode} from "./config/tabs/compactMode";-import {onMenuMouseScrollStorageChanged, refreshMenuMouseScroll} from "./config/tabs/menuMouseScroll";import {closeNotebookHistoryDialogs} from "./history/notebookDialogs";import {closeNotebookLivePhotos} from "./protyle/preview/livePhoto";import {systemConfig} from "./config/systemConfig";@@ -94,8 +91,7 @@ export class App {type: "main",callback: () => {if (window.siyuan.isReady) {- void refreshCompactMode().catch(error => console.error("Could not refresh compact mode", error));- void refreshMenuMouseScroll().catch(error => console.error("Could not refresh menu mouse scrolling", error));+ void refreshSettingConfig().catch(error => console.error("Could not refresh settings", error));}},msgCallback: (data) => {@@ -185,31 +181,19 @@ export class App {case "setLocalStorageVal":if (window.siyuan.storage) {window.siyuan.storage[data.data.key] = data.data.val;- onAgentStreamingMarkdownStorageChanged(data.data.key);- onCompactModeStorageChanged(data.data.key);- onMenuMouseScrollStorageChanged(data.data.key);}break;case "setLocalStorageVals":Object.keys(data.data.keyVals).forEach((k) => {window.siyuan.storage[k] = data.data.keyVals[k];- onAgentStreamingMarkdownStorageChanged(k);- onCompactModeStorageChanged(k);- onMenuMouseScrollStorageChanged(k);});break;case "removeLocalStorageVal":delete window.siyuan.storage[data.data.key];- onAgentStreamingMarkdownStorageChanged(data.data.key);- onCompactModeStorageChanged(data.data.key);- onMenuMouseScrollStorageChanged(data.data.key);break;case "removeLocalStorageVals":data.data.keys.forEach((k: string) => {delete window.siyuan.storage[k];- onAgentStreamingMarkdownStorageChanged(k);- onCompactModeStorageChanged(k);- onMenuMouseScrollStorageChanged(k);});break;case "rename":diff --git a/app/src/layout/dock/Outline.ts b/app/src/layout/dock/Outline.tsindex efa9e1bd53..efe0dd6e2a 100644--- a/app/src/layout/dock/Outline.ts+++ b/app/src/layout/dock/Outline.ts@@ -1,3 +1,4 @@+import {patchAppearancePreference} from "../../config/tabs/appearancePreferences";import {saveOutlineState} from "../../config/util/resourceConfig";import {toggleMenu} from "../../menus/menuToggle";import {bindPanelSearch} from "./panelSearch";@@ -13,7 +14,6 @@ import {getAllModels} from "../getAll";import {hasClosestBlock, hasClosestByClassName, hasTopClosestByClassName} from "../../protyle/util/hasClosest";import {isPhablet,- setStorageVal,updateHotkeyAfterTip,writeBlockDOMClipboard} from "../../protyle/util/compatibility";@@ -83,7 +83,7 @@ export class Outline extends Model {<svg><use xlink:href='#iconSearch'></use></svg></span><span class="fn__space"></span>- <span data-type="keepCurrentExpand" class="block__icon ariaLabel${window.siyuan.storage[Constants.LOCAL_OUTLINE].keepCurrentExpand ? " block__icon--active" : ""}" data-position="north" aria-label="${window.siyuan.languages.outlineKeepCurrentExpand}">+ <span data-type="keepCurrentExpand" class="block__icon ariaLabel${window.siyuan.config.appearance.outlineKeepCurrentExpand ? " block__icon--active" : ""}" data-position="north" aria-label="${window.siyuan.languages.outlineKeepCurrentExpand}"><svg><use xlink:href="#iconFocus"></use></svg></span><span class="fn__space"></span>@@ -194,19 +194,19 @@ export class Outline extends Model {topExtHTML: window.siyuan.config.readonly ? undefined : '<span class="b3-list-item__action"><svg><use xlink:href="#iconMore"></use></svg></span>',});// 保持当前标题展开功能- options.tab.panelElement.querySelector('[data-type="keepCurrentExpand"]').addEventListener("click", (event: MouseEvent & {+ options.tab.panelElement.querySelector('[data-type="keepCurrentExpand"]').addEventListener("click", async (event: MouseEvent & {target: Element}) => {const iconElement = hasClosestByClassName(event.target, "block__icon");if (!iconElement) {return;}- if (iconElement.classList.contains("block__icon--active")) {+ if (window.siyuan.config.readonly || window.siyuan.isPublish) return;+ await patchAppearancePreference("outlineKeepCurrentExpand", !window.siyuan.config.appearance.outlineKeepCurrentExpand);+ if (!window.siyuan.config.appearance.outlineKeepCurrentExpand) {iconElement.classList.remove("block__icon--active");- window.siyuan.storage[Constants.LOCAL_OUTLINE].keepCurrentExpand = false;} else {iconElement.classList.add("block__icon--active");- window.siyuan.storage[Constants.LOCAL_OUTLINE].keepCurrentExpand = true;let focusElement;getAllModels().editor.find(editItem => {if (editItem.editor.protyle.block.rootID === this.blockId) {@@ -224,8 +224,6 @@ export class Outline extends Model {this.setCurrent(focusElement);}}- // 保存keepCurrentExpand状态到localStorage- setStorageVal(Constants.LOCAL_OUTLINE, window.siyuan.storage[Constants.LOCAL_OUTLINE]);});options.tab.panelElement.addEventListener("click", (event: MouseEvent & { target: HTMLElement }) => {let target = event.target as HTMLElement;@@ -668,7 +666,7 @@ export class Outline extends Model {if (!currentElement) {return;}- if (window.siyuan.storage[Constants.LOCAL_OUTLINE].keepCurrentExpand) {+ if (window.siyuan.config.appearance.outlineKeepCurrentExpand) {let ulElement = currentElement.parentElement;while (ulElement && !ulElement.classList.contains("b3-list") && ulElement.tagName === "UL") {ulElement.classList.remove("fn__none");@@ -896,8 +894,6 @@ export class Outline extends Model {});}this.saveExpendIds();- window.siyuan.storage[Constants.LOCAL_OUTLINE].expandLevel = targetLevel;- setStorageVal(Constants.LOCAL_OUTLINE, window.siyuan.storage[Constants.LOCAL_OUTLINE]);}public setAllExpanded(expanded: boolean) {diff --git a/app/src/layout/dock/agent/AgentSessionPanel.ts b/app/src/layout/dock/agent/AgentSessionPanel.tsindex 4119ec7ba4..8c7c0fde1b 100644--- a/app/src/layout/dock/agent/AgentSessionPanel.ts+++ b/app/src/layout/dock/agent/AgentSessionPanel.ts@@ -11,7 +11,6 @@ import {useShell} from "../../../util/pathName";/// #endifimport {getHostCapabilities} from "../../../util/hostCapabilities";import {isInMobileApp, isPhablet} from "../../../protyle/util/compatibility";-import {Constants} from "../../../constants";import {bindMenuMouseScroll} from "../../../menus/menuMouseScroll";export class AgentSessionPanel {@@ -119,7 +118,7 @@ export class AgentSessionPanel {const itemsContainer = this.popup.querySelector(".b3-list") as HTMLElement;if (!this.mobile) {bindMenuMouseScroll(this.popup, () => !isInMobileApp() &&- window.siyuan.storage?.[Constants.LOCAL_MENU_MOUSE_SCROLL] === true, itemsContainer);+ window.siyuan.config.appearance?.menuMouseScroll === true, itemsContainer);}this.renderItems(itemsContainer, result.sessions, false);const searchInput = this.popup.querySelector(".agent-session-popup__search") as HTMLInputElement;diff --git a/app/src/menus/Menu.ts b/app/src/menus/Menu.tsindex 7b086d1081..01c47cb65e 100644--- a/app/src/menus/Menu.ts+++ b/app/src/menus/Menu.ts@@ -68,7 +68,7 @@ export class Menu {this.element = element || document.getElementById("commonMenu");if (!isMobile()) {this.clearMouseScroll = bindMenuMouseScroll(this.element, () =>- !isInMobileApp() && window.siyuan.storage?.[Constants.LOCAL_MENU_MOUSE_SCROLL] === true);+ !isInMobileApp() && window.siyuan.config.appearance?.menuMouseScroll === true);}// 内容增删或文字变化后重新定位;不监听分组类和定位样式,避免更新触发循环。new MutationObserver((records) => {diff --git a/app/src/menus/menuLayout.dom.test.ts b/app/src/menus/menuLayout.dom.test.tsindex de85ae4945..55a5a5c3cd 100644--- a/app/src/menus/menuLayout.dom.test.ts+++ b/app/src/menus/menuLayout.dom.test.ts@@ -116,7 +116,7 @@ const browserCases = async (sources: Record<string, string>, css: string) => {.fn__hidden { visibility: hidden !important; }`;document.head.append(style);- Object.assign(window, {siyuan: {languages: {back: "Back"}, zIndex: 0, storage: {},+ Object.assign(window, {siyuan: {languages: {back: "Back"}, zIndex: 0, storage: {}, config: {appearance: {}},mobile: {size: {portrait: {height1: innerHeight}}}, menus: {}}});const {Menu, MenuItem}: typeof import("./Menu") = load("menus/Menu");const {Menu: PluginMenu}: typeof import("../plugin/Menu") = load("plugin/Menu");@@ -295,7 +295,7 @@ const browserCases = async (sources: Record<string, string>, css: string) => {pointer(followingItems, .3);pointer(followingItems, .6);check.equal(followingItems.scrollTop, 0, "The preference defaults to off");- window.siyuan.storage.menuMouseScroll = true;+ window.siyuan.config.appearance.menuMouseScroll = true;pointer(followingItems, .3);check.equal(followingItems.scrollTop, 0, "Entering establishes an anchor without jumping");pointer(followingItems, .55);@@ -339,10 +339,10 @@ const browserCases = async (sources: Record<string, string>, css: string) => {const beforeMutationMove = followingItems.scrollTop;pointer(followingItems, .6);check.equal(followingItems.scrollTop, beforeMutationMove, "Dynamic content establishes a new anchor");- window.siyuan.storage.menuMouseScroll = false;+ window.siyuan.config.appearance.menuMouseScroll = false;pointer(followingItems, .8);check.equal(followingItems.scrollTop, beforeMutationMove, "Disabling takes effect on an open menu");- window.siyuan.storage.menuMouseScroll = true;+ window.siyuan.config.appearance.menuMouseScroll = true;followingItems.scrollTop = 0;following.resetMouseScroll();const nativePointer = (type: string, x: number, y: number) =>@@ -364,7 +364,7 @@ const browserCases = async (sources: Record<string, string>, css: string) => {check.equal(clicked, Number(nativeHit.textContent.trim().replace("Mouse item ", "")), "Native click selects the visible item");dispose(following);- window.siyuan.storage.menuMouseScroll = true;+ window.siyuan.config.appearance.menuMouseScroll = true;const mouseSubmenus = createMenu();mouseSubmenus.addItem({label: "Scrollable children", submenu: Array.from({length: 80}, (_, i) => ({label: `Child ${i}`}))});addItems(mouseSubmenus, 50);@@ -433,11 +433,11 @@ const browserCases = async (sources: Record<string, string>, css: string) => {const avItems = avPanel.querySelector<HTMLElement>(".b3-menu__items");check.ok(avPanel.querySelector(".av__automation-panel"));check.ok(avItems.scrollHeight > avItems.clientHeight, "The database panel has overflowing form content");- window.siyuan.storage.menuMouseScroll = false;+ window.siyuan.config.appearance.menuMouseScroll = false;pointer(avItems, .3);pointer(avItems, .7);check.equal(avItems.scrollTop, 0, "Database panels respect the disabled preference");- window.siyuan.storage.menuMouseScroll = true;+ window.siyuan.config.appearance.menuMouseScroll = true;pointer(avItems, .3);pointer(avItems, .7);check.equal(avItems.scrollTop, 0, "Database forms stay stationary even with the preference enabled and no focused input");@@ -505,11 +505,11 @@ const browserCases = async (sources: Record<string, string>, css: string) => {return {host, controller, events, buttons, items: toolbar.querySelector<HTMLElement>(".b3-menu__items")};};const pdfMenu = createPDFMenu();- window.siyuan.storage.menuMouseScroll = false;+ window.siyuan.config.appearance.menuMouseScroll = false;pointer(pdfMenu.items, .3);pointer(pdfMenu.items, .7);check.equal(pdfMenu.items.scrollTop, 0, "PDF menus respect the disabled preference");- window.siyuan.storage.menuMouseScroll = true;+ window.siyuan.config.appearance.menuMouseScroll = true;pointer(pdfMenu.items, .3);pointer(pdfMenu.items, .7);check.ok(pdfMenu.items.scrollTop > 0, "PDF toolbar menus support mouse scrolling");@@ -550,11 +550,11 @@ const browserCases = async (sources: Record<string, string>, css: string) => {const searchTop = calendarMenu.search.getBoundingClientRect().top;calendarMenu.search.value = "Draft search";calendarMenu.search.setSelectionRange(2, 5);- window.siyuan.storage.menuMouseScroll = false;+ window.siyuan.config.appearance.menuMouseScroll = false;pointer(calendarMenu.items, .3);pointer(calendarMenu.items, .7);check.equal(calendarMenu.items.scrollTop, 0, "Calendar lists respect the disabled preference");- window.siyuan.storage.menuMouseScroll = true;+ window.siyuan.config.appearance.menuMouseScroll = true;pointer(calendarMenu.items, .3);pointer(calendarMenu.items, .7);check.ok(calendarMenu.items.scrollTop > 0, "Calendar undated lists support mouse scrolling");@@ -586,11 +586,11 @@ const browserCases = async (sources: Record<string, string>, css: string) => {sessionRoot.style.cssText = "position:fixed;left:40px;top:60px;width:300px";const sessionItems = sessionRoot.querySelector<HTMLElement>(".b3-list");const sessionSearch = sessionRoot.querySelector<HTMLInputElement>("input");- window.siyuan.storage.menuMouseScroll = false;+ window.siyuan.config.appearance.menuMouseScroll = false;pointer(sessionItems, .3);pointer(sessionItems, .7);check.equal(sessionItems.scrollTop, 0, "Session lists respect the disabled preference");- window.siyuan.storage.menuMouseScroll = true;+ window.siyuan.config.appearance.menuMouseScroll = true;pointer(sessionItems, .3);pointer(sessionItems, .7);check.ok(sessionItems.scrollTop > 0, "Session lists use their custom scrolling container");diff --git a/app/src/mobile/dock/MobileOutline.ts b/app/src/mobile/dock/MobileOutline.tsindex 3e0e667300..58fc4f87a4 100644--- a/app/src/mobile/dock/MobileOutline.ts+++ b/app/src/mobile/dock/MobileOutline.ts@@ -1,3 +1,4 @@+import {patchAppearancePreference} from "../../config/tabs/appearancePreferences";import {saveOutlineState} from "../../config/util/resourceConfig";import {toggleMenu} from "../../menus/menuToggle";import {bindPanelSearch} from "../../layout/dock/panelSearch";@@ -6,7 +7,7 @@ import {Tree} from "../../util/Tree";import {fetchPost} from "../../util/fetch";import {confirmBlockRef} from "../../util/checkBlockRef";import {hasClosestBlock, hasClosestByClassName} from "../../protyle/util/hasClosest";-import {setStorageVal, writeBlockDOMClipboard} from "../../protyle/util/compatibility";+import {writeBlockDOMClipboard} from "../../protyle/util/compatibility";import {Constants} from "../../constants";import {MenuItem} from "../../menus/Menu";import {getPreviousBlock} from "../../protyle/wysiwyg/getBlock";@@ -74,7 +75,7 @@ export class MobileOutline extends Model {<div class="fn__space"></div><input spellcheck="false" class="b3-text-field search__label fn__none fn__size200" placeholder="${window.siyuan.languages.searchPlaceholder}" /><svg data-type="search" class="toolbar__icon"><use xlink:href='#iconSearch'></use></svg>- <svg data-type="keepCurrentExpand" class="toolbar__icon${window.siyuan.storage[Constants.LOCAL_OUTLINE].keepCurrentExpand ? " toolbar__icon--active" : ""}"><use xlink:href="#iconFocus"></use></svg>+ <svg data-type="keepCurrentExpand" class="toolbar__icon${window.siyuan.config.appearance.outlineKeepCurrentExpand ? " toolbar__icon--active" : ""}"><use xlink:href="#iconFocus"></use></svg><svg data-type="expandLevel" class="toolbar__icon"><use xlink:href="#iconExpandLevel"></use></svg></div><div class="b3-list-item fn__none" data-type="doc-title"></div>@@ -135,19 +136,19 @@ export class MobileOutline extends Model {topExtHTML: window.siyuan.config.readonly ? undefined : '<span class="b3-list-item__action"><svg><use xlink:href="#iconMore"></use></svg></span>',});// 保持当前标题展开功能- this.element.querySelector('[data-type="keepCurrentExpand"]').addEventListener("click", (event: MouseEvent & {+ this.element.querySelector('[data-type="keepCurrentExpand"]').addEventListener("click", async (event: MouseEvent & {target: Element}) => {const iconElement = hasClosestByClassName(event.target, "toolbar__icon");if (!iconElement) {return;}- if (iconElement.classList.contains("toolbar__icon--active")) {+ if (window.siyuan.config.readonly || window.siyuan.isPublish) return;+ await patchAppearancePreference("outlineKeepCurrentExpand", !window.siyuan.config.appearance.outlineKeepCurrentExpand);+ if (!window.siyuan.config.appearance.outlineKeepCurrentExpand) {iconElement.classList.remove("toolbar__icon--active");- window.siyuan.storage[Constants.LOCAL_OUTLINE].keepCurrentExpand = false;} else {iconElement.classList.add("toolbar__icon--active");- window.siyuan.storage[Constants.LOCAL_OUTLINE].keepCurrentExpand = true;let focusElement;const blockElement = hasClosestBlock(window.siyuan.mobile.editor.protyle.toolbar.range?.startContainer);if (blockElement) {@@ -157,8 +158,6 @@ export class MobileOutline extends Model {this.setCurrent(focusElement);}}- // 保存keepCurrentExpand状态到localStorage- setStorageVal(Constants.LOCAL_OUTLINE, window.siyuan.storage[Constants.LOCAL_OUTLINE]);});this.element.addEventListener("click", (event: MouseEvent & { target: HTMLElement }) => {let target = event.target as HTMLElement;@@ -510,7 +509,7 @@ export class MobileOutline extends Model {if (!currentElement) {return;}- if (window.siyuan.storage[Constants.LOCAL_OUTLINE].keepCurrentExpand) {+ if (window.siyuan.config.appearance.outlineKeepCurrentExpand) {let ulElement = currentElement.parentElement;while (ulElement && !ulElement.classList.contains("b3-list") && ulElement.tagName === "UL") {ulElement.classList.remove("fn__none");@@ -761,8 +760,6 @@ export class MobileOutline extends Model {});}this.saveExpendIds();- window.siyuan.storage[Constants.LOCAL_OUTLINE].expandLevel = targetLevel;- setStorageVal(Constants.LOCAL_OUTLINE, window.siyuan.storage[Constants.LOCAL_OUTLINE]);}private setAllExpanded(expanded: boolean) {diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.tsindex 939b74b07c..a7ca1a7512 100644--- a/app/src/mobile/index.ts+++ b/app/src/mobile/index.ts@@ -3,6 +3,7 @@ import {ensureLute} from "../protyle/util/lute";import {completeStartup, guardStartup, reportStartupError, setStartupLanguage, setStartupStage} from "../boot/startupError";import {Constants} from "../constants";import {systemConfig} from "../config/systemConfig";+import {refreshSettingConfig} from "../config/setting/sync";import {openStandaloneDatabaseItemByURI} from "../protyle/render/av/openStandaloneDatabaseItem";import {onMessage} from "./util/onMessage";import {genUUID} from "../util/genID";@@ -101,6 +102,11 @@ class App {mainWs.connect({id: genUUID(),type: "main",+ callback: () => {+ if (window.siyuan.isReady) {+ void refreshSettingConfig().catch(error => console.error("Could not refresh settings", error));+ }+ },msgCallback: (data) => {emitToPlugins("ws-main", data);onMessage(this, data);diff --git a/app/src/mobile/menu/getRecentDocs.ts b/app/src/mobile/menu/getRecentDocs.tsindex 2b50edbf30..60dc7a4caf 100644--- a/app/src/mobile/menu/getRecentDocs.ts+++ b/app/src/mobile/menu/getRecentDocs.ts@@ -1,3 +1,4 @@+import {fileConfigApi} from "../../config/tabs/fileRuntime";import {fetchPost} from "../../util/fetch";import {getFileTreeIconHTML} from "../../emoji/fileTreeIcon";import {Constants} from "../../constants";@@ -6,7 +7,6 @@ import {hasClosestByClassName} from "../../protyle/util/hasClosest";import {openModel} from "./model";import {openMobileFileById} from "../editor";import type {App} from "../../index";-import {setStorageVal} from "../../protyle/util/compatibility";interface IRecentDoc {rootID: string;@@ -28,7 +28,7 @@ ${getFileTreeIconHTML(item.icon, "file", "b3-list-item__graphic", true)}};export const getRecentDocs = (app: App) => {- const sortBy = window.siyuan.storage[Constants.LOCAL_RECENT_DOCS].type as TRecentDocsSort;+ const sortBy = window.siyuan.config.fileTree.recentDocsSort as TRecentDocsSort;fetchPost("/api/storage/getRecentDocs", {sortBy}, (response) => {let recentDocs = response.data as IRecentDoc[];openModel({@@ -72,8 +72,9 @@ export const getRecentDocs = (app: App) => {recentDocs = newResponse.data as IRecentDoc[];renderRecentDocs(recentDocs, listElement, searchElement.value);});- window.siyuan.storage[Constants.LOCAL_RECENT_DOCS].type = newSortBy;- setStorageVal(Constants.LOCAL_RECENT_DOCS, window.siyuan.storage[Constants.LOCAL_RECENT_DOCS]);+ if (!window.siyuan.config.readonly && !window.siyuan.isPublish) {+ void fileConfigApi.patch("recentDocsSort", newSortBy);+ }});listElement.addEventListener("click", (event) => {const liElement = hasClosestByClassName(event.target as HTMLElement, "b3-list-item");diff --git a/app/src/mobile/util/mobileBars.test.ts b/app/src/mobile/util/mobileBars.test.tsindex 819d2f13e2..b1b158dfc1 100644--- a/app/src/mobile/util/mobileBars.test.ts+++ b/app/src/mobile/util/mobileBars.test.ts@@ -5,7 +5,6 @@ import {resolve} from "node:path";import {runInNewContext} from "node:vm";import {ModuleKind, transpileModule} from "typescript";import {bindMobileBarsScroll, clearMobileBarsScroll} from "./mobileBars";-import {MOBILE_BARS_CONFIG_KEY} from "./mobileBarsConfig";import * as mobileBarsState from "./mobileBarsState";class TestClassList {@@ -198,8 +197,8 @@ describe("mobile bars", () => {const originalWindow = globalThis.window;const originalRequestAnimationFrame = globalThis.requestAnimationFrame;let frame: FrameRequestCallback;- const storage = {[MOBILE_BARS_CONFIG_KEY]: {autoHide: true}};- Object.defineProperty(globalThis, "window", {configurable: true, value: {siyuan: {storage}}});+ const appearance = {mobileBars: {autoHide: true}};+ Object.defineProperty(globalThis, "window", {configurable: true, value: {siyuan: {config: {appearance}}}});Object.defineProperty(globalThis, "requestAnimationFrame", {configurable: true,value: (callback: FrameRequestCallback) => {@@ -262,11 +261,11 @@ describe("mobile bars", () => {scrollTo(0);assertPosition(0);assert.equal(breadcrumbElement.attributes.has("inert"), false);- storage[MOBILE_BARS_CONFIG_KEY].autoHide = false;+ appearance.mobileBars.autoHide = false;scrollTo(100);assertPosition(0);assert.equal(breadcrumbElement.attributes.get("aria-hidden"), "false");- storage[MOBILE_BARS_CONFIG_KEY].autoHide = true;+ appearance.mobileBars.autoHide = true;scrollTo(148);assertPosition(1);} finally {diff --git a/app/src/mobile/util/mobileBarsConfig.ts b/app/src/mobile/util/mobileBarsConfig.tsindex f3948c9136..e89b9c061d 100644--- a/app/src/mobile/util/mobileBarsConfig.ts+++ b/app/src/mobile/util/mobileBarsConfig.ts@@ -1,7 +1,5 @@-export const MOBILE_BARS_CONFIG_KEY = "local-mobile-bars";-export const isMobileBarsAutoHide = () =>- window.siyuan.storage[MOBILE_BARS_CONFIG_KEY]?.autoHide !== false;+ window.siyuan.config.appearance.mobileBars?.autoHide !== false;export const createDefaultMobileBarsConfig = () => ({autoHide: true,@@ -19,4 +17,4 @@ export const resolveMobileSidebarConfig = (config?: {autoHide?: boolean, sidebar};export const getMobileSidebarConfig = () =>- resolveMobileSidebarConfig(window.siyuan.storage[MOBILE_BARS_CONFIG_KEY]);+ resolveMobileSidebarConfig(window.siyuan.config.appearance.mobileBars);diff --git a/app/src/mobile/util/mobileBarsSetting.ts b/app/src/mobile/util/mobileBarsSetting.tsindex 05b9904bb6..05cc568eac 100644--- a/app/src/mobile/util/mobileBarsSetting.ts+++ b/app/src/mobile/util/mobileBarsSetting.ts@@ -1,6 +1,6 @@-import {setStorageVal} from "../../protyle/util/compatibility";+import {patchAppearancePreference} from "../../config/tabs/appearancePreferences";import {escapeHtml} from "../../util/escape";-import {isMobileBarsAutoHide, MOBILE_BARS_CONFIG_KEY} from "./mobileBarsConfig";+import {isMobileBarsAutoHide} from "./mobileBarsConfig";import {showMobileBars} from "./mobileBars";export const genMobileBarsSettingHTML = () => `<label class="b3-label fn__flex config-item">@@ -13,9 +13,16 @@ export const genMobileBarsSettingHTML = () => `<label class="b3-label fn__flex cexport const mountMobileBarsSetting = (root: HTMLElement) => {root.querySelector<HTMLInputElement>("#mobileBarsAutoHide")?.addEventListener("change", (event) => {- const config = {...window.siyuan.storage[MOBILE_BARS_CONFIG_KEY], autoHide: (event.target as HTMLInputElement).checked};- window.siyuan.storage[MOBILE_BARS_CONFIG_KEY] = config;- setStorageVal(MOBILE_BARS_CONFIG_KEY, config);- showMobileBars();+ void patchAppearancePreference("mobileBars.autoHide", (event.target as HTMLInputElement).checked).then(() => {+ syncMobileBarsSetting(root);+ showMobileBars();+ });+ });+};++export const syncMobileBarsSetting = (root: ParentNode = document) => {+ root.querySelectorAll<HTMLInputElement>("#mobileBarsAutoHide").forEach(input => {+ input.checked = isMobileBarsAutoHide();+ input.disabled = window.siyuan.config.readonly || window.siyuan.isPublish;});};diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.tsindex a207a0837e..44382ae6aa 100644--- a/app/src/mobile/util/onMessage.ts+++ b/app/src/mobile/util/onMessage.ts@@ -1,10 +1,7 @@import {openMobileFileById} from "../editor";import {refreshSettingConfig} from "../../config/setting/sync";-import {onAgentStreamingMarkdownStorageChanged} from "../../config/tabs/ai/agentStreamingMarkdown";import {closeNotebookHistoryDialogs} from "../../history/notebookDialogs";import {closeNotebookLivePhotos} from "../../protyle/preview/livePhoto";-import {MOBILE_BARS_CONFIG_KEY} from "./mobileBarsConfig";-import {showMobileBars} from "./mobileBars";import {forceQuit,processBacklinkIndexCommit,@@ -152,10 +149,6 @@ export const onMessage = (app: App, data: IWebSocketData) => {break;case "setLocalStorageVal":window.siyuan.storage[data.data.key] = data.data.val;- onAgentStreamingMarkdownStorageChanged(data.data.key);- if (data.data.key === MOBILE_BARS_CONFIG_KEY) {- showMobileBars();- }if (data.data.key === Constants.LOCAL_MOBILE_BOTTOM_BAR) {renderMobileBottomBar();}@@ -167,10 +160,6 @@ export const onMessage = (app: App, data: IWebSocketData) => {Object.keys(data.data.keyVals).forEach((k) => {window.siyuan.storage[k] = data.data.keyVals[k];});- Object.keys(data.data.keyVals).forEach(onAgentStreamingMarkdownStorageChanged);- if (Object.prototype.hasOwnProperty.call(data.data.keyVals, MOBILE_BARS_CONFIG_KEY)) {- showMobileBars();- }if (Object.prototype.hasOwnProperty.call(data.data.keyVals, Constants.LOCAL_MOBILE_BOTTOM_BAR)) {renderMobileBottomBar();}@@ -180,10 +169,6 @@ export const onMessage = (app: App, data: IWebSocketData) => {break;case "removeLocalStorageVal":delete window.siyuan.storage[data.data.key];- onAgentStreamingMarkdownStorageChanged(data.data.key);- if (data.data.key === MOBILE_BARS_CONFIG_KEY) {- showMobileBars();- }if (data.data.key === Constants.LOCAL_MOBILE_BOTTOM_BAR) {renderMobileBottomBar();}@@ -195,10 +180,6 @@ export const onMessage = (app: App, data: IWebSocketData) => {data.data.keys.forEach((k: string) => {delete window.siyuan.storage[k];});- data.data.keys.forEach(onAgentStreamingMarkdownStorageChanged);- if (data.data.keys.includes(MOBILE_BARS_CONFIG_KEY)) {- showMobileBars();- }if (data.data.keys.includes(Constants.LOCAL_MOBILE_BOTTOM_BAR)) {renderMobileBottomBar();}diff --git a/app/src/mobile/util/sidebarSetting.test.ts b/app/src/mobile/util/sidebarSetting.test.tsindex 3ba98e22e1..94c9d87181 100644--- a/app/src/mobile/util/sidebarSetting.test.ts+++ b/app/src/mobile/util/sidebarSetting.test.ts@@ -4,10 +4,10 @@ import {readFileSync} from "node:fs";import {resolve} from "node:path";import {runInNewContext} from "node:vm";import {ModuleKind, transpileModule} from "typescript";-import {MOBILE_BARS_CONFIG_KEY, resolveMobileSidebarConfig} from "./mobileBarsConfig";+import {resolveMobileSidebarConfig} from "./mobileBarsConfig";-test("sidebar switches retain one entry and preserve unrelated local settings", () => {- const storage = {[MOBILE_BARS_CONFIG_KEY]: {autoHide: false, sidebarSwipe: true, sidebarButtons: true}};+test("sidebar switches retain one entry and preserve unrelated configuration", async () => {+ const mobileBars = {autoHide: false, sidebarSwipe: true, sidebarButtons: true};const inputs = new Map(["sidebarSwipe", "sidebarButtons"].map(key => [key, {checked: false,disabled: false,@@ -23,13 +23,16 @@ test("sidebar switches retain one entry and preserve unrelated local settings",const code = transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;runInNewContext(code, {exports: moduleExports,- window: {siyuan: {storage, config: {readonly: false}, isPublish: false}},+ window: {siyuan: {config: {readonly: false, appearance: {mobileBars}}, isPublish: false}},require: (name: string) => {if (name === "./mobileBarsConfig") {- return {MOBILE_BARS_CONFIG_KEY, getMobileSidebarConfig: () => resolveMobileSidebarConfig(storage[MOBILE_BARS_CONFIG_KEY])};+ return {getMobileSidebarConfig: () => resolveMobileSidebarConfig(mobileBars)};}- if (name === "../../protyle/util/compatibility") {- return {setStorageVal: () => saves++};+ if (name === "../../config/tabs/appearancePreferences") {+ return {patchAppearancePreference: async (path: string, value: boolean) => {+ saves++;+ Reflect.set(mobileBars, path.split(".")[1], value);+ }};}if (name === "./sidebarButtons") {return {updateSidebarButtons: () => updates++};@@ -44,18 +47,22 @@ test("sidebar switches retain one entry and preserve unrelated local settings",assert.equal(buttons.checked, true);swipe.checked = false;swipe.change();+ await Promise.resolve();assert.equal(buttons.disabled, true);assert.equal(swipe.disabled, false);- assert.equal(storage[MOBILE_BARS_CONFIG_KEY].autoHide, false);+ assert.equal(mobileBars.autoHide, false);buttons.checked = false;buttons.change();+ await Promise.resolve();assert.equal(buttons.checked, true);assert.equal(saves, 1);swipe.checked = true;swipe.change();+ await Promise.resolve();assert.equal(buttons.disabled, false);buttons.checked = false;buttons.change();+ await Promise.resolve();assert.equal(swipe.disabled, true);assert.equal(swipe.checked, true);assert.equal(saves, 3);diff --git a/app/src/mobile/util/sidebarSetting.ts b/app/src/mobile/util/sidebarSetting.tsindex 9ee6518364..be5debd622 100644--- a/app/src/mobile/util/sidebarSetting.ts+++ b/app/src/mobile/util/sidebarSetting.ts@@ -1,6 +1,6 @@-import {setStorageVal} from "../../protyle/util/compatibility";+import {patchAppearancePreference} from "../../config/tabs/appearancePreferences";import {escapeHtml} from "../../util/escape";-import {getMobileSidebarConfig, MOBILE_BARS_CONFIG_KEY} from "./mobileBarsConfig";+import {getMobileSidebarConfig} from "./mobileBarsConfig";import {updateSidebarButtons} from "./sidebarButtons";import {showMobileBars} from "./mobileBars";@@ -14,33 +14,38 @@ export const genSidebarSettingHTML = () => settings.map(key => `<label class="b3<input data-sidebar-setting="${key}" type="checkbox" class="b3-switch fn__flex-center"></label>`).join("");+export const syncSidebarSetting = (root: ParentNode = document) => {+ const config = getMobileSidebarConfig();+ settings.forEach(key => {+ const input = root.querySelector<HTMLInputElement>(`[data-sidebar-setting="${key}"]`);+ if (!input) {+ return;+ }+ input.checked = config[key];+ input.disabled = window.siyuan.config.readonly || window.siyuan.isPublish ||+ !config[key === "sidebarSwipe" ? "sidebarButtons" : "sidebarSwipe"];+ });+};+export const mountSidebarSetting = (root: HTMLElement) => {- const render = () => {- const config = getMobileSidebarConfig();- settings.forEach(key => {- const input = root.querySelector<HTMLInputElement>(`[data-sidebar-setting="${key}"]`);- if (!input) {- return;- }- input.checked = config[key];- input.disabled = window.siyuan.config.readonly || window.siyuan.isPublish ||- !config[key === "sidebarSwipe" ? "sidebarButtons" : "sidebarSwipe"];- });- };+ const render = () => syncSidebarSetting(root);settings.forEach(key => {root.querySelector<HTMLInputElement>(`[data-sidebar-setting="${key}"]`)?.addEventListener("change", event => {+ if (window.siyuan.config.readonly || window.siyuan.isPublish) {+ render();+ return;+ }const current = getMobileSidebarConfig();const checked = (event.target as HTMLInputElement).checked;if (!checked && !current[key === "sidebarSwipe" ? "sidebarButtons" : "sidebarSwipe"]) {render();return;}- const config = {...window.siyuan.storage[MOBILE_BARS_CONFIG_KEY], ...current, [key]: checked};- window.siyuan.storage[MOBILE_BARS_CONFIG_KEY] = config;- setStorageVal(MOBILE_BARS_CONFIG_KEY, config);- render();- updateSidebarButtons();- showMobileBars();+ void patchAppearancePreference(`mobileBars.${key}`, checked).then(() => {+ render();+ updateSidebarButtons();+ showMobileBars();+ });});});render();diff --git a/app/src/protyle/render/av/calendar/undated.ts b/app/src/protyle/render/av/calendar/undated.tsindex ae9cab7be0..696b9dee9d 100644--- a/app/src/protyle/render/av/calendar/undated.ts+++ b/app/src/protyle/render/av/calendar/undated.ts@@ -52,7 +52,7 @@ export const bindCalendarUndated = (options: {const dateKeyID = (data.view as IAVTable).calendar.dateKeyID;const mobile = isMobile();const resetMouseScroll = mobile ? undefined : bindMenuMouseScroll(panel, () =>- !isInMobileApp() && window.siyuan.storage?.[Constants.LOCAL_MENU_MOUSE_SCROLL] === true);+ !isInMobileApp() && window.siyuan.config.appearance?.menuMouseScroll === true);const normalizedQuery = query.trim();const cache = state.undatedCache?.dateKeyID === dateKeyID && state.undatedCache.query === normalizedQuery &&state.undatedCache.search === state.undatedSearch.trim() ? state.undatedCache : undefined;diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.tsindex 749318cd67..674f222c05 100644--- a/app/src/protyle/util/compatibility.ts+++ b/app/src/protyle/util/compatibility.ts@@ -17,7 +17,6 @@ import {prepareExternalClipboardHTML} from "./richClipboard";import {isIOSPlatform, isIPadOSPlatform} from "./browserCompatibility";import {canOpenExternalURL, getHostCapabilities} from "../../util/hostCapabilities";import {createDefaultMobileBottomBarConfig} from "../../mobile/util/mobileBottomBarConfig";-import {createDefaultMobileBarsConfig, MOBILE_BARS_CONFIG_KEY} from "../../mobile/util/mobileBarsConfig";export {encodeBase64, getTextSiyuanFromTextHTML} from "./clipboardData";@@ -759,18 +758,9 @@ export const getLocalStorage = (cb: () => void, onError?: (error: unknown) => vorowTab: "",layoutTab: 0};- defaultStorage[Constants.LOCAL_PDFTHEME] = {- light: "light",- dark: "dark",- annoColor: "var(--b3-pdf-background1)"- };defaultStorage[Constants.LOCAL_LAYOUTS] = []; // {name: "", layout:{}, time: number, filespaths: IFilesPath[]}defaultStorage[Constants.LOCAL_PLUGIN_DOCKS] = {}; // { pluginName: {dockId: IPluginDockTab}}defaultStorage[Constants.LOCAL_PLUGINTOPUNPIN] = [];- defaultStorage[Constants.LOCAL_OUTLINE] = {- keepCurrentExpand: false,- expandLevel: 6- };defaultStorage[Constants.LOCAL_FILEPOSITION] = {}; // {id: IScrollAttr}defaultStorage[Constants.LOCAL_DIALOGPOSITION] = {}; // {id: IPosition}defaultStorage[Constants.LOCAL_HISTORY] = {@@ -831,9 +821,6 @@ export const getLocalStorage = (cb: () => void, onError?: (error: unknown) => voversion: 1,tabs: [],};- // 仅未保存过移动端偏好时启用默认侧栏按钮。- defaultStorage[MOBILE_BARS_CONFIG_KEY] = typeof response.data[MOBILE_BARS_CONFIG_KEY] === "undefined" ?- createDefaultMobileBarsConfig() : {autoHide: true};defaultStorage[Constants.LOCAL_MOBILE_BOTTOM_BAR] = createDefaultMobileBottomBarConfig();defaultStorage[Constants.LOCAL_MOBILE_SIDE_PANEL] = {version: 1,@@ -868,19 +855,18 @@ export const getLocalStorage = (cb: () => void, onError?: (error: unknown) => vo};defaultStorage[Constants.LOCAL_ZOOM] = 1;defaultStorage[Constants.LOCAL_MOVE_PATH] = {keys: [], k: ""};- defaultStorage[Constants.LOCAL_RECENT_DOCS] = {type: "viewedAt"}; // TRecentDocsSortdefaultStorage[Constants.LOCAL_AV_CALENDAR_MODES] = {};defaultStorage[Constants.LOCAL_TABS_READING] = {};- [Constants.LOCAL_EXPORTIMG, Constants.LOCAL_EXPORTPATH, Constants.LOCAL_SEARCHKEYS, Constants.LOCAL_PDFTHEME, Constants.LOCAL_BAZAAR,+ [Constants.LOCAL_EXPORTIMG, Constants.LOCAL_EXPORTPATH, Constants.LOCAL_SEARCHKEYS, Constants.LOCAL_BAZAAR,Constants.LOCAL_EXPORTWORD, Constants.LOCAL_EXPORTPDF, Constants.LOCAL_DOCINFO, Constants.LOCAL_MOBILE_TABS,- Constants.LOCAL_MOBILE_BOTTOM_BAR, Constants.LOCAL_MOBILE_SIDE_PANEL, MOBILE_BARS_CONFIG_KEY,+ Constants.LOCAL_MOBILE_BOTTOM_BAR, Constants.LOCAL_MOBILE_SIDE_PANEL,Constants.LOCAL_FONTSTYLES,Constants.LOCAL_SEARCHDATA, Constants.LOCAL_ZOOM, Constants.LOCAL_LAYOUTS,Constants.LOCAL_PLUGINTOPUNPIN, Constants.LOCAL_SEARCHASSET, Constants.LOCAL_FLASHCARD,Constants.LOCAL_DIALOGPOSITION, Constants.LOCAL_SEARCHUNREF, Constants.LOCAL_HISTORY,- Constants.LOCAL_OUTLINE, Constants.LOCAL_FILEPOSITION, Constants.LOCAL_FILESPATHS, Constants.LOCAL_IMAGES,- Constants.LOCAL_PLUGIN_DOCKS, Constants.LOCAL_EMOJIS, Constants.LOCAL_MOVE_PATH, Constants.LOCAL_RECENT_DOCS,+ Constants.LOCAL_FILEPOSITION, Constants.LOCAL_FILESPATHS, Constants.LOCAL_IMAGES,+ Constants.LOCAL_PLUGIN_DOCKS, Constants.LOCAL_EMOJIS, Constants.LOCAL_MOVE_PATH,Constants.LOCAL_CLOSED_TABS, Constants.LOCAL_AV_CALENDAR_MODES, Constants.LOCAL_TABS_READING].forEach((key) => {const value = response.data[key];if (typeof value === "string") {diff --git a/app/src/protyle/util/storageStartup.test.ts b/app/src/protyle/util/storageStartup.test.tsindex 63b7837eef..4182f3e606 100644--- a/app/src/protyle/util/storageStartup.test.ts+++ b/app/src/protyle/util/storageStartup.test.ts@@ -6,7 +6,6 @@ import {runInNewContext} from "node:vm";import {ModuleKind, transpileModule} from "typescript";import type {Constants as AppConstants} from "../../constants";import {createDefaultMobileBottomBarConfig, normalizeMobileBottomBarConfig} from "../../mobile/util/mobileBottomBarConfig";-import {createDefaultMobileBarsConfig, MOBILE_BARS_CONFIG_KEY, resolveMobileSidebarConfig} from "../../mobile/util/mobileBarsConfig";const constantsExports: {Constants?: typeof AppConstants} = {};runInNewContext(transpileModule(readFileSync(resolve("src/constants.ts"), "utf8"), {@@ -35,8 +34,6 @@ const loadStorage = (values: Record<string, unknown>) => {getDefaultType: () => ({}),getDefaultSubType: () => ({}),createDefaultMobileBottomBarConfig,- createDefaultMobileBarsConfig,- MOBILE_BARS_CONFIG_KEY,normalizeSearchTypes: (types: unknown) => types,sanitizeClosedTabs: (tabs: unknown[]) => tabs,setStorageVal: () => assert.fail("Loading storage must not overwrite persisted data"),@@ -56,34 +53,10 @@ const loadZoom = (value: unknown) => {return zoom;};-test("fresh or reset mobile preferences enable sidebar buttons alongside swipe", () => {- const first = loadStorage({})[MOBILE_BARS_CONFIG_KEY];- const second = loadStorage({})[MOBILE_BARS_CONFIG_KEY];- assert.deepEqual(first, createDefaultMobileBarsConfig());- assert.deepEqual(resolveMobileSidebarConfig(first as ReturnType<typeof createDefaultMobileBarsConfig>), {sidebarSwipe: true, sidebarButtons: true});- assert.notEqual(first, second);-});--test("startup preserves legacy and explicit sidebar choices in object and serialized storage", () => {- for (const persisted of [- {autoHide: false},- {autoHide: false, sidebarSwipe: true, sidebarButtons: false},- {autoHide: false, sidebarSwipe: true, sidebarButtons: true},- {autoHide: false, sidebarSwipe: false, sidebarButtons: true},- ]) {- for (const value of [persisted, JSON.stringify(persisted)]) {- const loaded = loadStorage({[MOBILE_BARS_CONFIG_KEY]: value})[MOBILE_BARS_CONFIG_KEY];- assert.equal(JSON.stringify(loaded), JSON.stringify(persisted));- assert.deepEqual(resolveMobileSidebarConfig(loaded as typeof persisted), resolveMobileSidebarConfig(persisted));- }- }-});--test("malformed legacy mobile preferences retain safe sidebar access", () => {- for (const value of [null, "null", "invalid", "false", "{}", "[]"]) {- const loaded = loadStorage({[MOBILE_BARS_CONFIG_KEY]: value})[MOBILE_BARS_CONFIG_KEY];- assert.deepEqual(resolveMobileSidebarConfig(loaded as Parameters<typeof resolveMobileSidebarConfig>[0]),- {sidebarSwipe: true, sidebarButtons: value === null}, String(value));+test("reader and control preferences no longer create defaults in local storage", () => {+ const storage = loadStorage({});+ for (const key of ["local-mobile-bars", "local-outline", "local-pdftheme", "local-recent-docs"]) {+ assert.equal(Object.prototype.hasOwnProperty.call(storage, key), false, key);}});diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 6b07da4f88..ba9f96a7c2 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -1874,7 +1874,7 @@ export type SearchWidgetResult = { "content": string; "name": string; };export type SetAIRequestInput = { "agent"?: SettingAgentInput | null; "decision"?: SettingDecisionInput | null; "editing"?: SettingEditingInput | null; "embedding"?: SettingEmbeddingInput | null; "imageGeneration"?: SettingImageGenerationInput | null; "mcp"?: SettingMCPInput | null; "providers"?: Array<SettingProviderInput | null> | null; "rerank"?: SettingRerankInput | null; "web"?: SettingAIWebInput | null; };-export type SetAppearanceRequestInput = { "bodyGradient"?: SettingBodyGradientInput | null; "closeButtonBehavior"?: number | null; "codeBlockThemeDark"?: string | null; "codeBlockThemeLight"?: string | null; "darkThemes"?: Array<SettingAppearanceThemeInput | null> | null; "entryVisibility"?: SettingEntryVisibilityInput | null; "globalFontFamilies"?: Array<SettingEditorFontInput | null> | null; "hideStatusBar"?: boolean | null; "hideToolbar"?: boolean | null; "icon"?: string | null; "iconVer"?: string | null; "icons"?: Array<SettingAppearanceIconInput | null> | null; "lang"?: string | null; "lightThemes"?: Array<SettingAppearanceThemeInput | null> | null; "mode"?: number | null; "modeOS"?: boolean | null; "notifications"?: SettingNotificationsInput | null; "statusBar"?: SettingStatusBarInput | null; "themeDark"?: string | null; "themeJS"?: boolean | null; "themeLight"?: string | null; "themeVer"?: string | null; };+export type SetAppearanceRequestInput = { "bodyGradient"?: SettingBodyGradientInput | null; "closeButtonBehavior"?: number | null; "codeBlockThemeDark"?: string | null; "codeBlockThemeLight"?: string | null; "compactMode"?: boolean | null; "darkThemes"?: Array<SettingAppearanceThemeInput | null> | null; "entryVisibility"?: SettingEntryVisibilityInput | null; "globalFontFamilies"?: Array<SettingEditorFontInput | null> | null; "hideStatusBar"?: boolean | null; "hideToolbar"?: boolean | null; "icon"?: string | null; "iconVer"?: string | null; "icons"?: Array<SettingAppearanceIconInput | null> | null; "lang"?: string | null; "lightThemes"?: Array<SettingAppearanceThemeInput | null> | null; "menuMouseScroll"?: boolean | null; "mobileBars"?: SettingMobileBarsInput | null; "mode"?: number | null; "modeOS"?: boolean | null; "notifications"?: SettingNotificationsInput | null; "outlineKeepCurrentExpand"?: boolean | null; "pdfTheme"?: SettingPDFThemeInput | null; "statusBar"?: SettingStatusBarInput | null; "themeDark"?: string | null; "themeJS"?: boolean | null; "themeLight"?: string | null; "themeVer"?: string | null; };export type SetAssetAnnotationRequestInput = { "data": string; "path": string; };@@ -1908,7 +1908,7 @@ export type SetEntryVisibilityRequestInput = { "active"?: string | null; "profilexport type SetExportRequestInput = { "addTitle"?: boolean | null; "blockEmbedMode"?: number | null; "blockRefMode"?: number | null; "blockRefTextLeft"?: string | null; "blockRefTextRight"?: string | null; "fileAnnotationRefMode"?: number | null; "imageWatermarkDesc"?: string | null; "imageWatermarkStr"?: string | null; "includeRelatedDocs"?: boolean | null; "includeSubDocs"?: boolean | null; "inlineMemo"?: boolean | null; "markdownYFM"?: boolean | null; "pandocBin"?: string | null; "pandocParams"?: string | null; "paragraphBeginningSpace"?: boolean | null; "pdfFooter"?: string | null; "pdfWatermarkDesc"?: string | null; "pdfWatermarkStr"?: string | null; "removeAssetsID"?: boolean | null; "tagCloseMarker"?: string | null; "tagOpenMarker"?: string | null; };-export type SetFiletreeRequestInput = { "allowCreateDeeper"?: boolean | null; "alwaysSelectOpenedFile"?: boolean | null; "boxDocEnabled"?: boolean | null; "closeTabOnDoubleClick"?: boolean | null; "closeTabsOnStart"?: boolean | null; "createDocAtTop"?: boolean | null; "docCreateSaveBox"?: string | null; "docCreateSavePath"?: string | null; "docCreateTemplatePath"?: string | null; "docIconClickMode"?: number | null; "largeFileWarningSize"?: number | null; "maxListCount"?: number | null; "maxOpenTabCount"?: number | null; "noSplitScreenWhenOpenTab"?: boolean | null; "openFilesUseCurrentTab"?: boolean | null; "parentDocTitleClickMode"?: number | null; "recentDocsMaxListCount"?: number | null; "refCreateSaveBox"?: string | null; "refCreateSavePath"?: string | null; "removeDocWithoutConfirm"?: boolean | null; "shorthandSaveBox"?: string | null; "shorthandSavePath"?: string | null; "sort"?: number | null; "tabStartupMode"?: number | null; "useSVGDefaultIcon"?: boolean | null; "useSingleLineSave"?: boolean | null; };+export type SetFiletreeRequestInput = { "allowCreateDeeper"?: boolean | null; "alwaysSelectOpenedFile"?: boolean | null; "boxDocEnabled"?: boolean | null; "closeTabOnDoubleClick"?: boolean | null; "closeTabsOnStart"?: boolean | null; "createDocAtTop"?: boolean | null; "docCreateSaveBox"?: string | null; "docCreateSavePath"?: string | null; "docCreateTemplatePath"?: string | null; "docIconClickMode"?: number | null; "largeFileWarningSize"?: number | null; "maxListCount"?: number | null; "maxOpenTabCount"?: number | null; "noSplitScreenWhenOpenTab"?: boolean | null; "openFilesUseCurrentTab"?: boolean | null; "parentDocTitleClickMode"?: number | null; "recentDocsMaxListCount"?: number | null; "recentDocsSort"?: string | null; "refCreateSaveBox"?: string | null; "refCreateSavePath"?: string | null; "removeDocWithoutConfirm"?: boolean | null; "shorthandSaveBox"?: string | null; "shorthandSavePath"?: string | null; "sort"?: number | null; "tabStartupMode"?: number | null; "useSVGDefaultIcon"?: boolean | null; "useSingleLineSave"?: boolean | null; };export type SetFlashcardRequestInput = { "blockquote"?: boolean | null; "callout"?: boolean | null; "deck"?: boolean | null; "heading"?: boolean | null; "list"?: boolean | null; "mark"?: boolean | null; "maximumInterval"?: number | null; "newCardLimit"?: number | null; "requestRetention"?: number | null; "reviewCardLimit"?: number | null; "reviewMode"?: number | null; "superBlock"?: boolean | null; "weights"?: string | null; };@@ -1958,21 +1958,21 @@ export type SettingAIWeb = { "apiKey": string; "fetchProvider": string; "searchPexport type SettingAIWebInput = { "apiKey"?: string | null; "fetchProvider"?: string | null; "searchProvider"?: string | null; "timeout"?: number | null; };-export type SettingAgent = { "approvalPolicy": SettingApprovalPolicy | null; "capabilityPolicy": SettingCapabilityPolicy | null; "confirmTimeout": number; "maxCompletionTokens": number; "maxRetries": number; "maxToolCallRounds": number; "modelId": string; "sessionTimeout": number; "skills": SettingAgentSkills | null; "streamIdleTimeout": number; "temperature": number; };+export type SettingAgent = { "approvalPolicy": SettingApprovalPolicy | null; "capabilityPolicy": SettingCapabilityPolicy | null; "confirmTimeout": number; "maxCompletionTokens": number; "maxRetries": number; "maxToolCallRounds": number; "modelId": string; "sessionTimeout": number; "skills": SettingAgentSkills | null; "streamIdleTimeout": number; "streamingMarkdown": boolean; "temperature": number; };-export type SettingAgentInput = { "approvalPolicy"?: SettingApprovalPolicyInput | null; "capabilityPolicy"?: SettingCapabilityPolicyInput | null; "confirmTimeout"?: number | null; "maxCompletionTokens"?: number | null; "maxRetries"?: number | null; "maxToolCallRounds"?: number | null; "modelId"?: string | null; "sessionTimeout"?: number | null; "skills"?: SettingAgentSkillsInput | null; "streamIdleTimeout"?: number | null; "temperature"?: number | null; };+export type SettingAgentInput = { "approvalPolicy"?: SettingApprovalPolicyInput | null; "capabilityPolicy"?: SettingCapabilityPolicyInput | null; "confirmTimeout"?: number | null; "maxCompletionTokens"?: number | null; "maxRetries"?: number | null; "maxToolCallRounds"?: number | null; "modelId"?: string | null; "sessionTimeout"?: number | null; "skills"?: SettingAgentSkillsInput | null; "streamIdleTimeout"?: number | null; "streamingMarkdown"?: boolean | null; "temperature"?: number | null; };export type SettingAgentSkills = { "builtinDisabled": Array<string> | null; "userEnabled": Array<string> | null; };export type SettingAgentSkillsInput = { "builtinDisabled"?: Array<string> | null; "userEnabled"?: Array<string> | null; };-export type SettingAppearance = { "bodyGradient": SettingBodyGradient | null; "closeButtonBehavior": number; "codeBlockThemeDark": string; "codeBlockThemeLight": string; "darkThemes": Array<SettingAppearanceTheme | null> | null; "entryVisibility": SettingEntryVisibility | null; "globalFontFamilies": Array<SettingEditorFont | null> | null; "hideStatusBar": boolean; "hideToolbar": boolean; "icon": string; "iconVer": string; "icons": Array<SettingAppearanceIcon | null> | null; "lang": string; "lightThemes": Array<SettingAppearanceTheme | null> | null; "mode": number; "modeOS": boolean; "notifications": SettingNotifications | null; "statusBar": SettingStatusBar | null; "themeDark": string; "themeJS": boolean; "themeLight": string; "themeVer": string; };+export type SettingAppearance = { "bodyGradient": SettingBodyGradient | null; "closeButtonBehavior": number; "codeBlockThemeDark": string; "codeBlockThemeLight": string; "compactMode": boolean; "darkThemes": Array<SettingAppearanceTheme | null> | null; "entryVisibility": SettingEntryVisibility | null; "globalFontFamilies": Array<SettingEditorFont | null> | null; "hideStatusBar": boolean; "hideToolbar": boolean; "icon": string; "iconVer": string; "icons": Array<SettingAppearanceIcon | null> | null; "lang": string; "lightThemes": Array<SettingAppearanceTheme | null> | null; "menuMouseScroll": boolean; "mobileBars": SettingMobileBars | null; "mode": number; "modeOS": boolean; "notifications": SettingNotifications | null; "outlineKeepCurrentExpand": boolean; "pdfTheme": SettingPDFTheme | null; "statusBar": SettingStatusBar | null; "themeDark": string; "themeJS": boolean; "themeLight": string; "themeVer": string; };export type SettingAppearanceIcon = { "label": string; "name": string; };export type SettingAppearanceIconInput = { "label"?: string | null; "name"?: string | null; };-export type SettingAppearanceInput = { "bodyGradient"?: SettingBodyGradientInput | null; "closeButtonBehavior"?: number | null; "codeBlockThemeDark"?: string | null; "codeBlockThemeLight"?: string | null; "darkThemes"?: Array<SettingAppearanceThemeInput | null> | null; "entryVisibility"?: SettingEntryVisibilityInput | null; "globalFontFamilies"?: Array<SettingEditorFontInput | null> | null; "hideStatusBar"?: boolean | null; "hideToolbar"?: boolean | null; "icon"?: string | null; "iconVer"?: string | null; "icons"?: Array<SettingAppearanceIconInput | null> | null; "lang"?: string | null; "lightThemes"?: Array<SettingAppearanceThemeInput | null> | null; "mode"?: number | null; "modeOS"?: boolean | null; "notifications"?: SettingNotificationsInput | null; "statusBar"?: SettingStatusBarInput | null; "themeDark"?: string | null; "themeJS"?: boolean | null; "themeLight"?: string | null; "themeVer"?: string | null; };+export type SettingAppearanceInput = { "bodyGradient"?: SettingBodyGradientInput | null; "closeButtonBehavior"?: number | null; "codeBlockThemeDark"?: string | null; "codeBlockThemeLight"?: string | null; "compactMode"?: boolean | null; "darkThemes"?: Array<SettingAppearanceThemeInput | null> | null; "entryVisibility"?: SettingEntryVisibilityInput | null; "globalFontFamilies"?: Array<SettingEditorFontInput | null> | null; "hideStatusBar"?: boolean | null; "hideToolbar"?: boolean | null; "icon"?: string | null; "iconVer"?: string | null; "icons"?: Array<SettingAppearanceIconInput | null> | null; "lang"?: string | null; "lightThemes"?: Array<SettingAppearanceThemeInput | null> | null; "menuMouseScroll"?: boolean | null; "mobileBars"?: SettingMobileBarsInput | null; "mode"?: number | null; "modeOS"?: boolean | null; "notifications"?: SettingNotificationsInput | null; "outlineKeepCurrentExpand"?: boolean | null; "pdfTheme"?: SettingPDFThemeInput | null; "statusBar"?: SettingStatusBarInput | null; "themeDark"?: string | null; "themeJS"?: boolean | null; "themeLight"?: string | null; "themeVer"?: string | null; };export type SettingAppearanceTheme = { "frontends"?: Array<string>; "label": string; "name": string; };@@ -2068,9 +2068,9 @@ export type SettingExport = { "addTitle": boolean; "blockEmbedMode": number; "blexport type SettingExportInput = { "addTitle"?: boolean | null; "blockEmbedMode"?: number | null; "blockRefMode"?: number | null; "blockRefTextLeft"?: string | null; "blockRefTextRight"?: string | null; "fileAnnotationRefMode"?: number | null; "imageWatermarkDesc"?: string | null; "imageWatermarkStr"?: string | null; "includeRelatedDocs"?: boolean | null; "includeSubDocs"?: boolean | null; "inlineMemo"?: boolean | null; "markdownYFM"?: boolean | null; "pandocBin"?: string | null; "pandocParams"?: string | null; "paragraphBeginningSpace"?: boolean | null; "pdfFooter"?: string | null; "pdfWatermarkDesc"?: string | null; "pdfWatermarkStr"?: string | null; "removeAssetsID"?: boolean | null; "tagCloseMarker"?: string | null; "tagOpenMarker"?: string | null; };-export type SettingFileTree = { "allowCreateDeeper": boolean; "alwaysSelectOpenedFile": boolean; "boxDocEnabled": boolean | null; "closeTabOnDoubleClick": boolean; "closeTabsOnStart": boolean; "createDocAtTop": boolean | null; "docCreateSaveBox": string; "docCreateSavePath": string; "docCreateTemplatePath": string; "docIconClickMode": number; "largeFileWarningSize": number; "maxListCount": number; "maxOpenTabCount": number; "noSplitScreenWhenOpenTab": boolean; "openFilesUseCurrentTab": boolean; "parentDocTitleClickMode": number; "recentDocsMaxListCount": number; "refCreateSaveBox": string; "refCreateSavePath": string; "removeDocWithoutConfirm": boolean; "shorthandSaveBox": string; "shorthandSavePath": string; "sort": number; "tabStartupMode": number | null; "useSVGDefaultIcon": boolean | null; "useSingleLineSave": boolean; };+export type SettingFileTree = { "allowCreateDeeper": boolean; "alwaysSelectOpenedFile": boolean; "boxDocEnabled": boolean | null; "closeTabOnDoubleClick": boolean; "closeTabsOnStart": boolean; "createDocAtTop": boolean | null; "docCreateSaveBox": string; "docCreateSavePath": string; "docCreateTemplatePath": string; "docIconClickMode": number; "largeFileWarningSize": number; "maxListCount": number; "maxOpenTabCount": number; "noSplitScreenWhenOpenTab": boolean; "openFilesUseCurrentTab": boolean; "parentDocTitleClickMode": number; "recentDocsMaxListCount": number; "recentDocsSort": string; "refCreateSaveBox": string; "refCreateSavePath": string; "removeDocWithoutConfirm": boolean; "shorthandSaveBox": string; "shorthandSavePath": string; "sort": number; "tabStartupMode": number | null; "useSVGDefaultIcon": boolean | null; "useSingleLineSave": boolean; };-export type SettingFileTreeInput = { "allowCreateDeeper"?: boolean | null; "alwaysSelectOpenedFile"?: boolean | null; "boxDocEnabled"?: boolean | null; "closeTabOnDoubleClick"?: boolean | null; "closeTabsOnStart"?: boolean | null; "createDocAtTop"?: boolean | null; "docCreateSaveBox"?: string | null; "docCreateSavePath"?: string | null; "docCreateTemplatePath"?: string | null; "docIconClickMode"?: number | null; "largeFileWarningSize"?: number | null; "maxListCount"?: number | null; "maxOpenTabCount"?: number | null; "noSplitScreenWhenOpenTab"?: boolean | null; "openFilesUseCurrentTab"?: boolean | null; "parentDocTitleClickMode"?: number | null; "recentDocsMaxListCount"?: number | null; "refCreateSaveBox"?: string | null; "refCreateSavePath"?: string | null; "removeDocWithoutConfirm"?: boolean | null; "shorthandSaveBox"?: string | null; "shorthandSavePath"?: string | null; "sort"?: number | null; "tabStartupMode"?: number | null; "useSVGDefaultIcon"?: boolean | null; "useSingleLineSave"?: boolean | null; };+export type SettingFileTreeInput = { "allowCreateDeeper"?: boolean | null; "alwaysSelectOpenedFile"?: boolean | null; "boxDocEnabled"?: boolean | null; "closeTabOnDoubleClick"?: boolean | null; "closeTabsOnStart"?: boolean | null; "createDocAtTop"?: boolean | null; "docCreateSaveBox"?: string | null; "docCreateSavePath"?: string | null; "docCreateTemplatePath"?: string | null; "docIconClickMode"?: number | null; "largeFileWarningSize"?: number | null; "maxListCount"?: number | null; "maxOpenTabCount"?: number | null; "noSplitScreenWhenOpenTab"?: boolean | null; "openFilesUseCurrentTab"?: boolean | null; "parentDocTitleClickMode"?: number | null; "recentDocsMaxListCount"?: number | null; "recentDocsSort"?: string | null; "refCreateSaveBox"?: string | null; "refCreateSavePath"?: string | null; "removeDocWithoutConfirm"?: boolean | null; "shorthandSaveBox"?: string | null; "shorthandSavePath"?: string | null; "sort"?: number | null; "tabStartupMode"?: number | null; "useSVGDefaultIcon"?: boolean | null; "useSingleLineSave"?: boolean | null; };export type SettingFlashcard = { "blockquote": boolean; "callout": boolean; "deck": boolean; "heading": boolean; "list": boolean; "mark": boolean; "maximumInterval": number; "newCardLimit": number; "requestRetention": number; "reviewCardLimit": number; "reviewMode": number; "superBlock": boolean; "weights": string; };@@ -2100,6 +2100,10 @@ export type SettingMarkdown = { "blockFullWidthTaskList": boolean | null; "codeBexport type SettingMarkdownInput = { "blockFullWidthTaskList"?: boolean | null; "codeBlockMiddleDot"?: boolean | null; "inlineAsterisk"?: boolean | null; "inlineFullWidthStrikethrough"?: boolean | null; "inlineMark"?: boolean | null; "inlineMath"?: boolean | null; "inlineStrikethrough"?: boolean | null; "inlineSub"?: boolean | null; "inlineSup"?: boolean | null; "inlineTag"?: boolean | null; "inlineUnderscore"?: boolean | null; };+export type SettingMobileBars = { "autoHide": boolean | null; "sidebarButtons": boolean | null; "sidebarSwipe": boolean | null; };++export type SettingMobileBarsInput = { "autoHide"?: boolean | null; "sidebarButtons"?: boolean | null; "sidebarSwipe"?: boolean | null; };+export type SettingModel = { "contextLength"?: number; "displayName"?: string; "enabled": boolean; "id": string; "name": string; };export type SettingModelInput = { "contextLength"?: number | null; "displayName"?: string | null; "enabled"?: boolean | null; "id"?: string | null; "name"?: string | null; };@@ -2112,6 +2116,10 @@ export type SettingOCR = { "aiModelId"?: string; "auto": boolean; "model": strinexport type SettingOCRInput = { "aiModelId"?: string | null; "auto": boolean; "model": string; "provider": string; "reasoningEffort"?: string | null; "showEmpty"?: boolean | null; "showError"?: boolean | null; "showText"?: boolean | null; "thresholds"?: OCRThresholdsInput | null; };+export type SettingPDFTheme = { "annoColor": string; "dark": string; "light": string; };++export type SettingPDFThemeInput = { "annoColor"?: string | null; "dark"?: string | null; "light"?: string | null; };+export type SettingPatchData = { "issues": Array<SettingIssue> | null; };export type SettingPetalDisabledData = { "dataChangePlugins": Array<string> | null; "globalPetalChanged": boolean; "globalPetalDisabled": boolean; "globalPetalEnabled": boolean; "globalPetalRevision": number; "reloadPlugins": Array<string> | null; "uninstallPlugins": Array<string> | null; "unloadPlugins": Array<string> | null; };diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex 25149d0d9f..ff22baeebe 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -169,6 +169,8 @@ declare namespace Config {* AI agent global settings*/export interface IAgent {+ /** 流式输出渲染 Markdown,默认关闭,重置普通设置时随 AI 配置保留 */+ streamingMarkdown: boolean;modelId: string;sessionTimeout: number;streamIdleTimeout: number;@@ -337,6 +339,14 @@ declare namespace Config {* SiYuan appearance related configuration*/export interface IAppearance {+ /** 用户偏好保存在 conf.json;升级不读取旧 local.json 键,外观重置时恢复默认值 */+ compactMode: boolean;+ /** 默认关闭;新建空工作空间默认开启 */+ menuMouseScroll: boolean;+ pdfTheme: {light: string; dark: string; annoColor: string};+ outlineKeepCurrentExpand: boolean;+ /** 三项默认开启,侧栏滑动与按钮至少保留一种 */+ mobileBars: {autoHide: boolean; sidebarSwipe: boolean; sidebarButtons: boolean};/** 背景渐变,未配置时根据工作空间名称自动配色 */bodyGradient?: {mode: string;@@ -957,6 +967,8 @@ declare namespace Config {* Document tree related configuration*/export interface IFileTree {+ /** 默认 viewedAt,未知值回落默认值;文档树设置重置时恢复默认 */+ recentDocsSort: string;/*** Whether to allow the creation of sub-documents deeper than 7 levels*/diff --git a/app/src/util/appearanceAssets.test.ts b/app/src/util/appearanceAssets.test.tsindex 4dcc78f68e..9ce9c0f6d9 100644--- a/app/src/util/appearanceAssets.test.ts+++ b/app/src/util/appearanceAssets.test.ts@@ -41,6 +41,7 @@ const createAssets = (ensureLute: () => Promise<void> = async () => {}, client:};const html = element({"data-theme-mode": "light"});const appearance = {+ pdfTheme: {light: "light", dark: "dark", annoColor: "var(--b3-pdf-background1)"},lang: "en", mode: 0, modeOS: false, themeLight: "custom", themeDark: "midnight", themeVer: "1.0.0",icon: "custom", iconVer: "1.0.0", themeJS: false,lightThemes: [{name: "custom", label: "Custom", frontends: ["all"]}],diff --git a/app/src/util/assets.ts b/app/src/util/assets.tsindex 58d34f2c0c..96013740c9 100644--- a/app/src/util/assets.ts+++ b/app/src/util/assets.ts@@ -221,8 +221,8 @@ export const loadAssets = async (appearance: Config.IAppearance) => {getAllModels().graph.forEach(item => {item.searchGraph();});- const pdfTheme = window.siyuan.config.appearance.mode === 0 ? window.siyuan.storage[Constants.LOCAL_PDFTHEME].light :- window.siyuan.storage[Constants.LOCAL_PDFTHEME].dark;+ const pdfTheme = window.siyuan.config.appearance.mode === 0 ? window.siyuan.config.appearance.pdfTheme.light :+ window.siyuan.config.appearance.pdfTheme.dark;document.querySelectorAll(".pdf__outer").forEach(item => {const darkElement = item.querySelector("#pdfDark");const lightElement = item.querySelector("#pdfLight");diff --git a/app/src/window/index.ts b/app/src/window/index.tsindex 6da02875f8..7d6e117b98 100644--- a/app/src/window/index.ts+++ b/app/src/window/index.ts@@ -3,9 +3,6 @@ import {closeNotebookHistoryDialogs} from "../history/notebookDialogs";import {closeNotebookLivePhotos} from "../protyle/preview/livePhoto";import {Constants} from "../constants";import {refreshSettingConfig} from "../config/setting/sync";-import {onAgentStreamingMarkdownStorageChanged} from "../config/tabs/ai/agentStreamingMarkdown";-import {onCompactModeStorageChanged, refreshCompactMode} from "../config/tabs/compactMode";-import {onMenuMouseScrollStorageChanged, refreshMenuMouseScroll} from "../config/tabs/menuMouseScroll";import {systemConfig} from "../config/systemConfig";import {Menus} from "../menus";import {Model} from "../layout/Model";@@ -66,8 +63,7 @@ class App {type: "main",callback: () => {if (window.siyuan.isReady) {- void refreshCompactMode().catch(error => console.error("Could not refresh compact mode", error));- void refreshMenuMouseScroll().catch(error => console.error("Could not refresh menu mouse scrolling", error));+ void refreshSettingConfig().catch(error => console.error("Could not refresh settings", error));}},msgCallback: (data) => {@@ -137,34 +133,22 @@ class App {case "setLocalStorageVal":if (window.siyuan.storage) {window.siyuan.storage[data.data.key] = data.data.val;- onAgentStreamingMarkdownStorageChanged(data.data.key);- onCompactModeStorageChanged(data.data.key);- onMenuMouseScrollStorageChanged(data.data.key);onWindowWorkspaceStorageChanged(data.data.key);}break;case "setLocalStorageVals":Object.keys(data.data.keyVals).forEach((k) => {window.siyuan.storage[k] = data.data.keyVals[k];- onAgentStreamingMarkdownStorageChanged(k);- onCompactModeStorageChanged(k);- onMenuMouseScrollStorageChanged(k);onWindowWorkspaceStorageChanged(k);});break;case "removeLocalStorageVal":delete window.siyuan.storage[data.data.key];- onAgentStreamingMarkdownStorageChanged(data.data.key);- onCompactModeStorageChanged(data.data.key);- onMenuMouseScrollStorageChanged(data.data.key);onWindowWorkspaceStorageChanged(data.data.key);break;case "removeLocalStorageVals":data.data.keys.forEach((k: string) => {delete window.siyuan.storage[k];- onAgentStreamingMarkdownStorageChanged(k);- onCompactModeStorageChanged(k);- onMenuMouseScrollStorageChanged(k);onWindowWorkspaceStorageChanged(k);});break;diff --git a/kernel/api/contract_setting_test.go b/kernel/api/contract_setting_test.goindex 6b99d81a1c..007e8b0d8d 100644--- a/kernel/api/contract_setting_test.go+++ b/kernel/api/contract_setting_test.go@@ -86,6 +86,22 @@ func TestAPIContractSettingConfigCompatibility(t *testing.T) {compareSettingConfig(t, apicontract.SetPublish, func() *conf.Publish { return &conf.Publish{} }, append(common, `{"auth":null,"port":65535.0}`, `{"port":65536}`, `{"auth":{"accounts":[null]}}`))}+func TestAPIContractSettingPreferencesCompatibility(t *testing.T) {+ compareSettingConfig(t, apicontract.SetAI, func() *conf.AI { return &conf.AI{} }, []string{+ `{}`, `{"agent":{"streamingMarkdown":true}}`, `{"agent":{"streamingMarkdown":false}}`,+ `{"agent":{"streamingMarkdown":null}}`, `{"agent":{"streamingMarkdown":"true"}}`,+ })+ compareSettingConfig(t, apicontract.SetAppearance, conf.NewAppearance, []string{+ `{}`, `{"compactMode":true,"menuMouseScroll":false,"outlineKeepCurrentExpand":true}`,+ `{"pdfTheme":{"light":"dark","dark":"light","annoColor":"red"},"mobileBars":{"autoHide":false}}`,+ `{"pdfTheme":null,"mobileBars":null}`, `{"mobileBars":{"sidebarSwipe":null,"sidebarButtons":false}}`,+ `{"compactMode":"true"}`, `{"pdfTheme":{"light":false}}`, `{"mobileBars":{"autoHide":1}}`,+ })+ compareSettingConfig(t, apicontract.SetFiletree, conf.NewFileTree, []string{+ `{}`, `{"recentDocsSort":"updated"}`, `{"recentDocsSort":null}`, `{"recentDocsSort":true}`,+ })+}+func TestAPIContractSettingMindmapCompatibility(t *testing.T) {compareSettingConfig(t, apicontract.SetSearch, func() *conf.Search { return &conf.Search{} }, []string{`{}`, `{"mindmap":true,"mindmapItem":false}`, `{"mindmap":false,"mindmapItem":true}`,diff --git a/kernel/api/setting_contract.go b/kernel/api/setting_contract.goindex 8a3216f010..e9d9a4173c 100644--- a/kernel/api/setting_contract.go+++ b/kernel/api/setting_contract.go@@ -158,6 +158,7 @@ func settingAgentPayload(value *conf.Agent) *apicontract.SettingAgent {return nil}result := &apicontract.SettingAgent{}+ result.StreamingMarkdown = value.StreamingMarkdownresult.ModelID = value.ModelIDresult.SessionTimeout = value.SessionTimeoutresult.StreamIdleTimeout = value.StreamIdleTimeout@@ -502,6 +503,7 @@ func settingFileTreePayload(value *conf.FileTree) *apicontract.SettingFileTree {return nil}result := &apicontract.SettingFileTree{}+ result.RecentDocsSort = value.RecentDocsSortresult.AlwaysSelectOpenedFile = value.AlwaysSelectOpenedFileresult.OpenFilesUseCurrentTab = value.OpenFilesUseCurrentTabresult.CloseTabOnDoubleClick = value.CloseTabOnDoubleClick@@ -584,6 +586,15 @@ func settingAppearancePayload(value *conf.Appearance) *apicontract.SettingAppearreturn nil}result := &apicontract.SettingAppearance{}+ result.CompactMode = value.CompactMode+ result.MenuMouseScroll = value.MenuMouseScroll+ result.OutlineKeepCurrentExpand = value.OutlineKeepCurrentExpand+ if value.PDFTheme != nil {+ result.PDFTheme = &apicontract.SettingPDFTheme{Light: value.PDFTheme.Light, Dark: value.PDFTheme.Dark, AnnoColor: value.PDFTheme.AnnoColor}+ }+ if value.MobileBars != nil {+ result.MobileBars = &apicontract.SettingMobileBars{AutoHide: value.MobileBars.AutoHide, SidebarSwipe: value.MobileBars.SidebarSwipe, SidebarButtons: value.MobileBars.SidebarButtons}+ }result.BodyGradient = settingBodyGradientPayload(value.BodyGradient)if value.GlobalFontFamilies != nil {result.GlobalFontFamilies = make([]*apicontract.SettingEditorFont, len(value.GlobalFontFamilies))diff --git a/kernel/api/system_import_preferences_test.go b/kernel/api/system_import_preferences_test.goindex b66917407b..576ce58c7c 100644--- a/kernel/api/system_import_preferences_test.go+++ b/kernel/api/system_import_preferences_test.go@@ -70,6 +70,13 @@ func TestAPIContractImportedPortablePreferences(t *testing.T) {appearance.HideStatusBar = trueappearance.ModeOS = falseappearance.Mode = 1+ appearance.CompactMode = true+ appearance.MenuMouseScroll = true+ appearance.OutlineKeepCurrentExpand = true+ appearance.PDFTheme = &conf.PDFTheme{Light: "dark", Dark: "light", AnnoColor: "red"}+ appearance.MobileBars = &conf.MobileBars{AutoHide: new(false), SidebarSwipe: new(false), SidebarButtons: new(true)}+ source.FileTree.Load().RecentDocsSort = "updated"+ source.AI.Load().Agent.StreamingMarkdown = trueappearance.GlobalFontFamilies = []*conf.EditorFont{{Family: "serif"}}appearance.EntryVisibility = &conf.EntryVisibility{Version: conf.EntryVisibilityVersion, Active: "portable",Profiles: []*conf.EntryVisibilityProfile{{ID: "portable", Name: "Portable", Defaults: conf.EntryVisibilityProfileFull,@@ -117,6 +124,12 @@ func TestAPIContractImportedPortablePreferences(t *testing.T) {t.Fatalf("import failed: %d", code)}actualAppearance := target.Appearance.Load()+ if !actualAppearance.CompactMode || !actualAppearance.MenuMouseScroll || !actualAppearance.OutlineKeepCurrentExpand ||+ !reflect.DeepEqual(actualAppearance.PDFTheme, source.Appearance.Load().PDFTheme) ||+ !reflect.DeepEqual(actualAppearance.MobileBars, source.Appearance.Load().MobileBars) ||+ target.FileTree.Load().RecentDocsSort != "updated" || !target.AI.Load().Agent.StreamingMarkdown {+ t.Fatal("reader and control preferences did not survive configuration transfer")+ }if target.Lang != "ja" || actualAppearance.Lang != "ja" || !actualAppearance.HideStatusBar || actualAppearance.Mode != 1 || actualAppearance.ModeOS ||!reflect.DeepEqual(actualAppearance.EntryVisibility, source.Appearance.Load().EntryVisibility) ||!reflect.DeepEqual(actualAppearance.GlobalFontFamilies, source.Appearance.Load().GlobalFontFamilies) ||@@ -146,6 +159,13 @@ func TestAPIContractImportedPortablePreferences(t *testing.T) {!reflect.DeepEqual(saved.Variables.Load(), source.Variables.Load()) || !reflect.DeepEqual(saved.UILayout.Load(), source.UILayout.Load()) {t.Fatalf("imported preferences were not persisted: %v", err)}+ if !reflect.DeepEqual(saved.Appearance.Load().PDFTheme, source.Appearance.Load().PDFTheme) ||+ !reflect.DeepEqual(saved.Appearance.Load().MobileBars, source.Appearance.Load().MobileBars) ||+ !saved.Appearance.Load().CompactMode || !saved.Appearance.Load().MenuMouseScroll ||+ !saved.Appearance.Load().OutlineKeepCurrentExpand || saved.FileTree.Load().RecentDocsSort != "updated" ||+ !saved.AI.Load().Agent.StreamingMarkdown {+ t.Fatal("imported reader and control preferences were not persisted")+ }})}}diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex bfedcd3487..bee7d18db9 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -39975,6 +39975,16 @@}]},+ "compactMode": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"darkThemes": {"anyOf": [{@@ -40115,6 +40125,26 @@}]},+ "menuMouseScroll": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "mobileBars": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingMobileBarsInput"+ },+ {+ "type": "null"+ }+ ]+ },"mode": {"anyOf": [{@@ -40145,6 +40175,26 @@}]},+ "outlineKeepCurrentExpand": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "pdfTheme": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingPDFThemeInput"+ },+ {+ "type": "null"+ }+ ]+ },"statusBar": {"anyOf": [{@@ -41680,6 +41730,16 @@}]},+ "recentDocsSort": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },"refCreateSaveBox": {"anyOf": [{@@ -43051,6 +43111,9 @@"streamIdleTimeout": {"type": "integer"},+ "streamingMarkdown": {+ "type": "boolean"+ },"temperature": {"type": "number"}@@ -43066,6 +43129,7 @@"sessionTimeout","skills","streamIdleTimeout",+ "streamingMarkdown","temperature"],"additionalProperties": false@@ -43173,6 +43237,16 @@}]},+ "streamingMarkdown": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"temperature": {"anyOf": [{@@ -43276,6 +43350,9 @@"codeBlockThemeLight": {"type": "string"},+ "compactMode": {+ "type": "boolean"+ },"darkThemes": {"anyOf": [{@@ -43381,6 +43458,19 @@}]},+ "menuMouseScroll": {+ "type": "boolean"+ },+ "mobileBars": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingMobileBars"+ },+ {+ "type": "null"+ }+ ]+ },"mode": {"type": "integer"},@@ -43397,6 +43487,19 @@}]},+ "outlineKeepCurrentExpand": {+ "type": "boolean"+ },+ "pdfTheme": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingPDFTheme"+ },+ {+ "type": "null"+ }+ ]+ },"statusBar": {"anyOf": [{@@ -43425,6 +43528,7 @@"closeButtonBehavior","codeBlockThemeDark","codeBlockThemeLight",+ "compactMode","darkThemes","entryVisibility","globalFontFamilies",@@ -43435,9 +43539,13 @@"icons","lang","lightThemes",+ "menuMouseScroll",+ "mobileBars","mode","modeOS","notifications",+ "outlineKeepCurrentExpand",+ "pdfTheme","statusBar","themeDark","themeJS",@@ -43531,6 +43639,16 @@}]},+ "compactMode": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"darkThemes": {"anyOf": [{@@ -43671,6 +43789,26 @@}]},+ "menuMouseScroll": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "mobileBars": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingMobileBarsInput"+ },+ {+ "type": "null"+ }+ ]+ },"mode": {"anyOf": [{@@ -43701,6 +43839,26 @@}]},+ "outlineKeepCurrentExpand": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "pdfTheme": {+ "anyOf": [+ {+ "$ref": "#/$defs/SettingPDFThemeInput"+ },+ {+ "type": "null"+ }+ ]+ },"statusBar": {"anyOf": [{@@ -46733,6 +46891,9 @@"recentDocsMaxListCount": {"type": "integer"},+ "recentDocsSort": {+ "type": "string"+ },"refCreateSaveBox": {"type": "string"},@@ -46793,6 +46954,7 @@"openFilesUseCurrentTab","parentDocTitleClickMode","recentDocsMaxListCount",+ "recentDocsSort","refCreateSaveBox","refCreateSavePath","removeDocWithoutConfirm",@@ -46978,6 +47140,16 @@}]},+ "recentDocsSort": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },"refCreateSaveBox": {"anyOf": [{@@ -47910,6 +48082,83 @@},"additionalProperties": false},+ "SettingMobileBars": {+ "type": "object",+ "properties": {+ "autoHide": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "sidebarButtons": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "sidebarSwipe": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "autoHide",+ "sidebarButtons",+ "sidebarSwipe"+ ],+ "additionalProperties": false+ },+ "SettingMobileBarsInput": {+ "type": "object",+ "properties": {+ "autoHide": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "sidebarButtons": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "sidebarSwipe": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": false+ },"SettingModel": {"type": "object","properties": {@@ -48219,6 +48468,62 @@],"additionalProperties": false},+ "SettingPDFTheme": {+ "type": "object",+ "properties": {+ "annoColor": {+ "type": "string"+ },+ "dark": {+ "type": "string"+ },+ "light": {+ "type": "string"+ }+ },+ "required": [+ "annoColor",+ "dark",+ "light"+ ],+ "additionalProperties": false+ },+ "SettingPDFThemeInput": {+ "type": "object",+ "properties": {+ "annoColor": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "dark": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "light": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": false+ },"SettingPatchData": {"type": "object","properties": {diff --git a/kernel/apicontract/setting.go b/kernel/apicontract/setting.goindex 987b5b0dde..dac94d6cf5 100644--- a/kernel/apicontract/setting.go+++ b/kernel/apicontract/setting.go@@ -100,6 +100,8 @@ type SettingDecisionProfile struct {}type SettingAgent struct {+ // 默认关闭,保存在 conf.json;升级不读取前端旧键,重置普通设置时随 AI 配置保留。+ StreamingMarkdown bool `json:"streamingMarkdown" api:"optional,nullable"`ModelID string `json:"modelId" api:"optional,nullable"`SessionTimeout int `json:"sessionTimeout" api:"optional,nullable"`StreamIdleTimeout int `json:"streamIdleTimeout" api:"optional,nullable"`@@ -337,9 +339,11 @@ type SettingExport struct {}type SettingFileTree struct {- AlwaysSelectOpenedFile bool `json:"alwaysSelectOpenedFile" api:"optional,nullable"`- OpenFilesUseCurrentTab bool `json:"openFilesUseCurrentTab" api:"optional,nullable"`- CloseTabOnDoubleClick bool `json:"closeTabOnDoubleClick" api:"optional,nullable"`+ // 默认 viewedAt;支持 created、updated、openAt、closedAt,未知值回落 viewedAt。重置文档树设置时恢复默认。+ RecentDocsSort string `json:"recentDocsSort" api:"optional,nullable"`+ AlwaysSelectOpenedFile bool `json:"alwaysSelectOpenedFile" api:"optional,nullable"`+ OpenFilesUseCurrentTab bool `json:"openFilesUseCurrentTab" api:"optional,nullable"`+ CloseTabOnDoubleClick bool `json:"closeTabOnDoubleClick" api:"optional,nullable"`// 单击文档图标或笔记本图标的行为:0 修改图标,1 展开或折叠子文档。无子文档时,1 在有可打开文档时打开文档,否则修改图标。// 超出取值范围的输入按 0 处理。已废弃的 docIconClickExpand 不再读取,旧配置升级后回到 0。DocIconClickMode int `json:"docIconClickMode" api:"optional,nullable"`@@ -415,28 +419,50 @@ type SettingSearch struct {}type SettingAppearance struct {- BodyGradient *SettingBodyGradient `json:"bodyGradient" api:"optional,nullable"`- GlobalFontFamilies []*SettingEditorFont `json:"globalFontFamilies" api:"optional,nullable"`- Mode int `json:"mode" api:"optional,nullable"`- ModeOS bool `json:"modeOS" api:"optional,nullable"`- DarkThemes []*SettingAppearanceTheme `json:"darkThemes" api:"optional,nullable"`- LightThemes []*SettingAppearanceTheme `json:"lightThemes" api:"optional,nullable"`- ThemeDark string `json:"themeDark" api:"optional,nullable"`- ThemeLight string `json:"themeLight" api:"optional,nullable"`- ThemeVer string `json:"themeVer" api:"optional,nullable"`- Icons []*SettingAppearanceIcon `json:"icons" api:"optional,nullable"`- Icon string `json:"icon" api:"optional,nullable"`- IconVer string `json:"iconVer" api:"optional,nullable"`- CodeBlockThemeLight string `json:"codeBlockThemeLight" api:"optional,nullable"`- CodeBlockThemeDark string `json:"codeBlockThemeDark" api:"optional,nullable"`- Lang string `json:"lang" api:"optional,nullable"`- ThemeJS bool `json:"themeJS" api:"optional,nullable"`- CloseButtonBehavior int `json:"closeButtonBehavior" api:"optional,nullable"`- HideToolbar bool `json:"hideToolbar" api:"optional,nullable"`- HideStatusBar bool `json:"hideStatusBar" api:"optional,nullable"`- StatusBar *SettingStatusBar `json:"statusBar" api:"optional,nullable"`- Notifications *SettingNotifications `json:"notifications" api:"optional,nullable"`- EntryVisibility *SettingEntryVisibility `json:"entryVisibility" api:"optional,nullable"`+ // 以下用户偏好保存在 conf.json,支持配置导入导出;不读取或迁移 local.json 旧键。+ // 重置外观设置时恢复默认;紧凑模式与菜单鼠标滚动默认关闭,新建空工作空间的菜单鼠标滚动默认开启。+ CompactMode bool `json:"compactMode" api:"optional,nullable"`+ MenuMouseScroll bool `json:"menuMouseScroll" api:"optional,nullable"`+ PDFTheme *SettingPDFTheme `json:"pdfTheme" api:"optional,nullable"`+ OutlineKeepCurrentExpand bool `json:"outlineKeepCurrentExpand" api:"optional,nullable"`+ MobileBars *SettingMobileBars `json:"mobileBars" api:"optional,nullable"`+ BodyGradient *SettingBodyGradient `json:"bodyGradient" api:"optional,nullable"`+ GlobalFontFamilies []*SettingEditorFont `json:"globalFontFamilies" api:"optional,nullable"`+ Mode int `json:"mode" api:"optional,nullable"`+ ModeOS bool `json:"modeOS" api:"optional,nullable"`+ DarkThemes []*SettingAppearanceTheme `json:"darkThemes" api:"optional,nullable"`+ LightThemes []*SettingAppearanceTheme `json:"lightThemes" api:"optional,nullable"`+ ThemeDark string `json:"themeDark" api:"optional,nullable"`+ ThemeLight string `json:"themeLight" api:"optional,nullable"`+ ThemeVer string `json:"themeVer" api:"optional,nullable"`+ Icons []*SettingAppearanceIcon `json:"icons" api:"optional,nullable"`+ Icon string `json:"icon" api:"optional,nullable"`+ IconVer string `json:"iconVer" api:"optional,nullable"`+ CodeBlockThemeLight string `json:"codeBlockThemeLight" api:"optional,nullable"`+ CodeBlockThemeDark string `json:"codeBlockThemeDark" api:"optional,nullable"`+ Lang string `json:"lang" api:"optional,nullable"`+ ThemeJS bool `json:"themeJS" api:"optional,nullable"`+ CloseButtonBehavior int `json:"closeButtonBehavior" api:"optional,nullable"`+ HideToolbar bool `json:"hideToolbar" api:"optional,nullable"`+ HideStatusBar bool `json:"hideStatusBar" api:"optional,nullable"`+ StatusBar *SettingStatusBar `json:"statusBar" api:"optional,nullable"`+ Notifications *SettingNotifications `json:"notifications" api:"optional,nullable"`+ EntryVisibility *SettingEntryVisibility `json:"entryVisibility" api:"optional,nullable"`+}++// SettingPDFTheme 明亮界面默认 light,暗黑界面默认 dark;主题值只接受 light、dark。+// 标注颜色为空时使用 var(--b3-pdf-background1),允许保存用户选择的 CSS 颜色。+type SettingPDFTheme struct {+ Light string `json:"light" api:"optional,nullable"`+ Dark string `json:"dark" api:"optional,nullable"`+ AnnoColor string `json:"annoColor" api:"optional,nullable"`+}++// SettingMobileBars 三项默认开启,侧栏滑动与按钮不能同时关闭。+type SettingMobileBars struct {+ AutoHide *bool `json:"autoHide" api:"optional,nullable"`+ SidebarSwipe *bool `json:"sidebarSwipe" api:"optional,nullable"`+ SidebarButtons *bool `json:"sidebarButtons" api:"optional,nullable"`}type SettingBodyGradient struct {diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex 5fe0d6e9ae..9bc621700d 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -74,6 +74,7 @@ const DefaultAgentSessionTimeout = 1800const MaxAgentSessionTimeout = 3600type Agent struct {+ StreamingMarkdown bool `json:"streamingMarkdown"` // 智能体流式输出时渲染 MarkdownModelID string `json:"modelId"`SessionTimeout int `json:"sessionTimeout"`StreamIdleTimeout int `json:"streamIdleTimeout"`diff --git a/kernel/conf/appearance.go b/kernel/conf/appearance.goindex a941a562cd..fd43c7816a 100644--- a/kernel/conf/appearance.go+++ b/kernel/conf/appearance.go@@ -19,28 +19,53 @@ package confimport "github.com/siyuan-note/siyuan/kernel/util"type Appearance struct {- BodyGradient *BodyGradient `json:"bodyGradient"` // 背景渐变,空值表示自动配色- GlobalFontFamilies []*EditorFont `json:"globalFontFamilies"` // 按优先级排列的全局默认字体- Mode int `json:"mode"` // 模式:0:明亮,1:暗黑- ModeOS bool `json:"modeOS"` // 模式是否跟随系统- DarkThemes []*AppearanceTheme `json:"darkThemes"` // 暗黑模式外观主题列表- LightThemes []*AppearanceTheme `json:"lightThemes"` // 明亮模式外观主题列表- ThemeDark string `json:"themeDark"` // 选择的暗黑模式外观主题- ThemeLight string `json:"themeLight"` // 选择的明亮模式外观主题- ThemeVer string `json:"themeVer"` // 选择的主题版本- Icons []*AppearanceIcon `json:"icons"` // 图标列表- Icon string `json:"icon"` // 选择的图标- IconVer string `json:"iconVer"` // 选择的图标版本- CodeBlockThemeLight string `json:"codeBlockThemeLight"` // 明亮模式下代码块主题- CodeBlockThemeDark string `json:"codeBlockThemeDark"` // 暗黑模式下代码块主题- Lang string `json:"lang"` // 选择的界面语言,同 AppConf.Lang- ThemeJS bool `json:"themeJS"` // 是否启用了主题 JavaScript- CloseButtonBehavior int `json:"closeButtonBehavior"` // 关闭按钮行为,0:退出,1:最小化到托盘- HideToolbar bool `json:"hideToolbar"` // 是否隐藏顶栏工具栏- HideStatusBar bool `json:"hideStatusBar"` // 是否隐藏底部状态栏- StatusBar *util.StatusBar `json:"statusBar"` // 底部状态栏配置- Notifications *util.Notifications `json:"notifications"` // 外观通知开关配置- EntryVisibility *EntryVisibility `json:"entryVisibility"` // 桌面端入口可见性配置+ CompactMode bool `json:"compactMode"` // 桌面端紧凑模式+ MenuMouseScroll bool `json:"menuMouseScroll"` // 桌面端菜单鼠标滚动+ PDFTheme *PDFTheme `json:"pdfTheme"` // PDF 阅读主题与标注颜色+ OutlineKeepCurrentExpand bool `json:"outlineKeepCurrentExpand"` // 大纲保持当前标题展开+ MobileBars *MobileBars `json:"mobileBars"` // 移动端工具栏与侧栏访问偏好+ BodyGradient *BodyGradient `json:"bodyGradient"` // 背景渐变,空值表示自动配色+ GlobalFontFamilies []*EditorFont `json:"globalFontFamilies"` // 按优先级排列的全局默认字体+ Mode int `json:"mode"` // 模式:0:明亮,1:暗黑+ ModeOS bool `json:"modeOS"` // 模式是否跟随系统+ DarkThemes []*AppearanceTheme `json:"darkThemes"` // 暗黑模式外观主题列表+ LightThemes []*AppearanceTheme `json:"lightThemes"` // 明亮模式外观主题列表+ ThemeDark string `json:"themeDark"` // 选择的暗黑模式外观主题+ ThemeLight string `json:"themeLight"` // 选择的明亮模式外观主题+ ThemeVer string `json:"themeVer"` // 选择的主题版本+ Icons []*AppearanceIcon `json:"icons"` // 图标列表+ Icon string `json:"icon"` // 选择的图标+ IconVer string `json:"iconVer"` // 选择的图标版本+ CodeBlockThemeLight string `json:"codeBlockThemeLight"` // 明亮模式下代码块主题+ CodeBlockThemeDark string `json:"codeBlockThemeDark"` // 暗黑模式下代码块主题+ Lang string `json:"lang"` // 选择的界面语言,同 AppConf.Lang+ ThemeJS bool `json:"themeJS"` // 是否启用了主题 JavaScript+ CloseButtonBehavior int `json:"closeButtonBehavior"` // 关闭按钮行为,0:退出,1:最小化到托盘+ HideToolbar bool `json:"hideToolbar"` // 是否隐藏顶栏工具栏+ HideStatusBar bool `json:"hideStatusBar"` // 是否隐藏底部状态栏+ StatusBar *util.StatusBar `json:"statusBar"` // 底部状态栏配置+ Notifications *util.Notifications `json:"notifications"` // 外观通知开关配置+ EntryVisibility *EntryVisibility `json:"entryVisibility"` // 桌面端入口可见性配置+}++type PDFTheme struct {+ Light string `json:"light"`+ Dark string `json:"dark"`+ AnnoColor string `json:"annoColor"`+}++type MobileBars struct {+ AutoHide *bool `json:"autoHide"`+ SidebarSwipe *bool `json:"sidebarSwipe"`+ SidebarButtons *bool `json:"sidebarButtons"`+}++func NewPDFTheme() *PDFTheme {+ return &PDFTheme{Light: "light", Dark: "dark", AnnoColor: "var(--b3-pdf-background1)"}+}++func NewMobileBars() *MobileBars {+ return &MobileBars{AutoHide: new(true), SidebarSwipe: new(true), SidebarButtons: new(true)}}type BodyGradient struct {@@ -61,6 +86,8 @@ func NewAppearance() *Appearance {// NewAppearanceForContainer 使用显式容器参数选择状态栏默认项。func NewAppearanceForContainer(mobile bool) *Appearance {return &Appearance{+ PDFTheme: NewPDFTheme(),+ MobileBars: NewMobileBars(),GlobalFontFamilies: []*EditorFont{},Mode: 0,ModeOS: true,diff --git a/kernel/conf/filetree.go b/kernel/conf/filetree.goindex 3560dfdb91..6894f329af 100644--- a/kernel/conf/filetree.go+++ b/kernel/conf/filetree.go@@ -21,6 +21,7 @@ import ()type FileTree struct {+ RecentDocsSort string `json:"recentDocsSort"` // 最近文档排序方式AlwaysSelectOpenedFile bool `json:"alwaysSelectOpenedFile"` // 是否自动选中当前打开的文件OpenFilesUseCurrentTab bool `json:"openFilesUseCurrentTab"` // 在当前页签打开文件CloseTabOnDoubleClick bool `json:"closeTabOnDoubleClick"` // 是否使用双击关闭页签@@ -51,6 +52,7 @@ type FileTree struct {func NewFileTree() *FileTree {return &FileTree{+ RecentDocsSort: "viewedAt",AlwaysSelectOpenedFile: false,OpenFilesUseCurrentTab: false,CloseTabOnDoubleClick: false,diff --git a/kernel/conf/preferences_test.go b/kernel/conf/preferences_test.gonew file mode 100644index 0000000000..e6cf08d200--- /dev/null+++ b/kernel/conf/preferences_test.go@@ -0,0 +1,47 @@+package conf++import (+ "encoding/json"+ "reflect"+ "testing"+)++func TestPreferenceDefaultsAndNormalization(t *testing.T) {+ for _, raw := range []string{`{}`, `{"pdfTheme":null,"mobileBars":null}`, `{"pdfTheme":{},"mobileBars":{}}`} {+ appearance := &Appearance{}+ if err := json.Unmarshal([]byte(raw), appearance); err != nil {+ t.Fatal(err)+ }+ NormalizeAppearance(appearance, false)+ if appearance.CompactMode || appearance.MenuMouseScroll || appearance.OutlineKeepCurrentExpand ||+ !reflect.DeepEqual(appearance.PDFTheme, NewPDFTheme()) || !reflect.DeepEqual(appearance.MobileBars, NewMobileBars()) {+ t.Fatalf("unexpected preference defaults: %+v", appearance)+ }+ }+ appearance := &Appearance{CompactMode: true, MenuMouseScroll: true, OutlineKeepCurrentExpand: true,+ PDFTheme: &PDFTheme{Light: "invalid", Dark: "", AnnoColor: " "},+ MobileBars: &MobileBars{AutoHide: new(false), SidebarSwipe: new(false), SidebarButtons: new(false)}}+ NormalizeAppearance(appearance, true)+ if !appearance.CompactMode || !appearance.MenuMouseScroll || !appearance.OutlineKeepCurrentExpand ||+ !reflect.DeepEqual(appearance.PDFTheme, NewPDFTheme()) || *appearance.MobileBars.AutoHide ||+ *appearance.MobileBars.SidebarSwipe || !*appearance.MobileBars.SidebarButtons {+ t.Fatal("normalization lost explicit choices or allowed inaccessible sidebars")+ }+ appearance.PDFTheme = &PDFTheme{Light: "dark", Dark: "light", AnnoColor: "rgb(1, 2, 3)"}+ NormalizeAppearance(appearance, false)+ if appearance.PDFTheme.Light != "dark" || appearance.PDFTheme.Dark != "light" || appearance.PDFTheme.AnnoColor != "rgb(1, 2, 3)" {+ t.Fatal("explicit PDF preferences changed")+ }+ for _, sort := range []string{"", "invalid", "viewedAt", "created", "updated", "openAt", "closedAt"} {+ expected := sort+ if sort == "" || sort == "invalid" {+ expected = "viewedAt"+ }+ if got := NormalizeFileTree(&FileTree{RecentDocsSort: sort}).RecentDocsSort; got != expected {+ t.Fatalf("sort %q became %q", sort, got)+ }+ }+ if NewAI().Agent.StreamingMarkdown || NormalizeAI(&AI{}).Agent.StreamingMarkdown {+ t.Fatal("streaming Markdown must default to disabled")+ }+}diff --git a/kernel/conf/settings_normalize.go b/kernel/conf/settings_normalize.goindex 3a539c1dd0..a00ea3a506 100644--- a/kernel/conf/settings_normalize.go+++ b/kernel/conf/settings_normalize.go@@ -55,6 +55,11 @@ func NormalizeFileTree(fileTree *FileTree) *FileTree {fileTree.BoxDocEnabled = new(false)}fileTree.RecentDocsMaxListCount = max(MinFileTreeRecentDocsListCount, min(MaxFileTreeRecentDocsListCount, fileTree.RecentDocsMaxListCount))+ switch fileTree.RecentDocsSort {+ case "viewedAt", "created", "updated", "openAt", "closedAt":+ default:+ fileTree.RecentDocsSort = "viewedAt"+ }return fileTree}@@ -267,6 +272,34 @@ func NormalizeAppearance(appearance *Appearance, mobile bool) *Appearance {appearance.CodeBlockThemeLight = "github"}appearance.StatusBar = util.NormalizeStatusBar(appearance.StatusBar, mobile)+ if appearance.PDFTheme == nil {+ appearance.PDFTheme = NewPDFTheme()+ }+ if appearance.PDFTheme.Light != "light" && appearance.PDFTheme.Light != "dark" {+ appearance.PDFTheme.Light = "light"+ }+ if appearance.PDFTheme.Dark != "light" && appearance.PDFTheme.Dark != "dark" {+ appearance.PDFTheme.Dark = "dark"+ }+ if strings.TrimSpace(appearance.PDFTheme.AnnoColor) == "" {+ appearance.PDFTheme.AnnoColor = NewPDFTheme().AnnoColor+ }+ if appearance.MobileBars == nil {+ appearance.MobileBars = NewMobileBars()+ }+ if appearance.MobileBars.AutoHide == nil {+ appearance.MobileBars.AutoHide = new(true)+ }+ if appearance.MobileBars.SidebarSwipe == nil {+ appearance.MobileBars.SidebarSwipe = new(true)+ }+ if appearance.MobileBars.SidebarButtons == nil {+ appearance.MobileBars.SidebarButtons = new(true)+ }+ // 至少保留一种侧栏访问方式。+ if !*appearance.MobileBars.SidebarSwipe && !*appearance.MobileBars.SidebarButtons {+ appearance.MobileBars.SidebarButtons = new(true)+ }if nil == appearance.Notifications {appearance.Notifications = util.NewNotifications()}diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 53e493b2a4..0371897d09 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -476,9 +476,7 @@ func InitConf() {}if boxes, listErr := ListNotebooks(); listErr == nil {prepareOnboardingForEmptyWorkspace(Conf.Onboarding.Load(), util.ReadOnly, len(boxes))- if err := initMenuMouseScrollPreference(confFileExists, len(boxes)); err != nil {- logging.LogWarnf("initialize menu mouse scrolling preference failed: %s", err)- }+ initMenuMouseScrollPreference(Conf.Appearance.Load(), confFileExists, len(boxes))}if 0 < len(Conf.Repo.Load().Key) {diff --git a/kernel/model/conf_preferences.go b/kernel/model/conf_preferences.gonew file mode 100644index 0000000000..cfdffb22a0--- /dev/null+++ b/kernel/model/conf_preferences.go@@ -0,0 +1,13 @@+package model++import (+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// 新建空工作空间启用菜单鼠标滚动;已有工作空间缺省保持关闭,不读取旧 KV 偏好。+func initMenuMouseScrollPreference(appearance *conf.Appearance, confFileExists bool, notebookCount int) {+ if !confFileExists && notebookCount == 0 && !util.ReadOnly {+ appearance.MenuMouseScroll = true+ }+}diff --git a/kernel/model/conf_preferences_test.go b/kernel/model/conf_preferences_test.gonew file mode 100644index 0000000000..6bd05fb3e4--- /dev/null+++ b/kernel/model/conf_preferences_test.go@@ -0,0 +1,69 @@+package model++import (+ "encoding/json"+ "os"+ "path/filepath"+ "reflect"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestConfPreferencesPersistPatchAndReset(t *testing.T) {+ prepareConfConsistencyTest(t)+ settingsResetTestEnvironment(t)+ Conf.AI.Load().Agent.StreamingMarkdown = true+ oldStorage := []byte(`{"local-compact-mode":true,"local-menu-mouse-scroll":true,"local-outline":{"keepCurrentExpand":true},"local-pdftheme":{"light":"dark"},"local-mobile-bars":{"autoHide":false},"local-recent-docs":{"type":"updated"},"siyuan-agent-streaming-markdown":true}`)+ if err := os.WriteFile(settingsResetPaths()[1], oldStorage, 0600); err != nil {+ t.Fatal(err)+ }+ for _, item := range []struct{ namespace, patch string }{+ {"appearance", `{"compactMode":true,"menuMouseScroll":true,"outlineKeepCurrentExpand":true,"pdfTheme":{"light":"dark","annoColor":"red"},"mobileBars":{"autoHide":false,"sidebarSwipe":false}}`},+ {"fileTree", `{"recentDocsSort":"updated"}`},+ {"ai", `{"agent":{"streamingMarkdown":true}}`},+ {"appearance", `{"pdfTheme":{"dark":"light"},"mobileBars":{"sidebarButtons":false}}`},+ } {+ if _, err := ApplyConfPatch(item.namespace, []byte(item.patch)); err != nil {+ t.Fatal(err)+ }+ }+ data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))+ if err != nil {+ t.Fatal(err)+ }+ reloaded := NewAppConf()+ if err = json.Unmarshal(data, reloaded); err != nil {+ t.Fatal(err)+ }+ appearance := reloaded.Appearance.Load()+ if !appearance.CompactMode || !appearance.MenuMouseScroll || !appearance.OutlineKeepCurrentExpand ||+ appearance.PDFTheme.Light != "dark" || appearance.PDFTheme.Dark != "light" || appearance.PDFTheme.AnnoColor != "red" ||+ *appearance.MobileBars.AutoHide || *appearance.MobileBars.SidebarSwipe || !*appearance.MobileBars.SidebarButtons ||+ reloaded.FileTree.Load().RecentDocsSort != "updated" || !reloaded.AI.Load().Agent.StreamingMarkdown {+ t.Fatal("persisted preferences or partial update preservation changed")+ }+ if err = ResetSettings(); err != nil {+ t.Fatal(err)+ }+ appearance = Conf.Appearance.Load()+ if appearance.CompactMode || appearance.MenuMouseScroll || appearance.OutlineKeepCurrentExpand ||+ appearance.PDFTheme.Light != "light" || appearance.PDFTheme.Dark != "dark" ||+ !*appearance.MobileBars.AutoHide || !*appearance.MobileBars.SidebarSwipe || !*appearance.MobileBars.SidebarButtons ||+ Conf.FileTree.Load().RecentDocsSort != "viewedAt" || !Conf.AI.Load().Agent.StreamingMarkdown {+ t.Fatal("reset must restore appearance and file tree preferences while preserving AI")+ }+ if data, err = os.ReadFile(settingsResetPaths()[1]); err != nil {+ t.Fatal(err)+ }+ var old, stored map[string]any+ if err = json.Unmarshal(oldStorage, &old); err != nil {+ t.Fatal(err)+ }+ if err = json.Unmarshal(data, &stored); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(old, stored) {+ t.Fatal("retired KV keys must not be maintained by settings reset")+ }+}diff --git a/kernel/model/menu_mouse_scroll_test.go b/kernel/model/menu_mouse_scroll_test.goindex 6f3baea2a0..ea14b86258 100644--- a/kernel/model/menu_mouse_scroll_test.go+++ b/kernel/model/menu_mouse_scroll_test.go@@ -1,88 +1,34 @@package modelimport (- "bytes"- "os"- "path/filepath"- "testing"-+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/util"+ "testing")func TestInitMenuMouseScrollPreference(t *testing.T) {- const key = "local-menu-mouse-scroll"for _, test := range []struct {- name string- confFileExists bool- notebookCount int- readOnly bool- storage string- wantEnabled bool- wantUnchanged bool- wantError bool+ name string+ exists, readonly, enabled bool+ notebooks int+ want bool}{- {name: "new empty workspace", wantEnabled: true},- {name: "existing empty workspace", confFileExists: true, wantUnchanged: true},- {name: "existing notebooks without configuration", notebookCount: 1, wantUnchanged: true},- {name: "readonly workspace", readOnly: true, wantUnchanged: true},- {name: "explicitly disabled", storage: `{"local-menu-mouse-scroll":false}`, wantUnchanged: true},- {name: "explicitly enabled", storage: `{"local-menu-mouse-scroll":true}`, wantEnabled: true, wantUnchanged: true},- {name: "existing enabled workspace", confFileExists: true, storage: `{"local-menu-mouse-scroll":true}`,- wantEnabled: true, wantUnchanged: true},- {name: "existing preferences", storage: `{"other-preference":"saved"}`, wantEnabled: true},- {name: "invalid preference preserved", storage: `{"local-menu-mouse-scroll":"true"}`, wantUnchanged: true},- {name: "corrupt storage", storage: `{"other-preference":`, wantUnchanged: true, wantError: true},- {name: "null storage", storage: `null`, wantUnchanged: true, wantError: true},+ {name: "new empty workspace", want: true},+ {name: "existing empty workspace", exists: true},+ {name: "existing notebooks", notebooks: 1},+ {name: "readonly workspace", readonly: true},+ {name: "explicitly disabled", exists: true},+ {name: "explicitly enabled", exists: true, enabled: true, want: true},} {t.Run(test.name, func(t *testing.T) {- previousDataDir, previousReadOnly := util.DataDir, util.ReadOnly- util.DataDir, util.ReadOnly = t.TempDir(), test.readOnly- t.Cleanup(func() { util.DataDir, util.ReadOnly = previousDataDir, previousReadOnly })- storagePath := filepath.Join(util.DataDir, "storage", "local.json")- if test.storage != "" {- if err := os.MkdirAll(filepath.Dir(storagePath), 0755); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(storagePath, []byte(test.storage), 0644); err != nil {- t.Fatal(err)- }- }- if err := initMenuMouseScrollPreference(test.confFileExists, test.notebookCount); (err != nil) != test.wantError {- t.Fatalf("initialization error = %v, wantError %v", err, test.wantError)- }- if test.wantUnchanged {- data, err := os.ReadFile(storagePath)- if test.storage == "" {- if !os.IsNotExist(err) {- t.Fatalf("unexpected storage file or error: %v", err)- }- } else if err != nil || !bytes.Equal(data, []byte(test.storage)) {- t.Fatalf("existing storage changed: %q, error %v", data, err)- }- }- if test.wantError {- return- }- storage, err := getLocalStorageWithError()- if err != nil {- t.Fatal(err)- }- if enabled, _ := storage[key].(bool); enabled != test.wantEnabled {- t.Fatalf("enabled = %v, want %v", storage[key], test.wantEnabled)- }- if test.name == "existing preferences" && storage["other-preference"] != "saved" {- t.Fatalf("unrelated preference was lost: %#v", storage)- }- if test.wantEnabled && !test.confFileExists {- if _, err = SetLocalStorageVals(map[string]any{key: false}); err != nil {- t.Fatal(err)- }- if err = initMenuMouseScrollPreference(false, 0); err != nil {- t.Fatal(err)- }- if storage = GetLocalStorage(); storage[key] != false {- t.Fatalf("initialization overwrote the user's later choice: %#v", storage)- }+ previous := util.ReadOnly+ util.ReadOnly = test.readonly+ t.Cleanup(func() { util.ReadOnly = previous })+ appearance := conf.NewAppearance()+ appearance.MenuMouseScroll = test.enabled+ initMenuMouseScrollPreference(appearance, test.exists, test.notebooks)+ if appearance.MenuMouseScroll != test.want {+ t.Fatalf("enabled = %v, want %v", appearance.MenuMouseScroll, test.want)}})}diff --git a/kernel/model/settings_reset.go b/kernel/model/settings_reset.goindex 60686c1ef4..cb5718ac4d 100644--- a/kernel/model/settings_reset.go+++ b/kernel/model/settings_reset.go@@ -17,8 +17,8 @@ import (// 仅清理内置偏好;保存的布局、插件数据、最近记录和未知键保持不变。var resetSettingsStorageKeys = []string{"local-zoom", "local-searchdata", "local-searchasset", "local-searchunref",- "local-exportpdf", "local-exportword", "local-exportimg", "local-pdftheme", "local-flashcard",- "local-mobile-bars", "local-mobile-bottom-bar", "local-mobile-side-panel", "local-outline",+ "local-exportpdf", "local-exportword", "local-exportimg", "local-flashcard",+ "local-mobile-bottom-bar", "local-mobile-side-panel","local-fileposition", "local-dialogposition",}diff --git a/kernel/model/settings_reset_test.go b/kernel/model/settings_reset_test.goindex c8a5234e77..f18a26da2b 100644--- a/kernel/model/settings_reset_test.go+++ b/kernel/model/settings_reset_test.go@@ -134,7 +134,7 @@ func TestSettingsResetPreservesDataAndProtectedConfiguration(t *testing.T) {if err = json.Unmarshal(data, &stored); err != nil {t.Fatal(err)}- if stored["local-zoom"] != nil || stored["local-mobile-bars"] != nil || stored["local-layouts"] == nil || stored["plugin-unknown"] == nil {+ if stored["local-zoom"] != nil || stored["local-mobile-bars"] == nil || stored["local-layouts"] == nil || stored["plugin-unknown"] == nil {t.Fatal("local storage whitelist was not respected")}data, err = os.ReadFile(settingsResetPaths()[0])diff --git a/kernel/model/storage.go b/kernel/model/storage.goindex 6aeefce051..e83c8eed9e 100644--- a/kernel/model/storage.go+++ b/kernel/model/storage.go@@ -38,29 +38,6 @@ import (var localStorageLock = sync.Mutex{}-// 首次创建空工作空间时初始化菜单滚动偏好,保留已有工作空间和用户保存的选择。-func initMenuMouseScrollPreference(confFileExists bool, notebookCount int) error {- if confFileExists || notebookCount != 0 || util.ReadOnly {- return nil- }- localStorageLock.Lock()- defer localStorageLock.Unlock()-- storage, err := readLocalStorage()- if err != nil {- return err- }- if storage == nil {- return errors.New("local storage must be a JSON object")- }- const key = "local-menu-mouse-scroll"- if _, configured := storage[key]; configured {- return nil- }- storage[key] = true- return setLocalStorage(storage)-}-func GetLocalStorage() (ret map[string]any) {ret, _ = getLocalStorageWithError()return