Skip to content

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

:sparkles: Support code block settings in table cells and mind maps https://github.com/siyuan-note/siyuan/issues/19717

Daniele246b5f892fb
diff --git a/app/src/assets/scss/protyle/_protyle.scss b/app/src/assets/scss/protyle/_protyle.scss
index a1e4f8bf85..19f2ef8942 100644
--- a/app/src/assets/scss/protyle/_protyle.scss
+++ b/app/src/assets/scss/protyle/_protyle.scss
@@ -8,6 +8,22 @@
display: none;
}
+.protyle-lite-fragment .protyle-action__copy {
+ border-radius: var(--b3-border-radius);
+}
+
+.table__cell-editor,
+.list-mindmap__editor {
+ .code-block .protyle-action__menu {
+ display: block;
+ }
+
+ .code-block .protyle-action__copy {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+ }
+}
+
.protyle-scroll {
--b3-dynamicscroll-width: 200px;
position: absolute;
@@ -932,16 +948,18 @@
// 跟随单元格的可用宽度,保证预览与编辑使用相同的折行边界。
width: auto;
max-width: 100%;
+}
- .code-block {
- // 预览与编辑共用最小宽度,为代码内容和顶部操作区保留空间。
- min-width: 200px;
+.table__cell-rich .code-block,
+.table__cell-editor .code-block,
+.list-mindmap__content .code-block {
+ // 预览与编辑共用最小宽度,为代码内容和顶部操作区保留空间。
+ min-width: 200px;
- .protyle-action__language {
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
+ .protyle-action__language {
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
}
}
diff --git a/app/src/protyle/lite/codeActions.ts b/app/src/protyle/lite/codeActions.ts
new file mode 100644
index 0000000000..b565134cce
--- /dev/null
+++ b/app/src/protyle/lite/codeActions.ts
@@ -0,0 +1,71 @@
+import {MenuItem} from "../../menus/Menu";
+import {showMessage} from "../../dialog/message";
+import {isMobile} from "../../util/functions";
+import {highlightRender} from "../render/highlightRender";
+import {writeText} from "../util/compatibility";
+import {nbsp2space, removeZWJ} from "../util/normalizeText";
+
+export const getLiteCodeMenuItems = (node: Element, update: (attribute: string, value: string) => void): IMenu[] => {
+ const editor = window.siyuan.config.editor;
+ return [
+ {attribute: "linewrap", label: "md31", fallback: editor.codeLineWrap},
+ {attribute: "ligatures", label: "md2", fallback: editor.codeLigatures},
+ {attribute: "linenumber", label: "md27", fallback: editor.codeSyntaxHighlightLineNum},
+ ].map(({attribute, label, fallback}) => {
+ const value = node.getAttribute(attribute);
+ const checked = value === "true" || (value !== "false" && fallback);
+ return {
+ id: label,
+ label: window.siyuan.languages[label],
+ checked,
+ click: () => update(attribute, String(!checked)),
+ };
+ });
+};
+
+export const bindLiteCodeActions = (host: HTMLElement, protyle: IProtyle, options: {
+ signal: AbortSignal,
+ canEdit: () => boolean,
+ beforeChange?: () => void,
+ onChange: () => void,
+}) => {
+ host.addEventListener("click", event => {
+ const button = event.target instanceof Element ?
+ event.target.closest(".protyle-action__copy, .protyle-action__menu") : null;
+ const code = button?.closest('.code-block[data-type="NodeCodeBlock"]');
+ const content = code?.querySelector(".hljs");
+ if (!content || !protyle.wysiwyg.element.contains(code)) {
+ return;
+ }
+ // 轻量编辑器隔离外层点击事件,代码操作在内部处理。
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ if (button.classList.contains("protyle-action__copy")) {
+ writeText(removeZWJ(nbsp2space(content.textContent.replace(/\n$/, ""))));
+ showMessage(window.siyuan.languages.copied, 2000);
+ return;
+ }
+ if (!options.canEdit()) {
+ return;
+ }
+ const menu = window.siyuan.menus.menu;
+ menu.remove();
+ getLiteCodeMenuItems(code, (attribute, value) => {
+ if (options.signal.aborted || !options.canEdit() || !protyle.wysiwyg.element.contains(code)) {
+ return;
+ }
+ options.beforeChange?.();
+ code.setAttribute(attribute, value);
+ // 属性变化不会触发片段的正文观察器,需显式交由宿主事务保存。
+ options.onChange();
+ content.removeAttribute("data-render");
+ highlightRender(code);
+ }).forEach(item => menu.append(new MenuItem(item).element));
+ if (isMobile()) {
+ menu.fullscreen();
+ } else {
+ const rect = button.getBoundingClientRect();
+ menu.popup({x: rect.left, y: rect.top, isLeft: true});
+ }
+ }, {capture: true, signal: options.signal});
+};
diff --git a/app/src/protyle/render/av/richText.ts b/app/src/protyle/render/av/richText.ts
index 3b54b54d2a..9a5417ec98 100644
--- a/app/src/protyle/render/av/richText.ts
+++ b/app/src/protyle/render/av/richText.ts
@@ -192,7 +192,9 @@ export const sanitizeAVRichTextBlockDOM = (blockDOM: string, images = false) =>
const name = attribute.name.toLowerCase();
const imageAttribute = images && ["src", "data-src", "alt", "title", "loading"].includes(name) &&
(element.tagName === "IMG" || element.classList.contains("img"));
- if ((!AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES.includes(name) && !imageAttribute) ||
+ const codeAttribute = images && element.dataset.type === "NodeCodeBlock" &&
+ ["linewrap", "ligatures", "linenumber"].includes(name) && ["true", "false"].includes(attribute.value);
+ if ((!AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES.includes(name) && !imageAttribute && !codeAttribute) ||
name === "xlink:href" && !attribute.value.startsWith("#icon")) {
element.removeAttribute(attribute.name);
}
@@ -334,8 +336,10 @@ export const serializeAVRichTextBlockDOM = (blockDOM: string, lute = getAVRichTe
const hasEmptyParagraph = paragraphs.some(element => lute.BlockDOM2Md(element.outerHTML).trim() === "");
const singleEmptyParagraph = template.content.children.length === 1 &&
template.content.firstElementChild === paragraphs[0] && hasEmptyParagraph;
- // 多块内容中的空段落依靠块属性列表保留,同时保留相邻块的标识,避免属性被合并到前一段。
- if (hasEmptyParagraph && !singleEmptyParagraph) {
+ const hasCodeSettings = images && !!template.content.querySelector(
+ '[data-type="NodeCodeBlock"]:is([linewrap], [ligatures], [linenumber])');
+ // 空段落和代码设置依靠块属性列表保留,同时保留相邻块的标识,避免属性被合并到前一段。
+ if ((hasEmptyParagraph && !singleEmptyParagraph) || hasCodeSettings) {
cleanBlockDOM = cleanAVRichTextBlockDOMStructure(sanitizedBlockDOM, true);
}
const styleBackslashEncoding = createAVRichTextStyleBackslashEncoding(cleanBlockDOM);
diff --git a/app/src/protyle/render/listMindmap/editor.ts b/app/src/protyle/render/listMindmap/editor.ts
index de8e01ae71..db8d49c218 100644
--- a/app/src/protyle/render/listMindmap/editor.ts
+++ b/app/src/protyle/render/listMindmap/editor.ts
@@ -4,6 +4,7 @@ import {isMobile} from "../../../util/functions";
import {hintRef, hintSlash} from "../../hint/extend";
import {registerBuiltinSlashHint} from "../../hint/builtinSlash";
import {mountProtyleLiteFragment} from "../../lite/fragmentEditor";
+import {bindLiteCodeActions} from "../../lite/codeActions";
import {setMobileToolbarUndo} from "../../lite/mobileToolbar";
import {getDefaultToolbar} from "../../toolbar/defaults";
import {hideElements} from "../../ui/hideElements";
@@ -231,6 +232,14 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
};
setMobileToolbarUndo(fragment.protyle, owner, undo);
const signal = events.signal;
+ bindLiteCodeActions(host, fragment.protyle, {
+ signal,
+ canEdit: () => !finished && !closing && options.canEdit(),
+ onChange: () => {
+ changed = true;
+ void commit();
+ },
+ });
["beforeinput", "input", "compositionstart", "compositionupdate", "compositionend", "copy", "cut", "paste",
"pointerdown", "pointerup", "pointermove", "mousedown", "mouseup", "mousemove", "click", "dblclick",
"contextmenu", "dragstart", "dragover", "drop", "focusin", "focusout", "keyup"]
diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.ts
index 7e89a1a389..a2a2fb014a 100644
--- a/app/src/protyle/render/listMindmap/model.test.ts
+++ b/app/src/protyle/render/listMindmap/model.test.ts
@@ -377,6 +377,32 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
check.equal(edited.contentBlocks[2].dataset.nodeId, added.dataset.nodeId);
check.equal(editable.element.querySelector(':scope > [data-type="NodeList"]'), childList);
check.equal(childList.outerHTML, childHTML);
+ const codeSettingHolder = document.createElement("div");
+ codeSettingHolder.innerHTML = lute.Md2BlockDOM("- Parent\n\n ```js\n x\n ```\n");
+ const codeSettingList = codeSettingHolder.firstElementChild as HTMLElement;
+ const codeSettingNode = api.readListMindmap(codeSettingList).root;
+ const codeSettingBlocks: HTMLElement[] = codeSettingNode.contentBlocks.map((block: HTMLElement) =>
+ block.cloneNode(true) as HTMLElement);
+ const settingCode = codeSettingBlocks.find(block => block.dataset.type === "NodeCodeBlock");
+ check.ok(settingCode);
+ const codeSettingID = settingCode.dataset.nodeId;
+ const oldCodeSettings = codeSettingList.outerHTML;
+ for (const [name, value] of [["linewrap", "false"], ["ligatures", "true"], ["linenumber", "false"]]) {
+ settingCode.setAttribute(name, value);
+ }
+ check.equal(api.replaceListMindmapContent(codeSettingList, codeSettingNode.id,
+ codeSettingBlocks.map(block => block.outerHTML).join("")), true);
+ const newCodeSettings = codeSettingList.outerHTML;
+ for (const html of [newCodeSettings, oldCodeSettings, newCodeSettings]) {
+ const roundTrip = document.createElement("div");
+ roundTrip.innerHTML = lute.Md2BlockDOM(lute.BlockDOM2Md(html));
+ const restoredCode = roundTrip.querySelector(`[data-node-id="${codeSettingID}"]`);
+ check.ok(restoredCode, "code settings keep the source block identity");
+ for (const [name, value] of [["linewrap", "false"], ["ligatures", "true"], ["linenumber", "false"]]) {
+ check.equal(restoredCode.getAttribute(name), html === oldCodeSettings ? null : value,
+ "source snapshots restore code settings through undo and redo");
+ }
+ }
const nestedTaskHolder = document.createElement("div");
lute.SetDataTask(true);
nestedTaskHolder.innerHTML = lute.Md2BlockDOM("- Node\n\n > - [ ] Nested task\n");
diff --git a/app/src/protyle/render/tableCellRichEditor.ts b/app/src/protyle/render/tableCellRichEditor.ts
index 6eec3bb228..286622b911 100644
--- a/app/src/protyle/render/tableCellRichEditor.ts
+++ b/app/src/protyle/render/tableCellRichEditor.ts
@@ -26,8 +26,7 @@ import {getTableCellEditorLute} from "../util/tableCellRichLute";
import {setTableCellRichContext} from "../util/tableCellRichContext";
import {updateOutlineCurrentBlock} from "../util/outlineBlock";
import {canEnterCodeBlock} from "../wysiwyg/codeBlockEnter";
-import {writeText} from "../util/compatibility";
-import {nbsp2space, removeZWJ} from "../util/normalizeText";
+import {bindLiteCodeActions} from "../lite/codeActions";
let activeEditor: {cell: Element, finish: () => void} | undefined;
@@ -287,18 +286,6 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem
setMobileToolbarUndo(fragment.protyle, owner, undoCell);
setTableCellRichContext(fragment.protyle, {owner, cell, finish});
const signal = controller.signal;
- host.addEventListener("click", event => {
- const button = event.target instanceof Element ? event.target.closest(".protyle-action__copy") : null;
- if (!button || !fragment.wysiwyg.contains(button)) {
- return;
- }
- // 单元格隔离外层点击事件,代码复制需在编辑器内部完成。
- const text = button.parentElement.nextElementSibling.textContent.replace(/\n$/, "");
- writeText(removeZWJ(nbsp2space(text)));
- showMessage(window.siyuan.languages.copied, 2000);
- event.preventDefault();
- event.stopImmediatePropagation();
- }, {capture: true, signal});
bindTableCellRichDrag(owner, cell, fragment.wysiwyg, finish, signal,
target => openTableCellRichEditor(owner, target));
const captureBeforeChange = () => {
@@ -307,6 +294,12 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem
}
};
host.addEventListener("beforeinput", captureBeforeChange, {capture: true, signal});
+ bindLiteCodeActions(host, fragment.protyle, {
+ signal,
+ canEdit: () => !finished && !owner.disabled,
+ beforeChange: captureBeforeChange,
+ onChange: commit,
+ });
host.addEventListener("pointerdown", event => {
captureBeforeChange();
if (fragment.wysiwyg.contains(event.target as Node)) {
diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.ts
index 8644003c62..727ee96398 100644
--- a/app/src/protyle/util/tableCellRichLute.test.ts
+++ b/app/src/protyle/util/tableCellRichLute.test.ts
@@ -256,8 +256,32 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
let bubbled = 0;
Object.assign(window.siyuan, {languages: {copied: "Copied"}});
const copyController = new AbortController();
+ let canEditCode = true;
+ let menuItems: IMenu[] = [];
+ let menuShown = 0;
+ let mobileMenuShown = 0;
+ let mobileCodeMenu = false;
+ let updates = 0;
+ let oldCode: ReturnType<typeof api.serializeTableCellRich>;
+ const settingCell = document.createElement("td");
+ Object.assign(window.siyuan, {menus: {menu: {
+ remove: () => { menuItems = []; }, append: () => {}, popup: () => { menuShown++; },
+ fullscreen: () => { mobileMenuShown++; },
+ }}});
const copyDependencies = {
host, fragment, signal: copyController.signal,
+ canEdit: () => canEditCode,
+ beforeChange: () => { oldCode = api.serializeTableCellRich(wysiwyg.innerHTML); },
+ commit: () => {
+ updates++;
+ api.updateTableCellEditingValue(settingCell, api.serializeTableCellRich(wysiwyg.innerHTML));
+ },
+ isMobile: () => mobileCodeMenu,
+ highlightRender: () => {},
+ MenuItem: class {
+ element = document.createElement("button");
+ constructor(item: IMenu) { menuItems.push(item); }
+ },
writeText: (text: string) => copied.push(text),
showMessage: (text: string) => {
check.equal(text, "Copied");
@@ -280,9 +304,50 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
check.equal(copied.length, 6);
check.equal(messages, 6);
check.equal(bubbled, 0, "copy stays inside the cell editor");
+ Object.assign(window.siyuan.config.editor, {codeLineWrap: true, codeLigatures: false, codeSyntaxHighlightLineNum: true});
+ const settingsBody = "a | b\n\n<test> & c\n";
+ wysiwyg.innerHTML = base.Md2BlockDOM("```js\n" + settingsBody + "```");
+ const defaults = [true, false, true];
+ for (const [index, attribute] of ["linewrap", "ligatures", "linenumber"].entries()) {
+ wysiwyg.querySelector(".protyle-action__menu use").dispatchEvent(new MouseEvent("click", {bubbles: true}));
+ check.equal(menuItems.length, 3);
+ check.equal(menuItems[index].checked, defaults[index]);
+ menuItems[index].click(document.createElement("button"), new MouseEvent("click"));
+ wysiwyg.innerHTML = api.getTableCellRichBlockDOM(settingCell);
+ check.equal(wysiwyg.firstElementChild.getAttribute(attribute), String(!defaults[index]));
+ check.equal(wysiwyg.querySelector('.hljs [contenteditable="true"]').textContent, settingsBody);
+ check.equal(api.serializeTableCellRich(wysiwyg.innerHTML).markdown,
+ api.serializeTableCellRich(api.getTableCellRichBlockDOM(settingCell)).markdown);
+ const redo = settingCell.getAttribute("data-sy-table-cell-rich");
+ api.updateTableCellEditingValue(settingCell, oldCode);
+ const undoHolder = document.createElement("div");
+ undoHolder.innerHTML = api.getTableCellRichBlockDOM(settingCell);
+ check.equal(undoHolder.firstElementChild.hasAttribute(attribute), false);
+ settingCell.setAttribute("data-sy-table-cell-rich", redo);
+ check.equal(api.getTableCellRichBlockDOM(settingCell), wysiwyg.innerHTML);
+ }
+ check.equal(updates, 3, "each setting explicitly commits through the host");
+ canEditCode = false;
+ wysiwyg.querySelector(".protyle-action__menu").dispatchEvent(new MouseEvent("click", {bubbles: true}));
+ check.equal(menuShown, 3, "read-only editors cannot open the settings menu");
+ menuItems[0].click(document.createElement("button"), new MouseEvent("click"));
+ check.equal(updates, 3, "stale menu callbacks cannot change a read-only editor");
+ canEditCode = true;
+ mobileCodeMenu = true;
+ wysiwyg.querySelector(".protyle-action__menu").dispatchEvent(new MouseEvent("click", {bubbles: true}));
+ check.equal(mobileMenuShown, 1, "mobile opens the fullscreen menu");
+ check.equal(menuShown, 3);
+ wysiwyg.firstElementChild.setAttribute("linewrap", "invalid");
+ const cleanCode = document.createElement("div");
+ cleanCode.innerHTML = api.sanitizeAVRichTextBlockDOM(wysiwyg.innerHTML, true);
+ check.equal(cleanCode.firstElementChild.hasAttribute("linewrap"), false);
+ cleanCode.innerHTML = api.sanitizeAVRichTextBlockDOM(wysiwyg.innerHTML);
+ check.equal(cleanCode.firstElementChild.hasAttribute("ligatures"), false);
copyController.abort();
wysiwyg.querySelector(".protyle-action__copy").dispatchEvent(new MouseEvent("click", {bubbles: true}));
check.equal(copied.length, 6, "closing the editor removes the copy handler");
+ menuItems[0].click(document.createElement("button"), new MouseEvent("click"));
+ check.equal(updates, 3, "closing the editor invalidates menu callbacks");
const selectionDependencies = {getContenteditableElement, isNotEditBlock: () => false, revealTabsForTarget: () => {}};
const selectionAPI = new Function(...Object.keys(selectionDependencies), selectionSource +
"\nreturn {captureRichCellSelection, captureRichCellSelectionAtPoint, restoreRichCellSelection, focusByOffset, getSelectionOffset};")(
@@ -390,9 +455,8 @@ test("table cells insert code through slash and Enter without losing soft breaks
const start = editor.indexOf('host.addEventListener("keydown", event => {');
const end = editor.indexOf("}, {capture: true, signal});", start) + "}, {capture: true, signal});".length;
const keydownSource = compile(editor.substring(start, end));
- const copyStart = editor.indexOf('host.addEventListener("click", event => {');
- const copyEnd = editor.indexOf("}, {capture: true, signal});", copyStart) + "}, {capture: true, signal});".length;
- const copySource = compile(read("normalizeText.ts") + "\n" + editor.substring(copyStart, copyEnd));
+ const copySource = compile(read("normalizeText.ts")) + "\n" + compile(read("../lite/codeActions.ts")) +
+ "\nbindLiteCodeActions(host, fragment.protyle, {signal, canEdit, beforeChange, onChange: commit});";
const selectionSource = compile(read("selection.ts")) + "\n" + compile(read("tableCellRichSelection.ts"));
const highlightSource = compile(read("../render/highlightRender.ts"));
const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-table-cell-code-test-"));
diff --git a/kernel/av/table_cell_rich_test.go b/kernel/av/table_cell_rich_test.go
new file mode 100644
index 0000000000..187cb5199b
--- /dev/null
+++ b/kernel/av/table_cell_rich_test.go
@@ -0,0 +1,60 @@
+package av
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+)
+
+func TestTableCellRichCodeSettings(t *testing.T) {
+ for _, attribute := range []string{"linewrap", "linenumber", "ligatures"} {
+ for _, value := range []string{"true", "false"} {
+ t.Run(attribute+"/"+value, func(t *testing.T) {
+ source := "before\n\n```go\na | b\n```\n{: id=\"20260921000000-code001\" " + attribute + "=\"" + value + "\"}\n\nafter"
+ rich := &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
+ for pass := 0; pass < 3; pass++ {
+ tree, err := ParseTableCellRich(rich)
+ if err != nil {
+ t.Fatal(err)
+ }
+ codes := tree.Root.ChildrenByType(ast.NodeCodeBlock)
+ if len(codes) != 1 || codes[0].IALAttr(attribute) != value || codes[0].ChildByType(ast.NodeCodeBlockCode).TokensStr() != "a | b\n" {
+ t.Fatalf("code setting or content changed: %s", rich.Content)
+ }
+ content, err := RenderTableCellRich(tree)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(content, "before") || !strings.Contains(content, "after") || pass > 0 && content != rich.Content {
+ t.Fatalf("table source is not stable: %q != %q", content, rich.Content)
+ }
+ rich.Content = content
+ }
+ if _, err := ParseValueTextRich(&ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: source}); err == nil {
+ t.Fatal("table code settings must not expand the database rich text whitelist")
+ }
+ })
+ }
+ }
+}
+
+func TestTableCellRichRejectsInvalidCodeSettings(t *testing.T) {
+ for _, source := range []string{
+ "```go\ncode\n```\n{: id=\"20260921000000-code001\" linewrap=\"invalid\"}",
+ "```go\ncode\n```\n{: id=\"20260921000000-code001\" ligatures=\"TRUE\"}",
+ "```go\ncode\n```\n{: id=\"20260921000000-code001\" linenumber=\"1\"}",
+ "```go\ncode\n```\n{: id=\"20260921000000-code001\" linewrap=\"true\" custom-other=\"value\"}",
+ "paragraph\n{: id=\"20260921000000-code001\" linewrap=\"true\"}",
+ "# heading\n{: id=\"20260921000000-code001\" linenumber=\"false\"}",
+ "```mermaid\ngraph TD\n```\n{: id=\"20260921000000-code001\" linewrap=\"true\"}",
+ } {
+ rich := &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
+ if _, err := ParseTableCellRich(rich); err == nil {
+ t.Fatalf("accepted unsupported code attributes: %s", source)
+ }
+ if rich.Content != source {
+ t.Fatal("rejected source must remain unchanged")
+ }
+ }
+}
diff --git a/kernel/av/value.go b/kernel/av/value.go
index 94c57845ab..d981260a0b 100644
--- a/kernel/av/value.go
+++ b/kernel/av/value.go
@@ -603,7 +603,11 @@ func validateValueTextRichTreeWithImages(tree *parse.Tree, images bool) (err err
if !entering {
return ast.WalkContinue
}
- if !isAllowedValueTextRichNode(node) && !(images && isAllowedTableCellRichImageNode(node)) {
+ allowed := isAllowedValueTextRichNode(node)
+ if images && ast.NodeKramdownBlockIAL == node.Type {
+ allowed = isAllowedValueTextRichBlockIAL(node, true)
+ }
+ if !allowed && !(images && isAllowedTableCellRichImageNode(node)) {
err = fmt.Errorf("unsupported attribute view rich text node [%s]", node.Type.String())
return ast.WalkStop
}
@@ -701,7 +705,7 @@ func isAllowedValueTextRichNode(node *ast.Node) bool {
case ast.NodeCodeBlock, ast.NodeCodeBlockFenceInfoMarker:
return !isValueTextRichExecutableCodeFence(node.CodeBlockInfo)
case ast.NodeKramdownBlockIAL:
- return isAllowedValueTextRichBlockIAL(node)
+ return isAllowedValueTextRichBlockIAL(node, false)
case ast.NodeKramdownSpanIAL:
return isAllowedValueTextRichSpanIAL(node)
case ast.NodeTextMark:
@@ -1300,7 +1304,7 @@ func normalizeValueTextRichTreeStyles(tree *parse.Tree) (err error) {
return
}
-func isAllowedValueTextRichBlockIAL(node *ast.Node) bool {
+func isAllowedValueTextRichBlockIAL(node *ast.Node, codeSettings bool) bool {
ial := parse.Tokens2IAL(node.Tokens)
if 1 > len(ial) {
return false
@@ -1324,6 +1328,12 @@ func isAllowedValueTextRichBlockIAL(node *ast.Node) bool {
if "doc" != attr[1] {
return false
}
+ case "linewrap", "ligatures", "linenumber":
+ // 普通表格的代码设置仅允许布尔值,且必须属于紧邻的代码块。
+ if !codeSettings || nil == node.Previous || ast.NodeCodeBlock != node.Previous.Type ||
+ ("true" != attr[1] && "false" != attr[1]) || node.Previous.IALAttr(attr[0]) != attr[1] {
+ return false
+ }
default:
return false
}
@@ -1403,11 +1413,15 @@ func valueTextRichBlockDOM2Kramdown(luteEngine *lute.Lute, blockDOM string) stri
}
}
}
- // 多块内容中的空段落依靠块属性列表保留,相邻块的标识也必须保留以隔开属性列表。
+ // 空段落和代码设置依靠块属性列表保留,相邻块的标识也必须保留以隔开属性列表。
preserveBlockIDs := false
ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
- if entering && ast.NodeParagraph == node.Type && "" == strings.TrimSpace(strings.ReplaceAll(node.Content(), "\u200b", "")) {
- preserveBlockIDs = !singleEmptyParagraph
+ if !entering {
+ return ast.WalkContinue
+ }
+ if ast.NodeParagraph == node.Type && !singleEmptyParagraph && "" == strings.TrimSpace(strings.ReplaceAll(node.Content(), "\u200b", "")) ||
+ ast.NodeCodeBlock == node.Type && ("" != node.IALAttr("linewrap") || "" != node.IALAttr("ligatures") || "" != node.IALAttr("linenumber")) {
+ preserveBlockIDs = true
return ast.WalkStop
}
return ast.WalkContinue
diff --git a/kernel/model/table_cell_rich_fts5_test.go b/kernel/model/table_cell_rich_fts5_test.go
new file mode 100644
index 0000000000..1b62e96c91
--- /dev/null
+++ b/kernel/model/table_cell_rich_fts5_test.go
@@ -0,0 +1,61 @@
+//go:build fts5
+
+package model
+
+import (
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestTableCellRichCodeSettingsTransactions(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ luteEngine := util.NewLute()
+ tableTree := parse.Parse("", []byte("| Header |\n| --- |\n| code |"), luteEngine.ParseOptions)
+ table := tableTree.Root.FirstChild
+ table.ID = ast.NewNodeID()
+ table.SetIALAttr("id", table.ID)
+ const plain = "```go\na | b\n```"
+ table.LastChild.FirstChild.TableCellRich = &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: plain}
+ if err = treenode.RefreshTableCellRichProjection(tableTree.Root); err != nil {
+ t.Fatal(err)
+ }
+ tree.Root.AppendChild(table)
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ const settings = plain + "\n" + `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}`
+ for index, source := range []string{settings, plain, settings} {
+ updated := parse.Parse("", []byte("| Header |\n| --- |\n| code |"), luteEngine.ParseOptions)
+ updatedTable := updated.Root.FirstChild
+ updatedTable.ID = table.ID
+ updatedTable.SetIALAttr("id", table.ID)
+ updatedTable.LastChild.FirstChild.TableCellRich = &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
+ if err = treenode.RefreshTableCellRichProjection(updated.Root); err != nil {
+ t.Fatal(err)
+ }
+ tx := &Transaction{isReplay: index > 0, DoOperations: []*Operation{{Action: "update", ID: table.ID,
+ Data: luteEngine.Tree2BlockDOM(updated, luteEngine.RenderOptions, luteEngine.ParseOptions)}}}
+ if err = PerformTxSync(tx); err != nil {
+ t.Fatalf("code setting update, undo or redo failed: %s", err)
+ }
+ restored, err := LoadTreeByBlockID(table.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cell := treenode.GetNodeInTree(restored, table.ID).LastChild.FirstChild
+ if cell.TableCellRich == nil || cell.TableCellRich.Content != source {
+ t.Fatalf("saved settings changed: %#v", cell.TableCellRich)
+ }
+ }
+}
diff --git a/kernel/model/table_cell_rich_test.go b/kernel/model/table_cell_rich_test.go
index c77a508b2f..005bc47d77 100644
--- a/kernel/model/table_cell_rich_test.go
+++ b/kernel/model/table_cell_rich_test.go
@@ -38,46 +38,51 @@ func TestTableCellRichDocumentReaders(t *testing.T) {
},
}
source := "- **first**\n- second\n\n```go\na | b\nc\n```"
- for name, read := range readers {
- t.Run(name, func(t *testing.T) {
- tree, err := read(legacy)
- if nil != err {
- t.Fatal(err)
- }
- cell := tree.Root.FirstChild.LastChild.FirstChild
- if tree.Root.Spec != "2" || cell.TableCellRich != nil || cell.FirstChild.TokensStr() != "**literal** - list" || cell.IALAttr("colspan") != "2" {
- t.Fatal("legacy cell must retain its content, format, and document version")
- }
- cell.TableCellRich = &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
- treenode.UpgradeSpec(tree)
- luteEngine := util.NewLute()
- data := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions).Render()
- restored, err := read(data)
- if nil != err {
- t.Fatal(err)
- }
- restoredCell := restored.Root.FirstChild.LastChild.FirstChild
- if restoredCell.TableCellRich.Content != source || !strings.Contains(restoredCell.Text(), "first") || strings.Contains(restoredCell.Text(), "literal") {
- t.Fatal("reader must preserve rich source and rebuild its inline projection")
- }
- unknown := bytes.Replace(data, []byte(`"spec": 1`), []byte(`"spec": 99`), 1)
- if bytes.Equal(unknown, data) {
- unknown = bytes.Replace(data, []byte(`"spec":1`), []byte(`"spec":99`), 1)
- }
- original := bytes.Clone(unknown)
- if _, err = read(unknown); nil == err {
- t.Fatal("unsupported rich format must fail before normalization")
- }
- if !bytes.Equal(original, unknown) {
- t.Fatal("reader changed unsupported input")
- }
- })
+ for _, source := range []string{source, source + "\n" +
+ `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}`} {
+ for name, read := range readers {
+ t.Run(name, func(t *testing.T) {
+ tree, err := read(legacy)
+ if nil != err {
+ t.Fatal(err)
+ }
+ cell := tree.Root.FirstChild.LastChild.FirstChild
+ if tree.Root.Spec != "2" || cell.TableCellRich != nil || cell.FirstChild.TokensStr() != "**literal** - list" || cell.IALAttr("colspan") != "2" {
+ t.Fatal("legacy cell must retain its content, format, and document version")
+ }
+ cell.TableCellRich = &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
+ treenode.UpgradeSpec(tree)
+ luteEngine := util.NewLute()
+ data := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions).Render()
+ restored, err := read(data)
+ if nil != err {
+ t.Fatal(err)
+ }
+ restoredCell := restored.Root.FirstChild.LastChild.FirstChild
+ if restoredCell.TableCellRich.Content != source || !strings.Contains(restoredCell.Text(), "first") || strings.Contains(restoredCell.Text(), "literal") {
+ t.Fatal("reader must preserve rich source and rebuild its inline projection")
+ }
+ unknown := bytes.Replace(data, []byte(`"spec": 1`), []byte(`"spec": 99`), 1)
+ if bytes.Equal(unknown, data) {
+ unknown = bytes.Replace(data, []byte(`"spec":1`), []byte(`"spec":99`), 1)
+ }
+ original := bytes.Clone(unknown)
+ if _, err = read(unknown); nil == err {
+ t.Fatal("unsupported rich format must fail before normalization")
+ }
+ if !bytes.Equal(original, unknown) {
+ t.Fatal("reader changed unsupported input")
+ }
+ })
+ }
}
}
func TestTableCellRichHTMLAndMarkdownExports(t *testing.T) {
luteEngine := util.NewLute()
- source := "- **first**\n- second\n\n```go\na | b\nc\n```\n\n![image](assets/original.png)"
+ source := "- **first**\n- second\n\n```go\na | b\nc\n```\n" +
+ `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}` +
+ "\n\n![image](assets/original.png)"
tree := parse.Parse("", []byte("| Header |\n| --- |\n| value |"), luteEngine.ParseOptions)
cell := tree.Root.FirstChild.LastChild.FirstChild
cell.TableCellRich = &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
@@ -96,6 +101,10 @@ func TestTableCellRichHTMLAndMarkdownExports(t *testing.T) {
if err := treenode.MaterializeTableCellRichExport(tree.Root); nil != err {
t.Fatal(err)
}
+ codes := cell.ChildrenByType(ast.NodeCodeBlock)
+ if len(codes) != 1 || codes[0].IALAttr("linewrap") != "false" || codes[0].IALAttr("linenumber") != "true" || codes[0].IALAttr("ligatures") != "false" {
+ t.Fatal("export materialization lost code settings")
+ }
ast.Walk(cell, func(node *ast.Node, entering bool) ast.WalkStatus {
if entering && node.Type == ast.NodeLinkDest {
node.Tokens = []byte("assets/exported.png")
diff --git a/kernel/treenode/table_cell_rich_test.go b/kernel/treenode/table_cell_rich_test.go
index 74a50b7382..c267aa95c6 100644
--- a/kernel/treenode/table_cell_rich_test.go
+++ b/kernel/treenode/table_cell_rich_test.go
@@ -27,6 +27,7 @@ func richTableTree(t *testing.T, source string) (*parse.Tree, *ast.Node) {
func TestTableCellRichSourceProjectionAndSpec(t *testing.T) {
sources := []string{
"- **first**\n- second\n\n> quotation\n\n```go\na | b\nc\n```\n\n$$\nx^2\n$$",
+ "```go\na | b\n```\n" + `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}`,
"- [ ] open\n- [x] done\n\n![image](assets/image.png) ((20240101000000-abcdefg 'reference'))",
"<span data-type=\"text\" style=\"color: var(--b3-font-color1);\">styled</span>",
"",
@@ -63,7 +64,8 @@ func TestTableCellRichSourceProjectionAndSpec(t *testing.T) {
}
func TestTableCellRichSynchronizesAssetReferenceAndText(t *testing.T) {
- tree, cell := richTableTree(t, "![image](assets/old.png) ((20240101000000-abcdefg 'reference')) text\n\n```go\nold\n```")
+ tree, cell := richTableTree(t, "![image](assets/old.png) ((20240101000000-abcdefg 'reference')) text\n\n```go\nold\n```\n"+
+ `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}`)
ast.Walk(cell, func(node *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
@@ -82,7 +84,8 @@ func TestTableCellRichSynchronizesAssetReferenceAndText(t *testing.T) {
if err := SyncTableCellRichInlineChanges(tree.Root); nil != err {
t.Fatal(err)
}
- for _, expected := range []string{"assets/new.png", "20240102000000-abcdefg", "<new> & value"} {
+ for _, expected := range []string{"assets/new.png", "20240102000000-abcdefg", "<new> & value",
+ `linewrap="false"`, `linenumber="true"`, `ligatures="false"`} {
if !strings.Contains(cell.TableCellRich.Content, expected) {
t.Fatalf("source does not contain %q: %s", expected, cell.TableCellRich.Content)
}
@@ -110,6 +113,7 @@ func TestTableCellRichFrontendProjectionParity(t *testing.T) {
`var(--b3-font-family-editor), var(--b3-font-family);"}`
for _, source := range []string{
"- **first**\n- second\n\n```go\na < b && c\nd\n```\n\n$$\nx < y\n$$",
+ "```go\na < b && c\n```\n" + `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}`,
"![image](assets/image.png) ((20240101000000-abcdefg 'reference')) `a & b`",
styled,
`<span data-type="text">styled</span>{: style='font-family: ` +