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(doc): arrow key in doc (#391)

Ran Luo398ea5ebf08a
diff --git a/packages/base-docs/src/Controller/move-cursor.controller.ts b/packages/base-docs/src/Controller/move-cursor.controller.ts
index 8c0fb5aa16..3def382620 100644
--- a/packages/base-docs/src/Controller/move-cursor.controller.ts
+++ b/packages/base-docs/src/Controller/move-cursor.controller.ts
@@ -5,14 +5,13 @@ import {
INodePosition,
INodeSearch,
IRenderManagerService,
- isFirstSpan,
- isPlaceholderOrSpace,
ITextSelectionRenderManager,
NodePositionConvertToCursor,
} from '@univerjs/base-render';
import {
Direction,
Disposable,
+ getTextIndexByCursor,
ICommandInfo,
ICommandService,
IUniverInstanceService,
@@ -71,6 +70,7 @@ export class MoveCursorController extends Disposable {
private _moveCursorFunction(direction: Direction) {
const activeRange = this._textSelectionRenderManager.getActiveRange();
+ const allRanges = this._textSelectionRenderManager.getRanges();
const activeSelection = this._textSelectionRenderManager.getActiveTextSelection();
@@ -83,103 +83,64 @@ export class MoveCursorController extends Disposable {
}
const startNodePosition = activeSelection.getStart();
+
const preSpan = skeleton.findSpanByPosition(startNodePosition);
const documentOffsetConfig = docObject.document.getOffsetConfig();
- const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, segmentId, style } = activeRange;
+ const { cursorStart, cursorEnd, isEndBack, isStartBack, style } = activeRange;
- let cursor = cursorStart;
+ if (direction === Direction.LEFT || direction === Direction.RIGHT) {
+ let cursor;
- if (direction === Direction.DOWN || direction === Direction.UP) {
- const newPos = this._getTopOrBottomPosition(skeleton, preSpan, direction === Direction.DOWN);
- if (newPos == null) {
- return;
- }
+ if (!activeRange.isCollapse || allRanges.length > 1) {
+ let min = Infinity;
+ let max = -Infinity;
- const newActiveRange = new NodePositionConvertToCursor(documentOffsetConfig, skeleton).getRangePointData(
- newPos,
- newPos
- ).cursorList[0];
-
- // move selection
- this._textSelectionManagerService.replace([
- {
- ...newActiveRange,
- style,
- },
- ]);
-
- // const selectionRemain = documents.remainActiveSelection() as TextSelection | undefined;
- // if (selectionRemain == null) {
- // return;
- // }
-
- // this._syncSelection(documents as Documents, selectionRemain, newPos, true);
- } else if (direction === Direction.LEFT) {
- let span: Nullable<IDocumentSkeletonSpan>;
- let isBack = false;
- if (isFirstSpan(preSpan)) {
- span = skeleton.findNodeByCharIndex(cursor);
-
- if (preSpan === span) {
- isBack = true;
+ for (const range of allRanges) {
+ min = Math.min(min, getTextIndexByCursor(range!.cursorStart, range!.isStartBack) + 1);
+ max = Math.max(max, getTextIndexByCursor(range!.cursorEnd, range!.isEndBack) + 1);
}
- while (isPlaceholderOrSpace(span)) {
- span = skeleton.findNodeByCharIndex(--cursor);
- }
+ cursor = direction === Direction.LEFT ? min : max;
} else {
- span = skeleton.findNodeByCharIndex(--cursor);
+ if (direction === Direction.LEFT) {
+ cursor = Math.max(0, getTextIndexByCursor(cursorStart, isStartBack));
+ } else {
+ const dataStreamLength = skeleton.getModel().getBodyModel().getBody().dataStream.length ?? Infinity;
+ // -1 because the length of the string will be 1 larger than the index, and the reason for subtracting another 1 is because it ends in \n
+ cursor = Math.min(dataStreamLength - 2, getTextIndexByCursor(cursorEnd, isEndBack) + 2);
+ }
}
- // move selection
this._textSelectionManagerService.replace([
{
cursorStart: cursor,
cursorEnd: cursor,
isCollapse: true,
- isEndBack: isBack,
- isStartBack: isBack,
+ isEndBack: true,
+ isStartBack: true,
style,
},
]);
-
- // const selectionRemain = documents.remainActiveSelection() as TextSelection | undefined;
- // this._adjustSelection(documents, selectionRemain, span, isBack, true);
} else {
- if (isStartBack === true) {
- cursor -= 1;
- }
-
- let span = skeleton.findNodeByCharIndex(++cursor);
-
- const originCursor = cursor;
-
- while (isPlaceholderOrSpace(span)) {
- span = skeleton.findNodeByCharIndex(++cursor);
+ const newPos = this._getTopOrBottomPosition(skeleton, preSpan, direction === Direction.DOWN);
+ if (newPos == null) {
+ return;
}
- let isBack = false;
- if (isFirstSpan(span) && preSpan !== span) {
- isBack = true;
- } else {
- cursor = originCursor;
- }
+ const newActiveRange = new NodePositionConvertToCursor(documentOffsetConfig, skeleton).getRangePointData(
+ newPos,
+ newPos
+ ).cursorList[0];
// move selection
this._textSelectionManagerService.replace([
{
- cursorStart: cursor,
- cursorEnd: cursor,
- isCollapse: true,
- isEndBack: isBack,
- isStartBack: isBack,
+ ...newActiveRange,
style,
},
]);
- // const selectionRemain = documents.remainActiveSelection() as TextSelection | undefined;
- // this._adjustSelection(documents, selectionRemain, span, isBack, true);
}
}
diff --git a/packages/base-docs/src/Controller/text-selection.controller.ts b/packages/base-docs/src/Controller/text-selection.controller.ts
index 68f7a34f27..7af7423e05 100644
--- a/packages/base-docs/src/Controller/text-selection.controller.ts
+++ b/packages/base-docs/src/Controller/text-selection.controller.ts
@@ -119,6 +119,7 @@ export class TextSelectionController extends Disposable {
this._downObserver = document?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
this._textSelectionRenderManager.eventTrigger(evt, document.getOffsetConfig(), viewportMain);
+
if (evt.button !== 2) {
state.stopPropagation();
}
diff --git a/packages/base-render/src/Basics/Position.ts b/packages/base-render/src/Basics/Position.ts
index 3fd79987df..079ecc09c2 100644
--- a/packages/base-render/src/Basics/Position.ts
+++ b/packages/base-render/src/Basics/Position.ts
@@ -5,15 +5,16 @@ export function getOffsetRectForDom(ele: HTMLElement) {
const box = ele.getBoundingClientRect();
const body = document.body;
const docElem = document.documentElement;
- //获取页面的scrollTop,scrollLeft(兼容性写法)
+ // 获取页面的 scrollTop,scrollLeft(兼容性写法)
const scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
const scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
const clientTop = docElem.clientTop || body.clientTop;
const clientLeft = docElem.clientLeft || body.clientLeft;
const top = box.top + scrollTop - clientTop;
const left = box.left + scrollLeft - clientLeft;
+
return {
- //Math.round 兼容火狐浏览器bug
+ // Math.round 兼容火狐浏览器 bug
top,
left,
};
diff --git a/packages/base-render/src/Basics/Tools.ts b/packages/base-render/src/Basics/Tools.ts
index 6dca32d9d4..ddc7a1daa2 100644
--- a/packages/base-render/src/Basics/Tools.ts
+++ b/packages/base-render/src/Basics/Tools.ts
@@ -40,6 +40,7 @@ export const getColor = (RgbArray: number[], opacity?: number): string => {
if (opacity != null) {
return `${RGBA_PAREN + RgbArray.join(',')},${opacity})`;
}
+
return `${RGB_PAREN + RgbArray.join(',')})`;
};
diff --git a/packages/base-render/src/Component/Docs/Common/TextSelection.ts b/packages/base-render/src/Component/Docs/Common/TextSelection.ts
index e49a5843b2..da54bdbd85 100644
--- a/packages/base-render/src/Component/Docs/Common/TextSelection.ts
+++ b/packages/base-render/src/Component/Docs/Common/TextSelection.ts
@@ -26,6 +26,8 @@ const TEXT_RANGE_KEY_PREFIX = '__TestSelectionRange__';
const TEXT_ANCHOR_KEY_PREFIX = '__TestSelectionAnchor__';
+const ID_LENGTH = 6;
+
export function cursorConvertToTextSelection(
scene: Scene,
range: ITextSelectionRangeWithStyle,
@@ -43,6 +45,7 @@ export function cursorConvertToTextSelection(
const startNode = docSkeleton.findNodePositionByCharIndex(cursorStart, isStartBack);
let endNode;
+
if (isCollapse !== true) {
endNode = docSkeleton.findNodePositionByCharIndex(cursorEnd, isEndBack);
}
@@ -171,7 +174,6 @@ export class TextSelection {
refresh(documentOffsetConfig: IDocumentOffsetConfig, docSkeleton: DocumentSkeleton) {
const start = this.startNodePosition;
-
const end = this.endNodePosition;
this._anchorShape?.hide();
@@ -183,20 +185,21 @@ export class TextSelection {
const { docsLeft, docsTop } = documentOffsetConfig;
- const convert = new NodePositionConvertToCursor(documentOffsetConfig, docSkeleton);
+ const convertor = new NodePositionConvertToCursor(documentOffsetConfig, docSkeleton);
if (this.isCollapsed()) {
- const data = convert.getRangePointData(start, start);
- const { pointGroup, cursorList } = data;
+ const { pointGroup, cursorList } = convertor.getRangePointData(start, start);
+
this._setRangeList(cursorList);
- pointGroup.length > 0 && this._createAndUpdateAnchor(pointGroup, docsLeft, docsTop);
+ pointGroup.length > 0 && this._createOrUpdateAnchor(pointGroup, docsLeft, docsTop);
+
return;
}
- const data = convert.getRangePointData(start, end);
- const { pointGroup, cursorList } = data;
+ const { pointGroup, cursorList } = convertor.getRangePointData(start, end);
+
this._setRangeList(cursorList);
- pointGroup.length > 0 && this._createAndUpdateRange(pointGroup, docsLeft, docsTop);
+ pointGroup.length > 0 && this._createOrUpdateRange(pointGroup, docsLeft, docsTop);
}
getStart() {
@@ -254,17 +257,19 @@ export class TextSelection {
return true;
}
- private _createAndUpdateRange(pointsGroup: IPoint[][], left: number, top: number) {
+ private _createOrUpdateRange(pointsGroup: IPoint[][], left: number, top: number) {
if (this._rangeShape) {
this._rangeShape.translate(left, top);
this._rangeShape.updatePointGroup(pointsGroup);
this._rangeShape.show();
+
return;
}
- const polygon = new RegularPolygon(TEXT_RANGE_KEY_PREFIX + Tools.generateRandomId(6), {
+ const OPACITY = 0.2;
+ const polygon = new RegularPolygon(TEXT_RANGE_KEY_PREFIX + Tools.generateRandomId(ID_LENGTH), {
pointsGroup,
- fill: this._style?.fill || getColor(COLORS.black, 0.2),
+ fill: this._style?.fill || getColor(COLORS.black, OPACITY),
left,
top,
evented: false,
@@ -293,16 +298,18 @@ export class TextSelection {
};
}
- private _createAndUpdateAnchor(pointsGroup: IPoint[][], docsLeft: number, docsTop: number) {
+ private _createOrUpdateAnchor(pointsGroup: IPoint[][], docsLeft: number, docsTop: number) {
const bounding = this._getAnchorBounding(pointsGroup);
- const { left, top, width, height } = bounding;
+ const { left, top, height } = bounding;
+
if (this._anchorShape) {
this._anchorShape.transformByState({ left: left + docsLeft, top: top + docsTop, height });
this._anchorShape.show();
+
return;
}
- const anchor = new Rect(TEXT_ANCHOR_KEY_PREFIX + Tools.generateRandomId(6), {
+ const anchor = new Rect(TEXT_ANCHOR_KEY_PREFIX + Tools.generateRandomId(ID_LENGTH), {
left: left + docsLeft,
top: top + docsTop,
height,
diff --git a/packages/base-render/src/Component/Docs/text-selection-render-manager.ts b/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
index eab06f065d..b1a066fee6 100644
--- a/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
+++ b/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
@@ -252,6 +252,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
getActiveTextSelection() {
const list = this._textSelectionList;
+
for (const textSelection of list) {
if (textSelection.isActive()) {
return textSelection;
@@ -267,14 +268,17 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
if (textSelection == null) {
return;
}
+
this._addTextSelection(textSelection);
}
+ // @jocs, what's the meaning of this method? and it is not being used anywhere
remain() {
const activeSelection = this.getActiveTextSelection();
if (activeSelection == null) {
return;
}
+
const index = this._textSelectionList.indexOf(activeSelection);
return this._textSelectionList.splice(index, 1)[0];
@@ -292,9 +296,11 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
return this.getTextSelectionList()
.map((textSelection) => {
const range = textSelection.getRange();
+
if (range == null) {
return;
}
+
return {
...range,
segmentId: this._currentSegmentId,
@@ -321,14 +327,12 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
activate(x: number, y: number) {
this._container.style.left = `${x}px`;
this._container.style.top = `${y}px`;
- this._container.style.zIndex = `1000`;
+ this._container.style.zIndex = '1000';
this._cursor.style.animation = 'univer_cursor_blinkStyle 1s steps(1) infinite';
this._cursor.style.display = 'revert';
- setTimeout(() => {
- this.focus();
- }, 0);
+ requestAnimationFrame(() => this.focus());
}
focus(): void {
@@ -364,6 +368,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
// this._attachSelectionEvent(this._documents);
}
+ // Handle pointer down.
eventTrigger(
evt: IPointerEvent | IMouseEvent,
documentOffsetConfig: IDocumentOffsetConfig,
@@ -417,6 +422,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
if (evt.ctrlKey || this._isEmptyTextSelection()) {
const newTextSelection = new TextSelection(scene, position);
+
this._addTextSelection(newTextSelection);
} else {
this._updateTextSelection(position);
@@ -443,13 +449,17 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
scene.setCursor(CURSOR_TYPE.TEXT);
+
if (Math.sqrt((moveOffsetX - preMoveOffsetX) ** 2 + (moveOffsetY - preMoveOffsetY) ** 2) < 3) {
return;
}
+
this._moving(moveOffsetX, moveOffsetY, scrollTimer);
+
scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {
this._moving(moveOffsetX, moveOffsetY, scrollTimer);
});
+
preMoveOffsetX = moveOffsetX;
preMoveOffsetY = moveOffsetY;
});
@@ -457,6 +467,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
scene.onPointerMoveObserver.remove(this._moveObserver);
scene.onPointerUpObserver.remove(this._upObserver);
+
scene.enableEvent();
this._textSelection$.next(this.getTextSelectionList());
@@ -611,10 +622,10 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
if (position == null) {
return;
}
-
+ const HALF = 0.5;
let isBack = false;
//|| (span.streamType === DataStreamTreeTokenType.PARAGRAPH && isStart)
- if (ratioX < 0.5) {
+ if (ratioX < HALF) {
isBack = true;
}
@@ -627,10 +638,12 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
private _interactTextSelection(activeTextSelection: TextSelection) {
const newTextSelection: TextSelection[] = [];
let hasIntersection = false;
+
this._textSelectionList.forEach((textSelection) => {
if (textSelection === activeTextSelection) {
return true;
}
+
if (!activeTextSelection.isIntersection(textSelection)) {
newTextSelection.push(textSelection);
} else {
@@ -642,6 +655,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
if (!hasIntersection) {
return;
}
+
newTextSelection.push(activeTextSelection);
this._textSelectionList = newTextSelection;
}
diff --git a/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts b/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts
index bb0a4c12a3..5a3db21252 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts
@@ -46,7 +46,7 @@ export class BorderAuxiliary extends SheetExtension {
const scale = this._getScale(parentScale);
ctx.beginPath();
ctx.lineWidth = getLineWith(1) / scale;
- ctx.strokeStyle = getColor([212, 212, 212])!;
+ ctx.strokeStyle = getColor([212, 212, 212]);
const width = fixLineWidthByScale(columnTotalWidth, scale);
const height = fixLineWidthByScale(rowTotalHeight, scale);
const columnWidthAccumulationLength = columnWidthAccumulation.length;
diff --git a/packages/base-render/src/ScrollTimer.ts b/packages/base-render/src/ScrollTimer.ts
index 721549c751..02825c601a 100644
--- a/packages/base-render/src/ScrollTimer.ts
+++ b/packages/base-render/src/ScrollTimer.ts
@@ -54,7 +54,7 @@ export class ScrollTimer {
this._runRenderLoop();
}
- _scroll(viewport: Nullable<any>) {
+ private _scroll(viewport: Nullable<any>) {
const topBounding = viewport?.top || 0;
const bottomBounding = topBounding + (viewport?.height || 0);
const leftBounding = viewport?.left || 0;
diff --git a/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_SIMPLE.ts b/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_SIMPLE.ts
new file mode 100644
index 0000000000..2c0f316b4c
--- /dev/null
+++ b/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_SIMPLE.ts
@@ -0,0 +1,19 @@
+import { IDocumentData } from '@univerjs/core';
+
+export const DEFAULT_DOCUMENT_DATA_SIMPLE: IDocumentData = {
+ id: 'd',
+ body: {
+ dataStream:
+ 'What’s New in the 2022 Gartner Hype Cycle for Emerging Technologies\rEmerging technologies for 2022 fit into three main themes: evolving/expanding immersive experiences\r\n',
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+};
diff --git a/packages/common-plugin-data/src/Docs/index.ts b/packages/common-plugin-data/src/Docs/index.ts
index 5ec184cfe4..f5fb951a21 100644
--- a/packages/common-plugin-data/src/Docs/index.ts
+++ b/packages/common-plugin-data/src/Docs/index.ts
@@ -1,4 +1,5 @@
// @index('./*.ts', f => `export * from '${f.path}'`)
export * from './DEFAULT_DOCUMENT_DATA';
export * from './DEFAULT_DOCUMENT_DATA_EN';
+export * from './DEFAULT_DOCUMENT_DATA_SIMPLE';
// @endindex
diff --git a/packages/core/src/Docs/Domain/DocumentBodyModel.ts b/packages/core/src/Docs/Domain/DocumentBodyModel.ts
index 6e35486254..f7d8a5700a 100644
--- a/packages/core/src/Docs/Domain/DocumentBodyModel.ts
+++ b/packages/core/src/Docs/Domain/DocumentBodyModel.ts
@@ -508,6 +508,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
}
this.children.forEach((n) => traverseTreeNode(n));
+
return pieces.join('');
}
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
index 90c71c9d79..1bf67f47a8 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
@@ -170,6 +170,7 @@ export class StartEditController extends Disposable {
isStartBack: true,
},
]);
+
this._textSelectionRenderManager.activate(HIDDEN_EDITOR_POSITION, HIDDEN_EDITOR_POSITION);
});
}