Skip to content

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

:bug: Keep new mind map nodes visible and preserve editing while panning https://github.com/siyuan-note/siyuan/issues/20594

Daniela8f05a7a7549
diff --git a/app/src/protyle/render/listMindmap/editor.test.ts b/app/src/protyle/render/listMindmap/editor.test.ts
index 2a741bdaf6..384d30e82f 100644
--- a/app/src/protyle/render/listMindmap/editor.test.ts
+++ b/app/src/protyle/render/listMindmap/editor.test.ts
@@ -62,6 +62,7 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
document.body.append(container);
const state = {
focusedText: "",
+ panTarget: undefined as Element | undefined,
flushed: 0,
destroyed: 0,
finished: 0,
@@ -183,6 +184,7 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
canEdit: () => element.isConnected,
onResize: noop,
onAdd: async (kind: string) => { state.additions.push(kind); },
+ isPanTarget: (event: PointerEvent) => event.target === state.panTarget,
onFinish: () => state.finished++,
onUndo: noop,
onSave: async (html: string) => {
@@ -249,6 +251,29 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
const paragraph = (id: string, html: string) =>
`<div data-type="NodeParagraph" data-node-id="${id}" class="p"><div contenteditable="true">${html}</div></div>`;
// 粘贴到选中节点时保留原正文,在当前可见正文末尾启动上传;上传结束前保留编辑器。
+ const panEditor = create(paragraph("body", "Keep caret"));
+ const panTarget = document.createElement("div");
+ document.body.append(panTarget);
+ panEditor.state.panTarget = panTarget;
+ const editable = panEditor.wysiwyg.querySelector<HTMLElement>('[contenteditable="true"]');
+ editable.focus();
+ const panRange = document.createRange();
+ panRange.setStart(editable.firstChild, 3);
+ panRange.collapse(true);
+ getSelection().removeAllRanges();
+ getSelection().addRange(panRange);
+ panTarget.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true}));
+ await settle();
+ check.equal(panEditor.state.finished, 0, "canvas panning does not close the node editor");
+ check.equal(document.activeElement, editable);
+ check.equal(getSelection().anchorOffset, 3, "canvas panning retains the insertion point");
+ await require("electron").ipcRenderer.invoke("mindmap-view-editor-type", "X");
+ check.equal(editable.textContent, "KeeXp caret", "typing continues at the retained insertion point");
+ document.body.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true}));
+ await until(() => panEditor.state.finished === 1);
+ panTarget.remove();
+ await panEditor.remove();
+
const imageEditor = create(paragraph("body", "Keep text"));
const images = [new File(["image"], "image.png", {type: "image/png"})];
imageEditor.editor.pasteImages(images);
diff --git a/app/src/protyle/render/listMindmap/editor.ts b/app/src/protyle/render/listMindmap/editor.ts
index c391fd70f7..c8db625299 100644
--- a/app/src/protyle/render/listMindmap/editor.ts
+++ b/app/src/protyle/render/listMindmap/editor.ts
@@ -33,6 +33,7 @@ interface ListMindmapEditorOptions {
onAdd: (kind: "child" | "sibling") => Promise<void>;
onFinish: () => void;
onUndo: (redo: boolean, selection?: Record<string, string>) => void;
+ isPanTarget?: (event: PointerEvent) => boolean;
replaceFirstParagraph?: string;
selection?: Record<string, string>;
}
@@ -486,7 +487,9 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
return !!target.closest("#keyboardToolbar, #commonMenu, .b3-dialog");
};
document.addEventListener("pointerdown", event => {
- if (!belongs(event.target as Node)) {
+ if (options.isPanTarget?.(event)) {
+ captureBeforeChange();
+ } else if (!belongs(event.target as Node)) {
finish();
} else {
// 工具栏浮层位于节点 host 外,格式命令执行前仍需保存原文字选区。
diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.ts
index d735c090f1..c7215baa2f 100644
--- a/app/src/protyle/render/listMindmap/index.ts
+++ b/app/src/protyle/render/listMindmap/index.ts
@@ -671,6 +671,7 @@ class ListMindmapController {
onSave: (html, undo, redo) => this.change(() => replaceListMindmapContent(this.list, id, html), true, id, {undo, redo}),
onResize: () => this.view.refreshLayout(),
onAdd: kind => this.add(id, kind),
+ isPanTarget: event => this.view.isPanTarget(event),
onFinish: () => {
if (this.activeEditor !== editor) {
return;
diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.ts
index 8cff9e21f6..3227340811 100644
--- a/app/src/protyle/render/listMindmap/view.ts
+++ b/app/src/protyle/render/listMindmap/view.ts
@@ -394,6 +394,9 @@ export class ListMindmapView {
private dismissControls = (event: PointerEvent) => {
const target = event.target as Node;
this.tooltip.hidden = true;
+ if (this.editingId && this.isPanTarget(event)) {
+ return;
+ }
if (this.summarySelecting && (this.viewport.contains(target) || this.summaryControls.contains(target))) {
return;
}
@@ -889,6 +892,7 @@ export class ListMindmapView {
}
this.selectNode(id);
this.options.host.focus({preventScroll: true});
+ this.revealNode(id);
}
public setEditing(id?: string) {
@@ -2065,6 +2069,16 @@ export class ListMindmapView {
}
};
+ public isPanTarget(event: PointerEvent) {
+ const target = event.target as HTMLElement;
+ return !this.locked && !this.pinching && !this.summarySelecting && !this.relationFrom &&
+ (event.pointerType !== "touch" || event.isPrimary) && [0, 2].includes(event.button) &&
+ this.viewport.contains(target) && target.closest(".mindmap-view") === this.options.host &&
+ !target.closest("button, input, select, textarea, audio, video, iframe, .mindmap-view__node--editing") &&
+ (this.panning || event.button === 2 ||
+ !target.closest(".mindmap-view__node, .mindmap-view__summary") && !this.findLine(event));
+ }
+
private pointerDown = (event: PointerEvent) => {
if (this.locked || this.pinching || event.pointerType === "touch" && !event.isPrimary) {
return;
@@ -2084,6 +2098,12 @@ export class ListMindmapView {
const element = target.closest<HTMLElement>(".mindmap-view__node");
const id = element?.dataset.mindmapId;
this.preparePointer(event);
+ if (this.editingId && this.isPanTarget(event)) {
+ // 平移只改变画布位置,保留节点编辑器及其文字选区。
+ event.preventDefault();
+ this.beginPointer(event);
+ return;
+ }
this.finishThen(() => {
if (this.pendingPointerId === event.pointerId) {
this.beginPointer(event, id);
@@ -2170,7 +2190,9 @@ export class ListMindmapView {
if (id) {
this.selectNode(id);
}
- this.options.host.focus({preventScroll: true});
+ if (!this.editingId || id) {
+ this.options.host.focus({preventScroll: true});
+ }
this.pointer = {
pointerId: event.pointerId,
rightButton: event.button === 2,
@@ -2413,7 +2435,13 @@ export class ListMindmapView {
if (moved && id && targetId && placement) {
this.options.onMove?.(id, targetId, placement);
} else if (!moved && !id && !pointer.rightButton && !this.readOnly && !this.panning) {
- this.selectLine(event);
+ if (this.editingId) {
+ this.clearSelection();
+ }
+ this.finishThen(() => {
+ this.options.host.focus({preventScroll: true});
+ this.selectLine(event);
+ });
}
};
diff --git a/app/src/protyle/render/listMindmap/viewportFocus.test.ts b/app/src/protyle/render/listMindmap/viewportFocus.test.ts
new file mode 100644
index 0000000000..a2cc905a6c
--- /dev/null
+++ b/app/src/protyle/render/listMindmap/viewportFocus.test.ts
@@ -0,0 +1,137 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isClassDeclaration, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("view.ts", readFileSync("src/protyle/render/listMindmap/view.ts", "utf8"),
+ ScriptTarget.ES2021, true);
+const view = source.statements.find(item => isClassDeclaration(item) && item.name?.text === "ListMindmapView");
+assert.ok(view && isClassDeclaration(view));
+const names = ["focusNode", "revealNode", "isPanTarget", "dismissControls", "pointerDown", "preparePointer", "beginPointer", "pointerUp"];
+const methods = view.members.filter(item => item.name && names.includes(item.name.getText(source)));
+assert.equal(methods.length, names.length);
+const compiled = transpileModule(`class View { ${methods.map(item => item.getText(source)).join("\n")} }
+globalThis.View = View;`, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+
+const setup = () => {
+ const frames: (() => void)[] = [];
+ const context: any = {clearTimeout, requestAnimationFrame: (action: () => void) => frames.push(action)};
+ runInNewContext(compiled, context);
+ let focus = "editor";
+ let finished = 0;
+ let drawn = 0;
+ const host = {focus: () => focus = "canvas"};
+ const target = Object.assign(new context.View(), {
+ options: {host}, editingId: "new", model: {nodes: new Map([["new", {}]])},
+ selectedId: "new", tooltip: {},
+ nodeElements: new Map(), offsetX: 0, offsetY: 0,
+ viewport: {contains: (element: unknown) => !!element, setPointerCapture: () => {},
+ getBoundingClientRect: () => ({left: 0, top: 0, right: 400, bottom: 300, width: 400, height: 300})},
+ selectNode: () => {}, findLine: (): unknown => undefined, selectLine: () => {},
+ clearSelection: () => { target.selectedId = undefined; },
+ boundedPan: (x: number, y: number) => ({x, y}), draw: () => drawn++,
+ finishThen: (action: () => void) => { finished++; target.editingId = undefined; action(); },
+ cancelPointer: () => { target.pointer = undefined; },
+ });
+ const element = (kind = "background") => ({
+ dataset: {mindmapId: "other"},
+ closest: (selector: string) => {
+ if (selector === ".mindmap-view") {
+ return host;
+ }
+ return kind !== "background" && selector.includes(kind) ? element() : null;
+ },
+ });
+ const event = (kind = "background", overrides: Record<string, unknown> = {}) => ({
+ target: element(kind), pointerId: 1, pointerType: "mouse", isPrimary: true, button: 0,
+ clientX: 20, clientY: 20, defaultPrevented: false,
+ preventDefault() { this.defaultPrevented = true; }, ...overrides,
+ });
+ return {target, frames, event, focus: () => focus, finished: () => finished, drawn: () => drawn};
+};
+
+test("focusing a new offscreen node reveals it after the pending layout", () => {
+ const {target, frames, drawn} = setup();
+ target.frame = 1;
+ let rect = {left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0};
+ target.nodeElements.set("new", {getBoundingClientRect: () => rect});
+ target.focusNode("new");
+ assert.equal(drawn(), 0);
+ rect = {left: 420, top: 320, right: 500, bottom: 360, width: 80, height: 40};
+ frames.forEach(action => action());
+ assert.equal(target.offsetX, -116);
+ assert.equal(target.offsetY, -76);
+ assert.equal(drawn(), 1);
+});
+
+test("focusing visible, missing or removed nodes does not pan", () => {
+ const {target, drawn} = setup();
+ target.nodeElements.set("new", {getBoundingClientRect: () =>
+ ({left: 100, top: 100, right: 200, bottom: 140, width: 100, height: 40})});
+ target.focusNode("new");
+ target.focusNode("missing");
+ target.destroyed = true;
+ target.focusNode("new");
+ assert.equal(drawn(), 0);
+});
+
+test("mouse, right-button and primary touch panning preserve the editing focus", () => {
+ for (const overrides of [{}, {button: 2}, {pointerType: "touch"}]) {
+ const {target, event, focus, finished} = setup();
+ const down = event("background", overrides);
+ target.dismissControls(down);
+ target.pointerDown(down);
+ assert.equal(down.defaultPrevented, true);
+ assert.equal(focus(), "editor");
+ assert.equal(finished(), 0);
+ assert.ok(target.pointer);
+ target.pointer.moved = true;
+ target.pointerUp(down);
+ assert.equal(focus(), "editor");
+ assert.equal(finished(), 0);
+ assert.equal(target.editingId, "new");
+ assert.equal(target.selectedId, "new");
+ }
+});
+
+test("a background click still finishes editing while a canceled drag leaves it active", () => {
+ const {target, event, focus, finished} = setup();
+ const down = event();
+ target.pointerDown(down);
+ target.pointerUp(down);
+ assert.equal(finished(), 1);
+ assert.equal(focus(), "canvas");
+ target.editingId = "new";
+ target.pointerDown(event());
+ target.cancelPointer();
+ assert.equal(target.editingId, "new");
+ assert.equal(finished(), 1);
+});
+
+test("nodes, controls, nested maps, lines and non-pan modes retain their own interactions", () => {
+ const {target, event} = setup();
+ for (const kind of [".mindmap-view__node", "button", ".mindmap-view__node--editing", ".mindmap-view__summary"]) {
+ assert.equal(target.isPanTarget(event(kind)), false, kind);
+ }
+ assert.equal(target.isPanTarget(event("background", {pointerType: "touch", isPrimary: false})), false);
+ assert.equal(target.isPanTarget(event("background", {target: {closest: () => ({})}})), false);
+ target.findLine = () => ({relation: true});
+ assert.equal(target.isPanTarget(event()), false);
+ target.findLine = (): unknown => undefined;
+ for (const key of ["locked", "pinching", "summarySelecting", "relationFrom"]) {
+ target[key] = true;
+ assert.equal(target.isPanTarget(event()), false, key);
+ target[key] = false;
+ }
+});
+
+test("clicking a virtual root preserves its selection for title editing", () => {
+ const {target, event} = setup();
+ target.editingId = undefined;
+ target.model.nodes.set("new", {virtual: true});
+ const down = event();
+ target.beginPointer(down, "new");
+ target.pointerUp(down);
+ assert.equal(target.selectedId, "new");
+});