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 breadcrumb child block navigation https://github.com/siyuan-note/siyuan/issues/2613
Daniele371a5a0e922
diff --git a/app/src/constants.ts b/app/src/constants.tsindex e5e0b326dd..e18e3237f9 100644--- a/app/src/constants.ts+++ b/app/src/constants.ts@@ -261,6 +261,7 @@ export abstract class Constants {public static readonly MENU_FROM_TITLE_BREADCRUMB = "title-breadcrumb"; // 在面包屑触发的文档块菜单public static readonly MENU_BREADCRUMB_MORE = "breadcrumbMore"; // 面包屑更多菜单public static readonly MENU_BREADCRUMB_MOBILE_PATH = "breadcrumb-mobile-path"; // 移动端面包屑菜单+ public static readonly MENU_BREADCRUMB_CHILDREN = "breadcrumb-children"; // 面包屑下级块菜单public static readonly MENU_DOC_TREE_MORE = "docTreeMore"; // 侧栏文档树右键菜单public static readonly MENU_FROM_DOC_TREE_MORE_NOTEBOOK = "tree-notebook"; // 侧栏文档树右键菜单,单个笔记本diff --git a/app/src/menus/Menu.ts b/app/src/menus/Menu.tsindex 943f4f75aa..9e3eed8819 100644--- a/app/src/menus/Menu.ts+++ b/app/src/menus/Menu.ts@@ -329,15 +329,59 @@ export class MenuItem {options.bind(this.element);}- if (options.submenu) {+ if (options.submenu || options.loadSubmenu) {const submenuElement = document.createElement("div");submenuElement.classList.add("b3-menu__submenu");submenuElement.innerHTML = '<div class="b3-menu__items"></div>';- options.submenu.forEach((item) => {+ (options.submenu || [{+ type: "readonly",+ label: window.siyuan.languages.loading,+ }]).forEach((item: IMenu) => {submenuElement.firstElementChild.append(new MenuItem(item, menu)?.element || "");});this.element.insertAdjacentHTML("beforeend", '<svg class="b3-menu__icon b3-menu__icon--small"><use xlink:href="#iconRight"></use></svg>');this.element.append(submenuElement);+ if (options.loadSubmenu) {+ let loading = false;+ let loaded = false;+ const loadSubmenu = () => {+ if (loading || loaded) {+ return;+ }+ loading = true;+ options.loadSubmenu().then((items) => {+ if (!this.element.isConnected) {+ return;+ }+ const itemsElement = submenuElement.firstElementChild;+ itemsElement.innerHTML = "";+ if (items.length === 0) {+ itemsElement.append(new MenuItem({+ type: "readonly",+ label: window.siyuan.languages.emptyContent,+ }, menu).element);+ } else {+ items.forEach((item) => {+ itemsElement.append(new MenuItem(item, menu)?.element || "");+ });+ }+ loaded = true;+ menu.showSubMenu(submenuElement);+ }).catch(() => {+ if (!this.element.isConnected) {+ return;+ }+ submenuElement.firstElementChild.innerHTML = "";+ submenuElement.firstElementChild.append(new MenuItem({+ type: "readonly",+ label: window.siyuan.languages.emptyContent,+ }, menu).element);+ }).finally(() => {+ loading = false;+ });+ };+ this.element.addEventListener(isMobile() ? "click" : "mouseenter", loadSubmenu);+ }}}}diff --git a/app/src/protyle/breadcrumb/index.ts b/app/src/protyle/breadcrumb/index.tsindex b5ca3cfa04..09583b9b96 100644--- a/app/src/protyle/breadcrumb/index.ts+++ b/app/src/protyle/breadcrumb/index.ts@@ -1,5 +1,5 @@import {getIconByType} from "../../editor/getIcon";-import {fetchPost} from "../../util/fetch";+import {fetchPost, fetchSyncPost} from "../../util/fetch";import {Constants} from "../../constants";import {MenuItem} from "../../menus/Menu";import {fullscreen, net2LocalAssets, updateReadonly} from "./action";@@ -66,6 +66,21 @@ ${padHTML}this.element = element.firstElementChild as HTMLElement;element.addEventListener("click", (event) => {let target = event.target as HTMLElement;+ const arrowElement = target.closest(".protyle-breadcrumb__arrow");+ if (arrowElement && this.element.contains(arrowElement)) {+ const itemElement = arrowElement.previousElementSibling as HTMLElement;+ if (itemElement?.classList.contains("protyle-breadcrumb__item")) {+ const targetRect = arrowElement.getBoundingClientRect();+ this.openChildrenMenu(protyle, itemElement.getAttribute("data-node-id"), {+ x: targetRect.left,+ y: targetRect.bottom,+ isLeft: false,+ });+ event.preventDefault();+ event.stopPropagation();+ return;+ }+ }while (target && !target.isEqualNode(element)) {const id = target.getAttribute("data-node-id");const type = target.getAttribute("data-type");@@ -183,6 +198,19 @@ ${padHTML}}});/// #if !MOBILE+ this.element.addEventListener("contextmenu", (event) => {+ const itemElement = (event.target as HTMLElement).closest(".protyle-breadcrumb__item");+ if (!itemElement || !this.element.contains(itemElement)) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ this.openChildrenMenu(protyle, itemElement.getAttribute("data-node-id"), {+ x: event.clientX,+ y: event.clientY,+ isLeft: false,+ });+ });element.addEventListener("mouseleave", () => {protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--hl").forEach(item => {item.classList.remove("protyle-wysiwyg--hl");@@ -194,6 +222,115 @@ ${padHTML}/// #endif}+ private async openChildrenMenu(protyle: IProtyle, id: string, position: IPosition) {+ if (!id) {+ return;+ }++ const menuName = `${Constants.MENU_BREADCRUMB_CHILDREN}-${id}`;+ const menu = new Menu(menuName);+ if (menu.isOpen) {+ return;+ }++ const currentPathIDs = new Set<string>();+ this.element.querySelectorAll(".protyle-breadcrumb__item").forEach((item) => {+ const itemID = item.getAttribute("data-node-id");+ if (itemID) {+ currentPathIDs.add(itemID);+ }+ });+ const excludeTypes: string[] = [];+ if (this.element.parentElement?.parentElement?.classList.contains("card__block")) {+ excludeTypes.push("NodeTextMark-mark");+ }++ let items: IMenu[];+ try {+ items = await this.genChildrenMenuItems(protyle, id, currentPathIDs, excludeTypes);+ } catch (e) {+ console.warn("get breadcrumb children failed", e);+ if (window.siyuan.menus.menu.element.getAttribute("data-name") === menuName) {+ window.siyuan.menus.menu.remove();+ }+ return;+ }+ if (window.siyuan.menus.menu.element.getAttribute("data-name") !== menuName) {+ return;+ }+ if (items.length === 0) {+ window.siyuan.menus.menu.remove();+ return;+ }++ items.forEach((item) => {+ menu.addItem(item);+ });+ menu.open(position);+ }++ private async genChildrenMenuItems(protyle: IProtyle, id: string, currentPathIDs: Set<string>,+ excludeTypes: string[], offset = 0): Promise<IMenu[]> {+ const request: Record<string, any> = {+ id,+ offset,+ limit: 64,+ excludeTypes,+ };+ if (isEncryptedBox(protyle.notebookId)) {+ request.notebook = protyle.notebookId;+ }+ const response = await fetchSyncPost("/api/block/getBlockBreadcrumbChildren", request);+ const data = response.data as {+ items: IBreadcrumb[],+ hasMore: boolean,+ };+ if (!data?.items) {+ return [];+ }++ const items = data.items.map((item) => {+ const menuItem: IMenu = {+ id: item.id,+ icon: getIconByType(item.type, item.subType),+ label: item.name || window.siyuan.languages.untitled,+ current: currentPathIDs.has(item.id),+ click: () => {+ zoomOut({protyle, id: item.id});+ },+ };+ if (item.hasChildren) {+ menuItem.loadSubmenu = () => this.genChildrenMenuItems(protyle, item.id, currentPathIDs, excludeTypes);+ }+ return menuItem;+ });++ if (data.hasMore) {+ items.push({+ icon: "iconMore",+ label: window.siyuan.languages.loadMore,+ click: (element) => {+ element.setAttribute("disabled", "disabled");+ this.genChildrenMenuItems(protyle, id, currentPathIDs, excludeTypes, offset + data.items.length)+ .then((nextItems) => {+ if (!element.isConnected) {+ return;+ }+ nextItems.forEach((item) => {+ element.before(new MenuItem(item).element);+ });+ element.remove();+ window.siyuan.menus.menu.resetPosition();+ }).catch(() => {+ element.removeAttribute("disabled");+ });+ return true;+ },+ });+ }+ return items;+ }+private startRecord(protyle: IProtyle) {this.messageId = showMessage(`<div class="fn__flex fn__flex-wrap"><span class="fn__flex-center">${window.siyuan.languages.recording}</span><span class="fn__space"></span>diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex a885b8fe92..ee3ba65469 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -963,6 +963,7 @@ interface IMenu {action?: string,id?: string,submenu?: IMenu[]+ loadSubmenu?: () => Promise<IMenu[]>disabled?: booleanicon?: stringiconHTML?: stringdiff --git a/app/src/types/protyle.d.ts b/app/src/types/protyle.d.tsindex 7bddb8383f..233b868b0d 100644--- a/app/src/types/protyle.d.ts+++ b/app/src/types/protyle.d.ts@@ -123,7 +123,8 @@ interface IBreadcrumb {name: string,type: string,subType: string,- children: []+ children: IBreadcrumb[],+ hasChildren?: boolean}interface ILuteOptions extends IMarkdownConfig {diff --git a/kernel/api/block.go b/kernel/api/block.goindex 6474c145df..910345f45a 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -751,6 +751,51 @@ func getBlockBreadcrumb(c *gin.Context) {ret.Data = blockPath}+func getBlockBreadcrumbChildren(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }++ id := arg["id"].(string)+ if util.InvalidIDPattern(id, ret) {+ return+ }++ var excludeTypes []string+ if excludeTypesArg := arg["excludeTypes"]; nil != excludeTypesArg {+ for _, excludeType := range excludeTypesArg.([]any) {+ excludeTypes = append(excludeTypes, excludeType.(string))+ }+ }++ offset := 0+ if offsetArg := arg["offset"]; nil != offsetArg {+ offset = int(offsetArg.(float64))+ }+ limit := 64+ if limitArg := arg["limit"]; nil != limitArg {+ limit = int(limitArg.(float64))+ }++ boxID := encryptedNotebookFromArg(arg)+ if !isBlockPublishAccessible(c, id, boxID) {+ ret.Data = &model.BlockBreadcrumbChildren{Items: []*model.BlockPath{}}+ return+ }++ children, err := model.GetBlockBreadcrumbChildrenInBox(id, excludeTypes, offset, limit, boxID)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ ret.Data = children+}+func getBlockIndex(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/router.go b/kernel/api/router.goindex d35c7dec8e..1ee3e2e5f3 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -234,6 +234,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/block/getChildBlocks", model.CheckAuth, model.CheckAdminRole, getChildBlocks)ginServer.Handle("POST", "/api/block/getTailChildBlocks", model.CheckAuth, model.CheckAdminRole, getTailChildBlocks)ginServer.Handle("POST", "/api/block/getBlockBreadcrumb", model.CheckAuth, getBlockBreadcrumb)+ ginServer.Handle("POST", "/api/block/getBlockBreadcrumbChildren", model.CheckAuth, getBlockBreadcrumbChildren)ginServer.Handle("POST", "/api/block/getBlockIndex", model.CheckAuth, getBlockIndex)ginServer.Handle("POST", "/api/block/getBlocksIndexes", model.CheckAuth, getBlocksIndexes)ginServer.Handle("POST", "/api/block/getRefIDs", model.CheckAuth, getRefIDs)diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.goindex 45064bfd97..b91b699b9a 100644--- a/kernel/model/blockinfo.go+++ b/kernel/model/blockinfo.go@@ -528,11 +528,17 @@ func GetBlocksIndexes(ids []string) (ret map[string]int) {}type BlockPath struct {- ID string `json:"id"`- Name string `json:"name"`- Type string `json:"type"`- SubType string `json:"subType"`- Children []*BlockPath `json:"children"`+ ID string `json:"id"`+ Name string `json:"name"`+ Type string `json:"type"`+ SubType string `json:"subType"`+ Children []*BlockPath `json:"children"`+ HasChildren bool `json:"hasChildren,omitempty"`+}++type BlockBreadcrumbChildren struct {+ Items []*BlockPath `json:"items"`+ HasMore bool `json:"hasMore"`}func BuildBlockBreadcrumb(id string, excludeTypes []string) (ret []*BlockPath, err error) {@@ -556,6 +562,140 @@ func BuildBlockBreadcrumbInBox(id string, excludeTypes []string, boxID string) (return}+func GetBlockBreadcrumbChildren(id string, excludeTypes []string, offset, limit int) (ret *BlockBreadcrumbChildren, err error) {+ return GetBlockBreadcrumbChildrenInBox(id, excludeTypes, offset, limit, "")+}++func GetBlockBreadcrumbChildrenInBox(id string, excludeTypes []string, offset, limit int, boxID string) (ret *BlockBreadcrumbChildren, err error) {+ ret = &BlockBreadcrumbChildren{Items: []*BlockPath{}}+ if offset < 0 {+ offset = 0+ }+ if limit < 1 {+ limit = 64+ } else if 256 < limit {+ limit = 256+ }++ tree, err := loadTreeByBlockIDInBox(id, boxID)+ if nil == tree {+ err = nil+ return+ }+ node := treenode.GetNodeInTree(tree, id)+ if nil == node {+ return+ }++ index := 0+ walkBlockBreadcrumbChildren(node, func(child *ast.Node) bool {+ if index < offset {+ index+++ return true+ }+ if limit <= len(ret.Items) {+ ret.HasMore = true+ return false+ }++ item := buildBlockBreadcrumbChild(child, excludeTypes)+ item.HasChildren = hasBlockBreadcrumbChildren(child)+ ret.Items = append(ret.Items, item)+ index+++ return true+ })+ return+}++func walkBlockBreadcrumbChildren(node *ast.Node, walker func(child *ast.Node) bool) {+ if nil == node {+ return+ }++ if ast.NodeHeading == node.Type {+ headingLevels := []int{node.HeadingLevel}+ for child := node.Next; nil != child; child = child.Next {+ if !child.IsBlock() {+ continue+ }+ if ast.NodeHeading == child.Type {+ if child.HeadingLevel <= node.HeadingLevel {+ return+ }+ for 1 < len(headingLevels) && headingLevels[len(headingLevels)-1] >= child.HeadingLevel {+ headingLevels = headingLevels[:len(headingLevels)-1]+ }+ if 1 == len(headingLevels) && !walker(child) {+ return+ }+ headingLevels = append(headingLevels, child.HeadingLevel)+ } else if 1 == len(headingLevels) && !walker(child) {+ return+ }+ }+ return+ }++ if ast.NodeDocument != node.Type && !node.IsContainerBlock() {+ return+ }++ var headingLevels []int+ for child := node.FirstChild; nil != child; child = child.Next {+ if !child.IsBlock() {+ continue+ }+ if ast.NodeHeading == child.Type {+ for 0 < len(headingLevels) && headingLevels[len(headingLevels)-1] >= child.HeadingLevel {+ headingLevels = headingLevels[:len(headingLevels)-1]+ }+ if 0 == len(headingLevels) && !walker(child) {+ return+ }+ headingLevels = append(headingLevels, child.HeadingLevel)+ } else if 0 == len(headingLevels) && !walker(child) {+ return+ }+ }+}++func hasBlockBreadcrumbChildren(node *ast.Node) (ret bool) {+ walkBlockBreadcrumbChildren(node, func(child *ast.Node) bool {+ ret = true+ return false+ })+ return+}++func buildBlockBreadcrumbChild(node *ast.Node, excludeTypes []string) (ret *BlockPath) {+ maxNameLen := 1024+ fc := treenode.FirstLeafBlock(node)+ name := node.IALAttr("name")+ if ast.NodeAttributeView == node.Type {+ name, _ = av.GetAttributeViewName(node.AttributeViewID)+ } else if "" == name {+ if ast.NodeListItem == node.Type || ast.NodeList == node.Type || ast.NodeSuperBlock == node.Type ||+ ast.NodeBlockquote == node.Type || ast.NodeCallout == node.Type {+ name = gulu.Str.SubStr(renderBlockText(fc, excludeTypes, true), maxNameLen)+ } else {+ name = gulu.Str.SubStr(renderBlockText(node, excludeTypes, true), maxNameLen)+ }+ }+ if ast.NodeListItem == node.Type && "" == name {+ name = gulu.Str.SubStr(renderBlockText(fc, excludeTypes, true), maxNameLen)+ }++ name = strings.ReplaceAll(name, editor.Caret, "")+ name = util.UnescapeHTML(name)+ name = util.EscapeHTML(name)+ return &BlockPath{+ ID: node.ID,+ Name: name,+ Type: node.Type.String(),+ SubType: treenode.SubTypeAbbr(node),+ }+}+func buildBlockBreadcrumb(node *ast.Node, excludeTypes []string, isEmbedBlock bool, headingMode ...int) (ret []*BlockPath) {ret = []*BlockPath{}if nil == node {diff --git a/kernel/model/blockinfo_test.go b/kernel/model/blockinfo_test.gonew file mode 100644index 0000000000..75b683426c--- /dev/null+++ b/kernel/model/blockinfo_test.go@@ -0,0 +1,69 @@+package model++import (+ "reflect"+ "testing"++ "github.com/88250/lute/ast"+)++func TestWalkBlockBreadcrumbChildren(t *testing.T) {+ doc := &ast.Node{Type: ast.NodeDocument, ID: "doc"}+ paragraphBeforeHeading := &ast.Node{Type: ast.NodeParagraph, ID: "p0"}+ heading1 := &ast.Node{Type: ast.NodeHeading, ID: "h1", HeadingLevel: 1}+ paragraph1 := &ast.Node{Type: ast.NodeParagraph, ID: "p1"}+ heading3 := &ast.Node{Type: ast.NodeHeading, ID: "h3", HeadingLevel: 3}+ paragraph2 := &ast.Node{Type: ast.NodeParagraph, ID: "p2"}+ heading2 := &ast.Node{Type: ast.NodeHeading, ID: "h2", HeadingLevel: 2}+ paragraph3 := &ast.Node{Type: ast.NodeParagraph, ID: "p3"}+ heading1Sibling := &ast.Node{Type: ast.NodeHeading, ID: "h1-sibling", HeadingLevel: 1}+ paragraph4 := &ast.Node{Type: ast.NodeParagraph, ID: "p4"}+ for _, node := range []*ast.Node{+ paragraphBeforeHeading,+ heading1,+ paragraph1,+ heading3,+ paragraph2,+ heading2,+ paragraph3,+ heading1Sibling,+ paragraph4,+ } {+ doc.AppendChild(node)+ }++ assertBlockBreadcrumbChildIDs(t, doc, []string{"p0", "h1", "h1-sibling"})+ assertBlockBreadcrumbChildIDs(t, heading1, []string{"p1", "h3", "h2"})+ assertBlockBreadcrumbChildIDs(t, heading3, []string{"p2"})+ assertBlockBreadcrumbChildIDs(t, heading2, []string{"p3"})+ assertBlockBreadcrumbChildIDs(t, heading1Sibling, []string{"p4"})+ assertBlockBreadcrumbChildIDs(t, paragraph1, []string{})+}++func TestWalkBlockBreadcrumbContainerChildren(t *testing.T) {+ list := &ast.Node{Type: ast.NodeList, ID: "list"}+ item1 := &ast.Node{Type: ast.NodeListItem, ID: "item1"}+ item2 := &ast.Node{Type: ast.NodeListItem, ID: "item2"}+ list.AppendChild(item1)+ list.AppendChild(item2)++ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}+ nestedList := &ast.Node{Type: ast.NodeList, ID: "nested-list"}+ item1.AppendChild(paragraph)+ item1.AppendChild(nestedList)++ assertBlockBreadcrumbChildIDs(t, list, []string{"item1", "item2"})+ assertBlockBreadcrumbChildIDs(t, item1, []string{"paragraph", "nested-list"})+}++func assertBlockBreadcrumbChildIDs(t *testing.T, node *ast.Node, expected []string) {+ t.Helper()+ actual := []string{}+ walkBlockBreadcrumbChildren(node, func(child *ast.Node) bool {+ actual = append(actual, child.ID)+ return true+ })+ if !reflect.DeepEqual(expected, actual) {+ t.Fatalf("unexpected breadcrumb children: expected %v, got %v", expected, actual)+ }+}