An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Store frequent slash visibility in entry profiles https://github.com/siyuan-note/siyuan/issues/20270
Danield196c8b3f146
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.tsindex d8c0f7e70f..fa34ab22c7 100644--- a/app/src/config/entryVisibility/catalog.test.ts+++ b/app/src/config/entryVisibility/catalog.test.ts@@ -554,10 +554,10 @@ test("slash menu catalog follows the built-in hint order", () => {const section = getEntryCatalogSection("editor.slash");assert.deepEqual(section?.children.map((item) => item.key), ["menu"]);const children = getEntryCatalogChildren(SLASH_MENU_ROOT_PATH);- assert.deepEqual(children.map((item) => item.key), slashMenuBuiltinOrder);- assert.equal(children.filter((item) => item.type === "entry").length, 68);+ assert.deepEqual(children.map((item) => item.key), ["frequent", ...slashMenuBuiltinOrder]);+ assert.equal(children.filter((item) => item.type === "entry").length, 69);assert.equal(children.filter((item) => item.type === "separator").length, 5);- assert.equal(children.every((item) => item.simple), true);+ assert.equal(children.filter(item => item.key !== "frequent").every((item) => item.simple), true);});test("slash menu catalog stays aligned with the built-in hint declarations", () => {diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 3ee781030f..388207197f 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -503,6 +503,7 @@ const gutterSingle = () => [];export const SLASH_MENU_ROOT_PATH = "editor.slash.menu";+export const SLASH_MENU_FREQUENT_PATH = `${SLASH_MENU_ROOT_PATH}.frequent`;// 共享工具栏声明决定目录默认顺序,块类型位于首位,字体和字号位于外观之前。// 移动端操作按钮复用统一声明,复制和剪切由悬浮工具栏提供,显隐和排序使用已有配置标识。@@ -538,6 +539,7 @@ const mobileToolbarContexts = (children: IEntryCatalogNode[]) => MOBILE_TOOLBAR_});const slashMenuBuiltinChildren = [+ node("frequent", lang("slashMenuFrequent"), false),node("template", lang("template")),node("widget", lang("widget")),node("assets", lang("assets")),diff --git a/app/src/config/entryVisibility/frequentSlashUi.test.ts b/app/src/config/entryVisibility/frequentSlashUi.test.tsindex 8569bf7fc5..2f711ca12c 100644--- a/app/src/config/entryVisibility/frequentSlashUi.test.ts+++ b/app/src/config/entryVisibility/frequentSlashUi.test.ts@@ -5,8 +5,13 @@ import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, transpileModule} from "typescript";import * as dockOrder from "./dockOrder";+import * as profileHelpers from "./profile";+import * as orderHelpers from "./order";-const loadEditor = (builtin = false, initialEnabled = true) => {+const frequentPath = "editor.slash.menu.frequent";+const rootPath = "editor.slash.menu";++const loadEditor = (id = "custom", initialEnabled = true, mobile = false) => {const listeners: Record<string, (event: any) => void> = {};const search = {value: "", addEventListener: (_event: string, callback: typeof listeners.input) => {listeners.search = callback;@@ -17,24 +22,31 @@ const loadEditor = (builtin = false, initialEnabled = true) => {".b3-dialog__body": {innerHTML: ""},"[data-type='entry-browser']": browser,"[data-type='entry-search']": search,+ "[data-type='entry-section']": {innerHTML: ""},+ "[data-type='entry-mobile-options']": {innerHTML: ""},"[data-profile-field='name']": {focus() {}},}[selector]),addEventListener: (event: string, callback: typeof listeners.input) => { listeners[event] = callback; },};- const entries = [{key: "template", label: () => "Template"}, {key: "heading1", label: () => "Heading 1"}];+ const entries = [{key: "frequent", label: () => "Frequently used"}, {key: "template", label: () => "Template"}, {key: "heading1", label: () => "Heading 1"}];const rootEntry = {key: "menu", label: () => "Slash menu", displayChildrenDirectly: true, children: entries};const sections = [{key: "editor.slash", label: () => "Slash menu", children: [rootEntry]}];- const config = {active: "custom", profiles: [{id: "custom", name: "Custom", entries: {}, orders: {}}]};+ const config = {active: "custom", profiles: [{id: "custom", name: "Custom", entries: {[frequentPath]: initialEnabled, [rootPath]: !mobile},+ orders: {[rootPath]: ["heading1", "template", "frequent"]}},+ {id: "other", name: "Other", entries: {[frequentPath]: initialEnabled}, orders: {}}]};const siyuan = {languages: new Proxy({slashMenuFrequent: "Frequently used"}, {get: (target, key) => target[key as keyof typeof target] || String(key),}), config: {appearance: {entryVisibility: config}}};- let enabled = initialEnabled;let discardPrompts = 0;let allowDiscard = true;- const writes: boolean[] = [];+ const writes: unknown[] = [];+ let nextID = 0;const emptyDock = dockOrder.createDockEntryOrderSnapshot({});const dependencies = {- ...dockOrder,+ ...dockOrder, ...profileHelpers, ...orderHelpers,+ SLASH_MENU_FREQUENT_PATH: frequentPath,+ genUUID: () => `new-${++nextID}`,+ bindTouchOrder: () => () => {},SLASH_MENU_ROOT_PATH: "editor.slash.menu",ENTRY_PROFILE_FULL: "full", ENTRY_PROFILE_SIMPLE: "simple",entryCatalog: sections,@@ -44,23 +56,26 @@ const loadEditor = (builtin = false, initialEnabled = true) => {getEditorToolbarCatalogSnapshot: (): [] => [],refreshToolbarCatalogEntries() {}, refreshTopBarCatalog() {}, refreshDockCatalog() {}, refreshSlashMenuCatalog() {},getDockEntryOrderSnapshot: () => emptyDock,- createEntryProfileSnapshot: () => ({}), createEntryOrderSnapshot: () => ({}),- isMobile: () => false,+ createEntryProfileSnapshot: (template: string) => ({[frequentPath]: template === "full", [rootPath]: !mobile}),+ createEntryOrderSnapshot: () => ({}),+ getEntryPaths: () => [rootPath, frequentPath],+ isEntryVisible: (path: string, stopAt?: string) => path === frequentPath+ ? (stopAt === rootPath || !mobile) && siyuan.config.appearance.entryVisibility.profiles[0].entries[frequentPath]+ : !mobile,+ getConfiguredEntryVisibility: (path: string, stopAt?: string) => path === frequentPath+ ? (stopAt === rootPath || !mobile) && siyuan.config.appearance.entryVisibility.profiles[0].entries[frequentPath]+ : !mobile,+ isMobile: () => mobile,isInMobileApp: () => false,- isFrequentSlashEnabled: () => enabled,- setFrequentSlashEnabled: (value: boolean) => { enabled = value; writes.push(value); },getHostCapabilities: () => ({importExport: false}),getEntryCatalogChildren: () => entries,getEntryCatalogPathChain: (_section: string, path: string) => [path],- getSavedEntryOrder: (): undefined => undefined,- resolveEntryOrder: (order: string[]) => order,- getProfileEntryVisibility: () => true,getEntryCatalogCustomDefaultVisibility: () => true,isEntryCatalogNodeConfigurable: () => true,isEntryOrderSortable: () => true,escapeAttr: (value: string) => value,escapeHtml: (value: string) => value,- saveEntryVisibility: (value: typeof config) => { siyuan.config.appearance.entryVisibility = value; },+ saveEntryVisibility: (value: typeof config) => { siyuan.config.appearance.entryVisibility = value; writes.push(value); },confirmDialog: (_title: string, _text: string, callback: () => void) => {discardPrompts++;if (allowDiscard) callback();@@ -70,85 +85,112 @@ const loadEditor = (builtin = false, initialEnabled = true) => {const code = transpileModule(source + `createEntryView = () => fixtureView;removeEntryView = () => { fixtureView.closed = true; };-exports.open = openProfileEditor;`, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;- const exports = {} as {open: (root: any, id: string) => void};+exports.open = openProfileEditor;+exports.create = createProfile;+exports.duplicate = duplicateProfile;`, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;+ const exports = {} as {open: (root: any, id: string) => void;+ create: (template: string, current?: boolean) => Config.IEntryVisibilityProfile;+ duplicate: (profile: any) => Config.IEntryVisibilityProfile};runInNewContext(code, {exports, require: () => dependencies, window: {siyuan}, fixtureView: view});const root = {querySelector: (): null => null};- const open = () => { view.closed = false; exports.open(root, builtin ? "full" : "custom"); };+ const open = () => { view.closed = false; exports.open(root, id); };open();- return {browser, view, writes, open,+ return {browser, view, writes, open, create: exports.create, duplicate: exports.duplicate,config: () => siyuan.config.appearance.entryVisibility,- enabled: () => enabled,+ enabled: () => siyuan.config.appearance.entryVisibility.profiles[0].entries[frequentPath],discardPrompts: () => discardPrompts,preventDiscard: () => { allowDiscard = false; },- externalChange: (value: boolean) => { enabled = value; },- toggle: (checked: boolean) => listeners.change({target: {dataset: {type: "slash-menu-frequent"}, checked}}),+ toggle: (checked: boolean) => listeners.change({target: {dataset: {entryPath: frequentPath}, checked, matches: () => true}}),+ template: (value: string) => listeners.change({target: {dataset: {profileField: "template"}, value, matches: () => false}}),rerender: () => listeners.search({}),search: (value: string) => { search.value = value; listeners.search({}); },action: (action: string) => listeners.click({target: {closest: (selector: string) =>- selector === "[data-action]" ? {dataset: {action}} : null}}),+ selector === "[data-action]" ? {dataset: {action, entryParent: rootPath}} : null}}),};};const frequentRow = (html: string) => html.match(/<label[^>]*>\s*<span[^>]*>Frequently used<\/span>[\s\S]*?<\/label>/)?.[0];-test("frequent slash setting uses the first compact row without profile or drag identifiers", () => {- const fixture = loadEditor();- const row = frequentRow(fixture.browser.innerHTML);- assert.ok(row);- assert.match(row, /config-entry-visibility__row--toggleable/);- assert.match(row, /class="b3-switch"[^>]*data-type="slash-menu-frequent"[^>]* checked/);- assert.doesNotMatch(row, /data-entry-|draggable|config-entry-visibility__drag|readonly|disabled/);- assert.ok(fixture.browser.innerHTML.indexOf(row) < fixture.browser.innerHTML.indexOf('data-entry-key="template"'));- assert.equal(fixture.writes.length, 0);-});--test("custom frequent slash changes are staged across rerenders and discarded on Cancel or Back", () => {- for (const action of ["cancel", "back"]) {- const fixture = loadEditor();- const profile = JSON.stringify(fixture.config());+for (const mobile of [false, true]) {+ test(`frequent is a pinned profile row on ${mobile ? "mobile" : "desktop"}`, () => {+ const fixture = loadEditor("custom", true, mobile);+ const row = frequentRow(fixture.browser.innerHTML);+ assert.ok(row);+ assert.match(row, /data-entry-path="editor.slash.menu.frequent"/);+ assert.match(row, / checked/);+ assert.doesNotMatch(row, /draggable|config-entry-visibility__drag|readonly|disabled/);+ assert.ok(fixture.browser.innerHTML.indexOf(row) < fixture.browser.innerHTML.indexOf('data-entry-key="template"'));+ fixture.action("reset-entry-order");+ assert.ok(fixture.browser.innerHTML.indexOf(frequentRow(fixture.browser.innerHTML)) <+ fixture.browser.innerHTML.indexOf('data-entry-key="template"'));fixture.toggle(false);- fixture.rerender();- assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);- assert.equal(fixture.enabled(), true);- assert.equal(fixture.writes.length, 0);- fixture.action(action);- assert.equal(fixture.discardPrompts(), 1);- assert.equal(fixture.view.closed, true);- assert.equal(JSON.stringify(fixture.config()), profile);+ fixture.action("confirm");+ assert.equal(fixture.enabled(), false);+ assert.equal(fixture.config().profiles[1].entries[frequentPath], true);+ assert.equal(fixture.writes.length, 1);fixture.open();- assert.match(frequentRow(fixture.browser.innerHTML), / checked/);- }-});+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+ });-test("searching the frequent label finds its workspace switch without adding a profile entry", () => {- const fixture = loadEditor();- const profile = JSON.stringify(fixture.config());- fixture.toggle(false);- fixture.search("frequently used");- assert.ok(frequentRow(fixture.browser.innerHTML));- assert.doesNotMatch(fixture.browser.innerHTML, /data-entry-key="template"|config-entry-visibility__drag/);- assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);- fixture.search("");- assert.match(fixture.browser.innerHTML, /data-entry-key="template"/);- assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);- assert.equal(JSON.stringify(fixture.config()), profile);-});+ test(`built-in frequent defaults are readonly on ${mobile ? "mobile" : "desktop"}`, () => {+ for (const id of ["simple", "full"]) {+ const fixture = loadEditor(id, true, mobile);+ const row = frequentRow(fixture.browser.innerHTML);+ assert.match(row, /data-entry-readonly/);+ assert.equal(/ checked/.test(row), id === "full");+ fixture.toggle(id !== "full");+ fixture.rerender();+ assert.equal(/ checked/.test(frequentRow(fixture.browser.innerHTML)), id === "full");+ fixture.action("cancel");+ assert.equal(fixture.discardPrompts(), 0);+ assert.equal(fixture.writes.length, 0);+ }+ });-test("custom frequent slash changes persist only with Confirm and stay out of profiles", () => {- const fixture = loadEditor();- const profile = JSON.stringify(fixture.config());- fixture.toggle(false);- fixture.action("confirm");- assert.deepEqual(fixture.writes, [false]);- assert.equal(fixture.enabled(), false);- assert.equal(fixture.view.closed, true);- assert.equal(JSON.stringify(fixture.config()), profile);- fixture.open();- assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);-});+ test(`custom frequent drafts cancel and search correctly on ${mobile ? "mobile" : "desktop"}`, () => {+ for (const action of ["cancel", "back"]) {+ const fixture = loadEditor("custom", true, mobile);+ const original = JSON.stringify(fixture.config());+ fixture.toggle(false);+ fixture.search("frequently used");+ assert.ok(frequentRow(fixture.browser.innerHTML));+ assert.doesNotMatch(fixture.browser.innerHTML, /data-entry-key="template"|config-entry-visibility__drag/);+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+ fixture.search("");+ fixture.rerender();+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+ assert.equal(fixture.enabled(), true);+ fixture.action(action);+ assert.equal(fixture.discardPrompts(), 1);+ assert.equal(fixture.view.closed, true);+ assert.equal(fixture.writes.length, 0);+ assert.equal(JSON.stringify(fixture.config()), original);+ fixture.open();+ assert.match(frequentRow(fixture.browser.innerHTML), / checked/);+ }+ });-test("declining discard preserves a pending frequent slash change until Confirm", () => {+ test(`copy and template choices preserve frequent semantics on ${mobile ? "mobile" : "desktop"}`, () => {+ const fixture = loadEditor("custom", true, mobile);+ assert.equal(fixture.create("simple").entries[frequentPath], false);+ assert.equal(fixture.create("full").entries[frequentPath], true);+ assert.equal(fixture.create("full", true).entries[frequentPath], true);+ const copy = fixture.duplicate(fixture.config().profiles[0]);+ assert.equal(copy.entries[frequentPath], true);+ copy.entries[frequentPath] = false;+ assert.equal(fixture.enabled(), true);+ fixture.template("simple");+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+ fixture.template("full");+ assert.match(frequentRow(fixture.browser.innerHTML), / checked/);+ fixture.template("current");+ assert.match(frequentRow(fixture.browser.innerHTML), / checked/);+ fixture.action("cancel");+ assert.equal(fixture.enabled(), true);+ });+}++test("declining discard preserves a pending frequent profile change until Confirm", () => {const fixture = loadEditor();fixture.preventDiscard();fixture.toggle(false);@@ -156,38 +198,8 @@ test("declining discard preserves a pending frequent slash change until Confirm"assert.equal(fixture.view.closed, false);assert.equal(fixture.writes.length, 0);fixture.action("confirm");- assert.deepEqual(fixture.writes, [false]);-});--test("unchanged or reverted custom settings do not overwrite a newer workspace preference", () => {- for (const reverted of [false, true]) {- const fixture = loadEditor();- if (reverted) {- fixture.toggle(false);- fixture.toggle(true);- }- fixture.externalChange(false);- fixture.action("confirm");- assert.equal(fixture.enabled(), false);- assert.equal(fixture.writes.length, 0);- }-});--test("built-in profile viewers apply the independent workspace switch immediately", () => {- const fixture = loadEditor(true);- const profile = JSON.stringify(fixture.config());- assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), /readonly|disabled/);- assert.match(fixture.browser.innerHTML, /data-entry-readonly/);- fixture.toggle(false);- assert.deepEqual(fixture.writes, [false]);- fixture.rerender();- assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);- fixture.action("cancel");- assert.equal(fixture.discardPrompts(), 0);- assert.equal(fixture.view.closed, true);- assert.equal(JSON.stringify(fixture.config()), profile);- fixture.open();- assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+ assert.equal(fixture.enabled(), false);+ assert.equal(fixture.writes.length, 1);});test("all bundled languages include a tab-indented frequent slash translation", () => {diff --git a/app/src/config/entryVisibility/mobileUi.test.ts b/app/src/config/entryVisibility/mobileUi.test.tsindex 22664aee07..a5609f712b 100644--- a/app/src/config/entryVisibility/mobileUi.test.ts+++ b/app/src/config/entryVisibility/mobileUi.test.ts@@ -20,11 +20,11 @@ const browserCases = async (sources: Record<string, string>, languages: Record<slet settingsWindow = false;const ownerSnapshot: Record<string, string[]> = {};let ownerReads = 0;- let frequentSlashEnabled = true;+ const frequentPath = "editor.slash.menu.frequent";const cache: Record<string, Record<string, any>> = {};const noop = () => {};window.siyuan = {languages, mobile: {}, storage: {}, config: {editor: {codeTabSpaces: 4}, appearance: {- entryVisibility: {active: "custom", profiles: [{id: "custom", name: "Custom", entries: {}, orders: {}}]},+ entryVisibility: {active: "custom", profiles: [{id: "custom", name: "Custom", entries: {[frequentPath]: true}, orders: {}}]},}}, layout: {}} as unknown as typeof window.siyuan;const load = (id: string): Record<string, any> => {if (cache[id]) {@@ -33,7 +33,8 @@ const browserCases = async (sources: Record<string, string>, languages: Record<sif (id === "config/entryVisibility/runtime") {return {ENTRY_PROFILE_FULL: "full", ENTRY_PROFILE_SIMPLE: "simple", ENTRY_VISIBILITY_VERSION: 1,- createEntryProfileSnapshot: () => ({"editor.slash.menu": !mobile}), createEntryOrderSnapshot: () => ({}),+ createEntryProfileSnapshot: (template: string) => ({"editor.slash.menu": !mobile,+ [frequentPath]: template === "full"}), createEntryOrderSnapshot: () => ({}),getConfiguredEntryVisibility: () => true,saveEntryVisibility: (config: Config.IEntryVisibility) => {window.siyuan.config.appearance.entryVisibility = config;@@ -48,8 +49,6 @@ const browserCases = async (sources: Record<string, string>, languages: Record<s"dialog/confirmDialog": {confirmDialog: (_title: string, _text: string, callback: () => void) => callback()},"dialog/message": {showMessage: noop},"protyle/util/compatibility": {isInMobileApp: () => true},- "protyle/hint/frequentSlashStorage": {isFrequentSlashEnabled: () => frequentSlashEnabled,- setFrequentSlashEnabled: (enabled: boolean) => { frequentSlashEnabled = enabled; }},"protyle/toolbar/catalogSnapshot": {getEditorToolbarCatalogSnapshot: (): [] => []},"config/setting/windowContext": {isSettingsWindow: () => settingsWindow,getSettingsOwnerApp: () => window.siyuan.ws?.app,@@ -106,15 +105,21 @@ const browserCases = async (sources: Record<string, string>, languages: Record<sconst section = editor.querySelector<HTMLSelectElement>("[data-type='entry-section']");section.value = "editor.slash";section.dispatchEvent(new Event("change", {bubbles: true}));- const frequent = editor.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']");- check(frequent?.checked && !frequent.disabled, "Frequent slash defaults to on in every profile view");+ const frequent = editor.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu.frequent']");+ check(frequent && frequent.checked === (id !== "simple") && !frequent.disabled,+ "Frequent defaults to off in Simple and on in Full and this custom profile");+ check(frequent.hasAttribute("data-entry-readonly") === (id !== "custom"),+ "Built-in frequent switches must be read-only");frequent.click();- check(frequentSlashEnabled === (id === "custom"), "Only built-in views save the workspace switch immediately");if (id !== "custom") {- frequent.click();+ check(frequent.checked === (id === "full"), "Clicking a built-in frequent switch must not change it");+ } else {+ check(!editor.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu.frequent']").checked,+ "Custom frequent changes must update only the draft");}+ check(config().profiles[0].entries[frequentPath], "Viewing or editing must preserve saved frequent preference");editor.querySelector<HTMLElement>("[data-action='cancel']").click();- check(frequentSlashEnabled, "Cancelling a custom draft does not change the workspace switch");+ check(config().profiles[0].entries[frequentPath], "Cancelling a custom draft preserves its saved frequent preference");}check(JSON.stringify(config()) === saved, "Viewing and cancelling profiles must preserve saved preferences");root.querySelector<HTMLElement>("[data-profile-id='full'] [data-action='activate']").click();@@ -180,18 +185,19 @@ const browserCases = async (sources: Record<string, string>, languages: Record<sreturn "Narrow new and existing profiles passed";}selectSlash();- const frequent = view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']");+ const frequent = view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu.frequent']");check(frequent.checked, "Frequent slash defaults to on");const frequentRow = frequent.closest("label");check(frequentRow === frequentRow.parentElement.firstElementChild, "Frequent is the first compact slash row");- check(!frequentRow.hasAttribute("data-entry-row") && !frequentRow.querySelector(".config-entry-visibility__drag"),- "The workspace switch must not participate in profile sorting");+ check(frequentRow.getAttribute("data-entry-path-row") === frequentPath &&+ !frequentRow.querySelector(".config-entry-visibility__drag"),+ "The frequent profile switch must stay pinned outside sorting");frequent.click();- check(frequentSlashEnabled, "Custom frequent changes must remain staged until confirmed");+ check(config().profiles[0].entries[frequentPath], "Custom frequent changes must remain staged until confirmed");let enabled = view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu']");check(!enabled.checked, "Mobile slash defaults to off");enabled.click();- check(!view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']").checked,+ check(!view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu.frequent']").checked,"Frequent switch draft must survive a list rerender");check(config().profiles[0].entries["editor.slash.menu"] !== true, "Total switch must remain a draft until confirmed");check(view.querySelectorAll("[data-type='entry-mobile-options'] input").length === 1, "Only one total switch is shown");@@ -244,7 +250,7 @@ const browserCases = async (sources: Record<string, string>, languages: Record<ssend(browser, "pointerup", {clientX: -20, clientY: -20});check(!browser.querySelector(".config-entry-visibility__row--drop-after"), "Outside release clears drop target");view.querySelector<HTMLElement>("[data-action='confirm']").click();- check(!frequentSlashEnabled, "Confirm must save the independent frequent switch");+ check(config().profiles[0].entries[frequentPath] === false, "Confirm must save frequent in the custom profile");const order = config().profiles[0].orders["editor.slash.menu"];check(config().profiles[0].entries["editor.slash.menu"] === true, "Confirm saves total switch in the profile");check(order.includes("plugin:missing:item"), "Unavailable plugin slots must survive sorting");@@ -253,14 +259,14 @@ const browserCases = async (sources: Record<string, string>, languages: Record<sselectSlash();enabled = view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu']");check(enabled.checked, "Reopening must preserve profile setting");- check(!view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']").checked,- "Reopening must preserve the workspace frequent setting");- view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']").click();+ check(!view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu.frequent']").checked,+ "Reopening must preserve the profile frequent setting");+ view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu.frequent']").click();const search = view.querySelector<HTMLInputElement>("[data-type='entry-search']");search.value = languages.slashMenuFrequent;search.dispatchEvent(new Event("input", {bubbles: true}));- check(view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']")?.checked,- "Searching the frequent label must reveal the pending workspace switch");+ check(view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu.frequent']")?.checked,+ "Searching the frequent label must reveal the pending profile switch");check(!view.querySelector("[data-entry-key='template']"), "Frequent search must not include unrelated candidates");search.value = "heading1";search.dispatchEvent(new Event("input", {bubbles: true}));@@ -273,7 +279,7 @@ const browserCases = async (sources: Record<string, string>, languages: Record<scheck(view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu.heading1']").disabled,"Disabled menu must disable candidate controls");view.querySelector<HTMLElement>("[data-action='cancel']").click();- check(!frequentSlashEnabled, "Cancel must discard the staged frequent change");+ check(config().profiles[0].entries[frequentPath] === false, "Cancel must discard the staged frequent change");check(config().profiles[0].entries["editor.slash.menu"] === true, "Cancel must discard the total switch change");view = open("full");selectSlash();@@ -283,8 +289,11 @@ const browserCases = async (sources: Record<string, string>, languages: Record<senabled = view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu']");enabled.click();check(!enabled.checked, "Built-in total switch follows mobile default and remains read-only");- view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']").click();- check(frequentSlashEnabled, "Built-in viewers must allow immediate workspace frequent changes");+ const fullFrequent = view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu.frequent']");+ check(fullFrequent.checked && fullFrequent.hasAttribute("data-entry-readonly"), "Full frequent must be on and read-only");+ fullFrequent.click();+ check(fullFrequent.checked, "Full frequent remains enabled after clicking");+ check(config().profiles[0].entries[frequentPath] === false, "Built-in views must not change custom profiles");view.querySelector<HTMLElement>("[data-action='cancel']").click();mobile = false;delete window.siyuan.mobile;diff --git a/app/src/config/entryVisibility/profile.test.ts b/app/src/config/entryVisibility/profile.test.tsindex d04d89bdf6..5b273e7af3 100644--- a/app/src/config/entryVisibility/profile.test.ts+++ b/app/src/config/entryVisibility/profile.test.ts@@ -20,6 +20,8 @@ import {import {getMobileToolbarContextPath} from "./mobileToolbarContext";import {mergeEntryOrderPreservingUnknown, resolveEntryOrder} from "./order";+const frequentPath = "editor.slash.menu.frequent";+test("mobile toolbar contexts expose relevant entries and hide caret references by default", () => {const input = getMobileToolbarContextPath(false);const selection = getMobileToolbarContextPath(true);@@ -76,7 +78,9 @@ test("mobile context orders retain legacy plugin slots and reset independently",resetEntryProfileOrder(profile, input);assert.deepEqual(resolveEntryOrder(defaults, getSavedEntryOrder(profile, input, defaults), new Set()), defaults);assert.deepEqual(profile.orders["editor.toolbar"], legacy);- assert.deepEqual(normalizeEntryVisibilityImportProfile(profile, 6, {}), profile);+ assert.deepEqual(normalizeEntryVisibilityImportProfile(profile, 6, {}), {+ ...profile, entries: {[frequentPath]: true},+ });});test("chart height migration retains shared visibility and plugin order", () => {@@ -89,7 +93,7 @@ test("chart height migration retains shared visibility and plugin order", () =>"gutter.single": ["pluginBefore", "width", "height", "pluginAfter"],"gutter.single.chart": ["pluginBefore", "height", "update", "pluginAfter"],}}, 6, {});- assert.deepEqual(profile.entries, {"gutter.single.height": existing ?? false});+ assert.deepEqual(profile.entries, {"gutter.single.height": existing ?? false, [frequentPath]: true});assert.deepEqual(profile.orders, {"gutter.single": ["pluginBefore", "width", "height", "pluginAfter"],"gutter.single.chart": ["pluginBefore", "update", "pluginAfter"],@@ -102,7 +106,8 @@ test("task state imports match kernel migrations and remain stable on reimport",const fixtures = JSON.parse(readFileSync(resolve(process.cwd(), "../kernel/conf/testdata/task_status_menu.json"), "utf8"));for (const fixture of fixtures) {const profile = normalizeEntryVisibilityImportProfile({name: "Custom", ...fixture.input}, 5, {});- assert.deepEqual(profile, {name: "Custom", ...fixture.expected}, fixture.name);+ assert.deepEqual(profile, {name: "Custom", ...fixture.expected,+ entries: {...fixture.expected.entries, [frequentPath]: true}}, fixture.name);assert.deepEqual(normalizeEntryVisibilityImportProfile(profile, 6, {}), profile);assert.deepEqual(normalizeEntryVisibilityImportProfile(profile, 5, {}), profile);}@@ -117,6 +122,7 @@ test("database submenu migration preserves visibility, order and plugin slots",assert.deepEqual(profile.entries, {"gutter.single.database.exportCSV": false,"gutter.single.database.showDatabaseInFolder": true,+ [frequentPath]: true,});assert.deepEqual(profile.orders, {"gutter.single": ["pluginBefore", "separator_exportCSV", "database", "pluginMiddle", "pluginAfter"],@@ -214,7 +220,7 @@ test("legacy entry visibility imports require base without persisting it", () =>}, 2, {});assert.deepEqual(profile, {name: "Legacy",- entries: {visible: true, hidden: false},+ entries: {visible: true, hidden: false, [frequentPath]: true},orders: {menu: ["known", "plugin"]},});assert.equal(normalizeEntryVisibilityImportProfile({@@ -230,7 +236,7 @@ test("current entry visibility imports do not require base", () => {entries: {},}, 4, defaultOrders), {name: "Current",- entries: {},+ entries: {[frequentPath]: true},orders: defaultOrders,});});@@ -243,7 +249,7 @@ test("version 1 entry visibility imports use default orders", () => {entries: {},}, 1, defaultOrders), {name: "Version 1",- entries: {},+ entries: {[frequentPath]: true},orders: defaultOrders,});});@@ -261,7 +267,7 @@ test("version 3 entry visibility imports migrate the edit mode submenu", () => {},}, 3, {}), {name: "Legacy edit mode",- entries: {"document.more.editMode": false},+ entries: {"document.more.editMode": false, [frequentPath]: true},orders: {},});});@@ -276,7 +282,40 @@ test("version 3 entry visibility imports keep the merged mode entry when a legac},}, 3, {}), {name: "Partially visible edit mode",- entries: {"document.more.editMode": true},+ entries: {"document.more.editMode": true, [frequentPath]: true},orders: {},});});++test("legacy profile imports materialize the frequent default across every supported version", () => {+ for (const version of [1, 2, 3, 4, 5, 6]) {+ const input = {name: "Legacy", base: "simple", entries: {"editor.slash.menu": false}};+ const profile = normalizeEntryVisibilityImportProfile(input, version, {});+ assert.equal(profile.entries[frequentPath], true);+ assert.equal(profile.entries["editor.slash.menu"], false);+ assert.equal(Object.prototype.hasOwnProperty.call(input.entries, frequentPath), false);+ const exported = JSON.parse(JSON.stringify({version: 6, profile}));+ assert.deepEqual(normalizeEntryVisibilityImportProfile(exported.profile, exported.version, {}), profile);+ }+});++test("frequent profile choices survive import and export without changing order or plugin entries", () => {+ for (const enabled of [false, true]) {+ const input = {name: "Custom", entries: {+ [frequentPath]: enabled, "editor.slash.menu.plugin:example:item": false,+ }, orders: {"editor.slash.menu": ["plugin:example:item", "template"]}};+ const profile = normalizeEntryVisibilityImportProfile(input, 6, {});+ assert.deepEqual(profile, input);+ const exported = JSON.parse(JSON.stringify({version: 6, profile}));+ assert.deepEqual(normalizeEntryVisibilityImportProfile(exported.profile, exported.version, {}), input);+ }+});++test("invalid imported frequent values use the explicit default", () => {+ for (const invalid of [null, "false", 0, {}, []]) {+ const profile = normalizeEntryVisibilityImportProfile({+ name: "Custom", entries: {[frequentPath]: invalid},+ }, 6, {});+ assert.deepEqual(profile.entries, {[frequentPath]: true});+ }+});diff --git a/app/src/config/entryVisibility/profile.ts b/app/src/config/entryVisibility/profile.tsindex e0d0f9d88d..42f004f064 100644--- a/app/src/config/entryVisibility/profile.ts+++ b/app/src/config/entryVisibility/profile.ts@@ -175,5 +175,6 @@ export const normalizeEntryVisibilityImportProfile = (migrateTaskStatusMenu({entries, orders});}migrateChartHeightMenu({entries, orders});+ entries["editor.slash.menu.frequent"] ??= true;return {name: profile.name, entries, orders};};diff --git a/app/src/config/entryVisibility/runtime.test.ts b/app/src/config/entryVisibility/runtime.test.tsindex 2a5a2a9421..8a9a671d04 100644--- a/app/src/config/entryVisibility/runtime.test.ts+++ b/app/src/config/entryVisibility/runtime.test.ts@@ -16,6 +16,63 @@ import {mergeDockEntryOrderSnapshot,} from "./dockOrder";+test("frequent slash defaults and snapshots follow profiles on desktop and mobile", () => {+ const source = readFileSync(resolve(process.cwd(), "src/config/entryVisibility/runtime.ts"), "utf8");+ const compiled = transpileModule(source + "\nexports.writable = getWritableEntryProfile;", {+ compilerOptions: {module: ModuleKind.CommonJS},+ }).outputText;+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "window");+ const path = catalog.SLASH_MENU_FREQUENT_PATH;+ const root = catalog.SLASH_MENU_ROOT_PATH;+ try {+ for (const mobile of [false, true]) {+ for (const template of ["simple", "full"] as const) {+ const config: Config.IEntryVisibility = {version: 6, active: template, profiles: []};+ const window = {siyuan: {+ config: {appearance: {entryVisibility: config}},+ languages: {entryCustomProfile: "Custom"},+ ...(mobile ? {mobile: {}} : {}),+ }};+ Object.defineProperty(globalThis, "window", {configurable: true, value: window});+ const runtime = {} as typeof import("./runtime") & {+ writable: (config: Config.IEntryVisibility) => Config.IEntryVisibilityProfile;+ };+ runInNewContext(compiled, {exports: runtime, window, require: () => ({+ ...catalog, ...profileVisibility, TOOLBAR_ENTRY_ROOT_PATH, genUUID: () => "custom",+ })});+ const enabled = template === "full";+ assert.equal(runtime.getConfiguredEntryVisibility(path, root), enabled);+ assert.equal(runtime.getConfiguredEntryVisibility(path), enabled && !mobile);+ assert.equal(runtime.createEntryProfileSnapshot(template)[path], enabled);+ const custom = runtime.writable(config);+ assert.equal(custom.entries[path], enabled);+ custom.entries[root] = false;+ for (const visible of [false, true]) {+ custom.entries[path] = visible;+ assert.equal(runtime.getConfiguredEntryVisibility(path), false);+ assert.equal(runtime.getConfiguredEntryVisibility(path, root), visible);+ }+ const saved = JSON.stringify(custom);+ config.active = "simple";+ assert.equal(runtime.getConfiguredEntryVisibility(path, root), false);+ config.active = "full";+ assert.equal(runtime.getConfiguredEntryVisibility(path, root), true);+ config.active = custom.id;+ assert.equal(JSON.stringify(custom), saved);+ assert.equal(runtime.getConfiguredEntryVisibility(path, root), true);+ delete custom.entries[path];+ assert.equal(runtime.getConfiguredEntryVisibility(path, root), true);+ }+ }+ } finally {+ if (descriptor) {+ Object.defineProperty(globalThis, "window", descriptor);+ } else {+ Reflect.deleteProperty(globalThis, "window");+ }+ }+});+test("daily note and flashcard presets preserve custom choices and mobile defaults", () => {const source = readFileSync(resolve(process.cwd(), "src/config/entryVisibility/runtime.ts"), "utf8");const compiled = transpileModule(source + "\nexports.writable = getWritableEntryProfile;", {diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.tsindex 74db83a71a..2577a38169 100644--- a/app/src/config/entryVisibility/ui.ts+++ b/app/src/config/entryVisibility/ui.ts@@ -17,6 +17,7 @@ import {refreshTopBarCatalog,refreshToolbarCatalogEntries,SLASH_MENU_ROOT_PATH,+ SLASH_MENU_FREQUENT_PATH,TOP_BAR_ROOT_PATH,STATUS_BAR_ROOT_PATH,} from "./catalog";@@ -51,7 +52,6 @@ import {bindTouchOrder} from "./touchOrder";import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";import {MOBILE_TOOLBAR_CONTEXT_KEYS} from "./mobileToolbarContext";import {getSettingsOwnerApp} from "../setting/windowContext";-import {isFrequentSlashEnabled, setFrequentSlashEnabled} from "../../protyle/hint/frequentSlashStorage";/// #if !MOBILEimport {getSettingsWindowHost, isSettingsWindow} from "../setting/windowContext";import {getEditorToolbarCatalogSnapshot} from "../../protyle/toolbar/catalogSnapshot";@@ -142,7 +142,7 @@ const createProfile = (template: TEntryVisibilityTemplate, current = false, name};if (current) {getEntryPaths().forEach((path) => {- profile.entries[path] = isEntryVisible(path);+ profile.entries[path] = isEntryVisible(path, path === SLASH_MENU_FREQUENT_PATH ? SLASH_MENU_ROOT_PATH : undefined);});}return profile;@@ -316,7 +316,7 @@ const renderEntryRows = (profile: Config.IEntryVisibilityProfile, prefix: stringconst renderEntryColumn = (profile: Config.IEntryVisibilityProfile, title: string, prefix: string,nodes: IEntryCatalogNode[], depth: number, selectedPaths: string[],- parentEnabled: boolean, readOnly: boolean, sortable: boolean, frequentSlashEnabled: boolean,+ parentEnabled: boolean, readOnly: boolean, sortable: boolean,getItemPath = (item: IEntryCatalogNode) => `${prefix}.${item.key}`) => `<section class="config-entry-visibility__column"data-entry-column data-entry-depth="${depth}"><div class="config-entry-visibility__column-title">@@ -324,13 +324,10 @@ const renderEntryColumn = (profile: Config.IEntryVisibilityProfile, title: strin${sortable ? renderOrderReset(prefix) : ""}</div><div class="config-entry-visibility__column-list">- ${prefix === SLASH_MENU_ROOT_PATH ? `<label class="config-entry-visibility__row config-entry-visibility__row--toggleable">- <span class="config-entry-visibility__label">${escapeHtml(window.siyuan.languages.slashMenuFrequent)}</span>- <input class="b3-switch" type="checkbox" data-type="slash-menu-frequent"- aria-label="${escapeAttr(window.siyuan.languages.slashMenuFrequent)}"${frequentSlashEnabled ? " checked" : ""}>- <span class="config-entry-visibility__arrow-space"></span>- </label>` : ""}- ${renderEntryRows(profile, prefix, nodes, depth, selectedPaths, parentEnabled, readOnly, sortable, getItemPath)}+ ${renderEntryRows(profile, prefix, nodes.filter(item => `${prefix}.${item.key}` === SLASH_MENU_FREQUENT_PATH),+ depth, selectedPaths, true, readOnly, false, getItemPath)}+ ${renderEntryRows(profile, prefix, nodes.filter(item => `${prefix}.${item.key}` !== SLASH_MENU_FREQUENT_PATH),+ depth, selectedPaths, parentEnabled, readOnly, sortable, getItemPath)}</div></section>`;@@ -466,8 +463,7 @@ const getDockEntrySelectedPaths = (key: string) => [`${DOCK_SECTION_KEY}.${key}`const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey: string,selectedPaths: string[], readOnly: boolean, visiblePaths?: Set<string>,- visibleSectionKeys?: Set<string>, dockOrderSnapshot = getDockEntryOrderSnapshot(),- frequentSlashEnabled = isFrequentSlashEnabled()) => {+ visibleSectionKeys?: Set<string>, dockOrderSnapshot = getDockEntryOrderSnapshot()) => {const catalog = getVisibleEntryCatalog();const sections = visibleSectionKeys? catalog.filter((item) => visibleSectionKeys.has(item.key))@@ -505,11 +501,11 @@ const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey:const columnNodes = visiblePaths? orderedNodes.filter((item) => item.type !== "separator" && visiblePaths.has(`${prefix}.${item.key}`)): orderedNodes;- if (columnNodes.length === 0 && prefix !== SLASH_MENU_ROOT_PATH) {+ if (columnNodes.length === 0) {break;}columns.push(renderEntryColumn(profile, title, prefix, columnNodes, depth, columnSelectedPaths,- parentEnabled, readOnly, !visiblePaths && isEntryOrderSortable(prefix) && !readOnly, frequentSlashEnabled));+ parentEnabled, readOnly, !visiblePaths && isEntryOrderSortable(prefix) && !readOnly));const selectedPath = columnSelectedPaths[depth];const selectedNode = selectedPath && columnNodes.find((item) => `${prefix}.${item.key}` === selectedPath);if (!selectedNode?.children?.length) {@@ -551,12 +547,6 @@ const getEntrySearchResults = (query: string) => {};getVisibleEntryCatalog().forEach((section) => {visit(section, section.key, section.children, [section.label()]);- const root = getDirectDisplayRoot(section);- if (root && `${section.key}.${root.key}` === SLASH_MENU_ROOT_PATH &&- window.siyuan.languages.slashMenuFrequent.toLowerCase().includes(query)) {- results.push({section, item: root, path: SLASH_MENU_ROOT_PATH,- labels: [section.label(), window.siyuan.languages.slashMenuFrequent]});- }});return results;};@@ -630,8 +620,6 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {: createProfile(ENTRY_PROFILE_SIMPLE);draft.orders ||= createEntryOrderSnapshot();const initialJSON = JSON.stringify(draft);- const initialFrequentSlashEnabled = isFrequentSlashEnabled();- let frequentSlashEnabled = initialFrequentSlashEnabled;const creating = !builtin && !existing;const view = createEntryView(root);const body = view.querySelector<HTMLElement>(".b3-dialog__body");@@ -731,7 +719,7 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {</label>` : "";}browser.innerHTML = renderEntryColumns(draft, selectedSectionKey, selectedPaths, builtin,- filter?.visiblePaths, filter?.visibleSectionKeys, dockOrderSnapshot, frequentSlashEnabled);+ filter?.visiblePaths, filter?.visibleSectionKeys, dockOrderSnapshot);previousQuery = query;const columnsContainer = browser.querySelector<HTMLElement>(".config-entry-visibility__columns");const columns = Array.from(browser.querySelectorAll<HTMLElement>("[data-entry-column]"));@@ -757,7 +745,7 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {removeEntryView(root, view);};const closeEditor = () => {- if (JSON.stringify(draft) !== initialJSON || !builtin && frequentSlashEnabled !== initialFrequentSlashEnabled) {+ if (JSON.stringify(draft) !== initialJSON) {confirmDialog(window.siyuan.languages.confirm, window.siyuan.languages.discardUnsavedChanges, leaveEditor);return;}@@ -818,7 +806,8 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {}return;}- if (!row || row.dataset.entryParent !== dragging.parentPath || !row.dataset.entryKey) {+ if (!row || row.dataset.entryParent !== dragging.parentPath || !row.dataset.entryKey ||+ `${row.dataset.entryParent}.${row.dataset.entryKey}` === SLASH_MENU_FREQUENT_PATH) {clearDropTarget();dragging.order = undefined;return;@@ -920,13 +909,6 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {});view.addEventListener("change", (event) => {const control = event.target as HTMLInputElement | HTMLSelectElement;- if (control.dataset.type === "slash-menu-frequent") {- frequentSlashEnabled = (control as HTMLInputElement).checked;- if (builtin) {- setFrequentSlashEnabled(frequentSlashEnabled);- }- return;- }if (control.dataset.type === "entry-section") {selectedSectionKey = control.value;selectedPaths = [];@@ -952,7 +934,7 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {draft.orders = createEntryOrderSnapshot(selectedTemplate === "current");if (selectedTemplate === "current") {getEntryPaths().forEach((path) => {- draft.entries[path] = isEntryVisible(path);+ draft.entries[path] = isEntryVisible(path, path === SLASH_MENU_FREQUENT_PATH ? SLASH_MENU_ROOT_PATH : undefined);});}renderBrowser();@@ -1002,9 +984,6 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {config.profiles.push(draft);}saveEntryVisibility(config);- if (frequentSlashEnabled !== initialFrequentSlashEnabled) {- setFrequentSlashEnabled(frequentSlashEnabled);- }renderProfileCards(root);leaveEditor();}diff --git a/app/src/protyle/gutter/turnIntoMenu.test.ts b/app/src/protyle/gutter/turnIntoMenu.test.tsindex 1ab31ad52b..1799ad3df3 100644--- a/app/src/protyle/gutter/turnIntoMenu.test.ts+++ b/app/src/protyle/gutter/turnIntoMenu.test.ts@@ -55,7 +55,7 @@ test("saved conversion orders and visibility survive profile migration and defauconst input = {name: "Custom", entries: {[`${path}.quote`]: false}, orders: {[path]: saved}};for (const version of [3, 4, 5, 6]) {const profile = normalizeEntryVisibilityImportProfile(input, version, {[path]: defaults});- assert.deepEqual(profile, input);+ assert.deepEqual(profile, {...input, entries: {...input.entries, "editor.slash.menu.frequent": true}});assert.deepEqual(mergeEntryOrderPreservingUnknown(defaults, profile.orders[path]), saved);assert.deepEqual(resolveEntryOrder(defaults, profile.orders[path], new Set()),saved.filter(key => key !== "plugin:example:item"));diff --git a/app/src/protyle/hint/frequentSlashStorage.test.ts b/app/src/protyle/hint/frequentSlashStorage.test.tsindex 297353a695..a3b4a6d09a 100644--- a/app/src/protyle/hint/frequentSlashStorage.test.ts+++ b/app/src/protyle/hint/frequentSlashStorage.test.ts@@ -4,9 +4,16 @@ import {join} from "node:path";import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import * as catalog from "../../config/entryVisibility/catalog";+import * as profileVisibility from "../../config/entryVisibility/profile";import * as frequentSlash from "./frequentSlash";-const constants = {LOCAL_SLASH_FREQUENT_ENABLED: "enabled", LOCAL_SLASH_USAGE: "usage"};+const constants = {LOCAL_SLASH_USAGE: "usage"};+const frequentPath = "editor.slash.menu.frequent";+const runtimeCompiled = transpileModule(+ readFileSync(join(__dirname, "../../config/entryVisibility/runtime.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;const compiled = transpileModule(readFileSync(join(__dirname, "frequentSlashStorage.ts"), "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText;@@ -17,7 +24,15 @@ const fixture = (values: Record<string, unknown> = {},persist: (write: TWrite) => Promise<unknown> = () => Promise.resolve()) => {const writes: TWrite[] = [];const storage: Record<string, unknown> = structuredClone(values);- const siyuan = {storage, config: {readonly: false}, isPublish: false};+ const config: Config.IEntryVisibility = {version: 6, active: "full", profiles: [+ {id: "custom-on", name: "Enabled", entries: {[frequentPath]: true}, orders: {}},+ {id: "custom-off", name: "Disabled", entries: {[frequentPath]: false}, orders: {}},+ ]};+ const siyuan = {storage, config: {readonly: false, appearance: {entryVisibility: config}}, isPublish: false};+ const runtime = {} as typeof import("../../config/entryVisibility/runtime");+ runInNewContext(runtimeCompiled, {+ exports: runtime, window: {siyuan}, require: () => ({...catalog, ...profileVisibility}),+ });const exports = {} as typeof import("./frequentSlashStorage");const settings = {} as typeof import("../../config/setting/pending");runInNewContext(transpileModule(readFileSync(join(__dirname, "../../config/setting/pending.ts"), "utf8"), {@@ -30,6 +45,8 @@ const fixture = (values: Record<string, unknown> = {},require: (id: string) => {if (id === "../../constants") return {Constants: constants};if (id === "./frequentSlash") return frequentSlash;+ if (id === "../../config/entryVisibility/runtime") return runtime;+ if (id === "../../config/entryVisibility/catalog") return catalog;if (id === "../../config/setting/pending") return settings;assert.equal(id, "../util/compatibility");return {setStorageVal: (key: string, value: unknown) => {@@ -39,31 +56,34 @@ const fixture = (values: Record<string, unknown> = {},}};},});- return {...exports, storage, writes, siyuan, settings};+ return {...exports, storage, writes, siyuan, settings, config};};const settle = () => new Promise<void>(resolve => setImmediate(resolve));const entries = [{key: "code"}, {key: "heading1"}];const getKey = (entry: {key: string}) => entry.key;-test("frequent slash defaults on and honors only an explicit false preference", () => {- for (const enabled of [undefined, null, true, "false", 0, {}, []]) {- assert.equal(fixture({enabled}).isFrequentSlashEnabled(), true);+test("frequent slash follows the active profile and ignores the legacy global preference", () => {+ for (const enabled of [undefined, null, true, false, "false", 0, {}, []]) {+ const f = fixture({enabled});+ for (const active of ["full", "simple", "custom-on", "custom-off"]) {+ f.config.active = active;+ assert.equal(f.isFrequentSlashEnabled(), active === "full" || active === "custom-on");+ }}- assert.equal(fixture({enabled: false}).isFrequentSlashEnabled(), false);});test("disabled frequent slash preserves history and stops all execution writes", async () => {const f = fixture({usage: {code: 4, "plugin:uninstalled:item": 2}});- f.setFrequentSlashEnabled(false);+ f.config.active = "custom-off";assert.equal(f.isFrequentSlashEnabled(), false);assert.equal(f.getFrequentSlashItems(entries, getKey).length, 0);f.recordSlashExecution("code");f.recordSlashExecution("heading1");await settle();assert.deepEqual(f.storage.usage, {code: 4, "plugin:uninstalled:item": 2});- assert.deepEqual(f.writes, [{key: "enabled", value: false}]);- f.setFrequentSlashEnabled(true);+ assert.deepEqual(f.writes, []);+ f.config.active = "custom-on";assert.deepEqual(f.getFrequentSlashItems(entries, getKey), [entries[0]]);f.recordSlashExecution("heading1");await settle();@@ -71,6 +91,23 @@ test("disabled frequent slash preserves history and stops all execution writes",assert.equal(f.writes.filter(write => write.key === "usage").length, 1);});+test("frequent slash remains usable by the keyboard toolbar when its slash parent is hidden", async () => {+ const f = fixture({usage: {code: 2}});+ f.config.active = "custom-on";+ f.config.profiles[0].entries[catalog.SLASH_MENU_ROOT_PATH] = false;+ assert.equal(f.isFrequentSlashEnabled(), true);+ assert.deepEqual(f.getFrequentSlashItems(entries, getKey), [entries[0]]);+ f.recordSlashExecution("code");+ await settle();+ assert.deepEqual(f.storage.usage, {code: 3});+ f.config.profiles[0].entries[frequentPath] = false;+ assert.equal(f.isFrequentSlashEnabled(), false);+ f.recordSlashExecution("code");+ await settle();+ assert.deepEqual(f.storage.usage, {code: 3});+ assert.equal(f.writes.length, 1);+});+test("usage records stable plugin identities independently and normalizes damaged storage", async () => {const f = fixture({usage: {code: "wrong", zero: 0, "plugin:uninstalled:item": 3}});for (const key of ["code", "plugin:first:code", "plugin:second:code", "code"]) {@@ -111,29 +148,29 @@ test("usage safely records prototype-like own keys without changing object protoassert.equal(Object.prototype.hasOwnProperty.call({}, "usage"), false);});-test("readonly, published, and missing storage contexts do not mutate or persist preferences", async () => {+test("readonly, published, and missing storage contexts do not mutate or persist usage", async () => {for (const mode of ["readonly", "publish", "missing"]) {const f = fixture({usage: {code: 3}});if (mode === "readonly") f.siyuan.config.readonly = true;if (mode === "publish") f.siyuan.isPublish = true;if (mode === "missing") f.siyuan.storage = undefined;- f.setFrequentSlashEnabled(false);+ f.config.active = "custom-off";f.recordSlashExecution("code");await settle();assert.deepEqual(f.storage, {usage: {code: 3}});assert.equal(f.writes.length, 0);- assert.equal(f.isFrequentSlashEnabled(), true);+ assert.equal(f.isFrequentSlashEnabled(), false);}});-test("ranking and counting read storage updates from other windows without cached preferences", async () => {- const f = fixture({enabled: false, usage: {code: 1}});- f.storage.enabled = true;+test("ranking and counting read profile and storage updates without cached preferences", async () => {+ const f = fixture({usage: {code: 1}});+ f.config.active = "custom-on";f.storage.usage = {heading1: 6};assert.deepEqual(f.getFrequentSlashItems(entries, getKey), [entries[1]]);f.recordSlashExecution("heading1");assert.deepEqual(f.storage.usage, {heading1: 7});- f.storage.enabled = false;+ f.config.active = "custom-off";f.recordSlashExecution("code");await settle();assert.deepEqual(f.storage.usage, {heading1: 7});@@ -159,16 +196,16 @@ test("usage persistence serializes and coalesces snapshots so old writes cannotassert.equal(f.writes.length, 2);});-test("disabling while usage is saving preserves both pending counts and the separate preference", async () => {+test("switching to a disabled profile while saving preserves pending counts", async () => {const release: Array<() => void> = [];const f = fixture({}, () => new Promise<void>(resolve => release.push(resolve)));f.recordSlashExecution("code");f.recordSlashExecution("code");- f.setFrequentSlashEnabled(false);+ f.config.active = "custom-off";f.recordSlashExecution("heading1");- assert.equal(f.storage.enabled, false);+ assert.equal(f.isFrequentSlashEnabled(), false);assert.deepEqual(f.storage.usage, {code: 2});- for (let index = 0; index < 3; index++) {+ for (let index = 0; index < 2; index++) {await settle();assert.equal(f.writes.length, index + 1);release.shift()();@@ -177,7 +214,6 @@ test("disabling while usage is saving preserves both pending counts and the sepaassert.deepEqual(f.writes, [{key: "usage", value: {code: 1}},{key: "usage", value: {code: 2}},- {key: "enabled", value: false},]);});@@ -201,11 +237,11 @@ test("failed persistence does not poison the queue or discard newer in-memory coassert.deepEqual(f.storage.usage, {code: 2});});-test("settings close waits for the complete queued preference drain", async () => {+test("settings close waits for the complete queued usage drain", async () => {const release: Array<() => void> = [];const f = fixture({}, () => new Promise<void>(resolve => release.push(resolve)));- f.setFrequentSlashEnabled(false);- f.setFrequentSlashEnabled(true);+ f.recordSlashExecution("code");+ f.recordSlashExecution("code");let flushed = false;const flush = f.settings.flushSettingSaves().then(() => { flushed = true; });await settle();@@ -218,7 +254,7 @@ test("settings close waits for the complete queued preference drain", async () =release.shift()();await flush;assert.equal(flushed, true);- assert.deepEqual(f.writes, [{key: "enabled", value: false}, {key: "enabled", value: true}]);+ assert.deepEqual(f.writes, [{key: "usage", value: {code: 1}}, {key: "usage", value: {code: 2}}]);});test("a rejected storage operation does not poison the drain or make settings flush reject", async () => {@@ -251,7 +287,7 @@ test("the drain preserves failures already tracked by the storage request", asynconst f = fixture({}, () => f.settings.trackSettingSave(new Promise<void>((_resolve, rejectPromise) => {reject = rejectPromise;})));- f.setFrequentSlashEnabled(false);+ f.recordSlashExecution("code");const flush = f.settings.flushSettingSaves();reject(new Error("request failed"));await assert.rejects(flush, /request failed/);diff --git a/app/src/protyle/hint/frequentSlashStorage.ts b/app/src/protyle/hint/frequentSlashStorage.tsindex 2e0109d8d8..3787ec3da7 100644--- a/app/src/protyle/hint/frequentSlashStorage.ts+++ b/app/src/protyle/hint/frequentSlashStorage.ts@@ -1,9 +1,12 @@+import {SLASH_MENU_FREQUENT_PATH, SLASH_MENU_ROOT_PATH} from "../../config/entryVisibility/catalog";+import {getConfiguredEntryVisibility} from "../../config/entryVisibility/runtime";import {Constants} from "../../constants";import {trackSettingSave} from "../../config/setting/pending";import {setStorageVal} from "../util/compatibility";import {normalizeSlashUsage, rankFrequentSlashItems} from "./frequentSlash";-export const isFrequentSlashEnabled = () => window.siyuan.storage?.[Constants.LOCAL_SLASH_FREQUENT_ENABLED] !== false;+export const isFrequentSlashEnabled = () =>+ getConfiguredEntryVisibility(SLASH_MENU_FREQUENT_PATH, SLASH_MENU_ROOT_PATH);const writable = () => window.siyuan.storage && !window.siyuan.config.readonly && !window.siyuan.isPublish;@@ -34,14 +37,6 @@ const persist = (key: string, value: unknown) => {})());};-export const setFrequentSlashEnabled = (enabled: boolean) => {- if (!writable()) {- return;- }- window.siyuan.storage[Constants.LOCAL_SLASH_FREQUENT_ENABLED] = enabled;- void persist(Constants.LOCAL_SLASH_FREQUENT_ENABLED, enabled);-};-export const getFrequentSlashItems = <T>(items: T[], getKey: (item: T) => string): T[] =>isFrequentSlashEnabled() ? rankFrequentSlashItems(items, getKey,normalizeSlashUsage(window.siyuan.storage?.[Constants.LOCAL_SLASH_USAGE])) : [];diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex babf8fd8b0..800614d5dc 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -345,6 +345,7 @@ func InitConf() {Conf.Appearance.EntryVisibility = nil}Conf.Appearance.EntryVisibility = conf.NormalizeEntryVisibility(Conf.Appearance.EntryVisibility, entryVisibilityFallback)+ migrateSlashFrequent(Conf.Appearance.EntryVisibility, getLocalStorageWithError)var langOK boolfor _, l := range Conf.Langs {if Conf.Lang == l.Name {diff --git a/kernel/model/slash_frequent.go b/kernel/model/slash_frequent.gonew file mode 100644index 0000000000..0c926548ff--- /dev/null+++ b/kernel/model/slash_frequent.go@@ -0,0 +1,35 @@+package model++import "github.com/siyuan-note/siyuan/kernel/conf"++// 将常用命令开关迁移到自定义方案,读取失败时保留未配置状态以便下次重试。+func migrateSlashFrequent(entryVisibility *conf.EntryVisibility, loadStorage func() (map[string]any, error)) {+ const key = "editor.slash.menu.frequent"+ var profiles []*conf.EntryVisibilityProfile+ if nil == entryVisibility {+ return+ }+ for _, profile := range entryVisibility.Profiles {+ if nil == profile || "" == profile.ID || "" == profile.Name ||+ conf.EntryVisibilityProfileSimple == profile.ID || conf.EntryVisibilityProfileFull == profile.ID {+ continue+ }+ if _, exists := profile.Entries[key]; !exists {+ profiles = append(profiles, profile)+ }+ }+ if 0 == len(profiles) {+ return+ }+ storage, err := loadStorage()+ if nil != err {+ return+ }+ enabled, configured := storage["local-slash-frequent-enabled"].(bool)+ for _, profile := range profiles {+ if nil == profile.Entries {+ profile.Entries = map[string]bool{}+ }+ profile.Entries[key] = !configured || enabled+ }+}diff --git a/kernel/model/slash_frequent_test.go b/kernel/model/slash_frequent_test.gonew file mode 100644index 0000000000..8d9e022dab--- /dev/null+++ b/kernel/model/slash_frequent_test.go@@ -0,0 +1,107 @@+package model++import (+ "errors"+ "reflect"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+)++func TestMigrateSlashFrequent(t *testing.T) {+ const key = "editor.slash.menu.frequent"+ for _, test := range []struct {+ name string+ storage map[string]any+ want bool+ }{+ {"disabled", map[string]any{"local-slash-frequent-enabled": false}, false},+ {"enabled", map[string]any{"local-slash-frequent-enabled": true}, true},+ {"missing", map[string]any{}, true},+ {"null", map[string]any{"local-slash-frequent-enabled": nil}, true},+ {"string", map[string]any{"local-slash-frequent-enabled": "false"}, true},+ {"number", map[string]any{"local-slash-frequent-enabled": 0}, true},+ {"object", map[string]any{"local-slash-frequent-enabled": map[string]any{"value": false}}, true},+ {"array", map[string]any{"local-slash-frequent-enabled": []any{false}}, true},+ } {+ t.Run(test.name, func(t *testing.T) {+ originalStorage := make(map[string]any, len(test.storage))+ for key, value := range test.storage {+ originalStorage[key] = value+ }+ config := conf.NormalizeEntryVisibility(&conf.EntryVisibility{+ Version: conf.EntryVisibilityVersion,+ Active: "custom",+ Profiles: []*conf.EntryVisibilityProfile{+ nil,+ {ID: conf.EntryVisibilityProfileSimple, Name: "Simple"},+ {ID: conf.EntryVisibilityProfileFull, Name: "Full"},+ {ID: "invalid"},+ {ID: "custom", Name: "Custom"},+ {ID: "inactive", Name: "Inactive", Entries: map[string]bool{"other": false}, Orders: map[string][]string{"editor.slash.menu": {"plugin", "heading"}}},+ {ID: "disabled", Name: "Disabled", Entries: map[string]bool{key: false}},+ {ID: "enabled", Name: "Enabled", Entries: map[string]bool{key: true}},+ },+ }, conf.EntryVisibilityProfileFull)+ calls := 0+ load := func() (map[string]any, error) {+ calls+++ return test.storage, nil+ }+ migrateSlashFrequent(config, load)+ migrateSlashFrequent(config, load)+ if calls != 1 {+ t.Fatalf("expected one migration read, got %d", calls)+ }+ for i, want := range []bool{test.want, test.want, false, true} {+ if got, exists := config.Profiles[i].Entries[key]; !exists || got != want {+ t.Errorf("profile %q: got %v (present %v), want %v", config.Profiles[i].ID, got, exists, want)+ }+ }+ if config.Active != "custom" || config.Version != conf.EntryVisibilityVersion {+ t.Fatalf("migration changed active profile or version: %+v", config)+ }+ if config.Profiles[1].Entries["other"] || !reflect.DeepEqual(config.Profiles[1].Orders["editor.slash.menu"], []string{"plugin", "heading"}) {+ t.Fatal("migration changed unrelated visibility or ordering")+ }+ if !reflect.DeepEqual(test.storage, originalStorage) {+ t.Fatal("migration modified local storage")+ }+ })+ }+}++func TestMigrateSlashFrequentRetriesReadFailure(t *testing.T) {+ const key = "editor.slash.menu.frequent"+ config := &conf.EntryVisibility{Profiles: []*conf.EntryVisibilityProfile{{ID: "custom", Name: "Custom"}}}+ migrateSlashFrequent(config, func() (map[string]any, error) {+ return map[string]any{"local-slash-frequent-enabled": true}, errors.New("read failed")+ })+ if _, exists := config.Profiles[0].Entries[key]; exists {+ t.Fatal("failed read persisted a default")+ }+ migrateSlashFrequent(config, func() (map[string]any, error) {+ return map[string]any{"local-slash-frequent-enabled": false}, nil+ })+ if enabled, exists := config.Profiles[0].Entries[key]; !exists || enabled {+ t.Fatal("retry did not preserve disabled preference")+ }+}++func TestMigrateSlashFrequentSkipsBuiltins(t *testing.T) {+ for _, config := range []*conf.EntryVisibility{+ nil,+ conf.NewEntryVisibility(conf.EntryVisibilityProfileSimple),+ conf.NewEntryVisibility(conf.EntryVisibilityProfileFull),+ {Profiles: []*conf.EntryVisibilityProfile{+ nil,+ {ID: conf.EntryVisibilityProfileSimple, Name: "Simple"},+ {ID: conf.EntryVisibilityProfileFull, Name: "Full"},+ }},+ } {+ migrateSlashFrequent(config, func() (map[string]any, error) {+ t.Fatal("built-in profiles should not read legacy storage")+ return nil, nil+ })+ }+}diff --git a/kernel/model/storage.go b/kernel/model/storage.goindex cafbb8270f..be9bc86dac 100644--- a/kernel/model/storage.go+++ b/kernel/model/storage.go@@ -39,9 +39,14 @@ import (var localStorageLock = sync.Mutex{}func GetLocalStorage() (ret map[string]any) {+ ret, _ = getLocalStorageWithError()+ return+}++func getLocalStorageWithError() (map[string]any, error) {localStorageLock.Lock()defer localStorageLock.Unlock()- return getLocalStorage()+ return readLocalStorage()}func SetLocalStorage(val map[string]any) (err error) {@@ -80,14 +85,18 @@ func RemoveLocalStorageVals(keys []string) (err error) {}func getLocalStorage() (ret map[string]any) {+ ret, _ = readLocalStorage()+ return+}++func readLocalStorage() (ret map[string]any, err error) {// When local.json is corrupted, clear the file to avoid being unable to enter the main interface https://github.com/siyuan-note/siyuan/issues/7911ret = map[string]any{}lsPath := filepath.Join(util.DataDir, "storage/local.json")- if !filelock.IsExist(lsPath) {- return- }-data, err := filelock.ReadFile(lsPath)+ if os.IsNotExist(err) {+ return ret, nil+ }if err != nil {logging.LogErrorf("read storage [local] failed: %s", err)return