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 fold indicators for headings without child blocks https://github.com/siyuan-note/siyuan/issues/19878
Daniel4adc5bebd33a
diff --git a/app/src/assets/scss/protyle/_wysiwyg.scss b/app/src/assets/scss/protyle/_wysiwyg.scssindex 03213de87e..d7398c1636 100644--- a/app/src/assets/scss/protyle/_wysiwyg.scss+++ b/app/src/assets/scss/protyle/_wysiwyg.scss@@ -813,6 +813,10 @@left: -30px;}+ div[fold="1"][data-type="NodeHeading"][data-heading-empty="true"]::before {+ display: none;+ }+[data-node-id][fold="1"]:not(.li):not([data-type="NodeHeading"]) {@include mixin.text-clamp(1);opacity: .38;diff --git a/app/src/protyle/util/clear.ts b/app/src/protyle/util/clear.tsindex 6b265ed580..29f7dda163 100644--- a/app/src/protyle/util/clear.ts+++ b/app/src/protyle/util/clear.ts@@ -19,7 +19,7 @@ const clearViewState = (element: Element) => {const attributes = ["data-view-fold-source", "data-view-fold-hidden-source", "data-view-fold","data-view-fold-default", "data-view-fold-hidden", "data-view-heading-owner", "data-view-heading-loaded","data-backlink-reference", "data-backlink-reference-list", "data-backlink-hide-reference",- "data-backlink-task-focus"];+ "data-backlink-task-focus", "data-heading-empty"];const elements = [element, ...Array.from(element.querySelectorAll(attributes.map(attribute => {return `[${attribute}]`;}).join(", ")))];diff --git a/app/src/protyle/util/headingFoldIndicator.test.ts b/app/src/protyle/util/headingFoldIndicator.test.tsnew file mode 100644index 0000000000..9325cdef84--- /dev/null+++ b/app/src/protyle/util/headingFoldIndicator.test.ts@@ -0,0 +1,138 @@+import * as assert from "node:assert/strict";+import {afterEach, describe, it} from "node:test";+import {bindHeadingFoldIndicators, refreshHeadingFoldIndicators} from "./headingFoldIndicator";++class Heading {+ attributes = new Map<string, string>();+ constructor(id: string) {+ this.attributes.set("data-node-id", id);+ this.attributes.set("fold", "1");+ }+ getAttribute(name: string) { return this.attributes.get(name) ?? null; }+ setAttribute(name: string, value: string) { this.attributes.set(name, value); }+ removeAttribute(name: string) { this.attributes.delete(name); }+ hasAttribute(name: string) { return this.attributes.has(name); }+ querySelector(): Element | null { return null; }+}++const originalGlobals = ["window", "MutationObserver", "Element"].map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)] as const);+afterEach(() => {+ originalGlobals.forEach(([key, descriptor]) => {+ if (descriptor) {+ Object.defineProperty(globalThis, key, descriptor);+ } else {+ Reflect.deleteProperty(globalThis, key);+ }+ });+});++const fixture = () => {+ const timers = new Map<number, () => void>();+ let timerID = 0;+ let onMutation: (records: any[]) => void;+ let disconnected = false;+ Object.assign(globalThis, {+ Element: Heading,+ window: {+ setTimeout: (callback: () => void) => { timers.set(++timerID, callback); return timerID; },+ clearTimeout: (id: number) => timers.delete(id),+ },+ MutationObserver: class {+ constructor(callback: typeof onMutation) { onMutation = callback; }+ observe() { /* 记录回调以模拟块结构变化。 */ }+ disconnect() { disconnected = true; }+ },+ });+ const headings = [new Heading("empty"), new Heading("full"), new Heading("empty")];+ const root = {+ isConnected: true,+ querySelectorAll: () => headings.filter(heading => heading.getAttribute("fold") === "1"),+ contains: (heading: Heading) => headings.includes(heading),+ };+ const protyle = {block: {rootID: "doc"}, notebookId: "notebook"} as IProtyle;+ const requests: {ids: string[], notebook: string, done: (info: any) => void}[] = [];+ const dispose = bindHeadingFoldIndicators(protyle, root as unknown as HTMLElement, (ids, notebook, done) => {+ requests.push({ids, notebook, done});+ });+ const flush = () => {+ const callbacks = Array.from(timers.values());+ timers.clear();+ callbacks.forEach(callback => callback());+ };+ return {headings, root, protyle, requests, dispose, flush, mutate: (records: any[]) => onMutation(records),+ disconnected: () => disconnected};+};++describe("heading fold indicators", () => {+ it("uses authoritative children instead of the visible sibling layout and preserves folding", () => {+ const f = fixture();+ f.flush();+ assert.deepEqual(f.requests[0].ids, ["empty", "full"]);+ assert.equal(f.requests[0].notebook, "notebook");+ f.requests[0].done({empty: {headingChildren: false}, full: {headingChildren: true}});+ assert.equal(f.headings[0].getAttribute("data-heading-empty"), "true");+ assert.equal(f.headings[2].getAttribute("data-heading-empty"), "true");+ assert.equal(f.headings[1].getAttribute("data-heading-empty"), null);+ assert.ok(f.headings.every(heading => heading.getAttribute("fold") === "1"));+ f.dispose();+ });++ it("refreshes after transactions and removes the empty marker when children are added", () => {+ const f = fixture();+ f.flush();+ f.requests[0].done({empty: {headingChildren: false}});+ refreshHeadingFoldIndicators(f.protyle);+ refreshHeadingFoldIndicators(f.protyle);+ f.flush();+ assert.equal(f.requests.length, 2);+ f.requests[1].done({empty: {headingChildren: true}});+ assert.equal(f.headings[0].getAttribute("data-heading-empty"), null);+ f.dispose();+ });++ it("ignores obsolete responses, replaced headings and a changed document", () => {+ const f = fixture();+ f.flush();+ refreshHeadingFoldIndicators(f.protyle);+ f.requests[0].done({empty: {headingChildren: false}});+ assert.equal(f.headings[0].getAttribute("data-heading-empty"), null);+ f.flush();+ const removed = f.headings.shift();+ f.protyle.block.rootID = "other";+ f.requests[1].done({empty: {headingChildren: false}});+ assert.equal(removed.getAttribute("data-heading-empty"), null);+ assert.equal(f.headings[1].getAttribute("data-heading-empty"), null);+ f.dispose();+ });++ it("does not infer emptiness from failures, missing fields or unfolded headings", () => {+ const f = fixture();+ f.flush();+ f.requests[0].done(null);+ assert.equal(f.headings[0].getAttribute("data-heading-empty"), null);+ f.headings[0].setAttribute("data-heading-empty", "true");+ f.headings[1].removeAttribute("fold");+ f.requests[0].done({empty: {}, full: {headingChildren: false}});+ assert.equal(f.headings[0].getAttribute("data-heading-empty"), null);+ assert.equal(f.headings[1].getAttribute("data-heading-empty"), null);+ f.dispose();+ });++ it("observes block changes, skips inline changes, and disposes pending work", () => {+ const f = fixture();+ f.flush();+ f.mutate([{type: "childList", addedNodes: [{}], removedNodes: []}]);+ f.flush();+ assert.equal(f.requests.length, 1);+ f.mutate([{type: "childList", addedNodes: [new Heading("new")], removedNodes: []}]);+ f.flush();+ assert.equal(f.requests.length, 2);+ f.mutate([{type: "attributes"}]);+ f.dispose();+ f.flush();+ f.requests[1].done({empty: {headingChildren: false}});+ assert.equal(f.requests.length, 2);+ assert.equal(f.headings[0].getAttribute("data-heading-empty"), null);+ assert.equal(f.disconnected(), true);+ });+});diff --git a/app/src/protyle/util/headingFoldIndicator.ts b/app/src/protyle/util/headingFoldIndicator.tsnew file mode 100644index 0000000000..30c3cb39b5--- /dev/null+++ b/app/src/protyle/util/headingFoldIndicator.ts@@ -0,0 +1,73 @@+type HeadingInfo = {headingChildren?: boolean};+type RequestHeadingInfo = (ids: string[], notebook: string,+ done: (info: Record<string, HeadingInfo | null> | null) => void) => void;++const refreshers = new WeakMap<IProtyle, () => void>();++export const refreshHeadingFoldIndicators = (protyle: IProtyle) => {+ refreshers.get(protyle)?.();+};++// 只查询折叠标题,使用内核完整树的结果,避免将分页和折叠省略的内容误判为空。+export const bindHeadingFoldIndicators = (protyle: IProtyle, root: HTMLElement, request: RequestHeadingInfo) => {+ let timer: number;+ let version = 0;+ let disposed = false;+ const refresh = () => {+ const currentVersion = ++version;+ window.clearTimeout(timer);+ timer = window.setTimeout(() => {+ if (disposed || !root.isConnected) {+ return;+ }+ const rootID = protyle.block.rootID;+ const notebook = protyle.notebookId;+ const headings = Array.from(root.querySelectorAll('[data-type="NodeHeading"][fold="1"]'));+ const ids = Array.from(new Set(headings.map(heading => heading.getAttribute("data-node-id")).filter(Boolean)));+ if (ids.length === 0) {+ return;+ }+ request(ids, notebook, info => {+ if (!info || disposed || version !== currentVersion || !root.isConnected ||+ protyle.block.rootID !== rootID || protyle.notebookId !== notebook) {+ return;+ }+ headings.forEach(heading => {+ if (!root.contains(heading) || heading.getAttribute("fold") !== "1") {+ return;+ }+ if (info[heading.getAttribute("data-node-id")]?.headingChildren === false) {+ heading.setAttribute("data-heading-empty", "true");+ } else {+ heading.removeAttribute("data-heading-empty");+ }+ });+ });+ }, 150);+ };+ const observer = new MutationObserver(records => {+ // 行内输入和标记自身的更新不会重新查询;块结构及折叠状态变化合并刷新。+ if (records.some(record => record.type === "attributes" ||+ [...Array.from(record.addedNodes), ...Array.from(record.removedNodes)].some(node => {+ return node instanceof Element &&+ (node.hasAttribute("data-node-id") || node.querySelector("[data-node-id]"));+ }))) {+ refresh();+ }+ });+ observer.observe(root, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ["fold", "data-subtype", "data-node-id"],+ });+ refreshers.set(protyle, refresh);+ refresh();+ return () => {+ disposed = true;+ version++;+ window.clearTimeout(timer);+ observer.disconnect();+ refreshers.delete(protyle);+ };+};diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex ba068dcd92..9a3584326c 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -190,6 +190,7 @@ import {chartRender} from "../render/chartRender";import {reloadProtyle} from "../util/reload";import {nbsp2space, removeZWJ} from "../util/normalizeText";import {setFold, toggleListFold} from "../util/blockFold";+import {bindHeadingFoldIndicators} from "../util/headingFoldIndicator";import {BlockPanel} from "../../block/Panel";import {isEncryptedBox, parseSiYuanUriInfo} from "../../util/pathName";import {processSiYuanUri} from "../../util/uri";@@ -403,6 +404,7 @@ export class WYSIWYG {private largeListVirtualizer?: LargeListVirtualizer;private disposeSpellcheckFocus?: () => void;private disposeEmbedToolbarVisibility?: () => void;+ private disposeHeadingFoldIndicators?: () => void;private scheduleInput(callback: () => void | Promise<void>, delay = 0, replace = true) {if (replace && this.inputTimeout) {@@ -554,6 +556,11 @@ export class WYSIWYG {if (protyle.options.action.includes(Constants.CB_GET_HISTORY)) {return;}+ this.disposeHeadingFoldIndicators = bindHeadingFoldIndicators(protyle, this.element, (ids, notebook, done) => {+ fetchPost("/api/block/getBlockTreeInfos", {ids, notebook}, response => {+ done(response.code === 0 ? response.data : null);+ });+ });if (!isMobile() && !protyle.options.backlinkData && !protyle.lite) {this.largeListVirtualizer = new LargeListVirtualizer(protyle.element, this.element, protyle.id);}@@ -562,6 +569,7 @@ export class WYSIWYG {}public destroy() {+ this.disposeHeadingFoldIndicators?.();this.disposeEmbedToolbarVisibility?.();this.disposeSpellcheckFocus?.();this.largeListVirtualizer?.destroy();diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 1859c98a4c..ef8dc51daf 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -42,6 +42,7 @@ import {resize} from "../util/resize";import {scrollCenter} from "../../util/highlightById";import {consumeGutterFoldRestore} from "../ui/gutterVisibility";import {setFold} from "../util/blockFold";+import {refreshHeadingFoldIndicators} from "../util/headingFoldIndicator";import {queueTransaction, queueTransactionBatch} from "../util/transactionQueue";import {cleanHeadingNumberHTML,@@ -652,6 +653,7 @@ const promiseTransaction = (options: {}});queueHeadingNumberRefresh(protyle, responseTransaction.doOperations);+ refreshHeadingFoldIndicators(protyle);void applyViewFoldStates(protyle);options.callback?.();},@@ -1502,6 +1504,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd});});queueHeadingNumberRefresh(protyle, operations);+ refreshHeadingFoldIndicators(protyle);if (shouldReloadForHeadingBatch(protyle.block.rootID, operations)) {reloadProtyle(protyle, false);}diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 73136e509b..f28fd12d7e 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -716,7 +716,7 @@ export type BlockStat = { "blockCount": number; "imageCount": number; "linkCountexport type BlockTransaction = { "doOperations": Array<BlockOperation | null> | null; "templateDocTreePlanID"?: string; "timestamp": number; "undoOperations": Array<BlockOperation | null> | null; };-export type BlockTreeInfo = { "id": string; "nextID": string; "nextType": string; "parentID": string; "parentType": string; "previousID": string; "previousType": string; "type": string; };+export type BlockTreeInfo = { "headingChildren"?: boolean; "id": string; "nextID": string; "nextType": string; "parentID": string; "parentType": string; "previousID": string; "previousType": string; "type": string; };export type BlocksKramdownRequestInput = { "id"?: string | null; "ids": Array<string>; "mode"?: string | null; "notebook"?: string | null; };diff --git a/kernel/api/contract_block_transaction_test.go b/kernel/api/contract_block_transaction_test.goindex 82488ef5ee..4bf140804d 100644--- a/kernel/api/contract_block_transaction_test.go+++ b/kernel/api/contract_block_transaction_test.go@@ -107,6 +107,31 @@ func TestAPIContractHeadingTransactions(t *testing.T) {}treenode.UpsertBlockTree(tree)engine := gin.New()+ engine.POST("/api/block/getBlockTreeInfos", getBlockTreeInfos)+ infoRecorder := httptest.NewRecorder()+ infoBody, _ := json.Marshal(map[string]any{"ids": []string{heading.ID, child.ID, paragraphID}})+ engine.ServeHTTP(infoRecorder, httptest.NewRequest("POST", "/api/block/getBlockTreeInfos", strings.NewReader(string(infoBody))))+ requireAPIContract(t, "POST", "/api/block/getBlockTreeInfos", infoRecorder)+ var infoResponse struct {+ Code int `json:"code"`+ Data map[string]*apicontract.BlockTreeInfo `json:"data"`+ }+ if err := json.Unmarshal(infoRecorder.Body.Bytes(), &infoResponse); err != nil {+ t.Fatal(err)+ }+ if infoResponse.Code != 0 || infoResponse.Data[heading.ID] == nil || infoResponse.Data[child.ID] == nil ||+ infoResponse.Data[paragraphID] == nil {+ t.Fatalf("missing block tree info: %s", infoRecorder.Body.String())+ }+ if children := infoResponse.Data[heading.ID].HeadingChildren; children == nil || !*children {+ t.Fatal("parent heading must have children")+ }+ if children := infoResponse.Data[child.ID].HeadingChildren; children == nil || *children {+ t.Fatal("empty heading must explicitly report false")+ }+ if infoResponse.Data[paragraphID].HeadingChildren != nil {+ t.Fatal("non-heading must omit heading children")+ }engine.POST("/api/block/foldBlock", foldBlock)engine.POST("/api/block/unfoldBlock", unfoldBlock)engine.POST("/api/block/moveBlock", moveBlock)diff --git a/kernel/apicontract/block_tree.go b/kernel/apicontract/block_tree.goindex cee74c006d..168021efd9 100644--- a/kernel/apicontract/block_tree.go+++ b/kernel/apicontract/block_tree.go@@ -1,14 +1,17 @@package apicontracttype BlockTreeInfo struct {- ID string `json:"id"`- Type string `json:"type"`- ParentID string `json:"parentID"`- ParentType string `json:"parentType"`- PreviousID string `json:"previousID"`- PreviousType string `json:"previousType"`- NextID string `json:"nextID"`- NextType string `json:"nextType"`+ // HeadingChildren 仅对标题返回,表示完整文档同一容器内是否存在下辖块;空段落也算下辖块。+ // 此字段不受折叠状态、分页或当前视图影响;非标题省略,旧客户端可忽略。+ HeadingChildren *bool `json:"headingChildren,omitempty"`+ ID string `json:"id"`+ Type string `json:"type"`+ ParentID string `json:"parentID"`+ ParentType string `json:"parentType"`+ PreviousID string `json:"previousID"`+ PreviousType string `json:"previousType"`+ NextID string `json:"nextID"`+ NextType string `json:"nextType"`}type BlockPath struct {diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 4553df80c2..529c50abf0 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -18766,6 +18766,9 @@"BlockTreeInfo": {"type": "object","properties": {+ "headingChildren": {+ "type": "boolean"+ },"id": {"type": "string"},diff --git a/kernel/model/block.go b/kernel/model/block.goindex c71fa918fb..1e8b81f09d 100644--- a/kernel/model/block.go+++ b/kernel/model/block.go@@ -387,14 +387,15 @@ func hasSurvivingAttributeViewBlock(group *blockRefCheckGroup, boundAVIDs, avBlo}type BlockTreeInfo struct {- ID string `json:"id"`- Type string `json:"type"`- ParentID string `json:"parentID"`- ParentType string `json:"parentType"`- PreviousID string `json:"previousID"`- PreviousType string `json:"previousType"`- NextID string `json:"nextID"`- NextType string `json:"nextType"`+ HeadingChildren *bool `json:"headingChildren,omitempty"`+ ID string `json:"id"`+ Type string `json:"type"`+ ParentID string `json:"parentID"`+ ParentType string `json:"parentType"`+ PreviousID string `json:"previousID"`+ PreviousType string `json:"previousType"`+ NextID string `json:"nextID"`+ NextType string `json:"nextType"`}func GetBlockTreeInfos(ids []string) (ret map[string]*BlockTreeInfo) {@@ -404,18 +405,38 @@ func GetBlockTreeInfos(ids []string) (ret map[string]*BlockTreeInfo) {// GetBlockTreeInfosInBox 获取指定笔记本内的块树信息。空 box 仅查询普通全局库。func GetBlockTreeInfosInBox(ids []string, boxID string) (ret map[string]*BlockTreeInfo) {ret = map[string]*BlockTreeInfo{}+ // 同一批查询中的文档只加载和遍历一次,避免多个折叠标题重复读取整棵树。+ nodesByRoot := map[string]map[string]*ast.Node{}for _, id := range ids {- tree := loadTreeForBlockDOM(id, boxID)- if nil == tree {- continue+ var nodes map[string]*ast.Node+ if bt := treenode.GetBlockTreeInBox(id, boxID); nil != bt {+ nodes = nodesByRoot[bt.RootID]}- node := treenode.GetNodeInTree(tree, id)+ if nil == nodes {+ tree := loadTreeForBlockDOM(id, boxID)+ if nil == tree {+ continue+ }+ nodes = map[string]*ast.Node{}+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && "" != node.ID {+ nodes[node.ID] = node+ }+ return ast.WalkContinue+ })+ nodesByRoot[tree.Root.ID] = nodes+ }+ node := nodes[id]if nil == node {ret[id] = &BlockTreeInfo{ID: id}continue}bti := &BlockTreeInfo{ID: id, Type: node.Type.String()}+ if ast.NodeHeading == node.Type {+ hasChildren := treenode.HasHeadingChildren(node)+ bti.HeadingChildren = &hasChildren+ }ret[id] = btiparent := treenode.ParentBlock(node)if nil != parent {diff --git a/kernel/treenode/heading.go b/kernel/treenode/heading.goindex dd5412e875..de840df261 100644--- a/kernel/treenode/heading.go+++ b/kernel/treenode/heading.go@@ -210,6 +210,23 @@ func GetParentFoldedHeading(node *ast.Node) (parentFoldedHeading *ast.Node) {return}+// HasHeadingChildren 判断标题在同一容器内是否有下辖块,不展开折叠内容或扫描整个标题范围。+func HasHeadingChildren(heading *ast.Node) bool {+ if nil == heading || ast.NodeHeading != heading.Type {+ return false+ }+ for node := heading.Next; nil != node; node = node.Next {+ if ast.NodeSuperBlockCloseMarker == node.Type ||+ (ast.NodeHeading == node.Type && node.HeadingLevel <= heading.HeadingLevel) {+ return false+ }+ if node.IsBlock() && ast.NodeKramdownBlockIAL != node.Type {+ return true+ }+ }+ return false+}+func HeadingChildren(heading *ast.Node) (ret []*ast.Node) {start := heading.Nextif nil == start {diff --git a/kernel/treenode/heading_children_test.go b/kernel/treenode/heading_children_test.gonew file mode 100644index 0000000000..685177f449--- /dev/null+++ b/kernel/treenode/heading_children_test.go@@ -0,0 +1,45 @@+package treenode++import (+ "testing"++ "github.com/88250/lute/ast"+)++func TestHasHeadingChildren(t *testing.T) {+ for _, test := range []struct {+ name string+ next []*ast.Node+ want bool+ }{+ {"end", nil, false},+ {"same level", []*ast.Node{{Type: ast.NodeHeading, HeadingLevel: 2}}, false},+ {"higher level", []*ast.Node{{Type: ast.NodeHeading, HeadingLevel: 1}}, false},+ {"lower level", []*ast.Node{{Type: ast.NodeHeading, HeadingLevel: 3}}, true},+ {"empty paragraph", []*ast.Node{{Type: ast.NodeParagraph}}, true},+ {"IAL only", []*ast.Node{{Type: ast.NodeKramdownBlockIAL}}, false},+ {"IAL and paragraph", []*ast.Node{{Type: ast.NodeKramdownBlockIAL}, {Type: ast.NodeParagraph}}, true},+ {"super block end", []*ast.Node{{Type: ast.NodeSuperBlockCloseMarker}}, false},+ } {+ t.Run(test.name, func(t *testing.T) {+ parent := &ast.Node{Type: ast.NodeBlockquote}+ heading := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 2}+ parent.AppendChild(heading)+ for _, next := range test.next {+ parent.AppendChild(next)+ }+ root := &ast.Node{Type: ast.NodeDocument}+ root.AppendChild(parent)+ root.AppendChild(&ast.Node{Type: ast.NodeParagraph})+ for _, folded := range []bool{false, true} {+ SetSelfFolded(heading, folded)+ if got := HasHeadingChildren(heading); got != test.want {+ t.Fatalf("folded=%v: got %v, want %v", folded, got, test.want)+ }+ }+ })+ }+ if HasHeadingChildren(nil) || HasHeadingChildren(&ast.Node{Type: ast.NodeParagraph}) {+ t.Fatal("only headings have heading children")+ }+}