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 folded list item state after child changes https://github.com/siyuan-note/siyuan/issues/12327
Danielb677b88d5a0c
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 2eef5eb751..27008ca282 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -468,6 +468,9 @@ const promiseTransaction = (options: {processFold(operation, protyle);return;}+ if (operation.action === "setAttrs") {+ syncFoldAndStyleAttrs(protyle.wysiwyg.element, operation);+ }});}// 事务提交后再渲染嵌入块,避免其查询请求早于写入到达内核而拿到旧数据diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex a5809a389a..f9f74b1f24 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -435,6 +435,11 @@ func performTx(tx *Transaction) (ret *TxErr) {}}+ if ret = tx.normalizeListItemFolds(); nil != ret {+ tx.rollback()+ return+ }+if cr := tx.commit(); nil != cr {logging.LogErrorf("commit tx failed: %s", cr)if 1 == tx.state.Load() {@@ -555,6 +560,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {if isMovingFoldHeading := ast.NodeHeading == srcNode.Type && treenode.IsSelfFolded(srcNode); isMovingFoldHeading {headingChildren = treenode.HeadingChildren(srcNode)}+ srcParent := srcNode.Parentvar srcEmptyList *ast.Nodeif ast.NodeListItem == srcNode.Type && srcNode.Parent.FirstChild == srcNode && srcNode.Parent.LastChild == srcNode {@@ -626,6 +632,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {}}+ tx.markListItemFoldCandidate(srcParent, srcTree)for i := len(headingChildren) - 1; -1 < i; i-- {c := headingChildren[i]targetNode.InsertAfter(c)@@ -680,6 +687,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {return}+ tx.markListItemFoldCandidate(srcParent, srcTree)processed := falseif ast.NodeSuperBlock == targetNode.Type {// 在布局节点后插入@@ -989,6 +997,7 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {logging.LogWarnf("can't append a root to another root")return}+ srcParent := srcNode.Parentvar headingChildren []*ast.Nodeif isMovingFoldHeading := ast.NodeHeading == srcNode.Type && treenode.IsSelfFolded(srcNode); isMovingFoldHeading {@@ -1027,6 +1036,7 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {}targetRoot := targetTree.Root+ tx.markListItemFoldCandidate(srcParent, srcTree)if nil != targetNewList {if nil != targetRoot.LastChild {if ast.NodeList != targetRoot.LastChild.Type {@@ -1115,6 +1125,7 @@ func (tx *Transaction) doDelete0(operation *Operation, tree *parse.Tree) (deletetask.AppendAsyncTaskWithDelay(task.SetDefRefCount, util.SQLFlushInterval, refreshRefCount, tree.Root.ID)parent := node.Parent+ tx.markListItemFoldCandidate(parent, tree)if nil != node.Next && ast.NodeKramdownBlockIAL == node.Next.Type && bytes.Contains(node.Next.Tokens, []byte(node.ID)) {// 列表块撤销状态异常 https://github.com/siyuan-note/siyuan/issues/3985node.Next.Unlink()@@ -1677,6 +1688,9 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {if ast.NodeList == updatedNode.Type && ast.NodeList == oldNode.Parent.Type {updatedNode = updatedNode.FirstChild}+ if ast.NodeListItem == oldNode.Type {+ tx.markListItemFoldCandidate(oldNode, tree)+ }if oldNode.IsContainerBlock() {// 更新容器块的话需要考虑其子块中可能存在的折叠标题,需要把这些折叠标题的下方块移动到新节点下面@@ -2026,6 +2040,69 @@ func (tx *Transaction) doSetAttrs(operation *Operation) (ret *TxErr) {return}+func (tx *Transaction) markListItemFoldCandidate(node *ast.Node, tree *parse.Tree) {+ if nil == node || ast.NodeListItem != node.Type || "" == node.ID || nil == tree {+ return+ }+ if nil == tx.listItemFoldCandidateIDs {+ tx.listItemFoldCandidateIDs = map[string]struct{}{}+ }+ if _, ok := tx.listItemFoldCandidateIDs[node.ID]; ok {+ return+ }+ tx.listItemFoldCandidateIDs[node.ID] = struct{}{}+ tx.listItemFoldCandidates = append(tx.listItemFoldCandidates, listItemFoldCandidate{id: node.ID, tree: tree})+}++func listItemDirectBlockCount(node *ast.Node) (ret int) {+ for child := node.FirstChild; nil != child; child = child.Next {+ if child.IsBlock() && ast.NodeKramdownBlockIAL != child.Type {+ ret+++ }+ }+ return+}++func (tx *Transaction) normalizeListItemFolds() (ret *TxErr) {+ var undoOperations []*Operation+ hasUndo := 0 < len(tx.UndoOperations)+ for _, candidate := range tx.listItemFoldCandidates {+ node := treenode.GetNodeInTree(candidate.tree, candidate.id)+ if nil == node || ast.NodeListItem != node.Type || "1" != node.IALAttr("fold") ||+ 1 < listItemDirectBlockCount(node) {+ continue+ }++ attrs := map[string]string{"fold": ""}+ if _, err := setNodeAttrs0(node, attrs, candidate.tree.Box); nil != err {+ logging.LogErrorf("normalize list item [%s] fold failed: %s", node.ID, err)+ return &TxErr{code: TxErrCodePushMsg, msg: err.Error(), id: node.ID}+ }+ cache.PutBlockIALInBox(node.ID, candidate.tree.Box, parse.IAL2Map(node.KramdownIAL))++ // 规范化发生在原始操作执行完毕后,需补充操作供界面同步、撤销日志和重做使用。+ tx.DoOperations = append(tx.DoOperations, &Operation{+ Action: "setAttrs",+ ID: node.ID,+ Data: `{"fold":""}`,+ Context: map[string]any{"kernelGenerated": "normalizeListItemFold"},+ })+ if hasUndo {+ undoOperations = append(undoOperations, &Operation{+ Action: "setAttrs",+ ID: node.ID,+ Data: `{"fold":"1"}`,+ Context: map[string]any{"kernelGenerated": "normalizeListItemFold"},+ })+ }+ }+ if 0 < len(undoOperations) {+ slices.Reverse(undoOperations)+ tx.UndoOperations = append(undoOperations, tx.UndoOperations...)+ }+ return+}+type Operation struct {Action string `json:"action"`Data any `json:"data"`@@ -2063,6 +2140,11 @@ type Operation struct {Context map[string]any `json:"context"` // 上下文信息}+type listItemFoldCandidate struct {+ id string+ tree *parse.Tree+}+type Transaction struct {Timestamp int64 `json:"timestamp"`DoOperations []*Operation `json:"doOperations"`@@ -2083,6 +2165,9 @@ type Transaction struct {fromAPI bool // 是否来自 /api/transactions HTTP 入口(用于撤销日志捕获判别)isReplay bool // 是否为 undo/redo 重放构造的事务(重放不再进入撤销日志)+ listItemFoldCandidates []listItemFoldCandidate+ listItemFoldCandidateIDs map[string]struct{}+luteEngine *lute.Lutem *sync.Mutexstate atomic.Int32 // 0: 初始化,1:未提交,:2: 已提交,3: 已回滚@@ -2136,6 +2221,8 @@ func (tx *Transaction) begin() (err error) {tx.boxIcons = map[string]string{}tx.removedCreatedDocs = niltx.restoredCreatedDocs = nil+ tx.listItemFoldCandidates = nil+ tx.listItemFoldCandidateIDs = map[string]struct{}{}tx.luteEngine = util.NewLute()tx.m.Lock()tx.state.Store(1)@@ -2209,6 +2296,7 @@ func (tx *Transaction) commit() (err error) {func (tx *Transaction) rollback() {tx.trees, tx.nodes, tx.boxIcons, tx.removedCreatedDocs, tx.restoredCreatedDocs = nil, nil, nil, nil, nil+ tx.listItemFoldCandidates, tx.listItemFoldCandidateIDs = nil, niltx.state.Store(3)tx.m.Unlock()returndiff --git a/kernel/model/transaction_list_item_fold_test.go b/kernel/model/transaction_list_item_fold_test.gonew file mode 100644index 0000000000..57ede1b967--- /dev/null+++ b/kernel/model/transaction_list_item_fold_test.go@@ -0,0 +1,141 @@+package model++import (+ "fmt"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+)++func newFoldedListItemTree(blockCount int, task bool) (*parse.Tree, *ast.Node) {+ root := &ast.Node{Type: ast.NodeDocument, ID: "20260729000000-root001"}+ list := &ast.Node{Type: ast.NodeList, ID: "20260729000000-list001", ListData: &ast.ListData{Typ: 1}}+ item := &ast.Node{Type: ast.NodeListItem, ID: "20260729000000-item001", ListData: &ast.ListData{Typ: 1}}+ item.SetIALAttr("id", item.ID)+ item.SetIALAttr("fold", "1")+ if task {+ item.ListData.Typ = 3+ item.AppendChild(&ast.Node{Type: ast.NodeTaskListItemMarker})+ }+ for i := 0; i < blockCount; i++ {+ item.AppendChild(&ast.Node{Type: ast.NodeParagraph, ID: fmt.Sprintf("20260729000000-block%03d", i)})+ }+ item.AppendChild(&ast.Node{Type: ast.NodeKramdownBlockIAL})+ list.AppendChild(item)+ root.AppendChild(list)+ return &parse.Tree{+ Root: root,+ ID: root.ID,+ Box: "20260729000000-box0001",+ Path: "/20260729000000-root001.sy",+ }, item+}++func TestListItemDirectBlockCount(t *testing.T) {+ _, item := newFoldedListItemTree(1, true)+ if got := listItemDirectBlockCount(item); 1 != got {+ t.Fatalf("unexpected direct block count: got %d, want 1", got)+ }+}++func TestNormalizeListItemFoldsWithoutUndo(t *testing.T) {+ tree, item := newFoldedListItemTree(1, false)+ tx := &Transaction{DoOperations: []*Operation{{Action: "delete", ID: "20260729000000-deleted"}}}+ tx.markListItemFoldCandidate(item, tree)++ if ret := tx.normalizeListItemFolds(); nil != ret {+ t.Fatalf("normalize list item fold failed: %s", ret)+ }+ if 2 != len(tx.DoOperations) {+ t.Fatalf("missing generated do operation: got %d, want 2", len(tx.DoOperations))+ }+ if 0 != len(tx.UndoOperations) {+ t.Fatalf("generated an incomplete undo entry: got %d operations", len(tx.UndoOperations))+ }+}++func TestNormalizeListItemFoldsReversesGeneratedUndoOrder(t *testing.T) {+ firstTree, firstItem := newFoldedListItemTree(1, false)+ secondTree, secondItem := newFoldedListItemTree(1, false)+ secondItem.ID = "20260729000000-item002"+ secondItem.SetIALAttr("id", secondItem.ID)+ originalUndo := &Operation{Action: "insert", ID: "20260729000000-deleted"}+ tx := &Transaction{+ DoOperations: []*Operation{{Action: "delete", ID: originalUndo.ID}},+ UndoOperations: []*Operation{originalUndo},+ }+ tx.markListItemFoldCandidate(firstItem, firstTree)+ tx.markListItemFoldCandidate(secondItem, secondTree)++ if ret := tx.normalizeListItemFolds(); nil != ret {+ t.Fatalf("normalize list item fold failed: %s", ret)+ }+ if firstItem.ID != tx.DoOperations[1].ID || secondItem.ID != tx.DoOperations[2].ID {+ t.Fatalf("generated do operation order changed: %s, %s", tx.DoOperations[1].ID, tx.DoOperations[2].ID)+ }+ if secondItem.ID != tx.UndoOperations[0].ID || firstItem.ID != tx.UndoOperations[1].ID ||+ originalUndo != tx.UndoOperations[2] {+ t.Fatalf("unexpected generated undo operation order: %s, %s, %s",+ tx.UndoOperations[0].ID, tx.UndoOperations[1].ID, tx.UndoOperations[2].ID)+ }+}++func TestNormalizeListItemFolds(t *testing.T) {+ tests := []struct {+ name string+ blockCount int+ wantFold string+ wantGenerated bool+ }{+ {name: "empty", blockCount: 0, wantFold: "", wantGenerated: true},+ {name: "single block", blockCount: 1, wantFold: "", wantGenerated: true},+ {name: "multiple blocks", blockCount: 2, wantFold: "1", wantGenerated: false},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ tree, item := newFoldedListItemTree(test.blockCount, false)+ originalDo := &Operation{Action: "delete", ID: "20260729000000-deleted"}+ originalUndo := &Operation{Action: "insert", ID: "20260729000000-deleted"}+ tx := &Transaction{+ DoOperations: []*Operation{originalDo},+ UndoOperations: []*Operation{originalUndo},+ }+ tx.markListItemFoldCandidate(item, tree)+ tx.markListItemFoldCandidate(item, tree)++ if ret := tx.normalizeListItemFolds(); nil != ret {+ t.Fatalf("normalize list item fold failed: %s", ret)+ }+ if got := item.IALAttr("fold"); test.wantFold != got {+ t.Fatalf("unexpected fold: got %q, want %q", got, test.wantFold)+ }+ if 1 != len(tx.listItemFoldCandidates) {+ t.Fatalf("candidate was not deduplicated: got %d, want 1", len(tx.listItemFoldCandidates))+ }++ if !test.wantGenerated {+ if 1 != len(tx.DoOperations) || 1 != len(tx.UndoOperations) {+ t.Fatalf("unexpected generated operations: do %d, undo %d",+ len(tx.DoOperations), len(tx.UndoOperations))+ }+ return+ }+ if 2 != len(tx.DoOperations) || 2 != len(tx.UndoOperations) {+ t.Fatalf("missing generated operations: do %d, undo %d",+ len(tx.DoOperations), len(tx.UndoOperations))+ }+ generatedDo := tx.DoOperations[1]+ if "setAttrs" != generatedDo.Action || item.ID != generatedDo.ID || `{"fold":""}` != generatedDo.Data {+ t.Fatalf("unexpected generated do operation: %+v", generatedDo)+ }+ generatedUndo := tx.UndoOperations[0]+ if "setAttrs" != generatedUndo.Action || item.ID != generatedUndo.ID || `{"fold":"1"}` != generatedUndo.Data {+ t.Fatalf("unexpected generated undo operation: %+v", generatedUndo)+ }+ if originalUndo != tx.UndoOperations[1] {+ t.Fatal("generated undo operation was not prepended")+ }+ })+ }+}