An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Align table insertion for keyboard block selections
Daniel889a8d7d5cb1
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.syindex 70d074bf57..8f1ee6bda8 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy@@ -7,7 +7,7 @@"id": "20200924100950-9op5xi1","title": "Shortcuts","type": "doc",- "updated": "20261018200107"+ "updated": "20261019212821"},"Children": [{@@ -16,7 +16,7 @@"HeadingLevel": 2,"Properties": {"id": "20260928091747-wub2unw",- "updated": "20261015193140"+ "updated": "20261019212821"},"Children": [{@@ -116,6 +116,29 @@}]},+ {+ "ID": "20261019212821-369b5d7",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261019212821-369b5d7",+ "updated": "20261019212821"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "The table insertion shortcut replaces selected text or a continuous selection of text blocks with one empty table, including blocks selected using "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Shift + ↑/↓"+ },+ {+ "Type": "NodeText",+ "Data": ". Mouse and keyboard selections follow the same rule, and one undo restores the replaced content. To keep the original text, clear the selection and move the caret to the desired insertion position first."+ }+ ]+ },{"ID": "20261011091952-wqpp0rc","Type": "NodeParagraph",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.syindex 409400889a..d6dd6e7f49 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy@@ -7,7 +7,7 @@"id": "20200813004551-gm0pbn1","title": "快捷键","type": "doc",- "updated": "20261018200107"+ "updated": "20261019212821"},"Children": [{@@ -16,7 +16,7 @@"HeadingLevel": 2,"Properties": {"id": "20260928091747-w9nonqj",- "updated": "20261015193140"+ "updated": "20261019212821"},"Children": [{@@ -116,6 +116,29 @@}]},+ {+ "ID": "20261019212821-61a1d4f",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261019212821-61a1d4f",+ "updated": "20261019212821"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "插入表格快捷键会用一个空表格替换选中的文字或连续的文本块,包括通过 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Shift + ↑/↓"+ },+ {+ "Type": "NodeText",+ "Data": " 选中的块。鼠标和键盘选择遵循相同规则,一次撤销可恢复被替换的内容。若要保留原文,请先取消选择,再将光标移到需要插表的位置。"+ }+ ]+ },{"ID": "20261011091952-vdfybuu","Type": "NodeParagraph",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.syindex c2e2b6bf4a..b412c9b8b4 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy@@ -7,7 +7,7 @@"id": "20211226122549-jktxego","title": "快捷鍵","type": "doc",- "updated": "20261018200107"+ "updated": "20261019212821"},"Children": [{@@ -16,7 +16,7 @@"HeadingLevel": 2,"Properties": {"id": "20260928091747-a3qlogr",- "updated": "20261015193140"+ "updated": "20261019212821"},"Children": [{@@ -116,6 +116,29 @@}]},+ {+ "ID": "20261019212821-35049fc",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261019212821-35049fc",+ "updated": "20261019212821"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "插入表格快捷鍵會用一個空表格取代選取的文字或連續的文字區塊,包括透過 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Shift + ↑/↓"+ },+ {+ "Type": "NodeText",+ "Data": " 選取的區塊。滑鼠和鍵盤選取遵循相同規則,一次復原即可還原被取代的內容。若要保留原文,請先取消選取,再將游標移至需要插入表格的位置。"+ }+ ]+ },{"ID": "20261011091952-z1utga6","Type": "NodeParagraph",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.syindex 6914ae2a30..794991bdc6 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy@@ -9,7 +9,7 @@"id": "20240530101000-xsbxokr","title": "ショートカット","type": "doc",- "updated": "20261018200107"+ "updated": "20261019212821"},"Children": [{@@ -18,7 +18,7 @@"HeadingLevel": 2,"Properties": {"id": "20260928091747-t67pljp",- "updated": "20261015193140"+ "updated": "20261019212821"},"Children": [{@@ -110,6 +110,29 @@}]},+ {+ "ID": "20261019212821-e67bd42",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261019212821-e67bd42",+ "updated": "20261019212821"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "表の挿入ショートカットは、選択したテキストまたは連続するテキストブロックを一つの空の表に置き換えます。"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Shift + ↑/↓"+ },+ {+ "Type": "NodeText",+ "Data": " で選択したブロックにも同じルールが適用され、マウスとキーボードで動作が統一されています。一度の元に戻す操作で、置き換えた内容を復元できます。元の文章を残す場合は、選択を解除してから、表を挿入したい位置にカーソルを移動してください。"+ }+ ]+ },{"ID": "20261011091952-yanstq2","Type": "NodeParagraph",diff --git a/app/src/protyle/hint/fillCommand.test.ts b/app/src/protyle/hint/fillCommand.test.tsindex 8b91198661..00624f4b8b 100644--- a/app/src/protyle/hint/fillCommand.test.ts+++ b/app/src/protyle/hint/fillCommand.test.ts@@ -145,6 +145,7 @@ for (const scenario of ["database shortcut", "database mobile toolbar", "tag sea}})},hideElements() {}, isProtyleListItemFragment: () => false,getEditorRange: () => { rangeReads++; return range; },+ getBlockOperationElements: (): Element[] => [], getBlockSelectionModeElement: (): undefined => undefined,hasClosestBlock: (node: unknown) => node === original ? original : null,hasClosestByClassName: () => false,shouldCaptureHintUndoFocus, getUndoFocusContext: () => ({}),diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex a4ebdd5d5d..2b70a59242 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -1,6 +1,8 @@import {isTableLikeView} from "../render/av/viewType";import {Constants} from "../../constants";import {isBuiltinSlashHint} from "./builtinSlash";+import {getTableBlockSelectionRange} from "./tableInsertion";+import {getBlockOperationElements, getBlockSelectionModeElement} from "../wysiwyg/blockSelection";import {getSuperBlockCommandLayout} from "../../block/superBlock";import {genEmptySuperBlock} from "../../block/insertSuperBlock";import {@@ -1054,6 +1056,20 @@ ${genHintItemHTML(item)}// 直接插入命令使用正文选区,不沿用候选面板的来源和触发位置。public fillCommand(value: string, protyle: IProtyle, updateRange = true, slashEntryKey?: string) {+ if (value.startsWith("|")) {+ const elements = getBlockOperationElements(protyle.wysiwyg.element,+ getBlockSelectionModeElement(protyle.wysiwyg.element));+ if (elements.length > 0) {+ const range = getTableBlockSelectionRange(protyle.wysiwyg.element, elements);+ if (!range) {+ return;+ }+ hideElements(["select"], protyle);+ protyle.toolbar.range = range;+ focusByRange(range);+ updateRange = false;+ }+ }this.source = "hint";this.splitChar = "/";this.lastIndex = -1;diff --git a/app/src/protyle/hint/tableInsertion.ts b/app/src/protyle/hint/tableInsertion.tsnew file mode 100644index 0000000000..41f2677daf--- /dev/null+++ b/app/src/protyle/hint/tableInsertion.ts@@ -0,0 +1,26 @@+import {getContenteditableElement, getFirstBlock, getLastBlock} from "../wysiwyg/getBlock";+import {isContinuousBlockSelection} from "../wysiwyg/blockSelection";+import {hasClosestBlock, isInEmbedBlock} from "../util/hasClosest";++// 块选择的原生 Range 已折叠,插表前恢复与鼠标完整选择相同的正文范围。+export const getTableBlockSelectionRange = (editorElement: HTMLElement, selectedElements: Element[]) => {+ const elements = selectedElements.filter(element => editorElement.contains(element) &&+ !selectedElements.some(parent => parent !== element && parent.contains(element)));+ if (!isContinuousBlockSelection(elements)) {+ return undefined;+ }+ const first = getFirstBlock(elements[0]);+ const last = getLastBlock(elements[elements.length - 1]);+ const start = getContenteditableElement(first);+ const end = getContenteditableElement(last);+ if (!start || !end || isInEmbedBlock(first) || isInEmbedBlock(last) ||+ ![first, last].every(element =>+ ["NodeParagraph", "NodeHeading", "NodeCodeBlock"].includes(element.getAttribute("data-type"))) ||+ hasClosestBlock(start) !== first || hasClosestBlock(end) !== last) {+ return undefined;+ }+ const range = document.createRange();+ range.setStart(start, 0);+ range.setEnd(end, end.childNodes.length);+ return range;+};diff --git a/app/tests/fillCommand.test.js b/app/tests/fillCommand.test.jsindex b37d7a8c62..7e7aa0bfe9 100644--- a/app/tests/fillCommand.test.js+++ b/app/tests/fillCommand.test.js@@ -19,11 +19,29 @@ const compile = () => {assert.ok(declaration);const methods = declaration.members.filter(member => ["fillCommand", "fill", "consumeRefBracketClose","fixImageCursor", "openNewTableCell"].includes(member.name?.getText(hint))).map(member => member.getText(hint));+ const keyboard = ts.createSourceFile("keydown", read("wysiwyg/keydown"), ts.ScriptTarget.Latest, true);+ const keyboardCases = [];+ const visit = node => {+ if (ts.isIfStatement(node) && [+ 'matchHotKey("⇧↑", event)', 'matchHotKey("⇧↓", event)',+ "matchHotKey(window.siyuan.config.keymap.editor.insert.table, event) && !isInEmbedBlock(nodeElement)",+ ].includes(node.expression.getText(keyboard).replace(/\s+/g, " "))) keyboardCases.push(node.getText(keyboard));+ ts.forEachChild(node, visit);+ };+ visit(keyboard);+ assert.equal(keyboardCases.length, 3);// 使用真实命令、跨块事务、选区解析和块定位,只替换界面渲染及事务传输。return ts.transpileModule([read("util/hasClosest").replace(/^export /gm, ""),extract("wysiwyg/getBlock", ["getContenteditableElement", "getParentBlock", "getPreviousBlockSibling",- "getNextBlockSibling", "hasPreviousSibling", "hasNextSibling", "isEndOfBlock"]),+ "getNextBlockSibling", "hasPreviousSibling", "hasNextSibling", "isEndOfBlock", "getFirstBlock",+ "getLastBlock", "getNextBlock", "getPreviousBlock"]),+ extract("wysiwyg/blockSelection", ["BLOCK_SELECTION_CLASS", "BLOCK_SELECTION_MODE_CLASS", "clearSelectionState",+ "getBlockSelectionModeElement", "getBlockOperationElements", "isContinuousBlockSelection",+ "clearBlockSelection", "clearBlockSelectionMode"]),+ extract("hint/tableInsertion", ["getTableBlockSelectionRange"]),+ extract("wysiwyg/commonHotkey", ["extendSelectionToBlockEdge", "getSelectionFocus", "upSelect", "downSelect",+ "getStartEndElement"]),extract("util/selectionOffsets", ["selectIsEditor", "getSelectionOffset", "focusByRange"]),extract("util/selection", ["getBlockRanges", "getUndoFocusContext", "focusByWbr"]),extract("render/tabsVisibility", ["isHiddenTabContent"]),@@ -33,8 +51,15 @@ const compile = () => {extract("hint/blockHintRange", ["shouldCaptureHintUndoFocus"]),extract("util/insertHTML", ["markFoldHeadingChildren", "insertHTML"]),extract("wysiwyg/transaction", ["updateTransaction"]),+ `const keyboardHandler = (protyle, event) => {+ const editorElement = protyle.wysiwyg.element;+ const range = getEditorRange(editorElement);+ const nodeElement = hasClosestBlock(range.startContainer);+ const blockSelectionModeElement = getBlockSelectionModeElement(editorElement);+ ${keyboardCases.join("\n")}+ };`,`class Hint {${methods.join("\n")}}`,- "return {Hint};",+ "return {Hint, keyboardHandler, clearBlockSelectionMode};",].join("\n"), {compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS}}).outputText;};@@ -74,7 +99,16 @@ const runCases = async source => {Lute,Constants: {BLOCK_HINT_KEYS: ["(("], INLINE_TYPE: [], ZWSP: "\u200b", ATTRIBUTE_EDITING: "data-editing"},dayjs: () => ({format: () => "20261019120000"}),- hideElements() {},+ hideElements: (panels, protyle) => {+ if (panels.includes("select")) clearBlockSelectionMode(protyle.wysiwyg.element, true);+ },+ isMac: () => false,+ matchHotKey: (key, event) => key === "F6" ? event.key === "F6" :+ key === "⇧↑" ? event.shiftKey && event.key === "ArrowUp" :+ key === "⇧↓" ? event.shiftKey && event.key === "ArrowDown" : false,+ getVerticalCaretRect: (_element, range) => range.getBoundingClientRect(),+ countBlockWord() {},+ preventScroll() {},isMobile: () => mobile,isProtyleListItemFragment: () => false,getEditorRange: () => getSelection().getRangeAt(0),@@ -102,13 +136,21 @@ const runCases = async source => {return {openTableCellRichEditor: (_protyle, cell) => openedCells.push(cell)};},};- const {Hint} = new Function(...Object.keys(dependencies), source)(...Object.values(dependencies));+ window.siyuan = {config: {keymap: {editor: {general: {expandUp: "alt-up", expandDown: "alt-down"},+ insert: {table: "F6"}}}}};+ const {Hint, keyboardHandler, clearBlockSelectionMode} = new Function(...Object.keys(dependencies), source)(...Object.values(dependencies));const hint = new Hint();const protyle = {toolbar: {getCurrentType: () => []}, wysiwyg: {element: editor},- block: {parentID: "document"}, lute};+ block: {parentID: "document"}, lute, hint, contentElement: editor, scroll: {lastScrollTop: 0}};+ editor.addEventListener("keydown", event => keyboardHandler(protyle, event));const normalize = element => {const clone = element.cloneNode(true);clone.querySelectorAll("wbr").forEach(item => item.remove());+ clone.querySelectorAll(".protyle-wysiwyg--select, .protyle-wysiwyg--select-mode").forEach(item => {+ item.classList.remove("protyle-wysiwyg--select", "protyle-wysiwyg--select-mode");+ item.removeAttribute("select-start");+ item.removeAttribute("select-end");+ });clone.querySelectorAll("[data-editing], [updated]").forEach(item => {item.removeAttribute("data-editing");item.removeAttribute("updated");@@ -145,7 +187,8 @@ const runCases = async source => {for (mobile of [false, true]) {for (const layout of ["paragraphs", "blockquote", "list", "ordered-list", "task-list"]) {for (const selection of ["partial-forward", "partial-backward", "full", "start-at-end", "end-at-start",- "element-boundary", "single", "collapsed"]) {+ "element-boundary", "single", "collapsed", "blocks", "block-mode", "keyboard-up", "keyboard-down"]) {+ if (selection.startsWith("keyboard") && (mobile || !["paragraphs", "blockquote"].includes(layout))) continue;const label = `${mobile ? "mobile" : "desktop"}/${layout}/${selection}`;const md = layout === "blockquote" ? "> AAAA\n>\n> BBBB\n>\n> CCCC\n\noutside" :layout === "list" ? "- AAAA\n- BBBB\n- CCCC\n\noutside" :@@ -166,6 +209,25 @@ const runCases = async source => {if (selection === "element-boundary") {getSelection().setBaseAndExtent(first.parentElement, first.parentElement.childNodes.length, last, 2);}+ if (selection === "blocks") {+ Array.from(paragraphs).slice(0, 3).forEach(item =>+ (item.closest(".li") || item).classList.add("protyle-wysiwyg--select"));+ getSelection().collapse(first, 2);+ } else if (selection === "block-mode") {+ paragraphs[0].classList.add("protyle-wysiwyg--select-mode");+ getSelection().collapse(first, 2);+ } else if (selection.startsWith("keyboard")) {+ const up = selection === "keyboard-up";+ getSelection().collapse(up ? last : first, up ? 0 : 4);+ for (let i = 0; i < 3; i++) {+ const event = new KeyboardEvent("keydown", {key: up ? "ArrowUp" : "ArrowDown",+ shiftKey: true, bubbles: true, cancelable: true});+ editor.dispatchEvent(event);+ check.ok(event.defaultPrevented, label + ": keyboard selection handled");+ }+ check.equal(editor.querySelectorAll(".protyle-wysiwyg--select").length, 3, label + ": three blocks selected");+ check.ok(getSelection().isCollapsed, label + ": native range collapsed by block selection");+ }protyle.toolbar.range = getSelection().getRangeAt(0).cloneRange();const rangeOwner = node => (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement).closest("[data-node-id]").dataset.nodeId;@@ -177,7 +239,11 @@ const runCases = async source => {openedCells = [];const original = normalize(editor);const replayed = editor.cloneNode(true);- hint.fillCommand(`| ${Lute.Caret} | | |\n| --- | --- | --- |\n| | | |\n| | | |`, protyle, !mobile);+ if (selection.startsWith("keyboard")) {+ editor.dispatchEvent(new KeyboardEvent("keydown", {key: "F6", bubbles: true, cancelable: true}));+ } else {+ hint.fillCommand(`| ${Lute.Caret} | | |\n| --- | --- | --- |\n| | | |\n| | | |`, protyle, !mobile);+ }await Promise.resolve();await Promise.resolve();check.equal(transactions.length, 1, label + ": single transaction");@@ -189,6 +255,18 @@ const runCases = async source => {}const table = editor.querySelector('[data-type="NodeTable"]');check.ok(table, label + ": inserted table");+ if (selection === "blocks" || selection.startsWith("keyboard")) {+ check.doesNotMatch(editor.textContent, /AAAA|BBBB|CCCC/, label + ": selected blocks replaced");+ check.match(editor.textContent, /outside/, label + ": unselected content retained");+ check.equal(editor.querySelector(".protyle-wysiwyg--select"), null, label + ": selection marks cleared");+ const context = undoOperations.find(operation => operation.context?.undoFocusId)?.context;+ check.equal(context?.undoFocusId, paragraphs[0].dataset.nodeId, label + ": block selection undo start");+ check.equal(context?.undoFocusEndId, paragraphs[2].dataset.nodeId, label + ": block selection undo end");+ } else if (selection === "block-mode") {+ check.doesNotMatch(editor.textContent, /AAAA/, label + ": active block replaced");+ check.match(editor.textContent, /BBBB/, label + ": next block retained");+ check.equal(editor.querySelector(".protyle-wysiwyg--select-mode"), null, label + ": block mode cleared");+ }check.equal(openedCells.length, 1, label + ": table cell editor opened");check.equal(openedCells[0], table.querySelector("th, td"), label + ": first cell focused");const inserted = normalize(editor);@@ -223,6 +301,28 @@ const runCases = async source => {hint.fillCommand(`| ${Lute.Caret} |\n| --- |`, protyle, !mobile);check.equal(transactions.length, 0, boundary + ": unsupported boundary has no transaction");check.equal(normalize(editor), original, boundary + ": unsupported boundary preserves content");+ editor.querySelectorAll(":scope > [data-node-id]").forEach(item => item.classList.add("protyle-wysiwyg--select"));+ getSelection().collapse(first, 0);+ protyle.toolbar.range = getSelection().getRangeAt(0).cloneRange();+ if (mobile) getSelection().collapse(outside.firstChild, 1);+ const selectedOriginal = editor.innerHTML;+ hint.fillCommand(`| ${Lute.Caret} |\n| --- |`, protyle, !mobile);+ check.equal(transactions.length, 0, boundary + ": selected unsupported boundary has no transaction");+ check.equal(editor.innerHTML, selectedOriginal, boundary + ": unsupported block selection retained");+ }+ for (const crossParent of [false, true]) {+ editor.innerHTML = lute.Md2BlockDOM(crossParent ? "> AAAA\n\nBBBB\n\nCCCC" : "AAAA\n\nBBBB\n\nCCCC");+ const paragraphs = editor.querySelectorAll('[data-type="NodeParagraph"]');+ paragraphs[0].classList.add("protyle-wysiwyg--select");+ paragraphs[2].classList.add("protyle-wysiwyg--select");+ getSelection().collapse(paragraphs[0].firstElementChild.firstChild, 0);+ protyle.toolbar.range = getSelection().getRangeAt(0).cloneRange();+ if (mobile) getSelection().collapse(outside.firstChild, 1);+ transactions = [];+ const original = editor.innerHTML;+ hint.fillCommand(`| ${Lute.Caret} |\n| --- |`, protyle, !mobile);+ check.equal(transactions.length, 0, "discontinuous selection has no transaction");+ check.equal(editor.innerHTML, original, "discontinuous selection preserves unselected gaps and selection");}}return "Table insertion, undo and redo cases passed";