An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Preserve empty paragraphs in database text fields https://github.com/siyuan-note/siyuan/issues/19637
Daniel9e25ce7284df
diff --git a/app/src/protyle/render/av/richText.test.ts b/app/src/protyle/render/av/richText.test.tsindex 9231847392..287263443b 100644--- a/app/src/protyle/render/av/richText.test.ts+++ b/app/src/protyle/render/av/richText.test.ts@@ -550,6 +550,32 @@ describe("attribute view text value creation", () => {});describe("attribute view rich text DOM policy", () => {+ it("preserves leading, consecutive and trailing empty paragraphs across saves", {+ skip: hasDOM && typeof Lute !== "undefined" ? false :+ "The Node test environment does not provide DOM and Lute globals",+ }, async () => {+ Object.assign(globalThis, {NODE_ENV: "test", SIYUAN_VERSION: "test"});+ const richText = await import("./richText");+ for (const paragraphs of [[""], ["", ""], ["", "first", "", "", "last", ""]]) {+ let dom = paragraphs.map(content => '<div data-type="NodeParagraph">' ++ `<div contenteditable="true">${content}</div></div>`).join("");+ let previous: string;+ for (let round = 0; round < 3; round++) {+ const serialized = richText.serializeAVRichTextBlockDOM(dom);+ if (round > 0) {+ assert.equal(serialized.markdown, previous);+ }+ previous = serialized.markdown;+ dom = richText.getAVRichTextBlockDOM(serialized.markdown);+ const template = document.createElement("template");+ template.innerHTML = dom;+ assert.deepEqual(Array.from(template.content.querySelectorAll(+ '[data-type="NodeParagraph"] > [contenteditable="true"]'+ )).map(element => element.textContent), paragraphs);+ }+ }+ });+it("preserves code content and prepares block and inline math for preview rendering", {skip: hasDOM && typeof Lute !== "undefined" ? false :"The Node test environment does not provide DOM and Lute globals",diff --git a/app/src/protyle/render/av/richText.ts b/app/src/protyle/render/av/richText.tsindex 1f5a9dc060..ab0a91e2d8 100644--- a/app/src/protyle/render/av/richText.ts+++ b/app/src/protyle/render/av/richText.ts@@ -239,14 +239,17 @@ export const sanitizeAVRichTextBlockDOM = (blockDOM: string, images = false) =>return (template.innerHTML || "").trim();};-const cleanAVRichTextBlockDOMStructure = (blockDOM: string) => {+const cleanAVRichTextBlockDOMStructure = (blockDOM: string, preserveBlockIDs = false) => {const template = document.createElement("template");template.innerHTML = blockDOM;template.content.querySelectorAll(".protyle-attr, .protyle-icons").forEach((element) => element.remove());template.content.querySelectorAll<HTMLElement>("*").forEach((element) => {- ["data-node-id", "data-node-index", "updated"].forEach((attribute) => {+ (preserveBlockIDs ? ["data-node-index", "updated"] : ["data-node-id", "data-node-index", "updated"]).forEach((attribute) => {element.removeAttribute(attribute);});+ if (preserveBlockIDs && ALLOWED_BLOCK_TYPES.has(element.dataset.type) && !element.dataset.nodeId) {+ element.dataset.nodeId = Lute.NewNodeID();+ }});return (template.innerHTML || "").trim();};@@ -321,7 +324,14 @@ const getAVRichTextPlainContent = (blockDOM: string, lute: Lute) => {export const serializeAVRichTextBlockDOM = (blockDOM: string, lute = getAVRichTextLute(), images = false) => {const sanitizedBlockDOM = sanitizeAVRichTextBlockDOM(blockDOM, images);- const cleanBlockDOM = cleanAVRichTextBlockDOMStructure(sanitizedBlockDOM);+ let cleanBlockDOM = cleanAVRichTextBlockDOMStructure(sanitizedBlockDOM);+ const template = document.createElement("template");+ template.innerHTML = cleanBlockDOM;+ // 空段落依靠块属性列表保留,同时保留相邻块的标识,避免属性被合并到前一段。+ if (Array.from(template.content.querySelectorAll('[data-type="NodeParagraph"]'))+ .some(element => lute.BlockDOM2Md(element.outerHTML).trim() === "")) {+ cleanBlockDOM = cleanAVRichTextBlockDOMStructure(sanitizedBlockDOM, true);+ }const styleBackslashEncoding = createAVRichTextStyleBackslashEncoding(cleanBlockDOM);const protectedBlockDOM = protectAVRichTextStyleBackslashes(cleanBlockDOM, styleBackslashEncoding);const markdown = protectedBlockDOM ?diff --git a/kernel/av/value.go b/kernel/av/value.goindex c7ade76f93..158243c8cc 100644--- a/kernel/av/value.go+++ b/kernel/av/value.go@@ -1391,7 +1391,21 @@ func RenderValueTextRich(tree *parse.Tree) (content string, err error) {}func valueTextRichBlockDOM2Kramdown(luteEngine *lute.Lute, blockDOM string) string {- blockDOM = valueTextRichBlockDOMStructuralAttrs.ReplaceAllString(blockDOM, "")+ // 空段落依靠块属性列表保留,相邻块的标识也必须保留以隔开属性列表。+ preserveBlockIDs := false+ ast.Walk(luteEngine.BlockDOM2Tree(blockDOM).Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeParagraph == node.Type && "" == strings.TrimSpace(strings.ReplaceAll(node.Content(), "\u200b", "")) {+ preserveBlockIDs = true+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ blockDOM = valueTextRichBlockDOMStructuralAttrs.ReplaceAllStringFunc(blockDOM, func(attribute string) string {+ if preserveBlockIDs && strings.HasPrefix(strings.TrimSpace(attribute), "data-node-id=") {+ return attribute+ }+ return ""+ })blockDOM, backslashSentinel, backtickSentinel := protectValueTextRichBlockDOMStyleCharacters(blockDOM)markdown := strings.TrimSpace(luteEngine.BlockDOM2Md(blockDOM))if "" != backtickSentinel {diff --git a/kernel/av/value_text_test.go b/kernel/av/value_text_test.goindex 9b3ea9a3fc..ca502ff92a 100644--- a/kernel/av/value_text_test.go+++ b/kernel/av/value_text_test.go@@ -26,6 +26,37 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+func TestValueTextRichEmptyParagraphs(t *testing.T) {+ for _, paragraphs := range [][]string{{""}, {"", ""}, {"", "first", "", "", "last", ""}} {+ var dom strings.Builder+ for _, content := range paragraphs {+ dom.WriteString(`<div data-node-id="` + ast.NewNodeID() + `" data-type="NodeParagraph"><div contenteditable="true">` + content + `</div></div>`)+ }+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown,+ Content: valueTextRichBlockDOM2Kramdown(newValueTextRichLute(), dom.String())}+ for round := 0; round < 3; round++ {+ before := rich.Content+ tree, err := NormalizeValueTextRich(rich)+ if nil != err {+ t.Fatal(err)+ }+ var actual []string+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeParagraph == node.Type {+ actual = append(actual, strings.TrimRight(node.Content(), "\n"))+ }+ return ast.WalkContinue+ })+ if len(actual) != len(paragraphs) || strings.Join(actual, "|") != strings.Join(paragraphs, "|") {+ t.Fatalf("paragraphs changed: want %q, got %q", paragraphs, actual)+ }+ if before != rich.Content {+ t.Fatalf("normalization changed source: %q != %q", before, rich.Content)+ }+ }+ }+}+func TestValueTextPlainJSONCompatibility(t *testing.T) {const content = "**literal** <tag> ((20240101000000-abcdefg))\nnext"value := &ValueText{}