Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support customizing plugin toolbar items https://github.com/siyuan-note/siyuan/issues/12731

Daniele14b082e4f7d
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index a33e865a8d..e95182e562 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -2,7 +2,13 @@ import * as assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {resolve} from "node:path";
import test from "node:test";
-import {DESKTOP_TOOLBAR_ENTRIES, TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";
+import {
+ DESKTOP_TOOLBAR_ENTRIES,
+ getDefaultToolbar,
+ getPluginToolbarEntryKey,
+ markPluginToolbarEntries,
+ TOOLBAR_ENTRY_ROOT_PATH,
+} from "../../protyle/toolbar/defaults";
import {
entryCatalog,
getEntryCatalogChildren,
@@ -16,6 +22,7 @@ import {
getSlashMenuEntryPath,
isEntryOrderSortable,
refreshSlashMenuCatalog,
+ refreshToolbarCatalog,
SLASH_MENU_ROOT_PATH,
} from "./catalog";
@@ -115,6 +122,33 @@ test("toolbar catalog follows the default toolbar declaration", () => {
assert.equal(children.every((item) => item.simple), true);
});
+test("toolbar catalog follows plugin insertion slots and removes unloaded plugin entries", () => {
+ const defaults = getDefaultToolbar(false).map((item) => typeof item === "string" ? {name: item} : item);
+ const pluginItem = {name: "shared.item"};
+ const pluginKey = getPluginToolbarEntryKey("plugin.name", pluginItem.name);
+ const pluginSeparatorKey = getPluginToolbarEntryKey("plugin.name", "1", "separator");
+ try {
+ const toolbar = markPluginToolbarEntries(defaults,
+ [defaults[0], pluginItem, "|", ...defaults.slice(1)], "plugin.name", () => "Plugin Name - Shared Item")
+ .map((item) => typeof item === "string" ? {name: item} : item);
+ refreshToolbarCatalog(toolbar);
+ const children = getEntryCatalogChildren(TOOLBAR_ENTRY_ROOT_PATH);
+ assert.deepEqual(children.slice(0, 4).map((item) => item.key), [
+ DESKTOP_TOOLBAR_ENTRIES[0].key,
+ pluginKey,
+ pluginSeparatorKey,
+ DESKTOP_TOOLBAR_ENTRIES[1].key,
+ ]);
+ assert.equal(getEntryCatalogNode(`${TOOLBAR_ENTRY_ROOT_PATH}.${pluginKey}`)?.label(),
+ "Plugin Name - Shared Item");
+ assert.equal(getEntryCatalogNode(`${TOOLBAR_ENTRY_ROOT_PATH}.${pluginSeparatorKey}`)?.type, "separator");
+ assert.equal(getEntryParentPath(`${TOOLBAR_ENTRY_ROOT_PATH}.${pluginKey}`), TOOLBAR_ENTRY_ROOT_PATH);
+ } finally {
+ refreshToolbarCatalog(defaults);
+ }
+ assert.equal(getEntryCatalogNode(`${TOOLBAR_ENTRY_ROOT_PATH}.${pluginKey}`), undefined);
+});
+
test("slash menu catalog follows the built-in hint order", () => {
const section = getEntryCatalogSection("editor.slash");
assert.deepEqual(section?.children.map((item) => item.key), ["menu"]);
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index 1e104bfdc8..66182b26f0 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -1,5 +1,11 @@
import {CODE_TAB_SPACE_VALUES} from "../../protyle/wysiwyg/codeBlockUtil";
-import {DESKTOP_TOOLBAR_ENTRIES, TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";
+import {
+ DESKTOP_TOOLBAR_ENTRIES,
+ getToolbarEntryId,
+ getToolbarEntryLabel,
+ TOOLBAR_ENTRY_ROOT_PATH,
+} from "../../protyle/toolbar/defaults";
+import {mergeEntryOrderPreservingUnknown} from "./order";
export interface IEntryCatalogNode {
key: string;
@@ -416,6 +422,7 @@ export const SLASH_MENU_ROOT_PATH = "editor.slash.menu";
const toolbarBuiltinChildren = DESKTOP_TOOLBAR_ENTRIES.map((item) => item.separator
? separator(item.key)
: node(item.key, lang(item.lang)));
+const toolbarBuiltinNodeMap = new Map(toolbarBuiltinChildren.map((item) => [item.key, item]));
const slashMenuBuiltinChildren = [
node("template", lang("template")),
@@ -493,6 +500,12 @@ const slashMenuRoot = {
displayChildrenDirectly: true,
};
+const toolbarCatalogSection: IEntryCatalogSection = {
+ key: TOOLBAR_ENTRY_ROOT_PATH,
+ label: location(lang("editor"), lang("entryToolbar")),
+ children: toolbarBuiltinChildren,
+};
+
export const entryCatalog: IEntryCatalogSection[] = [
{
key: "dock",
@@ -672,11 +685,7 @@ export const entryCatalog: IEntryCatalogSection[] = [
node("docInfo", lang("entryDocumentStatistics"), false),
],
},
- {
- key: TOOLBAR_ENTRY_ROOT_PATH,
- label: location(lang("editor"), lang("entryToolbar")),
- children: toolbarBuiltinChildren,
- },
+ toolbarCatalogSection,
{
key: "editor.slash",
label: location(lang("editor"), lang("entrySlashMenu")),
@@ -938,6 +947,58 @@ export const getEntryCatalogPathChain = (sectionKey: string, path: string) => {
return current === sectionKey ? chain : [];
};
+const normalizeToolbarCatalogSeparators = (nodes: IEntryCatalogNode[]) => {
+ const result: IEntryCatalogNode[] = [];
+ nodes.forEach((item) => {
+ if (item.type === "separator" && (result.length === 0 || result[result.length - 1].type === "separator")) {
+ return;
+ }
+ result.push(item);
+ });
+ if (result[result.length - 1]?.type === "separator") {
+ result.pop();
+ }
+ return result;
+};
+
+const toolbarCatalogNodeSignature = (item: IEntryCatalogNode, pluginLabels: Map<string, string>) => [
+ item.key,
+ item.type,
+ pluginLabels.get(item.key) || "",
+];
+
+let toolbarCatalogSignature = JSON.stringify(toolbarBuiltinChildren.map((item) =>
+ toolbarCatalogNodeSignature(item, new Map())));
+
+export const refreshToolbarCatalog = (items: Array<string | IMenuItem>) => {
+ const nodes = new Map(toolbarBuiltinNodeMap);
+ const pluginLabels = new Map<string, string>();
+ const actualOrder: string[] = [];
+ items.forEach((item) => {
+ const menuItem = typeof item === "string" ? {name: item} : item;
+ const key = getToolbarEntryId(menuItem);
+ if (!key || actualOrder.includes(key)) {
+ return;
+ }
+ actualOrder.push(key);
+ if (nodes.has(key)) {
+ return;
+ }
+ const label = getToolbarEntryLabel(menuItem) || menuItem.tip || menuItem.name;
+ pluginLabels.set(key, label);
+ nodes.set(key, menuItem.name === "|" ? separator(key) : node(key, literal(label)));
+ });
+ const order = mergeEntryOrderPreservingUnknown(toolbarBuiltinChildren.map((item) => item.key), actualOrder);
+ const children = normalizeToolbarCatalogSeparators(order.flatMap((key) => nodes.get(key) || []));
+ const signature = JSON.stringify(children.map((item) => toolbarCatalogNodeSignature(item, pluginLabels)));
+ if (signature === toolbarCatalogSignature) {
+ return;
+ }
+ toolbarCatalogSection.children = children;
+ toolbarCatalogSignature = signature;
+ rebuildCatalogIndexes();
+};
+
interface ISlashMenuCatalogPlugin {
name: string;
displayName?: string;
diff --git a/app/src/protyle/toolbar/defaults.ts b/app/src/protyle/toolbar/defaults.ts
index 30faa3aebb..604bc55031 100644
--- a/app/src/protyle/toolbar/defaults.ts
+++ b/app/src/protyle/toolbar/defaults.ts
@@ -1,4 +1,4 @@
-const toolbarEntryId = Symbol("toolbarEntryId");
+const toolbarEntryMetadata = Symbol("toolbarEntryMetadata");
interface IToolbarEntry {
key: string;
@@ -9,7 +9,10 @@ interface IToolbarEntry {
}
type TConfigurableToolbarItem = IMenuItem & {
- [toolbarEntryId]?: string;
+ [toolbarEntryMetadata]?: {
+ id: string;
+ label?: string;
+ };
};
export const TOOLBAR_ENTRY_ROOT_PATH = "editor.toolbar";
@@ -101,10 +104,14 @@ const desktopToolbarEntryKeys = new Map(DESKTOP_TOOLBAR_ENTRIES
.filter((item) => !item.separator)
.map((item) => [item.name, item.key]));
+const setToolbarEntryMetadata = (item: IMenuItem, id: string, label?: string) => {
+ (item as TConfigurableToolbarItem)[toolbarEntryMetadata] = {id, label};
+ return item;
+};
+
const toolbarSeparator = (entryId: string): IMenuItem => {
const item: TConfigurableToolbarItem = {name: "|"};
- item[toolbarEntryId] = entryId;
- return item;
+ return setToolbarEntryMetadata(item, entryId);
};
export const getDefaultToolbar = (mobile: boolean): Array<string | IMenuItem> => {
@@ -137,6 +144,38 @@ export const getDefaultToolbar = (mobile: boolean): Array<string | IMenuItem> =>
});
};
-export const getToolbarEntryId = (item: IMenuItem) => item.name === "|"
- ? (item as TConfigurableToolbarItem)[toolbarEntryId]
- : desktopToolbarEntryKeys.get(item.name);
+export const getToolbarEntryId = (item: IMenuItem) =>
+ (item as TConfigurableToolbarItem)[toolbarEntryMetadata]?.id || desktopToolbarEntryKeys.get(item.name);
+
+export const getToolbarEntryLabel = (item: IMenuItem) =>
+ (item as TConfigurableToolbarItem)[toolbarEntryMetadata]?.label;
+
+const encodeToolbarEntryKeyPart = (value: string) => encodeURIComponent(value).replace(/\./g, "%2E");
+
+export const getPluginToolbarEntryKey = (pluginName: string, itemName: string,
+ type: "entry" | "separator" = "entry") =>
+ `${type === "separator" ? "plugin-separator" : "plugin"}:${encodeToolbarEntryKeyPart(pluginName)}:${encodeToolbarEntryKeyPart(itemName)}`;
+
+export const markPluginToolbarEntries = (previous: Array<string | IMenuItem>, updated: Array<string | IMenuItem>,
+ pluginName: string, getLabel: (item: IMenuItem) => string) => {
+ const previousItems = new Set(previous.filter((item): item is IMenuItem => typeof item !== "string"));
+ let separatorIndex = 0;
+ return updated.map((item) => {
+ if (typeof item === "string") {
+ if (item !== "|") {
+ return item;
+ }
+ separatorIndex++;
+ return toolbarSeparator(getPluginToolbarEntryKey(pluginName, separatorIndex.toString(), "separator"));
+ }
+ if (getToolbarEntryId(item) || previousItems.has(item)) {
+ return item;
+ }
+ if (item.name === "|") {
+ separatorIndex++;
+ return setToolbarEntryMetadata(item,
+ getPluginToolbarEntryKey(pluginName, separatorIndex.toString(), "separator"));
+ }
+ return setToolbarEntryMetadata(item, getPluginToolbarEntryKey(pluginName, item.name), getLabel(item));
+ });
+};
diff --git a/app/src/protyle/toolbar/entryVisibility.test.ts b/app/src/protyle/toolbar/entryVisibility.test.ts
index 0ade0c75d7..8aa4be4e27 100644
--- a/app/src/protyle/toolbar/entryVisibility.test.ts
+++ b/app/src/protyle/toolbar/entryVisibility.test.ts
@@ -1,6 +1,13 @@
import * as assert from "node:assert/strict";
import test from "node:test";
-import {DESKTOP_TOOLBAR_ENTRIES, getDefaultToolbar, getToolbarEntryId} from "./defaults";
+import {
+ DESKTOP_TOOLBAR_ENTRIES,
+ getDefaultToolbar,
+ getPluginToolbarEntryKey,
+ getToolbarEntryId,
+ getToolbarEntryLabel,
+ markPluginToolbarEntries,
+} from "./defaults";
import {normalizeToolbarSeparators, resolveToolbarItems} from "./entryVisibility";
interface IToolbarTestItem {
@@ -24,18 +31,42 @@ test("desktop toolbar defaults expose stable configuration identifiers", () => {
assert.equal(getToolbarEntryId({name: "plugin-item"}), undefined);
});
-test("toolbar applies configured order while preserving plugin slots", () => {
- const plugin = {};
- const result = resolve([{key: "a"}, plugin, {key: "b"}, {key: "c"}], {
+test("plugin toolbar entries use plugin-scoped configuration identifiers", () => {
+ const existing = {name: "existing"};
+ const pluginItem = {name: "shared.item"};
+ const marked = markPluginToolbarEntries([existing], [existing, pluginItem, "|"], "plugin.name",
+ (item) => `Plugin - ${item.name}`) as IMenuItem[];
+ assert.equal(getToolbarEntryId(existing), undefined);
+ assert.equal(getToolbarEntryId(marked[1]), getPluginToolbarEntryKey("plugin.name", "shared.item"));
+ assert.equal(getToolbarEntryLabel(marked[1]), "Plugin - shared.item");
+ assert.equal(getToolbarEntryId(Object.assign({}, marked[1])),
+ getPluginToolbarEntryKey("plugin.name", "shared.item"));
+ assert.equal(getToolbarEntryId(marked[2]), getPluginToolbarEntryKey("plugin.name", "1", "separator"));
+ assert.notEqual(getPluginToolbarEntryKey("plugin.name", "shared.item"),
+ getPluginToolbarEntryKey("another.plugin", "shared.item"));
+ assert.notEqual(getPluginToolbarEntryKey("plugin.name", "shared.item"),
+ getPluginToolbarEntryKey("plugin", "name.shared.item"));
+});
+
+test("toolbar applies configured order while preserving unregistered slots", () => {
+ const unregistered = {};
+ const result = resolve([{key: "a"}, unregistered, {key: "b"}, {key: "c"}], {
order: ["c", "b", "a"],
});
- assert.deepEqual(result.ordered, [{key: "c"}, plugin, {key: "b"}, {key: "a"}]);
+ assert.deepEqual(result.ordered, [{key: "c"}, unregistered, {key: "b"}, {key: "a"}]);
+});
+
+test("toolbar hides configured entries without hiding unregistered entries", () => {
+ const unregistered = {};
+ const result = resolve([{key: "a"}, unregistered, {key: "b"}], {hidden: ["a", "b"]});
+ assert.deepEqual(result.visible, [unregistered]);
});
-test("toolbar hides configured entries without hiding plugin entries", () => {
- const plugin = {};
- const result = resolve([{key: "a"}, plugin, {key: "b"}], {hidden: ["a", "b"]});
- assert.deepEqual(result.visible, [plugin]);
+test("toolbar hides a configured plugin entry without hiding unregistered entries", () => {
+ const pluginKey = getPluginToolbarEntryKey("plugin.name", "item");
+ const unregistered = {};
+ const result = resolve([{key: pluginKey}, unregistered], {hidden: [pluginKey]});
+ assert.deepEqual(result.visible, [unregistered]);
});
test("toolbar removes empty groups after visibility filtering", () => {
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index 33121f2246..e377e0c4e7 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -60,8 +60,9 @@ import {FormatPainter} from "./FormatPainter";
import {IFormatPainterSnapshot} from "./formatPainterCore";
import {clearDisallowedTextInputHotkey} from "../../util/hotKeyPolicy";
import {closeSubElement} from "./subElementLifecycle";
-import {getDefaultToolbar, getToolbarEntryId} from "./defaults";
+import {getDefaultToolbar, getToolbarEntryId, markPluginToolbarEntries} from "./defaults";
import {applyToolbarEntryVisibility} from "../../config/entryVisibility/runtime";
+import {refreshToolbarCatalog} from "../../config/entryVisibility/catalog";
const filterPluginToolbar = (toolbar: Array<string | IMenuItem>, lite: boolean) => {
if (!lite) {
@@ -80,6 +81,33 @@ const filterPluginToolbar = (toolbar: Array<string | IMenuItem>, lite: boolean)
});
};
+const applyPluginToolbar = (toolbar: Array<string | IMenuItem>, protyle: IProtyle) => {
+ let result = toolbar;
+ protyle.app.plugins.forEach((plugin) => {
+ const previous = [...result];
+ result = markPluginToolbarEntries(previous, plugin.updateProtyleToolbar(result), plugin.name, (item) => {
+ const pluginName = plugin.displayName?.trim() || plugin.name;
+ const label = item.tip || (item.lang ? window.siyuan.languages[item.lang] : "") || item.name;
+ return `${pluginName} - ${label}`;
+ });
+ result = filterPluginToolbar(result, protyle.lite);
+ result.forEach((toolbarItem) => {
+ if (typeof toolbarItem === "string" || Constants.INLINE_TYPE.concat("|").includes(toolbarItem.name)) {
+ return;
+ }
+ if (typeof toolbarItem.hotkey !== "string") {
+ toolbarItem.hotkey = "";
+ }
+ if (window.siyuan.config.keymap.plugin && window.siyuan.config.keymap.plugin[plugin.name] && window.siyuan.config.keymap.plugin[plugin.name][toolbarItem.name]) {
+ toolbarItem.hotkey = window.siyuan.config.keymap.plugin[plugin.name][toolbarItem.name].custom;
+ }
+ toolbarItem.hotkey = clearDisallowedTextInputHotkey(toolbarItem.hotkey);
+ });
+ result = toolbarKeyToMenu(result);
+ });
+ return result as IMenuItem[];
+};
+
interface IToolbarRangePosition {
left: number;
top: number;
@@ -110,22 +138,10 @@ export class Toolbar {
this.subElement.className = "protyle-util fn__none";
/// #endif
this.toolbarHeight = 29;
- protyle.app.plugins.forEach(item => {
- const pluginToolbar = filterPluginToolbar(item.updateProtyleToolbar(options.toolbar), protyle.lite);
- pluginToolbar.forEach(toolbarItem => {
- if (typeof toolbarItem === "string" || Constants.INLINE_TYPE.concat("|").includes(toolbarItem.name)) {
- return;
- }
- if (typeof toolbarItem.hotkey !== "string") {
- toolbarItem.hotkey = "";
- }
- if (window.siyuan.config.keymap.plugin && window.siyuan.config.keymap.plugin[item.name] && window.siyuan.config.keymap.plugin[item.name][toolbarItem.name]) {
- toolbarItem.hotkey = window.siyuan.config.keymap.plugin[item.name][toolbarItem.name].custom;
- }
- toolbarItem.hotkey = clearDisallowedTextInputHotkey(toolbarItem.hotkey);
- });
- options.toolbar = toolbarKeyToMenu(pluginToolbar);
- });
+ options.toolbar = applyPluginToolbar(options.toolbar, protyle);
+ if (!isMobile() && !protyle.lite) {
+ refreshToolbarCatalog(options.toolbar);
+ }
options.toolbar.forEach((menuItem: IMenuItem) => {
const itemElement = this.genItem(protyle, menuItem);
this.element.appendChild(itemElement);
@@ -139,22 +155,10 @@ export class Toolbar {
public update(protyle: IProtyle) {
this.element.innerHTML = "";
protyle.options.toolbar = toolbarKeyToMenu(getDefaultToolbar(isMobile()));
- protyle.app.plugins.forEach(item => {
- const pluginToolbar = filterPluginToolbar(item.updateProtyleToolbar(protyle.options.toolbar), protyle.lite);
- pluginToolbar.forEach(toolbarItem => {
- if (typeof toolbarItem === "string" || Constants.INLINE_TYPE.concat("|").includes(toolbarItem.name)) {
- return;
- }
- if (typeof toolbarItem.hotkey !== "string") {
- toolbarItem.hotkey = "";
- }
- if (window.siyuan.config.keymap.plugin && window.siyuan.config.keymap.plugin[item.name] && window.siyuan.config.keymap.plugin[item.name][toolbarItem.name]) {
- toolbarItem.hotkey = window.siyuan.config.keymap.plugin[item.name][toolbarItem.name].custom;
- }
- toolbarItem.hotkey = clearDisallowedTextInputHotkey(toolbarItem.hotkey);
- });
- protyle.options.toolbar = toolbarKeyToMenu(pluginToolbar);
- });
+ protyle.options.toolbar = applyPluginToolbar(protyle.options.toolbar, protyle);
+ if (!isMobile() && !protyle.lite) {
+ refreshToolbarCatalog(protyle.options.toolbar);
+ }
protyle.options.toolbar.forEach((menuItem: IMenuItem) => {
const itemElement = this.genItem(protyle, menuItem);
this.element.appendChild(itemElement);