An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve plugin event bus subscriptions and unload cleanup https://github.com/siyuan-note/siyuan/issues/18762
Danielbbdff638b5d3
diff --git a/app/src/asset/index.ts b/app/src/asset/index.tsindex dac620e9c5..20d2c716e5 100644--- a/app/src/asset/index.ts+++ b/app/src/asset/index.ts@@ -38,7 +38,9 @@ export class Asset extends Model {clearOBG();setPanelFocus(this.element.parentElement.parentElement);this.app.plugins.forEach(item => {- item.eventBus.emit("click-pdf", {event});+ if (item.eventBus.has("click-pdf")) {+ item.eventBus.emit("click-pdf", {event});+ }});});if (typeof this.pdfId === "string") {diff --git a/app/src/card/openCard.ts b/app/src/card/openCard.tsindex 93af957733..727b496be7 100644--- a/app/src/card/openCard.ts+++ b/app/src/card/openCard.ts@@ -808,10 +808,12 @@ export const bindCardEvent = async (options: {const emitEvent = (app: App, card: ICard, type: string) => {app.plugins.forEach(item => {- item.eventBus.emit("click-flashcard-action", {- type,- card- });+ if (item.eventBus.has("click-flashcard-action")) {+ item.eventBus.emit("click-flashcard-action", {+ type,+ card+ });+ }});};diff --git a/app/src/dialog/processSystem.ts b/app/src/dialog/processSystem.tsindex bb5b4d8beb..81a4e0da52 100644--- a/app/src/dialog/processSystem.ts+++ b/app/src/dialog/processSystem.ts@@ -20,6 +20,7 @@ import type {App} from "../index";import {saveScroll} from "../protyle/scroll/saveScroll";import {isInAndroid, isInHarmony, isInIOS, setStorageVal} from "../protyle/util/compatibility";import {Plugin} from "../plugin";+import {emitToPlugins} from "../plugin/EventBusCore";export const processBacklinkIndexCommit = (data: {rootIDs?: string[],@@ -125,9 +126,7 @@ export const lockScreen = async (app: App) => {if (window.siyuan.config.readonly || window.siyuan.isPublish) {return;}- app.plugins.forEach(item => {- item.eventBus.emit("lock-screen");- });+ emitToPlugins(app.plugins, "lock-screen");/// #if !MOBILEexportLayout({errorExit: false,@@ -513,13 +512,11 @@ export const processSync = (data?: IWebSocketData, plugins?: Plugin[]) => {useElement.setAttribute("xlink:href", syncDisabled ? "#iconCloudOff" : "#iconCloudSucc");}/// #endif- plugins.forEach((item) => {- if (data.code === 0) {- item.eventBus.emit("sync-start", data);- } else if (data.code === 1) {- item.eventBus.emit("sync-end", data);- } else if (data.code === 2) {- item.eventBus.emit("sync-fail", data);- }- });+ if (data.code === 0) {+ emitToPlugins(plugins, "sync-start", data);+ } else if (data.code === 1) {+ emitToPlugins(plugins, "sync-end", data);+ } else if (data.code === 2) {+ emitToPlugins(plugins, "sync-fail", data);+ }};diff --git a/app/src/dialog/tooltip.ts b/app/src/dialog/tooltip.tsindex 3685f678f0..7ccad9cdc2 100644--- a/app/src/dialog/tooltip.ts+++ b/app/src/dialog/tooltip.ts@@ -1,4 +1,5 @@import {isMobile} from "../util/functions";+import {emitToPlugins} from "../plugin/EventBusCore";export const showTooltip = (message: string,@@ -17,9 +18,7 @@ export const showTooltip = (target,tooltipElement: messageElement,};- window.siyuan.ws.app.plugins.forEach(plugin => {- plugin.eventBus.emit("before-show-tooltip", showDetail);- });+ emitToPlugins(window.siyuan.ws.app.plugins, "before-show-tooltip", showDetail);message = showDetail.message;if (!message) {hideTooltip();@@ -152,9 +151,11 @@ export const hideTooltip = () => {return;}window.siyuan.ws.app.plugins.forEach(plugin => {- plugin.eventBus.emit("before-hide-tooltip", {- tooltipElement: messageElement,- });+ if (plugin.eventBus.has("before-hide-tooltip")) {+ plugin.eventBus.emit("before-hide-tooltip", {+ tooltipElement: messageElement,+ });+ }});messageElement.classList.add("fn__none");};diff --git a/app/src/editor/openLinkEvent.test.ts b/app/src/editor/openLinkEvent.test.tsindex b6541eefd0..d52834ff69 100644--- a/app/src/editor/openLinkEvent.test.ts+++ b/app/src/editor/openLinkEvent.test.ts@@ -9,7 +9,7 @@ import {} from "./openLinkEvent";const createApp = (emitters: Array<(type: TEventBus, detail: unknown) => boolean>) => ({- plugins: emitters.map((emit) => ({eventBus: {emit}})),+ plugins: emitters.map((emit) => ({eventBus: {emit, has: () => true}})),}) as unknown as App;describe("link opening plugin events", () => {@@ -79,6 +79,24 @@ describe("link opening plugin events", () => {assert.deepEqual(calls, [1, 2]);});+ it("skips plugins without a matching subscription", () => {+ const calls: number[] = [];+ const app = {+ plugins: [{+ eventBus: {+ has: () => false,+ emit: () => {+ calls.push(1);+ return false;+ },+ },+ }],+ } as unknown as App;++ assert.equal(emitOpenLink(app, {href: "https://example.com", originalHref: "example.com"}), true);+ assert.deepEqual(calls, []);+ });+it("uses the same first-canceler-wins behavior for assets", () => {const calls: number[] = [];const app = createApp([diff --git a/app/src/editor/openLinkEvent.ts b/app/src/editor/openLinkEvent.tsindex e6eb0acfcb..6793e7ee97 100644--- a/app/src/editor/openLinkEvent.ts+++ b/app/src/editor/openLinkEvent.ts@@ -22,6 +22,9 @@ export const resolveOpenLinkEvent = (options: {const emitCancelablePluginEvent = <T>(app: App, type: TEventBus, detail: T) => {for (const plugin of app.plugins) {+ if (!plugin.eventBus.has(type)) {+ continue;+ }if (!plugin.eventBus.emit(type, detail)) {return false;}diff --git a/app/src/editor/util.ts b/app/src/editor/util.tsindex 7b0eb7a250..97e6e0145a 100644--- a/app/src/editor/util.ts+++ b/app/src/editor/util.ts@@ -664,7 +664,9 @@ export const updatePanelByEditor = (options: {}}options.protyle.app.plugins.forEach(item => {- item.eventBus.emit("switch-protyle", {protyle: options.protyle});+ if (item.eventBus.has("switch-protyle")) {+ item.eventBus.emit("switch-protyle", {protyle: options.protyle});+ }});}// 切换页签或关闭所有页签时,需更新对应的面板diff --git a/app/src/index.ts b/app/src/index.tsindex 0f188d8ebd..ed4814be35 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -41,6 +41,7 @@ import "./assets/scss/base.scss";import {reloadEmoji} from "./emoji";import {processIOSPurchaseResponse} from "./util/iOSPurchase";import {updateServerAddresses} from "./config/tabs/accessRuntime";+import {emitToPlugins} from "./plugin/EventBusCore";/// #if !BROWSERimport {ipcRenderer} from "electron";/// #endif@@ -74,9 +75,7 @@ export class App {id: genUUID(),type: "main",msgCallback: (data) => {- this.plugins.forEach((plugin) => {- plugin.eventBus.emit("ws-main", data);- });+ emitToPlugins(this.plugins, "ws-main", data);if (data) {switch (data.cmd) {case "logoutAuth":diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.tsindex e579d4c6bd..44631b1791 100644--- a/app/src/layout/dock/Files.ts+++ b/app/src/layout/dock/Files.ts@@ -27,6 +27,7 @@ import {} from "../../protyle/util/hasClosest";import type {App} from "../../index";import {refreshFileTree} from "../../dialog/processSystem";+import {emitToPlugins} from "../../plugin/EventBusCore";/// #if !BROWSERimport {ipcRenderer} from "electron";/// #endif@@ -1099,9 +1100,7 @@ export class Files extends Model {break;case "mount":this.onMount(data);- this.app.plugins.forEach((item) => {- item.eventBus.emit("opened-notebook", data);- });+ emitToPlugins(this.app.plugins, "opened-notebook", data);break;case "createnotebook":setNoteBook((notebooks) => {@@ -1124,9 +1123,7 @@ export class Files extends Model {case "closeBox":case "removeBox":this.onRemove(data);- this.app.plugins.forEach((item) => {- item.eventBus.emit("closed-notebook", data);- });+ emitToPlugins(this.app.plugins, "closed-notebook", data);break;case "removeDoc":this.onRemove(data);diff --git a/app/src/menus/Menu.ts b/app/src/menus/Menu.tsindex f0038a48c8..f164dccacf 100644--- a/app/src/menus/Menu.ts+++ b/app/src/menus/Menu.ts@@ -475,10 +475,12 @@ export class Menu {return;}window.siyuan.ws?.app?.plugins?.forEach((plugin) => {- plugin.eventBus.emit(type, {- menu: this.element,- ...detail,- });+ if (plugin.eventBus.has(type)) {+ plugin.eventBus.emit(type, {+ menu: this.element,+ ...detail,+ });+ }});}diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.tsindex 8e8af2e241..a44c44f4bc 100644--- a/app/src/mobile/editor.ts+++ b/app/src/mobile/editor.ts@@ -207,7 +207,9 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[updateRecentDocSwitchTime(createRecentDocUpdate(data.data.rootID, previousRootID));}app.plugins.forEach(item => {- item.eventBus.emit("switch-protyle", {protyle: window.siyuan.mobile.editor.protyle});+ if (item.eventBus.has("switch-protyle")) {+ item.eventBus.emit("switch-protyle", {protyle: window.siyuan.mobile.editor.protyle});+ }});complete(window.siyuan.mobile.editor.protyle);}@@ -249,7 +251,9 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[updateRecentDocSwitchTime(createRecentDocUpdate(data.data.rootID, previousRootID));}app.plugins.forEach(item => {- item.eventBus.emit("switch-protyle", {protyle: window.siyuan.mobile.editor.protyle});+ if (item.eventBus.has("switch-protyle")) {+ item.eventBus.emit("switch-protyle", {protyle: window.siyuan.mobile.editor.protyle});+ }});complete(window.siyuan.mobile.editor.protyle);}diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.tsindex 7dd279fdbc..74d9f04fea 100644--- a/app/src/mobile/index.ts+++ b/app/src/mobile/index.ts@@ -42,6 +42,7 @@ import {initRightMenu} from "./menu";import {openChangelog} from "../boot/openChangelog";import {registerServiceWorker} from "../util/serviceWorker";import {loadPlugins} from "../plugin/loader";+import {emitToPlugins} from "../plugin/EventBusCore";import {removeBlock} from "../protyle/wysiwyg/remove";import {isNotEditBlock} from "../protyle/wysiwyg/getBlock";import {updateCardHV} from "../card/util";@@ -75,9 +76,7 @@ class App {id: genUUID(),type: "main",msgCallback: (data) => {- this.plugins.forEach((plugin) => {- plugin.eventBus.emit("ws-main", data);- });+ emitToPlugins(this.plugins, "ws-main", data);onMessage(this, data);}});diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex cf5baaa2a5..6ff50da712 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -856,7 +856,9 @@ export const showKeyboardToolbar = () => {editor.protyle.element.parentElement.style.paddingBottom = "48px";}editor.protyle.app.plugins.forEach(item => {- item.eventBus.emit("mobile-keyboard-show");+ if (item.eventBus.has("mobile-keyboard-show")) {+ item.eventBus.emit("mobile-keyboard-show");+ }});}clearTimeout(scrollSelectionIntoViewTimeout);@@ -936,7 +938,9 @@ export const hideKeyboardToolbar = () => {editor.protyle.element.parentElement.style.paddingBottom = "";if (!toolbarHidden) {editor.protyle.app.plugins.forEach(item => {- item.eventBus.emit("mobile-keyboard-hide");+ if (item.eventBus.has("mobile-keyboard-hide")) {+ item.eventBus.emit("mobile-keyboard-hide");+ }});}}diff --git a/app/src/plugin/EventBus.test.ts b/app/src/plugin/EventBus.test.tsindex 3b4ba3b7da..cc67b9877b 100644--- a/app/src/plugin/EventBus.test.ts+++ b/app/src/plugin/EventBus.test.ts@@ -1,6 +1,6 @@import {describe, it} from "node:test";import * as assert from "node:assert/strict";-import {EventBus} from "./EventBusCore";+import {emitToPlugins, EventBus, hasPluginSubscriber} from "./EventBusCore";describe("plugin EventBus", () => {it("preserves on, once, and off behavior", () => {@@ -24,6 +24,102 @@ describe("plugin EventBus", () => {assert.equal(onceCount, 1);});+ it("tracks listeners and preserves duplicate registration behavior", () => {+ const eventBus = new EventBus("", new EventTarget());+ let callCount = 0;+ const listener = () => {+ callCount++;+ };++ eventBus.on("before-upload-assets", listener);+ eventBus.on("before-upload-assets", listener);+ assert.equal(eventBus.has("before-upload-assets"), true);++ eventBus.emit("before-upload-assets");+ assert.equal(callCount, 1);++ eventBus.off("before-upload-assets", listener);+ assert.equal(eventBus.has("before-upload-assets"), false);+ });++ it("allows off to cancel a pending once listener", () => {+ const eventBus = new EventBus("", new EventTarget());+ let called = false;+ const listener = () => {+ called = true;+ };++ eventBus.once("before-upload-assets", listener);+ eventBus.off("before-upload-assets", listener);+ eventBus.emit("before-upload-assets");++ assert.equal(called, false);+ assert.equal(eventBus.has("before-upload-assets"), false);+ });++ it("runs distinct once listeners independently", () => {+ const eventBus = new EventBus("", new EventTarget());+ const calls: number[] = [];+ eventBus.once("before-upload-assets", () => calls.push(1));+ eventBus.once("before-upload-assets", () => calls.push(2));++ eventBus.emit("before-upload-assets");+ eventBus.emit("before-upload-assets");++ assert.deepEqual(calls, [1, 2]);+ assert.equal(eventBus.has("before-upload-assets"), false);+ });++ it("keeps CustomEvent behavior", () => {+ const eventTarget = new EventTarget();+ const eventBus = new EventBus<{ value: number }>("", eventTarget);+ eventBus.on("before-upload-assets", event => {+ assert.equal(event instanceof CustomEvent, true);+ assert.equal(event.target, eventTarget);+ assert.equal(event.currentTarget, eventTarget);+ assert.equal(event.detail.value, 1);+ event.preventDefault();+ });++ assert.equal(eventBus.emit("before-upload-assets", {value: 1}), false);+ });++ it("destroys listeners permanently", () => {+ const eventBus = new EventBus("", new EventTarget());+ let callCount = 0;+ const listener = () => {+ callCount++;+ };+ eventBus.on("before-upload-assets", listener);++ eventBus.destroy();+ eventBus.destroy();+ eventBus.on("before-upload-assets", listener);++ assert.equal(eventBus.has("before-upload-assets"), false);+ assert.equal(eventBus.emit("before-upload-assets"), true);+ assert.deepEqual(eventBus.emitWithErrors("before-upload-assets"), {+ defaultPrevented: false,+ hasAsyncListener: false,+ });+ assert.equal(callCount, 0);+ });++ it("emits only to subscribers in plugin order", () => {+ const first = new EventBus("", new EventTarget());+ const second = new EventBus("", new EventTarget());+ const third = new EventBus("", new EventTarget());+ const calls: number[] = [];+ first.on("before-upload-assets", () => calls.push(1));+ third.on("before-upload-assets", () => calls.push(3));+ const plugins = [{eventBus: first}, {eventBus: second}, {eventBus: third}];++ assert.equal(hasPluginSubscriber(plugins, "before-upload-assets"), true);+ emitToPlugins(plugins, "before-upload-assets");++ assert.deepEqual(calls, [1, 3]);+ });+it("captures synchronous listener errors during safe dispatch", () => {const eventBus = new EventBus("", new EventTarget());let laterListenerCalled = false;diff --git a/app/src/plugin/EventBus.ts b/app/src/plugin/EventBus.tsindex 9f2fe9a720..21312ad623 100644--- a/app/src/plugin/EventBus.ts+++ b/app/src/plugin/EventBus.ts@@ -1,5 +1,6 @@import {MenuItem, subMenu} from "../menus/Menu";-export {EventBus} from "./EventBusCore";+import {emitToPlugins, hasPluginSubscriber} from "./EventBusCore";+export {emitToPlugins, EventBus, hasPluginSubscriber} from "./EventBusCore";export type {IEventBusSafeEmitResult} from "./EventBusCore";export const emitOpenMenu = (options: {@@ -9,11 +10,12 @@ export const emitOpenMenu = (options: {separatorPosition?: "top" | "bottom",appendToMenu?: boolean,}) => {+ if (!hasPluginSubscriber(options.plugins, options.type)) {+ return [];+ }const pluginSubMenu = new subMenu();options.detail.menu = pluginSubMenu;- options.plugins.forEach((plugin) => {- plugin.eventBus.emit(options.type, options.detail);- });+ emitToPlugins(options.plugins, options.type, options.detail);if (pluginSubMenu.menus.length > 0 && options.appendToMenu !== false) {if (options.separatorPosition === "top") {window.siyuan.menus.menu.append(new MenuItem({id: "separator_pluginTop", type: "separator"}).element);diff --git a/app/src/plugin/EventBusCore.ts b/app/src/plugin/EventBusCore.tsindex 65ae6385e8..2c936643b8 100644--- a/app/src/plugin/EventBusCore.ts+++ b/app/src/plugin/EventBusCore.ts@@ -14,12 +14,17 @@ export class EventBus<DetailType = any> {private eventTarget: EventTarget;private listeners = new Map<TEventBus, Map<(event: CustomEvent<DetailType>) => any, IEventBusListener<DetailType>>>();private safeDispatches = new WeakMap<Event, IEventBusSafeEmitResult>();+ private destroyed = false;constructor(name = "", eventTarget?: EventTarget) {- this.eventTarget = eventTarget || document.appendChild(document.createComment(name));+ void name;+ this.eventTarget = eventTarget || new EventTarget();}private addListener(type: TEventBus, listener: (event: CustomEvent<DetailType>) => any, once: boolean) {+ if (this.destroyed) {+ return;+ }let typeListeners = this.listeners.get(type);if (!typeListeners) {typeListeners = new Map();@@ -73,11 +78,21 @@ export class EventBus<DetailType = any> {}}+ has(type: TEventBus) {+ return !this.destroyed && !!this.listeners.get(type)?.size;+ }+emit(type: TEventBus, detail?: DetailType) {+ if (this.destroyed) {+ return true;+ }return this.eventTarget.dispatchEvent(new CustomEvent(type, {detail, cancelable: true}));}emitWithErrors(type: TEventBus, detail?: DetailType): IEventBusSafeEmitResult {+ if (this.destroyed) {+ return {defaultPrevented: false, hasAsyncListener: false};+ }const event = new CustomEvent(type, {detail, cancelable: true});const result: IEventBusSafeEmitResult = {defaultPrevented: false, hasAsyncListener: false};this.safeDispatches.set(event, result);@@ -89,4 +104,34 @@ export class EventBus<DetailType = any> {result.defaultPrevented = event.defaultPrevented;return result;}++ destroy() {+ if (this.destroyed) {+ return;+ }+ this.destroyed = true;+ this.listeners.forEach((typeListeners, type) => {+ typeListeners.forEach(({wrapped}) => {+ this.eventTarget.removeEventListener(type, wrapped);+ });+ });+ this.listeners.clear();+ this.safeDispatches = new WeakMap();+ }}++type TEventBusOwner = {+ eventBus: EventBus;+};++export const emitToPlugins = (plugins: TEventBusOwner[], type: TEventBus, detail?: any) => {+ Array.from(plugins).forEach((plugin) => {+ if (plugin.eventBus.has(type)) {+ plugin.eventBus.emit(type, detail);+ }+ });+};++export const hasPluginSubscriber = (plugins: TEventBusOwner[], type: TEventBus) => {+ return plugins.some((plugin) => plugin.eventBus.has(type));+};diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.tsindex 0009a725cc..9209ee7815 100644--- a/app/src/plugin/uninstall.ts+++ b/app/src/plugin/uninstall.ts@@ -36,6 +36,9 @@ export const uninstall = (app: App, name: string, isReload: boolean) => {} catch (e) {console.error(`plugin ${plugin.name} uninstall error:`, e);}+ }+ plugin.eventBus.destroy();+ if (!isReload) {window.siyuan.storage[Constants.LOCAL_PLUGIN_DOCKS][plugin.name] = {};setStorageVal(Constants.LOCAL_PLUGIN_DOCKS, window.siyuan.storage[Constants.LOCAL_PLUGIN_DOCKS]);}@@ -83,13 +86,6 @@ export const uninstall = (app: App, name: string, isReload: boolean) => {resizeTopBar();setTabPosition(true);/// #endif- // rm listen- Array.from(document.childNodes).find(item => {- if (item.nodeType === 8 && item.textContent === name) {- item.remove();- return true;- }- });// rm pluginapp.plugins.splice(index, 1);refreshDockCatalog(app.plugins);diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.tsindex 5933ebea51..8360cdf531 100644--- a/app/src/protyle/toolbar/index.ts+++ b/app/src/protyle/toolbar/index.ts@@ -63,6 +63,7 @@ import {closeSubElement} from "./subElementLifecycle";import {getDefaultToolbar, getToolbarEntryId, markPluginToolbarEntries} from "./defaults";import {applyToolbarEntryVisibility} from "../../config/entryVisibility/runtime";import {refreshToolbarCatalog} from "../../config/entryVisibility/catalog";+import {emitToPlugins} from "../../plugin/EventBusCore";const filterPluginToolbar = (toolbar: Array<string | IMenuItem>, lite: boolean) => {if (!lite) {@@ -1614,12 +1615,14 @@ export class Toolbar {textElement.select();}protyle.app.plugins.forEach(item => {- item.eventBus.emit("open-noneditableblock", {- protyle,- toolbar: this,- blockElement: nodeElement,- renderElement,- });+ if (item.eventBus.has("open-noneditableblock")) {+ item.eventBus.emit("open-noneditableblock", {+ protyle,+ toolbar: this,+ blockElement: nodeElement,+ renderElement,+ });+ }});}@@ -1649,9 +1652,7 @@ export class Toolbar {const eventDetail = {languages: hljsLanguages, type: "init", listElement};if (protyle.app && protyle.app.plugins) {- protyle.app.plugins.forEach((plugin: any) => {- plugin.eventBus.emit("code-language-update", eventDetail);- });+ emitToPlugins(protyle.app.plugins, "code-language-update", eventDetail);}hljsLanguages = eventDetail.languages;@@ -1723,9 +1724,7 @@ export class Toolbar {const eventDetail = {languages: value ? matchLanguages : hljsLanguages, type: "match", value, listElement};if (protyle.app && protyle.app.plugins) {- protyle.app.plugins.forEach((plugin: any) => {- plugin.eventBus.emit("code-language-update", eventDetail);- });+ emitToPlugins(protyle.app.plugins, "code-language-update", eventDetail);}matchLanguages = eventDetail.languages;@@ -2303,11 +2302,13 @@ export class Toolbar {if (protyle.app && protyle.app.plugins) {protyle.app.plugins.forEach((plugin: any) => {- plugin.eventBus.emit("code-language-change", {- language: currentLang,- languageElements,- protyle: protyle- });+ if (plugin.eventBus.has("code-language-change")) {+ plugin.eventBus.emit("code-language-change", {+ language: currentLang,+ languageElements,+ protyle: protyle+ });+ }});}diff --git a/app/src/protyle/upload/pluginEvent.ts b/app/src/protyle/upload/pluginEvent.tsindex 0442b74495..8791634739 100644--- a/app/src/protyle/upload/pluginEvent.ts+++ b/app/src/protyle/upload/pluginEvent.ts@@ -26,6 +26,7 @@ export type TPreparedAssetUpload = {interface IAssetUploadPlugin {name?: string;eventBus: {+ has(type: TEventBus): boolean;emitWithErrors(type: TEventBus, detail: IBeforeUploadAssetsDetail): {defaultPrevented: boolean;error?: unknown;@@ -294,7 +295,7 @@ export const prepareAssetUpload = (options: {timeout?: number;}): TPreparedAssetUpload | Promise<TPreparedAssetUpload> => {const task = new AssetUploadTask(options.input, options.requestId || genRequestId(), options.protyle);- const plugins = Array.from(options.plugins);+ const plugins = Array.from(options.plugins).filter(plugin => plugin.eventBus.has("before-upload-assets"));const timeout = options.timeout ?? ASSET_UPLOAD_PLUGIN_TIMEOUT;const context = {...options.context,diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.tsindex b93daf7d4f..3046d976f5 100644--- a/app/src/protyle/util/destroy.ts+++ b/app/src/protyle/util/destroy.ts@@ -42,8 +42,10 @@ export const destroy = (protyle: IProtyle) => {}}protyle.app.plugins.forEach(item => {- item.eventBus.emit("destroy-protyle", {- protyle,- });+ if (item.eventBus.has("destroy-protyle")) {+ item.eventBus.emit("destroy-protyle", {+ protyle,+ });+ }});};diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.tsindex 719601031f..f9c596b3d4 100644--- a/app/src/protyle/util/onGet.ts+++ b/app/src/protyle/util/onGet.ts@@ -386,10 +386,12 @@ const setHTML = (options: {protyle.options.defIds = [];if (options.action.includes(Constants.CB_GET_APPEND) || options.action.includes(Constants.CB_GET_BEFORE)) {protyle.app.plugins.forEach(item => {- item.eventBus.emit("loaded-protyle-dynamic", {- protyle,- position: options.action.includes(Constants.CB_GET_APPEND) ? "afterend" : "beforebegin"- });+ if (item.eventBus.has("loaded-protyle-dynamic")) {+ item.eventBus.emit("loaded-protyle-dynamic", {+ protyle,+ position: options.action.includes(Constants.CB_GET_APPEND) ? "afterend" : "beforebegin"+ });+ }});return;}@@ -440,7 +442,9 @@ const setHTML = (options: {}protyle.app.plugins.forEach(item => {- item.eventBus.emit("loaded-protyle-static", {protyle});+ if (item.eventBus.has("loaded-protyle-static")) {+ item.eventBus.emit("loaded-protyle-static", {protyle});+ }});};diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex d992c73cb2..0f79b5f61e 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -285,9 +285,14 @@ export const restoreLuteMarkdownSyntax = (protyle: IProtyle) => {const readLocalFile = async (protyle: IProtyle, localFiles: ILocalFiles[], options?: IUploadInsertOptions) => {if (protyle && protyle.app && protyle.app.plugins) {- for (let i = 0; i < protyle.app.plugins.length; i++) {+ const plugins = Array.from(protyle.app.plugins);+ for (let i = 0; i < plugins.length; i++) {+ const plugin = plugins[i];+ if (!plugin.eventBus.has("paste")) {+ continue;+ }const response: { localFiles: ILocalFiles[] } = await new Promise((resolve) => {- const emitResult = protyle.app.plugins[i].eventBus.emit("paste", {+ const emitResult = plugin.eventBus.emit("paste", {protyle,resolve,textHTML: "",@@ -657,6 +662,9 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenconst plugins = Array.from(protyle.app.plugins);for (let i = 0; i < plugins.length; i++) {const plugin = plugins[i];+ if (!plugin.eventBus.has("paste")) {+ continue;+ }const response = await new Promise<IClipboardData | undefined | typeof PASTE_PLUGIN_TIMED_OUT>((resolve,reject) => {let settled = false;diff --git a/app/src/protyle/util/setEditMode.ts b/app/src/protyle/util/setEditMode.tsindex e04d055c5d..ea916a2708 100644--- a/app/src/protyle/util/setEditMode.ts+++ b/app/src/protyle/util/setEditMode.ts@@ -58,6 +58,8 @@ export const setEditMode = (protyle: IProtyle, type: TEditorMode) => {/// #endifhideElements(["gutterOnly", "toolbar", "select", "hint", "util"], protyle);protyle.app.plugins.forEach(item => {- item.eventBus.emit("switch-protyle-mode", {protyle});+ if (item.eventBus.has("switch-protyle-mode")) {+ item.eventBus.emit("switch-protyle-mode", {protyle});+ }});};diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 95cd72442e..53467e7098 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -4281,10 +4281,12 @@ export class WYSIWYG {return;}protyle.app.plugins.forEach(item => {- item.eventBus.emit("click-editorcontent", {- protyle,- event- });+ if (item.eventBus.has("click-editorcontent")) {+ item.eventBus.emit("click-editorcontent", {+ protyle,+ event+ });+ }});const templateInteractiveElement = getAVTemplateInteractiveElement(event.target);if (templateInteractiveElement && !isAVTemplateLink(templateInteractiveElement)) {diff --git a/app/src/search/util.ts b/app/src/search/util.tsindex 1411cd6f4c..6d97692b0d 100644--- a/app/src/search/util.ts+++ b/app/src/search/util.ts@@ -41,6 +41,7 @@ import {import {resize} from "../protyle/util/resize";import {addClearButton} from "../util/addClearButton";import {checkFold} from "../util/noRelyPCFunction";+import {emitToPlugins} from "../plugin/EventBusCore";import {getUnRefList, openSearchUnRef, unRefMoreMenu} from "./unRef";import {getDefaultSubType, getDefaultType} from "./getDefault";import {isSupportCSSHL, searchMarkRender} from "../protyle/render/searchMarkRender";@@ -1382,9 +1383,7 @@ const emitBeforeSearchResultsRender = (blocks: IBlock[], edit: Protyle,searchElement,blocks,};- edit.protyle?.app.plugins.forEach((plugin) => {- plugin.eventBus.emit("before-search-results-render", detail);- });+ emitToPlugins(edit.protyle?.app.plugins || [], "before-search-results-render", detail);return detail.blocks;};@@ -1425,11 +1424,13 @@ export const inputEvent = (element: Element, config: Config.IUILayoutTabSearchCoconst previousElement = element.querySelector('[data-type="previous"]');const nextElement = element.querySelector('[data-type="next"]');edit.protyle?.app.plugins.forEach(item => {- item.eventBus.emit("input-search", {- protyle: edit,- config,- searchElement: searchInputElement,- });+ if (item.eventBus.has("input-search")) {+ item.eventBus.emit("input-search", {+ protyle: edit,+ config,+ searchElement: searchInputElement,+ });+ }});const requestConfig = JSON.parse(JSON.stringify(config)) as Config.IUILayoutTabSearchConfig;const requestFocusId = focusId ? Object.assign({}, focusId) : undefined;diff --git a/app/src/util/uri.ts b/app/src/util/uri.tsindex dd7401f422..84a16e2986 100644--- a/app/src/util/uri.ts+++ b/app/src/util/uri.ts@@ -52,12 +52,14 @@ const processSiYuanUriBlocks = (app: App, uriObj: URL): boolean => {/// #endif}app.plugins.forEach(plugin => {- plugin.eventBus.emit("open-siyuan-url-block", {- url: uriObj.href,- id,- focus,- exist: existResponse.data,- });+ if (plugin.eventBus.has("open-siyuan-url-block")) {+ plugin.eventBus.emit("open-siyuan-url-block", {+ url: uriObj.href,+ id,+ focus,+ exist: existResponse.data,+ });+ }});});return true;diff --git a/app/src/window/index.ts b/app/src/window/index.tsindex 3d7f98a160..bc628c3b33 100644--- a/app/src/window/index.ts+++ b/app/src/window/index.ts@@ -35,6 +35,7 @@ import {applyEntryVisibility} from "../config/entryVisibility/runtime";import {removeBlockPanelEditors} from "../block/panelRemoval";import {updateServerAddresses} from "../config/tabs/accessRuntime";import {applyCloudUserState} from "../config/tabs/accountUi";+import {emitToPlugins} from "../plugin/EventBusCore";class App {public plugins: import("../plugin").Plugin[] = [];@@ -49,9 +50,7 @@ class App {id: genUUID(),type: "main",msgCallback: (data) => {- this.plugins.forEach((plugin) => {- plugin.eventBus.emit("ws-main", data);- });+ emitToPlugins(this.plugins, "ws-main", data);if (data) {switch (data.cmd) {case "logoutAuth":