An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Fix referenced block deletion confirmation regressions https://github.com/siyuan-note/siyuan/issues/13396
Danielc9a93d53d53d
diff --git a/app/src/dialog/confirmDialog.ts b/app/src/dialog/confirmDialog.tsindex c574fb5f25..d073b9cd1b 100644--- a/app/src/dialog/confirmDialog.ts+++ b/app/src/dialog/confirmDialog.ts@@ -10,6 +10,15 @@ export const confirmDialog = (title: string, text: string,confirm();return;}+ const previousActiveElement = document.activeElement as HTMLElement;+ let handled = false;+ const handleCancel = () => {+ if (handled) {+ return;+ }+ handled = true;+ cancel?.(dialog);+ };const dialog = new Dialog({title,content: `<div class="b3-dialog__content">@@ -20,6 +29,16 @@ export const confirmDialog = (title: string, text: string,<button class="b3-button ${isDelete ? "b3-button--remove" : "b3-button--text"}" id="confirmDialogConfirmBtn">${window.siyuan.languages[isDelete ? "delete" : "confirm"]}</button></div>`,width: isMobile() ? "92vw" : "520px",+ destroyCallback: () => {+ handleCancel();+ if (!previousActiveElement?.isConnected) {+ return;+ }+ const activeElement = document.activeElement as HTMLElement;+ if (!activeElement || activeElement === document.body) {+ previousActiveElement.focus({preventScroll: true});+ }+ },});dialog.element.addEventListener("click", (event) => {@@ -27,15 +46,12 @@ export const confirmDialog = (title: string, text: string,const isDispatch = typeof event.detail === "string";while (target && target !== dialog.element || isDispatch) {if (target.id === "cancelDialogConfirmBtn" || (isDispatch && event.detail=== "Escape")) {- if (cancel) {- cancel(dialog);- }+ handleCancel();dialog.destroy();break;} else if (target.id === "confirmDialogConfirmBtn" || (isDispatch && event.detail=== "Enter")) {- if (confirm) {- confirm(dialog);- }+ handled = true;+ confirm?.(dialog);dialog.destroy();break;}@@ -43,4 +59,5 @@ export const confirmDialog = (title: string, text: string,}});dialog.element.setAttribute("data-key", Constants.DIALOG_CONFIRM);+ (dialog.element.querySelector("#cancelDialogConfirmBtn") as HTMLButtonElement).focus({preventScroll: true});};diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex d00852647b..f19f2d67ff 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -2518,6 +2518,7 @@ export class WYSIWYG {selectElements = [nodeElement];autoSelectedBlock = true;}+ const selectedStateElements = [...selectElements];let html = "";let textPlain = "";let isInCodeBlock = false;@@ -2597,7 +2598,7 @@ export class WYSIWYG {}return;}- if (selectElements.some(item => !item.isConnected || !item.classList.contains("protyle-wysiwyg--select"))) {+ if (selectedStateElements.some(item => !item.isConnected || !item.classList.contains("protyle-wysiwyg--select"))) {return;}needClipboardWrite = true;diff --git a/app/src/protyle/wysiwyg/remove.ts b/app/src/protyle/wysiwyg/remove.tsindex 2d89a93121..edcb52cf4e 100644--- a/app/src/protyle/wysiwyg/remove.ts+++ b/app/src/protyle/wysiwyg/remove.ts@@ -256,6 +256,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangconst foldTransactions = new Map<string, IWebSocketData>();if (!skipRefCheck) {const checkIDs: string[] = [];+ const exactIDs: string[] = [];const selectedSuperBlocks = new Map<Element, number>();for (const item of selectElements) {const topElement = getTopAloneElement(item);@@ -282,12 +283,15 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rang}selectedSuperBlocks.forEach((selectedCount, superBlock) => {if (getSbChildBlockCount(superBlock) - selectedCount <= 1) {- checkIDs.push(superBlock.getAttribute("data-node-id"));+ const superBlockID = superBlock.getAttribute("data-node-id");+ checkIDs.push(superBlockID);+ exactIDs.push(superBlockID);}});if (!await confirmBlockRef({scope: "blocks",ids: Array.from(new Set(checkIDs)),+ exactIDs: Array.from(new Set(exactIDs)),notebook: protyle.notebookId,}, protyle)) {return false;@@ -627,7 +631,8 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangconst removeBlockParent = isCallout ? blockParentElement.querySelector(".callout-content").childElementCount === 1 :blockParentElement.childElementCount === 2;if (removeBlockParent && !await confirmRefRemoval(protyle,- [blockParentElement.getAttribute("data-node-id")], [blockParentElement])) {+ [blockParentElement.getAttribute("data-node-id")], [blockParentElement],+ [blockParentElement.getAttribute("data-node-id")])) {return;}if (type !== "Delete") {@@ -810,10 +815,13 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangif (editableElement.textContent.trim() === "") {const id = blockElement.getAttribute("data-node-id");const checkIDs = [id];+ const exactIDs: string[] = [];if (parentElement && parentElement.getAttribute("data-type") === "NodeSuperBlock" && getSbChildBlockCount(parentElement) === 2) {- checkIDs.push(parentElement.getAttribute("data-node-id"));+ const parentID = parentElement.getAttribute("data-node-id");+ checkIDs.push(parentID);+ exactIDs.push(parentID);}- if (!await confirmRefRemoval(protyle, checkIDs, [blockElement])) {+ if (!await confirmRefRemoval(protyle, checkIDs, [blockElement], exactIDs)) {return;}const doOperations: IOperation[] = [{@@ -857,10 +865,13 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rang}const removeId = removeElement.getAttribute("data-node-id");const checkIDs = [removeId];+ const exactIDs: string[] = [];if (parentElement && parentElement.getAttribute("data-type") === "NodeSuperBlock" && getSbChildBlockCount(parentElement) === 2) {- checkIDs.push(parentElement.getAttribute("data-node-id"));+ const parentID = parentElement.getAttribute("data-node-id");+ checkIDs.push(parentID);+ exactIDs.push(parentID);}- if (!await confirmRefRemoval(protyle, checkIDs, [removeElement])) {+ if (!await confirmRefRemoval(protyle, checkIDs, [removeElement], exactIDs)) {return;}range.insertNode(document.createElement("wbr"));@@ -1064,10 +1075,11 @@ export const removeImage = (imgSelectElement: Element, nodeElement: HTMLElement,}};-const confirmRefRemoval = async (protyle: IProtyle, ids: string[], elements: Element[]) => {+const confirmRefRemoval = async (protyle: IProtyle, ids: string[], elements: Element[], exactIDs: string[] = []) => {const confirmed = await confirmBlockRef({scope: "blocks",ids,+ exactIDs,notebook: protyle.notebookId,}, protyle);if (confirmed && elements.every(item => item.isConnected)) {@@ -1085,7 +1097,8 @@ const removeLi = async (protyle: IProtyle, blockElement: Element, range: Range,// 第一个子列表合并到上一个块的末尾if (!blockElement.parentElement.previousElementSibling && blockElement.parentElement.parentElement.parentElement.classList.contains("list")) {if (!await confirmRefRemoval(protyle,- [blockElement.parentElement.getAttribute("data-node-id")], [blockElement.parentElement])) {+ [blockElement.parentElement.getAttribute("data-node-id")], [blockElement.parentElement],+ [blockElement.parentElement.getAttribute("data-node-id")])) {return;}range.insertNode(document.createElement("wbr"));@@ -1128,7 +1141,8 @@ const removeLi = async (protyle: IProtyle, blockElement: Element, range: Range,return;}if (!await confirmRefRemoval(protyle,- [blockElement.parentElement.getAttribute("data-node-id")], [blockElement.parentElement])) {+ [blockElement.parentElement.getAttribute("data-node-id")], [blockElement.parentElement],+ [blockElement.parentElement.getAttribute("data-node-id")])) {return;}moveToPrevious(blockElement, range, isDelete);@@ -1209,7 +1223,7 @@ const removeLi = async (protyle: IProtyle, blockElement: Element, range: Range,const deleteFoldedListItem = previousListItem.getAttribute("fold") !== "1" ||(getContenteditableElement(blockElement).textContent.trim() === "" &&blockElement.nextElementSibling.classList.contains("protyle-attr"));- if (deleteFoldedListItem && !await confirmRefRemoval(protyle, [listItemId], [listItemElement])) {+ if (deleteFoldedListItem && !await confirmRefRemoval(protyle, [listItemId], [listItemElement], [listItemId])) {return;}moveToPrevious(blockElement, range, isDelete);diff --git a/app/src/util/checkBlockRef.ts b/app/src/util/checkBlockRef.tsindex c173121efd..09c7f02529 100644--- a/app/src/util/checkBlockRef.ts+++ b/app/src/util/checkBlockRef.ts@@ -6,6 +6,7 @@ import {fetchSyncPost} from "./fetch";export interface IBlockRefCheckOptions {scope: "blocks" | "documents" | "notebook";ids?: string[];+ exactIDs?: string[];paths?: string[];notebook?: string;}diff --git a/kernel/api/block.go b/kernel/api/block.goindex 016a6f3a98..7c09430ffc 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -58,15 +58,36 @@ func checkBlockRef(c *gin.Context) {}switch scope {case "blocks":- ids, parsed := parseBlockRefStringArray(arg, "ids", ret)+ ids, parsed := parseBlockRefStringArray(arg, "ids", ret, true)if !parsed {return}+ var exactIDs []string+ if _, exists := arg["exactIDs"]; exists {+ exactIDs, parsed = parseBlockRefStringArray(arg, "exactIDs", ret, false)+ if !parsed {+ return+ }+ }for _, id := range ids {if util.InvalidIDPattern(id, ret) {return}}+ idSet := map[string]struct{}{}+ for _, id := range ids {+ idSet[id] = struct{}{}+ }+ for _, id := range exactIDs {+ if util.InvalidIDPattern(id, ret) {+ return+ }+ if _, exists := idSet[id]; !exists {+ ret.Code = -1+ ret.Msg = "Field [exactIDs] should be a subset of field [ids]"+ return+ }+ }notebook, valid := util.ParseJsonArg[string]("notebook", arg, ret, false, false)if !valid {return@@ -75,13 +96,13 @@ func checkBlockRef(c *gin.Context) {return}var err error- ret.Data, err = model.CheckBlockRefInBox(ids, notebook)+ ret.Data, err = model.CheckBlockRefInBox(ids, exactIDs, notebook)if err != nil {ret.Code = -1ret.Msg = err.Error()}case "documents":- paths, parsed := parseBlockRefStringArray(arg, "paths", ret)+ paths, parsed := parseBlockRefStringArray(arg, "paths", ret, true)if !parsed {return}@@ -111,9 +132,9 @@ func checkBlockRef(c *gin.Context) {}}-func parseBlockRefStringArray(arg map[string]any, key string, ret *gulu.Result) (values []string, ok bool) {+func parseBlockRefStringArray(arg map[string]any, key string, ret *gulu.Result, rejectEmpty bool) (values []string, ok bool) {var raw []any- if !util.ParseJsonArgs(arg, ret, util.BindJsonArg(key, &raw, true, true)) {+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg(key, &raw, true, rejectEmpty)) {return}for _, value := range raw {diff --git a/kernel/api/block_test.go b/kernel/api/block_test.goindex cc14cd4974..9a89a3734c 100644--- a/kernel/api/block_test.go+++ b/kernel/api/block_test.go@@ -25,6 +25,7 @@ import ("strings""testing"+ "github.com/88250/gulu""github.com/88250/lute/ast""github.com/88250/lute/parse""github.com/gin-gonic/gin"@@ -33,6 +34,21 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+func TestParseBlockRefStringArrayEmptyHandling(t *testing.T) {+ arg := map[string]any{"ids": []any{}}++ requiredResult := gulu.Ret.NewResult()+ if _, ok := parseBlockRefStringArray(arg, "ids", requiredResult, true); ok || requiredResult.Code != -1 {+ t.Fatalf("expected an empty required array to be rejected, got code %d", requiredResult.Code)+ }++ optionalResult := gulu.Ret.NewResult()+ values, ok := parseBlockRefStringArray(arg, "ids", optionalResult, false)+ if !ok || optionalResult.Code != 0 || len(values) != 0 {+ t.Fatalf("expected an empty optional array to be accepted, got code %d and values %v", optionalResult.Code, values)+ }+}+func TestFilterBlockIDsByPublishAccess(t *testing.T) {const (boxID = "20260724000000-boxid01"diff --git a/kernel/model/block.go b/kernel/model/block.goindex 0140563171..5f85f0d695 100644--- a/kernel/model/block.go+++ b/kernel/model/block.go@@ -129,12 +129,12 @@ func newBlockRefCheckGroup() *blockRefCheckGroup {// CheckBlockRef 保留原有调用语义。func CheckBlockRef(ids []string) bool {- ret, _ := CheckBlockRefInBox(ids, "")+ ret, _ := CheckBlockRefInBox(ids, nil, "")return ret}// CheckBlockRefInBox 检查块及其容器后代是否被引用。-func CheckBlockRefInBox(ids []string, boxID string) (ret bool, err error) {+func CheckBlockRefInBox(ids, exactIDs []string, boxID string) (ret bool, err error) {sql.FlushQueue()ids = gulu.Str.RemoveDuplicatedElem(ids)if 1 > len(ids) {@@ -149,6 +149,10 @@ func CheckBlockRefInBox(ids []string, boxID string) (ret bool, err error) {}group := newBlockRefCheckGroup()+ exactIDSet := map[string]struct{}{}+ for _, id := range exactIDs {+ exactIDSet[id] = struct{}{}+ }selectedByRoot := map[string]map[string]map[string]struct{}{}for _, bt := range bts {if "d" == bt.Type && bt.ID == bt.RootID {@@ -156,6 +160,9 @@ func CheckBlockRefInBox(ids []string, boxID string) (ret bool, err error) {continue}group.blockIDs[bt.ID] = struct{}{}+ if _, exact := exactIDSet[bt.ID]; exact {+ continue+ }if nil == selectedByRoot[bt.BoxID] {selectedByRoot[bt.BoxID] = map[string]map[string]struct{}{}}@@ -219,10 +226,8 @@ func CheckNotebookRef(boxID string) (ret bool, err error) {return false, ErrBoxNotFound}group := newBlockRefCheckGroup()- for _, bt := range treenode.GetBlockTreesByBoxID(boxID) {- if bt.ID == bt.RootID {- group.rootIDs[bt.RootID] = struct{}{}- }+ for _, rootID := range treenode.GetRootBlockIDsByBoxID(boxID) {+ group.rootIDs[rootID] = struct{}{}}return existBlockRefGroup(group)}diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.goindex 1c22eb98c1..4ebc5744fa 100644--- a/kernel/treenode/blocktree.go+++ b/kernel/treenode/blocktree.go@@ -73,6 +73,9 @@ func initDatabase(forceRebuild bool) {}}if !forceRebuild {+ if _, err := db.Exec("CREATE INDEX IF NOT EXISTS idx_blocktrees_box_id ON blocktrees(box_id)"); err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create blocktree box index failed: %s", err)+ }return}@@ -101,6 +104,11 @@ func initDBTables() {if err != nil {logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create index [idx_blocktrees_root_id] failed: %s", err)}++ _, err = db.Exec("CREATE INDEX idx_blocktrees_box_id ON blocktrees(box_id)")+ if err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create index [idx_blocktrees_box_id] failed: %s", err)+ }}func initDBConnection() {@@ -615,6 +623,25 @@ func GetBlockTreesByBoxID(boxID string) (ret []*BlockTree) {return}+func GetRootBlockIDsByBoxID(boxID string) (ret []string) {+ sqlStmt := "SELECT id FROM blocktrees WHERE box_id = ? AND id = root_id AND type = 'd'"+ rows, err := queryForBox(boxID, sqlStmt, boxID)+ if err != nil {+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)+ return+ }+ defer rows.Close()+ for rows.Next() {+ var id string+ if err = rows.Scan(&id); err != nil {+ logging.LogErrorf("query scan field failed: %s", err)+ return+ }+ ret = append(ret, id)+ }+ return+}+func RemoveBlockTreesByBoxID(boxID string) (ids []string) {sqlStmt := "SELECT id FROM blocktrees WHERE box_id = ?"rows, err := queryForBox(boxID, sqlStmt, boxID)@@ -974,6 +1001,7 @@ func initEncryptedBlockTreeTables(boxDB *sql.DB) (err error) {"CREATE TABLE IF NOT EXISTS blocktrees (id, root_id, parent_id, box_id, path, hpath, updated, type)","CREATE INDEX IF NOT EXISTS idx_blocktrees_id ON blocktrees(id)","CREATE INDEX IF NOT EXISTS idx_blocktrees_root_id ON blocktrees(root_id)",+ "CREATE INDEX IF NOT EXISTS idx_blocktrees_box_id ON blocktrees(box_id)",}for _, s := range stmts {if _, err = boxDB.Exec(s); err != nil {diff --git a/kernel/treenode/blocktree_query_test.go b/kernel/treenode/blocktree_query_test.gonew file mode 100644index 0000000000..b0e52e74ed--- /dev/null+++ b/kernel/treenode/blocktree_query_test.go@@ -0,0 +1,58 @@+// 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 (+ "database/sql"+ "path/filepath"+ "slices"+ "testing"++ "github.com/mattn/go-sqlite3"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func init() {+ sql.Register("sqlite3_extended", &sqlite3.SQLiteDriver{})+}++func TestGetRootBlockIDsByBoxID(t *testing.T) {+ const (+ boxID = "20260730000000-box0001"+ otherBoxID = "20260730000001-box0002"+ docID = "20260730000002-doc0001"+ otherDocID = "20260730000003-doc0002"+ )++ previousBlockTreeDBPath := util.BlockTreeDBPath+ util.BlockTreeDBPath = filepath.Join(t.TempDir(), "blocktree.db")+ InitBlockTree(true)+ t.Cleanup(func() {+ CloseDatabase()+ util.BlockTreeDBPath = previousBlockTreeDBPath+ if "" != previousBlockTreeDBPath {+ InitBlockTree(false)+ }+ })++ UpsertBlockTree(NewTree(boxID, "/"+docID+".sy", "/Document", "Document"))+ UpsertBlockTree(NewTree(otherBoxID, "/"+otherDocID+".sy", "/Other", "Other"))++ if rootIDs := GetRootBlockIDsByBoxID(boxID); !slices.Equal(rootIDs, []string{docID}) {+ t.Fatalf("unexpected document root IDs: %v", rootIDs)+ }+}