Skip to content

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

:bug: Restore code block insertion in table cells https://github.com/siyuan-note/siyuan/issues/19692

Daniel5375f2b183d3
diff --git a/app/src/protyle/render/tableCellRichEditor.ts b/app/src/protyle/render/tableCellRichEditor.ts
index 0ee061571e..61199ccf49 100644
--- a/app/src/protyle/render/tableCellRichEditor.ts
+++ b/app/src/protyle/render/tableCellRichEditor.ts
@@ -25,6 +25,7 @@ import {bindTableCellRichDrag} from "../util/tableCellRichDrag";
import {getTableCellEditorLute} from "../util/tableCellRichLute";
import {setTableCellRichContext} from "../util/tableCellRichContext";
import {updateOutlineCurrentBlock} from "../util/outlineBlock";
+import {canEnterCodeBlock} from "../wysiwyg/codeBlockEnter";
let activeEditor: {cell: Element, finish: () => void} | undefined;
@@ -419,8 +420,15 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem
}
const target = range?.startContainer instanceof Element ? range.startContainer : range?.startContainer.parentElement;
const inListOrCode = target?.closest('[data-type="NodeList"], [data-type="NodeCodeBlock"]');
+ const editable = target?.closest<HTMLElement>('[contenteditable="true"]');
+ const enterCode = event.key === "Enter" && !event.shiftKey &&
+ editable?.parentElement.getAttribute("data-type") === "NodeParagraph" &&
+ canEnterCodeBlock(editable,
+ getSelectionOffset(editable, fragment.wysiwyg, range).start,
+ window.siyuan.config.editor.markdown.codeBlockMiddleDot !== false);
const navigate = !inListOrCode && (event.key === "Tab" ||
- (event.key === "Enter" && !event.shiftKey && getTableCellInlineHTML(fragment.getBlockHTML()) !== null));
+ (event.key === "Enter" && !event.shiftKey && !enterCode &&
+ getTableCellInlineHTML(fragment.getBlockHTML()) !== null));
if (navigate) {
event.preventDefault();
event.stopImmediatePropagation();
diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.ts
new file mode 100644
index 0000000000..d53fc0d3ef
--- /dev/null
+++ b/app/src/protyle/util/tableCellRichLute.test.ts
@@ -0,0 +1,312 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {test} from "node:test";
+import {promisify} from "node:util";
+import {createSourceFile, isClassDeclaration, isMethodDeclaration, ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (source: string, enterSource: string, hintSource: string, keydownSource: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ const api = new Function(source + "\nreturn {getAgentLute, configureAVRichTextLute, getTableCellEditorLute, " +
+ "canEnterCodeBlock, hasCodeBlockFence, getTableCellInlineHTML, serializeTableCellRich, " +
+ "updateTableCellEditingValue, getTableCellRichBlockDOM, sanitizeAVRichTextBlockDOM};")() as
+ typeof import("../render/setLute") & typeof import("../render/av/richTextValue") &
+ typeof import("./tableCellRichLute") & typeof import("../wysiwyg/codeBlockEnter") &
+ typeof import("./tableCellRich") & typeof import("../render/av/richText");
+ const base = api.configureAVRichTextLute(api.getAgentLute({emojiSite: "/emojis", emojis: {},
+ headingAnchor: false, listStyle: false, paragraphBeginningSpace: true, sanitize: true}));
+ const lute = api.getTableCellEditorLute(base);
+ const editable = document.createElement("div");
+ for (const text of ["```", "```go", "~~~~shell", " ```js", "before\n\n```ts"]) {
+ editable.textContent = text;
+ check.equal(api.canEnterCodeBlock(editable, text.length, false), true, text);
+ }
+ editable.textContent = "···go";
+ check.equal(api.canEnterCodeBlock(editable, 5, true), true);
+ check.equal(api.canEnterCodeBlock(editable, 5, false), false);
+ for (const text of ["plain", "``", "```bad`", "text ```go", "first\n```bad`"]) {
+ editable.textContent = text;
+ check.equal(api.canEnterCodeBlock(editable, text.length, true), false, text);
+ }
+ editable.textContent = "````go";
+ check.equal(api.canEnterCodeBlock(editable, 3, true), false);
+ for (const type of ["text", "code"]) {
+ for (const prefix of ["", "first\n"]) {
+ editable.innerHTML = `<span data-type="${type}">${prefix}\`\`\`go</span>`;
+ check.equal(api.canEnterCodeBlock(editable, editable.textContent.length, true), false);
+ }
+ }
+ editable.innerHTML = '<span data-type="text">first\n```literal</span>\n```go';
+ check.equal(api.canEnterCodeBlock(editable, editable.textContent.length, true), true);
+ const paragraph = (content: string, text = false) => {
+ const holder = document.createElement("div");
+ holder.innerHTML = base.Md2BlockDOM("placeholder");
+ holder.querySelector('[contenteditable="true"]')[text ? "textContent" : "innerHTML"] = content;
+ return holder.innerHTML;
+ };
+ const parse = (html: string) => {
+ const holder = document.createElement("div");
+ holder.innerHTML = lute.SpinBlockDOM(html);
+ return holder;
+ };
+ const verifyCode = (holder: Element, language: string) => {
+ const code = holder.querySelector('[data-type="NodeCodeBlock"]');
+ check.ok(code, holder.innerHTML);
+ check.equal(code.querySelector(".protyle-action__language").textContent, language);
+ check.ok(code.querySelector(".hljs wbr"), "the caret belongs to the code body");
+ check.equal(holder.querySelector('[data-type="code"]'), null);
+ check.doesNotMatch(holder.innerHTML, /SYTABLECELLSOFTBREAK/);
+ return code;
+ };
+ for (const language of ["", "js"]) {
+ verifyCode(parse(paragraph("```" + language + Lute.Caret + "\n```", true)), language);
+ verifyCode(parse("```" + language + Lute.Caret + "\n```"), language);
+ verifyCode(parse(paragraph("```" + language + "<wbr>\n```")), language);
+ }
+ const prefixed = parse(paragraph('first\n\n<span data-type="strong">second</span>\n```go<wbr>\n```'));
+ verifyCode(prefixed, "go");
+ check.equal(prefixed.firstElementChild.querySelector('[contenteditable="true"]').textContent, "first\n\nsecond");
+ check.ok(prefixed.querySelector('[data-type="strong"]'));
+ const plain = parse(paragraph("first\n\nsecond<wbr>"));
+ check.equal(plain.childElementCount, 1);
+ check.equal(plain.querySelector('[contenteditable="true"]').textContent, "first\n\nsecond");
+ for (const [line, type] of [["# Heading", "NodeHeading"], ["- item", "NodeList"], ["[] task", "NodeList"]]) {
+ const converted = parse(paragraph("first\n\n" + line + "<wbr>"));
+ check.ok(converted.querySelector(`[data-type="${type}"] wbr`), line);
+ check.equal(converted.firstElementChild.querySelector('[contenteditable="true"]').textContent, "first\n");
+ }
+ const literal = parse(paragraph('<span data-type="text">```js\n```</span><wbr>'));
+ check.equal(literal.querySelector('[data-type="NodeCodeBlock"]'), null);
+ check.equal(literal.querySelector('[contenteditable="true"]').textContent, "```js\n```");
+ const existing = parse(base.Md2BlockDOM("```js\na | b\n\nc\n```"));
+ check.equal(existing.querySelector('.hljs [contenteditable="true"]').textContent, "a | b\n\nc\n");
+ check.doesNotMatch(api.sanitizeAVRichTextBlockDOM(base.Md2BlockDOM("```mermaid\ngraph TD\n```"), true), /NodeCodeBlock/);
+
+ const fixture = document.createElement("div");
+ fixture.innerHTML = '<table><tbody><tr><td><div class="table__cell-editor">' +
+ '<div class="protyle-wysiwyg"></div></div></td></tr></tbody></table>';
+ document.body.appendChild(fixture);
+ const cell = fixture.querySelector("td");
+ const host = cell.firstElementChild as HTMLElement;
+ const wysiwyg = host.firstElementChild as HTMLElement;
+ const hintElement = document.createElement("div");
+ hintElement.className = "fn__none";
+ const subElement = hintElement.cloneNode() as HTMLElement;
+ const calls: {rendered?: Element, transaction?: {element: Element, oldHTML: string,
+ additional?: {doOperations: IOperation[], undoOperations: IOperation[]}}, navigated: number} = {navigated: 0};
+ const protyle = {lute, lite: true, wysiwyg: {element: wysiwyg}, toolbar: {range: document.createRange(), subElement},
+ options: {hint: {extend: [{key: "/", hint: (): IHintData[] => []}]}}};
+ const getSelectionOffset = (editable: Node, _editor: Element, range: Range) => {
+ const prefix = document.createRange();
+ prefix.selectNodeContents(editable);
+ prefix.setEnd(range.startContainer, range.startOffset);
+ return {start: prefix.toString().length};
+ };
+ const getContenteditableElement = (element: Element) => element.querySelector('[contenteditable="true"]');
+ const focusByWbr = (element: Element, range: Range) => {
+ const marker = element.querySelector("wbr");
+ if (marker) {
+ range.setStartBefore(marker);
+ range.collapse(true);
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ }
+ };
+ const updateTransaction = (_protyle: unknown, element: Element, oldHTML: string, _context: unknown,
+ additional: {doOperations: IOperation[], undoOperations: IOperation[]}) => {
+ calls.transaction = {element, oldHTML, additional};
+ };
+ const constants = {LOCAL_CODELANG: "codeLanguage", SIYUAN_RENDER_CODE_LANGUAGES: ["mermaid"],
+ BLOCK_HINT_KEYS: ["((", "[["], INLINE_TYPE: ["code"], ZWSP: "\u200b", ATTRIBUTE_EDITING: "updated"};
+ Object.assign(window, {siyuan: {storage: {codeLanguage: ""}, config: {
+ editor: {markdown: {codeBlockMiddleDot: true}}, keymap: {editor: {table: {}, general: {}}},
+ }}});
+ const dependencies = {
+ ...api, Constants: constants, BLOCK_SELECTION_CLASS: "protyle-wysiwyg--select",
+ getBlockSelectionModeElement: (): undefined => undefined, getEmbedChildOperationContext: (): undefined => undefined,
+ hasClosestByClassName: (element: Element, className: string) => element.closest("." + className),
+ isNotEditBlock: () => false, getContenteditableElement, getSelectionOffset,
+ activateTrackedRangeInsertion: () => {}, setStorageVal: () => {},
+ highlightRender: (element: Element) => {
+ calls.rendered = element;
+ focusByWbr(element, protyle.toolbar.range);
+ },
+ processRender: () => { throw new Error("ordinary code must not use the render editor"); },
+ updateTransaction, focusByWbr, focusByRange: () => {}, hideElements: () => {},
+ hasClosestBlock: (node: Node) => (node instanceof Element ? node : node.parentElement).closest("[data-node-id]"),
+ shouldCaptureHintUndoFocus: () => false, isBuiltinSlashHint: () => true,
+ transaction: () => {},
+ };
+ const enter = new Function(...Object.keys(dependencies), enterSource + "\nreturn enter;")(...Object.values(dependencies)) as
+ typeof import("../wysiwyg/enter").enter;
+ const fill = new Function(...Object.keys(dependencies), hintSource + "\nreturn Hint.prototype.fill;")(...Object.values(dependencies));
+ const fragment = {wysiwyg, protyle, hintElement, getBlockHTML: () => wysiwyg.innerHTML};
+ const keyDependencies = {...dependencies, host, cell, fragment, owner: protyle, signal: new AbortController().signal,
+ captureBeforeChange: () => {}, composing: false, matchHotKey: () => false, finish: () => {},
+ fixTable: () => { calls.navigated++; }};
+ new Function(...Object.keys(keyDependencies), keydownSource)(...Object.values(keyDependencies));
+ const prepare = (text: string, offset = text.length) => {
+ wysiwyg.innerHTML = paragraph(text, true);
+ const range = document.createRange();
+ range.setStart(getContenteditableElement(wysiwyg).firstChild, offset);
+ range.collapse(true);
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ protyle.toolbar.range = range;
+ calls.rendered = undefined;
+ calls.transaction = undefined;
+ return range;
+ };
+ let entered: Promise<unknown>;
+ wysiwyg.addEventListener("keydown", event => {
+ if (event.key === "Enter" && !event.shiftKey) {
+ const range = getSelection().getRangeAt(0);
+ entered = enter(wysiwyg.firstElementChild as HTMLElement, range, protyle as unknown as IProtyle);
+ }
+ });
+ const replay = (operations: IOperation[]) => operations.forEach(operation => {
+ if (operation.action === "update") {
+ wysiwyg.querySelector(`[data-node-id="${operation.id}"]`).outerHTML = operation.data;
+ } else if (operation.action === "insert") {
+ wysiwyg.querySelector(`[data-node-id="${operation.previousID}"]`).insertAdjacentHTML("afterend", operation.data);
+ } else if (operation.action === "delete") {
+ wysiwyg.querySelector(`[data-node-id="${operation.id}"]`).remove();
+ }
+ });
+ for (const text of ["```", "```go", "~~~~js", "···ts", "first\n\nsecond\n```go", "first\n```literal\n```go"]) {
+ const range = prepare(text);
+ if (text.includes("literal")) {
+ const content = getContenteditableElement(wysiwyg);
+ content.innerHTML = '<span data-type="text">first\n```literal</span>\n```go';
+ range.setStart(content.lastChild, content.lastChild.textContent.length);
+ range.collapse(true);
+ }
+ const oldID = wysiwyg.firstElementChild.getAttribute("data-node-id");
+ const previousNavigation = calls.navigated;
+ getContenteditableElement(wysiwyg).dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true, cancelable: true}));
+ await entered;
+ check.equal(calls.navigated, previousNavigation, text);
+ const language = text.slice(text.lastIndexOf("\n") + 1).replace(/^[`~·]+/, "") || window.siyuan.storage.codeLanguage;
+ const code = verifyCode(wysiwyg, language);
+ check.equal(calls.rendered, code);
+ check.equal(calls.transaction.element.getAttribute("data-node-id"), oldID);
+ if (text.startsWith("first")) {
+ check.equal(wysiwyg.firstElementChild.querySelector('[contenteditable="true"]').textContent,
+ text.substring(0, text.lastIndexOf("\n")));
+ check.equal(calls.transaction.additional.doOperations.length, 1);
+ check.equal(calls.transaction.additional.undoOperations.length, 1);
+ }
+ const saved = wysiwyg.innerHTML;
+ const transaction = calls.transaction;
+ const updatedHTML = transaction.element.outerHTML;
+ replay([{action: "update", id: oldID, data: transaction.oldHTML}, ...(transaction.additional?.undoOperations || [])]);
+ check.equal(getContenteditableElement(wysiwyg).textContent, text);
+ replay([...(transaction.additional?.doOperations || []), {action: "update", id: oldID, data: updatedHTML}]);
+ check.equal(wysiwyg.innerHTML, saved, "redo restores the complete conversion");
+ wysiwyg.querySelectorAll("wbr").forEach(marker => marker.remove());
+ const body = "a | b\n\n<标签> & c\n";
+ wysiwyg.querySelector('.hljs [contenteditable="true"]').textContent = body;
+ const stored = document.createElement("td");
+ api.updateTableCellEditingValue(stored, api.serializeTableCellRich(wysiwyg.innerHTML));
+ const reopened = document.createElement("div");
+ reopened.innerHTML = api.getTableCellRichBlockDOM(stored);
+ check.equal(reopened.querySelectorAll('[data-type="NodeCodeBlock"]').length, 1);
+ check.equal(reopened.querySelector('.hljs [contenteditable="true"]').textContent, body);
+ if (text.startsWith("first")) {
+ check.equal(reopened.firstElementChild.querySelector('[contenteditable="true"]').textContent,
+ text.substring(0, text.lastIndexOf("\n")));
+ }
+ }
+ for (const [text, offset] of [["ordinary", 8], ["``", 2], ["```bad`", 7], ["```go", 2]] as const) {
+ prepare(text, offset);
+ const previous = calls.navigated;
+ entered = undefined;
+ getContenteditableElement(wysiwyg).dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true, cancelable: true}));
+ check.equal(calls.navigated, previous + 1, text);
+ check.equal(entered, undefined);
+ }
+ prepare("```go");
+ const previous = calls.navigated;
+ getContenteditableElement(wysiwyg).dispatchEvent(new KeyboardEvent("keydown", {key: "Tab", bubbles: true, cancelable: true}));
+ check.equal(calls.navigated, previous + 1);
+ prepare("```go");
+ entered = undefined;
+ const beforeSoftEnter = calls.navigated;
+ getContenteditableElement(wysiwyg).dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", shiftKey: true, bubbles: true, cancelable: true}));
+ check.equal(calls.navigated, beforeSoftEnter);
+ check.equal(entered, undefined);
+ window.siyuan.config.editor.markdown.codeBlockMiddleDot = false;
+ prepare("···go");
+ getContenteditableElement(wysiwyg).dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true, cancelable: true}));
+ check.equal(calls.navigated, beforeSoftEnter + 1);
+ for (const prefix of ["", "existing "]) {
+ const range = prepare(prefix + "/");
+ range.setStart(range.startContainer, prefix.length);
+ const context = {source: "hint", splitChar: "/", lastIndex: -1, fixImageCursor: () => {}};
+ fill.call(context, "```", protyle, false);
+ const code = verifyCode(wysiwyg, window.siyuan.storage.codeLanguage);
+ check.equal(calls.rendered, code);
+ check.ok(code.contains(getSelection().anchorNode));
+ }
+ fixture.remove();
+ return "Table cell code insertion cases passed";
+};
+
+test("table cells insert code through slash and Enter without losing soft breaks", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const compile = (source: string) => transpileModule(source.replace(/^import [\s\S]*?;\r?\n/gm, "")
+ .replace(/^export (?:type )?\{[\s\S]*?\}(?: from "[^"]+")?;\r?\n/gm, "")
+ .replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+ const read = (file: string) => readFileSync(path.join(__dirname, file), "utf8");
+ const source = ["inlineElementBoundary.ts", "../toolbar/fontFamilyCore.ts", "../../util/escape.ts",
+ "../render/setLute.ts", "../render/av/richTextValue.ts", "../render/av/richText.ts",
+ "../wysiwyg/taskListMarker.ts", "../wysiwyg/codeBlockEnter.ts", "tableCellRichLute.ts", "tableCellRichValue.ts",
+ "tableCellRich.ts"].map(file => compile(read(file))).join("\n");
+ const hint = createSourceFile("hint.ts", read("../hint/index.ts"), ScriptTarget.Latest, true);
+ const hintClass = hint.statements.find(isClassDeclaration);
+ const fill = hintClass.members.find(member => isMethodDeclaration(member) && member.name.getText(hint) === "fill");
+ const hintSource = compile("class Hint {" + fill.getText(hint) + "}");
+ const editor = read("../render/tableCellRichEditor.ts");
+ 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 temporary = mkdtempSync(path.join(tmpdir(), "siyuan-table-cell-code-test-"));
+ const script = path.join(temporary, "run.cjs");
+ const lutePath = path.resolve(__dirname, "../../../stage/protyle/js/lute/lute.min.js");
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(lutePath)}, "utf8"));
+ const result = await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +
+ browserCases.toString() + ")(" + [source, compile(read("../wysiwyg/enter.ts")), hintSource, keydownSource]
+ .map(value => JSON.stringify(value)).join(",") + ")")});
+ console.log(result);
+ win.destroy();
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ win.destroy();
+ app.exit(1);
+ }
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],
+ {env, timeout: 40000, windowsHide: true});
+ assert.match(result.stdout, /Table cell code insertion cases passed/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&
+ path.basename(temporary).startsWith("siyuan-table-cell-code-test-")) {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+ }
+});
diff --git a/app/src/protyle/util/tableCellRichLute.ts b/app/src/protyle/util/tableCellRichLute.ts
index 2d1d73178d..ca31d9daac 100644
--- a/app/src/protyle/util/tableCellRichLute.ts
+++ b/app/src/protyle/util/tableCellRichLute.ts
@@ -1,5 +1,27 @@
import {getTaskListMarker} from "../wysiwyg/taskListMarker";
+// 新建代码块的光标位于开围栏中,闭围栏由插入操作补齐;只放开这一段的结构换行。
+const getCodeFenceStart = (marker: Element, editable: Element): Text | undefined => {
+ if (!editable || marker.parentElement !== editable ||
+ editable.parentElement?.getAttribute("data-type") !== "NodeParagraph" ||
+ marker.previousSibling?.nodeType !== Node.TEXT_NODE) {
+ return;
+ }
+ const range = document.createRange();
+ range.selectNodeContents(editable);
+ range.setEndBefore(marker);
+ const before = document.createElement("div");
+ before.appendChild(range.cloneContents());
+ const opening = before.innerHTML.trimStart().match(/(?:^|\n)(`{3,})[^`\n<]*$/);
+ range.selectNodeContents(editable);
+ range.setStartAfter(marker);
+ const after = document.createElement("div");
+ after.appendChild(range.cloneContents());
+ if (opening && new RegExp("\\n`{" + opening[1].length + ",}[ \\t]*$").test(after.innerHTML.trimEnd())) {
+ return marker.previousSibling as Text;
+ }
+};
+
// 保留单元格内的软换行,并允许光标所在的新行触发块级语法。
export const getTableCellEditorLute = (lute: Lute, enableFullWidthTaskList = false): Lute => new Proxy(lute, {
get(target, property) {
@@ -13,8 +35,25 @@ export const getTableCellEditorLute = (lute: Lute, enableFullWidthTaskList = fal
while (html.includes(token)) {
token += "X";
}
- const marker = template.content.querySelector("wbr");
+ let marker = template.content.querySelector("wbr");
+ if (!marker && html.includes(Lute.Caret) && html.includes("```")) {
+ // 斜杠菜单使用文本光标,统一为 DOM 光标后再识别围栏和软换行边界。
+ const carets = document.createTreeWalker(template.content, NodeFilter.SHOW_TEXT);
+ while (carets.nextNode()) {
+ const text = carets.currentNode as Text;
+ const offset = text.data.indexOf(Lute.Caret);
+ if (offset >= 0) {
+ const tail = text.splitText(offset);
+ tail.deleteData(0, Lute.Caret.length);
+ marker = document.createElement("wbr");
+ tail.before(marker);
+ break;
+ }
+ }
+ }
const editable = marker?.closest('[contenteditable="true"]');
+ const codeStart = getCodeFenceStart(marker, editable);
+ let inCodeFence = false;
const getBlockPath = (element: Element) => {
const types: string[] = [];
while (element) {
@@ -34,7 +73,17 @@ export const getTableCellEditorLute = (lute: Lute, enableFullWidthTaskList = fal
const element = node.parentElement;
if (element?.closest('[contenteditable="true"]') &&
!element.closest('[data-type="NodeCodeBlock"], [data-type="NodeMathBlock"], .img')) {
- if (editable?.contains(node) && node.textContent.includes("\n") &&
+ if (node === codeStart) {
+ const offset = Math.max(0, node.textContent.lastIndexOf("\n"));
+ node.textContent = node.textContent.substring(0, offset).replace(/\n/g, token) +
+ node.textContent.substring(offset);
+ inCodeFence = true;
+ continue;
+ }
+ if (inCodeFence && editable.contains(node)) {
+ continue;
+ }
+ if (!codeStart && editable?.contains(node) && node.textContent.includes("\n") &&
(node.compareDocumentPosition(marker) & Node.DOCUMENT_POSITION_FOLLOWING)) {
boundary = node;
}
diff --git a/app/src/protyle/wysiwyg/codeBlockEnter.ts b/app/src/protyle/wysiwyg/codeBlockEnter.ts
index 341ed9dea6..31dab06cde 100644
--- a/app/src/protyle/wysiwyg/codeBlockEnter.ts
+++ b/app/src/protyle/wysiwyg/codeBlockEnter.ts
@@ -29,3 +29,41 @@ export const isCodeBlockFenceBeforeCaret = (text: string, caretOffset: number, e
}
return fenceEnd <= caretOffset;
};
+
+export const hasCodeBlockFence = (html: string, text: string, enableMiddleDot: boolean) =>
+ html.startsWith("```") || html.startsWith("~~~") ||
+ (html.includes("\n```") && text.includes("\n```")) ||
+ (html.includes("\n~~~") && text.includes("\n~~~")) ||
+ (enableMiddleDot && (html.startsWith("···") || (html.includes("\n···") && text.includes("\n···"))));
+
+// 表格导航与正文回车共用转换条件,避免不完整围栏和字面标记触发代码块。
+export const canEnterCodeBlock = (editable: Element, caretOffset: number, enableMiddleDot: boolean) => {
+ const html = editable.innerHTML.trimStart();
+ const text = editable.textContent;
+ const trimmedText = text.trimStart();
+ if (!hasCodeBlockFence(html, trimmedText, enableMiddleDot)) {
+ return false;
+ }
+ // 已保存的字面标记和行内代码不参与块级转换,围栏前的其他行内格式仍可保留。
+ const fences = trimmedText.matchAll(enableMiddleDot ? /(?:^|\n)(?:`{3,}|~{3,}|·{3,})/g : /(?:^|\n)(?:`{3,}|~{3,})/g);
+ const walker = document.createTreeWalker(editable, NodeFilter.SHOW_TEXT);
+ let node = walker.nextNode();
+ let offset = 0;
+ for (const fence of fences) {
+ const start = text.length - trimmedText.length + fence.index + (fence[0].startsWith("\n") ? 1 : 0);
+ const tail = text.substring(start);
+ const line = tail.split("\n", 1)[0];
+ if (!isCodeBlockFenceBeforeCaret(tail, caretOffset - start, enableMiddleDot) ||
+ line.replace(enableMiddleDot ? /·|~/g : /~/g, "`").replace(/^`{3,}/, "").includes("`")) {
+ continue;
+ }
+ while (node && offset + node.textContent.length <= start) {
+ offset += node.textContent.length;
+ node = walker.nextNode();
+ }
+ if (node && !node.parentElement.closest("span[data-type]")) {
+ return true;
+ }
+ }
+ return false;
+};
diff --git a/app/src/protyle/wysiwyg/enter.ts b/app/src/protyle/wysiwyg/enter.ts
index 4e65a2f9b9..919114f351 100644
--- a/app/src/protyle/wysiwyg/enter.ts
+++ b/app/src/protyle/wysiwyg/enter.ts
@@ -31,7 +31,7 @@ import {isMobile} from "../../util/functions";
import {processRender} from "../util/processCode";
import {hasClosestByAttribute, hasClosestByClassName} from "../util/hasClosest";
import {blockRender} from "../render/blockRender";
-import {isCodeBlockFenceBeforeCaret} from "./codeBlockEnter";
+import {canEnterCodeBlock, hasCodeBlockFence} from "./codeBlockEnter";
import {isEmptyListItemBlock, shouldCreateListItemChildOnEnter} from "./listContext";
import {
BLOCK_SELECTION_CLASS,
@@ -97,66 +97,65 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
}
const position = getSelectionOffset(editableElement, protyle.wysiwyg.element, range);
- const trimStartHTML = editableElement.innerHTML.trimStart();
- const trimStartText = editableElement.textContent.trimStart();
const enableCodeBlockMiddleDot = window.siyuan.config.editor.markdown.codeBlockMiddleDot !== false;
const codeBlockMarkerRegExp = enableCodeBlockMiddleDot ? /·|~/g : /~/g;
const codeBlockFenceStartRegExp = enableCodeBlockMiddleDot ? /^(~|·|`){3,}/g : /^(~|`){3,}/g;
const codeBlockFenceLineRegExp = enableCodeBlockMiddleDot ? /\n(~|·|`){3,}/g : /\n(~|`){3,}/g;
- const hasCodeBlockFence = (html: string, text: string) => html.startsWith("```") || html.startsWith("~~~") ||
- (html.indexOf("\n```") > -1 && text.indexOf("\n```") > -1) ||
- (html.indexOf("\n~~~") > -1 && text.indexOf("\n~~~") > -1) ||
- (enableCodeBlockMiddleDot && (html.startsWith("···") ||
- (html.indexOf("\n···") > -1 && text.indexOf("\n···") > -1)));
// 光标位于代码块围栏之前或内部时按普通换行处理 https://github.com/siyuan-note/siyuan/issues/18873
- if (hasCodeBlockFence(trimStartHTML, trimStartText) &&
- isCodeBlockFenceBeforeCaret(editableElement.textContent, position.start, enableCodeBlockMiddleDot)) {
- if (trimStartHTML.indexOf("\n") === -1 &&
- trimStartHTML.replace(codeBlockMarkerRegExp, "`").replace(/^`{3,}/g, "").indexOf("`") > -1) {
- // ```test` 不处理,正常渲染为段落块
- } else if (blockElement.classList.contains("p")) { // https://github.com/siyuan-note/siyuan/issues/6953
- activateTrackedRangeInsertion(trackedRangeInsertion);
- range.insertNode(document.createElement("wbr"));
- const oldHTML = blockElement.outerHTML;
- // https://github.com/siyuan-note/siyuan/issues/16744
- range.extractContents();
- const wbrElement = document.createElement("wbr");
- range.insertNode(wbrElement);
- wbrElement.after(document.createTextNode("\n"));
- let replaceInnerHTML = editableElement.innerHTML
- .replace(codeBlockFenceLineRegExp, "\n```").trim()
- .replace(codeBlockFenceStartRegExp, "```");
- if (!replaceInnerHTML.endsWith("\n```")) {
- replaceInnerHTML += "\n```";
+ if (blockElement.classList.contains("p") && canEnterCodeBlock(editableElement, position.start, enableCodeBlockMiddleDot)) {
+ activateTrackedRangeInsertion(trackedRangeInsertion);
+ range.insertNode(document.createElement("wbr"));
+ const oldHTML = blockElement.outerHTML;
+ // https://github.com/siyuan-note/siyuan/issues/16744
+ range.extractContents();
+ const wbrElement = document.createElement("wbr");
+ range.insertNode(wbrElement);
+ wbrElement.after(document.createTextNode("\n"));
+ let replaceInnerHTML = editableElement.innerHTML
+ .replace(codeBlockFenceLineRegExp, "\n```").trim()
+ .replace(codeBlockFenceStartRegExp, "```");
+ if (!replaceInnerHTML.endsWith("\n```")) {
+ replaceInnerHTML += "\n```";
+ }
+ editableElement.innerHTML = replaceInnerHTML;
+ const template = document.createElement("template");
+ template.innerHTML = protyle.lute.SpinBlockDOM(blockElement.outerHTML);
+ const replacements = Array.from(template.content.children) as HTMLElement[];
+ // 软换行前的正文保留为段落,渲染和光标定位使用实际生成的代码块。
+ const codeElement = template.content.querySelector("wbr")?.closest<HTMLElement>('[data-type="NodeCodeBlock"]');
+ blockElement.replaceWith(template.content);
+ blockElement = codeElement || replacements[0];
+ const languageElement = blockElement.querySelector(".protyle-action__language");
+ if (languageElement) {
+ if (window.siyuan.storage[Constants.LOCAL_CODELANG] && languageElement.textContent === "") {
+ languageElement.textContent = window.siyuan.storage[Constants.LOCAL_CODELANG];
+ } else if (!Constants.SIYUAN_RENDER_CODE_LANGUAGES.includes(languageElement.textContent)) {
+ window.siyuan.storage[Constants.LOCAL_CODELANG] = languageElement.textContent;
+ setStorageVal(Constants.LOCAL_CODELANG, window.siyuan.storage[Constants.LOCAL_CODELANG]);
}
- editableElement.innerHTML = replaceInnerHTML;
- blockElement.outerHTML = protyle.lute.SpinBlockDOM(blockElement.outerHTML);
- blockElement = protyle.wysiwyg.element.querySelector(`[data-node-id="${blockElement.getAttribute("data-node-id")}"]`);
- const languageElement = blockElement.querySelector(".protyle-action__language");
- if (languageElement) {
- if (window.siyuan.storage[Constants.LOCAL_CODELANG] && languageElement.textContent === "") {
- languageElement.textContent = window.siyuan.storage[Constants.LOCAL_CODELANG];
- } else if (!Constants.SIYUAN_RENDER_CODE_LANGUAGES.includes(languageElement.textContent)) {
- window.siyuan.storage[Constants.LOCAL_CODELANG] = languageElement.textContent;
- setStorageVal(Constants.LOCAL_CODELANG, window.siyuan.storage[Constants.LOCAL_CODELANG]);
- }
- if (Constants.SIYUAN_RENDER_CODE_LANGUAGES.includes(languageElement.textContent)) {
- blockElement.dataset.content = "";
- blockElement.dataset.subtype = languageElement.textContent;
- blockElement.className = "render-node";
- blockElement.innerHTML = `<div spin="1"></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div>`;
- protyle.toolbar.showRender(protyle, blockElement);
- processRender(blockElement);
- } else {
- highlightRender(blockElement);
- }
- } else {
+ if (Constants.SIYUAN_RENDER_CODE_LANGUAGES.includes(languageElement.textContent)) {
+ blockElement.dataset.content = "";
+ blockElement.dataset.subtype = languageElement.textContent;
+ blockElement.className = "render-node";
+ blockElement.innerHTML = `<div spin="1"></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div>`;
protyle.toolbar.showRender(protyle, blockElement);
processRender(blockElement);
+ } else {
+ highlightRender(blockElement);
}
- updateTransaction(protyle, blockElement, oldHTML, undefined, undefined, {trackedRangeInsertion});
- return true;
+ } else {
+ protyle.toolbar.showRender(protyle, blockElement);
+ processRender(blockElement);
}
+ // 转换产生多个块时,将新增块一起记入事务,撤销可完整恢复原段落。
+ updateTransaction(protyle, replacements[0], oldHTML, undefined, replacements.length > 1 ? {
+ doOperations: replacements.slice(1).map((element, index) => ({
+ action: "insert", id: element.dataset.nodeId, data: element.outerHTML,
+ previousID: replacements[index].dataset.nodeId,
+ })),
+ undoOperations: replacements.slice(1).map(element => ({action: "delete", id: element.dataset.nodeId})),
+ } : undefined, {trackedRangeInsertion});
+ return true;
}
// 代码块
if (blockElement.getAttribute("data-type") === "NodeCodeBlock") {
@@ -345,7 +344,7 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
const newHTML = newEditableElement.innerHTML.trimStart();
const newText = newEditableElement.textContent.trimStart();
// https://github.com/siyuan-note/siyuan/issues/10759
- if (hasCodeBlockFence(newHTML, newText)) {
+ if (hasCodeBlockFence(newHTML, newText, enableCodeBlockMiddleDot)) {
if (newHTML.indexOf("\n") === -1 &&
newHTML.replace(codeBlockMarkerRegExp, "`").replace(/^`{3,}/g, "").indexOf("`") > -1) {
// ```test` 不处理,正常渲染为段落块