An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support block type locking for external updates https://github.com/siyuan-note/siyuan/issues/17450
Danielc7e58c6da597
diff --git a/docs/API.ja.md b/docs/API.ja.mdindex ff46f12e22..ffb45e17f8 100644--- a/docs/API.ja.md+++ b/docs/API.ja.md@@ -826,13 +826,15 @@{"dataType": "markdown","data": "foobarbaz",- "id": "20211230161520-querkps"+ "id": "20211230161520-querkps",+ "lockType": false}```* `dataType`: 更新するデータ型、`markdown`または`dom`* `data`: 更新するデータ* `id`: 更新するブロックのID+ * `lockType`: 解析後のブロック型が既存のブロック型と異なる場合に更新を拒否するかどうか。不正な親子構造は常に拒否されますが、空の段落ブロックは任意の有効なブロック型に変換できます。デフォルトは`false`* 戻り値```jsondiff --git a/docs/API.md b/docs/API.mdindex 69a8cea80c..e5d6bf505f 100644--- a/docs/API.md+++ b/docs/API.md@@ -831,13 +831,15 @@ Move documents by `id`:{"dataType": "markdown","data": "foobarbaz",- "id": "20211230161520-querkps"+ "id": "20211230161520-querkps",+ "lockType": false}```* `dataType`: The data type to be updated, the value can be `markdown` or `dom`* `data`: Data to be updated* `id`: ID of the block to be updated+ * `lockType`: Whether to reject the update when the parsed block type differs from the existing block type; invalid parent-child structures are always rejected, while an empty paragraph can be converted to any valid block type; defaults to `false`* Return value```jsondiff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex 2f0110ebde..50b3842e84 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -826,13 +826,15 @@{"dataType": "markdown","data": "foobarbaz",- "id": "20211230161520-querkps"+ "id": "20211230161520-querkps",+ "lockType": false}```* `dataType`:待更新数据类型,值可选择 `markdown` 或者 `dom`* `data`:待更新的数据* `id`:待更新块的 ID+ * `lockType`:解析后的块类型与原块类型不同时是否拒绝更新;非法父子结构始终会被拒绝,空段落可转换为任意有效块类型;默认为 `false`* 返回值```jsondiff --git a/kernel/api/block_op.go b/kernel/api/block_op.goindex 0170103e8c..ad3540b713 100644--- a/kernel/api/block_op.go+++ b/kernel/api/block_op.go@@ -18,20 +18,34 @@ package apiimport ("errors"+ "fmt""net/http""github.com/88250/gulu""github.com/88250/lute""github.com/88250/lute/ast"- "github.com/88250/lute/parse""github.com/gin-gonic/gin"- "github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/filesys""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")+func parseBlockUpdateInput(arg map[string]any, ret *gulu.Result) (input model.BlockUpdateInput, ok bool) {+ if !util.ParseJsonArgs(arg, ret,+ util.BindJsonArg("id", &input.ID, true, true),+ util.BindJsonArg("data", &input.Data, true, false),+ util.BindJsonArg("dataType", &input.DataType, true, true),+ util.BindJsonArg("lockType", &input.LockType, false, false),+ ) {+ return+ }+ if util.InvalidIDPattern(input.ID, ret) {+ return input, false+ }+ return input, true+}+func buildUpdatedTaskListItemBlockDOM(id, marker string, luteEngine *lute.Lute) (data string, err error) {block, err := model.GetBlock(id, nil)if err != nil {@@ -839,91 +853,19 @@ func updateBlock(c *gin.Context) {return}- data := arg["data"].(string)- dataType := arg["dataType"].(string)- id := arg["id"].(string)- if util.InvalidIDPattern(id, ret) {- return- }-- luteEngine := util.NewLute()- if "markdown" == dataType {- var err error- data, err = dataBlockDOM(data, luteEngine)- if err != nil {- ret.Code = -1- ret.Msg = "data block DOM failed: " + err.Error()- return- }- }- tree := luteEngine.BlockDOM2Tree(data)- if nil == tree || nil == tree.Root || nil == tree.Root.FirstChild {- ret.Code = -1- ret.Msg = "parse tree failed"+ input, ok := parseBlockUpdateInput(arg, ret)+ if !ok {return}- block, err := model.GetBlock(id, nil)+ operations, _, err := model.BuildBlockUpdateOperations([]model.BlockUpdateInput{input})if err != nil {ret.Code = -1- ret.Msg = "get block failed: " + err.Error()+ ret.Msg = err.Error()return}- var transactions []*model.Transaction- if "NodeDocument" == block.Type {- oldTree, err := filesys.LoadTree(block.Box, block.Path, luteEngine)- if err != nil {- ret.Code = -1- ret.Msg = "load tree failed: " + err.Error()- return- }- var toRemoves []*ast.Node- var ops []*model.Operation- for n := oldTree.Root.FirstChild; nil != n; n = n.Next {- toRemoves = append(toRemoves, n)- ops = append(ops, &model.Operation{Action: "delete", ID: n.ID, Data: map[string]any{- "createEmptyParagraph": false, // 清空文档后前端不要创建空段落- }})- }- for _, n := range toRemoves {- n.Unlink()- }- ops = append(ops, &model.Operation{Action: "appendInsert", Data: data, ParentID: id})- transactions = append(transactions, &model.Transaction{- DoOperations: ops,- })- } else {- if "NodeListItem" == block.Type && ast.NodeList == tree.Root.FirstChild.Type {- // 使用 API `api/block/updateBlock` 更新列表项时渲染错误 https://github.com/siyuan-note/siyuan/issues/4658- tree.Root.AppendChild(tree.Root.FirstChild.FirstChild) // 将列表下的第一个列表项移到文档结尾,移动以后根下面直接挂列表项,渲染器可以正常工作- tree.Root.FirstChild.Unlink() // 删除列表- if nil != tree.Root.FirstChild && ast.NodeKramdownBlockIAL == tree.Root.FirstChild.Type {- tree.Root.FirstChild.Unlink() // 继续删除列表 IAL- }- }-- if nil != tree.Root.FirstChild {- tree.Root.FirstChild.SetIALAttr("id", id)- } else {- logging.LogWarnf("tree root has no child node, append empty paragraph node")- tree.Root.AppendChild(treenode.NewParagraph(id))- }-- data = luteEngine.Tree2BlockDOM(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)- transactions = []*model.Transaction{- {- DoOperations: []*model.Operation{- {- Action: "update",- ID: id,- Data: data,- },- },- },- }- }-+ transactions := []*model.Transaction{{DoOperations: operations}}model.PerformTransactions(&transactions)model.FlushTxQueue()@@ -1020,103 +962,30 @@ func batchUpdateBlock(c *gin.Context) {return}- type updateBlockArg struct {- ID string- Data string- DataType string- Block *model.Block- Tree *parse.Tree- }-- var blocks []*updateBlockArg- luteEngine := util.NewLute()- for _, blockArg := range blocksArg {- blockMap := blockArg.(map[string]any)- id := blockMap["id"].(string)- if util.InvalidIDPattern(id, ret) {- return- }-- data := blockMap["data"].(string)- dataType := blockMap["dataType"].(string)- if "markdown" == dataType {- var err error- data, err = dataBlockDOM(data, luteEngine)- if err != nil {- ret.Code = -1- ret.Msg = "data block DOM failed: " + err.Error()- return- }- }- tree := luteEngine.BlockDOM2Tree(data)- if nil == tree || nil == tree.Root || nil == tree.Root.FirstChild {+ inputs := make([]model.BlockUpdateInput, 0, len(blocksArg))+ for i, blockArg := range blocksArg {+ blockMap, isMap := blockArg.(map[string]any)+ if !isMap {ret.Code = -1- ret.Msg = "parse tree failed"+ ret.Msg = fmt.Sprintf("Field [blocks[%d]] should be of type [Object]", i)return}-- block, err := model.GetBlock(id, nil)- if err != nil {- ret.Code = -1- ret.Msg = "get block failed: " + err.Error()+ input, parsed := parseBlockUpdateInput(blockMap, ret)+ if !parsed {+ ret.Msg = fmt.Sprintf("blocks[%d]: %s", i, ret.Msg)return}-- blocks = append(blocks, &updateBlockArg{- ID: id,- Data: data,- DataType: dataType,- Block: block,- Tree: tree,- })+ inputs = append(inputs, input)}- var ops []*model.Operation- tx := &model.Transaction{}- transactions := []*model.Transaction{tx}- for _, upBlock := range blocks {- block := upBlock.Block- data := upBlock.Data- tree := upBlock.Tree- id := upBlock.ID- if "NodeDocument" == block.Type {- oldTree, err := filesys.LoadTree(block.Box, block.Path, luteEngine)- if err != nil {- ret.Code = -1- ret.Msg = "load tree failed: " + err.Error()- return- }- var toRemoves []*ast.Node-- for n := oldTree.Root.FirstChild; nil != n; n = n.Next {- toRemoves = append(toRemoves, n)- ops = append(ops, &model.Operation{Action: "delete", ID: n.ID, Data: map[string]any{- "createEmptyParagraph": false, // 清空文档后前端不要创建空段落- }})- }- for _, n := range toRemoves {- n.Unlink()- }- ops = append(ops, &model.Operation{Action: "appendInsert", Data: data, ParentID: id})- } else {- if "NodeListItem" == block.Type && ast.NodeList == tree.Root.FirstChild.Type {- // 使用 API `api/block/updateBlock` 更新列表项时渲染错误 https://github.com/siyuan-note/siyuan/issues/4658- tree.Root.AppendChild(tree.Root.FirstChild.FirstChild) // 将列表下的第一个列表项移到文档结尾,移动以后根下面直接挂列表项,渲染器可以正常工作- tree.Root.FirstChild.Unlink() // 删除列表- tree.Root.FirstChild.Unlink() // 继续删除列表 IAL- }- tree.Root.FirstChild.SetIALAttr("id", id)-- data = luteEngine.Tree2BlockDOM(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)- ops = append(ops, &model.Operation{- Action: "update",- ID: id,- Data: data,- })- }+ operations, _, err := model.BuildBlockUpdateOperations(inputs)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return}- tx.DoOperations = ops+ transactions := []*model.Transaction{{DoOperations: operations}}model.PerformTransactions(&transactions)model.FlushTxQueue()@@ -1162,34 +1031,5 @@ func broadcastTransactions(transactions []*model.Transaction) {}func dataBlockDOM(data string, luteEngine *lute.Lute) (ret string, err error) {- luteEngine.SetHTMLTag2TextMark(true) // API `/api/block/**` 无法使用 `<u>foo</u>` 与 `<kbd>bar</kbd>` 插入/更新行内元素 https://github.com/siyuan-note/siyuan/issues/6039-- ret, tree := luteEngine.Md2BlockDOMTree(data, true)- if "" == ret {- // 使用 API 插入空字符串出现错误 https://github.com/siyuan-note/siyuan/issues/3931- blankParagraph := treenode.NewParagraph("")- ret = luteEngine.RenderNodeBlockDOM(blankParagraph)- }-- invalidID := ""- ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering {- return ast.WalkContinue- }-- if "" != n.ID {- if !ast.IsNodeIDPattern(n.ID) {- invalidID = n.ID- return ast.WalkStop- }- }- return ast.WalkContinue- })-- if "" != invalidID {- err = errors.New("found invalid ID [" + invalidID + "]")- ret = ""- return- }- return+ return model.DataBlockDOM(data, luteEngine)}diff --git a/kernel/cli/cmd/block.go b/kernel/cli/cmd/block.goindex a0cf2cdc8f..b5bf7d32f7 100644--- a/kernel/cli/cmd/block.go+++ b/kernel/cli/cmd/block.go@@ -336,19 +336,23 @@ var blockUpdateCmd = &cobra.Command{if err != nil {return err}+ lockType, _ := cmd.Flags().GetBool("lock-type")++ operations, rootIDs, err := model.BuildBlockUpdateOperations([]model.BlockUpdateInput{{+ ID: id,+ Data: data,+ DataType: "markdown",+ LockType: lockType,+ }})+ if err != nil {+ return err+ }- dom := markdownToBlockDOM(data)- transactions := []*model.Transaction{{- DoOperations: []*model.Operation{{- Action: "update",- Data: dom,- ID: id,- }},- }}+ transactions := []*model.Transaction{{DoOperations: operations}}model.PerformTransactions(&transactions)model.FlushTxQueue()- if bt := treenode.GetBlockTree(id); bt != nil {- model.AppendPushReloadProtyleEntry(bt.RootID)+ for _, rootID := range rootIDs {+ model.AppendPushReloadProtyleEntry(rootID)}fmt.Println("ok")return nil@@ -604,6 +608,7 @@ func init() {blockUpdateCmd.Flags().String("id", "", "block ID")blockUpdateCmd.Flags().String("data", "", "markdown content")blockUpdateCmd.Flags().String("file", "", "read content from file path (- for stdin)")+ blockUpdateCmd.Flags().Bool("lock-type", false, "reject update when the parsed block type differs from the existing block type")blockDeleteCmd.Flags().String("id", "", "block ID")diff --git a/kernel/mcp/tools/block.go b/kernel/mcp/tools/block.goindex a99973b91a..5426f60c03 100644--- a/kernel/mcp/tools/block.go+++ b/kernel/mcp/tools/block.go@@ -20,7 +20,6 @@ import ("fmt""strings"- "github.com/88250/lute/ast""github.com/siyuan-note/siyuan/kernel/filesys""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/treenode"@@ -29,7 +28,7 @@ import (var BlockTool = &Tool{Name: "block",- Description: "Block operations. Actions: get(id), get_kramdown(id), get_children(id), tree_stat(id, by document), dom(id), insert(data, dataType, parentID?, nextID?, previousID?), append(data, dataType, parentID) / prepend(...) add a NEW child — use after block.update when both modifying and adding, update(id, data, dataType) replaces ONE block only (no append), delete(id), move(id, parentID, previousID?), breadcrumb(id), batch_get(ids) / batch_kramdown(ids) where ids is comma-separated.",+ Description: "Block operations. Actions: get(id), get_kramdown(id), get_children(id), tree_stat(id, by document), dom(id), insert(data, dataType, parentID?, nextID?, previousID?), append(data, dataType, parentID) / prepend(...) add a NEW child — use after block.update when both modifying and adding, update(id, data, dataType, lockType?) replaces ONE block only (no append), delete(id), move(id, parentID, previousID?), breadcrumb(id), batch_get(ids) / batch_kramdown(ids) where ids is comma-separated.",InputSchema: ToolSchema{Type: "object",Properties: map[string]Property{@@ -38,6 +37,7 @@ var BlockTool = &Tool{"ids": {Type: "string", Description: "Comma-separated block IDs (for batch_get, batch_kramdown)"},"data": {Type: "string", Description: "Content (markdown or dom)"},"dataType": {Type: "string", Description: "Content type: markdown or dom", Enum: []string{"markdown", "dom"}},+ "lockType": {Type: "boolean", Description: "Reject update when the parsed block type differs from the existing block type; defaults to false"},"parentID": {Type: "string", Description: "Parent block ID"},"nextID": {Type: "string", Description: "Next sibling block ID (for insert)"},"previousID": {Type: "string", Description: "Previous sibling block ID (for insert)"},@@ -293,67 +293,31 @@ func blockUpdate(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil}data, dataType := getBlockData(args)- if data == "" {+ if _, exists := args["data"]; !exists {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "data is required"}}, IsError: true}, nil}+ lockType, _ := args["lockType"].(bool)- // markdown 转 DOM 时 Lute 会给块生成全新的随机 ID,update 前必须把原块 id 钉回去,- // 否则块 ID 每次更新都会变,后续按原 id 操作会报 block not found- data = pinBlockID(data, dataType, id)-- transactions := []*model.Transaction{{- DoOperations: []*model.Operation{{- Action: "update",- ID: id,- Data: data,- }},- }}+ operations, rootIDs, err := model.BuildBlockUpdateOperations([]model.BlockUpdateInput{{+ ID: id,+ Data: data,+ DataType: dataType,+ LockType: lockType,+ }})+ if err != nil {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}, nil+ }+ transactions := []*model.Transaction{{DoOperations: operations}}model.PerformTransactions(&transactions)model.FlushTxQueue()- if bt := treenode.GetBlockTree(id); bt != nil {- util.PushReloadProtyle(bt.RootID)+ for _, rootID := range rootIDs {+ util.PushReloadProtyle(rootID)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block updated"}}}, nil}-// pinBlockID 把原块 id 钉回 markdown/dom 数据,保证 update 不改变块 ID。-// 参照 HTTP API /api/block/updateBlock 的 id 复位逻辑(block_op.go updateBlock 非 Document 分支)。-func pinBlockID(data, dataType, id string) string {- luteEngine := util.NewLute()- if dataType == "markdown" {- var err error- data, err = markdownToBlockDOM(data)- if err != nil {- return data- }- }-- tree := luteEngine.BlockDOM2Tree(data)- if nil == tree || nil == tree.Root || nil == tree.Root.FirstChild {- return data- }-- // 更新列表项时 markdown 会渲染成 NodeList>ListItem,需要先把列表项提升到根下,渲染器才能正常工作- // 使用 API `api/block/updateBlock` 更新列表项时渲染错误 https://github.com/siyuan-note/siyuan/issues/4658- if ast.NodeList == tree.Root.FirstChild.Type {- tree.Root.AppendChild(tree.Root.FirstChild.FirstChild) // 将列表下的第一个列表项移到文档结尾- tree.Root.FirstChild.Unlink() // 删除列表- if nil != tree.Root.FirstChild && ast.NodeKramdownBlockIAL == tree.Root.FirstChild.Type {- tree.Root.FirstChild.Unlink() // 继续删除列表 IAL- }- }-- if nil != tree.Root.FirstChild {- tree.Root.FirstChild.SetIALAttr("id", id)- } else {- tree.Root.AppendChild(treenode.NewParagraph(id))- }-- return luteEngine.Tree2BlockDOM(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)-}-func blockDelete(args map[string]any) (CallToolResult, error) {id, _ := args["id"].(string)if id == "" {diff --git a/kernel/model/block_update.go b/kernel/model/block_update.gonew file mode 100644index 0000000000..df9134688a--- /dev/null+++ b/kernel/model/block_update.go@@ -0,0 +1,222 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "errors"+ "fmt"+ "strings"++ "github.com/88250/lute"+ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// BlockUpdateInput 描述一个外部块更新请求。+type BlockUpdateInput struct {+ ID string+ Data string+ DataType string+ LockType bool+}++// BuildBlockUpdateOperations 解析并校验所有块更新,全部通过后返回可执行的事务操作。+func BuildBlockUpdateOperations(inputs []BlockUpdateInput) (operations []*Operation, rootIDs []string, err error) {+ if 1 > len(inputs) {+ return nil, nil, errors.New("block updates are empty")+ }++ luteEngine := util.NewLute()+ rootIDSet := map[string]struct{}{}+ for _, input := range inputs {+ if !ast.IsNodeIDPattern(input.ID) {+ return nil, nil, fmt.Errorf("invalid block ID [%s]", input.ID)+ }++ data, dataTree, parseErr := parseBlockUpdateData(input.Data, input.DataType, luteEngine)+ if parseErr != nil {+ return nil, nil, parseErr+ }++ oldTree, loadErr := LoadTreeByBlockID(input.ID)+ if loadErr != nil {+ return nil, nil, fmt.Errorf("load block tree [%s] failed: %w", input.ID, loadErr)+ }+ oldNode := treenode.GetNodeInTree(oldTree, input.ID)+ if nil == oldNode {+ return nil, nil, fmt.Errorf("block [%s] not found", input.ID)+ }++ if _, ok := rootIDSet[oldTree.ID]; !ok {+ rootIDSet[oldTree.ID] = struct{}{}+ rootIDs = append(rootIDs, oldTree.ID)+ }++ if ast.NodeDocument == oldNode.Type {+ if validateErr := treenode.ValidateBlockSubtree(dataTree.Root); validateErr != nil {+ return nil, nil, validateErr+ }+ for n := oldTree.Root.FirstChild; nil != n; n = n.Next {+ if !n.IsBlock() || ast.NodeKramdownBlockIAL == n.Type {+ continue+ }+ operations = append(operations, &Operation{Action: "delete", ID: n.ID, Data: map[string]any{+ "createEmptyParagraph": false, // 清空文档后前端不要创建空段落+ }})+ }+ operations = append(operations, &Operation{Action: "appendInsert", Data: data, ParentID: input.ID})+ continue+ }++ normalizedTree, updatedNode, normalizeErr := normalizeBlockUpdateTree(oldNode, dataTree, luteEngine)+ if normalizeErr != nil {+ return nil, nil, normalizeErr+ }+ if validateErr := treenode.ValidateBlockReplacement(oldNode, updatedNode); validateErr != nil {+ return nil, nil, validateErr+ }+ if typeErr := validateBlockUpdateType(oldNode, updatedNode, input.LockType); typeErr != nil {+ return nil, nil, typeErr+ }++ updatedNode.SetIALAttr("id", input.ID)+ data = luteEngine.Tree2BlockDOM(normalizedTree, luteEngine.RenderOptions, luteEngine.ParseOptions)+ operations = append(operations, &Operation{+ Action: "update",+ ID: input.ID,+ Data: data,+ LockType: input.LockType,+ })+ }+ return+}++// DataBlockDOM 将 Markdown 转换为块 DOM,并校验输入中显式指定的块 ID。+func DataBlockDOM(data string, luteEngine *lute.Lute) (ret string, err error) {+ luteEngine.SetHTMLTag2TextMark(true) // API 无法使用 HTML 标签插入或更新行内元素 https://github.com/siyuan-note/siyuan/issues/6039++ ret, tree := luteEngine.Md2BlockDOMTree(data, true)+ if "" == ret {+ // 使用 API 插入空字符串出现错误 https://github.com/siyuan-note/siyuan/issues/3931+ blankParagraph := treenode.NewParagraph("")+ ret = luteEngine.RenderNodeBlockDOM(blankParagraph)+ }++ invalidID := ""+ if nil != tree && nil != tree.Root {+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if "" != n.ID && !ast.IsNodeIDPattern(n.ID) {+ invalidID = n.ID+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ }+ if "" != invalidID {+ return "", errors.New("found invalid ID [" + invalidID + "]")+ }+ return+}++func parseBlockUpdateData(data, dataType string, luteEngine *lute.Lute) (ret string, tree *parse.Tree, err error) {+ ret = data+ switch dataType {+ case "markdown":+ ret, err = DataBlockDOM(data, luteEngine)+ if err != nil {+ err = fmt.Errorf("data block DOM failed: %w", err)+ return+ }+ case "dom":+ default:+ err = fmt.Errorf("unsupported block data type [%s]", dataType)+ return+ }++ tree = luteEngine.BlockDOM2Tree(ret)+ if nil == tree || nil == tree.Root || nil == firstContentBlock(tree.Root) {+ err = errors.New("parse tree failed")+ }+ return+}++func normalizeBlockUpdateTree(oldNode *ast.Node, tree *parse.Tree, luteEngine *lute.Lute) (ret *parse.Tree, updatedNode *ast.Node, err error) {+ updatedNode = firstContentBlock(tree.Root)+ if nil == updatedNode {+ return nil, nil, errors.New("parse tree failed")+ }+ if ast.NodeListItem == oldNode.Type && ast.NodeList == updatedNode.Type {+ listItem := firstContentBlock(updatedNode)+ if nil == listItem || ast.NodeListItem != listItem.Type {+ return nil, nil, errors.New("list block has no list item")+ }+ updatedNode = listItem+ }++ updatedNode.Unlink()+ root := &ast.Node{Type: ast.NodeDocument}+ root.AppendChild(updatedNode)+ ret = &parse.Tree{+ Root: root,+ Context: &parse.Context{ParseOption: luteEngine.ParseOptions},+ }+ return+}++func firstContentBlock(parent *ast.Node) *ast.Node {+ if nil == parent {+ return nil+ }+ for child := parent.FirstChild; nil != child; child = child.Next {+ if child.IsBlock() && ast.NodeKramdownBlockIAL != child.Type {+ return child+ }+ }+ return nil+}++func validateBlockUpdateType(oldNode, updatedNode *ast.Node, lockType bool) error {+ if !lockType || oldNode.Type == updatedNode.Type || isEmptyParagraphBlock(oldNode) {+ return nil+ }+ return fmt.Errorf("block [%s] type is locked: expected %s, got %s",+ oldNode.ID, oldNode.Type.String(), updatedNode.Type.String())+}++func isEmptyParagraphBlock(node *ast.Node) bool {+ if nil == node || ast.NodeParagraph != node.Type {+ return false+ }+ for child := node.FirstChild; nil != child; child = child.Next {+ switch child.Type {+ case ast.NodeText:+ text := strings.ReplaceAll(string(child.Tokens), "\u200b", "")+ if "" != strings.TrimSpace(text) {+ return false+ }+ case ast.NodeSoftBreak, ast.NodeBr:+ default:+ return false+ }+ }+ return true+}diff --git a/kernel/model/block_update_test.go b/kernel/model/block_update_test.gonew file mode 100644index 0000000000..88c454fd14--- /dev/null+++ b/kernel/model/block_update_test.go@@ -0,0 +1,88 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestNormalizeListItemBlockUpdateTree(t *testing.T) {+ root := &ast.Node{Type: ast.NodeDocument}+ list := &ast.Node{Type: ast.NodeList}+ firstItem := &ast.Node{Type: ast.NodeListItem, ID: "first-item"}+ firstItem.AppendChild(&ast.Node{Type: ast.NodeParagraph, ID: "paragraph"})+ secondItem := &ast.Node{Type: ast.NodeListItem, ID: "second-item"}+ list.AppendChild(firstItem)+ list.AppendChild(secondItem)+ root.AppendChild(list)++ oldNode := &ast.Node{Type: ast.NodeListItem, ID: "old-item"}+ normalizedTree, updatedNode, err := normalizeBlockUpdateTree(oldNode, &parse.Tree{Root: root}, util.NewLute())+ if err != nil {+ t.Fatalf("normalize list item update failed: %s", err)+ }+ if ast.NodeListItem != updatedNode.Type || "first-item" != updatedNode.ID {+ t.Fatalf("unexpected normalized node [%s] [%s]", updatedNode.Type.String(), updatedNode.ID)+ }+ if normalizedTree.Root.FirstChild != updatedNode || normalizedTree.Root.LastChild != updatedNode || nil != updatedNode.Next {+ t.Fatal("normalized update tree should contain only the first list item")+ }+}++func TestValidateBlockUpdateType(t *testing.T) {+ oldNode := &ast.Node{Type: ast.NodeCodeBlock, ID: "code"}+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}+ if err := validateBlockUpdateType(oldNode, paragraph, false); nil != err {+ t.Fatalf("unlocked type update should be allowed: %s", err)+ }+ if err := validateBlockUpdateType(oldNode, paragraph, true); nil == err {+ t.Fatal("locked type update should be rejected")+ }++ heading := &ast.Node{Type: ast.NodeHeading, ID: "heading"}+ if err := validateBlockUpdateType(heading, &ast.Node{Type: ast.NodeHeading}, true); nil != err {+ t.Fatalf("heading subtype update should be allowed: %s", err)+ }++ emptyParagraph := &ast.Node{Type: ast.NodeParagraph, ID: "empty-paragraph"}+ if err := validateBlockUpdateType(emptyParagraph, oldNode, true); nil != err {+ t.Fatalf("empty paragraph conversion should be allowed: %s", err)+ }++ emptyParagraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("\u200b \n")})+ if err := validateBlockUpdateType(emptyParagraph, oldNode, true); nil != err {+ t.Fatalf("paragraph containing only blank text should be convertible: %s", err)+ }+ emptyParagraph.FirstChild.Tokens = []byte("content")+ if err := validateBlockUpdateType(emptyParagraph, oldNode, true); nil == err {+ t.Fatal("non-empty paragraph conversion should be rejected")+ }+}++func TestDataBlockDOMEmptyData(t *testing.T) {+ data, err := DataBlockDOM("", util.NewLute())+ if err != nil {+ t.Fatalf("convert empty markdown failed: %s", err)+ }+ if "" == data {+ t.Fatal("empty markdown should produce a blank paragraph")+ }+}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 2aed3a2480..55018168d1 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -1631,6 +1631,28 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {return &TxErr{code: TxErrCodeBlockNotFound, msg: ErrBlockNotFound.Error(), id: id}}+ updatedNode := firstContentBlock(subTree.Root)+ if nil == updatedNode {+ logging.LogErrorf("get first node in sub tree [%s] failed", subTree.Root.ID)+ return &TxErr{code: TxErrCodeBlockNotFound, msg: ErrBlockNotFound.Error(), id: id}+ }+ if nil != oldNode.Parent && ast.NodeList == updatedNode.Type && ast.NodeList == oldNode.Parent.Type {+ updatedNode = firstContentBlock(updatedNode)+ }+ if nil == updatedNode {+ msg := "updated block node is invalid"+ logging.LogErrorf("%s [%s]", msg, id)+ return &TxErr{code: TxErrCodePushMsg, msg: msg, id: id}+ }+ if err = treenode.ValidateBlockReplacement(oldNode, updatedNode); err != nil {+ logging.LogErrorf("validate updated block [%s] structure failed: %s", id, err)+ return &TxErr{code: TxErrCodePushMsg, msg: err.Error(), id: id}+ }+ if err = validateBlockUpdateType(oldNode, updatedNode, operation.LockType); err != nil {+ logging.LogError(err.Error())+ return &TxErr{code: TxErrCodePushMsg, msg: err.Error(), id: id}+ }+// 收集引用的定义块 IDoldDefIDs := getRefDefIDs(oldNode)var newDefIDs []string@@ -1696,14 +1718,6 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {TouchRefUsed(newRefDefIDs)}- updatedNode := subTree.Root.FirstChild- if nil == updatedNode {- logging.LogErrorf("get fist node in sub tree [%s] failed", subTree.Root.ID)- return &TxErr{code: TxErrCodeBlockNotFound, msg: ErrBlockNotFound.Error(), id: id}- }- if ast.NodeList == updatedNode.Type && ast.NodeList == oldNode.Parent.Type {- updatedNode = updatedNode.FirstChild- }if ast.NodeListItem == oldNode.Type {tx.markListItemFoldCandidate(oldNode, tree)}@@ -2134,6 +2148,8 @@ type Operation struct {DeckID string `json:"deckID"` // 用于添加/删除闪卡Tree *parse.Tree `json:"-"` // 仅用于内核事务重放,不发送到前端+ LockType bool `json:"-"` // 外部块更新是否禁止改变主类型+AvID string `json:"avID"` // 属性视图 IDSrcIDs []string `json:"srcIDs"` // 用于从属性视图中删除行Srcs []map[string]any `json:"srcs"` // 用于添加属性视图行(包括绑定块){id, content, isDetached}diff --git a/kernel/treenode/block_structure.go b/kernel/treenode/block_structure.gonew file mode 100644index 0000000000..ab5359cccf--- /dev/null+++ b/kernel/treenode/block_structure.go@@ -0,0 +1,92 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package treenode++import (+ "fmt"++ "github.com/88250/lute/ast"+)++// CanContainBlock 判断指定类型的容器块是否可以容纳指定类型的内容块。+func CanContainBlock(parentType, childType ast.NodeType) bool {+ parent := &ast.Node{Type: parentType}+ return parent.IsContainerBlock() && parent.CanContain(childType)+}++// ValidateBlockSubtree 校验根块内部所有内容块的容纳关系。+func ValidateBlockSubtree(root *ast.Node) error {+ if nil == root || !isContentBlock(root) {+ return invalidBlockNodeError(root)+ }++ var ret error+ ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if !entering || n == root || !isContentBlock(n) {+ return ast.WalkContinue+ }++ parent := n.Parent+ for nil != parent && !isContentBlock(parent) {+ parent = parent.Parent+ }+ if nil == parent {+ return ast.WalkContinue+ }+ if !CanContainBlock(parent.Type, n.Type) {+ ret = invalidBlockContainmentError(parent, n)+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ return ret+}++// ValidateBlockReplacement 校验新块能否替换旧块,并校验新块内部的容纳关系。+func ValidateBlockReplacement(oldNode, newNode *ast.Node) error {+ if nil == oldNode || !isContentBlock(oldNode) {+ return invalidBlockNodeError(oldNode)+ }+ if nil == newNode || !isContentBlock(newNode) {+ return invalidBlockNodeError(newNode)+ }++ parent := oldNode.Parent+ for nil != parent && !isContentBlock(parent) {+ parent = parent.Parent+ }+ if nil != parent && !CanContainBlock(parent.Type, newNode.Type) {+ return invalidBlockContainmentError(parent, newNode)+ }+ return ValidateBlockSubtree(newNode)+}++func isContentBlock(node *ast.Node) bool {+ return nil != node && node.IsBlock() && ast.NodeKramdownBlockIAL != node.Type+}++func invalidBlockContainmentError(parent, child *ast.Node) error {+ return fmt.Errorf("invalid block structure: %s [%s] cannot contain %s [%s]",+ parent.Type.String(), parent.ID, child.Type.String(), child.ID)+}++func invalidBlockNodeError(node *ast.Node) error {+ if nil == node {+ return fmt.Errorf("invalid block structure: block node is nil")+ }+ return fmt.Errorf("invalid block structure: %s [%s] is not a content block", node.Type.String(), node.ID)+}diff --git a/kernel/treenode/block_structure_test.go b/kernel/treenode/block_structure_test.gonew file mode 100644index 0000000000..8b8a6fc84d--- /dev/null+++ b/kernel/treenode/block_structure_test.go@@ -0,0 +1,85 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package treenode++import (+ "testing"++ "github.com/88250/lute/ast"+)++func TestCanContainBlock(t *testing.T) {+ tests := []struct {+ name string+ parentType ast.NodeType+ childType ast.NodeType+ expected bool+ }{+ {"document paragraph", ast.NodeDocument, ast.NodeParagraph, true},+ {"document list item", ast.NodeDocument, ast.NodeListItem, false},+ {"list list item", ast.NodeList, ast.NodeListItem, true},+ {"list paragraph", ast.NodeList, ast.NodeParagraph, false},+ {"list item list", ast.NodeListItem, ast.NodeList, true},+ {"list item list item", ast.NodeListItem, ast.NodeListItem, false},+ {"blockquote list item", ast.NodeBlockquote, ast.NodeListItem, false},+ {"callout list item", ast.NodeCallout, ast.NodeListItem, false},+ {"super block list item", ast.NodeSuperBlock, ast.NodeListItem, true},+ {"paragraph paragraph", ast.NodeParagraph, ast.NodeParagraph, false},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if actual := CanContainBlock(test.parentType, test.childType); test.expected != actual {+ t.Fatalf("expected [%s] containing [%s] to be [%v], got [%v]",+ test.parentType.String(), test.childType.String(), test.expected, actual)+ }+ })+ }+}++func TestValidateBlockSubtree(t *testing.T) {+ list := &ast.Node{Type: ast.NodeList, ID: "list"}+ item := &ast.Node{Type: ast.NodeListItem, ID: "item"}+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}+ list.AppendChild(item)+ item.AppendChild(paragraph)+ if err := ValidateBlockSubtree(list); nil != err {+ t.Fatalf("expected valid list structure, got [%s]", err)+ }++ invalidList := &ast.Node{Type: ast.NodeList, ID: "invalid-list"}+ invalidList.AppendChild(&ast.Node{Type: ast.NodeParagraph, ID: "invalid-paragraph"})+ if err := ValidateBlockSubtree(invalidList); nil == err {+ t.Fatal("expected paragraph directly under list to be rejected")+ }+}++func TestValidateBlockReplacement(t *testing.T) {+ list := &ast.Node{Type: ast.NodeList, ID: "list"}+ oldItem := &ast.Node{Type: ast.NodeListItem, ID: "item"}+ list.AppendChild(oldItem)++ newItem := &ast.Node{Type: ast.NodeListItem, ID: "new-item"}+ newItem.AppendChild(&ast.Node{Type: ast.NodeParagraph, ID: "paragraph"})+ if err := ValidateBlockReplacement(oldItem, newItem); nil != err {+ t.Fatalf("expected list item replacement to be valid, got [%s]", err)+ }++ if err := ValidateBlockReplacement(oldItem, &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}); nil == err {+ t.Fatal("expected paragraph replacing a list item to be rejected")+ }+}