Skip to content

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

:bug: Use editor document menus in graph view https://github.com/siyuan-note/siyuan/issues/20148

Daniel77f2b588bb44
diff --git a/app/src/history/docReadonly.test.ts b/app/src/history/docReadonly.test.ts
index aaf4cb92d8..49ecbe5314 100644
--- a/app/src/history/docReadonly.test.ts
+++ b/app/src/history/docReadonly.test.ts
@@ -14,7 +14,8 @@ const loadModule = (path: string, mobile: boolean, dependencies: Record<string,
const code = transpileModule(source, {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
}).outputText;
- runInNewContext(code, {exports, require: (name: string) => dependencies[name] || {}, ...globals});
+ runInNewContext(code, {exports, require: (name: string) => name === "./documentMenu" ?
+ loadModule("protyle/header/documentMenu.ts", mobile, dependencies, globals) : dependencies[name] || {}, ...globals});
return exports;
};
@@ -38,7 +39,7 @@ for (const mobile of [false, true]) {
"../../menus/Menu": {MenuItem: class {element: IMenu; constructor(item: IMenu) { this.element = item; }}},
"../../menus/commonMenuItem": {copySubMenu: (): IMenu[] => [], exportMd: () => ({}), movePathToMenu: () => ({})},
"../../util/fetch": {fetchPost: (_url: string, _body: unknown, callback: (response: unknown) => void) =>
- callback({data: {name: "Document", ial: {id: "20231011123456", updated: "20231011123456"}}})},
+ callback({code: 0, data: {name: "Document", ial: {id: "20231011123456", updated: "20231011123456"}}})},
"../../history/doc": {openDocHistory: (options: typeof opened[number]) => opened.push(options)},
"../../util/pathName": {isEncryptedBox: () => false},
"../../util/hostCapabilities": {getHostCapabilities: () => ({})},
diff --git a/app/src/layout/dock/Graph.test.ts b/app/src/layout/dock/Graph.test.ts
index 3cc68f0443..92a6fc80a8 100644
--- a/app/src/layout/dock/Graph.test.ts
+++ b/app/src/layout/dock/Graph.test.ts
@@ -4,7 +4,6 @@ import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
import {flushSettingSaves, trackSettingRequest} from "../../config/setting/pending";
-import {posix} from "node:path";
for (const type of ["global", "local", "pin"]) {
test(`reset flushes the latest delayed graph settings before acknowledging (${type})`, async () => {
@@ -67,23 +66,25 @@ const createMenuGraph = (restricted = false) => {
const exports = {} as typeof import("./Graph");
const listeners = new Map<string, Set<() => void>>();
const requests: Array<{url: string, body: unknown}> = [];
- const menus: Parameters<typeof import("../../menus/navigation").initDocumentMenu>[1][] = [];
+ const menus: Parameters<typeof import("../../protyle/header/documentMenu").openDocumentMenu>[0][] = [];
const positions: IPosition[] = [];
- let resolveSiblings: (value: unknown) => void;
- const siblings = new Promise(resolve => { resolveSiblings = resolve; });
+ const engineOptions: import("./graph/types").IGraphEngineOptions[] = [];
+ let removedMenus = 0;
runInNewContext(transpileModule(readFileSync("src/layout/dock/Graph.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
}).outputText, {
exports, AbortController,
require: (name: string) => {
if (name === "../Model") { return {Model: class {}}; }
- if (name === "../../util/pathName") { return {pathPosix: () => posix}; }
+ if (name === "./graph/GraphEngine") { return {GraphEngine: class {
+ constructor(_target: unknown, options: typeof engineOptions[number]) { engineOptions.push(options); }
+ }}; }
if (name === "../../constants") { return {Constants: {
CUSTOM_SY_SUBDOC_SORT_MODE: "custom-sy-subdoc-sort-mode", CUSTOM_SY_READONLY: "custom-sy-readonly"}}; }
- if (name === "../../menus/navigation") { return {
- initDocumentMenu: (_app: unknown, options: typeof menus[number]) => {
+ if (name === "../../protyle/header/documentMenu") { return {
+ openDocumentMenu: (options: typeof menus[number]) => {
menus.push(options);
- return {popup: (position: IPosition) => positions.push(position)};
+ positions.push(options.position);
}}; }
if (name === "../../util/fetch") { return {
fetchSyncPost: (url: string, body: unknown) => {
@@ -96,7 +97,7 @@ const createMenuGraph = (restricted = false) => {
return Promise.resolve({code: 0, data: {rootID: "doc", name: "Document", subFileCount: 2,
ial: {"custom-sy-subdoc-sort-mode": "0", "custom-sy-readonly": "true"}}});
}
- return siblings;
+ throw new Error("Unexpected graph menu request: " + url);
}}; }
return {};
},
@@ -107,39 +108,42 @@ const createMenuGraph = (restricted = false) => {
},
removeEventListener: (name: string, listener: () => void) => listeners.get(name)?.delete(listener),
},
- window: {siyuan: {menus: {menu: {remove() {}}}, config: {editor: {readOnly: false}}}},
+ window: {siyuan: {menus: {menu: {remove() { removedMenus++; }}}, config: {editor: {readOnly: false}}}},
});
const graph = Object.assign(Object.create(exports.Graph.prototype), {
app: {}, menuRequestVersion: 0, graphElement: {isConnected: true, querySelectorAll: (): HTMLElement[] => []},
});
- return {graph, listeners, requests, menus, positions, resolveSiblings: () =>
- resolveSiblings({code: 0, data: {effectiveSortMode: 6, files: []}})};
+ return {graph, listeners, requests, menus, positions, engineOptions, removedMenus: () => removedMenus};
};
+test("graph interaction explicitly closes the shared menu", () => {
+ const {graph, engineOptions, removedMenus} = createMenuGraph();
+ graph.ensureGraphEngine();
+ engineOptions[0].onPointerDown();
+ assert.equal(removedMenus(), 1);
+});
+
test("graph document menu uses current metadata independently of the document tree display limit", async () => {
- const {graph, menus, positions, requests, listeners, resolveSiblings} = createMenuGraph();
+ const {graph, menus, positions, requests, listeners} = createMenuGraph();
const pending = graph.openGraphNodeMenu({node: {id: "doc", path: "/stale/doc.sy"}, x: 80, y: 100});
- resolveSiblings();
await pending;
assert.equal(menus.length, 1);
assert.equal(menus[0].path, "/parent/doc.sy");
- assert.equal(menus[0].childrenSortMode, 0);
- assert.equal(menus[0].customSort, true);
- assert.equal(menus[0].readonlyHistory, true);
- assert.equal(menus[0].elements.length, 0);
+ assert.equal(menus[0].disabled, true);
+ assert.equal(menus[0].from, "graph");
+ assert.equal(menus[0].protyle, undefined);
+ assert.equal(menus[0].docInfo.name, "Document");
assert.equal(JSON.stringify(positions), '[{"x":80,"y":100}]');
- assert.equal(JSON.stringify(requests[2].body),
- '{"notebook":"notebook","path":"/parent","maxListCount":1,"ignoreMaxListHint":true}');
+ assert.equal(requests.length, 2);
assert.equal(listeners.get("pointerdown").size, 0);
assert.equal(listeners.get("keydown").size, 0);
});
for (const event of ["pointerdown", "keydown"]) {
test(`graph menu requests are discarded after ${event}`, async () => {
- const {graph, menus, listeners, resolveSiblings} = createMenuGraph();
+ const {graph, menus, listeners} = createMenuGraph();
const pending = graph.openGraphNodeMenu({node: {id: "doc"}, x: 0, y: 0});
listeners.get(event).forEach(listener => listener());
- resolveSiblings();
await pending;
assert.equal(menus.length, 0);
assert.equal(listeners.get(event).size, 0);
diff --git a/app/src/layout/dock/Graph.ts b/app/src/layout/dock/Graph.ts
index 0100d4a428..43b62ee972 100644
--- a/app/src/layout/dock/Graph.ts
+++ b/app/src/layout/dock/Graph.ts
@@ -12,10 +12,10 @@ import {openGlobalSearch} from "../../search/util";
import type {App} from "../../index";
import {checkFold} from "../../util/noRelyPCFunction";
import {Editor} from "../../editor";
-import {getDocDisplayName, isEncryptedBox, pathPosix} from "../../util/pathName";
+import {getDocDisplayName, isEncryptedBox} from "../../util/pathName";
import {GraphEngine} from "./graph/GraphEngine";
import {IGraphNodeClick, IGraphNodeContextMenu, IGraphSourceLink, IGraphSourceNode} from "./graph/types";
-import {initDocumentMenu} from "../../menus/navigation";
+import {openDocumentMenu} from "../../protyle/header/documentMenu";
import {Constants} from "../../constants";
interface IGraphSearchOptions {
@@ -687,6 +687,7 @@ export class Graph extends Model {
private ensureGraphEngine() {
if (!this.graphEngine) {
this.graphEngine = new GraphEngine(this.graphElement, {
+ onPointerDown: () => window.siyuan.menus.menu.remove(),
onNodeClick: (details) => this.openGraphNode(details),
onNodeContextMenu: (details) => {
if (details.node.type !== "NodeDocument") {
@@ -778,32 +779,22 @@ export class Graph extends Model {
!info.data.box || !info.data.path || doc.data.rootID !== details.node.id) {
return;
}
- const siblings = await fetchSyncPost("/api/filetree/listDocsByPath", {
- notebook: info.data.box,
- path: pathPosix().dirname(info.data.path),
- maxListCount: 1,
- ignoreMaxListHint: true,
- }, undefined, false, abort.signal);
- if (request !== this.menuRequestVersion || !this.graphElement.isConnected || siblings.code !== 0) {
+ if (!this.graphElement.isConnected) {
return;
}
- const sortValue = doc.data.ial?.[Constants.CUSTOM_SY_SUBDOC_SORT_MODE];
- const sortMode = sortValue ? Number(sortValue) : null;
const position = {x: details.x, y: details.y};
- initDocumentMenu(this.app, {
+ openDocumentMenu({
+ app: this.app,
id: details.node.id,
notebookId: info.data.box,
path: info.data.path,
- name: doc.data.name,
- subFileCount: doc.data.subFileCount,
- childrenSortMode: Number.isInteger(sortMode) ? sortMode : null,
- customSort: siblings.data.effectiveSortMode === 6,
+ docInfo: doc.data,
target: this.graphElement,
- elements: this.graphElement.querySelectorAll<HTMLElement>(".b3-list-item"),
position,
- readonlyHistory: window.siyuan.config.editor.readOnly ||
+ from: "graph",
+ disabled: window.siyuan.config.readonly || window.siyuan.config.editor.readOnly ||
doc.data.ial?.[Constants.CUSTOM_SY_READONLY] === "true",
- }).popup(position);
+ });
} catch (error) {
if (!abort.signal.aborted) {
console.warn("Unable to open graph document menu", error);
diff --git a/app/src/layout/dock/graph/GraphEngine.test.ts b/app/src/layout/dock/graph/GraphEngine.test.ts
index f1e7612de6..bbf90c2973 100644
--- a/app/src/layout/dock/graph/GraphEngine.test.ts
+++ b/app/src/layout/dock/graph/GraphEngine.test.ts
@@ -3,6 +3,7 @@ import {readFileSync} from "node:fs";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {screenToGraph} from "./core";
const noop = () => {};
@@ -16,13 +17,13 @@ const setup = () => {
const listeners = new Map<string, (event: unknown) => void>();
const canvas = () => ({setAttribute: noop, addEventListener: noop, removeEventListener: noop, remove: noop});
runInNewContext(code, {
- exports, require: () => ({GraphLabelRenderer: class {destroy = noop;}}),
+ exports, require: () => ({GraphLabelRenderer: class {destroy = noop;}, screenToGraph}),
document: {createElement: canvas},
ResizeObserver: class {observe = noop; disconnect = noop;},
});
Object.assign(exports.GraphEngine.prototype, {
resize: noop, createRenderer: () => ({destroy: noop}), scheduleRender: noop,
- hideTooltip: noop, stopLayout: noop, resetInteraction: noop,
+ hideTooltip: noop, stopLayout: noop, resetInteraction: noop, updateCursor: noop,
});
const container = {append: noop,
getBoundingClientRect: () => ({left: 40, top: 60}),
@@ -30,7 +31,9 @@ const setup = () => {
removeEventListener: (name: string) => listeners.delete(name)};
const menus: import("./types").IGraphNodeContextMenu[] = [];
let clicks = 0;
+ let closedMenus = 0;
const engine = new exports.GraphEngine(container as unknown as HTMLElement, {
+ onPointerDown: () => { closedMenus++; },
onNodeClick: () => { clicks++; },
onNodeContextMenu: details => {
if (details.node.type !== "NodeDocument") { return false; }
@@ -49,7 +52,7 @@ const setup = () => {
preventDefault: () => { prevented = true; }, stopPropagation: () => { stopped = true; }});
return {prevented, stopped};
};
- return {state, listeners, menus, context, clicks: () => clicks};
+ return {state, listeners, menus, context, clicks: () => clicks, closedMenus: () => closedMenus};
};
test("graph context menu resolves transformed coordinates without opening or dragging the document", () => {
@@ -67,6 +70,25 @@ test("graph context menu resolves transformed coordinates without opening or dra
assert.equal(listeners.has("contextmenu"), false);
});
+test("starting a graph background interaction dismisses menus before preventing pointer defaults", () => {
+ const {listeners, closedMenus, state, clicks} = setup();
+ listeners.get("pointerdown")({pointerType: "mouse", button: 0, pointerId: 1, clientX: 500, clientY: 500,
+ preventDefault: () => { assert.equal(closedMenus(), 1); }});
+ assert.equal(state.selected, -1);
+ assert.equal(state.pointers.size, 1);
+ assert.equal(clicks(), 0);
+});
+
+test("an empty graph still dismisses menus while secondary mouse buttons do not start an interaction", () => {
+ const {listeners, closedMenus, state} = setup();
+ Object.assign(state, {data: undefined});
+ listeners.get("pointerdown")({pointerType: "mouse", button: 2});
+ assert.equal(closedMenus(), 0);
+ listeners.get("pointerdown")({pointerType: "touch", button: 0});
+ assert.equal(closedMenus(), 1);
+ assert.equal(state.pointers.size, 0);
+});
+
test("graph background and tag nodes do not receive a document context menu", () => {
const {context, menus, state} = setup();
assert.deepEqual(context(260, 290), {prevented: false, stopped: false});
diff --git a/app/src/layout/dock/graph/GraphEngine.ts b/app/src/layout/dock/graph/GraphEngine.ts
index faafb51d70..d7e7e42d2f 100644
--- a/app/src/layout/dock/graph/GraphEngine.ts
+++ b/app/src/layout/dock/graph/GraphEngine.ts
@@ -576,7 +576,11 @@ export class GraphEngine {
}
private readonly handlePointerDown = (event: PointerEvent) => {
- if (!this.data || (event.pointerType === "mouse" && event.button !== 0)) {
+ if (event.pointerType === "mouse" && event.button !== 0) {
+ return;
+ }
+ this.engineOptions.onPointerDown?.();
+ if (!this.data) {
return;
}
const pointer = this.getPointer(event);
diff --git a/app/src/layout/dock/graph/types.ts b/app/src/layout/dock/graph/types.ts
index 5314508fd3..49bc4bc50b 100644
--- a/app/src/layout/dock/graph/types.ts
+++ b/app/src/layout/dock/graph/types.ts
@@ -95,6 +95,7 @@ export interface IGraphNodeContextMenu extends Omit<IGraphNodeClick, "event"> {
export interface IGraphEngineOptions {
onNodeClick: (details: IGraphNodeClick) => void;
onNodeContextMenu?: (details: IGraphNodeContextMenu) => boolean;
+ onPointerDown?: () => void;
}
export interface IGraphSetDataOptions {
diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.ts
index fd0d031007..c15573c6a0 100644
--- a/app/src/menus/commonMenuItem.ts
+++ b/app/src/menus/commonMenuItem.ts
@@ -124,12 +124,12 @@ export const openWechatNotify = (nodeElement: Element) => {
});
};
-export const openFileWechatNotify = (protyle: IProtyle) => {
+export const openFileWechatNotify = (id: string, notebookId: string) => {
const docInfoParam: BlockQueryRequestInput = {
- id: protyle.block.rootID
+ id
};
- if (isEncryptedBox(protyle.notebookId)) {
- docInfoParam.notebook = protyle.notebookId;
+ if (isEncryptedBox(notebookId)) {
+ docInfoParam.notebook = notebookId;
}
fetchPost("/api/block/getDocInfo", docInfoParam, (response) => {
const reminder = response.data.ial[Constants.CUSTOM_REMINDER_WECHAT];
@@ -160,7 +160,7 @@ export const openFileWechatNotify = (protyle: IProtyle) => {
dialog.destroy();
});
btnsElement[1].addEventListener("click", () => {
- fetchPost("/api/block/setBlockReminder", {id: protyle.block.rootID, timed: "0"}, () => {
+ fetchPost("/api/block/setBlockReminder", {id, timed: "0"}, () => {
dialog.destroy();
});
});
@@ -172,7 +172,7 @@ export const openFileWechatNotify = (protyle: IProtyle) => {
return;
}
fetchPost("/api/block/setBlockReminder", {
- id: protyle.block.rootID,
+ id,
timed: dayjs(date).format("YYYYMMDDHHmmss")
}, () => {
dialog.destroy();
diff --git a/app/src/protyle/header/documentMenu.test.ts b/app/src/protyle/header/documentMenu.test.ts
new file mode 100644
index 0000000000..9b2b7cda9b
--- /dev/null
+++ b/app/src/protyle/header/documentMenu.test.ts
@@ -0,0 +1,219 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {posix} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {getEntryCatalogChildren} from "../../config/entryVisibility/catalog";
+
+const {parse} = require("ifdef-loader/preprocessor");
+const noop = () => {};
+
+const setup = (mobile = false, readonly = false, encrypted = false) => {
+ const items: IMenu[] = [];
+ const events: {detail: {protyle: IProtyle}, separatorPosition: string}[] = [];
+ const calls: {name: string, args: unknown[]}[] = [];
+ const attributes = new Map<string, string>();
+ const menu = {element: {classList: {contains: () => true}, getAttribute: (key: string) => attributes.get(key),
+ setAttribute: (key: string, value: string) => attributes.set(key, value)},
+ remove: () => { items.length = 0; }, append: (item: IMenu) => { if (item && !item.ignore) { items.push(item); } },
+ popup: noop, fullscreen: noop};
+ const record = (name: string) => (...args: unknown[]) => { calls.push({name, args}); };
+ const docInfo: import("../../types/api").DocInfo = {
+ id: "20261006112233-abcdefg", rootID: "20261006112233-abcdefg", name: "Document", icon: "", subFileCount: 2,
+ refCount: 0, refIDs: [], attrViews: [], ial: {id: "20261006112233-abcdefg", updated: "20261006123344"},
+ };
+ const keymaps = Object.fromEntries(["outline", "backlinks", "graphView", "attr", "spaceRepetition", "quickMakeCard",
+ "search", "addToDatabase"].map(key => [key, {custom: ""}]));
+ const app = {} as Parameters<typeof import("./documentMenu").openDocumentMenu>[0]["app"];
+ const target = {getAttribute: (): null => null} as unknown as HTMLElement;
+ const lute = {BlockDOM2HTML: (source: string) => "html:" + source};
+ const cardData: {cards: unknown[], unreviewedCount: number} = {cards: [], unreviewedCount: 0};
+ const globals = {window: {siyuan: {menus: {menu}, languages: {}, isPublish: false,
+ config: {readonly, cloudRegion: 0, flashcard: {deck: true}, system: {dataDir: "/data"},
+ keymap: {general: keymaps, editor: {general: keymaps}}}}}, getSelection: () => ({rangeCount: 0})};
+ const dependencies: Record<string, unknown> = {
+ "../../menus/Menu": {MenuItem: class {element: IMenu; constructor(item: IMenu) { this.element = item; }}},
+ "../../menus/commonMenuItem": {copySubMenu: (...args: unknown[]) => {
+ record("copySubMenu")(...args); return [{id: "copyID"}];
+ }, exportMd: () => ({id: "export"}), movePathToMenu: (...args: unknown[]) => {
+ record("move")(...args); return {id: "move"};
+ }, openFileAttr: record("attr"), openFileWechatNotify: record("wechatReminder")},
+ "../../editor/deleteFile": {deleteFile: record("delete")},
+ "../util/compatibility": {updateHotkeyTip: () => "", writeClipboardData: async (...args: unknown[]) => {
+ record("clipboard")(...args); return {status: "success"};
+ }},
+ "../../layout/dock/util": {openOutline: record("outline"), openBacklink: record("backlinks"), openGraph: record("graphView")},
+ "../../util/pathName": {isEncryptedBox: () => encrypted, pathPosix: () => posix,
+ getNotebookName: () => "Notebook", getDisplayName: (value: string) => value.replace(/\.sy$/, ""), useShell: record("folder")},
+ "../../card/makeCard": {makeCard: record("makeCard"), quickMakeCard: record("quickMakeCard")},
+ "../../card/openCard": {openCardByData: record("spaceRepetition")},
+ "../../card/viewCards": {viewCards: record("manage")},
+ "../../plugin/EventBus": {emitOpenMenu: (event: typeof events[number]) => {
+ events.push(event); menu.append({id: "plugin"}); menu.append({id: "separator_pluginBottom", type: "separator"});
+ }},
+ "../../search/spread": {openSearch: record("search")},
+ "../../mobile/menu/search": {popSearch: record("search")},
+ "../../history/doc": {openDocHistory: record("history")},
+ "../../window/openNewWindow": {openNewWindowById: record("newWindow")},
+ "../../menus/block": {transferBlockRef: (id: string) => {
+ menu.append({id: "transferBlockRef", click: () => { record("transferBlockRef")(id); }});
+ }},
+ "../render/av/addToDatabase": {addBlocksToDatabase: record("database"), addEditorToDatabase: record("editorDatabase")},
+ "../../editor/util": {openFileById: record("open")},
+ "../../mobile/editor": {openMobileFileById: record("open")},
+ "../util/hasClosest": {hasTopClosestByClassName: (): null => null},
+ "../../util/functions": {isMobile: () => mobile},
+ "../../dialog/tooltip": {hideTooltip: noop},
+ "../../dialog/message": {showMessage: noop},
+ "../render/setLute": {getLute: () => lute},
+ "../util/blockDOMClipboard": {buildBlockDOMClipboardRichData: (parser: typeof lute, source: string) =>
+ ({textHTML: parser.BlockDOM2HTML(source), textSiyuan: "sy:" + source})},
+ "../util/clipboardData": {buildWebClipboardHTML: (html: string) => "web:" + html},
+ "../export/util": {exportImage: record("copyAsPNG")},
+ "../wysiwyg/transaction": {transaction: record("transaction")},
+ "../../util/hostCapabilities": {getHostCapabilities: () => ({documentImportExport: true, localFileSystem: true})},
+ "../../constants": {Constants: {MENU_TITLE: "title", CUSTOM_RIFF_DECKS: "decks", QUICK_DECK_ID: "quick", DIALOG_SEARCH: "search"}},
+ "../../util/fetch": {
+ fetchPost: (url: string, body: unknown, callback: (response: unknown) => void) => {
+ record("fetchPost")(url, body);
+ callback({code: 0, data: url.endsWith("getDocInfo") ? docInfo :
+ url.endsWith("getTreeRiffDueCards") ? cardData : "/Document"});
+ },
+ fetchSyncPost: async (url: string, body: unknown) => {
+ record("fetchSyncPost")(url, body);
+ return {code: 0, data: url.endsWith("getBlockDOM") ? {dom: "Document DOM"} :
+ url.endsWith("getHPathByPath") ? "/Document" : {content: "Document Markdown"}};
+ },
+ },
+ path: posix,
+ dayjs: (value: string) => ({format: () => value}),
+ };
+ const load = (file: string) => {
+ const exports = {};
+ runInNewContext(transpileModule(parse(readFileSync("src/protyle/header/" + file + ".ts", "utf8"),
+ {MOBILE: mobile, BROWSER: mobile}, false, true, file), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {exports, require: (name: string) => dependencies[name] || {}, ...globals});
+ return exports;
+ };
+ const documentModule = load("documentMenu") as typeof import("./documentMenu");
+ dependencies["./documentMenu"] = documentModule;
+ const titleModule = load("openTitleMenu") as typeof import("./openTitleMenu");
+ const options: Parameters<typeof documentModule.openDocumentMenu>[0] = {
+ app, id: docInfo.id, notebookId: "notebook", path: "/parent/document.sy", docInfo, target,
+ position: {x: 60, y: 90}, from: "graph", disabled: readonly,
+ };
+ const click = async (id: string) => {
+ const item = items.find(item => item.id === id) || (items.find(item => item.id === "copy").submenu as IMenu[])
+ .find(item => item.id === id);
+ assert.ok(item, id);
+ await item.click(null, null);
+ };
+ return {documentModule, titleModule, options, items, events, calls, attributes, cardData, lute, click,
+ open: (overrides: Partial<typeof options> = {}) => documentModule.openDocumentMenu({...options, ...overrides})};
+};
+
+test("graph document menus share editor menu identities and order instead of document tree entries", () => {
+ const menu = setup();
+ menu.open();
+ const expected = getEntryCatalogChildren("document.title").map(item => item.key);
+ assert.deepEqual(menu.items.map(item => item.id), expected);
+ assert.equal(menu.attributes.get("data-name"), "title");
+ assert.equal(menu.attributes.get("data-from"), "app-graph");
+ assert.ok(!menu.items.some(item => ["newSiblingDoc", "rename", "pinDoc", "sort", "replace", "import"].includes(item.id)));
+ assert.equal(menu.events.length, 0);
+ const timestamps = menu.items.find(item => item.id === "updateAndCreatedAt");
+ assert.ok(timestamps.label.includes("20261006123344"));
+ assert.ok(timestamps.label.includes("20261006112233"));
+});
+
+test("graph document actions target the selected document without opening an editor", async () => {
+ const menu = setup();
+ menu.open();
+ await menu.click("outline");
+ await menu.click("backlinks");
+ await menu.click("graphView");
+ for (const name of ["outline", "backlinks", "graphView"]) {
+ const action = menu.calls.find(call => call.name === name).args[0] as {rootId: string, title: string};
+ assert.equal(action.rootId, menu.options.id);
+ assert.equal(action.title, "Document");
+ }
+ await menu.click("addToDatabase");
+ const database = menu.calls.find(call => call.name === "database");
+ assert.equal(JSON.stringify(database.args[0]), JSON.stringify([menu.options.id]));
+ assert.equal(database.args[1], menu.options.target);
+ assert.equal(database.args[2], menu.options.position);
+ await menu.click("delete");
+ assert.deepEqual(menu.calls.find(call => call.name === "delete").args, ["notebook", "/parent/document.sy"]);
+ await menu.click("wechatReminder");
+ assert.deepEqual(menu.calls.find(call => call.name === "wechatReminder").args, [menu.options.id, "notebook"]);
+ await menu.click("transferBlockRef");
+ assert.deepEqual(menu.calls.find(call => call.name === "transferBlockRef").args, [menu.options.id]);
+ assert.ok(!menu.calls.some(call => call.name === "open"));
+});
+
+test("copying a closed document uses the shared parser and retains Markdown and rich clipboard content", async () => {
+ const menu = setup();
+ menu.open();
+ await menu.click("copyDoc");
+ const clipboard = menu.calls.find(call => call.name === "clipboard").args[0] as {textPlain: string, textHTML: string};
+ assert.equal(clipboard.textPlain, "Document Markdown");
+ assert.equal(clipboard.textHTML, "web:html:Document DOM");
+ const request = menu.calls.find(call => call.name === "fetchSyncPost" && call.args[0] === "/api/block/getBlockDOM");
+ assert.equal((request.args[1] as {id: string}).id, menu.options.id);
+});
+
+test("graph flashcards keep response data and use document IDs with reversible operations", async () => {
+ const menu = setup();
+ menu.open();
+ const cardItems = menu.items.find(item => item.id === "riffCard").submenu as IMenu[];
+ await cardItems.find(item => item.id === "spaceRepetition").click(null, null);
+ assert.equal(menu.calls.find(call => call.name === "spaceRepetition").args[1], menu.cardData);
+ await cardItems.find(item => item.id === "manage").click(null, null);
+ assert.equal(menu.calls.find(call => call.name === "manage").args[2], "Notebook/Document");
+ await cardItems.find(item => item.id === "quickMakeCard").click(null, null);
+ const transaction = menu.calls.find(call => call.name === "transaction");
+ assert.equal(JSON.stringify(transaction.args[1]), JSON.stringify([{action: "addFlashcards", deckID: "quick", blockIDs: [menu.options.id]}]));
+ assert.equal(JSON.stringify(transaction.args[2]), JSON.stringify([{action: "removeFlashcards", deckID: "quick", blockIDs: [menu.options.id]}]));
+});
+
+for (const mobile of [false, true]) {
+ test(`editor title menus retain actual editor context and plugin extensions (${mobile ? "mobile" : "desktop"})`, async () => {
+ const menu = setup(mobile);
+ const protyle = {app: menu.options.app, notebookId: "notebook", path: menu.options.path, disabled: false,
+ block: {rootID: menu.options.id, id: "heading", showAll: true},
+ element: menu.options.target, options: {history: {}, render: {title: true}},
+ title: {editElement: {textContent: "Editor title"}}, lute: menu.lute,
+ } as unknown as IProtyle;
+ menu.titleModule.openTitleMenu(protyle, menu.options.position, "editor");
+ assert.equal(menu.events[0].detail.protyle, protyle);
+ assert.equal(menu.events[0].separatorPosition, "bottom");
+ assert.equal(menu.attributes.get("data-from"), "app-editor");
+ await menu.click("addToDatabase");
+ assert.equal(menu.calls.find(call => call.name === "editorDatabase").args[0], protyle);
+ await menu.click("copyAsPNG");
+ assert.deepEqual(menu.calls.find(call => call.name === "copyAsPNG").args, ["heading", true]);
+ const keys = menu.items.map(item => item.id);
+ assert.ok(keys.indexOf("separator_4") < keys.indexOf("plugin"));
+ assert.ok(keys.indexOf("plugin") < keys.indexOf("updateAndCreatedAt"));
+ });
+}
+
+test("locked graph documents retain viewing history while respecting editor mutation restrictions", async () => {
+ const menu = setup();
+ menu.open({disabled: true});
+ assert.ok(!menu.items.some(item => ["move", "addToDatabase", "delete", "transferBlockRef"].includes(item.id)));
+ await menu.click("fileHistory");
+ assert.equal((menu.calls.find(call => call.name === "history").args[0] as {readonly: boolean}).readonly, true);
+});
+
+test("workspace readonly and encrypted documents preserve existing history and notebook-boundary rules", () => {
+ const readonly = setup(false, true);
+ readonly.open();
+ assert.ok(!readonly.items.some(item => ["fileHistory", "wechatReminder", "riffCard", "delete"].includes(item.id)));
+ const encrypted = setup(false, false, true);
+ encrypted.open();
+ assert.equal(JSON.stringify(encrypted.calls.find(call => call.name === "move").args[1]), '["notebook"]');
+ assert.ok(!encrypted.items.some(item => item.id === "riffCard"));
+});
diff --git a/app/src/protyle/header/documentMenu.ts b/app/src/protyle/header/documentMenu.ts
new file mode 100644
index 0000000000..030828325a
--- /dev/null
+++ b/app/src/protyle/header/documentMenu.ts
@@ -0,0 +1,414 @@
+import type {DocInfo} from "../../types/api";
+import type {App} from "../../index";
+import {fetchPost, fetchSyncPost} from "../../util/fetch";
+import {MenuItem} from "../../menus/Menu";
+import {copySubMenu, exportMd, movePathToMenu, openFileAttr, openFileWechatNotify,} from "../../menus/commonMenuItem";
+import {deleteFile} from "../../editor/deleteFile";
+import {updateHotkeyTip, writeClipboardData} from "../util/compatibility";
+/// #if !MOBILE
+import {openBacklink, openGraph, openOutline} from "../../layout/dock/util";
+import * as path from "path";
+/// #else
+import {openMobileFileById} from "../../mobile/editor";
+/// #endif
+import {Constants} from "../../constants";
+import {openCardByData} from "../../card/openCard";
+import {viewCards} from "../../card/viewCards";
+import {getDisplayName, getNotebookName, isEncryptedBox, pathPosix, useShell} from "../../util/pathName";
+import {makeCard, quickMakeCard} from "../../card/makeCard";
+import {emitOpenMenu} from "../../plugin/EventBus";
+import * as dayjs from "dayjs";
+import {popSearch} from "../../mobile/menu/search";
+import {openSearch} from "../../search/spread";
+import {openDocHistory} from "../../history/doc";
+import {openNewWindowById} from "../../window/openNewWindow";
+import {transferBlockRef} from "../../menus/block";
+import {addBlocksToDatabase, addEditorToDatabase} from "../render/av/addToDatabase";
+import {openFileById} from "../../editor/util";
+import {hasTopClosestByClassName} from "../util/hasClosest";
+import {showMessage} from "../../dialog/message";
+import {buildBlockDOMClipboardRichData} from "../util/blockDOMClipboard";
+import {buildWebClipboardHTML} from "../util/clipboardData";
+import {exportImage} from "../export/util";
+import {getHostCapabilities} from "../../util/hostCapabilities";
+import {getLute} from "../render/setLute";
+import {transaction} from "../wysiwyg/transaction";
+
+export const openDocumentMenu = (options: {
+ app: App,
+ id: string,
+ notebookId: string,
+ path: string,
+ docInfo: DocInfo,
+ target: HTMLElement,
+ position: IPosition,
+ from: string,
+ disabled: boolean,
+ protyle?: IProtyle,
+ blockId?: string,
+ showAll?: boolean,
+ restoreKeyboard?: () => void,
+}) => {
+ const {app, id, notebookId, path: pathString, docInfo, target, position, from, disabled,
+ protyle, blockId = id, showAll = false, restoreKeyboard} = options;
+ const contentID = showAll ? blockId : id;
+ window.siyuan.menus.menu.remove();
+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_TITLE);
+ const isBoxDoc = notebookId === id;
+ const popoverElement = hasTopClosestByClassName(target, "block__popover", true);
+ window.siyuan.menus.menu.element.setAttribute("data-from", popoverElement ? popoverElement.dataset.level + "popover-" + from : "app-" + from);
+ const submenu = copySubMenu([id], true, undefined, contentID);
+ submenu.push({
+ id: "copyAsPNG",
+ iconHTML: "",
+ label: window.siyuan.languages.copyAsPNG,
+ ignore: !getHostCapabilities().documentImportExport,
+ click() {
+ exportImage(contentID, true);
+ }
+ });
+ submenu.push({
+ id: "copyDoc",
+ iconHTML: "",
+ label: window.siyuan.languages.copyDoc,
+ accelerator: undefined,
+ click: async () => {
+ const [responseHTML, responseText] = await Promise.all([
+ fetchSyncPost("/api/block/getBlockDOM", {
+ id,
+ notebook: notebookId,
+ }),
+ fetchSyncPost("/api/export/exportMdContent", {
+ id,
+ refMode: 3,
+ embedMode: 1,
+ yfm: false,
+ fillCSSVar: false,
+ adjustHeadingLevel: false
+ })
+ ]);
+
+ if (responseHTML.code !== 0 || responseText.code !== 0) {
+ return;
+ }
+ const lute = protyle?.lute || getLute({
+ emojis: {}, emojiSite: "/emojis", headingAnchor: false,
+ sanitize: true, listStyle: false, paragraphBeginningSpace: false,
+ });
+ const {textHTML, textSiyuan} = buildBlockDOMClipboardRichData(lute, responseHTML.data.dom);
+ const result = await writeClipboardData({
+ textPlain: responseText.data.content,
+ textHTML: buildWebClipboardHTML(textHTML, textSiyuan),
+ });
+ if (result.error) {
+ console.log("Write document clipboard error:", result.error);
+ }
+ if (result.status === "failed") {
+ showMessage(window.siyuan.languages.clipboardPermissionDenied, 7000, "error");
+ return;
+ }
+
+ showMessage(window.siyuan.languages.copied);
+ }
+ });
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "copy",
+ label: window.siyuan.languages.copy,
+ icon: "iconCopy",
+ type: "submenu",
+ submenu,
+ }).element);
+ if (!disabled) {
+ if (!isBoxDoc) {
+ window.siyuan.menus.menu.append(movePathToMenu([pathString], [notebookId]));
+ }
+ const range = getSelection().rangeCount > 0 ? getSelection().getRangeAt(0) : undefined;
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "addToDatabase",
+ label: window.siyuan.languages.addToDatabase,
+ accelerator: window.siyuan.config.keymap.general.addToDatabase.custom,
+ icon: "iconDatabase",
+ click: () => {
+ if (protyle) {
+ addEditorToDatabase(protyle, range, "title");
+ } else {
+ addBlocksToDatabase([id], target, position);
+ }
+ }
+ }).element);
+ if (!isBoxDoc) {
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "delete",
+ icon: "iconTrashcan",
+ label: window.siyuan.languages.delete,
+ click: () => {
+ deleteFile(notebookId, pathString);
+ }
+ }).element);
+ }
+ }
+ /// #if !MOBILE
+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "outline",
+ icon: "iconOutline",
+ label: window.siyuan.languages.outline,
+ accelerator: window.siyuan.config.keymap.editor.general.outline.custom,
+ click: () => {
+ openOutline({
+ app,
+ rootId: id,
+ notebookId,
+ title: protyle ? (protyle.options.render.title ?
+ (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : "") : docInfo.name,
+ isPreview: protyle ? !protyle.preview.element.classList.contains("fn__none") : false,
+ });
+ }
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "backlinks",
+ icon: "iconLink",
+ label: window.siyuan.languages.backlinks,
+ accelerator: window.siyuan.config.keymap.editor.general.backlinks.custom,
+ click: () => {
+ openBacklink({
+ app,
+ blockId,
+ rootId: id,
+ notebookId,
+ useBlockId: showAll,
+ title: protyle ? (protyle.title ?
+ (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : null) : docInfo.name,
+ });
+ }
+ }).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "graphView",
+ icon: "iconGraph",
+ label: window.siyuan.languages.graphView,
+ accelerator: window.siyuan.config.keymap.editor.general.graphView.custom,
+ click: () => {
+ openGraph({
+ app,
+ blockId,
+ rootId: id,
+ notebookId,
+ useBlockId: showAll,
+ title: protyle ? (protyle.title ?
+ (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : null) : docInfo.name,
+ });
+ }
+ }).element);
+ /// #endif
+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "attr",
+ label: window.siyuan.languages.attr,
+ icon: "iconAttr",
+ accelerator: window.siyuan.config.keymap.editor.general.attr.custom + "/" + updateHotkeyTip("⇧" + window.siyuan.languages.click),
+ click() {
+ openFileAttr(docInfo.ial, "bookmark", protyle);
+ }
+ }).element);
+ if (!window.siyuan.config.readonly) {
+ if (window.siyuan.config.cloudRegion === 0) {
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "wechatReminder",
+ label: window.siyuan.languages.wechatReminder,
+ icon: "iconMp",
+ click() {
+ openFileWechatNotify(id, notebookId);
+ }
+ }).element);
+ }
+ const isCardMade = !!docInfo.ial[Constants.CUSTOM_RIFF_DECKS];
+ if (!isEncryptedBox(notebookId)) {
+ const riffCardMenu: IMenu[] = [{
+ id: "spaceRepetition",
+ iconHTML: "",
+ label: window.siyuan.languages.spaceRepetition,
+ accelerator: window.siyuan.config.keymap.editor.general.spaceRepetition.custom,
+ click: () => {
+ fetchPost("/api/riff/getTreeRiffDueCards", {rootID: id}, (response) => {
+ openCardByData(app, response.data, "doc", id);
+ });
+ }
+ }, {
+ id: "manage",
+ iconHTML: "",
+ label: window.siyuan.languages.manage,
+ click: () => {
+ fetchPost("/api/filetree/getHPathByID", {
+ id
+ }, (response) => {
+ viewCards(app, id, pathPosix().join(getNotebookName(notebookId), response.data), "Tree");
+ });
+ }
+ }, {
+ id: isCardMade ? "removeCard" : "quickMakeCard",
+ iconHTML: "",
+ label: isCardMade ? window.siyuan.languages.removeCard : window.siyuan.languages.quickMakeCard,
+ accelerator: window.siyuan.config.keymap.editor.general.quickMakeCard.custom,
+ click: () => {
+ if (!protyle) {
+ const remove = (docInfo.ial[Constants.CUSTOM_RIFF_DECKS] || "").includes(Constants.QUICK_DECK_ID);
+ transaction(undefined, [{
+ action: remove ? "removeFlashcards" : "addFlashcards",
+ deckID: Constants.QUICK_DECK_ID,
+ blockIDs: [id],
+ }], [{
+ action: remove ? "addFlashcards" : "removeFlashcards",
+ deckID: Constants.QUICK_DECK_ID,
+ blockIDs: [id],
+ }]);
+ return;
+ }
+ let titleElement = protyle.title?.element;
+ if (!titleElement) {
+ titleElement = document.createElement("div");
+ titleElement.setAttribute("data-node-id", id);
+ titleElement.setAttribute(Constants.CUSTOM_RIFF_DECKS, docInfo.ial[Constants.CUSTOM_RIFF_DECKS]);
+ }
+ quickMakeCard(protyle, [titleElement]);
+ }
+ }];
+ if (window.siyuan.config.flashcard.deck) {
+ riffCardMenu.push({
+ id: "addToDeck",
+ iconHTML: "",
+ label: window.siyuan.languages.addToDeck,
+ click: () => {
+ makeCard(app, [id]);
+ }
+ });
+ }
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "riffCard",
+ label: window.siyuan.languages.riffCard,
+ type: "submenu",
+ icon: "iconRiffCard",
+ submenu: riffCardMenu,
+ }).element);
+ }
+ }
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "search",
+ label: window.siyuan.languages.search,
+ icon: "iconSearch",
+ accelerator: window.siyuan.config.keymap.general.search.custom,
+ async click() {
+ const searchPath = isBoxDoc ? "" : getDisplayName(pathString, false, true);
+ /// #if MOBILE
+ let hPath = getNotebookName(notebookId);
+ if (!isBoxDoc) {
+ const pathResponse = await fetchSyncPost("/api/filetree/getHPathByPath", {
+ notebook: notebookId,
+ path: searchPath + ".sy"
+ });
+ if (pathResponse.code !== 0) {
+ return;
+ }
+ hPath = pathPosix().join(hPath, pathResponse.data);
+ }
+ popSearch(app, {
+ hasReplace: false,
+ hPath,
+ idPath: [isBoxDoc ? notebookId : pathPosix().join(notebookId, searchPath)],
+ page: 1,
+ });
+ /// #else
+ openSearch({
+ app,
+ hotkey: Constants.DIALOG_SEARCH,
+ notebookId,
+ searchPath
+ });
+ /// #endif
+ }
+ }).element);
+ if (!disabled) {
+ transferBlockRef(id);
+ }
+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_3", type: "separator"}).element);
+ if (!protyle?.model) {
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "openBy",
+ label: window.siyuan.languages.openBy,
+ icon: "iconOpen",
+ click() {
+ /// #if !MOBILE
+ openFileById({
+ app,
+ id: blockId,
+ action: id !== blockId ? [Constants.CB_GET_ALL, Constants.CB_GET_FOCUS] : [Constants.CB_GET_CONTEXT],
+ });
+ /// #else
+ openMobileFileById(app, blockId, id !== blockId ? [Constants.CB_GET_ALL] : [Constants.CB_GET_CONTEXT]);
+ /// #endif
+ }
+ }).element);
+ }
+ /// #if !BROWSER
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "openByNewWindow",
+ label: window.siyuan.languages.openByNewWindow,
+ icon: "iconOpenWindow",
+ click() {
+ openNewWindowById(id);
+ }
+ }).element);
+ if (getHostCapabilities().localFileSystem) {
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "showInFolder",
+ icon: "iconFolder",
+ label: window.siyuan.languages.showInFolder,
+ click: () => {
+ useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, notebookId, pathString));
+ }
+ }).element);
+ }
+ /// #endif
+ if (!window.siyuan.config.readonly && !window.siyuan.isPublish &&
+ !protyle?.options.history?.created && !protyle?.options.history?.snapshot &&
+ target.getAttribute("disabled-forever") !== "true") {
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "fileHistory",
+ label: window.siyuan.languages.dataHistory,
+ icon: "iconHistory",
+ click() {
+ openDocHistory({
+ app,
+ id,
+ notebookId,
+ pathString: docInfo.name,
+ readonly: disabled,
+ });
+ }
+ }).element);
+ }
+ window.siyuan.menus.menu.append(exportMd(contentID));
+
+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_4", type: "separator"}).element);
+ if (protyle) {
+ emitOpenMenu({
+ type: "click-editortitleicon",
+ detail: {
+ protyle,
+ data: docInfo,
+ },
+ separatorPosition: "bottom",
+ });
+ }
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "updateAndCreatedAt",
+ iconHTML: "",
+ type: "readonly",
+ // 不能换行,否则移动端间距过大
+ label: `${window.siyuan.languages.modifiedAt} ${dayjs(docInfo.ial.updated).format("YYYY-MM-DD HH:mm:ss")}<br>${window.siyuan.languages.createdAt} ${dayjs(docInfo.ial.id.substr(0, 14)).format("YYYY-MM-DD HH:mm:ss")}`
+ }).element);
+ /// #if MOBILE
+ window.siyuan.menus.menu.fullscreen("all", restoreKeyboard);
+ /// #else
+ window.siyuan.menus.menu.popup(position);
+ /// #endif
+};
diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.ts
index dbc4cd64b8..8fa7711897 100644
--- a/app/src/protyle/header/openTitleMenu.ts
+++ b/app/src/protyle/header/openTitleMenu.ts
@@ -1,37 +1,10 @@
import type {BlockQueryRequestInput} from "../../types/api";
-import {fetchPost, fetchSyncPost} from "../../util/fetch";
-import {MenuItem} from "../../menus/Menu";
-import {copySubMenu, exportMd, movePathToMenu, openFileAttr, openFileWechatNotify,} from "../../menus/commonMenuItem";
-import {deleteFile} from "../../editor/deleteFile";
-import {updateHotkeyTip, writeClipboardData} from "../util/compatibility";
-/// #if !MOBILE
-import {openBacklink, openGraph, openOutline} from "../../layout/dock/util";
-import * as path from "path";
-/// #else
-import {openMobileFileById} from "../../mobile/editor";
-/// #endif
+import {fetchPost} from "../../util/fetch";
import {Constants} from "../../constants";
-import {openCardByData} from "../../card/openCard";
-import {viewCards} from "../../card/viewCards";
-import {getDisplayName, getNotebookName, isEncryptedBox, pathPosix, useShell} from "../../util/pathName";
-import {makeCard, quickMakeCard} from "../../card/makeCard";
-import {emitOpenMenu} from "../../plugin/EventBus";
-import * as dayjs from "dayjs";
import {hideTooltip} from "../../dialog/tooltip";
-import {popSearch} from "../../mobile/menu/search";
-import {openSearch} from "../../search/spread";
-import {openDocHistory} from "../../history/doc";
-import {openNewWindowById} from "../../window/openNewWindow";
-import {transferBlockRef} from "../../menus/block";
-import {addEditorToDatabase} from "../render/av/addToDatabase";
-import {openFileById} from "../../editor/util";
-import {hasTopClosestByClassName} from "../util/hasClosest";
-import {showMessage} from "../../dialog/message";
-import {buildBlockDOMClipboardRichData} from "../util/blockDOMClipboard";
-import {buildWebClipboardHTML} from "../util/clipboardData";
-import {exportImage} from "../export/util";
-import {getHostCapabilities} from "../../util/hostCapabilities";
+import {isEncryptedBox} from "../../util/pathName";
import {isMobile} from "../../util/functions";
+import {openDocumentMenu} from "./documentMenu";
export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: string, restoreKeyboard?: () => void) => {
hideTooltip();
@@ -51,340 +24,23 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: stri
docInfoParam.notebook = protyle.notebookId;
}
fetchPost("/api/block/getDocInfo", docInfoParam, (response) => {
- window.siyuan.menus.menu.remove();
- window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_TITLE);
- const isBoxDoc = protyle.notebookId === protyle.block.rootID;
- const popoverElement = hasTopClosestByClassName(protyle.element, "block__popover", true);
- window.siyuan.menus.menu.element.setAttribute("data-from", popoverElement ? popoverElement.dataset.level + "popover-" + from : "app-" + from);
- const submenu = copySubMenu([protyle.block.rootID], true, undefined, protyle.block.showAll ? protyle.block.id : protyle.block.rootID);
- submenu.push({
- id: "copyAsPNG",
- iconHTML: "",
- label: window.siyuan.languages.copyAsPNG,
- ignore: !getHostCapabilities().documentImportExport,
- click() {
- exportImage(protyle.block.showAll ? protyle.block.id : protyle.block.rootID, true);
- }
+ if (response.code !== 0 || !response.data) {
+ return;
+ }
+ openDocumentMenu({
+ app: protyle.app,
+ id: protyle.block.rootID,
+ notebookId: protyle.notebookId,
+ path: protyle.path,
+ docInfo: response.data,
+ target: protyle.element,
+ position,
+ from,
+ disabled: protyle.disabled,
+ protyle,
+ blockId: protyle.block.id,
+ showAll: protyle.block.showAll,
+ restoreKeyboard,
});
- submenu.push({
- id: "copyDoc",
- iconHTML: "",
- label: window.siyuan.languages.copyDoc,
- accelerator: undefined,
- click: async () => {
- const [responseHTML, responseText] = await Promise.all([
- fetchSyncPost("/api/block/getBlockDOM", {
- id: protyle.block.rootID,
- notebook: protyle.notebookId,
- }),
- fetchSyncPost("/api/export/exportMdContent", {
- id: protyle.block.rootID,
- refMode: 3,
- embedMode: 1,
- yfm: false,
- fillCSSVar: false,
- adjustHeadingLevel: false
- })
- ]);
-
- if (responseHTML.code !== 0 || responseText.code !== 0) {
- return;
- }
- const {textHTML, textSiyuan} = buildBlockDOMClipboardRichData(protyle.lute, responseHTML.data.dom);
- const result = await writeClipboardData({
- textPlain: responseText.data.content,
- textHTML: buildWebClipboardHTML(textHTML, textSiyuan),
- });
- if (result.error) {
- console.log("Write document clipboard error:", result.error);
- }
- if (result.status === "failed") {
- showMessage(window.siyuan.languages.clipboardPermissionDenied, 7000, "error");
- return;
- }
-
- showMessage(window.siyuan.languages.copied);
- }
- });
- window.siyuan.menus.menu.append(new MenuItem({
- id: "copy",
- label: window.siyuan.languages.copy,
- icon: "iconCopy",
- type: "submenu",
- submenu,
- }).element);
- if (!protyle.disabled) {
- if (!isBoxDoc) {
- window.siyuan.menus.menu.append(movePathToMenu([protyle.path]));
- }
- const range = getSelection().rangeCount > 0 ? getSelection().getRangeAt(0) : undefined;
- window.siyuan.menus.menu.append(new MenuItem({
- id: "addToDatabase",
- label: window.siyuan.languages.addToDatabase,
- accelerator: window.siyuan.config.keymap.general.addToDatabase.custom,
- icon: "iconDatabase",
- click: () => {
- addEditorToDatabase(protyle, range, "title");
- }
- }).element);
- if (!isBoxDoc) {
- window.siyuan.menus.menu.append(new MenuItem({
- id: "delete",
- icon: "iconTrashcan",
- label: window.siyuan.languages.delete,
- click: () => {
- deleteFile(protyle.notebookId, protyle.path);
- }
- }).element);
- }
- }
- /// #if !MOBILE
- window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);
- window.siyuan.menus.menu.append(new MenuItem({
- id: "outline",
- icon: "iconOutline",
- label: window.siyuan.languages.outline,
- accelerator: window.siyuan.config.keymap.editor.general.outline.custom,
- click: () => {
- openOutline({
- app: protyle.app,
- rootId: protyle.block.rootID,
- notebookId: protyle.notebookId,
- title: protyle.options.render.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : "",
- isPreview: !protyle.preview.element.classList.contains("fn__none")
- });
- }
- }).element);
- window.siyuan.menus.menu.append(new MenuItem({
- id: "backlinks",
- icon: "iconLink",
- label: window.siyuan.languages.backlinks,
- accelerator: window.siyuan.config.keymap.editor.general.backlinks.custom,
- click: () => {
- openBacklink({
- app: protyle.app,
- blockId: protyle.block.id,
- rootId: protyle.block.rootID,
- notebookId: protyle.notebookId,
- useBlockId: protyle.block.showAll,
- title: protyle.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : null
- });
- }
- }).element);
- window.siyuan.menus.menu.append(new MenuItem({
- id: "graphView",
- icon: "iconGraph",
- label: window.siyuan.languages.graphView,
- accelerator: window.siyuan.config.keymap.editor.general.graphView.custom,
- click: () => {
- openGraph({
- app: protyle.app,
- blockId: protyle.block.id,
- rootId: protyle.block.rootID,
- notebookId: protyle.notebookId,
- useBlockId: protyle.block.showAll,
- title: protyle.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : null
- });
- }
- }).element);
- /// #endif
- window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);
- window.siyuan.menus.menu.append(new MenuItem({
- id: "attr",
- label: window.siyuan.languages.attr,
- icon: "iconAttr",
- accelerator: window.siyuan.config.keymap.editor.general.attr.custom + "/" + updateHotkeyTip("⇧" + window.siyuan.languages.click),
- click() {
- openFileAttr(response.data.ial, "bookmark", protyle);
- }
- }).element);
- if (!window.siyuan.config.readonly) {
- if (window.siyuan.config.cloudRegion === 0) {
- window.siyuan.menus.menu.append(new MenuItem({
- id: "wechatReminder",
- label: window.siyuan.languages.wechatReminder,
- icon: "iconMp",
- click() {
- openFileWechatNotify(protyle);
- }
- }).element);
- }
- const isCardMade = !!response.data.ial[Constants.CUSTOM_RIFF_DECKS];
- if (!isEncryptedBox(protyle.notebookId)) {
- const riffCardMenu: IMenu[] = [{
- id: "spaceRepetition",
- iconHTML: "",
- label: window.siyuan.languages.spaceRepetition,
- accelerator: window.siyuan.config.keymap.editor.general.spaceRepetition.custom,
- click: () => {
- fetchPost("/api/riff/getTreeRiffDueCards", {rootID: protyle.block.rootID}, (response) => {
- openCardByData(protyle.app, response.data, "doc", protyle.block.rootID);
- });
- }
- }, {
- id: "manage",
- iconHTML: "",
- label: window.siyuan.languages.manage,
- click: () => {
- fetchPost("/api/filetree/getHPathByID", {
- id: protyle.block.rootID
- }, (response) => {
- viewCards(protyle.app, protyle.block.rootID, pathPosix().join(getNotebookName(protyle.notebookId), (response.data)), "Tree");
- });
- }
- }, {
- id: isCardMade ? "removeCard" : "quickMakeCard",
- iconHTML: "",
- label: isCardMade ? window.siyuan.languages.removeCard : window.siyuan.languages.quickMakeCard,
- accelerator: window.siyuan.config.keymap.editor.general.quickMakeCard.custom,
- click: () => {
- let titleElement = protyle.title?.element;
- if (!titleElement) {
- titleElement = document.createElement("div");
- titleElement.setAttribute("data-node-id", protyle.block.rootID);
- titleElement.setAttribute(Constants.CUSTOM_RIFF_DECKS, response.data.ial[Constants.CUSTOM_RIFF_DECKS]);
- }
- quickMakeCard(protyle, [titleElement]);
- }
- }];
- if (window.siyuan.config.flashcard.deck) {
- riffCardMenu.push({
- id: "addToDeck",
- iconHTML: "",
- label: window.siyuan.languages.addToDeck,
- click: () => {
- makeCard(protyle.app, [protyle.block.rootID]);
- }
- });
- }
- window.siyuan.menus.menu.append(new MenuItem({
- id: "riffCard",
- label: window.siyuan.languages.riffCard,
- type: "submenu",
- icon: "iconRiffCard",
- submenu: riffCardMenu,
- }).element);
- }
- }
- window.siyuan.menus.menu.append(new MenuItem({
- id: "search",
- label: window.siyuan.languages.search,
- icon: "iconSearch",
- accelerator: window.siyuan.config.keymap.general.search.custom,
- async click() {
- const searchPath = isBoxDoc ? "" : getDisplayName(protyle.path, false, true);
- /// #if MOBILE
- let hPath = getNotebookName(protyle.notebookId);
- if (!isBoxDoc) {
- const pathResponse = await fetchSyncPost("/api/filetree/getHPathByPath", {
- notebook: protyle.notebookId,
- path: searchPath + ".sy"
- });
- if (pathResponse.code !== 0) {
- return;
- }
- hPath = pathPosix().join(hPath, pathResponse.data);
- }
- popSearch(protyle.app, {
- hasReplace: false,
- hPath,
- idPath: [isBoxDoc ? protyle.notebookId : pathPosix().join(protyle.notebookId, searchPath)],
- page: 1,
- });
- /// #else
- openSearch({
- app: protyle.app,
- hotkey: Constants.DIALOG_SEARCH,
- notebookId: protyle.notebookId,
- searchPath
- });
- /// #endif
- }
- }).element);
- if (!protyle.disabled) {
- transferBlockRef(protyle.block.rootID);
- }
- window.siyuan.menus.menu.append(new MenuItem({id: "separator_3", type: "separator"}).element);
- if (!protyle.model) {
- window.siyuan.menus.menu.append(new MenuItem({
- id: "openBy",
- label: window.siyuan.languages.openBy,
- icon: "iconOpen",
- click() {
- /// #if !MOBILE
- openFileById({
- app: protyle.app,
- id: protyle.block.id,
- action: protyle.block.rootID !== protyle.block.id ? [Constants.CB_GET_ALL, Constants.CB_GET_FOCUS] : [Constants.CB_GET_CONTEXT],
- });
- /// #else
- openMobileFileById(protyle.app, protyle.block.id, protyle.block.rootID !== protyle.block.id ? [Constants.CB_GET_ALL] : [Constants.CB_GET_CONTEXT]);
- /// #endif
- }
- }).element);
- }
- /// #if !BROWSER
- window.siyuan.menus.menu.append(new MenuItem({
- id: "openByNewWindow",
- label: window.siyuan.languages.openByNewWindow,
- icon: "iconOpenWindow",
- click() {
- openNewWindowById(protyle.block.rootID);
- }
- }).element);
- if (getHostCapabilities().localFileSystem) {
- window.siyuan.menus.menu.append(new MenuItem({
- id: "showInFolder",
- icon: "iconFolder",
- label: window.siyuan.languages.showInFolder,
- click: () => {
- useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, protyle.notebookId, protyle.path));
- }
- }).element);
- }
- /// #endif
- if (!window.siyuan.config.readonly && !window.siyuan.isPublish &&
- !protyle.options.history?.created && !protyle.options.history?.snapshot &&
- protyle.element.getAttribute("disabled-forever") !== "true") {
- window.siyuan.menus.menu.append(new MenuItem({
- id: "fileHistory",
- label: window.siyuan.languages.dataHistory,
- icon: "iconHistory",
- click() {
- openDocHistory({
- app: protyle.app,
- id: protyle.block.rootID,
- notebookId: protyle.notebookId,
- pathString: response.data.name,
- readonly: protyle.disabled,
- });
- }
- }).element);
- }
- window.siyuan.menus.menu.append(exportMd(protyle.block.showAll ? protyle.block.id : protyle.block.rootID));
-
- window.siyuan.menus.menu.append(new MenuItem({id: "separator_4", type: "separator"}).element);
- if (protyle) {
- emitOpenMenu({
- type: "click-editortitleicon",
- detail: {
- protyle,
- data: response.data,
- },
- separatorPosition: "bottom",
- });
- }
- window.siyuan.menus.menu.append(new MenuItem({
- id: "updateAndCreatedAt",
- iconHTML: "",
- type: "readonly",
- // 不能换行,否则移动端间距过大
- label: `${window.siyuan.languages.modifiedAt} ${dayjs(response.data.ial.updated).format("YYYY-MM-DD HH:mm:ss")}<br>${window.siyuan.languages.createdAt} ${dayjs(response.data.ial.id.substr(0, 14)).format("YYYY-MM-DD HH:mm:ss")}`
- }).element);
- /// #if MOBILE
- window.siyuan.menus.menu.fullscreen("all", restoreKeyboard);
- /// #else
- window.siyuan.menus.menu.popup(position);
- /// #endif
});
};
diff --git a/app/src/protyle/render/av/relation.ts b/app/src/protyle/render/av/relation.ts
index d2ef59acdc..0919057e82 100644
--- a/app/src/protyle/render/av/relation.ts
+++ b/app/src/protyle/render/av/relation.ts
@@ -121,7 +121,8 @@ const setDatabase = (avId: string, element: HTMLElement, item: HTMLElement) => {
export const openSearchAV = (options: IOpenSearchAVOptions) => {
window.siyuan.menus.menu.remove();
- const menu = new Menu();
+ let cancelSearch: () => void;
+ const menu = new Menu(undefined, () => cancelSearch?.());
menu.addItem({
iconHTML: "",
type: "empty",
@@ -138,16 +139,26 @@ export const openSearchAV = (options: IOpenSearchAVOptions) => {
let searchTimer = 0;
let requestSequence = 0;
let controller: AbortController;
+ let closed = false;
+ cancelSearch = () => {
+ closed = true;
+ clearTimeout(searchTimer);
+ requestSequence++;
+ controller?.abort();
+ };
// 列表内容变化后重新适配菜单位置和面板高度。
const updateMenuPosition = () => {
window.siyuan.menus.menu.resetPosition();
};
const loadList = (keyword: string, cb?: () => void) => {
+ if (closed) {
+ return;
+ }
controller?.abort();
controller = new AbortController();
const currentSequence = ++requestSequence;
genSearchList(listElement, keyword, options, controller.signal, () => {
- if (currentSequence !== requestSequence) {
+ if (closed || currentSequence !== requestSequence) {
return;
}
cb?.();
@@ -155,6 +166,9 @@ export const openSearchAV = (options: IOpenSearchAVOptions) => {
});
};
const search = () => {
+ if (closed) {
+ return;
+ }
controller?.abort();
requestSequence++;
clearTimeout(searchTimer);
diff --git a/app/src/protyle/render/av/searchMenu.test.ts b/app/src/protyle/render/av/searchMenu.test.ts
new file mode 100644
index 0000000000..e998e9f67d
--- /dev/null
+++ b/app/src/protyle/render/av/searchMenu.test.ts
@@ -0,0 +1,108 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const noop = () => {};
+
+const setup = (mobile = false) => {
+ const exports = {} as typeof import("./relation");
+ const listeners = new Map<string, (event: unknown) => void>();
+ const timers = new Map<number, () => void>();
+ const requests: {signal: AbortSignal, callback: (response: unknown) => void}[] = [];
+ const positions: IPosition[] = [];
+ let closeCallback: () => void;
+ let focusCount = 0;
+ let resetCount = 0;
+ let timerId = 0;
+ const input = {value: "", addEventListener: (name: string, listener: (event: unknown) => void) => listeners.set(name, listener),
+ focus: () => { focusCount++; }};
+ const list = {innerHTML: "", querySelector: (): null => null};
+ const element = {querySelector: (selector: string) => selector === "input" ? input : list,
+ lastElementChild: {addEventListener: noop}, classList: {add: noop}, setAttribute: noop};
+ const menu = {resetPosition: () => { resetCount++; }, remove: () => {
+ const callback = closeCallback;
+ closeCallback = undefined;
+ callback?.();
+ }};
+ runInNewContext(transpileModule(readFileSync("src/protyle/render/av/relation.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {
+ exports, AbortController,
+ clearTimeout: (id: number) => timers.delete(id),
+ require: (name: string) => {
+ if (name === "../../../plugin/Menu") { return {Menu: class {
+ element = element;
+ constructor(_id: string, onClose: () => void) { closeCallback = onClose; }
+ addItem(options: IMenu) { options.bind(element as unknown as HTMLElement); }
+ open(position: IPosition) { positions.push(position); }
+ }}; }
+ if (name === "../../../util/fetch") { return {fetchPost: (_url: string, _data: unknown,
+ callback: (response: unknown) => void, _headers: unknown, _process: unknown, signal: AbortSignal) => {
+ requests.push({signal, callback});
+ }}; }
+ if (name === "../../../util/functions") { return {isMobile: () => mobile}; }
+ if (name === "../../util/hasClosest") { return {hasTopClosestByClassName: (): null => null}; }
+ if (name === "./searchAVFocus") { return {getSearchAVFocus: (): null => null}; }
+ if (name === "../../../constants") { return {Constants: {TIMEOUT_INPUT: 1}}; }
+ return {};
+ },
+ window: {siyuan: {menus: {menu}, languages: {}},
+ setTimeout: (callback: () => void) => { timers.set(++timerId, callback); return timerId; }},
+ });
+ exports.openSearchAV({avID: "", purpose: "addToDatabase", position: {x: 60, y: 90},
+ target: {getBoundingClientRect: () => ({left: 0, bottom: 0, height: 0})} as HTMLElement});
+ const respond = (index: number) => requests[index].callback({data: {results: []}});
+ const search = () => {
+ input.value = "database";
+ listeners.get("input")({stopPropagation: noop, isComposing: false});
+ };
+ const runTimers = () => {
+ const callbacks = Array.from(timers.values());
+ timers.clear();
+ callbacks.forEach(callback => callback());
+ };
+ return {requests, positions, timers, respond, search, runTimers, close: menu.remove,
+ focusCount: () => focusCount, resetCount: () => resetCount};
+};
+
+test("closing a pending database picker aborts its request and prevents reopening or focusing on a late response", () => {
+ const picker = setup();
+ picker.close();
+ assert.equal(picker.requests[0].signal.aborted, true);
+ picker.respond(0);
+ assert.equal(picker.positions.length, 0);
+ assert.equal(picker.focusCount(), 0);
+ assert.equal(picker.resetCount(), 0);
+});
+
+test("closing a database picker clears debounced search work", () => {
+ const picker = setup();
+ picker.respond(0);
+ picker.search();
+ assert.equal(picker.timers.size, 1);
+ picker.close();
+ assert.equal(picker.timers.size, 0);
+ picker.search();
+ assert.equal(picker.timers.size, 0);
+ picker.runTimers();
+ assert.equal(picker.requests.length, 1);
+});
+
+for (const mobile of [false, true]) {
+ test(`database searching keeps its position and cancels in-flight work on close (${mobile ? "mobile" : "desktop"})`, () => {
+ const picker = setup(mobile);
+ picker.respond(0);
+ assert.equal(JSON.stringify(picker.positions), '[{"x":60,"y":90}]');
+ assert.equal(picker.focusCount(), 1);
+ picker.search();
+ picker.runTimers();
+ assert.equal(picker.requests.length, 2);
+ picker.close();
+ assert.equal(picker.requests[1].signal.aborted, true);
+ picker.respond(1);
+ assert.equal(picker.positions.length, 1);
+ assert.equal(picker.resetCount(), 1);
+ });
+}