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 table cell editing with on-demand rich editors https://github.com/siyuan-note/siyuan/issues/19870
Daniel85e4de45c008
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex 823a4ea097..c5159f7714 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -695,8 +695,15 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {protyle.hint.splitChar = "/";protyle.hint.lastIndex = -1;- if (protyle.lite) {- // 轻量编辑器沿用自己的插入候选,保留单元格内容限制和智能体技能入口。+ const range = protyle.toolbar.range;+ const target = range?.startContainer instanceof Element ? range.startContainer : range?.startContainer.parentElement;+ const cell = target?.closest("td, th");+ const inTableCell = cell && cell.closest(".protyle-wysiwyg") === protyle.wysiwyg.element && cell.contains(range.endContainer);+ if (protyle.lite || inTableCell) {+ // 单元格和轻量编辑器沿用各自的插入候选,保留内容限制和智能体技能入口。+ if (inTableCell) {+ focusByRange(range);+ }unmountLiteSlashMenu = mountLiteSlashMenu(protyle, toolbarElement.querySelector(".keyboard__util"));return;}diff --git a/app/src/mobile/util/liteSlashMenu.test.ts b/app/src/mobile/util/liteSlashMenu.test.tsindex cb43263fa6..433b162366 100644--- a/app/src/mobile/util/liteSlashMenu.test.ts+++ b/app/src/mobile/util/liteSlashMenu.test.ts@@ -5,9 +5,9 @@ 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";+import {createSourceFile, isClassDeclaration, isMethodDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";-const browserCases = async (source: string, hintSource: string) => {+const browserCases = async (source: string, hintSource: string, keyboardSource: string) => {const check: typeof assert = require("node:assert/strict");const {mount, render, paddingElement} = new Function(source + hintSource +"\nreturn {mount: mountLiteSlashMenu, render: Hint.prototype.getHTMLByData, paddingElement: getMobileToolbarPaddingElement};")() as {@@ -108,6 +108,34 @@ const browserCases = async (source: string, hintSource: string) => {mount(protyle, panel);toolbar.style.width = "390px";+ const tableEditor = document.createElement("div");+ tableEditor.className = "protyle-wysiwyg";+ tableEditor.innerHTML = "<table contenteditable='true'><tbody><tr><td>inline</td></tr></tbody></table>";+ document.body.appendChild(tableEditor);+ const range = document.createRange();+ range.selectNodeContents(tableEditor.querySelector("td"));+ range.collapse(false);+ Object.assign(protyle, {lite: false, wysiwyg: {element: tableEditor}, toolbar: {range}});+ const keyboard = new Function("mountLiteSlashMenu", "focusByRange",+ "let unmountLiteSlashMenu;" + keyboardSource ++ "\nreturn {render: renderSlashMenu, unmount: () => unmountLiteSlashMenu()};")(mount, (saved: Range) => {+ getSelection().removeAllRanges();+ getSelection().addRange(saved);+ });+ provider.hint = () => {+ check.ok(tableEditor.querySelector("td").contains(getSelection().focusNode));+ return items.slice(0, 2);+ };+ getSelection().removeAllRanges();+ keyboard.render(protyle, toolbar);+ check.equal(panel.querySelectorAll("button.keyboard__slash-item[data-value]").length, 2);+ check.equal(panel.querySelector('[data-value="upload"]'), null);+ check.equal(protyle.hint.splitChar, "/");+ check.equal(protyle.hint.lastIndex, -1);+ check.equal(tableEditor.querySelector(".table__cell-editor"), null);+ keyboard.unmount();+ tableEditor.remove();+const agent = document.createElement("div");agent.className = "sy__agentChat sy__agentChat--mobile fn__flex-column";agent.style.position = "fixed";@@ -153,6 +181,13 @@ test("mobile slash panel retains synchronous and asynchronous candidates and relconst hintSource = transpileModule("class Hint {" + render.getText(hintFile) + "}", {compilerOptions: {target: ScriptTarget.ES2021},}).outputText;+ const keyboardFile = createSourceFile("keyboardToolbar.ts", readFileSync(path.join(__dirname, "keyboardToolbar.ts"), "utf8"),+ ScriptTarget.Latest, true);+ const keyboardRender = keyboardFile.statements.find(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(declaration => declaration.name.getText(keyboardFile) === "renderSlashMenu"));+ const keyboardSource = transpileModule(keyboardRender.getText(keyboardFile), {+ compilerOptions: {target: ScriptTarget.ES2021},+ }).outputText;const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-mobile-slash-test-"));const script = path.join(temporary, "run.cjs");writeFileSync(script, `const {app, BrowserWindow} = require("electron");@@ -169,7 +204,7 @@ app.whenReady().then(async () => {await win.webContents.insertCSS(require(${JSON.stringify(require.resolve("sass"))}).compile(${JSON.stringify(path.resolve(__dirname, "../../assets/scss/mobile.scss"))}, {logger: {warn() {}}}).css);console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +- browserCases.toString() + ")(" + JSON.stringify(source) + "," + JSON.stringify(hintSource) + ")")}));+ browserCases.toString() + ")(" + [source, hintSource, keyboardSource].map(value => JSON.stringify(value)).join(",") + ")")}));if (process.env.SIYUAN_MOBILE_SLASH_SCREENSHOT) {await new Promise(resolve => setTimeout(resolve, 200));require("node:fs").writeFileSync(process.env.SIYUAN_MOBILE_SLASH_SCREENSHOT, (await win.webContents.capturePage()).toPNG());diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex 11fd715dc8..4080b61523 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -1,6 +1,7 @@import {isTableLikeView} from "../render/av/viewType";import {Constants} from "../../constants";import {isBuiltinSlashHint} from "./builtinSlash";+import {isTableCellBlockSlash} from "../util/tableCellRichMenu";import {hasClosestBlock,hasClosestByAttribute,@@ -780,6 +781,34 @@ ${genHintItemHTML(item)}if (!nodeElement) {return;}+ if (["/", "、"].includes(this.splitChar) && isTableCellBlockSlash(value)) {+ const target = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;+ const cell = target?.closest<HTMLTableCellElement>("td, th");+ if (cell && cell.closest(".protyle-wysiwyg") === protyle.wysiwyg.element && cell.contains(range.endContainer)) {+ // 块级命令在单元格片段中执行,先保留完整命令选区,避免替换整张表格。+ if (this.lastIndex > -1) {+ range.setStart(range.startContainer, this.lastIndex);+ }+ focusByRange(range);+ const splitChar = this.splitChar;+ this.enableExtend = false;+ void import("../render/tableCellRichEditor").then(async module => {+ if (!cell.contains(getSelection().anchorNode) || !cell.contains(getSelection().focusNode)) {+ return;+ }+ const editor = await module.openTableCellRichEditor(protyle, cell, undefined, undefined, undefined, true);+ if (!editor) {+ return;+ }+ editor.hint.splitChar = splitChar;+ editor.hint.lastIndex = -1;+ editor.hint.source = "hint";+ editor.toolbar.range = getSelection().getRangeAt(0);+ editor.hint.fill(value, editor, false, refIsS);+ });+ return;+ }+ }if (["/", "、"].includes(this.splitChar) && isProtyleListItemFragment(protyle) &&["- " + Lute.Caret, "1. " + Lute.Caret, "- [ ] " + Lute.Caret].includes(value)) {this.enableExtend = false;@@ -1284,19 +1313,6 @@ ${genHintItemHTML(item)}}}}- // 新建表格后直接接管当前单元格,后续输入与鼠标点击进入编辑使用相同的限制。- const selection = getSelection();- const focus = selection?.focusNode;- const focusElement = focus instanceof Element ? focus : focus?.parentElement;- const cell = focusElement?.closest<HTMLTableCellElement>("td, th");- if (cell && cell.closest(".protyle-wysiwyg") === protyle.wysiwyg.element &&- cell.contains(selection.anchorNode)) {- void import("../render/tableCellRichEditor").then(module => {- if (cell.contains(getSelection()?.focusNode)) {- module.openTableCellRichEditor(protyle, cell);- }- });- }}public select(event: KeyboardEvent, protyle: IProtyle) {diff --git a/app/src/protyle/render/tableCellInput.test.ts b/app/src/protyle/render/tableCellInput.test.tsindex 369a0ff9b1..1eb9654d40 100644--- a/app/src/protyle/render/tableCellInput.test.ts+++ b/app/src/protyle/render/tableCellInput.test.ts@@ -7,11 +7,13 @@ import {test} from "node:test";import {promisify} from "node:util";import {createSourceFile, isClassDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";-const browserCases = async (source: string, queueSource: string, editorSource: string, menuSource: string) => {+const browserCases = async (source: string, queueSource: string, editorSource: string, menuSource: string, hintSource: string) => {const check: typeof assert = require("node:assert/strict");const noop = () => {};const tick = () => new Promise(resolve => setTimeout(resolve, 0));- const changes: {doOperations: IOperation[], undoOperations: IOperation[]}[] = [];+ const changes: {doOperations: IOperation[], undoOperations: IOperation[], undoContext?: Record<string, string>,+ context?: Record<string, string>}[] = [];+ let opening: Promise<IProtyle>;const focusByRange = (range: Range) => {getSelection().removeAllRanges();getSelection().addRange(range);@@ -21,30 +23,52 @@ const browserCases = async (source: string, queueSource: string, editorSource: sstorage: {}, languages: new Proxy({}, {get: () => "${x}"}), menus: {menu: {remove: noop}},}});const dependencies = {- Constants: {ZWSP: "\u200b", ATTRIBUTE_EDITING: "data-editing"},+ Constants: {ZWSP: "\u200b", ATTRIBUTE_EDITING: "data-editing", BLOCK_HINT_KEYS: ["(("],+ INLINE_TYPE: ["strong", "code"], SIYUAN_RENDER_CODE_LANGUAGES: [] as string[], LOCAL_CODELANG: "codeLang"},dayjs: () => ({format: () => "20260924120000"}), isMobile: () => true,normalizeSemanticInlineElements: noop, removeEmptySemanticInlineElement: noop,getSemanticMarkerPrefixLengthForNode: () => 0, getTextWithoutSemanticMarkers: (node: Node) => node.textContent,turnIntoTaskList: () => false, headingTurnIntoList: () => false, isProtyleListItemFirstParagraph: () => false,mathRender: noop, hideElements: noop, scrollCenter: noop, focusByRange,+ stripSemanticMarkersFromRangeText: (range: Range) => range.toString(), getCaretGoalX: () => 0,+ loadTableCellEditor: async () => ({openTableCellRichEditor: (...args: Parameters<typeof activate>) => {+ opening = activate(...args);+ return opening;+ }}),transaction: (_owner: IProtyle, doOperations: IOperation[], undoOperations: IOperation[]) => {+ if (_owner.lite) {+ return;+ }changes.push({doOperations, undoOperations});},- updateTransaction: (owner: IProtyle, block: Element, oldHTML: string) => {+ updateTransaction: (owner: IProtyle, block: Element, oldHTML: string, undoContext?: Record<string, string>,+ additional?: {context: Record<string, string>}) => {+ if (owner.lite) {+ return;+ }changes.push({doOperations: [{action: "update", id: block.getAttribute("data-node-id"), data: api.cleanTableCellRichHTML(block.outerHTML)}],undoOperations: [{action: "update", id: block.getAttribute("data-node-id"), data: api.cleanTableCellRichHTML(oldHTML)}],+ undoContext, context: additional?.context,});owner.wysiwyg.lastHTMLs[block.getAttribute("data-node-id")] = api.cleanTableCellRichHTML(block.outerHTML);},};- const api = new Function(...Object.keys(dependencies), source + "\nreturn {input, insertRow, insertRowAbove, insertColumn, " ++ const api = new Function(...Object.keys(dependencies), source.replace('import("../render/tableCellRichEditor")',+ "loadTableCellEditor()") + "\nreturn {input, insertRow, insertRowAbove, insertColumn, " +"getAgentLute, configureAVRichTextLute, getTableCellEditorLute, getAVRichTextLute, " +"getTableCellRichBlockDOM, serializeTableCellRich, cleanTableCellRichHTML, renderTableCellRich, " +- "setTableCellRich, getTableCellInlineHTML, getSelectionOffset, focusByOffset};")(...Object.values(dependencies)) as+ "setTableCellRich, getTableCellInlineHTML, getSelectionOffset, focusByOffset, focusByWbr, " ++ "updateTableCellEditingValue, captureRichCellSelection, restoreRichCellSelection, " ++ "captureInlineCellSelection, restoreInlineCellSelection, " ++ "hasClosestBlock, hasClosestByClassName, getContenteditableElement, hasPreviousSibling, hasNextSibling, " ++ "isTableCellBlockSlash, navigateToRichTableCell};")(...Object.values(dependencies)) astypeof import("../wysiwyg/input") & typeof import("../util/table") & typeof import("./setLute") &typeof import("./av/richText") & typeof import("./av/richTextValue") & typeof import("../util/tableCellRichLute") &- typeof import("../util/tableCellRich") & typeof import("../util/selection");+ typeof import("../util/tableCellRich") & typeof import("../util/selection") &+ typeof import("../util/tableCellRichSelection") & typeof import("../util/hasClosest") &+ typeof import("../wysiwyg/getBlock") & typeof import("../util/tableCellRichMenu") &+ typeof import("../util/tableCellRichNavigation");const lute = api.configureAVRichTextLute(api.getAgentLute({emojiSite: "/emojis", emojis: {},headingAnchor: false, listStyle: false, paragraphBeginningSpace: true, sanitize: true}));const Queue = new Function(queueSource + "\nreturn InputQueue;")() as new () => {@@ -77,9 +101,11 @@ const browserCases = async (source: string, queueSource: string, editorSource: selement.appendChild(wysiwyg);document.body.appendChild(element);const table = wysiwyg.firstElementChild as HTMLElement;+ const hidden = document.createElement("div");+ hidden.className = "fn__none";const queue = Object.assign(new Queue(), {element: wysiwyg, lastHTMLs: {[table.dataset.nodeId]: table.outerHTML}});const owner = {element, wysiwyg: queue, lute, contentElement: wysiwyg, options: {typewriterMode: false},- hint: {render: noop},+ hint: {render: noop, element: hidden}, toolbar: {subElement: hidden},block: {rootID: "root"}, disabled: false} as unknown as IProtyle;const range = document.createRange();range.selectNodeContents(table.querySelector("th"));@@ -88,15 +114,22 @@ const browserCases = async (source: string, queueSource: string, editorSource: schanges.length = 0;return {owner, queue, element, wysiwyg, table, range};};+ const hintDependencies = {+ ...dependencies, ...api, isProtyleListItemFragment: () => false, isBuiltinSlashHint: () => true,+ shouldCaptureHintUndoFocus: () => false, processRender: noop, highlightRender: noop,+ };+ const Hint = new Function(...Object.keys(hintDependencies), hintSource + "\nreturn Hint;")(+ ...Object.values(hintDependencies)) as new () => IProtyle["hint"];const editorDependencies = {...dependencies, ...api, TABLE_CELL_INLINE_ATTRIBUTE: "data-sy-table-cell-inline",TABLE_CELL_RICH_ATTRIBUTE: "data-sy-table-cell-rich", TABLE_CELL_SLASH_IDS: new Set(),hintRef: noop, hintTag: noop, registerBuiltinSlashHint: (callback: unknown) => callback,- getDefaultToolbar: (): string[] => [], captureRichCellSelection: noop, updateOutlineCurrentBlock: noop,+ getDefaultToolbar: (): string[] => [], updateOutlineCurrentBlock: noop,+ getUndoFocusContext: () => ({}),setMobileToolbarUndo: noop, setTableCellRichContext: noop, bindTableCellRichDrag: noop,- bindLiteCodeActions: noop, updateTableCellContentLayout: noop,+ bindLiteCodeActions: noop, updateTableCellContentLayout: noop, renderTableCellRichElements: noop,showMessage: (message: string) => { throw new Error(message); },- mountProtyleLiteFragment: (host: HTMLElement, options: {initialBlockHTML: string}) => {+ mountProtyleLiteFragment: (host: HTMLElement, options: import("../lite/fragmentEditor").ProtyleLiteFragmentOptions) => {// 保留会被 Lute 误读为正文的界面,验证输入任务与实际挂载边界的交接。host.innerHTML = '<div class="protyle-content"><div class="protyle-wysiwyg">' +options.initialBlockHTML + '</div></div><div class="protyle-preview">DesktopTabletMobile</div>' +@@ -105,21 +138,27 @@ const browserCases = async (source: string, queueSource: string, editorSource: sconst wysiwyg = host.querySelector<HTMLElement>(".protyle-wysiwyg");const hidden = document.createElement("div");hidden.className = "fn__none";+ const observer = new MutationObserver(() => options.onChange());+ observer.observe(wysiwyg, {childList: true, characterData: true, subtree: true});return {wysiwyg, hintElement: hidden,- protyle: {block: {}, toolbar: {element: hidden, subElement: hidden}, undo: {clear: noop}},- getBlockHTML: () => wysiwyg.innerHTML, destroy: noop,+ protyle: {block: {}, element: host, wysiwyg: {element: wysiwyg}, lite: true,+ lute: options.runtimeCapabilities.lute, options: options.protyleOptions, hint: new Hint(),+ toolbar: {element: hidden, subElement: hidden, render: noop, showRender: noop}, undo: {clear: noop}},+ getBlockHTML: () => wysiwyg.innerHTML, destroy: () => observer.disconnect(),focus: () => {const range = document.createRange();- range.selectNodeContents(wysiwyg.querySelector('[contenteditable="true"]'));+ range.selectNodeContents(wysiwyg.querySelector('[contenteditable="true"]') || wysiwyg);range.collapse(true);focusByRange(range);},};},};- const open = new Function(...Object.keys(editorDependencies), editorSource + "\nreturn openTableCellRichEditor;")(+ const activate = new Function(...Object.keys(editorDependencies), editorSource + "\nreturn openTableCellRichEditor;")(...Object.values(editorDependencies)) as typeof import("./tableCellRichEditor").openTableCellRichEditor;+ const open = (owner: IProtyle, cell: HTMLTableCellElement) =>+ activate(owner, cell, undefined, undefined, undefined, true);const noUI = (html: string) => check.doesNotMatch(html, /DesktopTabletMobile|Font family|Font Size|search-mark-regression|table__cell-editor/);const operationHTML = (operation: IOperation) => {check.ok(typeof operation.data === "string");@@ -131,6 +170,96 @@ const browserCases = async (source: string, queueSource: string, editorSource: sawait tick();};+ {+ const {owner, element, table, range} = fixture();+ const cell = table.querySelector("th");+ await activate(owner, cell);+ check.equal(table.querySelector(".table__cell-editor"), null);+ check.equal(cell.textContent, "Hello");+ check.equal(changes.length, 0);+ for (const key of ["ArrowLeft", "ArrowRight"]) {+ await activate(owner, cell, {key, goalX: 0});+ const position = api.getSelectionOffset(cell, owner.wysiwyg.element, getSelection().getRangeAt(0));+ check.equal(position.start, key === "ArrowLeft" ? 5 : 0);+ check.equal(table.querySelector(".table__cell-editor"), null);+ }+ await activate(owner, cell, undefined, undefined,+ {startIndex: 0, endIndex: 0, start: 1, end: 4, backward: true});+ check.equal(getSelection().toString(), "ell");+ check.equal(getSelection().anchorOffset, 4);+ check.equal(table.querySelector(".table__cell-editor"), null, "undo restores inline selection without mounting");+ const rich = table.querySelectorAll("th")[1];+ api.setTableCellRich(rich, "first\n\nsecond");+ range.selectNodeContents(rich);+ range.collapse(true);+ focusByRange(range);+ await activate(owner, rich);+ check.ok(rich.querySelector(".table__cell-editor"));+ await activate(owner, cell, {key: "ArrowLeft", goalX: 0});+ check.equal(table.querySelector(".table__cell-editor"), null, "leaving a rich cell returns to direct inline editing");+ check.equal(api.getSelectionOffset(cell, owner.wysiwyg.element, getSelection().getRangeAt(0)).start, 5);+ const arrow = new KeyboardEvent("keydown", {key: "ArrowRight", bubbles: true, cancelable: true});+ check.equal(api.navigateToRichTableCell(owner, arrow), true);+ check.equal(arrow.defaultPrevented, true);+ await tick();+ await opening;+ check.ok(rich.querySelector(".table__cell-editor"), "horizontal navigation does not skip a read-only rich preview");+ await activate(owner, cell, {key: "ArrowLeft", goalX: 0});+ api.focusByOffset(cell, 2, 2);+ check.equal(api.navigateToRichTableCell(owner, arrow), false, "arrows inside inline text stay native");+ api.focusByOffset(cell, 5, 5);+ check.equal(api.navigateToRichTableCell(owner, new KeyboardEvent("keydown", {key: "ArrowRight", shiftKey: true})), false);+ await finish(element);+ }++ for (const prefix of ["", "before ", "**bold** "]) {+ for (const [value, type] of [["```", "NodeCodeBlock"], ["- " + Lute.Caret, "NodeList"],+ ["# " + Lute.Caret, "NodeHeading"], ["$$", "NodeMathBlock"]]) {+ const {owner, queue, element, table, range} = fixture();+ const cell = table.querySelector("th");+ cell.textContent = prefix + "/command";+ range.selectNodeContents(cell);+ range.collapse(false);+ range.setStart(cell.firstChild, cell.textContent.length);+ focusByRange(range);+ const pendingRange = range.cloneRange();+ queue.scheduleInput(() => api.input(owner, table, pendingRange));+ const hint = new Hint();+ hint.render = noop;+ hint.splitChar = "/";+ hint.lastIndex = prefix.length;+ owner.toolbar = {range} as IProtyle["toolbar"];+ owner.hint = hint;+ window.siyuan.storage.codeLang = "";+ hint.fill(value, owner, false);+ await tick();+ check.ok(await opening, "the command opens its target cell");+ await tick();+ const current = owner.wysiwyg.element.querySelector("table");+ const editedCell = current.querySelector("th");+ check.ok(editedCell.querySelector(`.table__cell-editor [data-type="${type}"]`), value + editedCell.outerHTML);+ check.doesNotMatch(editedCell.querySelector(".protyle-wysiwyg").textContent, /\/command/);+ check.ok(editedCell.hasAttribute("data-sy-table-cell-rich"));+ check.equal(current.querySelectorAll("th")[1].textContent, "Keep");+ check.equal(current.querySelectorAll("tr").length, 3);+ check.equal(changes.length, 2, "pending input and the command each produce one outer table transaction");+ check.match(operationHTML(changes[1].undoOperations[0]), /\/command/);+ operationHTML(changes[1].doOperations[0]);+ const command = changes[1];+ current.closest('[data-type="NodeTable"]').outerHTML = operationHTML(command.undoOperations[0]);+ await tick();+ const restored = owner.wysiwyg.element.querySelector("th");+ await activate(owner, restored, undefined, undefined, JSON.parse(command.undoContext.undoFocusTableSelection));+ check.equal(getSelection().toString(), "/command", "undo selects the original command in the inline cell");+ check.equal(restored.querySelector(".table__cell-editor"), null);+ restored.closest('[data-type="NodeTable"]').outerHTML = operationHTML(command.doOperations[0]);+ await activate(owner, owner.wysiwyg.element.querySelector("th"), undefined, undefined,+ JSON.parse(command.context.undoFocusTableSelection));+ check.ok(owner.wysiwyg.element.querySelector(`.table__cell-editor [data-type="${type}"]`));+ await finish(element);+ }+ }+for (const count of [1, 5]) {for (const running of [false, true]) {for (const text of ["", "**pending**"]) {@@ -295,6 +424,8 @@ test("table cell editors wait for outer input and table menu Enter is consumed",const source = ["../util/longTextWrap.ts", "../util/inlineElementBoundary.ts", "../toolbar/fontFamilyCore.ts","../../util/escape.ts", "setLute.ts", "../wysiwyg/codeBlockUtil.ts", "av/richTextValue.ts", "av/richText.ts","../wysiwyg/taskListMarker.ts", "../util/tableCellRichLute.ts", "../util/tableCellRichValue.ts", "../util/tableCellRich.ts",+ "../util/trackedRangeAnchor.ts", "../util/tableCellRichSelection.ts", "../util/tableCellRichMenu.ts",+ "../util/tableCellRichNavigation.ts","../util/hasClosest.ts", "../wysiwyg/getBlock.ts", "../util/table.ts", "../wysiwyg/input.ts"].map(file => compile(read(file))).join("\n") + "\n" + compile(selectionSource);const wysiwyg = createSourceFile("wysiwyg.ts", read("../wysiwyg/index.ts"), ScriptTarget.Latest, true);@@ -305,6 +436,11 @@ test("table cell editors wait for outer input and table menu Enter is consumed",const menu = read("../../menus/protyle.ts");const menuStart = menu.indexOf("const insertMenus = [];", menu.indexOf("export const tableMenu"));const menuSource = compile(menu.substring(menuStart, menu.indexOf("menus.push(...insertMenus);", menuStart)));+ const hint = createSourceFile("hint.ts", read("../hint/index.ts"), ScriptTarget.Latest, true);+ const hintMembers = hint.statements.find(isClassDeclaration).members.filter(member =>+ ["fill", "fixImageCursor"].includes(member.name?.getText(hint)));+ const hintSource = compile("class Hint {" + hintMembers.map(member => member.getText(hint)).join("\n") + "}")+ .replace('import("../render/tableCellRichEditor")', "loadTableCellEditor()");const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-table-cell-input-test-"));const script = path.join(temporary, "run.cjs");const lutePath = path.resolve(__dirname, "../../../stage/protyle/js/lute/lute.min.js");@@ -317,7 +453,7 @@ app.whenReady().then(async () => {await win.loadURL("data:text/html,<html><body></body></html>");await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(lutePath)}, "utf8"));console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +- browserCases.toString() + ")(" + [source, queue, compile(read("tableCellRichEditor.ts")), menuSource]+ browserCases.toString() + ")(" + [source, queue, compile(read("tableCellRichEditor.ts")), menuSource, hintSource].map(value => JSON.stringify(value)).join(",") + ")")}));win.destroy();app.exit(0);diff --git a/app/src/protyle/render/tableCellRichEditor.ts b/app/src/protyle/render/tableCellRichEditor.tsindex 7f8eb5334b..6286e6de88 100644--- a/app/src/protyle/render/tableCellRichEditor.ts+++ b/app/src/protyle/render/tableCellRichEditor.ts@@ -19,7 +19,7 @@ import {focusEditableAtGoalX, getCaretGoalX} from "../wysiwyg/verticalCaret";import {fixTable} from "../util/table";import {updateTableCellContentLayout} from "../util/tableCellRich";import {TABLE_CELL_SLASH_IDS} from "../util/tableCellRichMenu";-import {captureRichCellSelection, captureRichCellSelectionAtPoint, restoreRichCellSelection} from "../util/tableCellRichSelection";+import {captureInlineCellSelection, captureRichCellSelection, captureRichCellSelectionAtPoint, restoreInlineCellSelection, restoreRichCellSelection} from "../util/tableCellRichSelection";import {matchHotKey} from "../util/hotKey";import {bindTableCellRichDrag} from "../util/tableCellRichDrag";import {getTableCellEditorLute} from "../util/tableCellRichLute";@@ -85,7 +85,7 @@ export const applyTableCellRichInlineMark = (owner: IProtyle, cells: HTMLTableCeexport const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCellElement,navigation?: {key: string, goalX: number}, point?: {x: number, y: number, target?: Element},- restoredSelection?: ReturnType<typeof captureRichCellSelection>) => {+ restoredSelection?: ReturnType<typeof captureRichCellSelection>, convert = false) => {if (owner.disabled || !cell.isConnected || activeEditor?.cell === cell) {return;}@@ -99,6 +99,27 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCe}const request = {};openingEditor = request;+ if (!convert && !cell.hasAttribute(TABLE_CELL_RICH_ATTRIBUTE)) {+ // 普通单元格直接编辑,跨单元格导航保留进入方向和光标横坐标。+ owner.wysiwyg.element.focus({preventScroll: true});+ if (restoredSelection) {+ const range = focusByOffset(cell, restoredSelection.start, restoredSelection.end);+ if (range && restoredSelection.backward) {+ getSelection().setBaseAndExtent(range.endContainer, range.endOffset, range.startContainer, range.startOffset);+ }+ } else if (navigation) {+ const backward = navigation.key === "ArrowLeft" || navigation.key === "ArrowUp";+ if (!["ArrowUp", "ArrowDown"].includes(navigation.key) ||+ !focusEditableAtGoalX(cell, backward ? "up" : "down", navigation.goalX, owner.contentElement)) {+ const range = document.createRange();+ range.selectNodeContents(cell);+ range.collapse(!backward);+ focusByRange(range);+ }+ }+ updateOutlineCurrentBlock(owner, cell);+ return;+ }const tableID = table.dataset.nodeId;const tableParent = table.parentElement;const rowIndex = (cell.parentElement as HTMLTableRowElement).rowIndex;@@ -107,6 +128,8 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCeconst clickedMath = point?.target?.closest('[data-subtype="math"]');const clickedMathIndex = clickedMath && cell.contains(clickedMath) ?Array.from(cell.querySelectorAll('[data-subtype="math"]')).indexOf(clickedMath) : -1;+ const commandSelection = convert && !cell.hasAttribute(TABLE_CELL_RICH_ATTRIBUTE) && getSelection().rangeCount ?+ captureInlineCellSelection(cell, getSelection().getRangeAt(0)) : undefined;// 外层输入先完成解析和事务,避免把即将挂载的单元格编辑界面当作正文。await owner.wysiwyg.flushPendingInput();if (openingEditor !== request || owner.disabled || !owner.element.isConnected) {@@ -119,6 +142,9 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCeif (!cell?.isConnected || cell.closest(".protyle-wysiwyg") !== owner.wysiwyg.element || activeEditor) {return;}+ if (commandSelection && !restoreInlineCellSelection(cell, commandSelection)) {+ return;+ }let initialBlockHTML: string;let source: string;try {@@ -508,12 +534,12 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCeconst mathElement = fragment.wysiwyg.querySelectorAll('[data-subtype="math"]')[clickedMathIndex];if (mathElement) {fragment.protyle.toolbar.showRender(fragment.protyle, mathElement);- return;+ return fragment.protyle;}}if (restoredSelection && restoreRichCellSelection(fragment.wysiwyg, restoredSelection)) {undoSelection = restoredSelection;- return;+ return fragment.protyle;}if (navigation) {const editables = fragment.wysiwyg.querySelectorAll<HTMLElement>('[contenteditable="true"]');@@ -522,38 +548,40 @@ export const openTableCellRichEditor = async (owner: IProtyle, cell: HTMLTableCeif (edit) {if ((navigation.key === "ArrowUp" || navigation.key === "ArrowDown") &&focusEditableAtGoalX(edit, backward ? "up" : "down", navigation.goalX, owner.contentElement)) {- return;+ return fragment.protyle;}const range = document.createRange();range.selectNodeContents(edit);range.collapse(!backward);focusByRange(range);}- return;+ return fragment.protyle;}if (clickedSelection && restoreRichCellSelection(fragment.wysiwyg, clickedSelection)) {- return;+ return fragment.protyle;}if (richSelection && (preserveSelection || !point) && restoreRichCellSelection(fragment.wysiwyg, richSelection)) {if (preserveSelection) {fragment.protyle.toolbar.render(fragment.protyle, getSelection().getRangeAt(0));}- return;+ return fragment.protyle;}if (point && !preserveSelection) {const range = document.caretRangeFromPoint(point.x, point.y);if (range && fragment.wysiwyg.contains(range.startContainer)) {focusByRange(range);- return;+ return fragment.protyle;}}if (initialOffset) {const edit = fragment.wysiwyg.querySelector('[contenteditable="true"]');if (edit) {focusByOffset(edit, initialOffset.start, initialOffset.end);+ undoSelection = captureRichCellSelection(fragment.wysiwyg, getSelection());if (preserveSelection) {fragment.protyle.toolbar.render(fragment.protyle, getSelection().getRangeAt(0));}}}+ return fragment.protyle;};diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.tsindex 35f6bdd3b3..d45a2f84d8 100644--- a/app/src/protyle/util/tableCellRichLute.test.ts+++ b/app/src/protyle/util/tableCellRichLute.test.ts@@ -13,12 +13,12 @@ const browserCases = async (source: string, enterSource: string, hintSource: strconst codeTabAttribute = "custom-sy-code-tab-spaces";const api = new Function("Constants", source + "\nreturn {getAgentLute, configureAVRichTextLute, getTableCellEditorLute, " +"canEnterCodeBlock, hasCodeBlockFence, getTableCellInlineHTML, serializeTableCellRich, " +- "updateTableCellEditingValue, getTableCellRichBlockDOM, sanitizeAVRichTextBlockDOM};")({+ "updateTableCellEditingValue, getTableCellRichBlockDOM, sanitizeAVRichTextBlockDOM, isTableCellBlockSlash};")({CUSTOM_SY_CODE_TAB_SPACES: codeTabAttribute,}) astypeof import("../render/setLute") & typeof import("../render/av/richTextValue") &typeof import("./tableCellRichLute") & typeof import("../wysiwyg/codeBlockEnter") &- typeof import("./tableCellRich") & typeof import("../render/av/richText");+ typeof import("./tableCellRich") & typeof import("../render/av/richText") & typeof import("./tableCellRichMenu");const base = api.configureAVRichTextLute(api.getAgentLute({emojiSite: "/emojis", emojis: {},headingAnchor: false, listStyle: false, paragraphBeginningSpace: true, sanitize: true}));const lute = api.getTableCellEditorLute(base);@@ -529,7 +529,7 @@ test("table cells insert code through slash and Enter without losing soft breaksconst source = ["longTextWrap.ts", "inlineElementBoundary.ts", "../toolbar/fontFamilyCore.ts", "../../util/escape.ts","../render/setLute.ts", "../wysiwyg/codeBlockUtil.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");+ "tableCellRich.ts", "tableCellRichMenu.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");diff --git a/app/src/protyle/util/tableCellRichMenu.ts b/app/src/protyle/util/tableCellRichMenu.tsindex 14cfd10ab4..f0cafd6e87 100644--- a/app/src/protyle/util/tableCellRichMenu.ts+++ b/app/src/protyle/util/tableCellRichMenu.ts@@ -3,3 +3,8 @@ export const TABLE_CELL_SLASH_IDS = new Set(["quote", "code", "math", "link", "bold", "italic", "underline", "strike", "mark", "sup", "sub", "inlineCode","kbd", "tag", "inlineMath",]);++export const isTableCellBlockSlash = (value: string) =>+ value === "```" || value === "$$" ||+ ["# ", "## ", "### ", "#### ", "##### ", "###### ", "- ", "1. ", "- [ ] ", "> "]+ .some(prefix => value === prefix + Lute.Caret);diff --git a/app/src/protyle/util/tableCellRichNavigation.ts b/app/src/protyle/util/tableCellRichNavigation.tsindex 9f3073f140..bb59e88968 100644--- a/app/src/protyle/util/tableCellRichNavigation.ts+++ b/app/src/protyle/util/tableCellRichNavigation.ts@@ -1,12 +1,14 @@import {buildTableGrid, getVerticalTableCell} from "./table";-import {isCaretAtVerticalBoundary} from "../wysiwyg/verticalCaret";+import {getCaretGoalX, isCaretAtVerticalBoundary} from "../wysiwyg/verticalCaret";import {stripSemanticMarkersFromRangeText} from "./inlineElementMarker";+import {TABLE_CELL_RICH_ATTRIBUTE} from "./tableCellRichValue";export const isTableCellCaretAtBoundary = (element: HTMLElement, range: Range, key: string) => {if (!range.collapsed || !element.contains(range.startContainer)) {return false;}- const editables = Array.from(element.querySelectorAll<HTMLElement>('[contenteditable="true"]'));+ const editables = element.matches("td, th") ? [element] :+ Array.from(element.querySelectorAll<HTMLElement>('[contenteditable="true"]'));const backward = key === "ArrowLeft" || key === "ArrowUp";const editable = backward ? editables[0] : editables[editables.length - 1];if (!editable?.contains(range.startContainer)) {@@ -38,3 +40,31 @@ export const getAdjacentRichTableCell = (cell: HTMLTableCellElement, key: stringconst index = cellInfos.findIndex(info => info.cell === cell);return index < 0 ? undefined : cellInfos[index + (key === "ArrowLeft" ? -1 : 1)]?.cell;};++export const navigateToRichTableCell = (protyle: IProtyle, event: KeyboardEvent) => {+ if (protyle.disabled || event.isComposing || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey ||+ !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key) ||+ !protyle.hint.element.classList.contains("fn__none") ||+ !protyle.toolbar.subElement.classList.contains("fn__none") ||+ protyle.wysiwyg.element.querySelector(".protyle-wysiwyg--select")) {+ return false;+ }+ const selection = getSelection();+ const range = selection.rangeCount ? selection.getRangeAt(0) : undefined;+ const element = range?.startContainer instanceof Element ? range.startContainer : range?.startContainer.parentElement;+ const cell = element?.closest<HTMLTableCellElement>("td, th");+ if (!cell || cell.hasAttribute(TABLE_CELL_RICH_ATTRIBUTE) ||+ cell.closest(".protyle-wysiwyg") !== protyle.wysiwyg.element || !isTableCellCaretAtBoundary(cell, range, event.key)) {+ return false;+ }+ const next = getAdjacentRichTableCell(cell, event.key);+ if (!next?.hasAttribute(TABLE_CELL_RICH_ATTRIBUTE)) {+ return false;+ }+ // 富内容预览不可直接编辑,边界导航需要显式进入其片段编辑器。+ const navigation = {key: event.key, goalX: getCaretGoalX(range)};+ event.preventDefault();+ event.stopPropagation();+ void import("../render/tableCellRichEditor").then(module => module.openTableCellRichEditor(protyle, next, navigation));+ return true;+};diff --git a/app/src/protyle/util/tableCellRichSelection.ts b/app/src/protyle/util/tableCellRichSelection.tsindex 1d4c7b0efd..65b86449ea 100644--- a/app/src/protyle/util/tableCellRichSelection.ts+++ b/app/src/protyle/util/tableCellRichSelection.ts@@ -1,4 +1,25 @@import {focusByOffset, focusByRange, getSelectionOffset} from "./selection";+import {mapTrackedTokenRange} from "./trackedRangeAnchor";++const getInlineCellSelectionText = (cell: Element) => {+ const clone = cell.cloneNode(true) as Element;+ // 与选区偏移一致,软换行和表情各占一个额外位置。+ clone.querySelectorAll("br, .emoji").forEach(element => element.before("\n"));+ return clone.textContent.split("");+};++export const captureInlineCellSelection = (cell: Element, range: Range) => {+ if (!cell.contains(range.startContainer) || !cell.contains(range.endContainer)) {+ return;+ }+ return {text: getInlineCellSelectionText(cell), ...getSelectionOffset(cell, undefined, range)};+};++export const restoreInlineCellSelection = (cell: Element, saved: ReturnType<typeof captureInlineCellSelection>) => {+ const mapped = mapTrackedTokenRange(saved.text, getInlineCellSelectionText(cell), saved,+ saved.start === saved.end, "before");+ return mapped && focusByOffset(cell, mapped.start, mapped.end);+};const getCellEditables = (root: Element) => Array.from(root.querySelectorAll<HTMLElement>('[data-type="NodeParagraph"] > [contenteditable]:not(.protyle-attr), ' +diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 2383143159..80bc38da86 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -43,6 +43,8 @@ import {} from "../util/selection";import {Constants} from "../../constants";import {mergeTableCellContents} from "../util/tableCellRich";+import {TABLE_CELL_RICH_ATTRIBUTE} from "../util/tableCellRichValue";+import {navigateToRichTableCell} from "../util/tableCellRichNavigation";import {resolveDocumentBlockElement} from "../util/outlineBlock";import {isMobile} from "../../util/functions";import {previewDocImage} from "../preview/image";@@ -4001,7 +4003,7 @@ export class WYSIWYG {};this.element.addEventListener("keyup", (event: KeyboardEvent) => {if (event.isComposing || protyle.disabled || event.ctrlKey || event.metaKey || event.altKey ||- !["Tab", "Enter", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key) ||+ !["Tab", "Enter", "Backspace", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key) ||(event.shiftKey && event.key !== "Tab")) {return;}@@ -4009,11 +4011,15 @@ export class WYSIWYG {const target = selection?.focusNode;const element = target instanceof Element ? target : target?.parentElement;const cell = element?.closest<HTMLTableCellElement>("th, td");- if (cell && cell.closest(".protyle-wysiwyg") === this.element && cell.contains(selection.anchorNode)) {+ if (cell?.hasAttribute(TABLE_CELL_RICH_ATTRIBUTE) &&+ cell.closest(".protyle-wysiwyg") === this.element && cell.contains(selection.anchorNode)) {void import("../render/tableCellRichEditor").then(module => module.openTableCellRichEditor(protyle, cell));}});this.element.addEventListener("keydown", (event: KeyboardEvent) => {+ if (navigateToRichTableCell(protyle, event)) {+ return;+ }if ((event.key === "Backspace" || event.key === "Delete") && getSelection().rangeCount > 0) {prepareInlineElementBoundaryMutation(getSelection().getRangeAt(0));}@@ -4638,7 +4644,8 @@ export class WYSIWYG {event.preventDefault();return;}- if (richCell && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey && !protyle.disabled &&+ if (richCell?.hasAttribute(TABLE_CELL_RICH_ATTRIBUTE) &&+ !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey && !protyle.disabled &&richCell.closest(".protyle-wysiwyg") === this.element &&!event.target.closest("a, [data-type~='block-ref'], [data-type~='a'], img")) {event.preventDefault();