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 intercepting link opening through plugin event bus https://github.com/siyuan-note/siyuan/issues/18830
Danielaf0286e84907
diff --git a/app/src/config/tabs/aboutTab.ts b/app/src/config/tabs/aboutTab.tsindex aee4faf3c7..d365a6838d 100644--- a/app/src/config/tabs/aboutTab.ts+++ b/app/src/config/tabs/aboutTab.ts@@ -2,7 +2,7 @@ import type {SettingTabBuilder} from "../setting/builder";import {Constants} from "../../constants";import {fetchPost} from "../../util/fetch";import {getCloudURL} from "../util/about";-import {openByMobile} from "../../editor/openLink";+import {openLink} from "../../editor/openLink";import {sendAppSetting} from "./appRuntime";const registerAboutVersionGroup = (tab: SettingTabBuilder) => {@@ -119,7 +119,7 @@ const registerAboutInfoGroup = (tab: SettingTabBuilder) => {</div>`,afterMount: (root) => {root.querySelector("#sponsorBtn")?.addEventListener("click", () => {- openByMobile(getCloudURL("sponsor"));+ openLink(window.siyuan.ws.app, getCloudURL("sponsor"));});},});diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.tsindex a183186f16..5c308ff834 100644--- a/app/src/config/tabs/accessTab.ts+++ b/app/src/config/tabs/accessTab.ts@@ -9,7 +9,7 @@ import {showMessage} from "../../dialog/message";import {shell} from "electron";/// #endifimport {isInAndroid, isInHarmony, isInIOS, isInMobileApp, saveExportFile} from "../../protyle/util/compatibility";-import {openByMobile} from "../../editor/openLink";+import {openByMobile, openLink} from "../../editor/openLink";import {bindPasswordIconaToggle, genConfigItemMainHtml} from "../render/fragments";import {genServerAddressesHTML,@@ -547,11 +547,7 @@ const registerAccessServerGroup = (tab: SettingTabBuilder) => {afterMount: (root) => {root.querySelector("#openLocalServer")?.addEventListener("click", () => {const url = `http://127.0.0.1:${location.port}`;- /// #if !BROWSER- void shell.openExternal(url);- /// #else- openByMobile(url);- /// #endif+ openLink(window.siyuan.ws.app, url);});},}, (stack) => {diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.tsindex df9044430d..0f39f0ab10 100644--- a/app/src/config/tabs/appearanceTab.ts+++ b/app/src/config/tabs/appearanceTab.ts@@ -13,7 +13,7 @@ import {getFrontend, isBrowser, isMobile, objEquals} from "../../util/functions"import {exitSiYuan} from "../../dialog/processSystem";import {isInMobileApp} from "../../protyle/util/compatibility";import {fetchPost, fetchSyncPost} from "../../util/fetch";-import {openByMobile} from "../../editor/openLink";+import {openLink} from "../../editor/openLink";import {openSnippets} from "../util/snippets";import {confirmDialog} from "../../dialog/confirmDialog";import {Dialog} from "../../dialog";@@ -795,7 +795,7 @@ const registerAppearancePersonalizationGroup = (tab: SettingTabBuilder) => {const mountAppearanceCodeSnippet = (root: HTMLElement) => {root.querySelector("#codeSnippetCommunityShare")?.addEventListener("click", () => {- openByMobile("https://ld246.com/tag/code-snippet");+ openLink(window.siyuan.ws.app, "https://ld246.com/tag/code-snippet");});root.querySelector("#codeSnippet")?.addEventListener("click", () => {openSnippets();diff --git a/app/src/editor/openLink.ts b/app/src/editor/openLink.tsindex 03a3c094e8..b1926ed543 100644--- a/app/src/editor/openLink.ts+++ b/app/src/editor/openLink.ts@@ -17,6 +17,7 @@ import {resolveAssetOpenAction,resolveExecutableAssetOpenAction,} from "./assetOpen";+import {emitOpenAsset, emitOpenLink, resolveOpenLinkEvent} from "./openLinkEvent";/// #if !MOBILEimport {openAssetNewWindow} from "../window/openNewWindow";/// #endif@@ -28,21 +29,6 @@ const isPreviewableAsset = (assetPath: string) => {(extension !== ".pdf" || assetPath.startsWith("assets/"));};-const emitOpenAsset = (- app: App,- path: string,- action: Config.TAssetOpenAction,- event?: MouseEvent,-) => {- let open = true;- app.plugins.forEach((plugin) => {- if (!plugin.eventBus.emit("open-asset", {path, action, event})) {- open = false;- }- });- return open;-};-export const openAssetByAction = (app: App,assetPath: string,@@ -121,8 +107,22 @@ export const openLink = (app: App, aLink: string, event?: MouseEvent, ctrlIsPres/// #if MOBILEaction = "app";/// #endif- if (isAsset && !emitOpenAsset(app, originalLinkAddress, action, event)) {- return;+ const openLinkEvent = resolveOpenLinkEvent({+ href: linkAddress,+ originalHref: aLink,+ isAsset,+ isLocal: isLocalPath(linkAddress),+ event,+ });+ if (isAsset) {+ if (!emitOpenAsset(app, originalLinkAddress, action, event)) {+ return;+ }+ } else if (openLinkEvent) {+ linkAddress = openLinkEvent.href;+ if (!emitOpenLink(app, openLinkEvent)) {+ return;+ }}if (processSiYuanUri(app, linkAddress)) {return;@@ -133,11 +133,6 @@ export const openLink = (app: App, aLink: string, event?: MouseEvent, ctrlIsPresif (isLocalPath(linkAddress)) {openAssetByAction(app, linkAddress, pdfParams, action);} else if (linkAddress) {- if (0 > linkAddress.indexOf(":")) {- // 使用 : 判断,不使用 :// 判断 Open external application protocol invalid https://github.com/siyuan-note/siyuan/issues/10075- // Support click to open hyperlinks like `www.foo.com` https://github.com/siyuan-note/siyuan/issues/9986- linkAddress = `https://${linkAddress}`;- }/// #if !BROWSERshell.openExternal(linkAddress).catch((e) => {showMessage(e);diff --git a/app/src/editor/openLinkEvent.test.ts b/app/src/editor/openLinkEvent.test.tsnew file mode 100644index 0000000000..b6541eefd0--- /dev/null+++ b/app/src/editor/openLinkEvent.test.ts@@ -0,0 +1,98 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import type {App} from "../index";+import {+ emitOpenAsset,+ emitOpenLink,+ type IOpenLinkEventDetail,+ resolveOpenLinkEvent,+} from "./openLinkEvent";++const createApp = (emitters: Array<(type: TEventBus, detail: unknown) => boolean>) => ({+ plugins: emitters.map((emit) => ({eventBus: {emit}})),+}) as unknown as App;++describe("link opening plugin events", () => {+ it("normalizes external links before emitting", () => {+ assert.deepEqual(resolveOpenLinkEvent({+ href: "example.com",+ originalHref: "example.com",+ isAsset: false,+ isLocal: false,+ }), {+ href: "https://example.com",+ originalHref: "example.com",+ event: undefined,+ });+ });++ it("leaves assets to the dedicated asset event", () => {+ assert.equal(resolveOpenLinkEvent({+ href: "assets/example.pdf",+ originalHref: "assets/example.pdf",+ isAsset: true,+ isLocal: true,+ }), undefined);+ });++ it("stops notifying plugins after a link opening is canceled", () => {+ const calls: number[] = [];+ const detail: IOpenLinkEventDetail = {+ href: "https://example.com",+ originalHref: "example.com",+ };+ const app = createApp([+ (type, receivedDetail) => {+ calls.push(1);+ assert.equal(type, "open-link");+ assert.equal(receivedDetail, detail);+ return true;+ },+ () => {+ calls.push(2);+ return false;+ },+ () => {+ calls.push(3);+ return true;+ },+ ]);++ assert.equal(emitOpenLink(app, detail), false);+ assert.deepEqual(calls, [1, 2]);+ });++ it("notifies every plugin when link opening is allowed", () => {+ const calls: number[] = [];+ const app = createApp([+ () => {+ calls.push(1);+ return true;+ },+ () => {+ calls.push(2);+ return true;+ },+ ]);++ assert.equal(emitOpenLink(app, {href: "siyuan://blocks/id", originalHref: "siyuan://blocks/id"}), true);+ assert.deepEqual(calls, [1, 2]);+ });++ it("uses the same first-canceler-wins behavior for assets", () => {+ const calls: number[] = [];+ const app = createApp([+ () => {+ calls.push(1);+ return false;+ },+ () => {+ calls.push(2);+ return true;+ },+ ]);++ assert.equal(emitOpenAsset(app, "assets/example.pdf", "right"), false);+ assert.deepEqual(calls, [1]);+ });+});diff --git a/app/src/editor/openLinkEvent.ts b/app/src/editor/openLinkEvent.tsnew file mode 100644index 0000000000..e6eb0acfcb--- /dev/null+++ b/app/src/editor/openLinkEvent.ts@@ -0,0 +1,43 @@+import type {App} from "../index";++export interface IOpenLinkEventDetail {+ href: string;+ originalHref: string;+ event?: MouseEvent | KeyboardEvent;+}++export const resolveOpenLinkEvent = (options: {+ href: string,+ originalHref: string,+ isAsset: boolean,+ isLocal: boolean,+ event?: MouseEvent | KeyboardEvent,+}): IOpenLinkEventDetail | undefined => {+ if (!options.href || options.isAsset) {+ return;+ }+ const href = !options.isLocal && 0 > options.href.indexOf(":") ? `https://${options.href}` : options.href;+ return {href, originalHref: options.originalHref, event: options.event};+};++const emitCancelablePluginEvent = <T>(app: App, type: TEventBus, detail: T) => {+ for (const plugin of app.plugins) {+ if (!plugin.eventBus.emit(type, detail)) {+ return false;+ }+ }+ return true;+};++export const emitOpenLink = (app: App, detail: IOpenLinkEventDetail) => {+ return emitCancelablePluginEvent(app, "open-link", detail);+};++export const emitOpenAsset = (+ app: App,+ path: string,+ action: Config.TAssetOpenAction,+ event?: MouseEvent,+) => {+ return emitCancelablePluginEvent(app, "open-asset", {path, action, event});+};diff --git a/app/src/layout/status.ts b/app/src/layout/status.tsindex e8ff0ace43..c9dd613161 100644--- a/app/src/layout/status.ts+++ b/app/src/layout/status.ts@@ -12,6 +12,7 @@ import {MenuItem} from "../menus/Menu";import {Constants} from "../constants";import {updateHotkeyTip} from "../protyle/util/compatibility";import {escapeAriaLabel} from "../util/escape";+import {openLink} from "../editor/openLink";export const initStatus = (isWindow = false) => {/// #if !MOBILE@@ -78,9 +79,9 @@ export const initStatus = (isWindow = false) => {icon: "iconFeedback",click: () => {if ("zh-CN" === window.siyuan.config.lang) {- window.open("https://ld246.com/article/1649901726096");+ openLink(window.siyuan.ws.app, "https://ld246.com/article/1649901726096");} else {- window.open("https://liuyun.io/article/1686530886208");+ openLink(window.siyuan.ws.app, "https://liuyun.io/article/1686530886208");}}}).element);@@ -97,14 +98,14 @@ export const initStatus = (isWindow = false) => {label: window.siyuan.languages["_trayMenu"].officialWebsite,icon: "iconSiYuan",click: () => {- window.open("https://b3log.org/siyuan");+ openLink(window.siyuan.ws.app, "https://b3log.org/siyuan");}}).element);window.siyuan.menus.menu.append(new MenuItem({label: window.siyuan.languages["_trayMenu"].openSource,icon: "iconGithub",click: () => {- window.open("https://github.com/siyuan-note/siyuan");+ openLink(window.siyuan.ws.app, "https://github.com/siyuan-note/siyuan");}}).element);const rect = target.getBoundingClientRect();diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.tsindex 84d7f34263..f8f024bfa5 100644--- a/app/src/menus/commonMenuItem.ts+++ b/app/src/menus/commonMenuItem.ts@@ -1,6 +1,3 @@-/// #if !BROWSER-import {shell} from "electron";-/// #endifimport {confirmDialog} from "../dialog/confirmDialog";import {getSearch, isMobile, isValidCustomAttrName} from "../util/functions";import {getAssetExtension, isEncryptedBox, isLocalPath, movePathTo, moveToPath, pathPosix} from "../util/pathName";@@ -15,8 +12,7 @@ import {saveExportFile,writeText} from "../protyle/util/compatibility";-import {openByMobile} from "../editor/openLink";-import {processSiYuanUri} from "../util/uri";+import {openByMobile, openLink} from "../editor/openLink";import {fetchPost, fetchSyncPost} from "../util/fetch";import {hideMessage, showMessage} from "../dialog/message";import {Dialog} from "../dialog";@@ -975,12 +971,7 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAcceleratlabel: window.siyuan.languages.useDefault,accelerator: showAccelerator ? window.siyuan.languages.click : "",click: () => {- if (processSiYuanUri(app, src)) {- return;- }- shell.openExternal(src).catch((e) => {- showMessage(e);- });+ openLink(app, src);}});/// #else@@ -989,7 +980,7 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAcceleratlabel: isInAndroid() || isInHarmony() ? window.siyuan.languages.useDefault : window.siyuan.languages.useBrowserView,accelerator: showAccelerator ? window.siyuan.languages.click : "",click: () => {- openByMobile(src);+ openLink(app, src);}});/// #endifdiff --git a/app/src/menus/workspace.ts b/app/src/menus/workspace.tsindex 5145baee22..61b8a452ac 100644--- a/app/src/menus/workspace.ts+++ b/app/src/menus/workspace.ts@@ -29,6 +29,7 @@ import {openRecentDocs} from "../business/openRecentDocs";import * as dayjs from "dayjs";import {upDownHint} from "../util/upDownHint";import {openDataMigration} from "./dataMigration";+import {openLink} from "../editor/openLink";const editLayout = (layoutName?: string) => {const dialog = new Dialog({@@ -567,9 +568,9 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {icon: "iconFeedback",click: () => {if ("zh-CN" === window.siyuan.config.lang) {- window.open("https://ld246.com/article/1649901726096");+ openLink(app, "https://ld246.com/article/1649901726096");} else {- window.open("https://liuyun.io/article/1686530886208");+ openLink(app, "https://liuyun.io/article/1686530886208");}}}).element);diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex b7a2e31a91..2e4ab0c354 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -101,7 +101,7 @@ type TEventBus = "ws-main" | "sync-start" | "sync-end" | "sync-fail" |"open-noneditableblock" |"open-menu-blockref" | "open-menu-fileannotationref" | "open-menu-tag" | "open-menu-link" | "open-menu-image" |"open-menu-av" | "open-menu-content" | "open-menu-breadcrumbmore" | "open-menu-doctree" | "open-menu-inbox" |- "open-siyuan-url-plugin" | "open-siyuan-url-block" | "open-asset" | "opened-notebook" |+ "open-siyuan-url-plugin" | "open-siyuan-url-block" | "open-asset" | "open-link" | "opened-notebook" |"closed-notebook" |"paste" |"input-search" |