An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support custom content elements in plugin top bar https://github.com/siyuan-note/siyuan/issues/19330
Danielbf862adb59fd
diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.tsindex 49b2907bea..2f81cf640a 100644--- a/app/src/plugin/index.ts+++ b/app/src/plugin/index.ts@@ -75,6 +75,7 @@ export class Plugin {}} = {};public topBarIcons: Element[] = [];+ private customTopBarElements = new WeakSet<HTMLElement>();public setting: Setting;public statusBarIcons: Element[] = [];public commands: ICommand[] = [];@@ -229,24 +230,51 @@ export class Plugin {public addTopBar(options: {id?: string,- icon: string,+ icon?: string,title: string,position?: "right" | "left",- callback: (evt: MouseEvent) => void+ element?: HTMLElement,+ callback?: (evt: MouseEvent) => void}) {if (isPluginDisposed(this)) {return;}- options.icon = options.icon.trim();- if (!options.icon.startsWith("icon") && !options.icon.startsWith("<svg")) {+ if (options.element && (isMobile() || isWindow())) {+ return;+ }+ if (!options.element) {+ options.icon = options.icon?.trim() || "";+ }+ if (!options.element && !options.icon.startsWith("icon") && !options.icon.startsWith("<svg")) {console.error(`plugin ${this.name} addTopBar error: icon must be svg id or svg tag`);return;}let iconElement = typeof options.id === "string" ? this.topBarIcons.find(item =>item.getAttribute("data-id") === options.id) as HTMLElement : undefined;+ if (options.element && this.topBarIcons.includes(options.element)) {+ if (typeof options.id !== "string") {+ iconElement = options.element;+ } else if (iconElement !== options.element) {+ console.error(`plugin ${this.name} addTopBar error: element is already registered with another id`);+ return;+ }+ }const isNew = !iconElement;+ if (iconElement && (options.element && options.element !== iconElement ||+ !options.element && this.customTopBarElements.has(iconElement))) {+ const replacement = options.element || document.createElement("div");+ ["id", "data-id", "data-topbar-entry", "data-location"].forEach(name => {+ const value = iconElement.getAttribute(name);+ if (value !== null) {+ replacement.setAttribute(name, value);+ }+ });+ iconElement.replaceWith(replacement);+ this.topBarIcons[this.topBarIcons.indexOf(iconElement)] = replacement;+ iconElement = replacement;+ }if (!iconElement) {- iconElement = document.createElement("div");+ iconElement = options.element || document.createElement("div");if (typeof options.id === "string") {iconElement.id = `plugin_${encodeURIComponent(this.name)}:${encodeURIComponent(options.id)}`;iconElement.setAttribute("data-id", options.id);@@ -261,16 +289,22 @@ export class Plugin {}}const previousLocation = iconElement.getAttribute("data-location");- iconElement.setAttribute("data-menu", "true");- iconElement.onclick = options.callback;- if (isMobile()) {+ if (options.element) {+ this.customTopBarElements.add(iconElement);+ iconElement.setAttribute("aria-label", options.title);+ iconElement.setAttribute("data-location", options.position || "right");+ } else {+ iconElement.setAttribute("data-menu", "true");+ iconElement.onclick = options.callback;+ }+ if (!options.element && isMobile()) {iconElement.className = "b3-menu__item";const iconHTML = options.icon.startsWith("icon") ?`<svg class="b3-menu__icon"><use xlink:href="#${options.icon}"></use></svg>` :`<span class="b3-menu__icon b3-menu__icon--custom">${options.icon}</span>`;iconElement.innerHTML = iconHTML +`<span class="b3-menu__label">${options.title}</span>`;- } else if (!isWindow()) {+ } else if (!options.element && !isWindow()) {iconElement.className = "toolbar__item ariaLabel";iconElement.setAttribute("aria-label", options.title);iconElement.innerHTML = options.icon.startsWith("icon") ? `<svg><use xlink:href="#${options.icon}"></use></svg>` : options.icon;@@ -282,7 +316,9 @@ export class Plugin {document.getElementById("menuPluginTopBar")?.after(iconElement);}} else if (!isWindow() && window.siyuan.storage) {- if (!document.contains(iconElement) || previousLocation !== iconElement.getAttribute("data-location")) {+ if (!document.contains(iconElement) ||+ options.element && iconElement.parentElement !== document.getElementById("toolbar") ||+ previousLocation !== iconElement.getAttribute("data-location")) {document.querySelector("#" + (iconElement.getAttribute("data-location") === "right" ? "barPlugins" : "drag"))?.before(iconElement);}}diff --git a/app/src/plugin/openTopBarMenu.ts b/app/src/plugin/openTopBarMenu.tsindex 7107f48338..8aa6ea9e90 100644--- a/app/src/plugin/openTopBarMenu.ts+++ b/app/src/plugin/openTopBarMenu.ts@@ -90,9 +90,12 @@ export const openTopBarMenu = (app: App, target?: Element) => {menuOption.submenu = submenu;}const customIconElement = item.querySelector(":scope > .b3-menu__icon--custom");- const iconElement = (customIconElement || item.querySelector("svg")).cloneNode(true) as HTMLElement;- iconElement.classList.add("b3-menu__icon");- menuOption.iconHTML = iconElement.outerHTML;+ const sourceIconElement = customIconElement || item.querySelector("svg");+ if (sourceIconElement) {+ const iconElement = sourceIconElement.cloneNode(true) as HTMLElement;+ iconElement.classList.add("b3-menu__icon");+ menuOption.iconHTML = iconElement.outerHTML;+ }menu.addItem(menuOption);hasPlugin = true;hasTopBar = true;diff --git a/app/src/plugin/topBar.test.ts b/app/src/plugin/topBar.test.tsnew file mode 100644index 0000000000..70c227a4ba--- /dev/null+++ b/app/src/plugin/topBar.test.ts@@ -0,0 +1,181 @@+import * as assert from "node:assert/strict";+import test from "node:test";+import {readFileSync} from "node:fs";+import {resolve} from "node:path";+import {runInNewContext} from "node:vm";+import * as ts from "typescript";+import {getLegacyPluginTopBarEntryKey, getPluginTopBarEntryKey} from "./topBarKey";++class TestElement {+ public attributes = new Map<string, string>();+ public className = "custom";+ public innerHTML = "Countdown";+ public onclick = () => "clicked";+ public replacement?: TestElement;+ public removed = false;+ public parentElement?: TestElement;++ get id() { return this.getAttribute("id"); }+ set id(value: string) { this.setAttribute("id", value); }+ getAttribute(name: string) { return this.attributes.get(name) ?? null; }+ setAttribute(name: string, value: string) { this.attributes.set(name, value); }+ replaceWith(element: TestElement) { this.replacement = element; }+ remove() { this.removed = true; }+}++const setup = (mobile = false, detached = false, mounted = false) => {+ const source = readFileSync(resolve(process.cwd(), "src/plugin/index.ts"), "utf8");+ const compiled = ts.transpileModule(source, {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},+ }).outputText;+ let refreshes = 0;+ const toolbar = new TestElement();+ const insertions: string[] = [];+ const dependencies = {+ isMobile: () => mobile,+ isWindow: () => detached,+ getPluginTopBarEntryKey,+ getLegacyPluginTopBarEntryKey,+ applyTopBarEntryVisibility: () => refreshes++,+ resizeTopBar: (): void => undefined,+ setTabPosition: (): void => undefined,+ };+ const exports: {Plugin?: typeof import("./index").Plugin} = {};+ runInNewContext(compiled, {+ exports,+ require: () => dependencies,+ console: {error: (): void => undefined},+ document: {+ createElement: () => new TestElement(),+ contains: (element: TestElement) => !!element.parentElement,+ getElementById: () => toolbar,+ querySelector: (selector: string) => ({before: (element: TestElement) => {+ insertions.push(selector);+ element.parentElement = toolbar;+ }}),+ },+ window: {siyuan: {storage: mounted ? {} : undefined}},+ });+ const plugin = Object.create(exports.Plugin.prototype);+ Object.assign(plugin, {name: "test", topBarIcons: [], customTopBarElements: new WeakSet()});+ return {plugin, toolbar, insertions, refreshes: () => refreshes};+};++test("custom top bar preserves content and handlers and registers a configurable entry", () => {+ const {plugin, refreshes} = setup();+ const element = new TestElement();+ const onclick = element.onclick;+ assert.equal(plugin.addTopBar({id: "timer", title: "Timer", element, icon: "invalid", callback: (): void => undefined}), element);+ assert.equal(element.className, "custom");+ assert.equal(element.innerHTML, "Countdown");+ assert.equal(element.onclick, onclick);+ assert.equal(element.getAttribute("data-menu"), null);+ assert.equal(element.id, "plugin_test:timer");+ assert.equal(element.getAttribute("data-id"), "timer");+ assert.equal(element.getAttribute("data-topbar-entry"), getPluginTopBarEntryKey("test", "timer"));+ assert.equal(element.getAttribute("data-location"), "right");+ assert.equal(element.getAttribute("aria-label"), "Timer");+ assert.equal(refreshes(), 1);+});++test("same ID replaces custom elements and supports switching between icons and custom content", () => {+ const {plugin} = setup();+ const icon = plugin.addTopBar({id: "timer", title: "Icon", icon: " iconClock "});+ const element = new TestElement();+ plugin.addTopBar({id: "timer", title: "Timer", element, position: "left"});+ assert.equal(icon.replacement, element);+ assert.equal(plugin.topBarIcons.length, 1);+ assert.equal(element.getAttribute("data-location"), "left");+ assert.equal(plugin.addTopBar({id: "timer", title: "Updated", element}), element);+ const replacement = new TestElement();+ plugin.addTopBar({id: "timer", title: "Replacement", element: replacement});+ assert.equal(element.replacement, replacement);+ const newIcon = plugin.addTopBar({id: "timer", title: "Icon", icon: "iconClock"});+ assert.equal(replacement.replacement, newIcon);+ assert.equal(replacement.innerHTML, "Countdown");+ assert.equal(newIcon.className, "toolbar__item ariaLabel");+ assert.equal(plugin.topBarIcons.length, 1);+ plugin.removeTopBar("timer");+ assert.equal(newIcon.removed, true);+ assert.equal(plugin.topBarIcons.length, 0);+});++test("custom elements without IDs receive distinct legacy keys", () => {+ const {plugin} = setup();+ const first = plugin.addTopBar({title: "First", element: new TestElement()});+ const second = plugin.addTopBar({title: "Second", element: new TestElement()});+ assert.notEqual(first.id, second.id);+ assert.notEqual(first.getAttribute("data-topbar-entry"), second.getAttribute("data-topbar-entry"));+});++test("unsupported windows skip custom entries and missing icons are rejected", () => {+ for (const {plugin} of [setup(true), setup(false, true)]) {+ assert.equal(plugin.addTopBar({title: "Timer", element: new TestElement()}), undefined);+ assert.equal(plugin.topBarIcons.length, 0);+ }+ const {plugin} = setup();+ assert.equal(plugin.addTopBar({title: "Missing"}), undefined);+ assert.equal(plugin.topBarIcons.length, 0);+});++test("reusing an element keeps a single registration and rejects conflicting IDs", () => {+ const {plugin} = setup();+ const element = new TestElement();+ plugin.addTopBar({title: "Timer", element});+ const id = element.id;+ plugin.addTopBar({title: "Updated", element});+ assert.equal(element.id, id);+ assert.equal(plugin.topBarIcons.length, 1);+ assert.equal(plugin.addTopBar({id: "other", title: "Conflict", element}), undefined);+ assert.equal(element.id, id);+ assert.equal(plugin.topBarIcons.length, 1);+});++test("custom elements move into the toolbar and keep their slot until their side changes", () => {+ const {plugin, toolbar, insertions} = setup(false, false, true);+ const element = new TestElement();+ element.parentElement = new TestElement();+ plugin.addTopBar({id: "timer", title: "Timer", element});+ assert.equal(element.parentElement, toolbar);+ assert.deepEqual(insertions, ["#barPlugins"]);+ plugin.addTopBar({id: "timer", title: "Updated", element});+ assert.deepEqual(insertions, ["#barPlugins"]);+ plugin.addTopBar({id: "timer", title: "Left", element, position: "left"});+ assert.deepEqual(insertions, ["#barPlugins", "#drag"]);+});++test("plugin menu supports custom content without SVG icons", () => {+ const source = readFileSync(resolve(process.cwd(), "src/plugin/openTopBarMenu.ts"), "utf8");+ const compiled = ts.transpileModule(source, {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},+ }).outputText;+ const items: IMenu[] = [];+ const dependencies = {+ Menu: class {+ addItem(item: IMenu) { items.push(item); }+ addSeparator(): void { return undefined; }+ open(): void { return undefined; }+ },+ Constants: {},+ isBazaarAvailable: () => true,+ isMobile: () => false,+ hasPluginSetting: () => false,+ };+ const exports: {openTopBarMenu?: typeof import("./openTopBarMenu").openTopBarMenu} = {};+ runInNewContext(compiled, {+ exports,+ require: () => dependencies,+ document: {contains: () => true},+ window: {siyuan: {languages: {}, config: {readonly: false}}},+ });+ const element = new TestElement();+ element.id = "plugin_test:timer";+ element.setAttribute("aria-label", "Timer");+ Object.assign(element, {querySelector: (): null => null});+ const target = {getBoundingClientRect: () => ({width: 10, right: 10, bottom: 10, height: 10})};+ exports.openTopBarMenu({plugins: [{topBarIcons: [element]}]} as never, target as never);+ const item = items.find(entry => entry.id === element.id);+ assert.equal(item.label, "Timer");+ assert.equal(item.icon, "iconInfo");+ assert.equal(item.iconHTML, undefined);+});