Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Stabilize database rich-text editor behavior https://github.com/siyuan-note/siyuan/issues/11553

Danielfaec2dafc72a
diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scss
index 58374e03b8..03981f1c0b 100644
--- a/app/src/assets/scss/business/_av.scss
+++ b/app/src/assets/scss/business/_av.scss
@@ -1123,6 +1123,12 @@
font: inherit;
> p,
+ > h1,
+ > h2,
+ > h3,
+ > h4,
+ > h5,
+ > h6,
> blockquote,
> ul,
> ol,
diff --git a/app/src/protyle/lite/fragmentEditor.ts b/app/src/protyle/lite/fragmentEditor.ts
index 19e7291972..0f64eacf4c 100644
--- a/app/src/protyle/lite/fragmentEditor.ts
+++ b/app/src/protyle/lite/fragmentEditor.ts
@@ -3,6 +3,7 @@ import type {App} from "../../index";
import {Constants} from "../../constants";
import {Protyle} from "../index";
import type {ProtyleRuntimeCapabilities} from "../runtimeCapabilities";
+import {removeLoading} from "../ui/initUI";
import {focusBlock} from "../util/selection";
import {invalidateTrackedRanges} from "../util/trackedRange";
@@ -134,6 +135,7 @@ export const mountProtyleLiteFragment = (host: HTMLElement,
} else {
setEmptyContent();
}
+ removeLoading(protyle);
const contentObserver = new MutationObserver(() => {
updateEmptyState();
diff --git a/app/src/protyle/render/av/richText.test.ts b/app/src/protyle/render/av/richText.test.ts
index 57e86c605a..abfc30dc65 100644
--- a/app/src/protyle/render/av/richText.test.ts
+++ b/app/src/protyle/render/av/richText.test.ts
@@ -287,6 +287,9 @@ describe("attribute view text source compatibility", () => {
});
it("uses a strict active-content and interaction policy for previews", () => {
+ for (const tag of ["h1", "h2", "h3", "h4", "h5", "h6"]) {
+ assert.equal(AV_RICH_TEXT_PREVIEW_ALLOWED_TAGS.includes(tag), true);
+ }
for (const tag of ["audio", "embed", "iframe", "img", "object", "script", "style", "video"]) {
assert.equal(AV_RICH_TEXT_PREVIEW_ALLOWED_TAGS.includes(tag), false);
assert.equal(AV_RICH_TEXT_EDITOR_ALLOWED_TAGS.includes(tag), false);
@@ -506,13 +509,14 @@ describe("attribute view text value creation", () => {
});
describe("attribute view rich text DOM policy", () => {
- it("drops unsupported blocks and preserves supported inline marks", {
+ it("preserves supported headings and inline marks while dropping unsupported blocks", {
skip: hasDOM ? false : "The Node test environment does not provide a DOM implementation",
}, async () => {
Object.assign(globalThis, {NODE_ENV: "test", SIYUAN_VERSION: "test"});
const richText = await import("./richText");
const blockDOM = [
'<div data-type="NodeHeading" data-subtype="h2"><div contenteditable="true">heading</div></div>',
+ '<div data-type="NodeHeading" data-subtype="h7"><div contenteditable="true">invalid</div></div>',
'<div data-type="NodeParagraph"><div contenteditable="true">',
'<span data-type="tag">tag</span>',
'<span data-type="file-annotation-ref">annotation</span>',
@@ -529,13 +533,14 @@ describe("attribute view rich text DOM policy", () => {
].join("");
const sanitized = richText.sanitizeAVRichTextBlockDOM(blockDOM);
- assert.match(sanitized, /data-type="NodeParagraph"[^>]*>.*heading/s);
+ assert.match(sanitized, /data-type="NodeHeading"[^>]*data-subtype="h2"[^>]*class="h2"/);
+ assert.doesNotMatch(sanitized, /data-subtype="h7"/);
assert.match(sanitized, /data-type="tag"/);
assert.match(sanitized, /data-type="file-annotation-ref"/);
assert.match(sanitized, /data-type="inline-memo"/);
assert.match(sanitized, /data-type="strong">unstyled strong/);
assert.match(sanitized, /data-type="strong text" style="color: var\(--b3-font-color2\);">styled strong/);
- for (const type of ["NodeHeading", "NodeImage", "NodeTable", "NodeHTMLBlock", "NodeBlockQueryEmbed"]) {
+ for (const type of ["NodeImage", "NodeTable", "NodeHTMLBlock", "NodeBlockQueryEmbed"]) {
assert.doesNotMatch(sanitized, new RegExp(`data-type="${type}"`));
}
assert.doesNotMatch(sanitized, /data-subtype="mermaid"/);
diff --git a/app/src/protyle/render/av/richText.ts b/app/src/protyle/render/av/richText.ts
index 26ed5c1ed2..3d2d6da7d2 100644
--- a/app/src/protyle/render/av/richText.ts
+++ b/app/src/protyle/render/av/richText.ts
@@ -49,6 +49,7 @@ export const AV_RICH_TEXT_CLASS = "av__celltext--rich";
const ALLOWED_BLOCK_TYPES = new Set([
"NodeParagraph",
+ "NodeHeading",
"NodeList",
"NodeListItem",
"NodeBlockquote",
@@ -117,14 +118,15 @@ export const sanitizeAVRichTextBlockDOM = (blockDOM: string) => {
element.remove();
return;
}
- if (ALLOWED_BLOCK_TYPES.has(type)) {
- removeUnsupportedBlockAttributes(element);
- return;
- }
if (type === "NodeHeading") {
- element.dataset.type = "NodeParagraph";
- element.className = "p";
- element.removeAttribute("data-subtype");
+ const subtype = element.dataset.subtype || "";
+ if (!/^h[1-6]$/.test(subtype)) {
+ element.remove();
+ return;
+ }
+ element.className = subtype;
+ }
+ if (ALLOWED_BLOCK_TYPES.has(type)) {
removeUnsupportedBlockAttributes(element);
return;
}
@@ -264,7 +266,8 @@ const getAVRichTextPlainContent = (blockDOM: string, lute: Lute) => {
const template = document.createElement("template");
template.innerHTML = blockDOM;
const blocks = Array.from(template.content.querySelectorAll<HTMLElement>(
- '[data-type="NodeParagraph"], [data-type="NodeCodeBlock"], [data-type="NodeMathBlock"]'
+ '[data-type="NodeParagraph"], [data-type="NodeHeading"], [data-type="NodeCodeBlock"], ' +
+ '[data-type="NodeMathBlock"]'
)).map((element) => lute.BlockDOM2Content(element.outerHTML));
return projectAVRichTextPlainBlocks(blocks, lute.BlockDOM2Content(blockDOM));
};
diff --git a/app/src/protyle/render/av/richTextEditor.ts b/app/src/protyle/render/av/richTextEditor.ts
index e9cc12024e..4193644eb3 100644
--- a/app/src/protyle/render/av/richTextEditor.ts
+++ b/app/src/protyle/render/av/richTextEditor.ts
@@ -5,6 +5,7 @@ import {hintRef, hintSlash} from "../../hint/extend";
import {mountProtyleLiteFragment} from "../../lite/fragmentEditor";
import {highlightRender} from "../highlightRender";
import {mathRender} from "../mathRender";
+import {positionAVRichTextEditor} from "./richTextEditorPosition";
import {
configureAVRichTextLute,
createAVRichTextValue,
@@ -17,6 +18,12 @@ import {
const SAFE_SLASH_IDS = new Set([
"ref",
+ "heading1",
+ "heading2",
+ "heading3",
+ "heading4",
+ "heading5",
+ "heading6",
"list",
"orderedList",
"check",
@@ -76,18 +83,7 @@ const setPanelPosition = (panelElement: HTMLElement, anchorElement: HTMLElement)
panelElement.removeAttribute("style");
return;
}
- const margin = 8;
- const anchorRect = anchorElement.getBoundingClientRect();
- const width = Math.min(Math.max(anchorRect.width, 420), window.innerWidth - margin * 2);
- const maxHeight = Math.max(240, Math.min(480, window.innerHeight - margin * 2));
- const left = Math.min(Math.max(anchorRect.left, margin), window.innerWidth - width - margin);
- const availableBelow = window.innerHeight - anchorRect.bottom - margin;
- const top = availableBelow >= Math.min(maxHeight, 320) ? anchorRect.bottom :
- Math.max(margin, anchorRect.top - maxHeight);
- panelElement.style.left = `${left}px`;
- panelElement.style.top = `${top}px`;
- panelElement.style.width = `${width}px`;
- panelElement.style.maxHeight = `${maxHeight}px`;
+ positionAVRichTextEditor(panelElement, anchorElement);
};
export const destroyAVRichTextEditor = (save = false) => {
@@ -149,6 +145,7 @@ export const openAVRichTextEditor = (options: AVRichTextEditorOptions) => {
protyle.undo.clear();
},
});
+ setPanelPosition(panelElement, options.anchorElement);
const initialMarkdown = serializeAVRichTextBlockDOM(fragment.getBlockHTML()).markdown;
let finished = false;
@@ -157,6 +154,8 @@ export const openAVRichTextEditor = (options: AVRichTextEditorOptions) => {
options.anchorElement.isConnected;
const resize = () => setPanelPosition(panelElement, options.anchorElement);
window.addEventListener("resize", resize);
+ const panelResizeObserver = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(resize);
+ panelResizeObserver?.observe(panelElement);
const ownerObserver = new MutationObserver(() => {
if (!isOwnerConnected()) {
void finish(false);
@@ -186,6 +185,7 @@ export const openAVRichTextEditor = (options: AVRichTextEditorOptions) => {
}
} finally {
ownerObserver.disconnect();
+ panelResizeObserver?.disconnect();
window.removeEventListener("resize", resize);
fragment.destroy();
maskElement.remove();
diff --git a/app/src/protyle/render/av/richTextEditorPosition.test.ts b/app/src/protyle/render/av/richTextEditorPosition.test.ts
new file mode 100644
index 0000000000..d1f8f56161
--- /dev/null
+++ b/app/src/protyle/render/av/richTextEditorPosition.test.ts
@@ -0,0 +1,112 @@
+import * as assert from "node:assert/strict";
+import {after, before, describe, it} from "node:test";
+import {positionAVRichTextEditor} from "./richTextEditorPosition";
+
+interface RectOptions {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+}
+
+const createRect = (options: RectOptions): DOMRect => ({
+ x: options.left,
+ y: options.top,
+ left: options.left,
+ top: options.top,
+ width: options.width,
+ height: options.height,
+ right: options.left + options.width,
+ bottom: options.top + options.height,
+ toJSON: () => ({}),
+});
+
+const createPanel = (height: number) => {
+ const style: Record<string, string> = {};
+ const panel = {
+ dataset: {} as DOMStringMap,
+ style,
+ height,
+ getBoundingClientRect() {
+ return createRect({
+ left: parseFloat(style.left) || 0,
+ top: parseFloat(style.top) || 0,
+ width: parseFloat(style.width) || 0,
+ height: this.height,
+ });
+ },
+ };
+ return panel;
+};
+
+const createAnchor = (options: RectOptions) => ({
+ getBoundingClientRect: () => createRect(options),
+}) as HTMLElement;
+
+describe("attribute view rich-text editor positioning", () => {
+ const windowDescriptor = Object.getOwnPropertyDescriptor(globalThis, "window");
+ const documentDescriptor = Object.getOwnPropertyDescriptor(globalThis, "document");
+
+ before(() => {
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {innerWidth: 1066, innerHeight: 540},
+ });
+ Object.defineProperty(globalThis, "document", {
+ configurable: true,
+ value: {getElementById: (id: string) => id === "sidebar" ? {} : null},
+ });
+ });
+
+ after(() => {
+ if (windowDescriptor) {
+ Object.defineProperty(globalThis, "window", windowDescriptor);
+ } else {
+ delete (globalThis as {window?: Window}).window;
+ }
+ if (documentDescriptor) {
+ Object.defineProperty(globalThis, "document", documentDescriptor);
+ } else {
+ delete (globalThis as {document?: Document}).document;
+ }
+ });
+
+ it("places the measured panel directly above a low cell", () => {
+ const panel = createPanel(240);
+ const anchor = createAnchor({left: 551, top: 412, width: 199, height: 32});
+
+ positionAVRichTextEditor(panel as unknown as HTMLElement, anchor);
+
+ assert.equal(panel.style.left, "551px");
+ assert.equal(panel.style.top, "172px");
+ assert.equal(panel.style.width, "420px");
+ assert.equal(panel.style.maxHeight, "480px");
+ assert.equal(panel.getBoundingClientRect().bottom, anchor.getBoundingClientRect().top);
+ });
+
+ it("places the panel directly below a cell when it fits", () => {
+ Object.assign(window, {innerWidth: 1000, innerHeight: 800});
+ const panel = createPanel(240);
+ const anchor = createAnchor({left: 100, top: 100, width: 150, height: 32});
+
+ positionAVRichTextEditor(panel as unknown as HTMLElement, anchor);
+
+ assert.equal(panel.style.top, "132px");
+ assert.equal(panel.getBoundingClientRect().top, anchor.getBoundingClientRect().bottom);
+ });
+
+ it("keeps horizontal margins and follows changes to the measured panel height", () => {
+ Object.assign(window, {innerWidth: 600, innerHeight: 540});
+ const panel = createPanel(240);
+ const anchor = createAnchor({left: 551, top: 412, width: 199, height: 32});
+
+ positionAVRichTextEditor(panel as unknown as HTMLElement, anchor);
+ assert.equal(panel.style.left, "172px");
+ assert.equal(panel.style.top, "172px");
+
+ panel.height = 300;
+ positionAVRichTextEditor(panel as unknown as HTMLElement, anchor);
+ assert.equal(panel.style.top, "112px");
+ assert.equal(panel.getBoundingClientRect().bottom, anchor.getBoundingClientRect().top);
+ });
+});
diff --git a/app/src/protyle/render/av/richTextEditorPosition.ts b/app/src/protyle/render/av/richTextEditorPosition.ts
new file mode 100644
index 0000000000..bfd36556ac
--- /dev/null
+++ b/app/src/protyle/render/av/richTextEditorPosition.ts
@@ -0,0 +1,14 @@
+import {setPosition} from "../../../util/setPosition";
+
+export const AV_RICH_TEXT_EDITOR_MARGIN = 8;
+
+export const positionAVRichTextEditor = (panelElement: HTMLElement, anchorElement: HTMLElement) => {
+ const anchorRect = anchorElement.getBoundingClientRect();
+ const width = Math.min(Math.max(anchorRect.width, 420), window.innerWidth - AV_RICH_TEXT_EDITOR_MARGIN * 2);
+ const maxHeight = Math.max(240, Math.min(480, window.innerHeight - AV_RICH_TEXT_EDITOR_MARGIN * 2));
+ const left = Math.min(Math.max(anchorRect.left, AV_RICH_TEXT_EDITOR_MARGIN),
+ window.innerWidth - width - AV_RICH_TEXT_EDITOR_MARGIN);
+ panelElement.style.width = `${width}px`;
+ panelElement.style.maxHeight = `${maxHeight}px`;
+ setPosition(panelElement, left, anchorRect.bottom, anchorRect.height, AV_RICH_TEXT_EDITOR_MARGIN);
+};
diff --git a/app/src/protyle/render/av/richTextValue.ts b/app/src/protyle/render/av/richTextValue.ts
index cd3b211fa4..8b62f99f34 100644
--- a/app/src/protyle/render/av/richTextValue.ts
+++ b/app/src/protyle/render/av/richTextValue.ts
@@ -3,8 +3,8 @@ import {getInlineFontFamilyName, getInlineFontFamilyStyle} from "../../toolbar/f
export const AV_RICH_TEXT_SPEC = 1 as const;
export const AV_RICH_TEXT_FORMAT = "kramdown" as const;
export const AV_RICH_TEXT_PREVIEW_ALLOWED_TAGS = [
- "a", "blockquote", "br", "code", "div", "em", "input", "kbd", "li", "mark", "ol", "p", "pre",
- "s", "span", "strong", "sub", "sup", "u", "ul",
+ "a", "blockquote", "br", "code", "div", "em", "h1", "h2", "h3", "h4", "h5", "h6", "input", "kbd",
+ "li", "mark", "ol", "p", "pre", "s", "span", "strong", "sub", "sup", "u", "ul",
];
export const AV_RICH_TEXT_PREVIEW_ALLOWED_ATTRIBUTES = [
"checked", "class", "data-content", "data-href", "data-id", "data-language", "data-subtype", "data-type",
diff --git a/kernel/av/value.go b/kernel/av/value.go
index b268ac9a7e..401b343d69 100644
--- a/kernel/av/value.go
+++ b/kernel/av/value.go
@@ -654,7 +654,7 @@ func isAllowedValueTextRichNode(node *ast.Node) bool {
return false
}
switch node.Type {
- case ast.NodeDocument, ast.NodeParagraph,
+ case ast.NodeDocument, ast.NodeParagraph, ast.NodeHeading, ast.NodeHeadingC8hMarker,
ast.NodeBlockquote, ast.NodeBlockquoteMarker,
ast.NodeList, ast.NodeListItem, ast.NodeTaskListItemMarker,
ast.NodeCodeBlockFenceOpenMarker, ast.NodeCodeBlockFenceCloseMarker, ast.NodeCodeBlockCode,
@@ -2150,7 +2150,7 @@ func valueTextRichPlainContent(tree *parse.Tree) string {
return ast.WalkContinue
}
switch node.Type {
- case ast.NodeParagraph, ast.NodeCodeBlock, ast.NodeMathBlock:
+ case ast.NodeParagraph, ast.NodeHeading, ast.NodeCodeBlock, ast.NodeMathBlock:
blocks = append(blocks, strings.TrimRight(node.Content(), "\n"))
return ast.WalkSkipChildren
}
diff --git a/kernel/av/value_text_test.go b/kernel/av/value_text_test.go
index 3340fcb452..a4385aa80e 100644
--- a/kernel/av/value_text_test.go
+++ b/kernel/av/value_text_test.go
@@ -99,6 +99,7 @@ func TestValueTextRichMultiBlockPlainProjection(t *testing.T) {
expected string
}{
{"paragraphs", "first\n\nsecond", "first\nsecond"},
+ {"headings", "# first\n\n###### second", "first\nsecond"},
{"list", "- first\n- second", "first\nsecond"},
{"task list", "- [ ] todo\n- [x] done", "todo\ndone"},
{"blockquote", "> first\n>\n> second", "first\nsecond"},
@@ -121,6 +122,7 @@ func TestValueTextRichMultiBlockPlainProjection(t *testing.T) {
func TestValueTextRichASTWhitelist(t *testing.T) {
allowed := []string{
"",
+ "# heading\n\n###### small heading",
"plain **strong** *emphasis* ~~strike~~ ==mark== `code` $x$ [link](https://example.com) " +
"((20240101000000-abcdefg \"reference\"))",
"<u>underline</u>",
@@ -153,7 +155,6 @@ func TestValueTextRichASTWhitelist(t *testing.T) {
}
rejected := []string{
- "# heading",
"![image](assets/image.png)",
"| a | b |\n| --- | --- |\n| 1 | 2 |",
"<div>HTML</div>",
@@ -175,6 +176,23 @@ func TestValueTextRichASTWhitelist(t *testing.T) {
}
}
+func TestValueTextRichHeadingRoundTrip(t *testing.T) {
+ rich := &ValueTextRich{
+ Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: "## heading",
+ }
+ tree, err := NormalizeValueTextRich(rich)
+ if nil != err {
+ t.Fatal(err)
+ }
+ if "## heading" != rich.Content {
+ t.Fatalf("heading syntax was not preserved: %q", rich.Content)
+ }
+ if nil == tree.Root.FirstChild || ast.NodeHeading != tree.Root.FirstChild.Type ||
+ 2 != tree.Root.FirstChild.HeadingLevel {
+ t.Fatalf("heading structure was not preserved: %v", tree.Root.FirstChild)
+ }
+}
+
func TestValueTextRichEmojiAliasRemainsLiteral(t *testing.T) {
rich := &ValueTextRich{
Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: ":siyuan: 😀",