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: Improve heading folding to preserve descendant states https://github.com/siyuan-note/siyuan/issues/18218
Danielcc846ad75d5a
diff --git a/app/src/layout/dock/Outline.ts b/app/src/layout/dock/Outline.tsindex b35c69a414..c1b8db25ef 100644--- a/app/src/layout/dock/Outline.ts+++ b/app/src/layout/dock/Outline.ts@@ -1183,7 +1183,7 @@ export class Outline extends Model {const data = this.getProtyleAndBlockElement(element);fetchPost("/api/block/getHeadingChildrenDOM", {id,- removeFoldAttr: data.blockElement.getAttribute("fold") !== "1"+ removeFoldAttr: false}, (response) => {if (isInAndroid()) {window.JSAndroid.writeHTMLClipboard(data.protyle.lute.BlockDOM2StdMd(response.data).trimEnd(), response.data + Constants.ZWSP);@@ -1206,7 +1206,7 @@ export class Outline extends Model {const data = this.getProtyleAndBlockElement(element);fetchPost("/api/block/getHeadingChildrenDOM", {id,- removeFoldAttr: data.blockElement.getAttribute("fold") !== "1"+ removeFoldAttr: false}, (response) => {if (isInAndroid()) {window.JSAndroid.writeHTMLClipboard(data.protyle.lute.BlockDOM2StdMd(response.data).trimEnd(), response.data + Constants.ZWSP);diff --git a/app/src/mobile/dock/MobileOutline.ts b/app/src/mobile/dock/MobileOutline.tsindex ec3185a0f5..0d614a05a8 100644--- a/app/src/mobile/dock/MobileOutline.ts+++ b/app/src/mobile/dock/MobileOutline.ts@@ -1057,7 +1057,7 @@ export class MobileOutline extends Model {const data = this.getProtyleAndBlockElement(element);fetchPost("/api/block/getHeadingChildrenDOM", {id,- removeFoldAttr: data.blockElement.getAttribute("fold") !== "1"+ removeFoldAttr: false}, (response) => {if (isInAndroid()) {window.JSAndroid.writeHTMLClipboard(data.protyle.lute.BlockDOM2StdMd(response.data).trimEnd(), response.data + Constants.ZWSP);@@ -1080,7 +1080,7 @@ export class MobileOutline extends Model {const data = this.getProtyleAndBlockElement(element);fetchPost("/api/block/getHeadingChildrenDOM", {id,- removeFoldAttr: data.blockElement.getAttribute("fold") !== "1"+ removeFoldAttr: false}, (response) => {if (isInAndroid()) {window.JSAndroid.writeHTMLClipboard(data.protyle.lute.BlockDOM2StdMd(response.data).trimEnd(), response.data + Constants.ZWSP);diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex c60746bff3..be23c1bfb4 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -2134,7 +2134,7 @@ export class Gutter {click() {fetchPost("/api/block/getHeadingChildrenDOM", {id,- removeFoldAttr: nodeElement.getAttribute("fold") !== "1"+ removeFoldAttr: false}, (response) => {if (isInAndroid()) {window.JSAndroid.writeSiYuanHTMLClipboard(protyle.lute.BlockDOM2StdMd(response.data).trimEnd(), protyle.lute.BlockDOM2HTML(response.data).trimEnd(), response.data + Constants.ZWSP);@@ -2154,7 +2154,7 @@ export class Gutter {click() {fetchPost("/api/block/getHeadingChildrenDOM", {id,- removeFoldAttr: nodeElement.getAttribute("fold") !== "1"+ removeFoldAttr: false}, (response) => {if (isInAndroid()) {window.JSAndroid.writeHTMLClipboard(protyle.lute.BlockDOM2StdMd(response.data).trimEnd(), response.data + Constants.ZWSP);@@ -2850,8 +2850,8 @@ export class Gutter {icon: "iconListTree",label: window.siyuan.languages.foldRecursive,accelerator: window.siyuan.config.keymap.editor.general.foldRecursive?.custom,- click() {- foldBlocksRecursively(protyle, [nodeElement]);+ async click() {+ await foldBlocksRecursively(protyle, [nodeElement]);focusBlock(nodeElement);}}).element);diff --git a/app/src/protyle/util/blockFold.ts b/app/src/protyle/util/blockFold.tsindex 6b6e1085b5..a3aa31817c 100644--- a/app/src/protyle/util/blockFold.ts+++ b/app/src/protyle/util/blockFold.ts@@ -7,6 +7,34 @@ import {scrollCenter} from "../../util/highlightById";import {clearSelect} from "./clear";import {removeFoldHeading} from "./heading";import {getSbChildBlockCount, getTopAloneElement} from "../wysiwyg/getBlock";+import {fetchSyncPost} from "../../util/fetch";++const applyFoldState = (protyle: IProtyle, nodeElement: Element, folded: boolean) => {+ if (!folded) {+ nodeElement.removeAttribute("fold");+ // https://github.com/siyuan-note/siyuan/issues/4411+ nodeElement.querySelectorAll(".protyle-linenumber__rows").forEach((item: HTMLElement) => {+ lineNumberRender(item.parentElement);+ });+ return;+ }++ nodeElement.setAttribute("fold", "1");+ // 光标在子列表中,再次 focus 段尾的时候不会变 https://ld246.com/article/1647099132461+ if (getSelection().rangeCount > 0) {+ const range = getSelection().getRangeAt(0);+ const blockElement = hasClosestBlock(range.startContainer);+ if (blockElement && blockElement.getBoundingClientRect().width === 0) {+ // https://github.com/siyuan-note/siyuan/issues/5833+ focusBlock(nodeElement, undefined, false);+ }+ }+ clearSelect(["img", "av"], nodeElement);+ scrollCenter(protyle, nodeElement);+ if (nodeElement.getAttribute("data-type") === "NodeHeading") {+ removeFoldHeading(nodeElement);+ }+};export const setFold = (protyle: IProtyle, nodeElement: Element, isOpen?: boolean,isRemove?: boolean, addLoading = true, getOperations = false) => {@@ -24,27 +52,12 @@ export const setFold = (protyle: IProtyle, nodeElement: Element, isOpen?: booleaif (typeof isOpen === "boolean" && !isOpen) {return {fold: -1};}- nodeElement.removeAttribute("fold");- // https://github.com/siyuan-note/siyuan/issues/4411- nodeElement.querySelectorAll(".protyle-linenumber__rows").forEach((item: HTMLElement) => {- lineNumberRender(item.parentElement);- });+ applyFoldState(protyle, nodeElement, false);} else {if (typeof isOpen === "boolean" && isOpen) {return {fold: -1};}- nodeElement.setAttribute("fold", "1");- // 光标在子列表中,再次 focus 段尾的时候不会变 https://ld246.com/article/1647099132461- if (getSelection().rangeCount > 0) {- const range = getSelection().getRangeAt(0);- const blockElement = hasClosestBlock(range.startContainer);- if (blockElement && blockElement.getBoundingClientRect().width === 0) {- // https://github.com/siyuan-note/siyuan/issues/5833- focusBlock(nodeElement, undefined, false);- }- }- clearSelect(["img", "av"], nodeElement);- scrollCenter(protyle, nodeElement);+ applyFoldState(protyle, nodeElement, true);}const id = nodeElement.getAttribute("data-node-id");const doOperations: IOperation[] = [];@@ -72,7 +85,6 @@ export const setFold = (protyle: IProtyle, nodeElement: Element, isOpen?: booleaaction: "unfoldHeading",id});- removeFoldHeading(nodeElement);}} else {doOperations.push({@@ -102,51 +114,60 @@ const isFoldable = (el: Element) => {(type === "NodeSuperBlock" && getSbChildBlockCount(el) > 1);};-export const foldBlocksRecursively = (protyle: IProtyle, nodeElements: Element[]) => {- const result: Set<Element> = new Set();- nodeElements.forEach(element => {- if (isFoldable(element)) {- result.add(element);+const foldBlocksRecursively0 = async (protyle: IProtyle, nodeElements: Element[]) => {+ const candidates = new Map<string, {element: Element, order: number}>();+ let order = 0;+ const addCandidate = (element: Element) => {+ if (!isFoldable(element) ||+ (element.getAttribute("data-type") === "NodeHeading" &&+ element.parentElement?.getAttribute("data-type") === "NodeListItem")) {+ return;}- element.querySelectorAll("[data-type='NodeHeading'], .li, .bq, .sb, .callout").forEach(child => {- if (isFoldable(child)) {- // Skip headings inside list items to avoid "double dot" and gutter icon conflicts- if (child.getAttribute("data-type") === "NodeHeading" &&- child.parentElement?.getAttribute("data-type") === "NodeListItem") {- return;- }- result.add(child);- }- });- const type = element.getAttribute("data-type");- if (type === "NodeHeading") {- const nodeH = parseInt(element.getAttribute("data-subtype").substr(1));- let nextElement = element.nextElementSibling;- while (nextElement) {- const currentH = parseInt(nextElement.getAttribute("data-subtype")?.substr(1));- if (!nextElement.classList.contains("protyle-attr") && (isNaN(currentH) || currentH > nodeH)) {- if (isFoldable(nextElement)) {- result.add(nextElement);- }- nextElement.querySelectorAll("[data-type='NodeHeading'], .li, .bq, .sb, .callout").forEach(child => {- if (isFoldable(child)) {- // Skip headings inside list items to avoid "double dot" and gutter icon conflicts- if (child.getAttribute("data-type") === "NodeHeading" &&- child.parentElement?.getAttribute("data-type") === "NodeListItem") {- return;- }- result.add(child);- }- });- nextElement = nextElement.nextElementSibling;- } else {- break;- }- }+ const id = element.getAttribute("data-node-id");+ if (!id || candidates.has(id)) {+ return;+ }+ candidates.set(id, {element, order});+ order++;+ };+ const addScope = (scope: ParentNode) => {+ if (scope instanceof Element) {+ addCandidate(scope);+ }+ scope.querySelectorAll("[data-type='NodeHeading'], .li, .bq, .sb, .callout").forEach(addCandidate);+ };++ const scopes = await Promise.all(nodeElements.map(async (element) => {+ let fullHTML = "";+ if (element.getAttribute("data-type") === "NodeHeading") {+ const response = await fetchSyncPost("/api/block/getHeadingChildrenDOM", {+ id: element.getAttribute("data-node-id"),+ removeFoldAttr: false,+ });+ fullHTML = response.data;+ } else if (element.querySelector('[data-type="NodeHeading"][fold="1"]')) {+ const response = await fetchSyncPost("/api/block/getBlockDOM", {+ id: element.getAttribute("data-node-id"),+ notebook: protyle.notebookId,+ });+ fullHTML = response.data.dom;+ }+ return {element, fullHTML};+ }));+ scopes.forEach(({element, fullHTML}) => {+ if (fullHTML) {+ const template = document.createElement("template");+ template.innerHTML = fullHTML;+ addScope(template.content);+ } else {+ addScope(element);}});- const elementsToFold = Array.from(result);+ const elementsToFold = Array.from(candidates.values()).sort((a, b) => a.order - b.order).map((candidate) => {+ return protyle.wysiwyg.element.querySelector(`[data-node-id="${candidate.element.getAttribute("data-node-id")}"]`) ||+ candidate.element;+ });if (elementsToFold.length === 0) {return;}@@ -156,15 +177,9 @@ export const foldBlocksRecursively = (protyle: IProtyle, nodeElements: Element[]if (isFoldAll && nodeElements.length === 1 && nodeElements[0].getAttribute("fold") === "1") {isFoldAll = false;}- elementsToFold.sort((a, b) => {- const position = a.compareDocumentPosition(b);- if (position & Node.DOCUMENT_POSITION_FOLLOWING) {- return isFoldAll ? 1 : -1;- } else if (position & Node.DOCUMENT_POSITION_PRECEDING) {- return isFoldAll ? -1 : 1;- }- return 0;- });+ if (isFoldAll) {+ elementsToFold.reverse();+ }const doOperations: IOperation[] = [];const undoOperations: IOperation[] = [];@@ -173,17 +188,57 @@ export const foldBlocksRecursively = (protyle: IProtyle, nodeElements: Element[]if ((isFoldAll && hasFold) || (!isFoldAll && !hasFold)) {return;}- const ops = setFold(protyle, element, !isFoldAll, false, false, true);- if (ops.doOperations && ops.doOperations.length > 0) {- doOperations.push(...ops.doOperations);- undoOperations.push(...ops.undoOperations);+ const id = element.getAttribute("data-node-id");+ if (element.getAttribute("data-type") === "NodeHeading") {+ doOperations.push({+ action: isFoldAll ? "foldHeading" : "unfoldHeading",+ id,+ });+ undoOperations.push({+ action: isFoldAll ? "unfoldHeading" : "foldHeading",+ id,+ });+ } else {+ doOperations.push({+ action: "setAttrs",+ id,+ data: JSON.stringify({fold: isFoldAll ? "1" : ""}),+ });+ undoOperations.push({+ action: "setAttrs",+ id,+ data: JSON.stringify({fold: isFoldAll ? "" : "1"}),+ });+ }+ if (element.isConnected) {+ applyFoldState(protyle, element, isFoldAll);}});if (doOperations.length > 0) {transaction(protyle, doOperations, undoOperations);preventScroll(protyle);- scrollCenter(protyle, elementsToFold[0]);+ const scrollElement = elementsToFold.find((element) => element.isConnected);+ if (scrollElement) {+ scrollCenter(protyle, scrollElement);+ }+ }+};++const recursiveFoldingProtyles = new WeakSet<IProtyle>();++export const foldBlocksRecursively = async (protyle: IProtyle, nodeElements: Element[]) => {+ if (recursiveFoldingProtyles.has(protyle)) {+ return;+ }++ recursiveFoldingProtyles.add(protyle);+ try {+ await foldBlocksRecursively0(protyle, nodeElements);+ } catch (error) {+ console.error(error);+ } finally {+ recursiveFoldingProtyles.delete(protyle);}};diff --git a/app/src/protyle/util/insertHTML.ts b/app/src/protyle/util/insertHTML.tsindex 3ba41962a2..be1f3b6531 100644--- a/app/src/protyle/util/insertHTML.ts+++ b/app/src/protyle/util/insertHTML.ts@@ -22,6 +22,7 @@ import {fetchPost, fetchSyncPost} from "../../util/fetch";import {getTableRangeCells, isIncludeCell} from "./table";import {getFieldIdByCellElement, getRowHTML} from "../render/av/row";import {setFold} from "./blockFold";+import {removeFoldHeading} from "./heading";// 粘贴时临时插入的占位行标记,遍历结束后统一移除,避免污染虚拟滚动的 renderedStart/renderedEnd/spacer 状态const PLACEHOLDER_ROW_CLASS = "av__row--placeholder";@@ -31,6 +32,32 @@ const removePlaceholderRows = (blockElement: HTMLElement) => {blockElement.querySelectorAll("." + PLACEHOLDER_ROW_CLASS).forEach(item => item.remove());};+const markFoldHeadingChildren = (parent: ParentNode) => {+ const foldedHeadings: {id: string, level: number}[] = [];+ Array.from(parent.children).forEach(item => {+ if (!item.hasAttribute("data-node-id")) {+ return;+ }++ const isHeading = item.getAttribute("data-type") === "NodeHeading";+ const level = isHeading ? parseInt(item.getAttribute("data-subtype").substring(1)) : 7;+ if (isHeading) {+ while (foldedHeadings.length > 0 && foldedHeadings[foldedHeadings.length - 1].level >= level) {+ foldedHeadings.pop();+ }+ }+ if (foldedHeadings.length > 0) {+ item.setAttribute("parent-heading", foldedHeadings[0].id);+ }+ if (isHeading && item.getAttribute("fold") === "1") {+ foldedHeadings.push({+ id: item.getAttribute("data-node-id"),+ level,+ });+ }+ });+};+const genEmptyAVRow = (view: IAVTable, rowID: string): IAVRow => {return {id: rowID,@@ -671,6 +698,7 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,if (tempElement.content.firstChild.nodeType === 3 || (tempElement.content.firstChild.nodeType === 1 && tempElement.content.firstElementChild.tagName !== "DIV")) {tempElement.innerHTML = protyle.lute.SpinBlockDOM(tempElement.innerHTML);}+ markFoldHeadingChildren(tempElement.content);(insertBefore ? Array.from(tempElement.content.children) : Array.from(tempElement.content.children).reverse()).find((item) => {let addId = item.getAttribute("data-node-id");const hasParentHeading = item.getAttribute("parent-heading");@@ -714,6 +742,9 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,});}if (!hasParentHeading) {+ Array.from(item.querySelectorAll('[data-type="NodeHeading"][fold="1"]')).reverse().forEach(heading => {+ removeFoldHeading(heading);+ });const rendersElement = [];if (item.classList.contains("render-node") && item.getAttribute("data-type") === "NodeCodeBlock") {rendersElement.push(item);@@ -734,7 +765,7 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,blockElement.after(item);}}- if (!lastElement) {+ if (!lastElement && !hasParentHeading) {lastElement = item;}});diff --git a/app/src/protyle/wysiwyg/commonHotkey.ts b/app/src/protyle/wysiwyg/commonHotkey.tsindex b9e1a41b96..48147a4fab 100644--- a/app/src/protyle/wysiwyg/commonHotkey.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.ts@@ -342,13 +342,17 @@ export const duplicateBlock = async (nodeElements: Element[], protyle: IProtyle)});if (item.getAttribute("data-type") === "NodeHeading" && item.getAttribute("fold") === "1") {foldHeadingIds.push({oldId: item.getAttribute("data-node-id"), newId});- const responseHTML = await fetchSyncPost("/api/block/getHeadingChildrenDOM", {id: item.getAttribute("data-node-id")});+ const responseHTML = await fetchSyncPost("/api/block/getHeadingChildrenDOM", {+ id: item.getAttribute("data-node-id"),+ removeFoldAttr: false,+ });const foldElement = document.createElement("template");foldElement.innerHTML = responseHTML.data;Array.from(foldElement.content.children).reverse().forEach((childItem: HTMLElement, childIndex) => {if (childIndex === foldElement.content.children.length - 1) {return;}+ childItem.removeAttribute("parent-heading");childItem.querySelectorAll("[data-node-id]").forEach(subItem => {subItem.setAttribute("data-node-id", Lute.NewNodeID());clearBlockElement(subItem);diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex f11aa64585..df792373d2 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -91,6 +91,19 @@ const syncFoldAttr = (element: Element, operation: IOperation) => {});};+const getVisibleFoldHeadingHTML = (html: string) => {+ if (!html.includes('data-type="NodeHeading"') || !html.includes('fold="1"')) {+ return html;+ }++ const template = document.createElement("template");+ template.innerHTML = html;+ Array.from(template.content.querySelectorAll('[data-type="NodeHeading"][fold="1"]')).reverse().forEach(item => {+ removeFoldHeading(item);+ });+ return template.innerHTML;+};+// 用于执行操作,外加处理当前编辑器中块引用、嵌入块的更新const promiseTransaction = (options: {protyle: IProtyle,@@ -135,7 +148,7 @@ const promiseTransaction = (options: {return;}const tempElement = document.createElement("template");- tempElement.innerHTML = html;+ tempElement.innerHTML = getVisibleFoldHeadingHTML(html);tempElement.content.querySelectorAll(".protyle-wysiwyg--select").forEach(selectItem => {selectItem.classList.remove("protyle-wysiwyg--select");});@@ -148,7 +161,7 @@ const promiseTransaction = (options: {};const allTempElement = document.createElement("template");- allTempElement.innerHTML = operation.data;+ allTempElement.innerHTML = getVisibleFoldHeadingHTML(operation.data);updateElements.forEach((item) => {if ((currentEmbedElement && isInEmbedBlock(item, false) === currentEmbedElement) ||(range && (item === range.startContainer || item.contains(range.startContainer)))) {@@ -267,6 +280,10 @@ const promiseTransaction = (options: {return;}if (operation.action === "insert") {+ if (operation.context?.ignoreProcess === "true") {+ return;+ }+ const visibleData = getVisibleFoldHeadingHTML(operation.data);// 块已被本地 DOM 操作插入时仍需同步其他普通副本,并跳过当前副本避免重复// https://github.com/siyuan-note/siyuan/issues/17890const insertedElement = protyle.wysiwyg.element.querySelector(`[data-node-id="${operation.id}"]`);@@ -300,7 +317,7 @@ const promiseTransaction = (options: {!hasClosestByAttribute(item, "data-node-id", operation.id) &&// 嵌入块后不能插入!item.parentElement.classList.contains("protyle-wysiwyg__embed")) {- item.insertAdjacentHTML("afterend", operation.data);+ item.insertAdjacentHTML("afterend", visibleData);cursorElements.push(item.nextElementSibling);}});@@ -317,7 +334,7 @@ const promiseTransaction = (options: {(!range || !item.contains(range.startContainer)) &&!hasClosestByAttribute(item, "data-node-id", operation.id) &&!item.parentElement.classList.contains("protyle-wysiwyg__embed")) {- item.insertAdjacentHTML("beforebegin", operation.data);+ item.insertAdjacentHTML("beforebegin", visibleData);cursorElements.push(item.previousElementSibling);}});@@ -334,14 +351,14 @@ const promiseTransaction = (options: {// 列表特殊处理if (item.firstElementChild && item.firstElementChild.classList.contains("protyle-action") &&item.firstElementChild.nextElementSibling?.getAttribute("data-node-id") !== operation.id) {- item.firstElementChild.insertAdjacentHTML("afterend", operation.data);+ item.firstElementChild.insertAdjacentHTML("afterend", visibleData);cursorElements.push(item.firstElementChild.nextElementSibling);} else if (item.classList.contains("callout") &&item.querySelector("[data-node-id]")?.getAttribute("data-node-id") !== operation.id) {- item.querySelector(".callout-content").insertAdjacentHTML("afterbegin", operation.data);+ item.querySelector(".callout-content").insertAdjacentHTML("afterbegin", visibleData);cursorElements.push(item.querySelector("[data-node-id]"));} else if (item.firstElementChild.getAttribute("data-node-id") !== operation.id) {- item.insertAdjacentHTML("afterbegin", operation.data);+ item.insertAdjacentHTML("afterbegin", visibleData);cursorElements.push(item.firstElementChild);}}@@ -530,9 +547,10 @@ const updateBlock = (updateElements: Element[], protyle: IProtyle, operation: IOcontentScrollTop = protyle.contentElement.scrollTop;}}- item.insertAdjacentHTML("afterend",+ const data = item.getAttribute("data-subtype") === "echarts" ?// 图标撤销后无法渲染- item.getAttribute("data-subtype") === "echarts" ? protyle.lute.SpinBlockDOM(operation.data) : operation.data);+ protyle.lute.SpinBlockDOM(operation.data) : operation.data;+ item.insertAdjacentHTML("afterend", getVisibleFoldHeadingHTML(data));item = item.nextElementSibling;item.previousElementSibling.remove();@@ -579,13 +597,15 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndreturn;}if (operation.action === "unfoldHeading") {+ const visibleRetData = typeof operation.retData === "string" ?+ getVisibleFoldHeadingHTML(operation.retData) : "";protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {item.removeAttribute("fold");if (isUndo) {// kernel 权威撤销:retData 已由 doUnfoldHeading 填充,需要插入子块 HTML 恢复折叠的内容- if (operation.retData) {- removeUnfoldRepeatBlock(operation.retData, protyle);- item.insertAdjacentHTML("afterend", operation.retData);+ if (visibleRetData) {+ removeUnfoldRepeatBlock(visibleRetData, protyle);+ item.insertAdjacentHTML("afterend", visibleRetData);}return;}@@ -595,15 +615,15 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndblockRender(protyle, embedElement);return;}- if (operation.retData) {- removeUnfoldRepeatBlock(operation.retData, protyle);- item.insertAdjacentHTML("afterend", operation.retData);+ if (visibleRetData) {+ removeUnfoldRepeatBlock(visibleRetData, protyle);+ item.insertAdjacentHTML("afterend", visibleRetData);}if (operation.data === "remove") {item.remove();}});- if (operation.retData) {+ if (visibleRetData) {if (protyle.disabled) {disabledProtyle(protyle);}@@ -874,7 +894,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd}, (response) => {document.querySelectorAll(`.protyle-wysiwyg [data-node-id="${response.data.id}"]`).forEach(item => {if (item.getAttribute("data-protyle-id")) {- item.outerHTML = response.data.dom;+ item.outerHTML = getVisibleFoldHeadingHTML(response.data.dom);item.removeAttribute("data-protyle-id");}});@@ -992,18 +1012,19 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndif (operation.context?.ignoreProcess === "true") {return;}+ const visibleData = getVisibleFoldHeadingHTML(operation.data);const cursorElements = [];if (operation.previousID) {const previousElement = protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`);if (previousElement.length === 0 && isUndo && protyle.wysiwyg.element.childElementCount === 0) {// https://github.com/siyuan-note/siyuan/issues/15396 操作后撤销- protyle.wysiwyg.element.innerHTML = operation.data;+ protyle.wysiwyg.element.innerHTML = visibleData;cursorElements.push(protyle.wysiwyg.element.firstElementChild);} else if (previousElement.length === 0 && protyle.options.backlinkData && isUndo && getSelection().rangeCount > 0) {// 反链面板删除超级块中的最后一个段落块后撤销const blockElement = hasClosestBlock(getSelection().getRangeAt(0).startContainer);if (blockElement) {- blockElement.insertAdjacentHTML("beforebegin", operation.data);+ blockElement.insertAdjacentHTML("beforebegin", visibleData);cursorElements.push(blockElement.previousElementSibling);}} else {@@ -1014,7 +1035,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndembedElement.removeAttribute("data-render");blockRender(protyle, embedElement);} else {- item.insertAdjacentHTML("afterend", operation.data);+ item.insertAdjacentHTML("afterend", visibleData);cursorElements.push(item.nextElementSibling);}});@@ -1027,7 +1048,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndembedElement.removeAttribute("data-render");blockRender(protyle, embedElement);} else {- item.insertAdjacentHTML("beforebegin", operation.data);+ item.insertAdjacentHTML("beforebegin", visibleData);cursorElements.push(item.previousElementSibling);}});@@ -1041,13 +1062,13 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd}});if (!protyle.options.backlinkData && operation.parentID === protyle.block.parentID && !protyle.block.showAll) {- protyle.wysiwyg.element.insertAdjacentHTML("afterbegin", operation.data);+ protyle.wysiwyg.element.insertAdjacentHTML("afterbegin", visibleData);cursorElements.push(protyle.wysiwyg.element.firstElementChild);} else if (parentElement.length === 0 && protyle.options.backlinkData && isUndo && getSelection().rangeCount > 0) {// 反链面板删除超级块中的段落块后撤销const blockElement = hasClosestBlock(getSelection().getRangeAt(0).startContainer);if (blockElement) {- blockElement.insertAdjacentHTML("beforebegin", operation.data);+ blockElement.insertAdjacentHTML("beforebegin", visibleData);cursorElements.push(blockElement.previousElementSibling);}} else {@@ -1059,13 +1080,13 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd} else {// 列表特殊处理if (item.firstElementChild?.classList.contains("protyle-action")) {- item.firstElementChild.insertAdjacentHTML("afterend", operation.data);+ item.firstElementChild.insertAdjacentHTML("afterend", visibleData);cursorElements.push(item.firstElementChild.nextElementSibling);} else if (item.classList.contains("callout")) {- item.querySelector(".callout-content").insertAdjacentHTML("afterbegin", operation.data);+ item.querySelector(".callout-content").insertAdjacentHTML("afterbegin", visibleData);cursorElements.push(item.querySelector("[data-node-id]"));} else {- item.insertAdjacentHTML("afterbegin", operation.data);+ item.insertAdjacentHTML("afterbegin", visibleData);cursorElements.push(item.firstElementChild);}}@@ -1721,33 +1742,9 @@ export const turnsOneInto = async (options: {if (!options.nodeElement.querySelector("wbr")) {getContenteditableElement(options.nodeElement)?.insertAdjacentHTML("afterbegin", "<wbr>");}+ let foldOperations: IOperation[] = [];if (["CancelBlockquote", "CancelList", "CancelCallout"].includes(options.type)) {- for (const item of options.nodeElement.querySelectorAll('[data-type="NodeHeading"][fold="1"]')) {- const itemId = item.getAttribute("data-node-id");- item.removeAttribute("fold");- const response = await fetchSyncPost("/api/transactions", {- session: options.protyle.id,- app: Constants.SIYUAN_APPID,- transactions: [{- doOperations: [{- action: "unfoldHeading",- id: itemId,- }],- undoOperations: [{- action: "foldHeading",- id: itemId- }],- }]- });- options.protyle.undo.add([{- action: "unfoldHeading",- id: itemId,- }], [{- action: "foldHeading",- id: itemId- }], options.protyle);- item.insertAdjacentHTML("afterend", response.data[0].doOperations[0].retData);- }+ foldOperations = await unfoldListHeadings(options.protyle, [options.nodeElement]);}const oldHTML = options.nodeElement.outerHTML;const previousBlockElement = getPreviousBlockSibling(options.nodeElement);@@ -1797,7 +1794,9 @@ export const turnsOneInto = async (options: {previousID: previousId,parentID: parentId});- transaction(options.protyle, doOperations, undoOperations);+ const doFoldOperations = foldOperations.map((operation) => ({...operation}));+ const undoFoldOperations = foldOperations.map((operation) => ({...operation}));+ transaction(options.protyle, doOperations.concat(doFoldOperations), undoOperations.concat(undoFoldOperations));} else {updateTransaction(options.protyle, options.nodeElement, oldHTML);}@@ -1869,6 +1868,8 @@ const processFold = (operation: IOperation, protyle: IProtyle) => {gutterFoldElement.removeAttribute("disabled");}if (operation.action === "unfoldHeading") {+ const visibleRetData = typeof operation.retData === "string" ?+ getVisibleFoldHeadingHTML(operation.retData) : "";const scrollTop = protyle.contentElement.scrollTop;protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {const embedElement = isInEmbedBlock(item);@@ -1881,8 +1882,8 @@ const processFold = (operation: IOperation, protyle: IProtyle) => {if (!item.lastElementChild.classList.contains("protyle-attr")) {item.lastElementChild.remove();}- removeUnfoldRepeatBlock(operation.retData, protyle);- item.insertAdjacentHTML("afterend", operation.retData);+ removeUnfoldRepeatBlock(visibleRetData, protyle);+ item.insertAdjacentHTML("afterend", visibleRetData);if (operation.data === "remove") {// https://github.com/siyuan-note/siyuan/issues/2188const selection = getSelection();diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex 6bb7c38851..74ae47bec9 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -375,7 +375,7 @@ func buildBacklink(refID string, refTree *parse.Tree, originalRefBlockIDs map[st// 反链面板中显示块引用计数 Display reference counts in the backlink panel https://github.com/siyuan-note/siyuan/issues/13618fillBlockRefCount(renderNodes)- dom := renderBlockDOMByNodes(renderNodes, luteEngine)+ dom := renderVisibleBlockDOMByNodes(renderNodes, luteEngine)var blockPaths []*BlockPathif (nil != node.Parent && ast.NodeDocument != node.Parent.Type) || (ast.NodeHeading != node.Type && 0 < treenode.HeadingLevel(node)) {blockPaths = buildBlockBreadcrumb(node, nil, false)diff --git a/kernel/model/block.go b/kernel/model/block.goindex 06ad5a4773..c1a85f42a1 100644--- a/kernel/model/block.go+++ b/kernel/model/block.go@@ -376,23 +376,12 @@ func GetUnfoldedParentID(id string) (parentID string) {return}- var firstFoldedParent *ast.Node+ parentID = idfor parent := treenode.HeadingParent(node); nil != parent && ast.NodeDocument != parent.Type; parent = treenode.HeadingParent(parent) {- if "1" == parent.IALAttr("fold") {- firstFoldedParent = parent- parentID = firstFoldedParent.ID- } else {- if nil != firstFoldedParent {- parentID = firstFoldedParent.ID- } else {- parentID = id- }- return+ if treenode.IsSelfFolded(parent) {+ parentID = parent.ID}}- if "" == parentID {- parentID = id- }return}@@ -406,19 +395,19 @@ func IsBlockFolded(id string) (isFolded, isRoot bool) {isRoot = true}- for range 32 {- b, _ := getBlock(id, nil)- if nil == b {- return- }-- if "1" == b.IAL["fold"] {+ node := treenode.GetNodeInTree(tree, id)+ if nil == node {+ return+ }+ if treenode.IsSelfFolded(node) || treenode.IsInFoldedHeading(node, nil) {+ isFolded = true+ return+ }+ for parent := node.Parent; nil != parent && ast.NodeDocument != parent.Type; parent = parent.Parent {+ if treenode.IsSelfFolded(parent) {isFolded = truereturn}-- id = b.ParentID-}return}@@ -631,6 +620,10 @@ func GetHeadingDeleteTransaction(id string) (transaction *Transaction, err errorvar nodes []*ast.Nodenodes = append(nodes, node)nodes = append(nodes, treenode.HeadingChildren(node)...)+ hiddenNodes := map[string]bool{}+ for _, hidden := range treenode.CollectFoldHiddenNodes(node.Parent) {+ hiddenNodes[hidden.ID] = true+ }transaction = &Transaction{}luteEngine := util.NewLute()@@ -649,7 +642,10 @@ func GetHeadingDeleteTransaction(id string) (transaction *Transaction, err errorop.PreviousID = n.Previous.ID}op.Action = "insert"- op.Data = luteEngine.RenderNodeBlockDOM(n)+ op.Data = luteEngine.RenderNodeBlockDOM(cleanRenderNode(n, false))+ if hiddenNodes[n.ID] {+ op.Context = map[string]any{"ignoreProcess": "true"}+ }transaction.UndoOperations = append(transaction.UndoOperations, op)}return@@ -684,7 +680,7 @@ func GetHeadingInsertTransaction(id string) (transaction *Transaction, err errorop := &Operation{Context: map[string]any{"ignoreProcess": "true"}}op.ID = n.IDop.Action = "insert"- op.Data = luteEngine.RenderNodeBlockDOM(n)+ op.Data = luteEngine.RenderNodeBlockDOM(cleanRenderNode(n, false))transaction.DoOperations = append(transaction.DoOperations, op)op = &Operation{}@@ -781,7 +777,7 @@ func GetHeadingChildrenDOM(id string, removeFoldAttr bool) (ret string) {}luteEngine := util.NewLute()- ret = renderBlockDOMByNodes(nodes, luteEngine)+ ret = renderCleanBlockDOMByNodes(nodes, luteEngine)return}@@ -817,7 +813,7 @@ func GetHeadingLevelTransaction(id string, level int) (transaction *Transaction,fillBlockRefCount(childrenHeadings)transaction = &Transaction{}- if "1" == node.IALAttr("fold") {+ if treenode.IsSelfFolded(node) {unfoldHeading(node, node)}@@ -826,7 +822,7 @@ func GetHeadingLevelTransaction(id string, level int) (transaction *Transaction,op := &Operation{}op.ID = c.IDop.Action = "update"- op.Data = luteEngine.RenderNodeBlockDOM(c)+ op.Data = luteEngine.RenderNodeBlockDOM(cleanRenderNode(c, false))transaction.UndoOperations = append(transaction.UndoOperations, op)c.HeadingLevel += diff@@ -839,7 +835,7 @@ func GetHeadingLevelTransaction(id string, level int) (transaction *Transaction,op = &Operation{}op.ID = c.IDop.Action = "update"- op.Data = luteEngine.RenderNodeBlockDOM(c)+ op.Data = luteEngine.RenderNodeBlockDOM(cleanRenderNode(c, false))transaction.DoOperations = append(transaction.DoOperations, op)}return@@ -893,7 +889,7 @@ func GetBlockDOMsInBox(ids []string, boxID string) (ret map[string]string) {return ast.WalkContinue})- ret[id] = luteEngine.RenderNodeBlockDOM(node)+ ret[id] = luteEngine.RenderNodeBlockDOM(cleanRenderNode(node, false))}return}@@ -962,7 +958,7 @@ func GetBlockDOMsWithEmbedInBoxWithAccessChecker(ids []string, boxID string, accreturn ast.WalkContinue})- htmlContent := luteEngine.RenderNodeBlockDOM(node)+ htmlContent := luteEngine.RenderNodeBlockDOM(cleanRenderNode(node, false))htmlContent = processEmbedHTML(htmlContent)@@ -1023,7 +1019,7 @@ func resolveEmbedContentInBox(n *ast.Node, luteEngine *lute.Lute, boxID string,var contentHTML stringif "d" == sqlBlock.Type {// 文档块:直接使用原始 AST 节点渲染,保持原始的 data-node-id- contentHTML = luteEngine.RenderNodeBlockDOM(subTree.Root)+ contentHTML = luteEngine.RenderNodeBlockDOM(cleanRenderNode(subTree.Root, true))} else if "h" == sqlBlock.Type {// 标题块:使用标题及其子块的原始 AST 节点渲染h := treenode.GetNodeInTree(subTree, sqlBlock.ID)@@ -1033,20 +1029,14 @@ func resolveEmbedContentInBox(n *ast.Node, luteEngine *lute.Lute, boxID string,var hChildren []*ast.NodehChildren = append(hChildren, h)hChildren = append(hChildren, treenode.HeadingChildren(h)...)-- // 创建一个临时的文档节点来包含所有子节点- tempRoot := &ast.Node{Type: ast.NodeDocument}- for _, hChild := range hChildren {- tempRoot.AppendChild(hChild)- }- contentHTML = luteEngine.RenderNodeBlockDOM(tempRoot)+ contentHTML = renderVisibleBlockDOMByNodes(hChildren, luteEngine)} else {// 其他块:直接使用原始 AST 节点渲染blockNode := treenode.GetNodeInTree(subTree, sqlBlock.ID)if nil == blockNode {continue}- contentHTML = luteEngine.RenderNodeBlockDOM(blockNode)+ contentHTML = luteEngine.RenderNodeBlockDOM(cleanRenderNode(blockNode, true))}if contentHTML != "" {@@ -1335,25 +1325,7 @@ func getEmbeddedBlock(trees map[string]*parse.Tree, sqlBlock *sql.Block, headingreturn}- var unlinks, nodes []*ast.Node- ast.Walk(def, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering {- return ast.WalkContinue- }-- if ast.NodeHeading == n.Type {- if "1" == n.IALAttr("fold") {- children := treenode.HeadingChildren(n)- for _, c := range children {- unlinks = append(unlinks, c)- }- }- }- return ast.WalkContinue- })- for _, n := range unlinks {- n.Unlink()- }+ var nodes []*ast.Node// headingMode: 0=显示标题与下方的块,1=仅显示标题,2=仅显示标题下方的块if ast.NodeHeading == def.Type {if 1 == headingMode {@@ -1361,29 +1333,13 @@ func getEmbeddedBlock(trees map[string]*parse.Tree, sqlBlock *sql.Block, headingnodes = append(nodes, def)} else if 2 == headingMode {// 仅显示标题下方的块(去除标题)- if "1" != def.IALAttr("fold") {- children := treenode.HeadingChildren(def)- for _, c := range children {- if "1" == c.IALAttr("heading-fold") {- // 嵌入块包含折叠标题时不应该显示其下方块 https://github.com/siyuan-note/siyuan/issues/4765- continue- }- nodes = append(nodes, c)- }+ if !treenode.IsSelfFolded(def) {+ nodes = append(nodes, treenode.HeadingChildren(def)...)}} else {// 0: 显示标题与下方的块nodes = append(nodes, def)- if "1" != def.IALAttr("fold") {- children := treenode.HeadingChildren(def)- for _, c := range children {- if "1" == c.IALAttr("heading-fold") {- // 嵌入块包含折叠标题时不应该显示其下方块 https://github.com/siyuan-note/siyuan/issues/4765- continue- }- nodes = append(nodes, c)- }- }+ nodes = append(nodes, treenode.HeadingChildren(def)...)}} else {// 非标题块,直接添加@@ -1408,8 +1364,9 @@ func getEmbeddedBlock(trees map[string]*parse.Tree, sqlBlock *sql.Block, headingluteEngine := NewLute()luteEngine.RenderOptions.ProtyleContenteditable = true- dom := renderBlockDOMByNodes(nodes, luteEngine)- content := renderBlockContentByNodes(nodes)+ visibleNodes := cleanRenderNodes(nodes, true)+ dom := renderBlockDOMByNodes(visibleNodes, luteEngine)+ content := renderBlockContentByNodes(visibleNodes)block = &Block{Box: def.Box, Path: def.Path, HPath: b.HPath, ID: def.ID, Type: def.Type.String(), Content: dom, Markdown: content /* 这里使用 Markdown 字段来临时存储 content */}if "" != sqlBlock.IAL {diff --git a/kernel/model/blockial.go b/kernel/model/blockial.goindex d35646b605..02e8f1014b 100644--- a/kernel/model/blockial.go+++ b/kernel/model/blockial.go@@ -342,6 +342,12 @@ func setNodeAttrs0(node *ast.Node, nameValues map[string]string, boxID string) (}oldAttrs = parse.IAL2Map(node.KramdownIAL)newAttrsUnEsc := parse.IAL2MapUnEsc(node.KramdownIAL)+ for name := range nameValues {+ if "fold" == strings.ToLower(name) {+ delete(newAttrsUnEsc, "heading-fold")+ break+ }+ }for name, value := range nameValues {value = util.RemoveInvalidRetainCtrl(value)diff --git a/kernel/model/blockial_fold_test.go b/kernel/model/blockial_fold_test.gonew file mode 100644index 0000000000..067380c2c6--- /dev/null+++ b/kernel/model/blockial_fold_test.go@@ -0,0 +1,48 @@+// 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/siyuan-note/siyuan/kernel/treenode"+)++func TestSetNodeAttrsClaimsFoldState(t *testing.T) {+ node := &ast.Node{Type: ast.NodeListItem, ID: "item"}+ node.SetIALAttr("fold", "1")+ node.SetIALAttr("heading-fold", "1")++ if _, err := setNodeAttrs0(node, map[string]string{"fold": "1"}, ""); nil != err {+ t.Fatal(err)+ }+ if !treenode.IsSelfFolded(node) {+ t.Fatal("explicit fold attribute should become self fold")+ }+ if "" != node.IALAttr("heading-fold") {+ t.Fatal("explicit fold attribute should remove legacy heading-fold")+ }++ node.SetIALAttr("heading-fold", "1")+ if _, err := setNodeAttrs0(node, map[string]string{"fold": ""}, ""); nil != err {+ t.Fatal(err)+ }+ if "" != node.IALAttr("fold") || "" != node.IALAttr("heading-fold") {+ t.Fatal("explicit unfold should remove both fold attributes")+ }+}diff --git a/kernel/model/export.go b/kernel/model/export.goindex f858321a16..4cff2559dc 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -3256,6 +3256,18 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,unlinks = nilvar emptyParagraphs []*ast.Node+ foldHidden := map[*ast.Node]bool{}+ ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && n.IsBlock() {+ treenode.ClearLegacyHeadingFold(n)+ }+ return ast.WalkContinue+ })+ if keepFold {+ for _, n := range treenode.CollectFoldHiddenNodes(ret.Root) {+ foldHidden[n] = true+ }+ }ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue@@ -3265,12 +3277,9 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,if !keepFold {// 块折叠以后导出 HTML/PDF 固定展开 https://github.com/siyuan-note/siyuan/issues/4064n.RemoveIALAttr("fold")- n.RemoveIALAttr("heading-fold")- } else {- if "1" == n.IALAttr("heading-fold") {- unlinks = append(unlinks, n)- return ast.WalkContinue- }+ } else if foldHidden[n] {+ unlinks = append(unlinks, n)+ return ast.WalkSkipChildren}// 导出时去掉内容块闪卡样式 https://github.com/siyuan-note/siyuan/issues/7374diff --git a/kernel/model/file.go b/kernel/model/file.goindex 2ce72ddd64..f4a0f1b7e4 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -657,14 +657,9 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,idx++if index == idx {node = n.DocChild()- if "1" == node.IALAttr("heading-fold") {+ if parentFoldedHeading := treenode.GetParentFoldedHeading(node); nil != parentFoldedHeading {// 加载到折叠标题下方块的话需要回溯到上方标题块- for h := node.Previous; nil != h; h = h.Previous {- if "1" == h.IALAttr("fold") {- node = h- break- }- }+ node = parentFoldedHeading}located = truereturn ast.WalkStop@@ -840,11 +835,8 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,return ast.WalkSkipChildren}- if !nInFoldedHeading && "1" == n.IALAttr("heading-fold") {- // 标题已展开但子块仍残留 heading-fold 时清理,避免列表等嵌套块渲染为空- n.RemoveIALAttr("heading-fold")- n.RemoveIALAttr("fold")- }+ // 旧版 heading-fold 仅用于兼容读取,不能输出为块自身的折叠状态。+ treenode.ClearLegacyHeadingFold(n)if avs := n.IALAttr(av.NodeAttrNameAvs); "" != avs {// 填充属性视图角标 Display the database title on the block superscript https://github.com/siyuan-note/siyuan/issues/10545@@ -988,7 +980,7 @@ func loadNodesByStartEnd(tree *parse.Tree, startID, endID string) (nodes []*ast.func loadNodesByMode(node *ast.Node, inputIndex, mode, size int, isDoc, isHeading bool) (nodes []*ast.Node, eof bool) {if 2 == mode /* 向下 */ {next := node.Next- if ast.NodeHeading == node.Type && "1" == node.IALAttr("fold") {+ if ast.NodeHeading == node.Type && treenode.IsSelfFolded(node) {// 标题展开时进行动态加载导致重复内容 https://github.com/siyuan-note/siyuan/issues/4671// 这里要考虑折叠标题是最后一个块的情况if children := treenode.HeadingChildren(node); 0 < len(children) {diff --git a/kernel/model/heading.go b/kernel/model/heading.goindex 057345197c..c0f18ab84b 100644--- a/kernel/model/heading.go+++ b/kernel/model/heading.go@@ -50,24 +50,12 @@ func (tx *Transaction) doFoldHeading(operation *Operation) (ret *TxErr) {children := treenode.HeadingChildren(heading)for _, child := range children {childrenIDs = append(childrenIDs, child.ID)- ast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering || !n.IsBlock() {- return ast.WalkContinue- }-- n.SetIALAttr("fold", "1")- n.SetIALAttr("heading-fold", "1")- return ast.WalkContinue- })}- heading.SetIALAttr("fold", "1")+ treenode.SetSelfFolded(heading, true)tx.writeTree(tree)IncSync()cache.PutBlockIALInBox(headingID, tree.Box, parse.IAL2Map(heading.KramdownIAL))- for _, child := range children {- cache.PutBlockIALInBox(child.ID, tree.Box, parse.IAL2Map(child.KramdownIAL))- }sql.UpsertTreeQueue(tree)operation.RetData = childrenIDsreturn@@ -86,58 +74,44 @@ func (tx *Transaction) doUnfoldHeading(operation *Operation) (ret *TxErr) {return &TxErr{code: TxErrCodeBlockNotFound, id: headingID}}- luteEngine := NewLute()- parentFoldedHeading := treenode.GetParentFoldedHeading(heading)- if nil != parentFoldedHeading {- // 如果当前标题在上方某个折叠的标题下方,则展开上方那个折叠标题以保持一致性- children := treenode.HeadingChildren(parentFoldedHeading)- for _, child := range children {- ast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering || !n.IsBlock() {- return ast.WalkContinue- }-- n.RemoveIALAttr("heading-fold")- n.RemoveIALAttr("fold")- return ast.WalkContinue- })- }- parentFoldedHeading.RemoveIALAttr("fold")- parentFoldedHeading.RemoveIALAttr("heading-fold")- go func() {- tx.WaitForCommit()- ReloadProtyle(tree.ID)- }()- }-children := treenode.HeadingChildren(heading)+ legacyNodes := map[string]*ast.Node{}for _, child := range children {ast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering {+ if !entering || !n.IsBlock() {return ast.WalkContinue}- n.RemoveIALAttr("heading-fold")- n.RemoveIALAttr("fold")+ if treenode.ClearLegacyHeadingFold(n) {+ legacyNodes[n.ID] = n+ }return ast.WalkContinue})}- heading.RemoveIALAttr("fold")- heading.RemoveIALAttr("heading-fold")+ if "1" == heading.IALAttr("heading-fold") {+ legacyNodes[heading.ID] = heading+ }+ treenode.SetSelfFolded(heading, false)tx.writeTree(tree)IncSync()cache.PutBlockIALInBox(headingID, tree.Box, parse.IAL2Map(heading.KramdownIAL))- for _, child := range children {- cache.PutBlockIALInBox(child.ID, tree.Box, parse.IAL2Map(child.KramdownIAL))+ for _, node := range legacyNodes {+ cache.PutBlockIALInBox(node.ID, tree.Box, parse.IAL2Map(node.KramdownIAL))}sql.UpsertTreeQueue(tree)// 展开折叠的标题后显示块引用计数 Display reference counts after unfolding headings https://github.com/siyuan-note/siyuan/issues/13618fillBlockRefCount(children)- operation.RetData = renderBlockDOMByNodes(children, luteEngine)+ operation.RetData = renderVisibleBlockDOMByNodes(children, NewLute())+ if 0 < len(legacyNodes) {+ go func() {+ tx.WaitForCommit()+ ReloadProtyle(tree.ID)+ }()+ }return}@@ -381,21 +355,19 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath, previousPath string, toT}}- // 折叠标题转换为文档时需要自动展开下方块 https://github.com/siyuan-note/siyuan/issues/2947+ // 标题转换为文档时清理旧版标题折叠派生状态,并保留下方块各自的折叠状态。children := treenode.HeadingChildren(headingNode)for _, child := range children {ast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering {+ if !entering || !n.IsBlock() {return ast.WalkContinue}- n.RemoveIALAttr("heading-fold")- n.RemoveIALAttr("fold")+ treenode.ClearLegacyHeadingFold(n)return ast.WalkContinue})}- headingNode.RemoveIALAttr("fold")- headingNode.RemoveIALAttr("heading-fold")+ treenode.SetSelfFolded(headingNode, false)luteEngine := util.NewLute()newTree := &parse.Tree{Root: &ast.Node{Type: ast.NodeDocument, ID: srcHeadingID}, Context: &parse.Context{ParseOption: luteEngine.ParseOptions}}diff --git a/kernel/model/listitem.go b/kernel/model/listitem.goindex fac5458dd9..6145943eb1 100644--- a/kernel/model/listitem.go+++ b/kernel/model/listitem.go@@ -111,7 +111,7 @@ func ListItem2Doc(srcListItemID, targetBoxID, targetPath, previousPath string, tlistItemNode.SetIALAttr("type", "doc")listItemNode.SetIALAttr("id", srcListItemID)listItemNode.SetIALAttr("title", listItemText)- listItemNode.RemoveIALAttr("fold")+ treenode.SetSelfFolded(listItemNode, false)listItemNode.RemoveIALAttr(DocHiddenAttr)newTree.Root.KramdownIAL = listItemNode.KramdownIALsrcLiParent := listItemNode.Parentdiff --git a/kernel/model/render.go b/kernel/model/render.goindex b7bdafd72d..8670a582c3 100644--- a/kernel/model/render.go+++ b/kernel/model/render.go@@ -175,6 +175,80 @@ func fillBlockRefCount(nodes []*ast.Node) {}}+func cloneRenderNode(node *ast.Node) *ast.Node {+ if nil == node {+ return nil+ }++ cloned := *node+ cloned.Parent = nil+ cloned.Previous = nil+ cloned.Next = nil+ cloned.FirstChild = nil+ cloned.LastChild = nil+ cloned.Children = nil+ cloned.Tokens = bytes.Clone(node.Tokens)+ if nil != node.KramdownIAL {+ cloned.KramdownIAL = make([][]string, 0, len(node.KramdownIAL))+ for _, attr := range node.KramdownIAL {+ cloned.KramdownIAL = append(cloned.KramdownIAL, append([]string{}, attr...))+ }+ }+ if nil != node.Properties {+ cloned.Properties = make(map[string]string, len(node.Properties))+ for name, value := range node.Properties {+ cloned.Properties[name] = value+ }+ }++ for child := node.FirstChild; nil != child; child = child.Next {+ cloned.AppendChild(cloneRenderNode(child))+ }+ return &cloned+}++func cleanRenderNodes(nodes []*ast.Node, visibleOnly bool) (ret []*ast.Node) {+ root := &ast.Node{Type: ast.NodeDocument}+ for _, node := range nodes {+ if cloned := cloneRenderNode(node); nil != cloned {+ root.AppendChild(cloned)+ }+ }++ ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && node.IsBlock() {+ treenode.ClearLegacyHeadingFold(node)+ }+ return ast.WalkContinue+ })+ if visibleOnly {+ for _, node := range treenode.CollectFoldHiddenNodes(root) {+ node.Unlink()+ }+ }++ for node := root.FirstChild; nil != node; node = node.Next {+ ret = append(ret, node)+ }+ return+}++func cleanRenderNode(node *ast.Node, visibleOnly bool) *ast.Node {+ nodes := cleanRenderNodes([]*ast.Node{node}, visibleOnly)+ if 0 == len(nodes) {+ return nil+ }+ return nodes[0]+}++func renderCleanBlockDOMByNodes(nodes []*ast.Node, luteEngine *lute.Lute) string {+ return renderBlockDOMByNodes(cleanRenderNodes(nodes, false), luteEngine)+}++func renderVisibleBlockDOMByNodes(nodes []*ast.Node, luteEngine *lute.Lute) string {+ return renderBlockDOMByNodes(cleanRenderNodes(nodes, true), luteEngine)+}+func renderBlockDOMByNodes(nodes []*ast.Node, luteEngine *lute.Lute) string {tree := &parse.Tree{Root: &ast.Node{Type: ast.NodeDocument}, Context: &parse.Context{ParseOption: luteEngine.ParseOptions}}blockRenderer := render.NewProtyleRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)@@ -327,21 +401,15 @@ func resolveEmbedR(n *ast.Node, blockEmbedMode int, luteEngine *lute.Lute, resolhChildren = append(hChildren, h)} else if 2 == blockHeadingMode {// 仅显示标题下方的块(默认行为)- if "1" != h.IALAttr("fold") {- children := treenode.HeadingChildren(h)- for _, c := range children {- if "1" == c.IALAttr("heading-fold") {- // 嵌入块包含折叠标题时不应该显示其下方块 https://github.com/siyuan-note/siyuan/issues/4765- continue- }- hChildren = append(hChildren, c)- }+ if !treenode.IsSelfFolded(h) {+ hChildren = append(hChildren, treenode.HeadingChildren(h)...)}} else {// 0: 显示标题与下方的块hChildren = append(hChildren, h)hChildren = append(hChildren, treenode.HeadingChildren(h)...)}+ hChildren = cleanRenderNodes(hChildren, true)if 0 == blockEmbedMode {embedTopLevel := 0for _, hChild := range hChildren {diff --git a/kernel/model/render_fold_test.go b/kernel/model/render_fold_test.gonew file mode 100644index 0000000000..f5755963ae--- /dev/null+++ b/kernel/model/render_fold_test.go@@ -0,0 +1,93 @@+// 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/siyuan-note/siyuan/kernel/treenode"+)++func TestCleanRenderNodesPreservesNestedFold(t *testing.T) {+ h1 := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 1, ID: "h1"}+ h2 := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 2, ID: "h2"}+ child := &ast.Node{Type: ast.NodeParagraph, ID: "child"}+ nextH1 := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 1, ID: "next-h1"}+ treenode.SetSelfFolded(h2, true)++ nodes := cleanRenderNodes([]*ast.Node{h1, h2, child, nextH1}, true)+ if 3 != len(nodes) {+ t.Fatalf("visible render should omit nested folded content, got %d nodes", len(nodes))+ }+ if "h1" != nodes[0].ID || "h2" != nodes[1].ID || "next-h1" != nodes[2].ID {+ t.Fatalf("unexpected visible node order [%s, %s, %s]", nodes[0].ID, nodes[1].ID, nodes[2].ID)+ }+ if !treenode.IsSelfFolded(nodes[1]) {+ t.Fatal("nested heading should keep its own fold state")+ }+}++func TestCleanRenderNodesDoesNotMutateLegacySource(t *testing.T) {+ legacyHeading := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 2, ID: "legacy-heading"}+ legacyHeading.SetIALAttr("fold", "1")+ legacyHeading.SetIALAttr("heading-fold", "1")+ child := &ast.Node{Type: ast.NodeParagraph, ID: "child"}++ nodes := cleanRenderNodes([]*ast.Node{legacyHeading, child}, true)+ if 2 != len(nodes) {+ t.Fatalf("legacy derived fold should not hide content, got %d nodes", len(nodes))+ }+ if "" != nodes[0].IALAttr("fold") || "" != nodes[0].IALAttr("heading-fold") {+ t.Fatal("legacy attributes should be removed from rendered clone")+ }+ if "1" != legacyHeading.IALAttr("fold") || "1" != legacyHeading.IALAttr("heading-fold") {+ t.Fatal("render cleanup should not mutate source tree")+ }+}++func TestCleanRenderNodesKeepsFoldedContainerChildren(t *testing.T) {+ listItem := &ast.Node{Type: ast.NodeListItem, ID: "item", ListData: &ast.ListData{}}+ child := &ast.Node{Type: ast.NodeParagraph, ID: "child"}+ treenode.SetSelfFolded(listItem, true)+ listItem.AppendChild(child)++ nodes := cleanRenderNodes([]*ast.Node{listItem}, true)+ if 1 != len(nodes) || nil == nodes[0].FirstChild || "child" != nodes[0].FirstChild.ID {+ t.Fatal("heading visibility projection should keep folded container children")+ }+ if !treenode.IsSelfFolded(nodes[0]) {+ t.Fatal("folded container should keep its own fold state")+ }+}++func TestCleanRenderDocumentHidesFoldedHeadingChildren(t *testing.T) {+ document := &ast.Node{Type: ast.NodeDocument, ID: "document"}+ heading := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 1, ID: "heading"}+ child := &ast.Node{Type: ast.NodeParagraph, ID: "child"}+ treenode.SetSelfFolded(heading, true)+ document.AppendChild(heading)+ document.AppendChild(child)++ nodes := cleanRenderNodes([]*ast.Node{document}, true)+ if 1 != len(nodes) || nil == nodes[0].FirstChild || "heading" != nodes[0].FirstChild.ID {+ t.Fatal("document render should keep the folded heading")+ }+ if nil != nodes[0].FirstChild.Next {+ t.Fatal("document render should omit folded heading children")+ }+}diff --git a/kernel/model/template.go b/kernel/model/template.goindex 3a58d17b5a..a49ac8020c 100644--- a/kernel/model/template.go+++ b/kernel/model/template.go@@ -552,17 +552,16 @@ func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, en.Unlink()}- // 折叠标题导出为模板后使用会出现内容重复 https://github.com/siyuan-note/siyuan/issues/4488+ // 折叠标题下方块需要在模板插入后从当前 DOM 中移除,展开标题时再由内核加载,避免内容重复。ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering {- return ast.WalkContinue- }-- if "1" == n.IALAttr("heading-fold") { // 为标题折叠下方块添加属性,前端渲染以后会统一做移除处理- n.SetIALAttr("status", "temp")+ if entering && n.IsBlock() {+ treenode.ClearLegacyHeadingFold(n)}return ast.WalkContinue})+ for _, n := range treenode.CollectFoldHiddenNodes(tree.Root) {+ n.SetIALAttr("status", "temp")+ }icon := tree.Root.IALAttr("icon")if "" != icon {diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex f9b5fbc068..1bcd63598f 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -519,10 +519,8 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {generateOpTypeHistory(srcTree, HistoryOpUpdate)var headingChildren []*ast.Node- if isMovingFoldHeading := ast.NodeHeading == srcNode.Type && "1" == srcNode.IALAttr("fold"); isMovingFoldHeading {+ if isMovingFoldHeading := ast.NodeHeading == srcNode.Type && treenode.IsSelfFolded(srcNode); isMovingFoldHeading {headingChildren = treenode.HeadingChildren(srcNode)- // Blocks below other non-folded headings are no longer moved when moving a folded heading https://github.com/siyuan-note/siyuan/issues/8321- headingChildren = treenode.GetHeadingFold(headingChildren)}var srcEmptyList *ast.Node@@ -532,8 +530,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {}if nil != operation.Context && "true" == operation.Context["removeFold"] {- srcNode.RemoveIALAttr("heading-fold")- srcNode.RemoveIALAttr("fold")+ treenode.SetSelfFolded(srcNode, false)}targetPreviousID := operation.PreviousID@@ -565,9 +562,8 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {return &TxErr{code: TxErrCodeBlockNotFound, id: targetPreviousID}}- if ast.NodeHeading == targetNode.Type && "1" == targetNode.IALAttr("fold") {+ if ast.NodeHeading == targetNode.Type && treenode.IsSelfFolded(targetNode) {targetChildren := treenode.HeadingChildren(targetNode)- targetChildren = treenode.GetHeadingFold(targetChildren)if l := len(targetChildren); 0 < l {targetNode = targetChildren[l-1]@@ -586,17 +582,8 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {// 折叠标题再编辑形成外层列表(前面加上 * )时,前端给的 tx 序列会形成死循环,在这里解开// Nested lists cause hang after collapsing headings https://github.com/siyuan-note/siyuan/issues/15943lastChild := headingChildren[len(headingChildren)-1]- if "1" == lastChild.IALAttr("heading-fold") && ast.NodeList == lastChild.Type &&+ if ast.NodeList == lastChild.Type &&nil != lastChild.FirstChild && nil != lastChild.FirstChild.FirstChild && lastChild.FirstChild.FirstChild.ID == targetPreviousID {- ast.Walk(lastChild, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering || !n.IsBlock() {- return ast.WalkContinue- }-- n.RemoveIALAttr("heading-fold")- n.RemoveIALAttr("fold")- return ast.WalkContinue- })headingChildren = headingChildren[:len(headingChildren)-1]}}@@ -957,7 +944,7 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {}var headingChildren []*ast.Node- if isMovingFoldHeading := ast.NodeHeading == srcNode.Type && "1" == srcNode.IALAttr("fold"); isMovingFoldHeading {+ if isMovingFoldHeading := ast.NodeHeading == srcNode.Type && treenode.IsSelfFolded(srcNode); isMovingFoldHeading {headingChildren = treenode.HeadingChildren(srcNode)}var srcEmptyList, targetNewList *ast.Node@@ -1389,7 +1376,7 @@ func (tx *Transaction) doInsert0(operation *Operation, tree *parse.Tree) (ret *Treturn &TxErr{code: TxErrCodeBlockNotFound, id: previousID}}- if ast.NodeHeading == node.Type && "1" == node.IALAttr("fold") {+ if ast.NodeHeading == node.Type && treenode.IsSelfFolded(node) {children := treenode.HeadingChildren(node)if l := len(children); 0 < l {node = children[l-1]@@ -1689,19 +1676,7 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {if needInsertAfterParentHeading {insertDom := dataif 2 == len(tx.DoOperations) && "foldHeading" == tx.DoOperations[1].Action {- children := treenode.HeadingChildren(updatedNode)- for _, child := range children {- ast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering || !n.IsBlock() {- return ast.WalkContinue- }-- n.SetIALAttr("fold", "1")- n.SetIALAttr("heading-fold", "1")- return ast.WalkContinue- })- }- updatedNode.SetIALAttr("fold", "1")+ treenode.SetSelfFolded(updatedNode, true)insertDom = tx.luteEngine.RenderNodeBlockDOM(updatedNode)}@@ -1756,20 +1731,7 @@ func unfoldHeading(heading, currentNode *ast.Node) {return}- children := treenode.HeadingChildren(heading)- for _, child := range children {- ast.Walk(child, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering || !n.IsBlock() {- return ast.WalkContinue- }-- n.RemoveIALAttr("fold")- n.RemoveIALAttr("heading-fold")- return ast.WalkContinue- })- }- heading.RemoveIALAttr("fold")- heading.RemoveIALAttr("heading-fold")+ treenode.SetSelfFolded(heading, false)util.BroadcastByType("protyle", "unfoldHeading", 0, "", map[string]any{"id": heading.ID, "currentNodeID": currentNode.ID})}@@ -2295,7 +2257,7 @@ func getRefsCacheByDefNode(updateNode *ast.Node) (ret []*sql.Ref, changedNodes [return ast.WalkContinue})}- if ast.NodeHeading == updateNode.Type && "1" == updateNode.IALAttr("fold") {+ if ast.NodeHeading == updateNode.Type && treenode.IsSelfFolded(updateNode) {// 如果是折叠标题,则需要向下查找引用children := treenode.HeadingChildren(updateNode)for _, child := range children {diff --git a/kernel/treenode/fold_heading_stack_test.go b/kernel/treenode/fold_heading_stack_test.goindex b142fd9176..d9c3b3fce6 100644--- a/kernel/treenode/fold_heading_stack_test.go+++ b/kernel/treenode/fold_heading_stack_test.go@@ -50,6 +50,89 @@ func TestFoldHeadingStackHidesChildren(t *testing.T) {}}+func TestFoldHeadingStackPreservesNestedFold(t *testing.T) {+ root := &ast.Node{Type: ast.NodeDocument}+ h1 := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 1, ID: "h1"}+ h2 := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 2, ID: "h2"}+ child := &ast.Node{Type: ast.NodeParagraph, ID: "p1"}+ nextH1 := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 1, ID: "h1-next"}+ SetSelfFolded(h1, true)+ SetSelfFolded(h2, true)+ root.AppendChild(h1)+ root.AppendChild(h2)+ root.AppendChild(child)+ root.AppendChild(nextH1)++ var foldedParentStack FoldHeadingStack+ foldedParentStack.Enter(h1)+ foldedParentStack.Enter(h2)+ if !foldedParentStack.Hidden() {+ t.Fatal("nested folded heading should be hidden by folded parent")+ }++ SetSelfFolded(h1, false)+ var unfoldedParentStack FoldHeadingStack+ unfoldedParentStack.Enter(h1)+ unfoldedParentStack.Enter(h2)+ if unfoldedParentStack.Hidden() {+ t.Fatal("nested folded heading should become visible after parent unfolds")+ }+ unfoldedParentStack.Enter(child)+ if !unfoldedParentStack.Hidden() {+ t.Fatal("nested folded heading should keep its own children hidden")+ }+ unfoldedParentStack.Enter(nextH1)+ if unfoldedParentStack.Hidden() {+ t.Fatal("same-level heading should end nested fold scope")+ }+}++func TestLegacyHeadingFoldIsNotSelfFold(t *testing.T) {+ legacy := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 2, ID: "legacy"}+ legacy.SetIALAttr("fold", "1")+ legacy.SetIALAttr("heading-fold", "1")+ if IsSelfFolded(legacy) {+ t.Fatal("legacy derived fold should not be treated as self fold")+ }++ SetSelfFolded(legacy, true)+ if !IsSelfFolded(legacy) {+ t.Fatal("explicit fold should become self fold")+ }+ if "" != legacy.IALAttr("heading-fold") {+ t.Fatal("explicit fold should remove legacy heading-fold")+ }++ legacy.SetIALAttr("heading-fold", "1")+ if !ClearLegacyHeadingFold(legacy) {+ t.Fatal("legacy fold should be cleared")+ }+ if "" != legacy.IALAttr("fold") || "" != legacy.IALAttr("heading-fold") {+ t.Fatal("legacy fold attributes should both be removed")+ }+}++func TestCollectFoldHiddenNodesKeepsContainerScope(t *testing.T) {+ root := &ast.Node{Type: ast.NodeDocument}+ list := &ast.Node{Type: ast.NodeList, ID: "list", ListData: &ast.ListData{}}+ item := &ast.Node{Type: ast.NodeListItem, ID: "item", ListData: &ast.ListData{}}+ heading := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 2, ID: "heading"}+ child := &ast.Node{Type: ast.NodeParagraph, ID: "child"}+ outside := &ast.Node{Type: ast.NodeParagraph, ID: "outside"}+ SetSelfFolded(item, true)+ SetSelfFolded(heading, true)+ item.AppendChild(heading)+ item.AppendChild(child)+ list.AppendChild(item)+ root.AppendChild(list)+ root.AppendChild(outside)++ hidden := CollectFoldHiddenNodes(root)+ if 1 != len(hidden) || hidden[0] != child {+ t.Fatalf("heading fold should only hide siblings in the same container, got %d nodes", len(hidden))+ }+}+func TestCollectFoldHiddenNodesKeepsCalloutChildren(t *testing.T) {callout := &ast.Node{Type: ast.NodeCallout, ID: "c1"}p := &ast.Node{Type: ast.NodeParagraph, ID: "p1"}diff --git a/kernel/treenode/heading.go b/kernel/treenode/heading.goindex d13d3f6d7e..87c871a455 100644--- a/kernel/treenode/heading.go+++ b/kernel/treenode/heading.go@@ -21,6 +21,38 @@ import ("github.com/88250/lute/parse")+// IsSelfFolded 判断块是否处于自身折叠状态。heading-fold 是旧版标题折叠向后代注入的临时标记,+// 同时存在时 fold 不代表块自身状态。+func IsSelfFolded(node *ast.Node) bool {+ return nil != node && "1" == node.IALAttr("fold") && "1" != node.IALAttr("heading-fold")+}++// SetSelfFolded 设置块自身的折叠状态。显式设置后需要移除旧版 heading-fold 标记,+// 以便后续能够区分用户状态和旧版标题折叠的派生状态。+func SetSelfFolded(node *ast.Node, folded bool) {+ if nil == node {+ return+ }++ node.RemoveIALAttr("heading-fold")+ if folded {+ node.SetIALAttr("fold", "1")+ } else {+ node.RemoveIALAttr("fold")+ }+}++// ClearLegacyHeadingFold 清理旧版标题折叠向块注入的派生状态。+func ClearLegacyHeadingFold(node *ast.Node) bool {+ if nil == node || "1" != node.IALAttr("heading-fold") {+ return false+ }++ node.RemoveIALAttr("heading-fold")+ node.RemoveIALAttr("fold")+ return true+}+func MoveFoldHeading(updateNode, oldNode *ast.Node) {foldHeadings := map[string][]*ast.Node{}// 找到原有节点中所有折叠标题节点的下方节点@@ -29,7 +61,7 @@ func MoveFoldHeading(updateNode, oldNode *ast.Node) {return ast.WalkContinue}- if ast.NodeHeading == n.Type && "1" == n.IALAttr("fold") {+ if ast.NodeHeading == n.Type && IsSelfFolded(n) {children := HeadingChildren(n)foldHeadings[n.ID] = children}@@ -43,7 +75,7 @@ func MoveFoldHeading(updateNode, oldNode *ast.Node) {return ast.WalkContinue}- if ast.NodeHeading == n.Type && "1" == n.IALAttr("fold") {+ if ast.NodeHeading == n.Type && IsSelfFolded(n) {updateFoldHeadings = append(updateFoldHeadings, n)}return ast.WalkContinue@@ -79,7 +111,7 @@ func (s *FoldHeadingStack) Enter(n *ast.Node) {}// 当前标题自身折叠时入栈,其后更深层级的兄弟块都被它盖住- if "1" == n.IALAttr("fold") {+ if IsSelfFolded(n) {s.levels = append(s.levels, n.HeadingLevel)}}@@ -92,7 +124,7 @@ func (s *FoldHeadingStack) Hidden() bool {return false}- if n := s.last; nil != n && ast.NodeHeading == n.Type && "1" == n.IALAttr("fold") && s.levels[depth-1] == n.HeadingLevel {+ if n := s.last; nil != n && ast.NodeHeading == n.Type && IsSelfFolded(n) && s.levels[depth-1] == n.HeadingLevel {// 折叠标题自身刚入栈:仅当它还被更浅的折叠标题盖住时才隐藏return 1 < depth}@@ -119,7 +151,7 @@ func collectFoldHiddenNodes(parent *ast.Node, unlinks *[]*ast.Node) {continue}- if n.IsContainerBlock() {+ if ast.NodeDocument == n.Type || n.IsContainerBlock() {collectFoldHiddenNodes(n, unlinks)}}@@ -136,7 +168,7 @@ func IsInFoldedHeading(node, currentHeading *ast.Node) bool {return false}if ast.NodeHeading == heading.Type {- if "1" == heading.IALAttr("heading-fold") || "1" == heading.IALAttr("fold") {+ if IsSelfFolded(heading) {return true}if heading == currentHeading {@@ -147,15 +179,6 @@ func IsInFoldedHeading(node, currentHeading *ast.Node) bool {return IsInFoldedHeading(heading, currentHeading)}-func GetHeadingFold(nodes []*ast.Node) (ret []*ast.Node) {- for _, n := range nodes {- if "1" == n.IALAttr("heading-fold") {- ret = append(ret, n)- }- }- return-}-func GetParentFoldedHeading(node *ast.Node) (parentFoldedHeading *ast.Node) {if nil == node {return@@ -175,7 +198,7 @@ func GetParentFoldedHeading(node *ast.Node) (parentFoldedHeading *ast.Node) {}currentLevel = n.HeadingLevel- if "1" == n.IALAttr("fold") {+ if IsSelfFolded(n) {if ast.NodeHeading != node.Type {parentFoldedHeading = n}diff --git a/kernel/treenode/node.go b/kernel/treenode/node.goindex aaed8a5187..4d51271491 100644--- a/kernel/treenode/node.go+++ b/kernel/treenode/node.go@@ -232,7 +232,7 @@ func CountBlockNodes(node *ast.Node) (ret int) {return ast.WalkContinue}- if "1" == n.IALAttr("fold") {+ if IsSelfFolded(n) {ret++return ast.WalkSkipChildren}