Skip to content

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

:art: Improve plugin event bus subscriber indexing https://github.com/siyuan-note/siyuan/issues/18762

Daniele18520daf9fc
diff --git a/app/src/asset/index.ts b/app/src/asset/index.ts
index 20d2c716e5..b2b6cbec17 100644
--- a/app/src/asset/index.ts
+++ b/app/src/asset/index.ts
@@ -17,6 +17,7 @@ import type {App} from "../index";
import {clearOBG} from "../layout/dock/util";
import {getDisplayName} from "../util/pathName";
import {PdfLoadState} from "./pdfLoadState";
+import {forEachPluginSubscriber} from "../plugin/EventBusCore";
export class Asset extends Model {
public path: string;
@@ -37,10 +38,8 @@ export class Asset extends Model {
this.element.addEventListener("click", (event) => {
clearOBG();
setPanelFocus(this.element.parentElement.parentElement);
- this.app.plugins.forEach(item => {
- if (item.eventBus.has("click-pdf")) {
- item.eventBus.emit("click-pdf", {event});
- }
+ forEachPluginSubscriber("click-pdf", eventBus => {
+ eventBus.emit("click-pdf", {event});
});
});
if (typeof this.pdfId === "string") {
diff --git a/app/src/boot/globalEvent/command/global.ts b/app/src/boot/globalEvent/command/global.ts
index 2bc198dea3..f7a7e16eed 100644
--- a/app/src/boot/globalEvent/command/global.ts
+++ b/app/src/boot/globalEvent/command/global.ts
@@ -439,7 +439,7 @@ export const globalCommand = (command: string, app: App) => {
editorConfigApi.patch("editor.readOnly", !window.siyuan.config.editor.readOnly);
return true;
case "lockScreen":
- lockScreen(app);
+ lockScreen();
return true;
case "newFile":
newFile(app);
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 69afa97dfa..911594c16b 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -1441,7 +1441,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
return;
}
if (matchHotKey(window.siyuan.config.keymap.general.lockScreen.custom, event)) {
- lockScreen(app);
+ lockScreen();
event.preventDefault();
return;
}
diff --git a/app/src/boot/onGetConfig.ts b/app/src/boot/onGetConfig.ts
index 614074d92d..476665efe4 100644
--- a/app/src/boot/onGetConfig.ts
+++ b/app/src/boot/onGetConfig.ts
@@ -203,7 +203,7 @@ export const initWindow = async (app: App) => {
}
});
ipcRenderer.on(Constants.SIYUAN_SEND_WINDOWS, (e, ipcData: IWebSocketData) => {
- onWindowsMsg(ipcData, app);
+ onWindowsMsg(ipcData);
});
ipcRenderer.on(Constants.SIYUAN_HOTKEY, (e, data) => {
let matchCommand = false;
diff --git a/app/src/card/openCard.ts b/app/src/card/openCard.ts
index 727b496be7..4c25b7b74f 100644
--- a/app/src/card/openCard.ts
+++ b/app/src/card/openCard.ts
@@ -36,6 +36,7 @@ import {
showFlashcardAnswer
} from "./flashcardMode";
import {setFold} from "../protyle/util/blockFold";
+import {forEachPluginSubscriber} from "../plugin/EventBusCore";
const genCardCount = (cardsData: ICardData, allIndex = 0) => {
let newIndex = 0;
@@ -719,7 +720,7 @@ export const bindCardEvent = async (options: {
} else {
revealFlashcardAnswer(editor.protyle, () => {
showRatingActions(actionElements, currentCard);
- emitEvent(options.app, currentCard, type);
+ emitEvent(currentCard, type);
});
const currentRevealState = getFlashcardRevealState(editor.protyle);
if (currentRevealState.pendingGeneration === currentRevealState.generation) {
@@ -739,7 +740,7 @@ export const bindCardEvent = async (options: {
index,
cardsData: options.cardsData
});
- emitEvent(options.app, options.cardsData.cards[index + 1], type);
+ emitEvent(options.cardsData.cards[index + 1], type);
}
return;
}
@@ -768,7 +769,7 @@ export const bindCardEvent = async (options: {
notebook: docId,
reviewedCards: options.cardsData.cards
}, async (result) => {
- emitEvent(options.app, options.cardsData.cards[index - 1], type);
+ emitEvent(options.cardsData.cards[index - 1], type);
index = 0;
options.cardsData = result.data;
for (let i = 0; i < options.app.plugins.length; i++) {
@@ -799,21 +800,19 @@ export const bindCardEvent = async (options: {
index,
cardsData: options.cardsData
});
- emitEvent(options.app, options.cardsData.cards[index - 1], type);
+ emitEvent(options.cardsData.cards[index - 1], type);
});
}
});
return editor;
};
-const emitEvent = (app: App, card: ICard, type: string) => {
- app.plugins.forEach(item => {
- if (item.eventBus.has("click-flashcard-action")) {
- item.eventBus.emit("click-flashcard-action", {
- type,
- card
- });
- }
+const emitEvent = (card: ICard, type: string) => {
+ forEachPluginSubscriber("click-flashcard-action", eventBus => {
+ eventBus.emit("click-flashcard-action", {
+ type,
+ card
+ });
});
};
diff --git a/app/src/dialog/processSystem.ts b/app/src/dialog/processSystem.ts
index 81a4e0da52..dff37fe7f4 100644
--- a/app/src/dialog/processSystem.ts
+++ b/app/src/dialog/processSystem.ts
@@ -16,10 +16,8 @@ import {confirmDialog} from "./confirmDialog";
import {escapeHtml} from "../util/escape";
import {needSubscribe} from "../util/needSubscribe";
import {hideAllElements} from "../protyle/ui/hideElements";
-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: {
@@ -122,11 +120,11 @@ export const setDefRefCount = (data: {
}
};
-export const lockScreen = async (app: App) => {
+export const lockScreen = async () => {
if (window.siyuan.config.readonly || window.siyuan.isPublish) {
return;
}
- emitToPlugins(app.plugins, "lock-screen");
+ emitToPlugins("lock-screen");
/// #if !MOBILE
exportLayout({
errorExit: false,
@@ -453,7 +451,7 @@ export const downloadProgress = (data: { id: string, percent: number }) => {
}
};
-export const processSync = (data?: IWebSocketData, plugins?: Plugin[]) => {
+export const processSync = (data?: IWebSocketData) => {
if (data?.code === 1) {
window.dispatchEvent(new CustomEvent("siyuan-sync-success"));
}
@@ -513,10 +511,10 @@ export const processSync = (data?: IWebSocketData, plugins?: Plugin[]) => {
}
/// #endif
if (data.code === 0) {
- emitToPlugins(plugins, "sync-start", data);
+ emitToPlugins("sync-start", data);
} else if (data.code === 1) {
- emitToPlugins(plugins, "sync-end", data);
+ emitToPlugins("sync-end", data);
} else if (data.code === 2) {
- emitToPlugins(plugins, "sync-fail", data);
+ emitToPlugins("sync-fail", data);
}
};
diff --git a/app/src/dialog/tooltip.ts b/app/src/dialog/tooltip.ts
index 7ccad9cdc2..df3f5e1ee5 100644
--- a/app/src/dialog/tooltip.ts
+++ b/app/src/dialog/tooltip.ts
@@ -1,5 +1,5 @@
import {isMobile} from "../util/functions";
-import {emitToPlugins} from "../plugin/EventBusCore";
+import {emitToPlugins, forEachPluginSubscriber} from "../plugin/EventBusCore";
export const showTooltip = (
message: string,
@@ -18,7 +18,7 @@ export const showTooltip = (
target,
tooltipElement: messageElement,
};
- emitToPlugins(window.siyuan.ws.app.plugins, "before-show-tooltip", showDetail);
+ emitToPlugins("before-show-tooltip", showDetail);
message = showDetail.message;
if (!message) {
hideTooltip();
@@ -150,12 +150,10 @@ export const hideTooltip = () => {
if (messageElement.classList.contains("fn__none")) {
return;
}
- window.siyuan.ws.app.plugins.forEach(plugin => {
- if (plugin.eventBus.has("before-hide-tooltip")) {
- plugin.eventBus.emit("before-hide-tooltip", {
- tooltipElement: messageElement,
- });
- }
+ forEachPluginSubscriber("before-hide-tooltip", eventBus => {
+ eventBus.emit("before-hide-tooltip", {
+ tooltipElement: messageElement,
+ });
});
messageElement.classList.add("fn__none");
};
diff --git a/app/src/editor/util.ts b/app/src/editor/util.ts
index 97e6e0145a..b2d9708017 100644
--- a/app/src/editor/util.ts
+++ b/app/src/editor/util.ts
@@ -35,6 +35,7 @@ import {clearOBG} from "../layout/dock/util";
import {Model} from "../layout/Model";
import {hideElements} from "../protyle/ui/hideElements";
import {isBrowserRenderableImagePath} from "../util/imageURL";
+import {forEachPluginSubscriber} from "../plugin/EventBusCore";
const isSameCustomTab = (type: string, data: any, options: IOpenFileOptions) => {
if (!options.custom || (options.custom.id && options.custom.id !== type)) {
@@ -663,10 +664,8 @@ export const updatePanelByEditor = (options: {
}
}
}
- options.protyle.app.plugins.forEach(item => {
- if (item.eventBus.has("switch-protyle")) {
- item.eventBus.emit("switch-protyle", {protyle: options.protyle});
- }
+ forEachPluginSubscriber("switch-protyle", eventBus => {
+ eventBus.emit("switch-protyle", {protyle: options.protyle});
});
}
// 切换页签或关闭所有页签时,需更新对应的面板
diff --git a/app/src/index.ts b/app/src/index.ts
index ed4814be35..e870715cd7 100644
--- a/app/src/index.ts
+++ b/app/src/index.ts
@@ -75,7 +75,7 @@ export class App {
id: genUUID(),
type: "main",
msgCallback: (data) => {
- emitToPlugins(this.plugins, "ws-main", data);
+ emitToPlugins("ws-main", data);
if (data) {
switch (data.cmd) {
case "logoutAuth":
@@ -225,7 +225,7 @@ export class App {
transactionError(data.msg);
break;
case "syncing":
- processSync(data, this.plugins);
+ processSync(data);
break;
case "backgroundtask":
progressBackgroundTask(data.data.tasks);
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index 44631b1791..bc2495accf 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -1100,7 +1100,7 @@ export class Files extends Model {
break;
case "mount":
this.onMount(data);
- emitToPlugins(this.app.plugins, "opened-notebook", data);
+ emitToPlugins("opened-notebook", data);
break;
case "createnotebook":
setNoteBook((notebooks) => {
@@ -1123,7 +1123,7 @@ export class Files extends Model {
case "closeBox":
case "removeBox":
this.onRemove(data);
- emitToPlugins(this.app.plugins, "closed-notebook", data);
+ emitToPlugins("closed-notebook", data);
break;
case "removeDoc":
this.onRemove(data);
diff --git a/app/src/layout/dock/Inbox.ts b/app/src/layout/dock/Inbox.ts
index 457a756687..fefb48c590 100644
--- a/app/src/layout/dock/Inbox.ts
+++ b/app/src/layout/dock/Inbox.ts
@@ -293,7 +293,6 @@ ${data.shorthandContent}
}
if (this.app.plugins) {
emitOpenMenu({
- plugins: this.app.plugins,
type: "open-menu-inbox",
detail: {
ids,
diff --git a/app/src/menus/Menu.ts b/app/src/menus/Menu.ts
index f164dccacf..45222e73cf 100644
--- a/app/src/menus/Menu.ts
+++ b/app/src/menus/Menu.ts
@@ -7,6 +7,7 @@ import {getTopBarHeight} from "../layout/getTopBarHeight";
import {electronUndo} from "../protyle/undo";
import {escapeAttr} from "../util/escape";
import {setMenuInputCurrent} from "./menuKeyboard";
+import {forEachPluginSubscriber} from "../plugin/EventBusCore";
/// #if !MOBILE
import {applyMenuEntryVisibility} from "../config/entryVisibility/runtime";
/// #endif
@@ -474,13 +475,11 @@ export class Menu {
if (this.element.id !== "commonMenu") {
return;
}
- window.siyuan.ws?.app?.plugins?.forEach((plugin) => {
- if (plugin.eventBus.has(type)) {
- plugin.eventBus.emit(type, {
- menu: this.element,
- ...detail,
- });
- }
+ forEachPluginSubscriber(type, eventBus => {
+ eventBus.emit(type, {
+ menu: this.element,
+ ...detail,
+ });
});
}
diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.ts
index 1f77520b1b..1085fd62cc 100644
--- a/app/src/menus/navigation.ts
+++ b/app/src/menus/navigation.ts
@@ -209,7 +209,6 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>
}).element);
if (app.plugins) {
emitOpenMenu({
- plugins: app.plugins,
type: "open-menu-doctree",
detail: {elements: selectItemElements, type: "notebooks", items},
separatorPosition: "top",
@@ -230,7 +229,6 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>
}).element);
if (app.plugins) {
emitOpenMenu({
- plugins: app.plugins,
type: "open-menu-doctree",
detail: {elements: selectItemElements, type: "items", items},
separatorPosition: "top",
@@ -373,7 +371,6 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>
}).element);
if (app.plugins) {
emitOpenMenu({
- plugins: app.plugins,
type: "open-menu-doctree",
detail: {
elements: selectItemElements,
@@ -652,7 +649,6 @@ export const initNavigationMenu = (app: App, liElement: HTMLElement) => {
}).element);
if (app.plugins) {
emitOpenMenu({
- plugins: app.plugins,
type: "open-menu-doctree",
detail: {
elements: selectItemElements,
@@ -995,7 +991,6 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
window.siyuan.menus.menu.append(exportMd(id));
if (app.plugins) {
emitOpenMenu({
- plugins: app.plugins,
type: "open-menu-doctree",
detail: {
elements: selectItemElements,
diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.ts
index b8d4b76cfa..79a71b3c86 100644
--- a/app/src/menus/protyle.ts
+++ b/app/src/menus/protyle.ts
@@ -321,7 +321,6 @@ export const fileAnnotationRefMenu = (protyle: IProtyle, refElement: HTMLElement
if (protyle?.app?.plugins) {
emitOpenMenu({
- plugins: protyle.app.plugins,
type: "open-menu-fileannotationref",
detail: {
protyle,
@@ -679,7 +678,6 @@ export const refMenu = (protyle: IProtyle, element: HTMLElement) => {
}
if (protyle?.app?.plugins) {
emitOpenMenu({
- plugins: protyle.app.plugins,
type: "open-menu-blockref",
detail: {
protyle,
@@ -927,7 +925,6 @@ export const contentMenu = (protyle: IProtyle, nodeElement: Element) => {
let pluginMenus: IMenu[] = [];
if (protyle?.app?.plugins) {
pluginMenus = emitOpenMenu({
- plugins: protyle.app.plugins,
type: "open-menu-content",
detail: {
protyle,
@@ -1488,7 +1485,6 @@ export const imgMenu = (protyle: IProtyle, range: Range, assetElement: HTMLEleme
}).element);
if (protyle?.app?.plugins) {
emitOpenMenu({
- plugins: protyle.app.plugins,
type: "open-menu-image",
detail: {
protyle,
@@ -1768,7 +1764,6 @@ style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"}" class="b3-text-fiel
if (!protyle.disabled && protyle?.app?.plugins) {
emitOpenMenu({
- plugins: protyle.app.plugins,
type: "open-menu-link",
detail: {
protyle,
@@ -1987,7 +1982,6 @@ export const tagMenu = (protyle: IProtyle, tagElement: HTMLElement) => {
if (protyle?.app?.plugins) {
emitOpenMenu({
- plugins: protyle.app.plugins,
type: "open-menu-tag",
detail: {
protyle,
diff --git a/app/src/menus/workspace.ts b/app/src/menus/workspace.ts
index 61b8a452ac..6a9e9f77ab 100644
--- a/app/src/menus/workspace.ts
+++ b/app/src/menus/workspace.ts
@@ -529,7 +529,7 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {
icon: "iconLock",
accelerator: window.siyuan.config.keymap.general.lockScreen.custom,
click: () => {
- lockScreen(app);
+ lockScreen();
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.ts
index a44c44f4bc..fb6f19093b 100644
--- a/app/src/mobile/editor.ts
+++ b/app/src/mobile/editor.ts
@@ -16,6 +16,7 @@ import {initMirror} from "../protyle/undo/globalUndo";
import {getDocByScroll, saveScroll} from "../protyle/scroll/saveScroll";
import {isEncryptedBox} from "../util/pathName";
import {bindMobileBarsScroll, pauseMobileBarsScroll} from "./util/mobileBars";
+import {forEachPluginSubscriber} from "../plugin/EventBusCore";
export const getCurrentEditor = () => {
return window.siyuan.mobile.popEditor || window.siyuan.mobile.editor;
@@ -206,10 +207,8 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[
if (updateRecent) {
updateRecentDocSwitchTime(createRecentDocUpdate(data.data.rootID, previousRootID));
}
- app.plugins.forEach(item => {
- if (item.eventBus.has("switch-protyle")) {
- item.eventBus.emit("switch-protyle", {protyle: window.siyuan.mobile.editor.protyle});
- }
+ forEachPluginSubscriber("switch-protyle", eventBus => {
+ eventBus.emit("switch-protyle", {protyle: window.siyuan.mobile.editor.protyle});
});
complete(window.siyuan.mobile.editor.protyle);
}
@@ -250,10 +249,8 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[
if (updateRecent) {
updateRecentDocSwitchTime(createRecentDocUpdate(data.data.rootID, previousRootID));
}
- app.plugins.forEach(item => {
- if (item.eventBus.has("switch-protyle")) {
- item.eventBus.emit("switch-protyle", {protyle: window.siyuan.mobile.editor.protyle});
- }
+ forEachPluginSubscriber("switch-protyle", eventBus => {
+ 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.ts
index 74d9f04fea..e2ad4dfb67 100644
--- a/app/src/mobile/index.ts
+++ b/app/src/mobile/index.ts
@@ -76,7 +76,7 @@ class App {
id: genUUID(),
type: "main",
msgCallback: (data) => {
- emitToPlugins(this.plugins, "ws-main", data);
+ emitToPlugins("ws-main", data);
onMessage(this, data);
}
});
@@ -281,7 +281,7 @@ window.reconnectWebSocket = () => {
};
window.lockscreenByMode = () => {
if (window.siyuan.config?.system.lockScreenMode === 1) {
- lockScreen(siyuanApp);
+ lockScreen();
}
};
window.goBack = goBack;
diff --git a/app/src/mobile/menu/index.ts b/app/src/mobile/menu/index.ts
index 7184505bf1..631da6fc94 100644
--- a/app/src/mobile/menu/index.ts
+++ b/app/src/mobile/menu/index.ts
@@ -647,7 +647,7 @@ export const initRightMenu = (app: App) => {
event.stopPropagation();
break;
} else if (target.id === "menuLock") {
- lockScreen(app);
+ lockScreen();
event.preventDefault();
event.stopPropagation();
break;
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 6ff50da712..2a1dcefd76 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -37,6 +37,7 @@ import {
TInlineStyleType,
} from "../../protyle/toolbar/inlineStyle";
import {openInlineStyleDialog} from "../../protyle/toolbar/inlineStyleDialog";
+import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
import {
getKeyboardHideResult,
getMovingSelectionEndpoint,
@@ -855,10 +856,8 @@ export const showKeyboardToolbar = () => {
if (editor.protyle.wysiwyg.element.contains(range.startContainer)) {
editor.protyle.element.parentElement.style.paddingBottom = "48px";
}
- editor.protyle.app.plugins.forEach(item => {
- if (item.eventBus.has("mobile-keyboard-show")) {
- item.eventBus.emit("mobile-keyboard-show");
- }
+ forEachPluginSubscriber("mobile-keyboard-show", eventBus => {
+ eventBus.emit("mobile-keyboard-show");
});
}
clearTimeout(scrollSelectionIntoViewTimeout);
@@ -937,10 +936,8 @@ export const hideKeyboardToolbar = () => {
if (editor) {
editor.protyle.element.parentElement.style.paddingBottom = "";
if (!toolbarHidden) {
- editor.protyle.app.plugins.forEach(item => {
- if (item.eventBus.has("mobile-keyboard-hide")) {
- item.eventBus.emit("mobile-keyboard-hide");
- }
+ forEachPluginSubscriber("mobile-keyboard-hide", eventBus => {
+ eventBus.emit("mobile-keyboard-hide");
});
}
}
diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.ts
index 04e559203d..6cc585bbe6 100644
--- a/app/src/mobile/util/onMessage.ts
+++ b/app/src/mobile/util/onMessage.ts
@@ -153,7 +153,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {
progressLoading(data);
break;
case"syncing":
- processSync(data, app.plugins);
+ processSync(data);
if (data.code === 1) {
document.getElementById("toolbarSync").classList.add("fn__none");
}
diff --git a/app/src/plugin/EventBus.test.ts b/app/src/plugin/EventBus.test.ts
index cc67b9877b..5abf67f095 100644
--- a/app/src/plugin/EventBus.test.ts
+++ b/app/src/plugin/EventBus.test.ts
@@ -14,6 +14,7 @@ describe("plugin EventBus", () => {
eventBus.once("before-upload-assets", () => {
onceCount++;
});
+ assert.equal(hasPluginSubscriber("before-upload-assets"), true);
eventBus.emit("before-upload-assets", {value: 1});
eventBus.emit("before-upload-assets", {value: 1});
@@ -22,6 +23,7 @@ describe("plugin EventBus", () => {
assert.equal(persistentCount, 2);
assert.equal(onceCount, 1);
+ assert.equal(hasPluginSubscriber("before-upload-assets"), false);
});
it("tracks listeners and preserves duplicate registration behavior", () => {
@@ -82,6 +84,7 @@ describe("plugin EventBus", () => {
});
assert.equal(eventBus.emit("before-upload-assets", {value: 1}), false);
+ eventBus.destroy();
});
it("destroys listeners permanently", () => {
@@ -110,14 +113,47 @@ describe("plugin EventBus", () => {
const second = new EventBus("", new EventTarget());
const third = new EventBus("", new EventTarget());
const calls: number[] = [];
- first.on("before-upload-assets", () => calls.push(1));
+ const firstListener = () => calls.push(1);
third.on("before-upload-assets", () => calls.push(3));
- const plugins = [{eventBus: first}, {eventBus: second}, {eventBus: third}];
+ first.on("before-upload-assets", firstListener);
+
+ assert.equal(hasPluginSubscriber("before-upload-assets"), true);
+ emitToPlugins("before-upload-assets");
+ assert.deepEqual(calls, [1, 3]);
- assert.equal(hasPluginSubscriber(plugins, "before-upload-assets"), true);
- emitToPlugins(plugins, "before-upload-assets");
+ calls.length = 0;
+ first.off("before-upload-assets", firstListener);
+ first.on("before-upload-assets", firstListener);
+ emitToPlugins("before-upload-assets");
assert.deepEqual(calls, [1, 3]);
+ first.destroy();
+ second.destroy();
+ third.destroy();
+ assert.equal(hasPluginSubscriber("before-upload-assets"), false);
+ });
+
+ it("uses a subscriber snapshot during broadcast", () => {
+ const first = new EventBus("", new EventTarget());
+ const second = new EventBus("", new EventTarget());
+ const third = new EventBus("", new EventTarget());
+ const calls: number[] = [];
+ const thirdListener = () => calls.push(3);
+ first.on("before-upload-assets", () => {
+ calls.push(1);
+ third.on("before-upload-assets", thirdListener);
+ });
+ second.on("before-upload-assets", () => calls.push(2));
+
+ emitToPlugins("before-upload-assets");
+ assert.deepEqual(calls, [1, 2]);
+
+ emitToPlugins("before-upload-assets");
+ assert.deepEqual(calls, [1, 2, 1, 2, 3]);
+
+ first.destroy();
+ second.destroy();
+ third.destroy();
});
it("captures synchronous listener errors during safe dispatch", () => {
@@ -134,6 +170,7 @@ describe("plugin EventBus", () => {
assert.equal((result.error as Error).message, "listener failed");
assert.equal(laterListenerCalled, false);
+ eventBus.destroy();
});
it("reports prevention and asynchronous listeners during safe dispatch", async () => {
@@ -148,5 +185,6 @@ describe("plugin EventBus", () => {
assert.equal(result.defaultPrevented, true);
assert.equal(result.hasAsyncListener, true);
+ eventBus.destroy();
});
});
diff --git a/app/src/plugin/EventBus.ts b/app/src/plugin/EventBus.ts
index 21312ad623..e3793e69f6 100644
--- a/app/src/plugin/EventBus.ts
+++ b/app/src/plugin/EventBus.ts
@@ -4,18 +4,17 @@ export {emitToPlugins, EventBus, hasPluginSubscriber} from "./EventBusCore";
export type {IEventBusSafeEmitResult} from "./EventBusCore";
export const emitOpenMenu = (options: {
- plugins: import("./index").Plugin[],
type: TEventBus,
detail: any,
separatorPosition?: "top" | "bottom",
appendToMenu?: boolean,
}) => {
- if (!hasPluginSubscriber(options.plugins, options.type)) {
+ if (!hasPluginSubscriber(options.type)) {
return [];
}
const pluginSubMenu = new subMenu();
options.detail.menu = pluginSubMenu;
- emitToPlugins(options.plugins, options.type, options.detail);
+ emitToPlugins(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.ts
index 2c936643b8..644f8f5f06 100644
--- a/app/src/plugin/EventBusCore.ts
+++ b/app/src/plugin/EventBusCore.ts
@@ -10,11 +10,15 @@ export interface IEventBusSafeEmitResult {
hasAsyncListener: boolean;
}
+const subscribers = new Map<TEventBus, EventBus[]>();
+let eventBusOrder = 0;
+
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;
+ private readonly order = eventBusOrder++;
constructor(name = "", eventTarget?: EventTarget) {
void name;
@@ -55,6 +59,37 @@ export class EventBus<DetailType = any> {
};
typeListeners.set(listener, {listener, wrapped, once});
this.eventTarget.addEventListener(type, wrapped);
+ if (typeListeners.size === 1) {
+ this.addSubscriber(type);
+ }
+ }
+
+ private addSubscriber(type: TEventBus) {
+ let typeSubscribers = subscribers.get(type);
+ if (!typeSubscribers) {
+ typeSubscribers = [];
+ subscribers.set(type, typeSubscribers);
+ }
+ const index = typeSubscribers.findIndex(eventBus => eventBus.order > this.order);
+ if (index === -1) {
+ typeSubscribers.push(this);
+ } else {
+ typeSubscribers.splice(index, 0, this);
+ }
+ }
+
+ private removeSubscriber(type: TEventBus) {
+ const typeSubscribers = subscribers.get(type);
+ if (!typeSubscribers) {
+ return;
+ }
+ const index = typeSubscribers.indexOf(this);
+ if (index > -1) {
+ typeSubscribers.splice(index, 1);
+ }
+ if (typeSubscribers.length === 0) {
+ subscribers.delete(type);
+ }
}
on(type: TEventBus, listener: (event: CustomEvent<DetailType>) => any) {
@@ -75,6 +110,7 @@ export class EventBus<DetailType = any> {
typeListeners.delete(listener);
if (typeListeners.size === 0) {
this.listeners.delete(type);
+ this.removeSubscriber(type);
}
}
@@ -114,24 +150,27 @@ export class EventBus<DetailType = any> {
typeListeners.forEach(({wrapped}) => {
this.eventTarget.removeEventListener(type, wrapped);
});
+ this.removeSubscriber(type);
});
this.listeners.clear();
this.safeDispatches = new WeakMap();
}
}
-type TEventBusOwner = {
- eventBus: EventBus;
+export const forEachPluginSubscriber = (type: TEventBus, callback: (eventBus: EventBus) => void) => {
+ const typeSubscribers = subscribers.get(type);
+ if (!typeSubscribers) {
+ return;
+ }
+ Array.from(typeSubscribers).forEach(callback);
};
-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 emitToPlugins = (type: TEventBus, detail?: any) => {
+ forEachPluginSubscriber(type, eventBus => {
+ eventBus.emit(type, detail);
});
};
-export const hasPluginSubscriber = (plugins: TEventBusOwner[], type: TEventBus) => {
- return plugins.some((plugin) => plugin.eventBus.has(type));
+export const hasPluginSubscriber = (type: TEventBus) => {
+ return !!subscribers.get(type)?.length;
};
diff --git a/app/src/protyle/breadcrumb/index.ts b/app/src/protyle/breadcrumb/index.ts
index 76306a1f2c..0f0a5dffcb 100644
--- a/app/src/protyle/breadcrumb/index.ts
+++ b/app/src/protyle/breadcrumb/index.ts
@@ -1043,7 +1043,6 @@ ${padHTML}
/// #endif
if (protyle?.app?.plugins) {
emitOpenMenu({
- plugins: protyle.app.plugins,
type: "open-menu-breadcrumbmore",
detail: {
protyle,
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index 49b910ca3f..6131d1ebe5 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -1513,7 +1513,6 @@ export class Gutter {
if (protyle?.app?.plugins) {
emitOpenMenu({
- plugins: protyle.app.plugins,
type: "click-blockicon",
detail: {
protyle,
@@ -2861,7 +2860,6 @@ export class Gutter {
if (!isEmbedMenu && protyle?.app?.plugins) {
emitOpenMenu({
- plugins: protyle.app.plugins,
type: "click-blockicon",
detail: {
protyle,
diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.ts
index 3633ded8a1..6ef8f33611 100644
--- a/app/src/protyle/header/openTitleMenu.ts
+++ b/app/src/protyle/header/openTitleMenu.ts
@@ -346,7 +346,6 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: stri
window.siyuan.menus.menu.append(new MenuItem({id: "separator_4", type: "separator"}).element);
if (protyle?.app?.plugins) {
emitOpenMenu({
- plugins: protyle.app.plugins,
type: "click-editortitleicon",
detail: {
protyle,
diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.ts
index d6ba7977d1..b3a6b9cfcf 100644
--- a/app/src/protyle/render/av/action.ts
+++ b/app/src/protyle/render/av/action.ts
@@ -1216,7 +1216,6 @@ ${window.siyuan.languages[avType === "table" ? "insertRowAfter" : "insertItemAft
}
if (protyle?.app?.plugins) {
emitOpenMenu({
- plugins: protyle.app.plugins,
type: "open-menu-av",
detail: {
protyle,
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index 8360cdf531..02fc73856c 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -63,7 +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";
+import {emitToPlugins, forEachPluginSubscriber} from "../../plugin/EventBusCore";
const filterPluginToolbar = (toolbar: Array<string | IMenuItem>, lite: boolean) => {
if (!lite) {
@@ -1614,15 +1614,13 @@ export class Toolbar {
if (!protyle.disabled) {
textElement.select();
}
- protyle.app.plugins.forEach(item => {
- if (item.eventBus.has("open-noneditableblock")) {
- item.eventBus.emit("open-noneditableblock", {
- protyle,
- toolbar: this,
- blockElement: nodeElement,
- renderElement,
- });
- }
+ forEachPluginSubscriber("open-noneditableblock", eventBus => {
+ eventBus.emit("open-noneditableblock", {
+ protyle,
+ toolbar: this,
+ blockElement: nodeElement,
+ renderElement,
+ });
});
}
@@ -1652,7 +1650,7 @@ export class Toolbar {
const eventDetail = {languages: hljsLanguages, type: "init", listElement};
if (protyle.app && protyle.app.plugins) {
- emitToPlugins(protyle.app.plugins, "code-language-update", eventDetail);
+ emitToPlugins("code-language-update", eventDetail);
}
hljsLanguages = eventDetail.languages;
@@ -1724,7 +1722,7 @@ export class Toolbar {
const eventDetail = {languages: value ? matchLanguages : hljsLanguages, type: "match", value, listElement};
if (protyle.app && protyle.app.plugins) {
- emitToPlugins(protyle.app.plugins, "code-language-update", eventDetail);
+ emitToPlugins("code-language-update", eventDetail);
}
matchLanguages = eventDetail.languages;
@@ -2301,14 +2299,12 @@ export class Toolbar {
const currentLang = selectedLang === window.siyuan.languages.clear ? "" : selectedLang;
if (protyle.app && protyle.app.plugins) {
- protyle.app.plugins.forEach((plugin: any) => {
- if (plugin.eventBus.has("code-language-change")) {
- plugin.eventBus.emit("code-language-change", {
- language: currentLang,
- languageElements,
- protyle: protyle
- });
- }
+ forEachPluginSubscriber("code-language-change", eventBus => {
+ eventBus.emit("code-language-change", {
+ language: currentLang,
+ languageElements,
+ protyle: protyle
+ });
});
}
diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.ts
index 3046d976f5..6144488cd2 100644
--- a/app/src/protyle/util/destroy.ts
+++ b/app/src/protyle/util/destroy.ts
@@ -3,6 +3,7 @@ import {isSupportCSSHL} from "../render/searchMarkRender";
import {destroyAIEditor} from "../../ai/editor";
import {cancelAssetUploads} from "../upload/pluginEvent";
import {unmountBreadcrumbButtons} from "../../plugin/breadcrumbButton";
+import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
export const destroy = (protyle: IProtyle) => {
if (!protyle) {
@@ -41,11 +42,9 @@ export const destroy = (protyle: IProtyle) => {
}, 10240);
}
}
- protyle.app.plugins.forEach(item => {
- if (item.eventBus.has("destroy-protyle")) {
- item.eventBus.emit("destroy-protyle", {
- protyle,
- });
- }
+ forEachPluginSubscriber("destroy-protyle", eventBus => {
+ eventBus.emit("destroy-protyle", {
+ protyle,
+ });
});
};
diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.ts
index f9c596b3d4..d6ad13b9ee 100644
--- a/app/src/protyle/util/onGet.ts
+++ b/app/src/protyle/util/onGet.ts
@@ -33,6 +33,7 @@ import {updateWidgetCacheVersion} from "./widgetCache";
import {normalizeHTMLAssetIFrameSources} from "../../asset/html";
import {hasFocusOffsets} from "./focusRestore";
import {isIPhone} from "./compatibility";
+import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
/// #if MOBILE
import {updateMobileTitleReadonly} from "./setEditMode";
/// #endif
@@ -385,13 +386,11 @@ 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 => {
- if (item.eventBus.has("loaded-protyle-dynamic")) {
- item.eventBus.emit("loaded-protyle-dynamic", {
- protyle,
- position: options.action.includes(Constants.CB_GET_APPEND) ? "afterend" : "beforebegin"
- });
- }
+ forEachPluginSubscriber("loaded-protyle-dynamic", eventBus => {
+ eventBus.emit("loaded-protyle-dynamic", {
+ protyle,
+ position: options.action.includes(Constants.CB_GET_APPEND) ? "afterend" : "beforebegin"
+ });
});
return;
}
@@ -441,10 +440,8 @@ const setHTML = (options: {
}
}
- protyle.app.plugins.forEach(item => {
- if (item.eventBus.has("loaded-protyle-static")) {
- item.eventBus.emit("loaded-protyle-static", {protyle});
- }
+ forEachPluginSubscriber("loaded-protyle-static", eventBus => {
+ eventBus.emit("loaded-protyle-static", {protyle});
});
};
diff --git a/app/src/protyle/util/setEditMode.ts b/app/src/protyle/util/setEditMode.ts
index ea916a2708..f11687ffc1 100644
--- a/app/src/protyle/util/setEditMode.ts
+++ b/app/src/protyle/util/setEditMode.ts
@@ -2,6 +2,7 @@ import {hideElements} from "../ui/hideElements";
import {getAllModels} from "../../layout/getAll";
import {updateOutline} from "../../editor/util";
import {resize} from "./resize";
+import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
/// #if MOBILE
export const updateMobileTitleReadonly = (protyle: IProtyle) => {
@@ -57,9 +58,7 @@ export const setEditMode = (protyle: IProtyle, type: TEditorMode) => {
updateMobileTitleReadonly(protyle);
/// #endif
hideElements(["gutterOnly", "toolbar", "select", "hint", "util"], protyle);
- protyle.app.plugins.forEach(item => {
- if (item.eventBus.has("switch-protyle-mode")) {
- item.eventBus.emit("switch-protyle-mode", {protyle});
- }
+ forEachPluginSubscriber("switch-protyle-mode", eventBus => {
+ eventBus.emit("switch-protyle-mode", {protyle});
});
};
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index 53467e7098..ca6a52632e 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -197,6 +197,7 @@ import {formatPainter} from "../toolbar/FormatPainter";
import {shouldOpenListItemAttr} from "./listContext";
import {getBlockEdgeCaretRange, isCaretRangeInsideElement} from "./blockEdgeCaret";
import {LargeListVirtualizer} from "./listVirtualization";
+import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
interface IShiftClickBlockPoint {
blockElement: HTMLElement;
@@ -4280,13 +4281,11 @@ export class WYSIWYG {
this.preventClick = false;
return;
}
- protyle.app.plugins.forEach(item => {
- if (item.eventBus.has("click-editorcontent")) {
- item.eventBus.emit("click-editorcontent", {
- protyle,
- event
- });
- }
+ forEachPluginSubscriber("click-editorcontent", eventBus => {
+ 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.ts
index 6d97692b0d..2829725a53 100644
--- a/app/src/search/util.ts
+++ b/app/src/search/util.ts
@@ -41,7 +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 {emitToPlugins, forEachPluginSubscriber} from "../plugin/EventBusCore";
import {getUnRefList, openSearchUnRef, unRefMoreMenu} from "./unRef";
import {getDefaultSubType, getDefaultType} from "./getDefault";
import {isSupportCSSHL, searchMarkRender} from "../protyle/render/searchMarkRender";
@@ -1383,7 +1383,7 @@ const emitBeforeSearchResultsRender = (blocks: IBlock[], edit: Protyle,
searchElement,
blocks,
};
- emitToPlugins(edit.protyle?.app.plugins || [], "before-search-results-render", detail);
+ emitToPlugins("before-search-results-render", detail);
return detail.blocks;
};
@@ -1423,14 +1423,12 @@ export const inputEvent = (element: Element, config: Config.IUILayoutTabSearchCo
listElement.scrollTo(0, 0);
const previousElement = element.querySelector('[data-type="previous"]');
const nextElement = element.querySelector('[data-type="next"]');
- edit.protyle?.app.plugins.forEach(item => {
- if (item.eventBus.has("input-search")) {
- item.eventBus.emit("input-search", {
- protyle: edit,
- config,
- searchElement: searchInputElement,
- });
- }
+ forEachPluginSubscriber("input-search", eventBus => {
+ 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.ts
index 84a16e2986..f1ef3f2778 100644
--- a/app/src/util/uri.ts
+++ b/app/src/util/uri.ts
@@ -14,6 +14,7 @@ import {isBazaarAvailable} from "./bazaarAvailability";
import type {App} from "../index";
import {openDatabaseItem} from "../protyle/render/av/openDatabaseItem";
+import {forEachPluginSubscriber} from "../plugin/EventBusCore";
const bazaarTypes = new Set<TBazaarType>(["plugins", "themes", "icons", "templates", "widgets"]);
@@ -51,15 +52,13 @@ const processSiYuanUriBlocks = (app: App, uriObj: URL): boolean => {
ipcRenderer.send(Constants.SIYUAN_CMD, "show");
/// #endif
}
- app.plugins.forEach(plugin => {
- if (plugin.eventBus.has("open-siyuan-url-block")) {
- plugin.eventBus.emit("open-siyuan-url-block", {
- url: uriObj.href,
- id,
- focus,
- exist: existResponse.data,
- });
- }
+ forEachPluginSubscriber("open-siyuan-url-block", eventBus => {
+ 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.ts
index bc628c3b33..219ae4487c 100644
--- a/app/src/window/index.ts
+++ b/app/src/window/index.ts
@@ -50,7 +50,7 @@ class App {
id: genUUID(),
type: "main",
msgCallback: (data) => {
- emitToPlugins(this.plugins, "ws-main", data);
+ emitToPlugins("ws-main", data);
if (data) {
switch (data.cmd) {
case "logoutAuth":
@@ -173,7 +173,7 @@ class App {
transactionError(data.msg);
break;
case "syncing":
- processSync(data, this.plugins);
+ processSync(data);
break;
case "backgroundtask":
progressBackgroundTask(data.data.tasks);
diff --git a/app/src/window/onWindowsMsg.ts b/app/src/window/onWindowsMsg.ts
index 4b3bbcbf58..d6fa4dd7fb 100644
--- a/app/src/window/onWindowsMsg.ts
+++ b/app/src/window/onWindowsMsg.ts
@@ -1,7 +1,6 @@
import {getInstanceById} from "../layout/util";
import {Tab} from "../layout/Tab";
import {lockScreen} from "../dialog/processSystem";
-import type {App} from "../index";
import {clearTabDragPreview} from "../layout/tabDrag";
const closeTab = (ipcData: IWebSocketData) => {
@@ -10,7 +9,7 @@ const closeTab = (ipcData: IWebSocketData) => {
tab.parent.removeTab(ipcData.data);
}
};
-export const onWindowsMsg = (ipcData: IWebSocketData, app: App) => {
+export const onWindowsMsg = (ipcData: IWebSocketData) => {
switch (ipcData.cmd) {
case "closetab":
closeTab(ipcData);
@@ -37,7 +36,7 @@ export const onWindowsMsg = (ipcData: IWebSocketData, app: App) => {
break;
case "lockscreenByMode":
if (window.siyuan.config.system.lockScreenMode === 1) {
- lockScreen(app);
+ lockScreen();
}
break;
}