Skip to content

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

:bug: Preserve block selections when inserting tables

Danielc4a917744875
diff --git a/app/src/protyle/hint/fillCommand.test.ts b/app/src/protyle/hint/fillCommand.test.ts
index 00624f4b8b..8b91198661 100644
--- a/app/src/protyle/hint/fillCommand.test.ts
+++ b/app/src/protyle/hint/fillCommand.test.ts
@@ -145,7 +145,6 @@ 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.ts
index 2b70a59242..a4ebdd5d5d 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -1,8 +1,6 @@
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 {
@@ -1056,20 +1054,6 @@ ${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.ts
deleted file mode 100644
index 41f2677daf..0000000000
--- a/app/src/protyle/hint/tableInsertion.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-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.js
index 7e7aa0bfe9..f6b5692488 100644
--- a/app/tests/fillCommand.test.js
+++ b/app/tests/fillCommand.test.js
@@ -34,12 +34,10 @@ const compile = () => {
return ts.transpileModule([
read("util/hasClosest").replace(/^export /gm, ""),
extract("wysiwyg/getBlock", ["getContenteditableElement", "getParentBlock", "getPreviousBlockSibling",
- "getNextBlockSibling", "hasPreviousSibling", "hasNextSibling", "isEndOfBlock", "getFirstBlock",
- "getLastBlock", "getNextBlock", "getPreviousBlock"]),
+ "getNextBlockSibling", "hasPreviousSibling", "hasNextSibling", "isEndOfBlock", "getNextBlock", "getPreviousBlock"]),
extract("wysiwyg/blockSelection", ["BLOCK_SELECTION_CLASS", "BLOCK_SELECTION_MODE_CLASS", "clearSelectionState",
- "getBlockSelectionModeElement", "getBlockOperationElements", "isContinuousBlockSelection",
+ "getBlockSelectionModeElement",
"clearBlockSelection", "clearBlockSelectionMode"]),
- extract("hint/tableInsertion", ["getTableBlockSelectionRange"]),
extract("wysiwyg/commonHotkey", ["extendSelectionToBlockEdge", "getSelectionFocus", "upSelect", "downSelect",
"getStartEndElement"]),
extract("util/selectionOffsets", ["selectIsEditor", "getSelectionOffset", "focusByRange"]),
@@ -255,17 +253,17 @@ 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");
+ if (["blocks", "block-mode"].includes(selection) || selection.startsWith("keyboard")) {
+ const retained = editor.cloneNode(true);
+ retained.querySelector('[data-type="NodeTable"]').remove();
+ check.equal(normalize(retained), original, label + ": block selection preserves all original content, IDs and attributes");
+ } else if (selection === "full") {
+ check.doesNotMatch(editor.textContent, /AAAA|BBBB|CCCC/, label + ": full text selection replaced");
+ check.match(editor.textContent, /outside/, label + ": unselected text retained");
+ } else if (selection.startsWith("partial-")) {
+ check.doesNotMatch(editor.textContent, /BBBB/, label + ": selected middle paragraph replaced");
+ check.equal(paragraphs[0].firstElementChild.textContent, "AA", label + ": start prefix retained");
+ check.match(editor.textContent, /CC/, label + ": end suffix retained");
}
check.equal(openedCells.length, 1, label + ": table cell editor opened");
check.equal(openedCells[0], table.querySelector("th, td"), label + ": first cell focused");
@@ -305,10 +303,21 @@ const runCases = async source => {
getSelection().collapse(first, 0);
protyle.toolbar.range = getSelection().getRangeAt(0).cloneRange();
if (mobile) getSelection().collapse(outside.firstChild, 1);
- const selectedOriginal = editor.innerHTML;
+ const selectedOriginal = normalize(editor);
+ const replayed = editor.cloneNode(true);
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");
+ check.equal(transactions.length, 1, boundary + ": block selection uses the collapsed text caret");
+ const retained = editor.cloneNode(true);
+ retained.querySelector('[data-type="NodeTable"]').remove();
+ check.equal(normalize(retained), selectedOriginal, boundary + ": selected atomic blocks retained");
+ const {doOperations, undoOperations} = transactions[0];
+ const inserted = normalize(editor);
+ replay(replayed, doOperations);
+ check.equal(normalize(replayed), inserted, boundary + ": transaction matches editor");
+ replay(editor, undoOperations);
+ check.equal(normalize(editor), selectedOriginal, boundary + ": undo restores original");
+ replay(editor, doOperations);
+ check.equal(normalize(editor), inserted, boundary + ": redo restores insertion");
}
for (const crossParent of [false, true]) {
editor.innerHTML = lute.Md2BlockDOM(crossParent ? "> AAAA\n\nBBBB\n\nCCCC" : "AAAA\n\nBBBB\n\nCCCC");
@@ -319,10 +328,21 @@ const runCases = async source => {
protyle.toolbar.range = getSelection().getRangeAt(0).cloneRange();
if (mobile) getSelection().collapse(outside.firstChild, 1);
transactions = [];
- const original = editor.innerHTML;
+ const original = normalize(editor);
+ const replayed = editor.cloneNode(true);
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");
+ check.equal(transactions.length, 1, "discontinuous block selection inserts at the text caret");
+ const retained = editor.cloneNode(true);
+ retained.querySelector('[data-type="NodeTable"]').remove();
+ check.equal(normalize(retained), original, "discontinuous selection preserves selected blocks and unselected gaps");
+ const {doOperations, undoOperations} = transactions[0];
+ const inserted = normalize(editor);
+ replay(replayed, doOperations);
+ check.equal(normalize(replayed), inserted, "discontinuous selection transaction matches editor");
+ replay(editor, undoOperations);
+ check.equal(normalize(editor), original, "discontinuous selection undo restores original");
+ replay(editor, doOperations);
+ check.equal(normalize(editor), inserted, "discontinuous selection redo restores insertion");
}
}
return "Table insertion, undo and redo cases passed";