Skip to content

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

:bug: Restore marketplace directories and tooltips in settings windows https://github.com/siyuan-note/siyuan/issues/20002

Daniel733c918f62b4
diff --git a/app/src/config/bazaar/events.ts b/app/src/config/bazaar/events.ts
index 3de1850d83..eec9b04c37 100644
--- a/app/src/config/bazaar/events.ts
+++ b/app/src/config/bazaar/events.ts
@@ -2,9 +2,6 @@ import {showMessage} from "../../dialog/message";
import {openPluginPublishData} from "./pluginPublish";
import {fetchPost} from "../../util/fetch";
import {confirmDialog} from "../../dialog/confirmDialog";
-/// #if !BROWSER
-import * as path from "path";
-/// #endif
import {getFrontend, isMobile} from "../../util/functions";
import {setStorageVal, writeText} from "../../protyle/util/compatibility";
import {hasClosestByAttribute, hasClosestByClassName} from "../../protyle/util/hasClosest";
@@ -12,7 +9,7 @@ import {Plugin} from "../../plugin";
import type {App} from "../../index";
import {escapeHtml} from "../../util/escape";
import {setGlobalPluginsDisabled} from "../../plugin/globalState";
-import {useShell} from "../../util/pathName";
+import {openBazaarPath} from "./openPath";
import {previewImages} from "../../protyle/preview/image";
import {isBazaarPackageRatingEditable, sortBazaarPackages} from "../../util/bazaarPackage";
import {Constants} from "../../constants";
@@ -124,9 +121,7 @@ const ACTION_HANDLERS = {
return CONTINUE;
}
const item = installedItem || pkgItem;
- /// #if !BROWSER
- useShell("openPath", path.join(window.siyuan.config.system.dataDir, pkgType, item.name));
- /// #endif
+ openBazaarPath(pkgType, item.name);
return HANDLED;
}) satisfies TBazaarActionHandler,
"open-storage": ((context) => {
@@ -135,9 +130,7 @@ const ACTION_HANDLERS = {
if (!item || pkgType !== "plugins" || !item.hasStorageData) {
return CONTINUE;
}
- /// #if !BROWSER
- useShell("openPath", path.join(window.siyuan.config.system.dataDir, "storage", "petal", item.name));
- /// #endif
+ openBazaarPath(pkgType, item.name, true);
return HANDLED;
}) satisfies TBazaarActionHandler,
"retry-update": ((context) => {
diff --git a/app/src/config/bazaar/openPath.ts b/app/src/config/bazaar/openPath.ts
new file mode 100644
index 0000000000..3b20829914
--- /dev/null
+++ b/app/src/config/bazaar/openPath.ts
@@ -0,0 +1,18 @@
+/// #if !BROWSER
+import * as path from "path";
+/// #endif
+import {useShell} from "../../util/pathName";
+import {getSettingsWindowHost} from "../setting/windowContext";
+
+export const openBazaarPath = (type: TBazaarType, name: string, storage = false) => {
+ const host = getSettingsWindowHost();
+ if (host) {
+ host.openBazaarPath(type, name, storage);
+ return;
+ }
+ /// #if !BROWSER
+ const dataDir = window.siyuan.config.system.dataDir;
+ if (!dataDir || !name || (storage && type !== "plugins")) return;
+ useShell("openPath", storage ? path.join(dataDir, "storage", "petal", name) : path.join(dataDir, type, name));
+ /// #endif
+};
diff --git a/app/src/config/setting/nativeWindow.ts b/app/src/config/setting/nativeWindow.ts
index 823f743fb1..6f65ec0f42 100644
--- a/app/src/config/setting/nativeWindow.ts
+++ b/app/src/config/setting/nativeWindow.ts
@@ -13,6 +13,7 @@ import {hasPluginSetting} from "../../plugin";
import {getWorkspaceName} from "../../util/processTitle";
import {getDockEntryOrderSnapshot} from "../entryVisibility/dockOrder";
import {hasNativeSettingTasks} from "./taskBlocker";
+import {openBazaarPath} from "../bazaar/openPath";
import type {App} from "../../index";
import type {ISettingsWindowHost} from "./windowContext";
import type {TSettingTab} from "./tabs";
@@ -105,6 +106,7 @@ export const openNativeSettings = async (app: App, command: ISettingsCommand = {
reload: () => { assertActive(); return reloadUI(); },
resetLayout: () => { assertActive(); return resetLayout(); },
getDockOrderSnapshot: () => { assertActive(); return getDockEntryOrderSnapshot(); },
+ openBazaarPath: (type, name, storage) => { assertActive(); openBazaarPath(type, name, storage); },
exit: setCurrentWorkspace => { assertActive(); return exitSiYuan(setCurrentWorkspace); },
plugin: plugin && {
name: plugin.name,
diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.ts
index c7d8d196e4..73ab6ddd8f 100644
--- a/app/src/config/setting/window.ts
+++ b/app/src/config/setting/window.ts
@@ -24,7 +24,7 @@ import {appearanceConfigApi, refreshAppearance} from "../tabs/appearanceRuntime"
import {Setting} from "../../plugin/Setting";
import {bindMenuKeydown} from "../../menus/Menu";
import {windowMouseMove} from "../../boot/globalEvent/mousemove";
-import {hideTooltip} from "../../dialog/tooltip";
+import {hideTooltip, initTooltips} from "../../dialog/tooltip";
import {applyCloudUserState} from "../tabs/accountUi";
import {updateServerAddresses} from "../tabs/accessRuntime";
import {installPluginStorageFetchAppId} from "../../util/fetchAppId";
@@ -227,6 +227,7 @@ const initialize = async () => {
event.preventDefault();
}
});
+ initTooltips();
window.addEventListener("mousemove", windowMouseMove);
window.addEventListener("blur", hideTooltip);
window.addEventListener("focus", () => {
diff --git a/app/src/config/setting/windowContext.ts b/app/src/config/setting/windowContext.ts
index ecd6fe0c21..5bcc5f053f 100644
--- a/app/src/config/setting/windowContext.ts
+++ b/app/src/config/setting/windowContext.ts
@@ -15,6 +15,7 @@ export interface ISettingsWindowHost {
reload: () => Promise<void>;
resetLayout: () => Promise<void>;
getDockOrderSnapshot: () => TDockOrderSnapshot;
+ openBazaarPath: (type: TBazaarType, name: string, storage?: boolean) => void;
exportLayout: (options: {cb: () => void; errorExit: boolean}) => Promise<void>;
exit: (setCurrentWorkspace?: boolean) => Promise<void>;
subscribePlugins: (listener: (state: IGlobalPluginStateSnapshot) => void) => () => void;
diff --git a/app/src/dialog/tooltip.ts b/app/src/dialog/tooltip.ts
index a86665bfaf..7713c60d20 100644
--- a/app/src/dialog/tooltip.ts
+++ b/app/src/dialog/tooltip.ts
@@ -1,6 +1,30 @@
import {isMobile} from "../util/functions";
import {emitToPlugins, forEachPluginSubscriber} from "../plugin/EventBusCore";
+// 无编辑器的窗口复用提示框渲染,不注册块预览事件。
+export const initTooltips = () => {
+ document.addEventListener("mouseover", (event: MouseEvent) => {
+ const target = (event.target as Element).closest(".ariaLabel");
+ if (target && !target.classList.contains("b3-tooltips")) {
+ let message = target.getAttribute("aria-label") || "";
+ try {
+ message = decodeURIComponent(message);
+ } catch (error) {
+ // 保留包含不完整 URI 转义的提示文本。
+ }
+ if (message) {
+ showTooltip(message, target, undefined, event);
+ return;
+ }
+ }
+ const tooltip = document.getElementById("tooltip");
+ if (!tooltip.contains(event.target as Node) || tooltip.clientHeight >= tooltip.scrollHeight) {
+ hideTooltip();
+ }
+ });
+ document.addEventListener("mouseleave", hideTooltip);
+};
+
export const showTooltip = (
message: string,
target: Element,
diff --git a/app/tests/nativeSettingsOwner.test.js b/app/tests/nativeSettingsOwner.test.js
index 02daac5b95..a9f1b011d9 100644
--- a/app/tests/nativeSettingsOwner.test.js
+++ b/app/tests/nativeSettingsOwner.test.js
@@ -57,6 +57,7 @@ const setup = () => {
"../../util/processTitle": {getWorkspaceName: () => "Workspace"},
"../entryVisibility/dockOrder": {getDockEntryOrderSnapshot: () => ({left: ["outline"]})},
"./taskBlocker": {hasNativeSettingTasks: () => nativeTask},
+ "../bazaar/openPath": {openBazaarPath: record("openBazaarPath")},
};
const context = {exports: {}, window, console: {error: record("error")}, require: name => {
assert.ok(modules[name], name);
@@ -97,6 +98,8 @@ test("host cleanup removes the token before throwing plugin callbacks and dispos
owner.subscribePlugins(() => notifications++);
subscriptions[0].throwOnDispose = true;
owner.suspendShortcuts();
+ owner.openBazaarPath("plugins", "example", true);
+ assert.deepEqual(calls.find(item => item[0] === "openBazaarPath"), ["openBazaarPath", "plugins", "example", true]);
ipcRenderer.emit("siyuan-settings-closed", {}, requests[0].data.token, false);
assert.equal(owner.isActive(), false);
assert.deepEqual(subscriptions.map(item => item.disposed), [1, 1]);
@@ -108,6 +111,7 @@ test("host cleanup removes the token before throwing plugin callbacks and dispos
owner.dispose();
assert.equal(calls.filter(item => item[0] === "closed").length, 1);
assert.throws(() => owner.reload(), /no longer available/);
+ assert.throws(() => owner.openBazaarPath("plugins", "example"), /no longer available/);
assert.throws(() => owner.plugin.mount(() => {}), /no longer available/);
await assert.rejects(owner.loadPlugin({}), /no longer available/);
});
diff --git a/app/tests/settingsBazaar.test.js b/app/tests/settingsBazaar.test.js
index e68bad177c..fead30c7cb 100644
--- a/app/tests/settingsBazaar.test.js
+++ b/app/tests/settingsBazaar.test.js
@@ -13,6 +13,47 @@ const compiled = ts.transpileModule(`export const bazaar = {${render.getText(sou
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
}).outputText;
+test("directory actions delegate to the owner and preserve installed-package and storage eligibility", () => {
+ const events = ts.createSourceFile("events.ts", readFileSync("src/config/bazaar/events.ts", "utf8"), ts.ScriptTarget.ES2021, true);
+ const handlers = events.statements.find(statement => ts.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => item.name.getText(events) === "ACTION_HANDLERS"));
+ const actions = ts.transpileModule("export " + handlers.getText(events), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+ }).outputText;
+ const pathCode = ts.transpileModule(readFileSync("src/config/bazaar/openPath.ts", "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+ }).outputText;
+ const opened = [];
+ const delegated = [];
+ let host = {openBazaarPath: (...args) => delegated.push(args)};
+ const window = {siyuan: {config: {system: {dataDir: ""}}}};
+ const exports = {};
+ const path = require("node:path");
+ runInNewContext(pathCode, {exports, window, require: name => ({path,
+ "../../util/pathName": {useShell: (...args) => opened.push(args)},
+ "../setting/windowContext": {getSettingsWindowHost: () => host},
+ })[name]});
+ const actionExports = {};
+ runInNewContext(actions, {exports: actionExports, CONTINUE: {handled: false}, HANDLED: {handled: true},
+ HANDLED_NATIVE: {handled: true}, openBazaarPath: exports.openBazaarPath});
+ const context = {pkgType: "plugins", installedItem: {name: "installed", hasStorageData: true}, pkgItem: {name: "available"}};
+ const {ACTION_HANDLERS} = actionExports;
+ assert.equal(ACTION_HANDLERS.open(context).handled, true);
+ assert.equal(ACTION_HANDLERS["open-storage"](context).handled, true);
+ assert.deepEqual(delegated, [["plugins", "installed", false], ["plugins", "installed", true]]);
+ assert.deepEqual(opened, []);
+ assert.equal(ACTION_HANDLERS["open-storage"]({...context, pkgType: "themes"}).handled, false);
+ assert.equal(ACTION_HANDLERS["open-storage"]({...context, installedItem: {name: "installed"}}).handled, false);
+ host = undefined;
+ exports.openBazaarPath("plugins", "installed");
+ assert.deepEqual(opened, []);
+ window.siyuan.config.system.dataDir = "D:/workspace/data";
+ ACTION_HANDLERS.open(context);
+ ACTION_HANDLERS["open-storage"](context);
+ assert.deepEqual(opened, [["openPath", path.join("D:/workspace/data", "plugins", "installed")],
+ ["openPath", path.join("D:/workspace/data", "storage", "petal", "installed")]]);
+});
+
for (const mode of ["settings-window", "main-window", "mobile"]) {
test(`installed package cards use plugin ownership for setting buttons (${mode})`, () => {
const packages = ["none", "configured", "custom"].map(name => ({name, preferredName: name, preferredDesc: ""}));
diff --git a/app/tests/settingsBoot.test.js b/app/tests/settingsBoot.test.js
index 0de09c17fe..41fe924ee4 100644
--- a/app/tests/settingsBoot.test.js
+++ b/app/tests/settingsBoot.test.js
@@ -43,6 +43,7 @@ const createBoot = (plugin = false, failed = "") => {
destroy() { calls.push("disconnect"); }
}},
"../../menus": {Menus: class {}},
+ "../../dialog/tooltip": {initTooltips: () => calls.push("tooltips"), hideTooltip() {}},
"../../util/genID": {genUUID: () => "id"},
"../../util/fetch": {fetchSyncPost: async (url, data) => {
if (url === "/api/system/getConf") return {code: 0, data: {conf: {appearance: {lang: "en"}}}};
@@ -108,6 +109,8 @@ for (const plugin of [false, true]) {
boot.pending.get("user")();
await initialized;
assert.ok(boot.calls.indexOf("render") < boot.calls.indexOf("siyuan-settings-ready"));
+ assert.ok(boot.calls.indexOf("render") < boot.calls.indexOf("tooltips"));
+ assert.ok(boot.calls.indexOf("tooltips") < boot.calls.indexOf("siyuan-settings-ready"));
});
}
diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.js
index e335208921..931e2ed5fe 100644
--- a/app/tests/settingsWindow.test.js
+++ b/app/tests/settingsWindow.test.js
@@ -14,7 +14,8 @@ const loadRendererModule = (source, modules) => {
const rendererModules = (sources) => {
let sequence = 0;
- window.siyuan = {dialogs: [], zIndex: 1, storage: {zoom: 1}, config: {system: {workspaceDir: "D:/workspaces/Workspace A & <B>/"}},
+ window.siyuan = {dialogs: [], zIndex: 1, storage: {zoom: 1}, config: {system: {
+ workspaceDir: "D:/workspaces/Workspace A & <B>/", dataDir: "D:/workspaces/Workspace A & <B>/data"}},
languages: {cancel: "Cancel", save: "Save", config: "Settings", workspace: "Workspace",
min: "Minimize", max: "Maximize", restore: "Restore", close: "Close"},
menus: {menu: {element: document.createElement("div"), remove() {}}}, ws: {app: {plugins: [], appId: "test"}}};
@@ -73,6 +74,19 @@ const bootChild = async (sources) => {
await ipcRenderer.invoke("test-settings-initializing");
canceled.remove();
window.siyuan.config.system.workspaceDir = "";
+ window.siyuan.config.system.dataDir = "";
+ const {openBazaarPath} = loadRendererModule(sources.bazaarPath, {
+ path: require("node:path"), "../../util/pathName": {useShell() { throw new Error("child opened a relative path"); }},
+ "../setting/windowContext": {getSettingsWindowHost: () => host},
+ });
+ const callsBefore = window.opener.settingsPaths.length;
+ openBazaarPath("plugins", "example");
+ openBazaarPath("plugins", "example", true);
+ const expected = require("node:path");
+ require("node:assert/strict").deepEqual(Array.from(window.opener.settingsPaths.slice(callsBefore), item => Array.from(item)), [
+ ["openPath", expected.join("D:/workspaces/Workspace A & <B>/data", "plugins", "example")],
+ ["openPath", expected.join("D:/workspaces/Workspace A & <B>/data", "storage", "petal", "example")],
+ ]);
document.title = host.title;
if (host.plugin) {
const {Setting} = loadRendererModule(sources.setting, {
@@ -99,6 +113,53 @@ const bootChild = async (sources) => {
require("node:assert/strict").equal(dialog.element.querySelector("#drag").textContent, document.title);
}
});
+ const check = require("node:assert/strict");
+ await new Promise((resolve, reject) => {
+ const script = document.createElement("script");
+ script.src = "/stage/protyle/js/protyle-html.js";
+ script.onload = resolve;
+ script.onerror = reject;
+ document.head.append(script);
+ });
+ check.equal(typeof window.Lute, "undefined");
+ const pluginEvents = [];
+ const {initTooltips} = loadRendererModule(sources.tooltip, {
+ "../util/functions": {isMobile: () => false},
+ "../plugin/EventBusCore": {emitToPlugins: name => pluginEvents.push(name),
+ forEachPluginSubscriber: (name, callback) => callback({emit: () => pluginEvents.push(name)})},
+ });
+ const tooltip = document.createElement("div");
+ tooltip.id = "tooltip";
+ tooltip.className = "tooltip fn__none";
+ const button = document.createElement("button");
+ button.className = "ariaLabel";
+ button.innerHTML = "<svg><use></use></svg>";
+ button.setAttribute("aria-label", encodeURIComponent('<b>Directory</b><img src="x" onerror="alert(1)">'));
+ button.setAttribute("data-delay", "0");
+ button.setAttribute("data-position", "north");
+ document.body.append(tooltip, button);
+ initTooltips();
+ const hover = element => element.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
+ hover(button.querySelector("use"));
+ check.equal(tooltip.classList.contains("fn__none"), false);
+ check.equal(tooltip.innerHTML, '<b>Directory</b><img src="x">');
+ check.equal(tooltip.style.animationDelay, "0ms");
+ check.equal(tooltip.style.pointerEvents, "none");
+ check.ok(parseFloat(tooltip.style.left) >= 0);
+ check.ok(parseFloat(tooltip.style.top) >= 0);
+ button.setAttribute("aria-label", "100% complete");
+ hover(button);
+ check.equal(tooltip.textContent, "100% complete");
+ button.classList.add("b3-tooltips");
+ hover(button);
+ check.equal(tooltip.classList.contains("fn__none"), true);
+ button.classList.remove("b3-tooltips");
+ hover(button);
+ hover(document.body);
+ check.equal(tooltip.classList.contains("fn__none"), true);
+ check.ok(pluginEvents.includes("before-show-tooltip"));
+ check.ok(pluginEvents.includes("before-hide-tooltip"));
+ button.remove();
if (!document.getElementById("pendingTheme").sheet) throw new Error("settings shown before theme loaded");
ipcRenderer.send("siyuan-settings-ready");
ipcRenderer.send("test-settings-ready");
@@ -108,6 +169,11 @@ const runCases = async (sources) => {
const assert = require("node:assert/strict");
const {ipcRenderer} = require("electron");
const {Dialog, genUUID, context, fit, titles} = rendererModules(sources);
+ window.settingsPaths = [];
+ const bazaarPath = loadRendererModule(sources.bazaarPath, {
+ path: require("node:path"), "../../util/pathName": {useShell: (...args) => window.settingsPaths.push(args)},
+ "../setting/windowContext": {getSettingsWindowHost: () => undefined},
+ });
class Plugin {openSetting() {}}
const pluginSettings = {};
new Function("Plugin", "exports", sources.pluginSettings)(Plugin, pluginSettings);
@@ -122,6 +188,7 @@ const runCases = async (sources) => {
"../../util/processTitle": titles,
"../entryVisibility/dockOrder": {getDockEntryOrderSnapshot: () => ({})},
"./taskBlocker": {hasNativeSettingTasks: () => false},
+ "../bazaar/openPath": bazaarPath,
});
const {Setting} = loadRendererModule(sources.setting, {
"../util/functions": {isMobile: () => false, getFrontend: () => "desktop"}, "../dialog": {Dialog},
@@ -363,7 +430,8 @@ if (process.versions.electron && process.type === "browser") {
for (const [key, file] of Object.entries({dialog: "dialog/index.ts", setting: "plugin/Setting.ts",
native: "config/setting/nativeWindow.ts", fit: "config/setting/windowDialog.ts", controls: "boot/windowControls.ts",
paint: "config/setting/windowPaint.ts", frontend: "util/functions.ts", titles: "util/processTitle.ts",
- mount: "config/setting/mount.ts", save: "config/setting/save.ts", fragments: "config/render/fragments.ts"})) {
+ mount: "config/setting/mount.ts", save: "config/setting/save.ts", fragments: "config/render/fragments.ts",
+ bazaarPath: "config/bazaar/openPath.ts", tooltip: "dialog/tooltip.ts"})) {
let source = fs.readFileSync(path.join(__dirname, "../src", file), "utf8");
if (key === "frontend") {
source = require("ifdef-loader/preprocessor").parse(source, {MOBILE: false, BROWSER: false}, false, true);
@@ -381,6 +449,11 @@ if (process.versions.electron && process.type === "browser") {
}).outputText;
const server = createServer((request, response) => {
const pathname = new URL(request.url, "http://localhost").pathname;
+ if (pathname === "/stage/protyle/js/protyle-html.js") {
+ response.setHeader("Content-Type", "text/javascript; charset=utf-8");
+ response.end(fs.readFileSync(path.join(__dirname, "../stage/protyle/js/protyle-html.js")));
+ return;
+ }
if (pathname.startsWith("/fixture/")) {
response.setHeader("Content-Type", "text/css; charset=utf-8");
if (pathname === "/fixture/missing.css") {