Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(docs): keep cursor stable at document bounds (#7149)

Univere4c33e15482c
diff --git a/packages/docs-ui/src/commands/operations/doc-cursor.operation.ts b/packages/docs-ui/src/commands/operations/doc-cursor.operation.ts
index 01bb3db165..fed4e5af0f 100644
--- a/packages/docs-ui/src/commands/operations/doc-cursor.operation.ts
+++ b/packages/docs-ui/src/commands/operations/doc-cursor.operation.ts
@@ -17,7 +17,7 @@
import type { Direction, IOperation } from '@univerjs/core';
import { CommandType } from '@univerjs/core';
-export type DocCursorMoveGranularity = 'character' | 'word' | 'line' | 'document';
+export type DocCursorMoveGranularity = 'character' | 'word' | 'line' | 'paragraph' | 'document';
export interface IMoveCursorOperationParams {
direction: Direction;
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts
index 19051e6249..73a3794c1c 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts
@@ -15,6 +15,7 @@
*/
import { DataStreamTreeTokenType, Direction } from '@univerjs/core';
+import { DocumentSkeletonPageType, LineType } from '@univerjs/engine-render';
import { describe, expect, it, vi } from 'vitest';
import { DocMoveCursorController } from '../doc-move-cursor.controller';
@@ -22,6 +23,14 @@ function createControllerHarness() {
return Object.create(DocMoveCursorController.prototype) as Record<string, (...args: unknown[]) => unknown>;
}
+function createOffsetSkeleton(validOffsets: number[]) {
+ const validOffsetSet = new Set(validOffsets);
+
+ return {
+ findNodePositionByCharIndex: vi.fn((offset: number) => validOffsetSet.has(offset) ? { offset } : undefined),
+ };
+}
+
describe('DocMoveCursorController movement helpers', () => {
it('resolves Chinese word boundaries with the shared Segmenter behavior', () => {
const controller = createControllerHarness();
@@ -138,6 +147,264 @@ describe('DocMoveCursorController movement helpers', () => {
expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(paragraphGlyph, -1);
});
+ it('enters the nearest column group column when moving vertically onto the block line', () => {
+ const controller = createControllerHarness();
+ const bodyGlyph = createGlyph('A', 118);
+ const firstColumnGlyph = createGlyph('L', 0);
+ const secondColumnGlyph = createGlyph('R', 16);
+ const beforeLine = createLine([bodyGlyph], 10, 0);
+ const blockLine = createBlockLine(11, 40);
+ const bodyColumn = createColumn([beforeLine, blockLine]);
+ const bodyPage = createPage([bodyColumn], DocumentSkeletonPageType.BODY);
+ const firstColumnPage = createPage([createColumn([createLine([firstColumnGlyph], 20, 0)])], DocumentSkeletonPageType.CELL);
+ const secondColumnPage = createPage([createColumn([createLine([secondColumnGlyph], 30, 0)])], DocumentSkeletonPageType.CELL);
+ const columnGroupColumnA = { columnId: 'a', left: 0, top: 0, width: 80, height: 20, st: 20, ed: 25, page: firstColumnPage };
+ const columnGroupColumnB = { columnId: 'b', left: 100, top: 0, width: 80, height: 20, st: 30, ed: 35, page: secondColumnPage };
+ const columnGroup = {
+ columnGroupId: 'cg-1',
+ columns: [columnGroupColumnA, columnGroupColumnB],
+ ed: 40,
+ height: 20,
+ left: 0,
+ st: 11,
+ top: 10,
+ width: 180,
+ };
+ Object.assign(columnGroupColumnA, { parent: columnGroup });
+ Object.assign(columnGroupColumnB, { parent: columnGroup });
+ Object.assign(firstColumnPage, { parent: columnGroupColumnA });
+ Object.assign(secondColumnPage, { parent: columnGroupColumnB });
+ Object.assign(columnGroup, { parent: bodyPage });
+ bodyPage.skeColumnGroups.set('cg-1', columnGroup as never);
+
+ const skeleton = {
+ findPositionByGlyph: vi.fn((glyph) => ({ glyph: glyph === secondColumnGlyph ? 'second' : 'other', segmentPage: -1 })),
+ };
+
+ expect(controller._getTopOrBottomPosition(
+ skeleton,
+ bodyGlyph,
+ { segmentPage: -1 },
+ true
+ )).toEqual({ glyph: 'second', isBack: true, segmentPage: -1 });
+ expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(secondColumnGlyph, -1);
+ });
+
+ it('leaves a column group column for the following body line when moving past its end', () => {
+ const controller = createControllerHarness();
+ const columnGlyph = createGlyph('C', 12);
+ const afterGlyph = createGlyph('Z', 112);
+ const blockLine = createBlockLine(11, 40);
+ const afterLine = createLine([afterGlyph], 41, 0);
+ const bodyColumn = createColumn([blockLine, afterLine]);
+ const bodyPage = createPage([bodyColumn], DocumentSkeletonPageType.BODY);
+ const columnPage = createPage([createColumn([createLine([columnGlyph], 30, 0)])], DocumentSkeletonPageType.CELL);
+ const columnGroupColumn = { columnId: 'b', left: 100, top: 0, width: 80, height: 20, st: 30, ed: 35, page: columnPage };
+ const columnGroup = {
+ columnGroupId: 'cg-1',
+ columns: [columnGroupColumn],
+ ed: 40,
+ height: 20,
+ left: 0,
+ st: 11,
+ top: 10,
+ width: 180,
+ };
+ Object.assign(columnGroupColumn, { parent: columnGroup });
+ Object.assign(columnPage, { parent: columnGroupColumn });
+ Object.assign(columnGroup, { parent: bodyPage });
+ bodyPage.skeColumnGroups.set('cg-1', columnGroup as never);
+
+ const skeleton = {
+ findPositionByGlyph: vi.fn((glyph) => ({ glyph: glyph === afterGlyph ? 'after' : 'other', segmentPage: -1 })),
+ };
+
+ expect(controller._getTopOrBottomPosition(
+ skeleton,
+ columnGlyph,
+ { segmentPage: -1 },
+ true
+ )).toEqual({ glyph: 'after', isBack: true, segmentPage: -1 });
+ expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(afterGlyph, -1);
+ });
+
+ it('enters the nearest column group column from below when moving upward', () => {
+ const controller = createControllerHarness();
+ const afterGlyph = createGlyph('Z', 112);
+ const columnGlyph = createGlyph('C', 12);
+ const blockLine = createBlockLine(11, 40);
+ const afterLine = createLine([afterGlyph], 41, 0);
+ const bodyColumn = createColumn([blockLine, afterLine]);
+ const bodyPage = createPage([bodyColumn], DocumentSkeletonPageType.BODY);
+ const columnPage = createPage([createColumn([createLine([columnGlyph], 30, 0)])], DocumentSkeletonPageType.CELL);
+ const columnGroupColumn = { columnId: 'b', left: 100, top: 0, width: 80, height: 20, st: 30, ed: 35, page: columnPage };
+ const columnGroup = createColumnGroup([columnGroupColumn], bodyPage);
+ bodyPage.skeColumnGroups.set('cg-1', columnGroup as never);
+
+ const skeleton = {
+ findPositionByGlyph: vi.fn((glyph) => ({ glyph: glyph === columnGlyph ? 'column' : 'other', segmentPage: -1 })),
+ };
+
+ expect(controller._getTopOrBottomPosition(
+ skeleton,
+ afterGlyph,
+ { segmentPage: -1 },
+ false
+ )).toEqual({ glyph: 'column', isBack: true, segmentPage: -1 });
+ expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(columnGlyph, -1);
+ });
+
+ it('leaves a column group column for the previous body line when moving above its start', () => {
+ const controller = createControllerHarness();
+ const beforeGlyph = createGlyph('A', 112);
+ const columnGlyph = createGlyph('C', 12);
+ const beforeLine = createLine([beforeGlyph], 10, 0);
+ const blockLine = createBlockLine(11, 40);
+ const bodyColumn = createColumn([beforeLine, blockLine]);
+ const bodyPage = createPage([bodyColumn], DocumentSkeletonPageType.BODY);
+ const columnPage = createPage([createColumn([createLine([columnGlyph], 30, 0)])], DocumentSkeletonPageType.CELL);
+ const columnGroupColumn = { columnId: 'b', left: 100, top: 0, width: 80, height: 20, st: 30, ed: 35, page: columnPage };
+ const columnGroup = createColumnGroup([columnGroupColumn], bodyPage);
+ bodyPage.skeColumnGroups.set('cg-1', columnGroup as never);
+
+ const skeleton = {
+ findPositionByGlyph: vi.fn((glyph) => ({ glyph: glyph === beforeGlyph ? 'before' : 'other', segmentPage: -1 })),
+ };
+
+ expect(controller._getTopOrBottomPosition(
+ skeleton,
+ columnGlyph,
+ { segmentPage: -1 },
+ false
+ )).toEqual({ glyph: 'before', isBack: true, segmentPage: -1 });
+ expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(beforeGlyph, -1);
+ });
+
+ it('enters the nearest docs table cell when moving vertically from a body line', () => {
+ const controller = createControllerHarness();
+ const bodyGlyph = createGlyph('A', 118);
+ const firstCellGlyph = createGlyph('L', 8);
+ const secondCellGlyph = createGlyph('R', 8);
+ const beforeLine = createLine([bodyGlyph], 10, 0);
+ const bodyColumn = createColumn([beforeLine]);
+ const bodyPage = createPage([bodyColumn], DocumentSkeletonPageType.BODY);
+ const firstCell = createCellPage([createLine([firstCellGlyph], 20, 0)], 0, 80);
+ const secondCell = createCellPage([createLine([secondCellGlyph], 30, 0)], 100, 80);
+ createTable(bodyPage, [createTableRow([firstCell, secondCell], 0)], 12, 40);
+
+ const skeleton = {
+ findPositionByGlyph: vi.fn((glyph) => ({ glyph: glyph === secondCellGlyph ? 'second' : 'other', segmentPage: -1 })),
+ };
+
+ expect(controller._getTopOrBottomPosition(
+ skeleton,
+ bodyGlyph,
+ { segmentPage: -1 },
+ true
+ )).toEqual({ glyph: 'second', isBack: true, segmentPage: -1 });
+ expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(secondCellGlyph, -1);
+ });
+
+ it('leaves a docs table cell with the cell-local cursor mapped back to the body line', () => {
+ const controller = createControllerHarness();
+ const cellGlyph = createGlyph('C', 12);
+ const wrongBodyGlyph = createGlyph('W', 12);
+ const rightBodyGlyph = createGlyph('R', 112);
+ const afterLine = createLine([wrongBodyGlyph, rightBodyGlyph], 41, 0);
+ const bodyColumn = createColumn([afterLine]);
+ const bodyPage = createPage([bodyColumn], DocumentSkeletonPageType.BODY);
+ const cell = createCellPage([createLine([cellGlyph], 20, 0)], 100, 80);
+ createTable(bodyPage, [createTableRow([cell], 0)], 12, 40);
+
+ const skeleton = {
+ findPositionByGlyph: vi.fn((glyph) => ({ glyph: glyph === rightBodyGlyph ? 'right' : 'wrong', segmentPage: -1 })),
+ };
+
+ expect(controller._getTopOrBottomPosition(
+ skeleton,
+ cellGlyph,
+ { segmentPage: -1 },
+ true
+ )).toEqual({ glyph: 'right', isBack: true, segmentPage: -1 });
+ expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(rightBodyGlyph, -1);
+ });
+
+ it('moves to the nearest docs table cell when crossing a row boundary', () => {
+ const controller = createControllerHarness();
+ const currentGlyph = createGlyph('C', 5);
+ const wrongCellGlyph = createGlyph('W', 8);
+ const rightCellGlyph = createGlyph('R', 8);
+ const bodyPage = createPage([createColumn([])], DocumentSkeletonPageType.BODY);
+ const currentCell = createCellPage([createLine([currentGlyph], 20, 0)], 80, 20);
+ const lowerLeftCell = createCellPage([createLine([wrongCellGlyph], 30, 0)], 0, 50);
+ const lowerRightCell = createCellPage([createLine([rightCellGlyph], 40, 0)], 100, 50);
+ createTable(bodyPage, [
+ createTableRow([currentCell], 0),
+ createTableRow([lowerLeftCell, lowerRightCell], 20),
+ ], 12, 60);
+
+ const skeleton = {
+ findPositionByGlyph: vi.fn((glyph) => ({ glyph: glyph === rightCellGlyph ? 'right' : 'wrong', segmentPage: -1 })),
+ };
+
+ expect(controller._getTopOrBottomPosition(
+ skeleton,
+ currentGlyph,
+ { segmentPage: -1 },
+ true
+ )).toEqual({ glyph: 'right', isBack: true, segmentPage: -1 });
+ expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(rightCellGlyph, -1);
+ });
+
+ it('enters the nearest docs table cell from below when moving upward', () => {
+ const controller = createControllerHarness();
+ const bodyGlyph = createGlyph('A', 118);
+ const firstCellGlyph = createGlyph('L', 8);
+ const secondCellGlyph = createGlyph('R', 8);
+ const afterLine = createLine([bodyGlyph], 41, 0);
+ const bodyColumn = createColumn([afterLine]);
+ const bodyPage = createPage([bodyColumn], DocumentSkeletonPageType.BODY);
+ const firstCell = createCellPage([createLine([firstCellGlyph], 20, 0)], 0, 80);
+ const secondCell = createCellPage([createLine([secondCellGlyph], 30, 0)], 100, 80);
+ createTable(bodyPage, [createTableRow([firstCell, secondCell], 0)], 12, 40);
+
+ const skeleton = {
+ findPositionByGlyph: vi.fn((glyph) => ({ glyph: glyph === secondCellGlyph ? 'second' : 'other', segmentPage: -1 })),
+ };
+
+ expect(controller._getTopOrBottomPosition(
+ skeleton,
+ bodyGlyph,
+ { segmentPage: -1 },
+ false
+ )).toEqual({ glyph: 'second', isBack: true, segmentPage: -1 });
+ expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(secondCellGlyph, -1);
+ });
+
+ it('leaves a docs table cell upward with the cell-local cursor mapped back to the body line', () => {
+ const controller = createControllerHarness();
+ const cellGlyph = createGlyph('C', 12);
+ const wrongBodyGlyph = createGlyph('W', 12);
+ const rightBodyGlyph = createGlyph('R', 112);
+ const beforeLine = createLine([wrongBodyGlyph, rightBodyGlyph], 10, 0);
+ const bodyColumn = createColumn([beforeLine]);
+ const bodyPage = createPage([bodyColumn], DocumentSkeletonPageType.BODY);
+ const cell = createCellPage([createLine([cellGlyph], 20, 0)], 100, 80);
+ createTable(bodyPage, [createTableRow([cell], 0)], 13, 40);
+
+ const skeleton = {
+ findPositionByGlyph: vi.fn((glyph) => ({ glyph: glyph === rightBodyGlyph ? 'right' : 'wrong', segmentPage: -1 })),
+ };
+
+ expect(controller._getTopOrBottomPosition(
+ skeleton,
+ cellGlyph,
+ { segmentPage: -1 },
+ false
+ )).toEqual({ glyph: 'right', isBack: true, segmentPage: -1 });
+ expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(rightBodyGlyph, -1);
+ });
+
it('keeps column boundary tokens out of the default cursor skip list', () => {
const controller = createControllerHarness();
@@ -155,4 +422,184 @@ describe('DocMoveCursorController movement helpers', () => {
expect(controller._getCursorOffsetByGranularity({}, 8, Direction.UP, 'document', '', -1, 20)).toBe(0);
expect(controller._getCursorOffsetByGranularity({}, 8, Direction.DOWN, 'document', '', -1, 20)).toBe(18);
});
+
+ it('resolves paragraph movement offsets from data-stream paragraph boundaries', () => {
+ const controller = createControllerHarness();
+ const dataStream = `Alpha${DataStreamTreeTokenType.PARAGRAPH}Beta${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`;
+
+ expect(controller._getParagraphBoundaryOffset(dataStream, 3, Direction.UP)).toBe(0);
+ expect(controller._getParagraphBoundaryOffset(dataStream, 0, Direction.UP)).toBe(0);
+ expect(controller._getParagraphBoundaryOffset(dataStream, 6, Direction.UP)).toBe(0);
+ expect(controller._getParagraphBoundaryOffset(dataStream, 6, Direction.DOWN)).toBe(11);
+ expect(controller._getParagraphBoundaryOffset(dataStream, 11, Direction.DOWN)).toBe(11);
+ });
+
+ it('normalizes document boundaries to renderable cursor offsets', () => {
+ const controller = createControllerHarness();
+ const dataStream = `${DataStreamTreeTokenType.BLOCK_START}A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.BLOCK_END}${DataStreamTreeTokenType.SECTION_BREAK}`;
+ const skeleton = createOffsetSkeleton([1]);
+
+ expect(controller._normalizeRenderableCursorOffset(skeleton, dataStream, [], 0, Direction.UP, '', -1)).toBe(1);
+ expect(controller._normalizeRenderableCursorOffset(skeleton, dataStream, [], dataStream.length - 2, Direction.DOWN, '', -1)).toBe(1);
+ });
+
+ it('keeps renderable cursor targets out of table and column structure tokens', () => {
+ const controller = createControllerHarness();
+ const tableStream = `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_ROW_START}${DataStreamTreeTokenType.TABLE_CELL_START}A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.TABLE_CELL_END}${DataStreamTreeTokenType.TABLE_ROW_END}${DataStreamTreeTokenType.TABLE_END}${DataStreamTreeTokenType.SECTION_BREAK}`;
+ const columnStream = `${DataStreamTreeTokenType.COLUMN_GROUP_START}${DataStreamTreeTokenType.COLUMN_START}B${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.COLUMN_END}${DataStreamTreeTokenType.COLUMN_GROUP_END}${DataStreamTreeTokenType.SECTION_BREAK}`;
+
+ expect(controller._normalizeRenderableCursorOffset(createOffsetSkeleton([3]), tableStream, [], 0, Direction.DOWN, '', -1)).toBe(3);
+ expect(controller._normalizeRenderableCursorOffset(createOffsetSkeleton([2]), columnStream, [], 0, Direction.DOWN, '', -1)).toBe(2);
+ });
+
+ it('moves whole-entity custom range targets to renderable range boundaries', () => {
+ const controller = createControllerHarness();
+ const dataStream = `ABCD${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`;
+ const customRanges = [{ wholeEntity: true, startIndex: 1, endIndex: 2 }];
+ const skeleton = createOffsetSkeleton([0, 1, 3, 4]);
+
+ expect(controller._normalizeRenderableCursorOffset(skeleton, dataStream, customRanges, 2, Direction.UP, '', -1)).toBe(1);
+ expect(controller._normalizeRenderableCursorOffset(skeleton, dataStream, customRanges, 2, Direction.DOWN, '', -1)).toBe(3);
+ });
+
+ it('returns undefined when no renderable cursor target exists', () => {
+ const controller = createControllerHarness();
+ const dataStream = `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_END}${DataStreamTreeTokenType.SECTION_BREAK}`;
+
+ expect(controller._normalizeRenderableCursorOffset(createOffsetSkeleton([]), dataStream, [], 0, Direction.DOWN, '', -1)).toBeUndefined();
+ });
});
+
+function createGlyph(content: string, left: number) {
+ return {
+ content,
+ count: 1,
+ left,
+ streamType: DataStreamTreeTokenType.LETTER,
+ };
+}
+
+function createLine(glyphs: unknown[], st: number, top: number) {
+ const line = {
+ divides: [] as unknown[],
+ ed: st + glyphs.length,
+ parent: null as unknown,
+ st,
+ top,
+ type: LineType.PARAGRAPH,
+ };
+ const divide = { glyphGroup: glyphs, left: 0, parent: line };
+ line.divides = [divide];
+ glyphs.forEach((glyph) => Object.assign(glyph as object, { parent: divide }));
+
+ return line;
+}
+
+function createBlockLine(st: number, ed: number) {
+ return {
+ divides: [],
+ ed,
+ parent: null as unknown,
+ paragraphIndex: ed,
+ st,
+ type: LineType.BLOCK,
+ };
+}
+
+function createColumn(lines: unknown[]) {
+ const column = {
+ lines,
+ parent: null as unknown,
+ };
+ lines.forEach((line) => Object.assign(line as object, { parent: column }));
+
+ return column;
+}
+
+function createPage(columns: unknown[], type: DocumentSkeletonPageType) {
+ const section = {
+ columns,
+ parent: null as unknown,
+ };
+ const page = {
+ sections: [section],
+ skeColumnGroups: new Map(),
+ skeTables: new Map(),
+ type,
+ };
+ Object.assign(section, { parent: page });
+ columns.forEach((column) => Object.assign(column as object, { parent: section }));
+
+ return page;
+}
+
+function createCellPage(lines: unknown[], left: number, width: number) {
+ return Object.assign(createPage([createColumn(lines)], DocumentSkeletonPageType.CELL), {
+ left,
+ marginLeft: 0,
+ marginRight: 0,
+ pageWidth: width,
+ });
+}
+
+function createTableRow(cells: ReturnType<typeof createCellPage>[], top: number) {
+ const row = {
+ cells,
+ height: 20,
+ index: 0,
+ isRepeatRow: false,
+ parent: null as unknown,
+ rowSource: {},
+ st: 0,
+ ed: 0,
+ top,
+ };
+ cells.forEach((cell) => Object.assign(cell, { parent: row }));
+
+ return row;
+}
+
+function createTable(
+ page: ReturnType<typeof createPage>,
+ rows: ReturnType<typeof createTableRow>[],
+ st: number,
+ ed: number
+) {
+ const table = {
+ height: 40,
+ left: 0,
+ parent: page,
+ rows,
+ st,
+ ed,
+ tableId: 'table-1',
+ tableSource: {},
+ top: 0,
+ width: 180,
+ };
+ rows.forEach((row, index) => Object.assign(row, { index, parent: table }));
+ page.skeTables.set('table-1', table as never);
+
+ return table;
+}
+
+function createColumnGroup(columns: object[], bodyPage: ReturnType<typeof createPage>) {
+ const columnGroup = {
+ columnGroupId: 'cg-1',
+ columns,
+ ed: 40,
+ height: 20,
+ left: 0,
+ st: 11,
+ top: 10,
+ width: 180,
+ };
+ columns.forEach((column) => {
+ const columnGroupColumn = column as { page: object; parent?: unknown };
+ columnGroupColumn.parent = columnGroup;
+ Object.assign(columnGroupColumn.page, { parent: columnGroupColumn });
+ });
+ Object.assign(columnGroup, { parent: bodyPage });
+
+ return columnGroup;
+}
diff --git a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
index cf0279dd29..02d157fca0 100644
--- a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
@@ -18,9 +18,12 @@ import type { ICommandInfo, Nullable } from '@univerjs/core';
import type {
DocumentSkeleton,
IDocumentSkeletonCached,
+ IDocumentSkeletonColumnGroup,
+ IDocumentSkeletonColumnGroupColumn,
IDocumentSkeletonGlyph,
IDocumentSkeletonLine,
IDocumentSkeletonPage,
+ IDocumentSkeletonRow,
IDocumentSkeletonTable,
INodePosition,
INodeSearch,
@@ -37,18 +40,13 @@ import {
RANGE_DIRECTION,
} from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
-import { DocumentSkeletonPageType, IRenderManagerService } from '@univerjs/engine-render';
+import { DocumentSkeletonPageType, IRenderManagerService, LineType } from '@univerjs/engine-render';
import { getDocObject } from '../basics/component-tools';
import {
- findAboveCell,
- findBellowCell,
- findLineBeforeAndAfterTable,
findTableAfterLine,
findTableBeforeLine,
firstLineInCell,
- firstLineInTable,
lastLineInCell,
- lastLineInTable,
} from '../basics/table';
import { MoveCursorOperation, MoveSelectionOperation } from '../commands/operations/doc-cursor.operation';
import { NodePositionConvertToCursor } from '../services/selection/convert-text-range';
@@ -62,6 +60,11 @@ interface IWholeEntityRange {
endIndex: number;
}
+interface ILineSearchTarget {
+ line: IDocumentSkeletonLine;
+ offsetLeft: number;
+}
+
export class DocMoveCursorController extends Disposable {
private _onInputSubscription: Nullable<Subscription>;
@@ -173,7 +176,14 @@ export class DocMoveCursorController extends Disposable {
: rangeDirection === RANGE_DIRECTION.FORWARD
? endOffset
: startOffset;
- const dataStreamLength = docDataModel.getSelfOrHeaderFooterModel(normalizedSegmentId).getBody()!.dataStream.length ?? Number.POSITIVE_INFINITY;
+ const body = docDataModel.getSelfOrHeaderFooterModel(normalizedSegmentId).getBody();
+
+ if (body == null) {
+ return;
+ }
+
+ const dataStreamLength = body.dataStream.length ?? Number.POSITIVE_INFINITY;
+ const customRanges = docDataModel.getCustomRanges() ?? [];
if (granularity !== 'character') {
const nextOffset = this._getCursorOffsetByGranularity(
@@ -183,22 +193,37 @@ export class DocMoveCursorController extends Disposable {
granularity,
normalizedSegmentId,
normalizedSegmentPage,
- dataStreamLength
+ dataStreamLength,
+ body.dataStream
);
if (nextOffset == null || nextOffset === focusOffset) {
return;
}
+ const normalizedNextOffset = this._normalizeRenderableCursorOffset(
+ skeleton,
+ body.dataStream,
+ customRanges,
+ nextOffset,
+ direction,
+ normalizedSegmentId,
+ normalizedSegmentPage
+ );
+
+ if (normalizedNextOffset == null || normalizedNextOffset === focusOffset) {
+ return;
+ }
+
this._textSelectionManagerService.replaceTextRanges([
{
startOffset: anchorOffset,
- endOffset: nextOffset,
+ endOffset: normalizedNextOffset,
style,
},
], false);
- this._scrollToFocusNodePosition(docDataModel.getUnitId(), nextOffset);
+ this._scrollToFocusNodePosition(docDataModel.getUnitId(), normalizedNextOffset);
return;
}
@@ -230,9 +255,17 @@ export class DocMoveCursorController extends Disposable {
if (newPos == null) {
// move selection
- const newFocusOffset = direction === Direction.UP ? 0 : dataStreamLength - 2;
-
- if (newFocusOffset === focusOffset) {
+ const newFocusOffset = this._normalizeRenderableCursorOffset(
+ skeleton,
+ body.dataStream,
+ customRanges,
+ direction === Direction.UP ? 0 : dataStreamLength - 2,
+ direction,
+ normalizedSegmentId,
+ normalizedSegmentPage
+ );
+
+ if (newFocusOffset == null || newFocusOffset === focusOffset) {
return;
}
@@ -251,17 +284,30 @@ export class DocMoveCursorController extends Disposable {
newPos,
newPos
).cursorList[0];
+ const newFocusOffset = this._normalizeRenderableCursorOffset(
+ skeleton,
+ body.dataStream,
+ customRanges,
+ newActiveRange.endOffset,
+ direction,
+ normalizedSegmentId,
+ normalizedSegmentPage
+ );
+
+ if (newFocusOffset == null || newFocusOffset === focusOffset) {
+ return;
+ }
// move selection
this._textSelectionManagerService.replaceTextRanges([
{
startOffset: anchorOffset,
- endOffset: newActiveRange.endOffset,
+ endOffset: newFocusOffset,
style,
},
], false);
- this._scrollToFocusNodePosition(docDataModel.getUnitId(), newActiveRange.endOffset);
+ this._scrollToFocusNodePosition(docDataModel.getUnitId(), newFocusOffset);
}
}
@@ -318,14 +364,27 @@ export class DocMoveCursorController extends Disposable {
granularity,
normalizedSegmentId,
normalizedSegmentPage,
- dataStreamLength
+ dataStreamLength,
+ body.dataStream
);
if (cursor == null) {
return;
}
- cursor = this._normalizeCursorOffset(body.dataStream, customRanges, cursor, direction);
+ cursor = this._normalizeRenderableCursorOffset(
+ skeleton,
+ body.dataStream,
+ customRanges,
+ cursor,
+ direction,
+ normalizedSegmentId,
+ normalizedSegmentPage
+ );
+
+ if (cursor == null) {
+ return;
+ }
this._textSelectionManagerService.replaceTextRanges([
{
@@ -378,17 +437,30 @@ export class DocMoveCursorController extends Disposable {
}
}
- cursor = this._normalizeWholeEntityRanges(customRanges, cursor, direction);
+ cursor = this._normalizeCursorOffset(body.dataStream, customRanges, cursor, direction);
+ const normalizedCursor = this._normalizeRenderableCursorOffset(
+ skeleton,
+ body.dataStream,
+ customRanges,
+ cursor,
+ direction,
+ normalizedSegmentId,
+ normalizedSegmentPage
+ );
+
+ if (normalizedCursor == null) {
+ return;
+ }
this._textSelectionManagerService.replaceTextRanges([
{
- startOffset: Math.max(0, cursor),
- endOffset: Math.max(0, cursor),
+ startOffset: normalizedCursor,
+ endOffset: normalizedCursor,
style,
},
], false);
- this._scrollToFocusNodePosition(docDataModel.getUnitId(), cursor);
+ this._scrollToFocusNodePosition(docDataModel.getUnitId(), normalizedCursor);
} else {
const startNode = skeleton.findNodeByCharIndex(startOffset, segmentId, segmentPage);
const endNode = skeleton.findNodeByCharIndex(endOffset, segmentId, segmentPage);
@@ -408,17 +480,37 @@ export class DocMoveCursorController extends Disposable {
if (collapsed) {
// Move cursor to the beginning place when arrow up at first line,
// and move cursor to the end place when arrow down at last line.
- cursor = direction === Direction.UP ? 0 : dataStreamLength - 2;
+ cursor = this._normalizeRenderableCursorOffset(
+ skeleton,
+ body.dataStream,
+ customRanges,
+ direction === Direction.UP ? 0 : dataStreamLength - 2,
+ direction,
+ normalizedSegmentId,
+ normalizedSegmentPage
+ );
} else {
// Handle at the startOffset at first line when arrow up,
// and endOffset at the last line when arrow down.
- cursor = direction === Direction.UP ? startOffset : endOffset;
+ cursor = this._normalizeRenderableCursorOffset(
+ skeleton,
+ body.dataStream,
+ customRanges,
+ direction === Direction.UP ? startOffset : endOffset,
+ direction,
+ normalizedSegmentId,
+ normalizedSegmentPage
+ );
+ }
+
+ if (cursor == null) {
+ return;
}
this._textSelectionManagerService.replaceTextRanges([
{
- startOffset: Math.max(0, cursor),
- endOffset: Math.max(0, cursor),
+ startOffset: cursor,
+ endOffset: cursor,
style,
},
], false);
@@ -430,16 +522,30 @@ export class DocMoveCursorController extends Disposable {
newPos,
newPos
).cursorList[0];
+ const cursor = this._normalizeRenderableCursorOffset(
+ skeleton,
+ body.dataStream,
+ customRanges,
+ newActiveRange.endOffset,
+ direction,
+ normalizedSegmentId,
+ normalizedSegmentPage
+ );
+
+ if (cursor == null) {
+ return;
+ }
// move selection
this._textSelectionManagerService.replaceTextRanges([
{
- ...newActiveRange,
+ startOffset: cursor,
+ endOffset: cursor,
style,
},
], false);
- this._scrollToFocusNodePosition(docDataModel.getUnitId(), newActiveRange.endOffset);
+ this._scrollToFocusNodePosition(docDataModel.getUnitId(), cursor);
}
}
@@ -450,11 +556,14 @@ export class DocMoveCursorController extends Disposable {
granularity: DocCursorMoveGranularity,
segmentId: string,
segmentPage: number,
- dataStreamLength: number
+ dataStreamLength: number,
+ dataStream = ''
): Nullable<number> {
switch (granularity) {
case 'document':
return direction === Direction.LEFT || direction === Direction.UP ? 0 : dataStreamLength - 2;
+ case 'paragraph':
+ return this._getParagraphBoundaryOffset(dataStream, focusOffset, direction);
case 'line':
return this._getLineBoundaryOffset(skeleton, focusOffset, direction, segmentId, segmentPage, dataStreamLength);
case 'word':
@@ -465,6 +574,46 @@ export class DocMoveCursorController extends Disposable {
}
}
+ private _getParagraphBoundaryOffset(
+ dataStream: string,
+ focusOffset: number,
+ direction: Direction
+ ): Nullable<number> {
+ if (direction !== Direction.UP && direction !== Direction.DOWN) {
+ return;
+ }
+
+ if (dataStream.length === 0) {
+ return 0;
+ }
+
+ const cursor = Math.min(Math.max(0, focusOffset), dataStream.length - 1);
+
+ if (direction === Direction.UP) {
+ const currentParagraphStart = this._getCurrentParagraphStartOffset(dataStream, cursor);
+ if (cursor > currentParagraphStart) {
+ return currentParagraphStart;
+ }
+
+ return this._getCurrentParagraphStartOffset(dataStream, Math.max(0, currentParagraphStart - 1));
+ }
+
+ const nextParagraphEnd = dataStream.indexOf(DataStreamTreeTokenType.PARAGRAPH, cursor);
+
+ return nextParagraphEnd === -1 ? dataStream.length - 1 : nextParagraphEnd + 1;
+ }
+
+ private _getCurrentParagraphStartOffset(dataStream: string, cursor: number): number {
+ for (let index = Math.min(cursor - 1, dataStream.length - 1); index >= 0; index--) {
+ const token = dataStream[index];
+ if (token === DataStreamTreeTokenType.PARAGRAPH || token === DataStreamTreeTokenType.SECTION_BREAK) {
+ return index + 1;
+ }
+ }
+
+ return 0;
+ }
+
private _getWordBoundaryOffset(
skeleton: DocumentSkeleton,
focusOffset: number,
@@ -592,6 +741,91 @@ export class DocMoveCursorController extends Disposable {
return this._normalizeWholeEntityRanges(customRanges, cursor, direction);
}
+ private _normalizeRenderableCursorOffset(
+ skeleton: DocumentSkeleton,
+ dataStream: string,
+ customRanges: IWholeEntityRange[],
+ cursor: number,
+ direction: Direction,
+ segmentId: string,
+ segmentPage: number
+ ): Nullable<number> {
+ const boundedCursor = Math.min(Math.max(0, cursor), Math.max(0, dataStream.length - 1));
+ const primaryCursor = this._findNearestRenderableCursorOffset(
+ skeleton,
+ dataStream,
+ customRanges,
+ boundedCursor,
+ direction,
+ segmentId,
+ segmentPage
+ );
+
+ if (primaryCursor != null) {
+ return primaryCursor;
+ }
+
+ const fallbackDirection = direction === Direction.LEFT || direction === Direction.UP ? Direction.DOWN : Direction.UP;
+
+ return this._findNearestRenderableCursorOffset(
+ skeleton,
+ dataStream,
+ customRanges,
+ boundedCursor,
+ fallbackDirection,
+ segmentId,
+ segmentPage
+ );
+ }
+
+ private _findNearestRenderableCursorOffset(
+ skeleton: DocumentSkeleton,
+ dataStream: string,
+ customRanges: IWholeEntityRange[],
+ cursor: number,
+ direction: Direction,
+ segmentId: string,
+ segmentPage: number
+ ): Nullable<number> {
+ const step = direction === Direction.LEFT || direction === Direction.UP ? -1 : 1;
+ let current = Math.min(Math.max(0, cursor), Math.max(0, dataStream.length - 1));
+ const visited = new Set<number>();
+
+ while (current >= 0 && current < dataStream.length && !visited.has(current)) {
+ visited.add(current);
+
+ const normalizedCursor = this._normalizeCursorOffset(dataStream, customRanges, current, direction);
+
+ if (normalizedCursor < 0 || normalizedCursor >= dataStream.length) {
+ return;
+ }
+
+ if (this._isRenderableCursorOffset(skeleton, dataStream, normalizedCursor, segmentId, segmentPage)) {
+ return normalizedCursor;
+ }
+
+ current = normalizedCursor + step;
+ }
+ }
+
+ private _isRenderableCursorOffset(
+ skeleton: DocumentSkeleton,
+ dataStream: string,
+ cursor: number,
+ segmentId: string,
+ segmentPage: number
+ ): boolean {
+ if (cursor < 0 || cursor >= dataStream.length) {
+ return false;
+ }
+
+ if (this._getNonRenderableCursorTokens().includes(dataStream[cursor])) {
+ return false;
+ }
+
+ return skeleton.findNodePositionByCharIndex(cursor, true, segmentId, segmentPage) != null;
+ }
+
private _normalizeWholeEntityRanges(
customRanges: IWholeEntityRange[],
cursor: number,
@@ -629,6 +863,16 @@ export class DocMoveCursorController extends Disposable {
return tokens;
}
+ private _getNonRenderableCursorTokens(): string[] {
+ return [
+ ...this._getCursorSkipTokens(),
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ DataStreamTreeTokenType.COLUMN_START,
+ DataStreamTreeTokenType.COLUMN_END,
+ ];
+ }
+
private _getTopOrBottomPosition(
docSkeleton: DocumentSkeleton,
glyph: Nullable<IDocumentSkeletonGlyph>,
@@ -642,13 +886,13 @@ export class DocMoveCursorController extends Disposable {
const offsetLeft = this._getGlyphLeftOffsetInLine(glyph);
- const line = this._getNextOrPrevLine(glyph, direction, skipCellContent);
+ const target = this._getNextOrPrevLineTarget(glyph, direction, offsetLeft, skipCellContent);
- if (line == null) {
+ if (target == null) {
return;
}
- const position: Nullable<INodeSearch> = this._matchPositionByLeftOffset(docSkeleton, line, offsetLeft, nodePosition);
+ const position: Nullable<INodeSearch> = this._matchPositionByLeftOffset(docSkeleton, target.line, target.offsetLeft, nodePosition);
if (position == null) {
return;
@@ -727,7 +971,12 @@ export class DocMoveCursorController extends Disposable {
}
// eslint-disable-next-line max-lines-per-function, complexity
- private _getNextOrPrevLine(glyph: IDocumentSkeletonGlyph, direction: boolean, skipCellContent = false) {
+ private _getNextOrPrevLineTarget(
+ glyph: IDocumentSkeletonGlyph,
+ direction: boolean,
+ offsetLeft: number,
+ skipCellContent = false
+ ): Nullable<ILineSearchTarget> {
const divide = glyph.parent;
const line = divide?.parent;
const column = line?.parent;
@@ -746,38 +995,37 @@ export class DocMoveCursorController extends Disposable {
let newLine: IDocumentSkeletonLine;
- if (page.type === DocumentSkeletonPageType.CELL && skipCellContent) {
- const nLine = findAboveOrBellowCellLine(page, direction);
+ if (this._isTableCellContentPage(page) && skipCellContent) {
+ const tableCellTarget = this._getAdjacentTableCellLineTarget(page, direction, offsetLeft);
- if (nLine) {
- return nLine;
+ if (tableCellTarget != null) {
+ return tableCellTarget;
}
}
if (direction === true) {
newLine = column.lines[currentLineIndex + 1];
- const tableAfterLine = findTableAfterLine(line, page);
+ const tableTarget = this._getTableLineTargetFromPageLine(line, page, direction, offsetLeft);
- if (tableAfterLine) {
- const firstLine = firstLineInTable(tableAfterLine);
- if (firstLine) {
- newLine = firstLine;
- }
+ if (tableTarget != null) {
+ return tableTarget;
}
} else {
newLine = column.lines[currentLineIndex - 1];
- // If the previous line is behind the table, find the last line of the table.
- const tableBeforeLine = findTableBeforeLine(line, page);
- if (tableBeforeLine) {
- const lastLine = lastLineInTable(tableBeforeLine);
- if (lastLine) {
- newLine = lastLine;
- }
+ const tableTarget = this._getTableLineTargetFromPageLine(line, page, direction, offsetLeft);
+
+ if (tableTarget != null) {
+ return tableTarget;
}
}
+ const columnGroupTarget = this._getColumnGroupLineTargetFromBlockLine(newLine, page, direction, offsetLeft);
+ if (columnGroupTarget != null) {
+ return columnGroupTarget;
+ }
+
if (newLine != null) {
- return newLine;
+ return { line: newLine, offsetLeft };
}
const currentColumnIndex = section.columns.indexOf(column);
@@ -794,7 +1042,7 @@ export class DocMoveCursorController extends Disposable {
}
if (newLine != null) {
- return newLine;
+ return { line: newLine, offsetLeft };
}
const currentSectionIndex = page.sections.indexOf(section);
@@ -813,11 +1061,18 @@ export class DocMoveCursorController extends Disposable {
}
if (newLine != null) {
- return newLine;
+ return { line: newLine, offsetLeft };
}
- if (page.type === DocumentSkeletonPageType.CELL) {
- return findAboveOrBellowCellLine(page, direction);
+ if (this._isColumnGroupContentPage(page)) {
+ const exitTarget = this._getColumnGroupExitLineTarget(page, direction, offsetLeft);
+ if (exitTarget != null) {
+ return exitTarget;
+ }
+ }
+
+ if (this._isTableCellContentPage(page)) {
+ return this._getAdjacentTableCellLineTarget(page, direction, offsetLeft);
}
const skeleton: Nullable<IDocumentSkeletonCached> = page.parent as IDocumentSkeletonCached;
@@ -846,10 +1101,369 @@ export class DocMoveCursorController extends Disposable {
}
if (newLine != null) {
- return newLine;
+ return { line: newLine, offsetLeft };
+ }
+ }
+
+ private _getTableLineTargetFromPageLine(
+ line: IDocumentSkeletonLine,
+ page: IDocumentSkeletonPage,
+ direction: boolean,
+ offsetLeft: number
+ ): Nullable<ILineSearchTarget> {
+ const table = direction ? findTableAfterLine(line, page) : findTableBeforeLine(line, page);
+
+ if (table == null) {
+ return;
+ }
+
+ return this._getTableBoundaryLineTarget(table, direction, offsetLeft);
+ }
+
+ private _getTableBoundaryLineTarget(
+ table: IDocumentSkeletonTable,
+ direction: boolean,
+ offsetLeft: number
+ ): Nullable<ILineSearchTarget> {
+ const rows = direction ? table.rows : [...table.rows].reverse();
+
+ for (const row of rows) {
+ if (row.isRepeatRow) {
+ continue;
+ }
+
+ const target = this._getNearestTableCellLineTarget(row.cells, direction, offsetLeft);
+ if (target != null) {
+ return target;
+ }
+ }
+ }
+
+ private _getAdjacentTableCellLineTarget(
+ cell: IDocumentSkeletonPage,
+ direction: boolean,
+ offsetLeft: number
+ ): Nullable<ILineSearchTarget> {
+ const row = cell.parent as Nullable<IDocumentSkeletonRow>;
+ const table = row?.parent;
+
+ if (row == null || table == null) {
+ return;
+ }
+
+ const hostOffsetLeft = this._getTableCellHostOffsetLeft(cell) + offsetLeft;
+ const adjacentRow = this._findAdjacentTableRow(table, row, direction);
+
+ if (adjacentRow != null) {
+ return this._getNearestTableCellLineTarget(adjacentRow.cells, direction, hostOffsetLeft);
+ }
+
+ const line = this._findLineAroundTable(table, direction);
+
+ if (line == null) {
+ return;
+ }
+
+ return { line, offsetLeft: hostOffsetLeft };
+ }
+
+ private _findAdjacentTableRow(
+ table: IDocumentSkeletonTable,
+ row: IDocumentSkeletonRow,
+ direction: boolean
+ ): Nullable<IDocumentSkeletonRow> {
+ const currentRowIndex = table.rows.indexOf(row);
+ if (currentRowIndex === -1) {
+ return;
+ }
+
+ const step = direction ? 1 : -1;
+ let rowIndex = currentRowIndex + step;
+
+ while (rowIndex >= 0 && rowIndex < table.rows.length) {
+ const adjacentRow = table.rows[rowIndex];
+ if (!adjacentRow.isRepeatRow) {
+ return adjacentRow;
+ }
+
+ rowIndex += step;
+ }
+
+ return this._findAdjacentTableSliceRow(table, direction);
+ }
+
+ private _findAdjacentTableSliceRow(
+ table: IDocumentSkeletonTable,
+ direction: boolean
+ ): Nullable<IDocumentSkeletonRow> {
+ if (!table.tableId.includes('#-#')) {
+ return;
+ }
+
+ const [sourceTableId, sliceIndexText] = table.tableId.split('#-#');
+ const sliceIndex = Number.parseInt(sliceIndexText);
+ const tablePage = table.parent;
+ const skeleton = tablePage?.parent as Nullable<IDocumentSkeletonCached>;
+
+ if (!Number.isFinite(sliceIndex) || skeleton?.pages == null) {
+ return;
+ }
+
+ const nextTableId = `${sourceTableId}#-#${sliceIndex + (direction ? 1 : -1)}`;
+ for (const page of skeleton.pages) {
+ const nextTable = page.skeTables?.get(nextTableId);
+ const rows = nextTable == null ? [] : direction ? nextTable.rows : [...nextTable.rows].reverse();
+ const row = rows.find((item) => !item.isRepeatRow);
+
+ if (row != null) {
+ return row;
+ }
+ }
+ }
+
+ private _getNearestTableCellLineTarget(
+ cells: IDocumentSkeletonPage[],
+ direction: boolean,
+ hostOffsetLeft: number
+ ): Nullable<ILineSearchTarget> {
+ const candidates = cells
+ .filter((cell) => !(cell as IDocumentSkeletonPage & { isMergedCellCovered?: boolean }).isMergedCellCovered)
+ .map((cell) => ({
+ cell,
+ distance: this._getDistanceToTableCell(cell, hostOffsetLeft),
+ }))
+ .sort((a, b) => a.distance - b.distance);
+
+ for (const candidate of candidates) {
+ const line = direction ? firstLineInCell(candidate.cell) : lastLineInCell(candidate.cell);
+ if (line != null) {
+ return {
+ line,
+ offsetLeft: hostOffsetLeft - this._getTableCellHostOffsetLeft(candidate.cell),
+ };
+ }
+ }
+ }
+
+ private _findLineAroundTable(
+ table: IDocumentSkeletonTable,
+ direction: boolean
+ ): Nullable<IDocumentSkeletonLine> {
+ const tablePage = table.parent;
+
+ if (tablePage == null) {
+ return;
+ }
+
+ const pages = (tablePage.parent as Nullable<IDocumentSkeletonCached>)?.pages ?? [tablePage];
+ const lineMatcher = direction
+ ? (line: IDocumentSkeletonLine) => line.st === table.ed + 1
+ : (line: IDocumentSkeletonLine) => line.ed === table.st - 1;
+
+ for (const page of pages) {
+ for (const section of page.sections) {
+ for (const column of section.columns) {
+ const lines = direction ? column.lines : [...column.lines].reverse();
+ const line = lines.find(lineMatcher);
+ if (line != null) {
+ return line;
+ }
+ }
+ }
+ }
+ }
+
+ private _getDistanceToTableCell(cell: IDocumentSkeletonPage, offsetLeft: number): number {
+ const left = this._getTableCellHostOffsetLeft(cell);
+ const right = left + this._getTableCellContentWidth(cell);
+
+ if (offsetLeft >= left && offsetLeft <= right) {
+ return 0;
+ }
+
+ return Math.min(Math.abs(offsetLeft - left), Math.abs(offsetLeft - right));
+ }
+
+ private _getTableCellHostOffsetLeft(cell: IDocumentSkeletonPage): number {
+ const row = cell.parent as Nullable<IDocumentSkeletonRow>;
+ const table = row?.parent;
+
+ return (table?.left ?? 0) + (cell.left ?? 0) + (cell.marginLeft ?? 0);
+ }
+
+ private _getTableCellContentWidth(cell: IDocumentSkeletonPage): number {
+ return Math.max(0, (cell.pageWidth ?? 0) - (cell.marginLeft ?? 0) - (cell.marginRight ?? 0));
+ }
+
+ private _isTableCellContentPage(page: IDocumentSkeletonPage): boolean {
+ const row = page.parent as Nullable<IDocumentSkeletonRow>;
+ const table = row?.parent;
+
+ return page.type === DocumentSkeletonPageType.CELL && row != null && table?.rows?.includes(row) === true && row.cells.includes(page);
+ }
+
+ private _getColumnGroupLineTargetFromBlockLine(
+ line: Nullable<IDocumentSkeletonLine>,
+ page: IDocumentSkeletonPage,
+ direction: boolean,
+ offsetLeft: number
+ ): Nullable<ILineSearchTarget> {
+ if (line == null || line.type !== LineType.BLOCK) {
+ return;
+ }
+
+ const columnGroup = this._findColumnGroupByBlockLine(page, line);
+ if (columnGroup == null) {
+ return;
+ }
+
+ return this._getColumnGroupContentLineTarget(columnGroup, direction, offsetLeft);
+ }
+
+ private _getColumnGroupContentLineTarget(
+ columnGroup: IDocumentSkeletonColumnGroup,
+ direction: boolean,
+ offsetLeft: number
+ ): Nullable<ILineSearchTarget> {
+ const candidates = columnGroup.columns
+ .map((column) => ({
+ column,
+ distance: this._getDistanceToColumnGroupColumn(column, offsetLeft),
+ }))
+ .sort((a, b) => a.distance - b.distance);
+
+ for (const candidate of candidates) {
+ const line = this._getColumnGroupColumnBoundaryLine(candidate.column, direction);
+ if (line != null) {
+ return {
+ line,
+ offsetLeft: offsetLeft - candidate.column.left,
+ };
+ }
+ }
+ }
+
+ private _getColumnGroupExitLineTarget(
+ page: IDocumentSkeletonPage,
+ direction: boolean,
+ offsetLeft: number
+ ): Nullable<ILineSearchTarget> {
+ const columnGroupColumn = page.parent as Nullable<IDocumentSkeletonColumnGroupColumn>;
+ const columnGroup = columnGroupColumn?.parent;
+ const hostPage = columnGroup?.parent;
+
+ if (columnGroupColumn == null || columnGroup == null || hostPage == null) {
+ return;
+ }
+
+ const blockLine = this._findColumnGroupBlockLine(columnGroup);
+ const line = blockLine == null ? undefined : this._getAdjacentLineAroundBlockLine(blockLine, direction);
+
+ if (line == null) {
+ return;
+ }
+
+ return {
+ line,
+ offsetLeft: columnGroupColumn.left + offsetLeft,
+ };
+ }
+
+ private _findColumnGroupByBlockLine(
+ page: IDocumentSkeletonPage,
+ line: IDocumentSkeletonLine
+ ): Nullable<IDocumentSkeletonColumnGroup> {
+ for (const columnGroup of page.skeColumnGroups?.values() ?? []) {
+ if (line.paragraphIndex === columnGroup.ed || (line.st <= columnGroup.ed && line.ed >= columnGroup.st)) {
+ return columnGroup;
+ }
+ }
+ }
+
+ private _findColumnGroupBlockLine(columnGroup: IDocumentSkeletonColumnGroup): Nullable<IDocumentSkeletonLine> {
+ const page = columnGroup.parent;
+ if (page == null) {
+ return;
+ }
+
+ for (const section of page.sections) {
+ for (const column of section.columns) {
+ for (const line of column.lines) {
+ if (line.type === LineType.BLOCK && this._findColumnGroupByBlockLine(page, line) === columnGroup) {
+ return line;
+ }
+ }
+ }
+ }
+ }
+
+ private _getAdjacentLineAroundBlockLine(
+ line: IDocumentSkeletonLine,
+ direction: boolean
+ ): Nullable<IDocumentSkeletonLine> {
+ const column = line.parent;
+ const section = column?.parent;
+ const page = section?.parent;
+
+ if (column == null || section == null || page == null) {
+ return;
+ }
+
+ const lineIndex = column.lines.indexOf(line);
+ if (lineIndex === -1) {
+ return;
+ }
+
+ const sameColumnLine = column.lines[direction ? lineIndex + 1 : lineIndex - 1];
+ if (sameColumnLine != null) {
+ return sameColumnLine;
+ }
+
+ const columnIndex = section.columns.indexOf(column);
+ if (columnIndex === -1) {
+ return;
+ }
+
+ if (direction) {
+ return section.columns[columnIndex + 1]?.lines[0];
+ }
+
+ const prevColumnLines = section.columns[columnIndex - 1]?.lines;
+ return prevColumnLines?.[prevColumnLines.length - 1];
+ }
+
+ private _getColumnGroupColumnBoundaryLine(
+ column: IDocumentSkeletonColumnGroupColumn,
+ direction: boolean
+ ): Nullable<IDocumentSkeletonLine> {
+ const sections = direction ? column.page.sections : [...column.page.sections].reverse();
+
+ for (const section of sections) {
+ const columns = direction ? section.columns : [...section.columns].reverse();
+ for (const skeletonColumn of columns) {
+ const lines = direction ? skeletonColumn.lines : [...skeletonColumn.lines].reverse();
+ const line = lines.find((item) => item.type !== LineType.BLOCK);
+ if (line != null) {
+ return line;
+ }
+ }
}
}
+ private _getDistanceToColumnGroupColumn(column: IDocumentSkeletonColumnGroupColumn, offsetLeft: number): number {
+ if (offsetLeft >= column.left && offsetLeft <= column.left + column.width) {
+ return 0;
+ }
+
+ return Math.min(Math.abs(offsetLeft - column.left), Math.abs(offsetLeft - column.left - column.width));
+ }
+
+ private _isColumnGroupContentPage(page: IDocumentSkeletonPage): boolean {
+ const parent = page.parent as Nullable<IDocumentSkeletonColumnGroupColumn>;
+
+ return parent?.page === page && parent.parent?.columns?.includes(parent) === true;
+ }
+
private _scrollToFocusNodePosition(unitId: string, offset: number) {
const backScrollController = this._renderManagerService.getRenderById(unitId)?.with(DocBackScrollRenderController);
if (backScrollController == null) {
@@ -868,37 +1482,3 @@ export class DocMoveCursorController extends Disposable {
return getDocObject(this._univerInstanceService, this._renderManagerService);
}
}
-
-function findAboveOrBellowCellLine(
- page: IDocumentSkeletonPage,
- direction: boolean
-) {
- let newLine = null;
- if (direction === true) {
- const bellowCell = findBellowCell(page);
- if (bellowCell) {
- newLine = firstLineInCell(bellowCell);
- } else {
- const table = page.parent?.parent as IDocumentSkeletonTable;
- const { lineAfterTable } = findLineBeforeAndAfterTable(table);
-
- if (lineAfterTable) {
- newLine = lineAfterTable;
- }
- }
- } else {
- const aboveCell = findAboveCell(page);
- if (aboveCell) {
- newLine = lastLineInCell(aboveCell)!;
- } else {
- const table = page.parent?.parent as IDocumentSkeletonTable;
- const { lineBeforeTable } = findLineBeforeAndAfterTable(table);
-
- if (lineBeforeTable) {
- newLine = lineBeforeTable;
- }
- }
- }
-
- return newLine;
-}
diff --git a/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts b/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
new file mode 100644
index 0000000000..cfdd64a9f0
--- /dev/null
+++ b/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
@@ -0,0 +1,113 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ITextRangeWithStyle } from '@univerjs/engine-render';
+import { DOC_RANGE_TYPE, IUniverInstanceService } from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { Subject } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { InsertRowBeforeMenuItemFactory } from '../context-menu';
+
+describe('doc context menu table predicates', () => {
+ it('disables table actions for expanded text selections inside a table cell', () => {
+ const harness = createTableMenuHarness({
+ activeTextRange: {
+ collapsed: false,
+ endOffset: 16,
+ startOffset: 12,
+ },
+ rectRanges: [],
+ });
+
+ expect(readDisabledState(harness)).toBe(true);
+ });
+
+ it('keeps table actions enabled for collapsed cursors inside a table cell', () => {
+ const harness = createTableMenuHarness({
+ activeTextRange: {
+ collapsed: true,
+ endOffset: 12,
+ startOffset: 12,
+ },
+ rectRanges: [],
+ });
+
+ expect(readDisabledState(harness)).toBe(false);
+ });
+
+ it('keeps table actions enabled for table rect selections', () => {
+ const harness = createTableMenuHarness({
+ activeTextRange: null,
+ rectRanges: [{
+ endOffset: 16,
+ rangeType: DOC_RANGE_TYPE.RECT,
+ startOffset: 12,
+ tableId: 'table-1',
+ }],
+ });
+
+ expect(readDisabledState(harness)).toBe(false);
+ });
+});
+
+function readDisabledState(harness: ReturnType<typeof createTableMenuHarness>) {
+ const item = InsertRowBeforeMenuItemFactory(harness.accessor as never);
+ const values: boolean[] = [];
+ const subscription = item.disabled$!.subscribe((value) => {
+ values.push(value);
+ });
+ subscription.unsubscribe();
+
+ return values.at(-1);
+}
+
+function createTableMenuHarness(options: {
+ activeTextRange: Pick<ITextRangeWithStyle, 'collapsed' | 'endOffset' | 'startOffset'> | null;
+ rectRanges: Array<{ endOffset: number; rangeType: DOC_RANGE_TYPE | string; startOffset: number; tableId: string }>;
+}) {
+ const selection$ = new Subject<unknown>();
+ const selectionManager = {
+ getActiveTextRange: () => options.activeTextRange,
+ getRectRanges: () => options.rectRanges,
+ textSelection$: selection$,
+ };
+ const univerInstanceService = {
+ getCurrentUniverDocInstance: () => ({
+ getSelfOrHeaderFooterModel: () => ({
+ getBody: () => ({
+ tables: [{ endIndex: 30, startIndex: 10, tableId: 'table-1' }],
+ }),
+ }),
+ }),
+ };
+
+ return {
+ accessor: {
+ get: (token: unknown) => {
+ if (token === DocSelectionManagerService) {
+ return selectionManager;
+ }
+
+ if (token === IUniverInstanceService) {
+ return univerInstanceService;
+ }
+
+ return null;
+ },
+ },
+ selection$,
+ };
+}
diff --git a/packages/docs-ui/src/menu/context-menu.ts b/packages/docs-ui/src/menu/context-menu.ts
index 45b6eee378..c23a8a3da5 100644
--- a/packages/docs-ui/src/menu/context-menu.ts
+++ b/packages/docs-ui/src/menu/context-menu.ts
@@ -75,6 +75,12 @@ function notInTableSubscriber(subscriber: Subscriber<boolean>, docSelectionManag
if (activeRange && (rectRanges == null || rectRanges.length === 0)) {
const { segmentId, startOffset, endOffset } = activeRange;
+ const isCollapsed = activeRange.collapsed === true || startOffset === endOffset;
+ if (!isCollapsed) {
+ subscriber.next(true);
+ return;
+ }
+
const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
const tables = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody()?.tables;
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 1c510e724d..698684041d 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -140,6 +140,8 @@ import {
MoveCursorLeftShortcut,
MoveCursorLineEndShortcut,
MoveCursorLineStartShortcut,
+ MoveCursorParagraphDownShortcut,
+ MoveCursorParagraphUpShortcut,
MoveCursorRightShortcut,
MoveCursorUpShortcut,
MoveCursorWordLeftShortcut,
@@ -150,6 +152,8 @@ import {
MoveSelectionLeftShortcut,
MoveSelectionLineEndShortcut,
MoveSelectionLineStartShortcut,
+ MoveSelectionParagraphDownShortcut,
+ MoveSelectionParagraphUpShortcut,
MoveSelectionRightShortcut,
MoveSelectionUpShortcut,
MoveSelectionWordLeftShortcut,
@@ -327,6 +331,10 @@ export class UniverDocsUIPlugin extends Plugin {
MoveCursorLineEndShortcut,
MoveSelectionLineStartShortcut,
MoveSelectionLineEndShortcut,
+ MoveCursorParagraphUpShortcut,
+ MoveCursorParagraphDownShortcut,
+ MoveSelectionParagraphUpShortcut,
+ MoveSelectionParagraphDownShortcut,
MoveCursorDocumentStartShortcut,
MoveCursorDocumentEndShortcut,
MoveSelectionDocumentStartShortcut,
diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
index efc5f159e4..d7684f4b19 100644
--- a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IMutiPageParagraphBound } from '../doc-event-manager.service';
+import type { IMutiPageParagraphBound, ITableBound } from '../doc-event-manager.service';
import { BlockType, DataStreamTreeTokenType, DOC_RANGE_TYPE, DocumentBlockRangeType, PresetListType } from '@univerjs/core';
import { DocumentEditArea } from '@univerjs/engine-render';
import { BehaviorSubject, Subject } from 'rxjs';
@@ -1022,7 +1022,7 @@ describe('DocParagraphMenuService', () => {
const dispose = vi.fn();
const hoverParagraphRealTime$ = new BehaviorSubject<IMutiPageParagraphBound | null>(null);
const hoverParagraphLeft$ = new BehaviorSubject<IMutiPageParagraphBound | null>(null);
- const hoverTableRealTime$ = new BehaviorSubject<null>(null);
+ const hoverTableRealTime$ = new BehaviorSubject<ITableBound | null>(null);
const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose }));
const service = createService({
attachPopupToRect,
@@ -1084,6 +1084,50 @@ describe('DocParagraphMenuService', () => {
expect(attachPopupToRect).not.toHaveBeenCalled();
});
+ it('hides a visible table menu as soon as text selection starts', () => {
+ const dispose = vi.fn();
+ const selectionStart$ = new Subject<unknown>();
+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose }));
+ const service = createService({
+ attachPopupToRect,
+ dataStream: '',
+ selectionStart$,
+ tables: [{ tableId: 'table-1', startIndex: 10, endIndex: 30 }],
+ });
+
+ service.showTableMenu({
+ pageIndex: 0,
+ rect: { bottom: 170, left: 100, right: 400, top: 80 },
+ tableId: 'table-1',
+ });
+ selectionStart$.next(null);
+
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(service.activeTarget).toBeNull();
+ });
+
+ it('does not show table menus from hover events while pointer text selection is active', async () => {
+ const hoverTableRealTime$ = new BehaviorSubject<ITableBound | null>(null);
+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));
+ const service = createService({
+ attachPopupToRect,
+ dataStream: '',
+ hoverTableRealTime$,
+ isOnPointerEvent: true,
+ tables: [{ tableId: 'table-1', startIndex: 10, endIndex: 30 }],
+ });
+
+ hoverTableRealTime$.next({
+ pageIndex: 0,
+ rect: { bottom: 170, left: 100, right: 400, top: 80 },
+ tableId: 'table-1',
+ });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(attachPopupToRect).not.toHaveBeenCalled();
+ expect(service.activeTarget).toBeNull();
+ });
+
it('calculates paragraph drop targets before and after the nearest body block', () => {
const paragraphBounds = new Map([
[3, createParagraphBound({
@@ -1190,11 +1234,13 @@ function createService(options: {
paragraphBounds?: Map<number, IMutiPageParagraphBound>;
hoverParagraphLeft$?: BehaviorSubject<IMutiPageParagraphBound | null>;
hoverParagraphRealTime$?: BehaviorSubject<IMutiPageParagraphBound | null>;
- hoverTableRealTime$?: BehaviorSubject<null>;
+ hoverTableRealTime$?: BehaviorSubject<ITableBound | null>;
+ isOnPointerEvent?: boolean;
inputBefore$?: Subject<unknown>;
keydown$?: Subject<unknown>;
replaceDocRanges?: ReturnType<typeof vi.fn>;
scrollAfter$?: { subscribeEvent: (callback: (event: { scrollY: number }) => void) => { dispose: () => void } };
+ selectionStart$?: Subject<unknown>;
textSelection$?: Subject<unknown>;
tableCellBounds?: Map<string, Array<{ colIndex: number; pageIndex: number; rect: { bottom: number; left: number; right: number; top: number }; rowIndex: number; tableId: string }>>;
tables?: Array<{ endIndex: number; startIndex: number; tableId: string }>;
@@ -1266,6 +1312,8 @@ function createService(options: {
{
onInputBefore$: options.inputBefore$ ?? new Subject(),
onKeydown$: options.keydown$ ?? new Subject(),
+ onSelectionStart$: options.selectionStart$ ?? new Subject(),
+ isOnPointerEvent: options.isOnPointerEvent ?? false,
} as never
);
}
diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
index bced1d3cd3..a864970b59 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -251,6 +251,11 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
return;
}
+ if (this._docSelectionRenderService.isOnPointerEvent) {
+ this.hideParagraphMenu(true);
+ return;
+ }
+
const selectionState = this._getExpandedSelectionState(this._docSelectionManagerService.getDocRanges());
if (selectionState.hasExpandedTextRange) {
this.hideParagraphMenu(true);
@@ -308,6 +313,10 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
})
);
+ this.disposeWithMe(this._docSelectionRenderService.onSelectionStart$.subscribe(() => {
+ this.hideParagraphMenu(true);
+ }));
+
this.disposeWithMe(this._docSelectionManagerService.textSelection$.subscribe(({ textRanges, rectRanges }) => {
const selectionState = this._getExpandedSelectionState([...textRanges, ...rectRanges]);
if (selectionState.hasExpandedTextRange || (selectionState.hasRectRange && this._paragrahMenu?.target.kind !== 'table')) {
diff --git a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
index 3e8b608774..75ed0e1573 100644
--- a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
@@ -488,6 +488,33 @@ describe('selection utils', () => {
expect(rectRange?.rectRanges[0]).toBeInstanceOf(RectRange);
});
+ it('keeps text selection inside one table cell even when glyph paths differ', () => {
+ const anchor = createNodePosition(['pages', 0, 'skeTables', 'table-1#-#0', 'rows', 0, 'cells', 0, 'sections', 0, 'columns', 0, 'lines', 0, 'divides', 0, 'glyphs', 0]);
+ const focus = createNodePosition(['pages', 0, 'skeTables', 'table-1#-#0', 'rows', 0, 'cells', 0, 'sections', 0, 'columns', 0, 'lines', 1, 'divides', 0, 'glyphs', 3], 3);
+ const cellPage = {} as { parent?: unknown };
+ const row = { index: 0, cells: [cellPage] };
+ cellPage.parent = row;
+ const skeleton = {
+ findGlyphByPosition: vi
+ .fn()
+ .mockReturnValueOnce(createGlyphInCell(cellPage))
+ .mockReturnValueOnce(createGlyphInCell(cellPage)),
+ } as never;
+
+ vi.spyOn(NodePositionConvertToRectRange.prototype, 'getNodePositionGroup').mockReturnValue([
+ {
+ anchor,
+ focus,
+ },
+ ] as never);
+
+ const result = getRangeListFromSelection(anchor, focus, {} as never, createDocument(), skeleton, {} as never, '', -1);
+
+ expect(result?.textRanges).toHaveLength(1);
+ expect(result?.rectRanges).toHaveLength(0);
+ expect(result?.textRanges[0]).toBeInstanceOf(TextRange);
+ });
+
it('expands core rect selection records to cover intersecting merged cells', () => {
const { anchor, focus, skeleton } = createRectRangeConvertorHarness();
const convertor = new NodePositionConvertToRectRange({
diff --git a/packages/docs-ui/src/services/selection/convert-rect-range.ts b/packages/docs-ui/src/services/selection/convert-rect-range.ts
index 1c09696d55..9d9976f94f 100644
--- a/packages/docs-ui/src/services/selection/convert-rect-range.ts
+++ b/packages/docs-ui/src/services/selection/convert-rect-range.ts
@@ -16,7 +16,6 @@
import type { ITable, Nullable } from '@univerjs/core';
import type { DocumentSkeleton, IDocsTableRenderViewport, IDocumentOffsetConfig, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, INodePosition, IPoint } from '@univerjs/engine-render';
-import { Tools } from '@univerjs/core';
import { DocumentSkeletonPageType, documentSkeletonTableIterator, getDocsTableRenderViewport, getPageFromPath, getTableIdAndSliceIndex, Liquid } from '@univerjs/engine-render';
import { compareNodePositionLogic, pushToPoints } from './convert-text-range';
@@ -67,11 +66,27 @@ export function isInSameTableCell(anchorNodePosition: INodePosition, focusNodePo
return false;
}
- if (anchorPath.length !== focusPath.length) {
+ const anchorTableIdIndex = anchorPath.indexOf('skeTables') + 1;
+ const anchorRowIndex = anchorPath.indexOf('rows') + 1;
+ const anchorCellIndex = anchorPath.indexOf('cells') + 1;
+ const focusTableIdIndex = focusPath.indexOf('skeTables') + 1;
+ const focusRowIndex = focusPath.indexOf('rows') + 1;
+ const focusCellIndex = focusPath.indexOf('cells') + 1;
+
+ if (
+ anchorTableIdIndex === 0 ||
+ anchorRowIndex === 0 ||
+ anchorCellIndex === 0 ||
+ focusTableIdIndex === 0 ||
+ focusRowIndex === 0 ||
+ focusCellIndex === 0
+ ) {
return false;
}
- return Tools.diffValue(anchorPath, focusPath);
+ return anchorPath[anchorTableIdIndex] === focusPath[focusTableIdIndex] &&
+ anchorPath[anchorRowIndex] === focusPath[focusRowIndex] &&
+ anchorPath[anchorCellIndex] === focusPath[focusCellIndex];
}
// Determine whether the selection is in the same table cell support across pages.
diff --git a/packages/docs-ui/src/shortcuts/__tests__/cursor.shortcut.spec.ts b/packages/docs-ui/src/shortcuts/__tests__/cursor.shortcut.spec.ts
index c3fe847dbe..2867e9e649 100644
--- a/packages/docs-ui/src/shortcuts/__tests__/cursor.shortcut.spec.ts
+++ b/packages/docs-ui/src/shortcuts/__tests__/cursor.shortcut.spec.ts
@@ -23,12 +23,16 @@ import {
MoveCursorDocumentStartShortcut,
MoveCursorLineEndShortcut,
MoveCursorLineStartShortcut,
+ MoveCursorParagraphDownShortcut,
+ MoveCursorParagraphUpShortcut,
MoveCursorWordLeftShortcut,
MoveCursorWordRightShortcut,
MoveSelectionDocumentEndShortcut,
MoveSelectionDocumentStartShortcut,
MoveSelectionLineEndShortcut,
MoveSelectionLineStartShortcut,
+ MoveSelectionParagraphDownShortcut,
+ MoveSelectionParagraphUpShortcut,
MoveSelectionWordLeftShortcut,
MoveSelectionWordRightShortcut,
} from '../cursor.shortcut';
@@ -114,4 +118,31 @@ describe('docs cursor shortcuts', () => {
staticParameters: { direction: Direction.RIGHT, granularity: 'word' },
});
});
+
+ it('registers paragraph movement shortcuts with Option on macOS and Ctrl elsewhere', () => {
+ expect(MoveCursorParagraphUpShortcut).toMatchObject({
+ id: MoveCursorOperation.id,
+ binding: KeyCode.ARROW_UP | MetaKeys.CTRL_COMMAND,
+ mac: KeyCode.ARROW_UP | MetaKeys.ALT,
+ staticParameters: { direction: Direction.UP, granularity: 'paragraph' },
+ });
+ expect(MoveCursorParagraphDownShortcut).toMatchObject({
+ id: MoveCursorOperation.id,
+ binding: KeyCode.ARROW_DOWN | MetaKeys.CTRL_COMMAND,
+ mac: KeyCode.ARROW_DOWN | MetaKeys.ALT,
+ staticParameters: { direction: Direction.DOWN, granularity: 'paragraph' },
+ });
+ expect(MoveSelectionParagraphUpShortcut).toMatchObject({
+ id: MoveSelectionOperation.id,
+ binding: KeyCode.ARROW_UP | MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT,
+ mac: KeyCode.ARROW_UP | MetaKeys.ALT | MetaKeys.SHIFT,
+ staticParameters: { direction: Direction.UP, granularity: 'paragraph' },
+ });
+ expect(MoveSelectionParagraphDownShortcut).toMatchObject({
+ id: MoveSelectionOperation.id,
+ binding: KeyCode.ARROW_DOWN | MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT,
+ mac: KeyCode.ARROW_DOWN | MetaKeys.ALT | MetaKeys.SHIFT,
+ staticParameters: { direction: Direction.DOWN, granularity: 'paragraph' },
+ });
+ });
});
diff --git a/packages/docs-ui/src/shortcuts/cursor.shortcut.ts b/packages/docs-ui/src/shortcuts/cursor.shortcut.ts
index e6b6a74486..98e84bceb5 100644
--- a/packages/docs-ui/src/shortcuts/cursor.shortcut.ts
+++ b/packages/docs-ui/src/shortcuts/cursor.shortcut.ts
@@ -23,7 +23,7 @@ import { whenDocAndEditorFocused } from './utils';
function moveCursorShortcut(
direction: Direction,
- granularity: 'word' | 'line' | 'document',
+ granularity: 'word' | 'line' | 'paragraph' | 'document',
binding: number,
mac: number = binding,
win: number = binding,
@@ -45,7 +45,7 @@ function moveCursorShortcut(
function moveSelectionShortcut(
direction: Direction,
- granularity: 'word' | 'line' | 'document',
+ granularity: 'word' | 'line' | 'paragraph' | 'document',
binding: number,
mac: number = binding,
win: number = binding,
@@ -221,6 +221,34 @@ export const MoveSelectionWordRightShortcut = moveSelectionShortcut(
KeyCode.ARROW_RIGHT | MetaKeys.ALT | MetaKeys.SHIFT
);
+export const MoveCursorParagraphUpShortcut = moveCursorShortcut(
+ Direction.UP,
+ 'paragraph',
+ KeyCode.ARROW_UP | MetaKeys.CTRL_COMMAND,
+ KeyCode.ARROW_UP | MetaKeys.ALT
+);
+
+export const MoveCursorParagraphDownShortcut = moveCursorShortcut(
+ Direction.DOWN,
+ 'paragraph',
+ KeyCode.ARROW_DOWN | MetaKeys.CTRL_COMMAND,
+ KeyCode.ARROW_DOWN | MetaKeys.ALT
+);
+
+export const MoveSelectionParagraphUpShortcut = moveSelectionShortcut(
+ Direction.UP,
+ 'paragraph',
+ KeyCode.ARROW_UP | MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT,
+ KeyCode.ARROW_UP | MetaKeys.ALT | MetaKeys.SHIFT
+);
+
+export const MoveSelectionParagraphDownShortcut = moveSelectionShortcut(
+ Direction.DOWN,
+ 'paragraph',
+ KeyCode.ARROW_DOWN | MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT,
+ KeyCode.ARROW_DOWN | MetaKeys.ALT | MetaKeys.SHIFT
+);
+
export const SelectAllShortcut: IShortcutItem = {
id: DocSelectAllCommand.id,
binding: KeyCode.A | MetaKeys.CTRL_COMMAND,