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: Expand text selection with Shift+Arrow keys from the caret position
Jeffrey Chened9cb684ddf6
diff --git a/app/src/protyle/wysiwyg/commonHotkey.test.ts b/app/src/protyle/wysiwyg/commonHotkey.test.tsindex 866685ea7b..e232ad3ca8 100644--- a/app/src/protyle/wysiwyg/commonHotkey.test.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.test.ts@@ -54,3 +54,130 @@ test("collapsed and foreign selections retain the current block and document fal}assert.deepEqual(copy({document: true}).writes, [{ids: ["document"], type: "blockEmbed"}]);});++// 扩选到块首/块尾必须保留选区锚点(只移动光标),锚点不在块内时才回退到改写范围。+// 是否已到达块的首行/末行以选区活动端(光标)为准,否则多行选区会按选区首行处理。+const expandToBlockEdge = (direction: "up" | "down", options: {+ backward?: boolean,+ start: number,+ end: number,+ focusTop: number,+ focusBottom: number,+ extendable?: boolean,+ nextBlock?: boolean,+}) => {+ const calls: string[] = [];+ const editable = {+ innerText: "abcdefghij\nklmnopqrst\nuvwxyz",+ getBoundingClientRect: () => ({top: 0, bottom: 100}),+ };+ const textNode = {nodeType: 3};+ const range = {+ startContainer: textNode,+ startOffset: options.start,+ endContainer: textNode,+ endOffset: 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,+ }],+ };+ let prevented = false;+ const dependencies = {+ matchHotKey: () => false,+ isMac: () => true,+ hasClosestByTag: (): undefined => undefined,+ getContenteditableElement: () => editable,+ getSelectionOffset: () => ({start: options.start, end: options.end}),+ getNextBlock: () => options.nextBlock ? {} : undefined,+ selectTextToEditorBoundary: (element: unknown, toStart: boolean) => {+ calls.push(`boundary:${element === editable}:${toStart}`);+ return options.extendable ? range : undefined;+ },+ setFirstNodeRange: () => calls.push("setFirstNodeRange"),+ setLastNodeRange: () => calls.push("setLastNodeRange"),+ hideElements: () => calls.push("hideElements"),+ countBlockWord: () => calls.push("countBlockWord"),+ };+ const exports = {} as {upSelect: (options: unknown) => void, downSelect: (options: unknown) => void};+ runInNewContext(source, {+ exports,+ require: () => dependencies,+ getComputedStyle: () => ({paddingTop: "0px", paddingBottom: "0px"}),+ getSelection: () => ({+ direction: options.backward ? "backward" : "forward",+ anchorNode: textNode,+ anchorOffset: options.backward ? options.end : options.start,+ }),+ document: {createRange: () => caretRange},+ window: {siyuan: {config: {keymap: {editor: {general: {expandUp: "⌥⇧↑", expandDown: "⌥⇧↓"}}}}}},+ });+ const selectOptions = {+ protyle: {wysiwyg: {element: {querySelectorAll: (): never[] => []}}},+ event: {preventDefault: () => prevented = true, stopPropagation: (): undefined => undefined},+ nodeElement: {+ classList: {contains: () => false, add: () => calls.push("classList.add")},+ getAttribute: () => "block-id",+ },+ editorElement: editable,+ range,+ cb: (): undefined => undefined,+ };+ if (direction === "up") {+ exports.upSelect(selectOptions);+ } else {+ exports.downSelect(selectOptions);+ }+ return {calls, prevented};+};++test("expand up preserves the selection anchor instead of rewriting the range", () => {+ assert.deepEqual(expandToBlockEdge("up", {start: 2, end: 6, focusTop: 0, focusBottom: 18, extendable: true}).calls,+ ["boundary:true:true"]);+ assert.deepEqual(expandToBlockEdge("down", {start: 2, end: 25, focusTop: 82, focusBottom: 100, extendable: true}).calls,+ ["boundary:true:false"]);+});++test("expand up and down fall back to the legacy range rewrite only for a foreign anchor", () => {+ assert.deepEqual(expandToBlockEdge("up", {start: 2, end: 6, focusTop: 0, focusBottom: 18}).calls,+ ["boundary:true:true", "setFirstNodeRange"]);+ assert.deepEqual(expandToBlockEdge("down", {start: 2, end: 25, focusTop: 82, focusBottom: 100}).calls,+ ["boundary:true:false", "setLastNodeRange"]);+ assert.equal(expandToBlockEdge("up", {start: 2, end: 6, focusTop: 0, focusBottom: 18}).prevented, true);+});++test("expand looks at the selection focus instead of the whole range", () => {+ const noOp = {calls: [] as string[], prevented: false};+ // 锚点在首行、光标在末行:不能因为 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,+ extendable: true});+ assert.deepEqual(backward, noOp);+ // 首行/末行自然换行时活动端不在块的首行/末行,交回浏览器继续向上/下移动一行+ assert.deepEqual(expandToBlockEdge("up", {start: 2, end: 6, focusTop: 30, focusBottom: 48, extendable: true}), noOp);+ assert.deepEqual(expandToBlockEdge("down", {start: 2, end: 25, focusTop: 64, focusBottom: 82, extendable: true}), noOp);+ // 非最后一个块时交由浏览器移动到下一个块+ assert.deepEqual(expandToBlockEdge("down", {start: 2, end: 25, focusTop: 82, focusBottom: 100, nextBlock: true,+ extendable: true}), noOp);+});++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});+ assert.deepEqual(up.calls, ["collapse", "hideElements", "classList.add", "countBlockWord"]);+ assert.equal(up.prevented, true);+ // 向下:活动端已在块尾+ const down = expandToBlockEdge("down", {start: 28, end: 28, focusTop: 64, focusBottom: 82});+ assert.deepEqual(down.calls, ["collapse", "hideElements", "classList.add", "countBlockWord"]);+ assert.equal(down.prevented, true);+});diff --git a/app/src/protyle/wysiwyg/commonHotkey.ts b/app/src/protyle/wysiwyg/commonHotkey.tsindex b384eecc75..e904f08ef2 100644--- a/app/src/protyle/wysiwyg/commonHotkey.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.ts@@ -4,6 +4,7 @@ import {fetchPost, fetchSyncPost} from "../../util/fetch";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 {getContenteditableElement, getNextBlock} from "./getBlock";import {hideElements} from "../ui/hideElements";import {countBlockWord} from "../../layout/status";@@ -135,6 +136,36 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemen/// #endif};+// 扩选到块首/块尾时只移动选区焦点并保留锚点,使 ⇧↑/⇧↓ 的结果随光标位于选区首尾而变化+const extendSelectionToBlockEdge = (editableElement: HTMLElement, range: Range, toStart: boolean) => {+ if (selectTextToEditorBoundary(editableElement, toStart)) {+ return;+ }+ // 锚点不在当前块内时(例如跨块选区)保持原有行为+ if (toStart) {+ setFirstNodeRange(editableElement, range);+ } else {+ setLastNodeRange(editableElement, range, false);+ }+};++// 扩选应以选区活动端(光标所在端)为准:Range 按文档顺序归一化,方向只能从 Selection 判断+const getSelectionFocus = (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 &&+ selection?.anchorOffset === range.endOffset);+ const caretRange = document.createRange();+ caretRange.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],+ };+};+export const upSelect = (options: {protyle: IProtyle,event: KeyboardEvent,@@ -150,17 +181,20 @@ export const upSelect = (options: {} else {const tdElement = hasClosestByTag(options.range.startContainer, "TD") || hasClosestByTag(options.range.startContainer, "TH");const nodeEditableElement = (tdElement || getContenteditableElement(options.nodeElement) || options.nodeElement) as HTMLElement;- const startIndex = getSelectionOffset(nodeEditableElement, options.editorElement, options.range).start;+ 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);if (!isMac() && isExpandUp) {// Windows 中 ⌥⇧↑ 默认无选中功能会导致 https://ld246.com/article/1716635371149- } else if (startIndex > 0) {+ } else if (focus.index > 0) {+ // 光标已在块的首行时把光标收至块首,其余情况交回浏览器向上移动一行// 选中上一个节点的处理在 toolbar/index.ts 中 `shift+方向键或三击选中`- if (innerText.substr(0, startIndex).indexOf("\n") === -1 &&+ if (innerText.substr(0, focus.index).indexOf("\n") === -1 &&// 当第一行太长自然换行的情况- options.range.getBoundingClientRect().top - nodeEditableElement.getBoundingClientRect().top - parseInt(getComputedStyle(nodeEditableElement).paddingTop) < 14) {- setFirstNodeRange(nodeEditableElement, options.range);+ focus.rect && focus.rect.top - nodeEditableElement.getBoundingClientRect().top -+ parseInt(getComputedStyle(nodeEditableElement).paddingTop) < 14) {+ extendSelectionToBlockEdge(nodeEditableElement, options.range, true);options.event.preventDefault();}return;@@ -197,24 +231,27 @@ export const downSelect = (options: {} else {const tdElement = hasClosestByTag(options.range.startContainer, "TD") || hasClosestByTag(options.range.startContainer, "TH");const nodeEditableElement = (tdElement || getContenteditableElement(options.nodeElement) || options.nodeElement) as HTMLElement;- const endIndex = getSelectionOffset(nodeEditableElement, options.editorElement, options.range).end;+ 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);if (!isMac() && isExpandDown) {// Windows 中 ⌥⇧↓ 默认无选中功能会导致 https://ld246.com/article/1716635371149- } else if (endIndex < innerText.length) {+ } else if (focus.index < innerText.length) {+ // 光标已在块的末行时把光标收至块尾,其余情况交回浏览器向下移动一行// 选中下一个节点的处理在 toolbar/index.ts 中 `shift+方向键或三击选中`- if (!getNextBlock(options.nodeElement) && innerText.trimRight().substr(endIndex).indexOf("\n") === -1 &&+ if (!getNextBlock(options.nodeElement) && innerText.trimRight().substr(focus.index).indexOf("\n") === -1 &&// 当最后一行太长自然换行的情况- nodeEditableElement.getBoundingClientRect().bottom - options.range.getBoundingClientRect().bottom - parseInt(getComputedStyle(nodeEditableElement).paddingBottom) < 14) {+ focus.rect && nodeEditableElement.getBoundingClientRect().bottom - focus.rect.bottom -+ parseInt(getComputedStyle(nodeEditableElement).paddingBottom) < 14) {// 当为最后一个块时应选中末尾- setLastNodeRange(nodeEditableElement, options.range, false);+ extendSelectionToBlockEdge(nodeEditableElement, options.range, false);if (options.nodeElement.classList.contains("code-block") && isExpandDown) {// 代码块中 shift+alt 向下选中到末尾时,最后一个字符无法选中options.event.preventDefault();}} else if (tdElement) {- setLastNodeRange(tdElement, options.range, false);+ extendSelectionToBlockEdge(tdElement as HTMLElement, options.range, false);options.event.preventDefault();}return;