Skip to content

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

:art: Improve Cut and Paste (#17850)

未来方舟57819eb4f195
diff --git a/app/src/protyle/undo/index.ts b/app/src/protyle/undo/index.ts
index 3d615e522d..8d47174283 100644
--- a/app/src/protyle/undo/index.ts
+++ b/app/src/protyle/undo/index.ts
@@ -4,6 +4,7 @@ import {Constants} from "../../constants";
import {hideElements} from "../ui/hideElements";
import {scrollCenter} from "../../util/highlightById";
import {matchHotKey} from "../util/hotKey";
+import {fetchSyncPost} from "../../util/fetch";
import {ipcRenderer} from "electron";
import {markMirror, refreshUndoButtons, requestRedo, requestUndo} from "./globalUndo";
@@ -26,6 +27,96 @@ export class Undo {
requestRedo(protyle);
}
+
+ // 重放 insert 操作前检查块 ID 是否已被占用(例如剪切后粘贴到其他编辑器时保留了原 ID,
+ // 此时撤销剪切会插入重复 ID 的块),冲突时在两个栈中统一替换为新 ID
+ private async resolveDuplicateIds(operations: IOperation[]) {
+ const ids = new Set<string>();
+ operations.forEach(op => {
+ if (op.action === "insert" && typeof op.data === "string") {
+ if (op.id) {
+ ids.add(op.id);
+ }
+ op.data.match(/data-node-id="[^"]+"/g)?.forEach((match: string) => {
+ ids.add(match.substring(14, match.length - 1));
+ });
+ }
+ });
+ if (ids.size === 0) {
+ return;
+ }
+ let existResponse: IWebSocketData;
+ try {
+ existResponse = await fetchSyncPost("/api/block/checkBlocksExist", {ids: Array.from(ids)});
+ } catch (e) {
+ return;
+ }
+ if (!existResponse?.data) {
+ return;
+ }
+ const replacements: [string, string][] = [];
+ ids.forEach(id => {
+ if (existResponse.data[id] === true) {
+ replacements.push([id, Lute.NewNodeID()]);
+ }
+ });
+ if (replacements.length === 0) {
+ return;
+ }
+ [this.undoStack, this.redoStack].forEach(stack => {
+ stack.forEach(item => {
+ [item.doOperations, item.undoOperations].forEach(ops => {
+ ops.forEach(op => {
+ replacements.forEach(([oldId, newId]) => {
+ if (op.id === oldId) {
+ op.id = newId;
+ }
+ if (op.parentID === oldId) {
+ op.parentID = newId;
+ }
+ if (op.previousID === oldId) {
+ op.previousID = newId;
+ }
+ if (op.nextID === oldId) {
+ op.nextID = newId;
+ }
+ if (typeof op.data === "string") {
+ op.data = op.data.split(`data-node-id="${oldId}"`).join(`data-node-id="${newId}"`);
+ }
+ });
+ });
+ });
+ });
+ });
+ }
+
+ private async render(protyle: IProtyle, state: IOperations, redo: boolean) {
+ hideElements(["hint", "gutter"], protyle);
+ protyle.wysiwyg.lastHTMLs = {};
+ await this.resolveDuplicateIds(redo ? state.doOperations : state.undoOperations);
+ if (!redo) {
+ for (let i = state.undoOperations.length - 1; i >= 0; i--) {
+ if (state.undoOperations[i].action === "insert") {
+ if (state.undoOperations[i].context) {
+ state.undoOperations[i].context.setRange = "true";
+ } else {
+ state.undoOperations[i].context = {setRange: "true"};
+ }
+ break;
+ }
+ }
+ onTransaction(protyle, state.undoOperations, true);
+ transaction(protyle, state.undoOperations, undefined, {skipSync: true});
+ } else {
+ for (let i = state.doOperations.length - 1; i >= 0; i--) {
+ if (state.doOperations[i].action === "insert") {
+ if (state.doOperations[i].context) {
+ state.doOperations[i].context.setRange = "true";
+ } else {
+ state.doOperations[i].context = {setRange: "true"};
+ }
+ break;
+
// renderLocal 仅在发起窗口本地应用操作(isUndo=true),不 POST 到 kernel
// (kernel 的 undo/redo 接口已执行事务并广播)。保留光标恢复/折叠/zoom/lastHTMLs 行为。
public renderLocal(protyle: IProtyle, operations: IOperation[], isRedo: boolean) {
@@ -37,6 +128,7 @@ export class Undo {
operations[i].context.setRange = "true";
} else {
operations[i].context = {setRange: "true"};
+
}
break;
}
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index cf7385df90..aeb3267317 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -6,7 +6,7 @@ import {hasClosestBlock, hasClosestByAttribute, hasClosestByClassName} from "./h
import {getEditorRange, getSelectionOffset} from "./selection";
import {blockRender} from "../render/blockRender";
import {highlightRender} from "../render/highlightRender";
-import {fetchPost} from "../../util/fetch";
+import {fetchPost, fetchSyncPost} from "../../util/fetch";
import {isDynamicRef, isFileAnnotation} from "../../util/functions";
import {insertHTML} from "./insertHTML";
import {scrollCenter} from "../../util/highlightById";
@@ -482,12 +482,23 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
}
}
let isBlock = false;
- tempElement.querySelectorAll("[data-node-id]").forEach((e) => {
- const newId = Lute.NewNodeID();
- e.setAttribute("data-node-id", newId);
- clearBlockElement(e);
+ const pastedBlockElements = tempElement.querySelectorAll("[data-node-id]");
+ if (pastedBlockElements.length > 0) {
isBlock = true;
- });
+ // 剪切后粘贴时原块已被删除,保留原 ID 可避免该块被其他位置的引用失效;
+ // 仅当 ID 仍存在(复制粘贴)时才生成新 ID
+ const oldIds: string[] = [];
+ pastedBlockElements.forEach((e) => {
+ oldIds.push(e.getAttribute("data-node-id"));
+ });
+ const existResponse = await fetchSyncPost("/api/block/checkBlocksExist", {ids: oldIds});
+ pastedBlockElements.forEach((e) => {
+ if (existResponse.data[e.getAttribute("data-node-id")] !== false) {
+ e.setAttribute("data-node-id", Lute.NewNodeID());
+ }
+ clearBlockElement(e);
+ });
+ }
if (nodeElement.classList.contains("table")) {
isBlock = false;
}
diff --git a/kernel/api/block.go b/kernel/api/block.go
index 71cb42147c..03eaf0b36c 100644
--- a/kernel/api/block.go
+++ b/kernel/api/block.go
@@ -23,6 +23,7 @@ import (
"strings"
"github.com/88250/gulu"
+ "github.com/88250/lute/ast"
"github.com/88250/lute/html"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/logging"
@@ -376,6 +377,25 @@ func checkBlockExist(c *gin.Context) {
ret.Data = treenode.ExistBlockTree(id)
}
+func checkBlocksExist(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ idsArg := arg["ids"].([]interface{})
+ var ids []string
+ for _, idArg := range idsArg {
+ if id, idOk := idArg.(string); idOk && ast.IsNodeIDPattern(id) {
+ ids = append(ids, id)
+ }
+ }
+ ret.Data = treenode.ExistBlockTrees(ids)
+}
+
func getDocInfo(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/api/router.go b/kernel/api/router.go
index b9b2847deb..e59ef4f8b3 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -228,6 +228,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/block/getDocInfo", model.CheckAuth, getDocInfo)
ginServer.Handle("POST", "/api/block/getDocsInfo", model.CheckAuth, getDocsInfo)
ginServer.Handle("POST", "/api/block/checkBlockExist", model.CheckAuth, checkBlockExist)
+ ginServer.Handle("POST", "/api/block/checkBlocksExist", model.CheckAuth, checkBlocksExist)
ginServer.Handle("POST", "/api/block/getUnfoldedParentID", model.CheckAuth, getUnfoldedParentID)
ginServer.Handle("POST", "/api/block/checkBlockFold", model.CheckAuth, checkBlockFold)
ginServer.Handle("POST", "/api/block/insertBlock", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, insertBlock)