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 transforming multiple headings with subheadings https://github.com/siyuan-note/siyuan/issues/11838
Danielcc1083dd8f28
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.tsindex a0d3b04369..696e723dbe 100644--- a/app/src/config/entryVisibility/catalog.test.ts+++ b/app/src/config/entryVisibility/catalog.test.ts@@ -107,6 +107,24 @@ test("super block actions and vertical alignment use their respective menu groupassert.equal(getEntryCatalogChildren("gutter.multi.layout").some((item) => item.key === "alignTop"), false);});+test("multiple block heading transform follows the regular transform menu", () => {+ const children = getEntryCatalogChildren("gutter.multi");++ assert.deepEqual(children.slice(0, 3).map((item) => item.key), [+ "turnInto",+ "tWithSubtitle",+ "mergeSuperBlock",+ ]);+ assert.deepEqual(getEntryCatalogChildren("gutter.multi.tWithSubtitle").map((item) => item.key), [+ "heading1",+ "heading2",+ "heading3",+ "heading4",+ "heading5",+ "heading6",+ ]);+});+test("simple profile follows the reviewed defaults", () => {const shown = ["document.title.copy.copyBlockEmbed",diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 67c43f9bcf..b6dd369d32 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -191,6 +191,15 @@ const gutterTurnInto = () => node("turnInto", lang("turnInto"), true, []),]);+const gutterHeadingTransform = () => node("tWithSubtitle", lang("tWithSubtitle"), true, [+ node("heading1", lang("heading1")),+ node("heading2", lang("heading2")),+ node("heading3", lang("heading3")),+ node("heading4", lang("heading4")),+ node("heading5", lang("heading5")),+ node("heading6", lang("heading6")),+]);+const gutterLayout = (includeSuperBlockAlignment = false) => node("layout", lang("layout"), true, [node("alignLeft", lang("alignLeft")),node("alignCenter", lang("alignCenter")),@@ -260,7 +269,7 @@ const gutterTable = () => node("table", lang("table"), true, [const gutterBase = (multi: boolean) => [gutterTurnInto(),- ...(multi ? [node("mergeSuperBlock", () => `${window.siyuan.languages.merge} ${window.siyuan.languages.superBlock}`, true, [+ ...(multi ? [gutterHeadingTransform(), node("mergeSuperBlock", () => `${window.siyuan.languages.merge} ${window.siyuan.languages.superBlock}`, true, [node("hLayout", lang("hLayout")),node("vLayout", lang("vLayout")),])] : []),@@ -351,14 +360,7 @@ const gutterSingle = () => []),]),separator("separator_1"),- node("tWithSubtitle", lang("tWithSubtitle"), true, [- node("heading1", lang("heading1")),- node("heading2", lang("heading2")),- node("heading3", lang("heading3")),- node("heading4", lang("heading4")),- node("heading5", lang("heading5")),- node("heading6", lang("heading6")),- ]),+ gutterHeadingTransform(),node("copyHeadings1", () => `${window.siyuan.languages.copy} ${window.siyuan.languages.headings1}`),node("cutHeadings1", () => `${window.siyuan.languages.cut} ${window.siyuan.languages.headings1}`),node("deleteHeadings1", () => `${window.siyuan.languages.delete} ${window.siyuan.languages.headings1}`),diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex 2f40f3c4fc..ec50635e61 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -77,6 +77,7 @@ import {getPlainText} from "../util/paste";import {getGutterSelection,getGutterSelectionTarget,+ getSameContainerHeadingLevel,hasMultipleBlockSelection,isCrossBlockTextRange,isGutterInsertStateMatched@@ -1004,6 +1005,7 @@ export class Gutter {public renderMultipleMenu(protyle: IProtyle, selectsElement: Element[]) {let isList = false;+ const headingLevel = getSameContainerHeadingLevel(selectsElement);const selectsElementGroups: Element[][] = [];selectsElement.forEach((item) => {if (item.classList.contains("li")) {@@ -1152,6 +1154,22 @@ export class Gutter {type: "submenu",submenu: turnIntoSubmenu}).element);+ if (headingLevel) {+ const ids = selectsElement.map((item) => item.getAttribute("data-node-id"));+ const headingSubMenu: IMenu[] = [];+ for (let level = 1; level <= 6; level++) {+ if (level !== headingLevel) {+ headingSubMenu.push(this.genHeadingTransform(protyle, ids, level));+ }+ }+ window.siyuan.menus.menu.append(new MenuItem({+ id: "tWithSubtitle",+ type: "submenu",+ icon: "iconRefresh",+ label: window.siyuan.languages.tWithSubtitle,+ submenu: headingSubMenu+ }).element);+ }if (isContinue && !(selectsElement[0].parentElement.classList.contains("sb") &&selectsElement.length + 1 === selectsElement[0].parentElement.childElementCount)) {window.siyuan.menus.menu.append(new MenuItem({@@ -2661,18 +2679,25 @@ export class Gutter {return window.siyuan.menus.menu;}- private genHeadingTransform(protyle: IProtyle, id: string, level: number) {+ private genHeadingTransform(protyle: IProtyle, id: string | string[], level: number) {+ const ids = Array.isArray(id) ? id : [id];return {id: "heading" + level,iconHTML: "",icon: "iconHeading" + level,label: window.siyuan.languages["heading" + level],click() {- fetchPost("/api/block/getHeadingLevelTransaction", {- id,- level+ fetchPost("/api/block/getHeadingLevelTransaction", ids.length === 1 ? {+ id: ids[0],+ level,+ } : {+ ids,+ level,}, (response) => {- response.data.doOperations.forEach((operation: IOperation, index: number) => {+ if (!response.data?.doOperations?.length) {+ return;+ }+ response.data.doOperations.forEach((operation: IOperation) => {protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((itemElement: HTMLElement) => {itemElement.outerHTML = operation.data;});@@ -2680,10 +2705,11 @@ export class Gutter {protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach((itemElement: HTMLElement) => {mathRender(itemElement);});- if (index === 0) {- focusBlock(protyle.wysiwyg.element.querySelector(`[data-node-id="${operation.id}"]`), protyle.wysiwyg.element, true);- }});+ const focusElement = protyle.wysiwyg.element.querySelector(`[data-node-id="${ids[0]}"]`);+ if (focusElement) {+ focusBlock(focusElement, protyle.wysiwyg.element, true);+ }transaction(protyle, response.data.doOperations, response.data.undoOperations);});}diff --git a/app/src/protyle/gutter/multiSelect.test.ts b/app/src/protyle/gutter/multiSelect.test.tsindex c9b03f7fde..f13c604aca 100644--- a/app/src/protyle/gutter/multiSelect.test.ts+++ b/app/src/protyle/gutter/multiSelect.test.ts@@ -3,6 +3,7 @@ import * as assert from "node:assert/strict";import {getGutterSelection,getGutterSelectionTarget,+ getSameContainerHeadingLevel,isCrossBlockTextRange,isGutterInsertStateMatched} from "./multiSelect";@@ -10,6 +11,7 @@ import {class TestElement {parentElement: TestElement | null = null;children: TestElement[] = [];+ attributes = new Map<string, string>();append(...elements: TestElement[]) {elements.forEach(element => {@@ -19,6 +21,15 @@ class TestElement {return this;}+ setAttribute(name: string, value: string) {+ this.attributes.set(name, value);+ return this;+ }++ getAttribute(name: string) {+ return this.attributes.get(name) || null;+ }+contains(element: TestElement) {let currentElement: TestElement | null = element;while (currentElement) {@@ -33,6 +44,52 @@ class TestElement {const asElement = (element: TestElement) => element as unknown as Element;+const heading = (level: number) => asElement(new TestElement()+ .setAttribute("data-type", "NodeHeading")+ .setAttribute("data-subtype", `h${level}`));++describe("getSameContainerHeadingLevel", () => {+ it("returns the level for headings in the same block container", () => {+ const parent = new TestElement();+ const first = heading(2);+ const second = heading(2);+ parent.append(first as unknown as TestElement, second as unknown as TestElement);++ assert.equal(getSameContainerHeadingLevel([first, second]), 2);+ });++ it("accepts non-contiguous headings in the same block container", () => {+ const parent = new TestElement();+ const first = heading(3);+ const paragraph = new TestElement().setAttribute("data-type", "NodeParagraph");+ const second = heading(3);+ parent.append(first as unknown as TestElement, paragraph, second as unknown as TestElement);++ assert.equal(getSameContainerHeadingLevel([first, second]), 3);+ });++ it("rejects mixed levels, block types, and containers", () => {+ const parent = new TestElement();+ const first = heading(1);+ const second = heading(2);+ const paragraph = asElement(new TestElement().setAttribute("data-type", "NodeParagraph"));+ parent.append(first as unknown as TestElement, second as unknown as TestElement,+ paragraph as unknown as TestElement);++ assert.equal(getSameContainerHeadingLevel([first, second]), undefined);+ assert.equal(getSameContainerHeadingLevel([first, paragraph]), undefined);++ const otherParent = new TestElement();+ const otherHeading = heading(1);+ otherParent.append(otherHeading as unknown as TestElement);+ assert.equal(getSameContainerHeadingLevel([first, otherHeading]), undefined);+ });++ it("requires an actual multiple selection", () => {+ assert.equal(getSameContainerHeadingLevel([heading(1)]), undefined);+ });+});+describe("getGutterSelection", () => {it("keeps the regular gutter behavior for a single selected block", () => {const selected = asElement(new TestElement());diff --git a/app/src/protyle/gutter/multiSelect.ts b/app/src/protyle/gutter/multiSelect.tsindex d923b822bd..4c759faa4e 100644--- a/app/src/protyle/gutter/multiSelect.ts+++ b/app/src/protyle/gutter/multiSelect.ts@@ -1,5 +1,21 @@export const hasMultipleBlockSelection = (blockSelectElements: Element[]) => blockSelectElements.length > 1;+export const getSameContainerHeadingLevel = (selectElements: Element[]) => {+ if (selectElements.length < 2) {+ return;+ }+ const firstElement = selectElements[0];+ const subtype = firstElement.getAttribute("data-subtype");+ if (firstElement.getAttribute("data-type") !== "NodeHeading" || !/^h[1-6]$/.test(subtype)) {+ return;+ }+ if (selectElements.some((item) => item.getAttribute("data-type") !== "NodeHeading" ||+ item.getAttribute("data-subtype") !== subtype || item.parentElement !== firstElement.parentElement)) {+ return;+ }+ return Number.parseInt(subtype.substring(1));+};+export const getGutterSelection = (blockSelectElements: Element[], rangeSelectElements: Element[]) => {if (hasMultipleBlockSelection(blockSelectElements)) {return {isMultiSelect: true, selectElements: blockSelectElements};diff --git a/kernel/api/block.go b/kernel/api/block.goindex 944bb22f1c..1c513ca26d 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -467,10 +467,19 @@ func getHeadingLevelTransaction(c *gin.Context) {return}- id := arg["id"].(string)level := int(arg["level"].(float64))- transaction, err := model.GetHeadingLevelTransaction(id, level)+ var ids []string+ if idsArg, ok := arg["ids"].([]any); ok {+ for _, id := range idsArg {+ ids = append(ids, id.(string))+ }+ ids = gulu.Str.RemoveDuplicatedElem(ids)+ } else {+ ids = []string{arg["id"].(string)}+ }++ transaction, err := model.GetHeadingLevelBatchTransaction(ids, level)if err != nil {ret.Code = -1ret.Msg = err.Error()diff --git a/kernel/model/block.go b/kernel/model/block.goindex f02d968050..7f05a4fd6e 100644--- a/kernel/model/block.go+++ b/kernel/model/block.go@@ -1017,43 +1017,107 @@ func GetHeadingChildrenDOM(id string, removeFoldAttr bool) (ret string) {}func GetHeadingLevelTransaction(id string, level int) (transaction *Transaction, err error) {- tree, err := LoadTreeByBlockID(id)- if err != nil {+ return GetHeadingLevelBatchTransaction([]string{id}, level)+}++func GetHeadingLevelBatchTransaction(ids []string, level int) (transaction *Transaction, err error) {+ if len(ids) == 0 || level < 1 || 6 < level {return}- node := treenode.GetNodeInTree(tree, id)- if nil == node {- err = fmt.Errorf(Conf.Language(15), id)+ tree, err := LoadTreeByBlockID(ids[0])+ if err != nil {return}- if ast.NodeHeading != node.Type {+ selectedHeadings, valid, missingID := headingLevelSelection(tree, ids)+ if "" != missingID {+ err = fmt.Errorf(Conf.Language(15), missingID)+ return+ }+ if !valid || len(selectedHeadings) == 0 {return}- hLevel := node.HeadingLevel+ hLevel := selectedHeadings[0].HeadingLevelif hLevel == level {return}diff := level - hLevel- var children, childrenHeadings []*ast.Node- children = append(children, node)- children = append(children, treenode.HeadingChildren(node)...)- for _, c := range children {- ccH := c.ChildrenByType(ast.NodeHeading)- childrenHeadings = append(childrenHeadings, ccH...)- }+ childrenHeadings := collectHeadingLevelNodes(tree.Root, selectedHeadings)fillBlockRefCount(childrenHeadings, tree.Box)- transaction = &Transaction{}- if treenode.IsSelfFolded(node) {- unfoldHeading(node, node)+ for _, heading := range selectedHeadings {+ if treenode.IsSelfFolded(heading) {+ unfoldHeading(heading, heading)+ }+ }++ transaction = buildHeadingLevelTransaction(childrenHeadings, diff)+ return+}++func headingLevelSelection(tree *parse.Tree, ids []string) (ret []*ast.Node, valid bool, missingID string) {+ if nil == tree || nil == tree.Root || len(ids) == 0 {+ return+ }++ selectedIDs := map[string]struct{}{}+ var parent *ast.Node+ headingLevel := 0+ for _, id := range ids {+ if _, ok := selectedIDs[id]; ok {+ continue+ }+ selectedIDs[id] = struct{}{}++ heading := treenode.GetNodeInTree(tree, id)+ if nil == heading {+ return nil, false, id+ }+ if ast.NodeHeading != heading.Type {+ return nil, false, ""+ }+ if len(ret) == 0 {+ parent = heading.Parent+ headingLevel = heading.HeadingLevel+ } else if heading.Parent != parent || heading.HeadingLevel != headingLevel {+ return nil, false, ""+ }+ ret = append(ret, heading)+ }+ valid = 0 < len(ret)+ return+}++func collectHeadingLevelNodes(root *ast.Node, selectedHeadings []*ast.Node) (ret []*ast.Node) {+ selectedNodes := map[*ast.Node]struct{}{}+ for _, heading := range selectedHeadings {+ selectedNodes[heading] = struct{}{}+ for _, child := range treenode.HeadingChildren(heading) {+ for _, childHeading := range child.ChildrenByType(ast.NodeHeading) {+ selectedNodes[childHeading] = struct{}{}+ }+ }}+ ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if _, ok := selectedNodes[node]; ok {+ ret = append(ret, node)+ }+ return ast.WalkContinue+ })+ return+}++func buildHeadingLevelTransaction(headings []*ast.Node, diff int) (transaction *Transaction) {+ transaction = &Transaction{}luteEngine := util.NewLute()- for _, c := range childrenHeadings {+ for _, c := range headings {op := &Operation{}op.ID = c.IDop.Action = "update"diff --git a/kernel/model/heading_level_test.go b/kernel/model/heading_level_test.gonew file mode 100644index 0000000000..095e991e7a--- /dev/null+++ b/kernel/model/heading_level_test.go@@ -0,0 +1,126 @@+// SiYuan - From thought to insight, with agents+// 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"+)++func TestHeadingLevelSelectionUsesDirectContainerAndLevel(t *testing.T) {+ root := &ast.Node{Type: ast.NodeDocument}+ h1First := newHeadingLevelTestNode("h1-first", 1)+ h2First := newHeadingLevelTestNode("h2-first", 2)+ h1Second := newHeadingLevelTestNode("h1-second", 1)+ h2Second := newHeadingLevelTestNode("h2-second", 2)+ root.AppendChild(h1First)+ root.AppendChild(h2First)+ root.AppendChild(h1Second)+ root.AppendChild(h2Second)+ tree := &parse.Tree{Root: root}++ selected, valid, missingID := headingLevelSelection(tree, []string{h2First.ID, h2First.ID, h2Second.ID})+ if !valid || "" != missingID {+ t.Fatalf("expected a valid selection, got valid [%v] and missing ID [%s]", valid, missingID)+ }+ assertHeadingLevelNodeIDs(t, selected, h2First.ID, h2Second.ID)++ selected, valid, missingID = headingLevelSelection(tree, []string{h1First.ID, h2First.ID})+ if valid || "" != missingID || nil != selected {+ t.Fatalf("expected mixed heading levels to be rejected")+ }++ selected, valid, missingID = headingLevelSelection(tree, []string{h1First.ID, "missing"})+ if valid || missingID != "missing" || nil != selected {+ t.Fatalf("expected the missing heading ID to be reported")+ }+}++func TestHeadingLevelSelectionRejectsNestedContainer(t *testing.T) {+ root := &ast.Node{Type: ast.NodeDocument}+ rootHeading := newHeadingLevelTestNode("root-heading", 1)+ list := &ast.Node{Type: ast.NodeList}+ item := &ast.Node{Type: ast.NodeListItem}+ nestedHeading := newHeadingLevelTestNode("nested-heading", 1)+ root.AppendChild(rootHeading)+ item.AppendChild(nestedHeading)+ list.AppendChild(item)+ root.AppendChild(list)++ selected, valid, missingID := headingLevelSelection(&parse.Tree{Root: root},+ []string{rootHeading.ID, nestedHeading.ID})+ if valid || "" != missingID || nil != selected {+ t.Fatalf("expected headings in different direct containers to be rejected")+ }+}++func TestCollectHeadingLevelNodesKeepsDocumentOrder(t *testing.T) {+ root := &ast.Node{Type: ast.NodeDocument}+ h1First := newHeadingLevelTestNode("h1-first", 1)+ h2First := newHeadingLevelTestNode("h2-first", 2)+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}+ h1Second := newHeadingLevelTestNode("h1-second", 1)+ h3Second := newHeadingLevelTestNode("h3-second", 3)+ root.AppendChild(h1First)+ root.AppendChild(h2First)+ root.AppendChild(paragraph)+ root.AppendChild(h1Second)+ root.AppendChild(h3Second)++ actual := collectHeadingLevelNodes(root, []*ast.Node{h1Second, h1First})+ assertHeadingLevelNodeIDs(t, actual, h1First.ID, h2First.ID, h1Second.ID, h3Second.ID)+}++func TestBuildHeadingLevelTransactionClampsLevels(t *testing.T) {+ h1 := newHeadingLevelTestNode("h1", 1)+ h2 := newHeadingLevelTestNode("h2", 2)+ h6 := newHeadingLevelTestNode("h6", 6)++ transaction := buildHeadingLevelTransaction([]*ast.Node{h1, h2, h6}, 1)+ if len(transaction.DoOperations) != 3 || len(transaction.UndoOperations) != 3 {+ t.Fatalf("expected three do and undo operations")+ }+ assertHeadingLevelNodeIDs(t, []*ast.Node{h1, h2, h6}, "h1", "h2", "h6")+ if h1.HeadingLevel != 2 || h2.HeadingLevel != 3 || h6.HeadingLevel != 6 {+ t.Fatalf("unexpected transformed levels [%d, %d, %d]", h1.HeadingLevel, h2.HeadingLevel, h6.HeadingLevel)+ }+ for i, id := range []string{"h1", "h2", "h6"} {+ if transaction.DoOperations[i].ID != id || transaction.UndoOperations[i].ID != id {+ t.Fatalf("expected operation for heading [%s] at index %d", id, i)+ }+ }+}++func newHeadingLevelTestNode(id string, level int) *ast.Node {+ heading := &ast.Node{Type: ast.NodeHeading, ID: id, HeadingLevel: level}+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(id)})+ return heading+}++func assertHeadingLevelNodeIDs(t *testing.T, nodes []*ast.Node, expected ...string) {+ t.Helper()+ if len(nodes) != len(expected) {+ t.Fatalf("expected %d headings, got %d", len(expected), len(nodes))+ }+ for i, node := range nodes {+ if node.ID != expected[i] {+ t.Fatalf("expected heading [%s] at index %d, got [%s]", expected[i], i, node.ID)+ }+ }+}