Skip to content

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

:sparkles: Support document context menus in graph view https://github.com/siyuan-note/siyuan/issues/20148

Daniel70d2b44798a2
diff --git a/app/src/constants.ts b/app/src/constants.ts
index 04ee35f876..2526db5e4b 100644
--- a/app/src/constants.ts
+++ b/app/src/constants.ts
@@ -82,6 +82,7 @@ export abstract class Constants {
public static readonly CUSTOM_REMINDER_WECHAT: string = "custom-reminder-wechat";
public static readonly CUSTOM_RIFF_DECKS: string = "custom-riff-decks";
public static readonly CUSTOM_SY_READONLY: string = "custom-sy-readonly";
+ public static readonly CUSTOM_SY_SUBDOC_SORT_MODE: string = "custom-sy-subdoc-sort-mode";
public static readonly CUSTOM_SY_FULLWIDTH: string = "custom-sy-fullwidth";
public static readonly CUSTOM_SY_HEADING_NUMBER: string = "custom-sy-heading-number";
public static readonly CUSTOM_SY_AV_VIEW: string = "custom-sy-av-view";
diff --git a/app/src/layout/dock/Graph.test.ts b/app/src/layout/dock/Graph.test.ts
index 26e4c107b6..3cc68f0443 100644
--- a/app/src/layout/dock/Graph.test.ts
+++ b/app/src/layout/dock/Graph.test.ts
@@ -4,6 +4,7 @@ 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 () => {
@@ -61,3 +62,93 @@ for (const type of ["global", "local", "pin"]) {
assert.equal(graph.settingsSavingSuspended, false);
});
}
+
+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 positions: IPosition[] = [];
+ let resolveSiblings: (value: unknown) => void;
+ const siblings = new Promise(resolve => { resolveSiblings = resolve; });
+ 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 === "../../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]) => {
+ menus.push(options);
+ return {popup: (position: IPosition) => positions.push(position)};
+ }}; }
+ if (name === "../../util/fetch") { return {
+ fetchSyncPost: (url: string, body: unknown) => {
+ requests.push({url, body});
+ if (url.endsWith("getBlockInfo")) {
+ return Promise.resolve({code: 0, data: restricted ? {publishAccessRequired: true} :
+ {box: "notebook", path: "/parent/doc.sy"}});
+ }
+ if (url.endsWith("getDocInfo")) {
+ 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;
+ }}; }
+ return {};
+ },
+ document: {
+ addEventListener: (name: string, listener: () => void) => {
+ if (!listeners.has(name)) { listeners.set(name, new Set()); }
+ listeners.get(name).add(listener);
+ },
+ removeEventListener: (name: string, listener: () => void) => listeners.get(name)?.delete(listener),
+ },
+ window: {siyuan: {menus: {menu: {remove() {}}}, 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: []}})};
+};
+
+test("graph document menu uses current metadata independently of the document tree display limit", async () => {
+ const {graph, menus, positions, requests, listeners, resolveSiblings} = 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(JSON.stringify(positions), '[{"x":80,"y":100}]');
+ assert.equal(JSON.stringify(requests[2].body),
+ '{"notebook":"notebook","path":"/parent","maxListCount":1,"ignoreMaxListHint":true}');
+ 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 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);
+ });
+}
+
+test("graph menu does not act on restricted document metadata", async () => {
+ const {graph, requests, menus} = createMenuGraph(true);
+ await graph.openGraphNodeMenu({node: {id: "doc"}, x: 0, y: 0});
+ assert.equal(menus.length, 0);
+ assert.equal(requests.length, 2);
+});
diff --git a/app/src/layout/dock/Graph.ts b/app/src/layout/dock/Graph.ts
index 5349149328..0100d4a428 100644
--- a/app/src/layout/dock/Graph.ts
+++ b/app/src/layout/dock/Graph.ts
@@ -5,16 +5,18 @@ import {getDockByType} from "../tabUtil";
import {Model} from "../Model";
import {BlockPanel} from "../../block/Panel";
import {fullscreen} from "../../protyle/breadcrumb/action";
-import {fetchPost} from "../../util/fetch";
+import {fetchPost, fetchSyncPost} from "../../util/fetch";
import {openFileById} from "../../editor/util";
import {updateHotkeyAfterTip} from "../../protyle/util/compatibility";
import {openGlobalSearch} from "../../search/util";
import type {App} from "../../index";
import {checkFold} from "../../util/noRelyPCFunction";
import {Editor} from "../../editor";
-import {getDocDisplayName, isEncryptedBox} from "../../util/pathName";
+import {getDocDisplayName, isEncryptedBox, pathPosix} from "../../util/pathName";
import {GraphEngine} from "./graph/GraphEngine";
-import {IGraphNodeClick, IGraphSourceLink, IGraphSourceNode} from "./graph/types";
+import {IGraphNodeClick, IGraphNodeContextMenu, IGraphSourceLink, IGraphSourceNode} from "./graph/types";
+import {initDocumentMenu} from "../../menus/navigation";
+import {Constants} from "../../constants";
interface IGraphSearchOptions {
id?: string;
@@ -43,6 +45,8 @@ export class Graph extends Model {
};
private renderedGraphData: Graph["graphData"];
private requestVersion = 0;
+ private menuRequestVersion = 0;
+ private menuAbort?: AbortController;
public type: "local" | "pin" | "global";
constructor(options: {
@@ -530,6 +534,8 @@ export class Graph extends Model {
public destroy() {
this.requestVersion++;
+ this.menuRequestVersion++;
+ this.menuAbort?.abort();
if (this.searchTimeout) {
window.clearTimeout(this.searchTimeout);
}
@@ -682,6 +688,13 @@ export class Graph extends Model {
if (!this.graphEngine) {
this.graphEngine = new GraphEngine(this.graphElement, {
onNodeClick: (details) => this.openGraphNode(details),
+ onNodeContextMenu: (details) => {
+ if (details.node.type !== "NodeDocument") {
+ return false;
+ }
+ void this.openGraphNodeMenu(details);
+ return true;
+ },
});
this.renderedGraphData = undefined;
}
@@ -743,4 +756,64 @@ export class Graph extends Model {
});
}
}
+
+ private async openGraphNodeMenu(details: IGraphNodeContextMenu) {
+ this.menuAbort?.abort();
+ const abort = new AbortController();
+ this.menuAbort = abort;
+ const request = ++this.menuRequestVersion;
+ const cancel = () => {
+ this.menuRequestVersion++;
+ abort.abort();
+ };
+ document.addEventListener("pointerdown", cancel, true);
+ document.addEventListener("keydown", cancel, true);
+ window.siyuan.menus.menu.remove();
+ try {
+ const [info, doc] = await Promise.all([
+ fetchSyncPost("/api/block/getBlockInfo", {id: details.node.id}, undefined, false, abort.signal),
+ fetchSyncPost("/api/block/getDocInfo", {id: details.node.id}, undefined, false, abort.signal),
+ ]);
+ if (request !== this.menuRequestVersion || info.code !== 0 || doc.code !== 0 || !info.data || !doc.data ||
+ !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) {
+ 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, {
+ 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,
+ target: this.graphElement,
+ elements: this.graphElement.querySelectorAll<HTMLElement>(".b3-list-item"),
+ position,
+ readonlyHistory: 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);
+ }
+ } finally {
+ document.removeEventListener("pointerdown", cancel, true);
+ document.removeEventListener("keydown", cancel, true);
+ if (this.menuAbort === abort) {
+ this.menuAbort = undefined;
+ }
+ }
+ }
}
diff --git a/app/src/layout/dock/graph/GraphEngine.test.ts b/app/src/layout/dock/graph/GraphEngine.test.ts
new file mode 100644
index 0000000000..f1e7612de6
--- /dev/null
+++ b/app/src/layout/dock/graph/GraphEngine.test.ts
@@ -0,0 +1,76 @@
+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 = () => {
+ const exports = {} as typeof import("./GraphEngine");
+ const source = readFileSync("src/layout/dock/graph/GraphEngine.ts", "utf8")
+ .replaceAll("import.meta.url", '"file:///graph/GraphEngine.ts"');
+ const code = transpileModule(source, {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ 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;}}),
+ 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,
+ });
+ const container = {append: noop,
+ getBoundingClientRect: () => ({left: 40, top: 60}),
+ addEventListener: (name: string, listener: (event: unknown) => void) => listeners.set(name, listener),
+ removeEventListener: (name: string) => listeners.delete(name)};
+ const menus: import("./types").IGraphNodeContextMenu[] = [];
+ let clicks = 0;
+ const engine = new exports.GraphEngine(container as unknown as HTMLElement, {
+ onNodeClick: () => { clicks++; },
+ onNodeContextMenu: details => {
+ if (details.node.type !== "NodeDocument") { return false; }
+ menus.push(details);
+ return true;
+ },
+ });
+ const state = Object.assign(engine, {
+ data: {nodes: [{id: "doc", type: "NodeDocument"}, {id: "tag", type: "tag"}], sizes: [10, 10]},
+ positions: new Float32Array([5, 8, 100, 100]), camera: {scale: 2, x: 20, y: 30},
+ }) as unknown as {selected: number, pointerAction: unknown, pointers: Map<number, unknown>, destroy: () => void};
+ const context = (clientX: number, clientY: number) => {
+ let prevented = false;
+ let stopped = false;
+ listeners.get("contextmenu")({clientX, clientY,
+ preventDefault: () => { prevented = true; }, stopPropagation: () => { stopped = true; }});
+ return {prevented, stopped};
+ };
+ return {state, listeners, menus, context, clicks: () => clicks};
+};
+
+test("graph context menu resolves transformed coordinates without opening or dragging the document", () => {
+ const {state, listeners, menus, context, clicks} = setup();
+ listeners.get("pointerdown")({pointerType: "mouse", button: 2});
+ assert.equal(state.pointerAction, undefined);
+ assert.equal(state.pointers.size, 0);
+ assert.deepEqual(context(70, 106), {prevented: true, stopped: true});
+ assert.equal(menus[0].node.id, "doc");
+ assert.equal(menus[0].x, 70);
+ assert.equal(menus[0].y, 106);
+ assert.equal(state.selected, 0);
+ assert.equal(clicks(), 0);
+ state.destroy();
+ assert.equal(listeners.has("contextmenu"), false);
+});
+
+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});
+ assert.deepEqual(context(500, 500), {prevented: false, stopped: false});
+ assert.equal(menus.length, 0);
+ assert.equal(state.selected, -1);
+});
diff --git a/app/src/layout/dock/graph/GraphEngine.ts b/app/src/layout/dock/graph/GraphEngine.ts
index ea6eff1e64..faafb51d70 100644
--- a/app/src/layout/dock/graph/GraphEngine.ts
+++ b/app/src/layout/dock/graph/GraphEngine.ts
@@ -106,6 +106,7 @@ export class GraphEngine {
this.container.addEventListener("pointerup", this.handlePointerUp);
this.container.addEventListener("pointercancel", this.handlePointerUp);
this.container.addEventListener("pointerleave", this.handlePointerLeave);
+ this.container.addEventListener("contextmenu", this.handleContextMenu);
this.container.addEventListener("wheel", this.handleWheel, {passive: false});
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(this.container);
@@ -308,6 +309,7 @@ export class GraphEngine {
this.container.removeEventListener("pointerup", this.handlePointerUp);
this.container.removeEventListener("pointercancel", this.handlePointerUp);
this.container.removeEventListener("pointerleave", this.handlePointerLeave);
+ this.container.removeEventListener("contextmenu", this.handleContextMenu);
this.container.removeEventListener("wheel", this.handleWheel);
this.baseCanvas.removeEventListener("webglcontextlost", this.handleContextLost);
if (this.renderFrame) {
@@ -542,7 +544,7 @@ export class GraphEngine {
});
}
- private getPointer(event: PointerEvent): IPointerPosition {
+ private getPointer(event: MouseEvent): IPointerPosition {
const rect = this.container.getBoundingClientRect();
return {
clientX: event.clientX,
@@ -618,6 +620,28 @@ export class GraphEngine {
event.preventDefault();
};
+ private readonly handleContextMenu = (event: MouseEvent) => {
+ if (!this.data || !this.engineOptions.onNodeContextMenu) {
+ return;
+ }
+ const pointer = this.getPointer(event);
+ const index = this.hitTest(pointer.x, pointer.y);
+ if (index < 0 || !this.engineOptions.onNodeContextMenu({
+ event,
+ node: this.data.nodes[index],
+ x: event.clientX,
+ y: event.clientY,
+ })) {
+ return;
+ }
+ this.selected = index;
+ this.selectionVersion++;
+ this.hideTooltip();
+ this.scheduleRender();
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
private readonly handlePointerMove = (event: PointerEvent) => {
const pointer = this.getPointer(event);
if (this.pointers.has(event.pointerId)) {
diff --git a/app/src/layout/dock/graph/types.ts b/app/src/layout/dock/graph/types.ts
index 84cd425d72..5314508fd3 100644
--- a/app/src/layout/dock/graph/types.ts
+++ b/app/src/layout/dock/graph/types.ts
@@ -88,8 +88,13 @@ export interface IGraphNodeClick {
y: number;
}
+export interface IGraphNodeContextMenu extends Omit<IGraphNodeClick, "event"> {
+ event: MouseEvent;
+}
+
export interface IGraphEngineOptions {
onNodeClick: (details: IGraphNodeClick) => void;
+ onNodeContextMenu?: (details: IGraphNodeContextMenu) => boolean;
}
export interface IGraphSetDataOptions {
diff --git a/app/src/menus/documentMenu.test.ts b/app/src/menus/documentMenu.test.ts
new file mode 100644
index 0000000000..6e97329139
--- /dev/null
+++ b/app/src/menus/documentMenu.test.ts
@@ -0,0 +1,163 @@
+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 setup = (mobile = false, readonly = false) => {
+ const exports = {} as typeof import("./navigation");
+ const items: IMenu[] = [];
+ const requests: {url: string, data: unknown}[] = [];
+ const histories: Parameters<typeof import("../history/doc").openDocHistory>[0][] = [];
+ const databases: unknown[][] = [];
+ const deletions: string[][] = [];
+ const moves: unknown[] = [];
+ const events: {detail: {elements: NodeListOf<HTMLElement>, items: {id: string}[]}}[] = [];
+ const created: unknown[][] = [];
+ const menuAttributes = new Map<string, string>();
+ const menu = {element: {setAttribute: (name: string, value: string) => menuAttributes.set(name, value)},
+ remove: () => { items.length = 0; }, append: (item: IMenu) => { if (!item.ignore) { items.push(item); } }};
+ const keymap = Object.fromEntries(["addToDatabase", "spaceRepetition", "quickMakeCard", "search", "replace", "duplicate"]
+ .map(key => [key, {custom: ""}]));
+ runInNewContext(transpileModule(parse(readFileSync("src/menus/navigation.ts", "utf8"),
+ {MOBILE: mobile, BROWSER: true}, false, true, "navigation.ts"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {
+ exports,
+ require: (name: string) => {
+ const dependencies: Record<string, unknown> = {
+ "./Menu": {MenuItem: class {element: IMenu; constructor(item: IMenu) { this.element = item; }}},
+ "./commonMenuItem": {copySubMenu: () => [{id: "copyID"}], exportMd: () => ({id: "export"}),
+ movePathToMenu: (paths: string[], notebooks: string[]) => {
+ moves.push({paths, notebooks}); return {id: "move"};
+ }, renameMenu: () => ({id: "rename"})},
+ "../util/pathName": {pathPosix: () => posix, isEncryptedBox: () => false,
+ getDisplayName: (name: string) => name.replace(/\.sy$/, "")},
+ "../util/pinnedDocs": {pinnedDocIDs: new Set()},
+ "../util/fetch": {fetchPost: (url: string, data: unknown, callback?: (response: unknown) => void) => {
+ requests.push({url, data}); callback?.({code: 0, data: {ial: {}}});
+ }},
+ "../util/contractFormData": {ContractFormData: class {}},
+ "../constants": {Constants: {MENU_DOC_TREE_MORE: "doctree", MENU_FROM_DOC_TREE_MORE_DOC: "doc"}},
+ "../util/newFile": {newFileInTree: (...args: unknown[]) => created.push(args)},
+ "../protyle/util/hasClosest": {hasClosestByTag: (row: {tree: unknown}) => row.tree},
+ "../editor/deleteFile": {deleteFile: (...args: string[]) => deletions.push(args)},
+ "../layout/tabUtil": {getDockByType: (): undefined => undefined},
+ "../history/doc": {openDocHistory: (options: typeof histories[number]) => histories.push(options)},
+ "./util": {openEditorTab: () => menu.append({id: "openBy"})},
+ "../plugin/EventBus": {emitOpenMenu: (event: typeof events[number]) => {
+ events.push(event); menu.append({id: "separator_pluginTop", type: "separator"}); menu.append({id: "plugin"});
+ }},
+ "../protyle/render/av/addToDatabase": {addBlocksToDatabase: (...args: unknown[]) => databases.push(args)},
+ "../util/fileTreeSort": {getConfiguredChildrenSortMode: () => 0, isCustomFileTreeList: () => false},
+ "../util/hostCapabilities": {getHostCapabilities: () => ({documentImportExport: true})},
+ };
+ return dependencies[name] || {};
+ },
+ window: {siyuan: {menus: {menu}, languages: {}, mobile: {docks: {}},
+ config: {readonly, fileTree: {parentDocClickExpand: true}, flashcard: {deck: true},
+ keymap: {general: keymap, editor: {general: keymap}}}}},
+ });
+ const options: Parameters<typeof exports.initDocumentMenu>[1] = {
+ id: "doc", notebookId: "notebook", path: "/parent/doc.sy", name: "Document",
+ subFileCount: 2, childrenSortMode: 0, customSort: false,
+ target: {} as HTMLElement, elements: [] as unknown as NodeListOf<HTMLElement>,
+ position: {x: 100, y: 120}, readonlyHistory: true,
+ };
+ const open = (overrides: Partial<typeof options> = {}) => exports.initDocumentMenu({} as Parameters<typeof exports.initDocumentMenu>[0],
+ {...options, ...overrides});
+ const click = (id: string) => {
+ const item = items.find(item => item.id === id);
+ assert.ok(item, id);
+ return item.click(null, null);
+ };
+ return {exports, open, click, options, items, requests, histories, databases, deletions, moves, events, created, menuAttributes};
+};
+
+for (const mobile of [false, true]) {
+ test(`complete document menu uses explicit document targets without a tree row (${mobile ? "mobile" : "desktop"})`, () => {
+ const {open, click, items, moves, deletions, databases, histories, events, options} = setup(mobile);
+ open();
+ assert.deepEqual(items.map(item => item.id), [
+ ...(mobile ? ["openInNewTab", "separator_open"] : []),
+ "openDocument", "newSiblingDoc", "separator_1", "copy", "move", "addToDatabase", "delete", "separator_2",
+ "rename", "attr", "pinDoc", "sort", "riffCard", "search", "replace", "separator_3", "openBy", "fileHistory",
+ "import", "export", "separator_pluginTop", "plugin",
+ ]);
+ click("delete");
+ assert.deepEqual(deletions, [["notebook", "/parent/doc.sy"]]);
+ assert.equal(JSON.stringify(moves), '[{"paths":["/parent/doc.sy"],"notebooks":["notebook"]}]');
+ click("addToDatabase");
+ assert.equal(JSON.stringify(databases[0][0]), '["doc"]');
+ assert.equal(databases[0][1], options.target);
+ assert.equal(databases[0][2], options.position);
+ click("fileHistory");
+ assert.equal(histories[0].id, "doc");
+ assert.equal(histories[0].readonly, true);
+ assert.equal(events[0].detail.elements, options.elements);
+ assert.equal(events[0].detail.items[0].id, "doc");
+ });
+}
+
+test("document menu keeps the existing configurable IDs, hierarchy and built-in order", () => {
+ const {open, items, menuAttributes} = setup();
+ open();
+ const catalog = getEntryCatalogChildren("docTree.document").map(item => item.key);
+ const keys = items.filter(item => item.id !== "plugin" && item.id !== "separator_pluginTop").map(item => item.id);
+ assert.deepEqual(keys, catalog.filter(key => keys.includes(key)));
+ assert.equal(menuAttributes.get("data-name"), "doctree");
+ assert.equal(menuAttributes.get("data-from"), "doc");
+});
+
+test("document menu applies inherited custom sorting and updates sort mode without a mounted file dock", () => {
+ const {open, click, items, created, requests} = setup();
+ open({customSort: true});
+ click("newDocAbove");
+ assert.equal(created[0][1], "notebook");
+ assert.equal(created[0][2], "/parent");
+ assert.equal(JSON.stringify(created[0][3]), '{"targetID":"doc","position":"before"}');
+ assert.ok(!items.some(item => item.id === "newSiblingDoc"));
+ const sort = items.find(item => item.id === "sort").submenu as IMenu[];
+ assert.equal(sort.find(item => item.id === "fileNameASC").checked, true);
+ sort.find(item => item.id === "sortByParent").click(null, null);
+ assert.equal(requests[0].url, "/api/filetree/setDocSortMode");
+ assert.equal(JSON.stringify(requests[0].data), '{"id":"doc","sortMode":null}');
+});
+
+test("readonly document menu retains opening and export while respecting existing mutation and history restrictions", () => {
+ const {open, items} = setup(false, true);
+ open();
+ assert.deepEqual(items.map(item => item.id), ["openDocument", "openBy", "export", "separator_pluginTop", "plugin"]);
+});
+
+test("notebook documents do not expose regular document deletion, moving, renaming or duplication", () => {
+ const {open, items} = setup();
+ open({id: "notebook", path: "/notebook.sy", customSort: true});
+ assert.ok(!items.some(item => ["delete", "move", "rename", "sort", "newDocAbove", "newDocBelow", "newSiblingDoc"].includes(item.id)));
+ const copy = items.find(item => item.id === "copy").submenu as IMenu[];
+ assert.ok(copy.filter(item => ["duplicate", "duplicateTree"].includes(item.id)).every(item => item.ignore));
+});
+
+test("document tree adapter preserves its real selection in plugin events", () => {
+ const {exports, options, events} = setup();
+ const rows = [options.target] as unknown as NodeListOf<HTMLElement>;
+ const row = {tree: {querySelectorAll: () => rows}, classList: {contains: () => true},
+ getAttribute: (name: string) => ({"data-node-id": "doc", "data-name": "Document.sy", "data-count": "2"})[name],
+ parentElement: {}};
+ exports.initFileMenu({} as Parameters<typeof exports.initFileMenu>[0], "notebook", "/doc.sy", row as unknown as Element);
+ assert.equal(events[0].detail.elements, rows);
+});
+
+test("import reload tolerates a document absent from the file tree", () => {
+ const {open, items, requests} = setup();
+ open();
+ const item = (items.find(item => item.id === "import").submenu as IMenu[])[0];
+ let change: (event: unknown) => void;
+ item.bind({querySelector: () => ({addEventListener: (_name: string, callback: typeof change) => { change = callback; }})} as unknown as HTMLElement);
+ change({target: {files: [{}]}});
+ assert.equal(requests[0].url, "/api/import/importSY");
+});
diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.ts
index 81917710db..eb0f885885 100644
--- a/app/src/menus/navigation.ts
+++ b/app/src/menus/navigation.ts
@@ -21,7 +21,7 @@ import {popSearch} from "../mobile/menu/search";
import {Constants} from "../constants";
import {newFileInTree} from "../util/newFile";
import {hasClosestByTag} from "../protyle/util/hasClosest";
-import {deleteFiles, deleteNotebooks} from "../editor/deleteFile";
+import {deleteFile, deleteFiles, deleteNotebooks} from "../editor/deleteFile";
/// #if !MOBILE
import {openFileById} from "../editor/util";
/// #endif
@@ -37,7 +37,7 @@ import {transaction} from "../protyle/wysiwyg/transaction";
import {emitOpenMenu} from "../plugin/EventBus";
import {isPhablet, saveExportFile} from "../protyle/util/compatibility";
import {exportMarkdownZip} from "../protyle/export/exportMd";
-import {addFilesToDatabase} from "../protyle/render/av/addToDatabase";
+import {addBlocksToDatabase, addFilesToDatabase} from "../protyle/render/av/addToDatabase";
import {getDocTreeMenuItems, getDocTreeMenuType} from "./navigationSelection";
import {
FILE_TREE_CHILDREN_SORT_MODE,
@@ -723,9 +723,38 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
if (selectItemElements.length > 1) {
return initMultiMenu(selectItemElements, app);
}
- const id = liElement.getAttribute("data-node-id");
- let name = liElement.getAttribute("data-name");
- name = getDisplayName(name, false, true);
+ return initDocumentMenu(app, {
+ id: liElement.getAttribute("data-node-id"),
+ notebookId,
+ path: pathString,
+ name: getDisplayName(liElement.getAttribute("data-name"), false, true),
+ subFileCount: Number(liElement.getAttribute("data-count")),
+ childrenSortMode: getConfiguredChildrenSortMode(liElement),
+ customSort: isCustomFileTreeList(liElement.getAttribute("data-pin-root") === "true" ? liElement : liElement.parentElement),
+ target: liElement as HTMLElement,
+ elements: selectItemElements,
+ treeElement: liElement,
+ });
+};
+
+export const initDocumentMenu = (app: App, options: {
+ id: string,
+ notebookId: string,
+ path: string,
+ name: string,
+ subFileCount: number,
+ childrenSortMode: number | null,
+ customSort: boolean,
+ target: HTMLElement,
+ elements: NodeListOf<HTMLElement>,
+ treeElement?: Element,
+ position?: IPosition,
+ readonlyHistory?: boolean,
+}) => {
+ const {id, notebookId, path: pathString, name, subFileCount} = options;
+ const isBoxDoc = id === notebookId;
+ window.siyuan.menus.menu.remove();
+ window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_DOC_TREE_MORE);
/// #if MOBILE
window.siyuan.menus.menu.append(new MenuItem({
id: "openInNewTab",
@@ -737,7 +766,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
}).element);
window.siyuan.menus.menu.append(new MenuItem({id: "separator_open", type: "separator"}).element);
/// #endif
- if (window.siyuan.config.fileTree.parentDocClickExpand && Number(liElement.getAttribute("data-count")) > 0) {
+ if (window.siyuan.config.fileTree.parentDocClickExpand && subFileCount > 0) {
window.siyuan.menus.menu.append(new MenuItem({
id: "openDocument",
label: window.siyuan.languages.openDocument,
@@ -756,7 +785,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
}).element);
}
if (!window.siyuan.config.readonly) {
- if (isCustomFileTreeList(liElement.getAttribute("data-pin-root") === "true" ? liElement : liElement.parentElement)) {
+ if (!isBoxDoc && options.customSort) {
window.siyuan.menus.menu.append(new MenuItem({
id: "newDocAbove",
icon: "iconBefore",
@@ -779,7 +808,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
});
}
}).element);
- } else {
+ } else if (!isBoxDoc) {
window.siyuan.menus.menu.append(new MenuItem({
id: "newSiblingDoc",
icon: "iconAddDoc",
@@ -797,6 +826,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
icon: "iconCopy",
submenu: (copySubMenu([id]) as IMenu[]).concat([{
id: "duplicate",
+ ignore: isBoxDoc,
iconHTML: "",
label: window.siyuan.languages.duplicateCopy,
accelerator: window.siyuan.config.keymap.editor.general.duplicate.custom,
@@ -809,41 +839,44 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
id: "duplicateTree",
iconHTML: "",
label: window.siyuan.languages.duplicateDocTree,
- ignore: !(Number(liElement.getAttribute("data-count")) > 0),
+ ignore: isBoxDoc || !(subFileCount > 0),
click() {
fetchPost("/api/filetree/duplicateDocTree", {id});
}
}])
}).element);
- const selectedItems = Array.from(fileElement.querySelectorAll(".b3-list-item--focus"));
- window.siyuan.menus.menu.append(movePathToMenu(getTopPaths(selectedItems), selectedItems.map((item) =>
- item.getAttribute("data-notebook") || item.closest("ul[data-url]")?.getAttribute("data-url") || "")));
+ if (!isBoxDoc) {
+ window.siyuan.menus.menu.append(movePathToMenu([pathString], [notebookId]));
+ }
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: () => {
- addFilesToDatabase([liElement]);
+ addBlocksToDatabase([id], options.target, options.position);
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
id: "delete",
+ ignore: isBoxDoc,
icon: "iconTrashcan",
label: window.siyuan.languages.delete,
accelerator: "⌦",
click: () => {
- deleteFiles(Array.from(fileElement.querySelectorAll(".b3-list-item--focus")));
+ deleteFile(notebookId, pathString);
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);
- window.siyuan.menus.menu.append(renameMenu({
- path: pathString,
- notebookId,
- name,
- type: "file",
- docId: id,
- }));
+ if (!isBoxDoc) {
+ window.siyuan.menus.menu.append(renameMenu({
+ path: pathString,
+ notebookId,
+ name,
+ type: "file",
+ docId: id,
+ }));
+ }
window.siyuan.menus.menu.append(new MenuItem({
id: "attr",
label: window.siyuan.languages.attr,
@@ -869,7 +902,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
click: () => { updatePinnedDocs([id], pinned ? "unpin" : "pin"); },
}).element);
}
- const configuredSortMode = getConfiguredChildrenSortMode(liElement);
+ const configuredSortMode = options.childrenSortMode;
const sortSubMenu = sortMenu("document", configuredSortMode, (sortMode) => {
fetchPost("/api/filetree/setDocSortMode", {
id,
@@ -878,12 +911,12 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
if (response.code !== 0) {
return;
}
- liElement.setAttribute(FILE_TREE_CHILDREN_SORT_MODE, sortMode?.toString() || "");
+ options.treeElement?.setAttribute(FILE_TREE_CHILDREN_SORT_MODE, sortMode?.toString() || "");
let files;
/// #if MOBILE
files = window.siyuan.mobile.docks.file;
/// #else
- files = (getDockByType("file").data["file"] as Files);
+ files = (getDockByType("file")?.data["file"] as Files);
/// #endif
files?.onDocSortModeChanged({
scope: "document",
@@ -896,6 +929,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
});
window.siyuan.menus.menu.append(new MenuItem({
id: "sort",
+ ignore: isBoxDoc,
icon: "iconSort",
label: window.siyuan.languages.sort,
type: "submenu",
@@ -1042,16 +1076,16 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
label: window.siyuan.languages.dataHistory,
icon: "iconHistory",
click() {
- openDocHistory({app, id, notebookId, pathString: name});
+ openDocHistory({app, id, notebookId, pathString: name, readonly: options.readonlyHistory});
}
}).element);
}
- genImportMenu(notebookId, pathString);
+ genImportMenu(notebookId, isBoxDoc ? "/" : pathString);
window.siyuan.menus.menu.append(exportMd(id));
emitOpenMenu({
type: "open-menu-doctree",
detail: {
- elements: selectItemElements,
+ elements: options.elements,
type: "doc",
items: [{id, path: pathString, notebookId}],
},
@@ -1070,9 +1104,13 @@ export const genImportMenu = (notebookId: string, pathString: string) => {
/// #if MOBILE
files = window.siyuan.mobile.docks.file;
/// #else
- files = (getDockByType("file").data["file"] as Files);
+ files = (getDockByType("file")?.data["file"] as Files);
/// #endif
- const liElement = files.element.querySelector(`[data-path="${pathString}"]`);
+ const liElement = files?.element.querySelector(`[data-url="${notebookId}"] [data-path="${pathString}"]`);
+ if (!liElement) {
+ window.siyuan.menus.menu.remove();
+ return;
+ }
liElement.querySelector(".b3-list-item__toggle").classList.remove("fn__hidden");
syncFileTreeItemDefaultIcon(liElement as HTMLElement);
files.getLeaf(liElement, notebookId, true);
diff --git a/app/src/protyle/render/av/addToDatabase.test.ts b/app/src/protyle/render/av/addToDatabase.test.ts
new file mode 100644
index 0000000000..78f145f74f
--- /dev/null
+++ b/app/src/protyle/render/av/addToDatabase.test.ts
@@ -0,0 +1,41 @@
+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";
+
+test("adding graph documents to a database preserves explicit positioning and undo transaction context", () => {
+ const exports = {} as typeof import("./addToDatabase");
+ const searches: {target: HTMLElement, position: IPosition, callback: (row: unknown) => void}[] = [];
+ const operations: IOperation[][] = [];
+ runInNewContext(transpileModule(readFileSync("src/protyle/render/av/addToDatabase.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {
+ exports, Lute: {NewNodeID: () => "item"},
+ require: (name: string) => {
+ if (name === "./relation") { return {openSearchAV: (options: typeof searches[number]) => searches.push(options)}; }
+ if (name === "../../wysiwyg/transaction") { return {
+ transaction: (_protyle: unknown, data: IOperation[]) => operations.push(data)}; }
+ if (name === "./filteredTip") { return {getAVFilteredTipContext: (scope: string) => ({scope})}; }
+ if (name === "dayjs") { return () => ({format: () => "20261006123456"}); }
+ return {};
+ },
+ });
+ const target = {} as HTMLElement;
+ const position = {x: 60, y: 90};
+ exports.addBlocksToDatabase(["document"], target, position);
+ assert.equal(searches[0].target, target);
+ assert.equal(searches[0].position, position);
+ searches[0].callback({dataset: {avId: "database", viewId: "view", blockId: "database-block"}});
+ assert.equal(operations[0][0].action, "insertAttrViewBlock");
+ assert.equal(operations[0][0].viewID, "view");
+ assert.equal(operations[0][0].ignoreDefaultFill, false);
+ assert.equal(JSON.stringify(operations[0][0].srcs), '[{"itemID":"item","id":"document","isDetached":false}]');
+ assert.equal(operations[0][1].action, "doUpdateUpdated");
+ exports.addFilesToDatabase([]);
+ assert.equal(searches.length, 1);
+ const row = {getAttribute: () => "tree-document"} as unknown as Element;
+ exports.addFilesToDatabase([row]);
+ assert.equal(searches[1].target, row);
+ assert.equal(searches[1].position, undefined);
+});
diff --git a/app/src/protyle/render/av/addToDatabase.ts b/app/src/protyle/render/av/addToDatabase.ts
index 4e89b40441..1a9ba79d77 100644
--- a/app/src/protyle/render/av/addToDatabase.ts
+++ b/app/src/protyle/render/av/addToDatabase.ts
@@ -6,21 +6,17 @@ import * as dayjs from "dayjs";
import {getAVFilteredTipContext} from "./filteredTip";
export const addFilesToDatabase = (fileLiElements: Element[]) => {
- const srcs: IOperationSrcs[] = [];
- fileLiElements.forEach(item => {
- const id = item.getAttribute("data-node-id");
- if (id) {
- srcs.push({
- itemID: Lute.NewNodeID(),
- id,
- isDetached: false
- });
- }
- });
+ addBlocksToDatabase(fileLiElements.map(item => item.getAttribute("data-node-id")).filter(Boolean),
+ fileLiElements[0] as HTMLElement);
+};
+
+export const addBlocksToDatabase = (ids: string[], target: HTMLElement, position?: IPosition) => {
+ const srcs: IOperationSrcs[] = ids.map(id => ({itemID: Lute.NewNodeID(), id, isDetached: false}));
if (srcs.length > 0) {
openSearchAV({
avID: "",
- target: fileLiElements[0] as HTMLElement,
+ target,
+ position,
purpose: "addToDatabase",
callback: (listItemElement) => {
const avID = listItemElement.dataset.avId;
diff --git a/app/src/protyle/render/av/relation.ts b/app/src/protyle/render/av/relation.ts
index 0d526bbc10..d2ef59acdc 100644
--- a/app/src/protyle/render/av/relation.ts
+++ b/app/src/protyle/render/av/relation.ts
@@ -44,6 +44,7 @@ type TSearchAVPurpose = "addToDatabase" | "selectRelation";
interface IOpenSearchAVOptions {
avID: string;
target: HTMLElement;
+ position?: IPosition;
callback?: (element: HTMLElement) => void;
purpose: TSearchAVPurpose;
blockID?: string;
@@ -227,7 +228,7 @@ export const openSearchAV = (options: IOpenSearchAVOptions) => {
});
loadList("", () => {
const rect = options.target.getBoundingClientRect();
- menu.open({
+ menu.open(options.position || {
x: rect.left,
y: rect.bottom,
h: rect.height,