Skip to content

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

:bug: Route whole mind map cuts through the editor https://github.com/siyuan-note/siyuan/issues/20774

Daniel1e35f4cf3ad0
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index 2756301866..226e17b87b 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -1,5 +1,5 @@
import {toggleMenu} from "../../menus/menuToggle";
-import {copyBlockSelection} from "../util/blockClipboard";
+import {copyBlockSelection, cutBlockSelection} from "../util/blockClipboard";
import {
hasClosestBlock,
hasClosestByAttribute,
@@ -1391,7 +1391,7 @@ export class Gutter {
icon: "iconCut",
click: () => {
focusBlock(selectsElement[0]);
- document.execCommand("cut");
+ cutBlockSelection(selectsElement[0]);
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
@@ -2050,7 +2050,7 @@ export class Gutter {
accelerator: "⌘X",
click: () => {
focusBlock(nodeElement);
- document.execCommand("cut");
+ cutBlockSelection(nodeElement);
}
}).element);
}
diff --git a/app/src/protyle/util/blockClipboard.ts b/app/src/protyle/util/blockClipboard.ts
index ec28712e1b..22aeab263e 100644
--- a/app/src/protyle/util/blockClipboard.ts
+++ b/app/src/protyle/util/blockClipboard.ts
@@ -1,9 +1,25 @@
import {isIOSPlatform} from "./browserCompatibility";
+const isMindmapBlock = (element: Element) =>
+ element.matches('[data-type="NodeMindmap"], [data-type="NodeList"][data-mindmap-view-rendered="true"]');
+
+export const cutBlockSelection = (element: Element) => {
+ if (isMindmapBlock(element)) {
+ // 隐藏源节点的脑图没有原生可剪切区域,交给正文编辑器写入剪贴板成功后删除。
+ copyBlockSelection(element, () => element.closest(".protyle-wysiwyg")?.dispatchEvent(new ClipboardEvent("cut", {
+ bubbles: true,
+ cancelable: true,
+ clipboardData: new DataTransfer(),
+ })));
+ return;
+ }
+ copyBlockSelection(element, () => document.execCommand("cut"));
+};
+
export const copyBlockSelection = (element: Element, copy: () => void = () => document.execCommand("copy")) => {
const avCursor = element.matches('[data-type="NodeAttributeView"]') ?
element.querySelector<HTMLElement>(".av__cursor") : null;
- const mindmap = element.matches('[data-type="NodeMindmap"], [data-type="NodeList"][data-mindmap-view-rendered="true"]');
+ const mindmap = isMindmapBlock(element);
if (!isIOSPlatform(navigator) && !avCursor && !mindmap) {
copy();
return;
diff --git a/app/src/protyle/util/mindmapClipboard.dom.test.ts b/app/src/protyle/util/mindmapClipboard.dom.test.ts
index d27826b276..75eb42a975 100644
--- a/app/src/protyle/util/mindmapClipboard.dom.test.ts
+++ b/app/src/protyle/util/mindmapClipboard.dom.test.ts
@@ -12,11 +12,16 @@ const compile = (source: string) => ts.transpileModule(source
compilerOptions: {target: ts.ScriptTarget.ES2021},
}).outputText;
-const browserCases = (source: string, copyBinding: string, css: string, lutePath: string) => {
+const browserCases = async (source: string, copyBinding: string, cutBinding: string, css: string, lutePath: string) => {
const check = require("node:assert/strict");
require(lutePath);
const identity = (value: string) => value;
const noop = (): void => undefined;
+ let clipboardFailed = false;
+ let cutCount = 0;
+ let cutData: {textSiyuan: string};
+ const errors: string[] = [];
+ window.addEventListener("unhandledrejection", event => errors.push(String(event.reason?.stack || event.reason)));
const closestBlock = (node: Node) => (node.nodeType === Node.ELEMENT_NODE ? node as Element : node.parentElement)
?.closest("[data-node-id]");
const dependencies = {
@@ -28,6 +33,22 @@ const browserCases = (source: string, copyBinding: string, css: string, lutePath
stripSemanticMarkersFromRangeText: (range: Range) => range.toString(),
hasClosestBlock: closestBlock,
hasClosestByTag: (): null => null,
+ hasClosestByClassName: (): null => null,
+ isInEmbedBlock: (): false => false,
+ getTopAloneElement: (element: Element) => element,
+ getNextBlock: (): false => false,
+ confirmBlockRef: async () => true,
+ focusBlock: noop,
+ showMessage: noop,
+ writeClipboardData: async (data: {textSiyuan: string}) => {
+ cutData = data;
+ return {status: clipboardFailed ? "failed" : "success"};
+ },
+ removeBlockPreservingSelectionMode: async (_owner: IProtyle, element: Element) => {
+ cutCount++;
+ element.remove();
+ return true;
+ },
getBlockSelectionModeElement: (): null => null,
getAVSelectedCells: (): Element[] => [],
isTableLikeView: () => false,
@@ -44,9 +65,10 @@ const browserCases = (source: string, copyBinding: string, css: string, lutePath
enhanceRichClipboard: noop,
};
const api = new Function(...Object.keys(dependencies), source +
- "return {copyBlockSelection, getPlainText, bindCopy: function(protyle) {" + copyBinding + "}};")(
+ "return {copyBlockSelection, getPlainText, cutSingle, cutMultiple, bindCopy: function(protyle) {" +
+ copyBinding + "}, bindCut: function(protyle) {" + cutBinding + "}};")(
...Object.values(dependencies));
- window.siyuan = {ctrlIsPressed: false} as unknown as typeof window.siyuan;
+ window.siyuan = {ctrlIsPressed: false, languages: {clipboardPermissionDenied: "Clipboard denied"}} as unknown as typeof window.siyuan;
const style = document.createElement("style");
style.textContent = css;
document.head.append(style);
@@ -61,6 +83,7 @@ const browserCases = (source: string, copyBinding: string, css: string, lutePath
lute.SetProtyleWYSIWYG(true);
const wysiwyg = {element: editor, copyAsRichText: false};
api.bindCopy.call(wysiwyg, {lute, wysiwyg, disabled: false});
+ api.bindCut.call(wysiwyg, {lute, wysiwyg, disabled: false, hint: {render: noop}, options: {render: {breadcrumb: false}}});
for (const exported of [false, true]) {
editor.innerHTML = lute.Md2BlockDOM("- Root\n - Child\n{: custom-sy-list-mindmap=\"1\"}\n");
const map = editor.firstElementChild as HTMLElement;
@@ -108,30 +131,78 @@ const browserCases = (source: string, copyBinding: string, css: string, lutePath
check.equal(map.outerHTML, before, "copy must preserve the source and rendered view");
}
}
+ for (const cut of [api.cutSingle, api.cutMultiple]) {
+ for (const fail of [true, false]) {
+ editor.innerHTML = lute.Md2BlockDOM("- Root\n - Child\n{: custom-sy-list-mindmap=\"1\"}\n");
+ const map = editor.firstElementChild as HTMLElement;
+ map.dataset.type = "NodeMindmap";
+ map.classList.add("protyle-wysiwyg--select");
+ map.querySelectorAll('[data-type="NodeListItem"]').forEach(item => item.setAttribute("data-type", "NodeMindmapItem"));
+ map.dataset.mindmapViewRendered = "true";
+ map.insertAdjacentHTML("beforeend", '<div class="mindmap-view" contenteditable="false" tabindex="0">Rendered map</div>');
+ outside.focus();
+ getSelection().removeAllRanges();
+ const saved = document.createRange();
+ saved.selectNodeContents(outside);
+ getSelection().addRange(saved);
+ clipboardFailed = fail;
+ cutData = undefined;
+ const before = cutCount;
+ cut(map);
+ await new Promise(resolve => setTimeout(resolve, 20));
+ check.deepEqual(errors, []);
+ check.ok(cutData, "menu cut reaches the editor even when native cutting has no editable target");
+ check.equal(cutCount, before + (fail ? 0 : 1), "menu cut deletes only after clipboard success");
+ check.equal(map.isConnected, fail, "clipboard failure preserves the whole map");
+ check.match(cutData.textSiyuan, /NodeMindmap/);
+ check.match(cutData.textSiyuan, /Child/);
+ check.doesNotMatch(cutData.textSiyuan, /mindmap-view|Rendered map/);
+ }
+ }
editor.remove();
outside.remove();
return "mindmap-clipboard-ok";
};
-test("mind map block copying reaches the editor, extracts source text and hides export source items", {timeout: 30000}, async () => {
+test("mind map block copy and cut reach the editor and preserve content on clipboard failure", {timeout: 30000}, async () => {
const model = readFileSync("src/protyle/render/listMindmap/model.ts", "utf8");
const paste = ts.createSourceFile("paste.ts", readFileSync("src/protyle/util/paste.ts", "utf8"), ts.ScriptTarget.Latest, true);
const plain = paste.statements.find(statement => ts.isVariableStatement(statement) &&
statement.declarationList.declarations.some(item => item.name.getText(paste) === "getPlainText"));
const wysiwyg = ts.createSourceFile("index.ts", readFileSync("src/protyle/wysiwyg/index.ts", "utf8"), ts.ScriptTarget.Latest, true);
let binding: ts.CallExpression;
+ let cutBinding: ts.CallExpression;
const visit = (node: ts.Node) => {
if (ts.isCallExpression(node) && node.expression.getText(wysiwyg) === "this.element.addEventListener" &&
node.arguments[0]?.getText(wysiwyg) === '"copy"') {
binding = node;
}
+ if (ts.isCallExpression(node) && node.expression.getText(wysiwyg) === "this.element.addEventListener" &&
+ node.arguments[0]?.getText(wysiwyg) === '"cut"') {
+ cutBinding = node;
+ }
node.forEachChild(visit);
};
visit(wysiwyg);
assert.ok(binding);
+ assert.ok(cutBinding);
+ const gutter = ts.createSourceFile("gutter.ts", readFileSync("src/protyle/gutter/index.ts", "utf8"), ts.ScriptTarget.Latest, true);
+ const cutMenus: string[] = [];
+ const visitMenu = (node: ts.Node) => {
+ if (ts.isObjectLiteralExpression(node) && node.properties.some(property =>
+ property.name?.getText(gutter) === "id" && ts.isPropertyAssignment(property) && property.initializer.getText(gutter) === '"cut"')) {
+ const click = node.properties.find(property => property.name?.getText(gutter) === "click") as ts.PropertyAssignment;
+ const text = click.initializer.getText(gutter);
+ cutMenus.push(`function ${text.includes("selectsElement") ? "cutMultiple(selectsElement)" : "cutSingle(nodeElement)"} { (${text})(); }`);
+ }
+ node.forEachChild(visitMenu);
+ };
+ visitMenu(gutter);
+ assert.equal(cutMenus.length, 2);
+ cutMenus[0] = cutMenus[0].replace("cutMultiple(selectsElement)", "cutMultiple(element)").replace("{ (", "{ const selectsElement = [element]; (");
const source = compile(model.slice(model.indexOf("const cleanListMindmapDOM ="),
model.indexOf("// 转换前将思维导图块"))) + compile(plain.getText(paste)) +
- compile(readFileSync("src/protyle/util/blockClipboard.ts", "utf8"));
+ compile(readFileSync("src/protyle/util/blockClipboard.ts", "utf8")) + compile(cutMenus.join("\n"));
const css = require("sass").compile("src/assets/scss/protyle/_mindmap-view.scss").css;
const directory = mkdtempSync(path.join(tmpdir(), "siyuan-mindmap-copy-"));
const script = path.join(directory, "main.cjs");
@@ -143,7 +214,7 @@ app.whenReady().then(async () => {
await win.loadURL("about:blank");
console.log(await win.webContents.executeJavaScript(${JSON.stringify(
`const __name = value => value; (() => {try {return (${browserCases.toString()})(${JSON.stringify(source)},
-${JSON.stringify(compile(binding.getText(wysiwyg)))}, ${JSON.stringify(css)},
+${JSON.stringify(compile(binding.getText(wysiwyg)))}, ${JSON.stringify(compile(cutBinding.getText(wysiwyg)))}, ${JSON.stringify(css)},
${JSON.stringify(path.resolve("stage/protyle/js/lute/lute.min.js"))});} catch (error) {return error.stack;}})()`)}));
app.exit(0);
} catch (error) { console.error(error); app.exit(1); }