An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve Cut and Paste https://github.com/siyuan-note/siyuan/pull/17850
Daniela264caa3fe22
diff --git a/app/src/protyle/undo/globalUndo.ts b/app/src/protyle/undo/globalUndo.tsindex 687fc59644..2612667914 100644--- a/app/src/protyle/undo/globalUndo.ts+++ b/app/src/protyle/undo/globalUndo.ts@@ -212,16 +212,16 @@ export const requestUndo = async (protyle: IProtyle) => {markMirror(rootID, {canUndo: !!data.canUndo, canRedo: !!data.canRedo});const mutatedRootIDs: string[] = data.mutatedRootIDs || [];if (mutatedRootIDs.length > 1) {- // 跨文档撤销:undoOperations 的锚点分散在多个文档,当前 protyle 无法本地乐观应用。+ // 跨文档撤销:doOperations 的锚点分散在多个文档,当前 protyle 无法本地乐观应用。// 改为靠 kernel 广播(含发起方)刷新所有涉及文档的 DOM。// 这里不调 renderLocal,避免在错误 protyle 上应用跨文档 move 导致前后端不一致。refreshUndoButtons(protyle);// 广播会到达当前窗口(/undo 对跨文档用 PushModeBroadcast),触发 onTransaction 刷新 DOM} else {- // 单文档撤销:发起窗口本地乐观应用(isUndo=true,保光标/折叠/zoom)- protyle.undo.renderLocal(protyle, data.undoOperations, false);+ // 单文档撤销:发起窗口本地乐观应用 doOperations(kernel 实际执行的操作,如 insert 恢复块)+ protyle.undo.renderLocal(protyle, data.doOperations, false);refreshUndoButtons(protyle);- const focusBlockId = data.undoOperations?.find((op: IOperation) => op.action === "insert")?.id;+ const focusBlockId = data.doOperations?.find((op: IOperation) => op.action === "insert")?.id;focusRootIDs(mutatedRootIDs, focusBlockId);}});diff --git a/app/src/protyle/undo/index.ts b/app/src/protyle/undo/index.tsindex 8d47174283..fe6d76d664 100644--- a/app/src/protyle/undo/index.ts+++ b/app/src/protyle/undo/index.ts@@ -4,7 +4,6 @@ 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";@@ -27,96 +26,6 @@ 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) {diff --git a/app/src/protyle/util/clear.ts b/app/src/protyle/util/clear.tsindex 2574964c92..cf76cb7f31 100644--- a/app/src/protyle/util/clear.ts+++ b/app/src/protyle/util/clear.ts@@ -1,11 +1,13 @@import {updateHeader} from "../render/av/row";import {Constants} from "../../constants";-export const clearBlockElement = (element: Element) => {+export const clearBlockElement = (element: Element, keepRefcount = false) => {element.classList.remove("protyle-wysiwyg--select", "protyle-wysiwyg--hl");element.removeAttribute(Constants.CUSTOM_RIFF_DECKS);- element.removeAttribute("refcount");- element.querySelector(".protyle-attr--refcount")?.remove();+ if (!keepRefcount) {+ element.removeAttribute("refcount");+ element.querySelector(".protyle-attr--refcount")?.remove();+ }element.querySelector(".protyle-attr--av")?.remove();element.removeAttribute("custom-avs");element.getAttributeNames().forEach(attr => {diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex aeb3267317..3835307dbc 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -493,10 +493,13 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven});const existResponse = await fetchSyncPost("/api/block/checkBlocksExist", {ids: oldIds});pastedBlockElements.forEach((e) => {- if (existResponse.data[e.getAttribute("data-node-id")] !== false) {+ const originalId = e.getAttribute("data-node-id");+ const isCutPaste = existResponse.data[originalId] === false; // 剪切来的(原块已删)+ if (!isCutPaste) {+ // 复制粘贴:生成新 IDe.setAttribute("data-node-id", Lute.NewNodeID());}- clearBlockElement(e);+ clearBlockElement(e, isCutPaste); // 剪切粘贴保留引用角标});}if (nodeElement.classList.contains("table")) {diff --git a/kernel/api/transaction.go b/kernel/api/transaction.goindex ff02c246cd..a8e9af40d7 100644--- a/kernel/api/transaction.go+++ b/kernel/api/transaction.go@@ -202,6 +202,8 @@ func performUndo(c *gin.Context) {UndoOperations: entry.DoOperationsForReplay(),}tx.MarkReplay()+ // 重放前解决剪切后粘贴造成的块 ID 冲突(已存在的 ID 换新,避免重复)+ model.ResolveReplayDuplicateIds(tx)if err := model.PerformTxSync(tx); nil != err {// 逆操作执行失败,回滚执行栈。返回 code=0 + data.failed=true(而非 code=-1),@@ -221,9 +223,10 @@ func performUndo(c *gin.Context) {pushUndoTransactions(app, session, []*model.Transaction{tx}, true, crossDoc)canUndo, canRedo, _ := model.GlobalUndoLog.State(rootID)+ // 返回重放后(已解决 ID 冲突)的 tx 操作,前端乐观应用与 kernel 落盘一致ret.Data = map[string]any{- "doOperations": entry.DoOperationsForReplay(),- "undoOperations": entry.UndoOperationsForReplay(),+ "doOperations": tx.DoOperations,+ "undoOperations": tx.UndoOperations,"mutatedRootIDs": entry.MutatedRootIDs(),"canUndo": canUndo,"canRedo": canRedo,@@ -265,6 +268,8 @@ func performRedo(c *gin.Context) {UndoOperations: entry.UndoOperationsForReplay(),}tx.MarkReplay()+ // 重放前解决剪切后粘贴造成的块 ID 冲突(已存在的 ID 换新,避免重复)+ model.ResolveReplayDuplicateIds(tx)if err := model.PerformTxSync(tx); nil != err {// 重做失败,回滚执行栈。返回 code=0 + data.failed=true(避免前端 isUndoing 死锁)。@@ -283,9 +288,10 @@ func performRedo(c *gin.Context) {pushUndoTransactions(app, session, []*model.Transaction{tx}, true, crossDoc)canUndo, canRedo, _ := model.GlobalUndoLog.State(rootID)+ // 返回重放后(已解决 ID 冲突)的 tx 操作,前端乐观应用与 kernel 落盘一致ret.Data = map[string]any{- "doOperations": entry.DoOperationsForReplay(),- "undoOperations": entry.UndoOperationsForReplay(),+ "doOperations": tx.DoOperations,+ "undoOperations": tx.UndoOperations,"mutatedRootIDs": entry.MutatedRootIDs(),"canUndo": canUndo,"canRedo": canRedo,diff --git a/kernel/model/undolog.go b/kernel/model/undolog.goindex c904b4d844..57dc86776c 100644--- a/kernel/model/undolog.go+++ b/kernel/model/undolog.go@@ -18,11 +18,14 @@ package modelimport ("fmt"+ "regexp""sync""sync/atomic""time""github.com/88250/gulu"+ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/treenode")// UndoEntry 是撤销栈中的一条记录。跨文档操作(MutatedRootIDs 含多个 rootID)的 entry@@ -363,3 +366,106 @@ func cloneOperations(ops []*Operation) []*Operation {}return ret}++var dataNodeIDPattern = regexp.MustCompile(`data-node-id="([^"]+)"`)+var refcountAttrPattern = regexp.MustCompile(`\s*refcount="[^"]*"`)+var refcountDivPattern = regexp.MustCompile(`<div class="protyle-attr--refcount[^"]*"[^>]*>.*?</div>`)++// ResolveReplayDuplicateIds 在 undo/redo 重放事务前解决块 ID 冲突。+// 场景:剪切块 X 后粘贴到别处(保留原 ID),再撤销剪切会 insert X,而 X 已存在于粘贴处,产生重复 ID。+// 这里对即将重放的 insert 操作做检查——若其引入的 ID 在块树中已存在,则在正反向操作及关联字段+// (ID/ParentID/PreviousID/NextID 与 Data 内联 ID)上统一替换为新 ID。+// 替换同时作用于 do/undo 两套操作:重放只执行 doOperations,但若不同步改 undoOperations,+// 随后对同一 entry 的 redo 会沿用旧 ID 再次撞库。+func ResolveReplayDuplicateIds(tx *Transaction) {+ if nil == tx || !tx.isReplay {+ return+ }++ // 收集所有 insert 操作引入的块 ID(op.ID + Data 内联的 data-node-id)+ ids := map[string]struct{}{}+ collect := func(ops []*Operation) {+ for _, op := range ops {+ if "insert" != op.Action {+ continue+ }+ if "" != op.ID && ast.IsNodeIDPattern(op.ID) {+ ids[op.ID] = struct{}{}+ }+ data, ok := op.Data.(string)+ if !ok {+ continue+ }+ for _, m := range dataNodeIDPattern.FindAllStringSubmatch(data, -1) {+ if ast.IsNodeIDPattern(m[1]) {+ ids[m[1]] = struct{}{}+ }+ }+ }+ }+ collect(tx.DoOperations)+ // 注意:只检测 DoOperations(实际执行的操作),不检测 UndoOperations。+ // UndoOperations 在 redo 时会作为新的 DoOperations 再次过 ResolveReplayDuplicateIds。+ // 若 undo 时也检测 UndoOperations 的 insert,会把 redo 用的 ID 换新,+ // 污染 DoOperations 的对应 delete(do/undo 共享 replacements),导致撤销删除错误 ID。+ if 0 == len(ids) {+ return+ }++ idList := make([]string, 0, len(ids))+ for id := range ids {+ idList = append(idList, id)+ }+ exist := treenode.ExistBlockTrees(idList)++ // 已存在的 ID 生成替换+ replacements := map[string]string{}+ for _, id := range idList {+ if exist[id] {+ replacements[id] = ast.NewNodeID()+ }+ }+ if 0 == len(replacements) {+ return+ }++ // 对 do/undo 两套操作统一替换 ID 及关联字段+ apply := func(ops []*Operation) {+ for _, op := range ops {+ // 记录本操作的 ID 是否被换新(在改 op.ID 之前判断,否则 replacements 的 key 是 oldID 查不到)+ _, idReplaced := replacements[op.ID]+ if newID, ok := replacements[op.ID]; ok {+ op.ID = newID+ }+ if newID, ok := replacements[op.ParentID]; ok {+ op.ParentID = newID+ }+ if newID, ok := replacements[op.PreviousID]; ok {+ op.PreviousID = newID+ }+ if newID, ok := replacements[op.NextID]; ok {+ op.NextID = newID+ }+ data, ok := op.Data.(string)+ if !ok {+ continue+ }+ for oldID, newID := range replacements {+ data = dataNodeIDPattern.ReplaceAllStringFunc(data, func(match string) string {+ if sub := dataNodeIDPattern.FindStringSubmatch(match); len(sub) > 1 && sub[1] == oldID {+ return `data-node-id="` + newID + `"`+ }+ return match+ })+ }+ // ID 被换新的块(剪切粘贴后撤销恢复的副本)清除引用角标,避免显示旧的 refcount。+ // 角标由 kernel 异步刷新(refreshRefCount)重建为正确值。+ if idReplaced {+ data = refcountDivPattern.ReplaceAllString(data, "")+ data = refcountAttrPattern.ReplaceAllString(data, "")+ }+ op.Data = data+ }+ }+ apply(tx.DoOperations)+}