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: Preserve block boundaries when expanding inline selections https://github.com/siyuan-note/siyuan/pull/20444
Daniel7548112a4151
diff --git a/app/src/protyle/wysiwyg/commonHotkey.test.ts b/app/src/protyle/wysiwyg/commonHotkey.test.tsindex e232ad3ca8..803a32e9e9 100644--- a/app/src/protyle/wysiwyg/commonHotkey.test.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.test.ts@@ -7,6 +7,9 @@ import {ModuleKind, ScriptTarget, transpileModule} from "typescript";const source = transpileModule(readFileSync("src/protyle/wysiwyg/commonHotkey.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText;+const caretSource = transpileModule(readFileSync("src/protyle/wysiwyg/verticalCaret.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;const copy = (options: {selected?: string[], rangeBlocks?: string[], collapsed?: boolean, outside?: boolean, document?: boolean}) => {const block = (id: string) => ({getAttribute: () => id});@@ -59,6 +62,9 @@ test("collapsed and foreign selections retain the current block and document fal// 是否已到达块的首行/末行以选区活动端(光标)为准,否则多行选区会按选区首行处理。const expandToBlockEdge = (direction: "up" | "down", options: {backward?: boolean,+ withoutDirection?: boolean,+ elementFocus?: boolean,+ missingCaretRect?: boolean,start: number,end: number,focusTop: number,@@ -66,32 +72,86 @@ const expandToBlockEdge = (direction: "up" | "down", options: {extendable?: boolean,nextBlock?: boolean,}) => {+ assert.ok(options.start <= options.end);const calls: string[] = [];const editable = {+ nodeType: 1,innerText: "abcdefghij\nklmnopqrst\nuvwxyz",+ isConnected: true,+ childNodes: [] as unknown[],+ contains: (node: unknown): boolean => node === editable || editable.childNodes.includes(node),+ ownerDocument: {createRange: () => createCaretRange()},getBoundingClientRect: () => ({top: 0, bottom: 100}),};- const textNode = {nodeType: 3};+ const textNode = {+ nodeType: 3,+ textContent: editable.innerText.substring(0, options.elementFocus ? options.end : editable.innerText.length),+ parentElement: editable,+ parentNode: editable,+ nextSibling: null as unknown,+ previousSibling: null as unknown,+ };+ editable.childNodes.push(textNode);+ if (options.elementFocus) {+ const trailingText = {...textNode, textContent: editable.innerText.substring(options.end), previousSibling: textNode};+ textNode.nextSibling = trailingText;+ editable.childNodes.push(trailingText);+ }const range = {startContainer: textNode,startOffset: options.start,- endContainer: textNode,- endOffset: options.end,+ endContainer: options.elementFocus ? editable : textNode,+ endOffset: options.elementFocus ? 1 : options.end,collapsed: false,getBoundingClientRect: () => ({top: 0, bottom: 100}),collapse: () => calls.push("collapse"),};- const caretRange = {- setStart: () => caretRange,- collapse: () => caretRange,- getClientRects: () => [{- top: options.focusTop,- bottom: options.focusBottom,- height: options.focusBottom - options.focusTop,- }],- };+ const createCaretRange = () => ({+ startContainer: undefined as unknown,+ startOffset: 0,+ endOffset: 0,+ collapsed: true,+ setStart(node: unknown, offset: number) {+ this.startContainer = node;+ this.startOffset = offset;+ this.endOffset = offset;+ this.collapsed = true;+ },+ setEnd(_node: unknown, offset: number) {+ this.endOffset = offset;+ this.collapsed = this.startOffset === offset;+ },+ collapse() {+ this.collapsed = true;+ },+ getClientRects() {+ return options.missingCaretRect && this.collapsed ? [] : [{+ left: 0,+ top: options.focusTop,+ bottom: options.focusBottom,+ height: options.focusBottom - options.focusTop,+ }];+ },+ });+ const caretRange = createCaretRange();+ const caretExports = {} as {getVerticalCaretRect: (element: unknown, range: unknown) => unknown};+ runInNewContext(caretSource, {+ exports: caretExports,+ require: () => ({+ getFoldedNavigationOwner: (): undefined => undefined,+ getReachableVerticalRects: (_element: unknown, rects: unknown[]) => rects,+ }),+ Node: {TEXT_NODE: 3, ELEMENT_NODE: 1},+ DOMRect: class {+ constructor(public left: number, public top: number, public width: number, public height: number) {}+ get bottom() {+ return this.top + this.height;+ }+ },+ });let prevented = false;const dependencies = {+ getVerticalCaretRect: caretExports.getVerticalCaretRect,matchHotKey: () => false,isMac: () => true,hasClosestByTag: (): undefined => undefined,@@ -113,7 +173,7 @@ const expandToBlockEdge = (direction: "up" | "down", options: {require: () => dependencies,getComputedStyle: () => ({paddingTop: "0px", paddingBottom: "0px"}),getSelection: () => ({- direction: options.backward ? "backward" : "forward",+ direction: options.withoutDirection ? undefined : options.backward ? "backward" : "forward",anchorNode: textNode,anchorOffset: options.backward ? options.end : options.start,}),@@ -136,6 +196,8 @@ const expandToBlockEdge = (direction: "up" | "down", options: {} else {exports.downSelect(selectOptions);}+ assert.equal(caretRange.startContainer, options.backward ? range.startContainer : range.endContainer);+ assert.equal(caretRange.startOffset, options.backward ? range.startOffset : range.endOffset);return {calls, prevented};};@@ -160,7 +222,7 @@ test("expand looks at the selection focus instead of the whole range", () => {assert.deepEqual(expandToBlockEdge("up", {start: 2, end: 25, focusTop: 64, focusBottom: 82}), noOp);assert.deepEqual(expandToBlockEdge("up", {start: 2, end: 25, focusTop: 64, focusBottom: 82, extendable: true}), noOp);// 反向选区以偏移较小的一端为活动端,光标在末行时同样不应收至块首- const backward = expandToBlockEdge("up", {backward: true, start: 25, end: 2, focusTop: 64, focusBottom: 82,+ const backward = expandToBlockEdge("up", {backward: true, start: 23, end: 25, focusTop: 64, focusBottom: 82,extendable: true});assert.deepEqual(backward, noOp);// 首行/末行自然换行时活动端不在块的首行/末行,交回浏览器继续向上/下移动一行@@ -171,6 +233,22 @@ test("expand looks at the selection focus instead of the whole range", () => {extendable: true}), noOp);});+test("backward selections use normalized range offsets with and without Selection.direction", () => {+ for (const withoutDirection of [false, true]) {+ assert.deepEqual(expandToBlockEdge("up", {backward: true, withoutDirection, start: 2, end: 25,+ focusTop: 0, focusBottom: 18, extendable: true}).calls, ["boundary:true:true"]);+ assert.deepEqual(expandToBlockEdge("down", {backward: true, withoutDirection, start: 2, end: 25,+ focusTop: 0, focusBottom: 18, extendable: true}), {calls: [], prevented: false});+ }+});++test("element focus boundaries still stop at the block edge when the collapsed range has no rectangle", () => {+ assert.deepEqual(expandToBlockEdge("up", {start: 2, end: 6, elementFocus: true, missingCaretRect: true,+ focusTop: 0, focusBottom: 18, extendable: true}), {calls: ["boundary:true:true"], prevented: true});+ assert.deepEqual(expandToBlockEdge("down", {start: 23, end: 25, elementFocus: true, missingCaretRect: true,+ focusTop: 82, focusBottom: 100, extendable: true}).calls, ["boundary:true:false"]);+});+test("expand keeps the block selection step when the focus is already at the block edge", () => {// 向上:活动端已在块首const up = expandToBlockEdge("up", {start: 0, end: 0, focusTop: 0, focusBottom: 18});diff --git a/app/src/protyle/wysiwyg/commonHotkey.ts b/app/src/protyle/wysiwyg/commonHotkey.tsindex e904f08ef2..4cb898fe37 100644--- a/app/src/protyle/wysiwyg/commonHotkey.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.ts@@ -5,6 +5,7 @@ import {isMac, writeText} from "../util/compatibility";import {focusBlock, getBlockElementsByRange, getEditorRange, setFirstNodeRange} from "../util/selection";import {getSelectionOffset, setLastNodeRange} from "../util/selectionOffsets";import {selectTextToEditorBoundary} from "../util/selectionBoundary";+import {getVerticalCaretRect} from "./verticalCaret";import {getContenteditableElement, getNextBlock} from "./getBlock";import {hideElements} from "../ui/hideElements";import {countBlockWord} from "../../layout/status";@@ -141,7 +142,7 @@ const extendSelectionToBlockEdge = (editableElement: HTMLElement, range: Range,if (selectTextToEditorBoundary(editableElement, toStart)) {return;}- // 锚点不在当前块内时(例如跨块选区)保持原有行为+ // 锚点不在当前块内时(例如跨块选区)直接设置范围边界if (toStart) {setFirstNodeRange(editableElement, range);} else {@@ -150,7 +151,7 @@ const extendSelectionToBlockEdge = (editableElement: HTMLElement, range: Range,};// 扩选应以选区活动端(光标所在端)为准:Range 按文档顺序归一化,方向只能从 Selection 判断-const getSelectionFocus = (range: Range, position: { start: number, end: number }) => {+const getSelectionFocus = (editableElement: HTMLElement, range: Range, position: { start: number, end: number }) => {const selection = getSelection() as Selection & {direction?: "forward" | "backward" | "none"};const backward = selection?.direction === "backward" ||(selection?.direction !== "forward" && selection?.anchorNode === range.endContainer &&@@ -159,10 +160,10 @@ const getSelectionFocus = (range: Range, position: { start: number, end: numbercaretRange.setStart(backward ? range.startContainer : range.endContainer,backward ? range.startOffset : range.endOffset);caretRange.collapse(true);- const rects = Array.from(caretRange.getClientRects()).filter(rect => rect.height > 0.5);+ // 行内元素边界可能没有折叠矩形,沿相邻内容测量活动端return {index: backward ? position.start : position.end,- rect: rects[rects.length - 1],+ rect: getVerticalCaretRect(editableElement, caretRange),};};@@ -184,7 +185,7 @@ export const upSelect = (options: {const position = getSelectionOffset(nodeEditableElement, options.editorElement, options.range);const innerText = nodeEditableElement.innerText;const isExpandUp = matchHotKey(window.siyuan.config.keymap.editor.general.expandUp, options.event);- const focus = getSelectionFocus(options.range, position);+ const focus = getSelectionFocus(nodeEditableElement, options.range, position);if (!isMac() && isExpandUp) {// Windows 中 ⌥⇧↑ 默认无选中功能会导致 https://ld246.com/article/1716635371149} else if (focus.index > 0) {@@ -234,7 +235,7 @@ export const downSelect = (options: {const position = getSelectionOffset(nodeEditableElement, options.editorElement, options.range);const innerText = nodeEditableElement.innerText;const isExpandDown = matchHotKey(window.siyuan.config.keymap.editor.general.expandDown, options.event);- const focus = getSelectionFocus(options.range, position);+ const focus = getSelectionFocus(nodeEditableElement, options.range, position);if (!isMac() && isExpandDown) {// Windows 中 ⌥⇧↓ 默认无选中功能会导致 https://ld246.com/article/1716635371149} else if (focus.index < innerText.length) {