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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
refactor(doc): refactor text selection (#405)
Ran Luo79fce7d6eb0e
diff --git a/packages/base-docs/src/Controller/delete-left-input.controller.ts b/packages/base-docs/src/Controller/delete-left-input.controller.tsindex bb76e39626..e1f16137b8 100644--- a/packages/base-docs/src/Controller/delete-left-input.controller.ts+++ b/packages/base-docs/src/Controller/delete-left-input.controller.ts@@ -67,17 +67,15 @@ export class DeleteLeftInputController extends Disposable {private _deleteFunction() {const activeRange = this._textSelectionRenderManager.getActiveRange();- const activeSelection = this._textSelectionRenderManager.getActiveTextSelection();-const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;- if (activeRange == null || skeleton == null || activeSelection == null) {+ if (activeRange == null || skeleton == null) {return;}const docsModel = this._currentUniverService.getCurrentUniverDocInstance();- const startNodePosition = activeSelection.getStart();+ const { startOffset, collapsed, segmentId, style, startNodePosition } = activeRange;const preSpan = skeleton.findSpanByPosition(startNodePosition);@@ -85,13 +83,11 @@ export class DeleteLeftInputController extends Disposable {const preIsIndent = isIndentBySpan(preSpan, docsModel.body);- const { cursorStart, isCollapse, segmentId, style } = activeRange;-- let cursor = cursorStart;+ let cursor = startOffset;cursor--;- if (isCollapse === false) {+ if (collapsed === false) {cursor += 1;}@@ -137,19 +133,19 @@ export class DeleteLeftInputController extends Disposable {paragraphs: [{ ...updateParagraph }],},range: {- cursorStart: paragraphIndex + 1,- cursorEnd: paragraphIndex + 1,- isCollapse: true,+ startOffset: paragraphIndex + 1,+ endOffset: paragraphIndex + 1,+ collapsed: true,},segmentId,});} else {- const endNodePosition = activeSelection?.getEnd();+ const { endNodePosition } = activeRange;if (endNodePosition != null) {const endSpan = skeleton.findSpanByPosition(endNodePosition);if (hasListSpan(endSpan) && !isSameLine(preSpan, endSpan)) {- activeRange.cursorEnd -= 1;+ activeRange.endOffset -= 1;}}@@ -169,9 +165,9 @@ export class DeleteLeftInputController extends Disposable {// move selectionthis._textSelectionManagerService.replace([{- cursorStart: cursor,- cursorEnd: cursor,- isCollapse: true,+ startOffset: cursor,+ endOffset: cursor,+ collapsed: true,style,},]);diff --git a/packages/base-docs/src/Controller/ime-input.controller.ts b/packages/base-docs/src/Controller/ime-input.controller.tsindex 9b87782d62..24e6fbaed1 100644--- a/packages/base-docs/src/Controller/ime-input.controller.ts+++ b/packages/base-docs/src/Controller/ime-input.controller.ts@@ -1,8 +1,4 @@-import {- IRenderManagerService,- ITextSelectionRangeWithStyle,- ITextSelectionRenderManager,-} from '@univerjs/base-render';+import { IRenderManagerService, ITextRangeWithStyle, ITextSelectionRenderManager } from '@univerjs/base-render';import {Disposable,ICommandService,@@ -23,7 +19,7 @@ import { TextSelectionManagerService } from '../services/text-selection-manager.export class IMEInputController extends Disposable {private _previousIMEContent: string = '';- private _previousIMERange: Nullable<ITextSelectionRangeWithStyle>;+ private _previousIMERange: Nullable<ITextRangeWithStyle>;private _onStartSubscription: Nullable<Subscription>;@@ -90,7 +86,7 @@ export class IMEInputController extends Disposable {const { event, activeRange } = config;- const { cursorStart, cursorEnd, segmentId, style } = this._previousIMERange;+ const { startOffset, endOffset, segmentId, style } = this._previousIMERange;if (skeleton == null || activeRange == null) {return;@@ -119,15 +115,15 @@ export class IMEInputController extends Disposable {// move selectionthis._textSelectionManagerService.replace([{- cursorStart: cursorStart + len,- cursorEnd: cursorEnd + len,- isCollapse: true,+ startOffset: startOffset + len,+ endOffset: endOffset + len,+ collapsed: true,style,},]);- if (!this._previousIMERange.isCollapse) {- this._previousIMERange.isCollapse = true;+ if (!this._previousIMERange.collapsed) {+ this._previousIMERange.collapsed = true;}this._previousIMEContent = content;diff --git a/packages/base-docs/src/Controller/inline-format.controller.ts b/packages/base-docs/src/Controller/inline-format.controller.tsindex 8e86942413..86fbd4ad0a 100644--- a/packages/base-docs/src/Controller/inline-format.controller.ts+++ b/packages/base-docs/src/Controller/inline-format.controller.ts@@ -62,7 +62,7 @@ export class InlineFormatController extends Disposable {}private handleInlineFormat(command: ICommandInfo) {- const segmentId = this._textSelectionRenderManager.getActiveRange()?.segmentId;+ const { segmentId } = this._textSelectionRenderManager.getActiveRange() ?? {};if (segmentId == null) {return;diff --git a/packages/base-docs/src/Controller/line-break-input.controller.ts b/packages/base-docs/src/Controller/line-break-input.controller.tsindex 4228aa161a..3636e873df 100644--- a/packages/base-docs/src/Controller/line-break-input.controller.ts+++ b/packages/base-docs/src/Controller/line-break-input.controller.ts@@ -87,7 +87,7 @@ export class LineBreakInputController extends Disposable {const docsModel = this._currentUniverService.getCurrentUniverDocInstance();const unitId = docsModel.getUnitId();- const { cursorStart, segmentId, style } = activeRange;+ const { startOffset, segmentId, style } = activeRange;// split paragraphthis._commandService.executeCommand(InsertCommand.id, {@@ -105,9 +105,9 @@ export class LineBreakInputController extends Disposable {// move selectionthis._textSelectionManagerService.replace([{- cursorStart: cursorStart + 1,- cursorEnd: cursorStart + 1,- isCollapse: true,+ startOffset: startOffset + 1,+ endOffset: startOffset + 1,+ collapsed: true,style,},]);diff --git a/packages/base-docs/src/Controller/move-cursor.controller.ts b/packages/base-docs/src/Controller/move-cursor.controller.tsindex c841e0a4d7..5ab7ac96a4 100644--- a/packages/base-docs/src/Controller/move-cursor.controller.ts+++ b/packages/base-docs/src/Controller/move-cursor.controller.ts@@ -69,54 +69,50 @@ export class MoveCursorController extends Disposable {private _moveCursorFunction(direction: Direction) {const activeRange = this._textSelectionRenderManager.getActiveRange();- const allRanges = this._textSelectionRenderManager.getRanges();-- const activeSelection = this._textSelectionRenderManager.getActiveTextSelection();+ const allRanges = this._textSelectionRenderManager.getAllTextRanges();const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;const docObject = this._getDocObject();- if (activeRange == null || skeleton == null || activeSelection == null || docObject == null) {+ if (activeRange == null || skeleton == null || docObject == null) {return;}- const startNodePosition = activeSelection.getStart();+ const { startOffset, endOffset, style, startNodePosition } = activeRange;const preSpan = skeleton.findSpanByPosition(startNodePosition);const documentOffsetConfig = docObject.document.getOffsetConfig();- const { cursorStart, cursorEnd, style } = activeRange;-if (direction === Direction.LEFT || direction === Direction.RIGHT) {let cursor;- if (!activeRange.isCollapse || allRanges.length > 1) {+ if (!activeRange.collapsed || allRanges.length > 1) {let min = Infinity;let max = -Infinity;for (const range of allRanges) {- min = Math.min(min, range!.cursorStart);- max = Math.max(max, range!.cursorEnd);+ min = Math.min(min, range.startOffset!);+ max = Math.max(max, range.endOffset!);}cursor = direction === Direction.LEFT ? min : max;} else {if (direction === Direction.LEFT) {- cursor = Math.max(0, cursorStart - 1);+ cursor = Math.max(0, startOffset - 1);} 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, cursorEnd + 1);+ cursor = Math.min(dataStreamLength - 2, endOffset + 1);}}this._textSelectionManagerService.replace([{- cursorStart: cursor,- cursorEnd: cursor,- isCollapse: true,+ startOffset: cursor,+ endOffset: cursor,+ collapsed: true,style,},]);@@ -151,7 +147,7 @@ export class MoveCursorController extends Disposable {if (selectionRange == null) {return;}- const referenceSpan = docSkeleton.findNodeByCharIndex(selectionRange.cursorStart);+ const referenceSpan = docSkeleton.findNodeByCharIndex(selectionRange.startOffset);if (referenceSpan == null || span == null) {return;}diff --git a/packages/base-docs/src/Controller/normal-input.controller.ts b/packages/base-docs/src/Controller/normal-input.controller.tsindex f1f4f5cac8..fdfe943df7 100644--- a/packages/base-docs/src/Controller/normal-input.controller.ts+++ b/packages/base-docs/src/Controller/normal-input.controller.ts@@ -64,7 +64,7 @@ export class NormalInputController extends Disposable {return;}- const { cursorStart, segmentId, style } = activeRange;+ const { startOffset, segmentId, style } = activeRange;await this._commandService.executeCommand(InsertCommand.id, {unitId: documentModel.getUnitId(),@@ -82,9 +82,9 @@ export class NormalInputController extends Disposable {// move selectionthis._textSelectionManagerService.replace([{- cursorStart: cursorStart + len,- cursorEnd: cursorStart + len,- isCollapse: true,+ startOffset: startOffset + len,+ endOffset: startOffset + len,+ collapsed: true,style,},]);diff --git a/packages/base-docs/src/Controller/text-selection.controller.ts b/packages/base-docs/src/Controller/text-selection.controller.tsindex 7af7423e05..47f30ed259 100644--- a/packages/base-docs/src/Controller/text-selection.controller.ts+++ b/packages/base-docs/src/Controller/text-selection.controller.ts@@ -1,12 +1,12 @@import {CURSOR_TYPE,- cursorConvertToTextSelection,+ cursorConvertToTextRange,Documents,getOneTextSelectionRange,IMouseEvent,IPointerEvent,IRenderManagerService,- ITextSelectionRangeWithStyle,+ ITextRangeWithStyle,ITextSelectionRenderManager,NodePositionConvertToCursor,} from '@univerjs/base-render';@@ -129,7 +129,9 @@ export class TextSelectionController extends Disposable {private _onChangeListener() {this._textSelectionManagerService.textSelectionInfo$.subscribe((param) => {const unitId = this._textSelectionManagerService.getCurrentSelection()?.unitId;+ // Remove all textRanges.this._textSelectionRenderManager.reset();+if (param == null || unitId == null) {return;}@@ -145,7 +147,7 @@ export class TextSelectionController extends Disposable {const { scene, document } = currentRender;for (const selectionWithStyle of param) {- const textSelection = cursorConvertToTextSelection(+ const textSelection = cursorConvertToTextRange(scene,selectionWithStyle,docSkeleton,@@ -161,7 +163,7 @@ export class TextSelectionController extends Disposable {}private _userActionSyncListener() {- this._textSelectionRenderManager.textSelection$.subscribe((textSelections) => {+ this._textSelectionRenderManager.textSelection$.subscribe((textRanges) => {const docsObject = this._docSkeletonManagerService.getCurrent();if (docsObject == null) {@@ -181,17 +183,20 @@ export class TextSelectionController extends Disposable {this._commandService.executeCommand(SetTextSelectionsOperation.id, {unitId,pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,- ranges: textSelections- .map((textSelection) => {- let { endNodePosition } = textSelection;- const { startNodePosition } = textSelection;- if (endNodePosition == null) {- endNodePosition = startNodePosition;+ ranges: textRanges+ .map((textRange) => {+ let { focusNodePosition } = textRange;+ const { anchorNodePosition } = textRange;++ if (focusNodePosition == null) {+ focusNodePosition = anchorNodePosition;}- const rangeList = convert.getRangePointData(startNodePosition, endNodePosition).cursorList;++ const rangeList = convert.getRangePointData(anchorNodePosition, focusNodePosition).cursorList;+return getOneTextSelectionRange(rangeList);})- .filter((x) => x !== null) as ITextSelectionRangeWithStyle[],+ .filter((x) => x !== null) as ITextRangeWithStyle[],});});}diff --git a/packages/base-docs/src/commands/commands/__tests__/inline-format.command.spec.ts b/packages/base-docs/src/commands/commands/__tests__/inline-format.command.spec.tsindex b65b838b2d..4c7e04c95e 100644--- a/packages/base-docs/src/commands/commands/__tests__/inline-format.command.spec.ts+++ b/packages/base-docs/src/commands/commands/__tests__/inline-format.command.spec.ts@@ -68,9 +68,9 @@ describe('Test inline format commands', () => {selectionManager.add([{- cursorStart: 0,- cursorEnd: 5,- isCollapse: false,+ startOffset: 0,+ endOffset: 5,+ collapsed: false,segmentId: '',},]);diff --git a/packages/base-docs/src/commands/commands/core-editing.command.ts b/packages/base-docs/src/commands/commands/core-editing.command.tsindex f6ceb4918b..59f8f9e70f 100644--- a/packages/base-docs/src/commands/commands/core-editing.command.ts+++ b/packages/base-docs/src/commands/commands/core-editing.command.ts@@ -6,7 +6,7 @@ import {ICommandService,IDocumentBody,IDocumentData,- ITextSelectionRange,+ ITextRange,IUndoRedoService,IUniverInstanceService,UpdateDocsAttributeType,@@ -34,7 +34,7 @@ export const BreakLineCommand: ICommand = {export interface IInsertCommandParams {unitId: string;body: IDocumentBody;- range: ITextSelectionRange;+ range: ITextRange;segmentId?: string;}@@ -49,7 +49,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {const commandService = accessor.get(ICommandService);const { range, segmentId, body, unitId } = params;- const { cursorStart, isCollapse } = range;+ const { startOffset, collapsed } = range;const doMutation: ICommandInfo<IRichTextEditingMutationParams> = {id: RichTextEditingMutation.id,@@ -59,10 +59,10 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {},};- if (isCollapse) {+ if (collapsed) {doMutation.params!.mutations.push({t: 'r',- len: cursorStart,+ len: startOffset,segmentId,});} else {@@ -103,7 +103,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {export interface IDeleteCommandParams {unitId: string;- range: ITextSelectionRange;+ range: ITextRange;segmentId?: string;}@@ -156,7 +156,7 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {export interface IUpdateCommandParams {unitId: string;updateBody: IDocumentBody;- range: ITextSelectionRange;+ range: ITextRange;coverType: UpdateDocsAttributeType;segmentId?: string;}@@ -184,18 +184,18 @@ export const UpdateCommand: ICommand<IUpdateCommandParams> = {},};- const { cursorStart, cursorEnd } = range;+ const { startOffset, endOffset } = range;doMutation.params!.mutations.push({t: 'r',- len: cursorStart,+ len: startOffset,segmentId,});doMutation.params!.mutations.push({t: 'r',body: updateBody,- len: cursorEnd - cursorStart,+ len: endOffset - startOffset,segmentId,coverType,});@@ -228,7 +228,7 @@ export const UpdateCommand: ICommand<IUpdateCommandParams> = {export interface IIMEInputCommandParams {newText: string;oldTextLen: number;- range: ITextSelectionRange;+ range: ITextRange;segmentId?: string;unitId: string;}@@ -248,10 +248,10 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {},};- if (range.isCollapse) {+ if (range.collapsed) {doMutation.params!.mutations.push({t: 'r',- len: range.cursorStart,+ len: range.startOffset,segmentId,});} else {@@ -317,14 +317,14 @@ export const CoverCommand: ICommand<ICoverCommandParams> = {};function getRetainAndDeleteFromReplace(- range: ITextSelectionRange,+ range: ITextRange,segmentId?: string): Array<IRetainMutationParams | IDeleteMutationParams> {- const { cursorStart, cursorEnd, isCollapse } = range;+ const { startOffset, endOffset, collapsed } = range;const dos: Array<IRetainMutationParams | IDeleteMutationParams> = [];- const textStart = cursorStart + (isCollapse ? -1 : 0);- const textEnd = cursorEnd - 1;+ const textStart = startOffset + (collapsed ? -1 : 0);+ const textEnd = endOffset - 1;if (textStart > 0) {dos.push({diff --git a/packages/base-docs/src/commands/commands/inline-format.command.ts b/packages/base-docs/src/commands/commands/inline-format.command.tsindex 2a4f98d410..9fa678c733 100644--- a/packages/base-docs/src/commands/commands/inline-format.command.ts+++ b/packages/base-docs/src/commands/commands/inline-format.command.ts@@ -1,4 +1,4 @@-import { ITextSelectionRangeWithStyle } from '@univerjs/base-render';+import { ITextRangeWithStyle } from '@univerjs/base-render';import {BooleanNumber,CommandType,@@ -141,14 +141,14 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {memoryCursor.reset();for (const selection of selections) {- const { cursorStart, cursorEnd } = selection;+ const { startOffset, endOffset } = selection;const body: IDocumentBody = {dataStream: '',textRuns: [{st: 0,- ed: cursorEnd - cursorStart,+ ed: endOffset - startOffset,ts: {[COMMAND_ID_TO_FORMAT_KEY_MAP[preCommandId]]: formatValue,},@@ -156,7 +156,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {],};- const len = cursorStart - memoryCursor.cursor;+ const len = startOffset - memoryCursor.cursor;if (len !== 0) {doMutation.params!.mutations.push({t: 'r',@@ -168,12 +168,12 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {doMutation.params!.mutations.push({t: 'r',body,- len: cursorEnd - cursorStart,+ len: endOffset - startOffset,segmentId,});memoryCursor.reset();- memoryCursor.moveCursor(cursorEnd);+ memoryCursor.moveCursor(endOffset);}const result = commandService.syncExecuteCommand<@@ -211,20 +211,20 @@ function isTextDecoration(value: unknown | ITextDecoration): value is ITextDecorfunction getReverseFormatValueInSelection(textRuns: ITextRun[],key: keyof IStyleBase,- selections: ITextSelectionRangeWithStyle[]+ selections: ITextRangeWithStyle[]): BooleanNumber | ITextDecoration {let ti = 0;let si = 0;while (ti !== textRuns.length && si !== selections.length) {- const { cursorStart, cursorEnd } = selections[si];+ const { startOffset, endOffset } = selections[si];// TODO: @jocs handle sid in textRunconst { st, ed, ts } = textRuns[ti];- if (cursorEnd <= st) {+ if (endOffset <= st) {si++;- } else if (ed <= cursorStart) {+ } else if (ed <= startOffset) {ti++;} else {if (ts?.[key] == null) {diff --git a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts b/packages/base-docs/src/commands/mutations/core-editing.mutation.tsindex 452361ec6c..023e9afe93 100644--- a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts+++ b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts@@ -71,6 +71,8 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,memoryCursor.reset();+ console.log(JSON.stringify(mutations, null, 2));+mutations.forEach((mutation) => {// FIXME: @jocs Since UpdateAttributeApply modifies the mutation(used in undo/redo),// so make a deep copy here, does UpdateAttributeApply need todiff --git a/packages/base-docs/src/commands/operations/text-selection.operation.ts b/packages/base-docs/src/commands/operations/text-selection.operation.tsindex bd4107833b..63aac49cc2 100644--- a/packages/base-docs/src/commands/operations/text-selection.operation.ts+++ b/packages/base-docs/src/commands/operations/text-selection.operation.ts@@ -1,6 +1,6 @@// This file provide operations to change selection of sheets.-import { ITextSelectionRangeWithStyle } from '@univerjs/base-render';+import { ITextRangeWithStyle } from '@univerjs/base-render';import { CommandType, IOperation } from '@univerjs/core';import { TextSelectionManagerService } from '../../services/text-selection-manager.service';@@ -8,7 +8,7 @@ import { TextSelectionManagerService } from '../../services/text-selection-managexport interface ISetTextSelectionsOperationParams {unitId: string;pluginName: string;- ranges: ITextSelectionRangeWithStyle[];+ ranges: ITextRangeWithStyle[];}export const SetTextSelectionsOperation: IOperation<ISetTextSelectionsOperationParams> = {diff --git a/packages/base-docs/src/services/text-selection-manager.service.ts b/packages/base-docs/src/services/text-selection-manager.service.tsindex a1416005ef..5a23ae028a 100644--- a/packages/base-docs/src/services/text-selection-manager.service.ts+++ b/packages/base-docs/src/services/text-selection-manager.service.ts@@ -1,4 +1,4 @@-import { ITextSelectionRangeWithStyle } from '@univerjs/base-render';+import { ITextRangeWithStyle } from '@univerjs/base-render';import { ISelectionCell, Nullable } from '@univerjs/core';import { IDisposable } from '@wendellhu/redi';import { BehaviorSubject } from 'rxjs';@@ -11,11 +11,11 @@ export interface ITextSelectionManagerSearchParam {}export interface ITextSelectionManagerInsertParam extends ITextSelectionManagerSearchParam {- textRanges: ITextSelectionRangeWithStyle[];+ textRanges: ITextRangeWithStyle[];}-//{ [pluginName: string]: { [unitId: string]: ITextSelectionRangeWithStyle[] } }-export type ITextSelectionInfo = Map<string, Map<string, ITextSelectionRangeWithStyle[]>>;+//{ [pluginName: string]: { [unitId: string]: ITextRangeWithStyle[] } }+export type ITextSelectionInfo = Map<string, Map<string, ITextRangeWithStyle[]>>;/*** This service is for selection.@@ -25,7 +25,7 @@ export class TextSelectionManagerService implements IDisposable {private _currentSelection: Nullable<ITextSelectionManagerSearchParam> = null;- private readonly _textSelectionInfo$ = new BehaviorSubject<Nullable<ITextSelectionRangeWithStyle[]>>(null);+ private readonly _textSelectionInfo$ = new BehaviorSubject<Nullable<ITextRangeWithStyle[]>>(null);readonly textSelectionInfo$ = this._textSelectionInfo$.asObservable();@@ -84,28 +84,26 @@ export class TextSelectionManagerService implements IDisposable {return this._textSelectionInfo;}- getTextRangesByParam(- param: Nullable<ITextSelectionManagerSearchParam>- ): Readonly<Nullable<ITextSelectionRangeWithStyle[]>> {+ getTextRangesByParam(param: Nullable<ITextSelectionManagerSearchParam>): Readonly<Nullable<ITextRangeWithStyle[]>> {return this._getTextRanges(param);}- getSelections(): Readonly<Nullable<ITextSelectionRangeWithStyle[]>> {+ getSelections(): Readonly<Nullable<ITextRangeWithStyle[]>> {return this._getTextRanges(this._currentSelection);}- getFirst(): Readonly<Nullable<ITextSelectionRangeWithStyle>> {+ getFirst(): Readonly<Nullable<ITextRangeWithStyle>> {return this._getFirstByParam(this._currentSelection);}- getLast(): Readonly<Nullable<ITextSelectionRangeWithStyle & { primary: ISelectionCell }>> {+ getLast(): Readonly<Nullable<ITextRangeWithStyle & { primary: ISelectionCell }>> {// The last selection position must have a primary.return this._getLastByParam(this._currentSelection) as Readonly<- Nullable<ITextSelectionRangeWithStyle & { primary: ISelectionCell }>+ Nullable<ITextRangeWithStyle & { primary: ISelectionCell }>>;}- add(textRanges: ITextSelectionRangeWithStyle[]) {+ add(textRanges: ITextRangeWithStyle[]) {if (this._currentSelection == null) {return;}@@ -115,7 +113,7 @@ export class TextSelectionManagerService implements IDisposable {});}- replace(textRanges: ITextSelectionRangeWithStyle[]) {+ replace(textRanges: ITextRangeWithStyle[]) {if (this._currentSelection == null) {return;}@@ -126,7 +124,7 @@ export class TextSelectionManagerService implements IDisposable {this.refresh(this._currentSelection);}- replaceWithNoRefresh(textRanges: ITextSelectionRangeWithStyle[]) {+ replaceWithNoRefresh(textRanges: ITextRangeWithStyle[]) {if (this._currentSelection == null) {return;}@@ -169,7 +167,7 @@ export class TextSelectionManagerService implements IDisposable {private _getFirstByParam(param: Nullable<ITextSelectionManagerSearchParam>- ): Readonly<Nullable<ITextSelectionRangeWithStyle>> {+ ): Readonly<Nullable<ITextRangeWithStyle>> {const textRange = this._getTextRanges(param);return textRange?.[0];@@ -177,7 +175,7 @@ export class TextSelectionManagerService implements IDisposable {private _getLastByParam(param: Nullable<ITextSelectionManagerSearchParam>- ): Readonly<Nullable<ITextSelectionRangeWithStyle>> {+ ): Readonly<Nullable<ITextRangeWithStyle>> {const textRange = this._getTextRanges(param);return textRange?.[textRange.length - 1];diff --git a/packages/base-render/src/Basics/index.ts b/packages/base-render/src/Basics/index.tsindex 6458538256..b841cfebc1 100644--- a/packages/base-render/src/Basics/index.ts+++ b/packages/base-render/src/Basics/index.ts@@ -7,8 +7,8 @@ export * from './IEvents';export * from './Interfaces';export * from './Path2';export * from './PerformanceMonitor';+export * from './range';export * from './ScrollXY';-export * from './TextSelection';export * from './Tools';export * from './Transform';export * from './Vector2';diff --git a/packages/base-render/src/Basics/TextSelection.ts b/packages/base-render/src/Basics/range.tssimilarity index 62%rename from packages/base-render/src/Basics/TextSelection.tsrename to packages/base-render/src/Basics/range.tsindex 7184eaac7e..600ec3404b 100644--- a/packages/base-render/src/Basics/TextSelection.ts+++ b/packages/base-render/src/Basics/range.ts@@ -1,4 +1,4 @@-import { ITextSelectionRangeParam } from '@univerjs/core';+import { ITextRangeParam } from '@univerjs/core';export interface ITextSelectionStyle {strokeWidth: number;@@ -14,6 +14,12 @@ export const NORMAL_TEXT_SELECTION_PLUGIN_STYLE: ITextSelectionStyle = {fill: 'rgba(0, 0, 0, 0.2)',};-export interface ITextSelectionRangeWithStyle extends ITextSelectionRangeParam {+export interface ITextRangeWithStyle extends ITextRangeParam {style?: ITextSelectionStyle;}++export enum RANGE_DIRECTION {+ NONE = 'none',+ BACKWARD = 'backward',+ FORWARD = 'forward',+}diff --git a/packages/base-render/src/Component/Docs/Common/TextSelection.ts b/packages/base-render/src/Component/Docs/Common/Range.tssimilarity index 55%rename from packages/base-render/src/Component/Docs/Common/TextSelection.tsrename to packages/base-render/src/Component/Docs/Common/Range.tsindex d2b2f4e75c..b571084040 100644--- a/packages/base-render/src/Component/Docs/Common/TextSelection.ts+++ b/packages/base-render/src/Component/Docs/Common/Range.ts@@ -1,12 +1,13 @@-import { ITextSelectionRange, Nullable, Tools } from '@univerjs/core';+import { ITextRange, Nullable, Tools } from '@univerjs/core';import { COLORS } from '../../../Basics/Const';import { INodePosition } from '../../../Basics/Interfaces';import {- ITextSelectionRangeWithStyle,+ ITextRangeWithStyle,ITextSelectionStyle,NORMAL_TEXT_SELECTION_PLUGIN_STYLE,-} from '../../../Basics/TextSelection';+ RANGE_DIRECTION,+} from '../../../Basics/range';import { getColor } from '../../../Basics/Tools';import { IPoint } from '../../../Basics/Vector2';import { Scene } from '../../../Scene';@@ -17,6 +18,7 @@ import { DocumentSkeleton } from '../DocSkeleton';import { IDocumentOffsetConfig } from '../Document';import {compareNodePosition,+ compareNodePositionLogic,getOneTextSelectionRange,NodePositionConvertToCursor,NodePositionMap,@@ -28,46 +30,108 @@ const TEXT_ANCHOR_KEY_PREFIX = '__TestSelectionAnchor__';const ID_LENGTH = 6;-export function cursorConvertToTextSelection(+export function cursorConvertToTextRange(scene: Scene,- range: ITextSelectionRangeWithStyle,+ range: ITextRangeWithStyle,docSkeleton: DocumentSkeleton,documentOffsetConfig: IDocumentOffsetConfig-): Nullable<TextSelection> {- const { cursorStart, cursorEnd, style = NORMAL_TEXT_SELECTION_PLUGIN_STYLE } = range;+): Nullable<TextRange> {+ const { startOffset, endOffset, style = NORMAL_TEXT_SELECTION_PLUGIN_STYLE } = range;- const startNode = docSkeleton.findNodePositionByCharIndex(cursorStart);- const endNode = cursorStart !== cursorEnd ? docSkeleton.findNodePositionByCharIndex(cursorEnd) : null;+ const anchorNodePosition = docSkeleton.findNodePositionByCharIndex(startOffset);+ const focusNodePosition = startOffset !== endOffset ? docSkeleton.findNodePositionByCharIndex(endOffset) : null;- const textSelection = new TextSelection(scene, startNode, endNode, style);+ const textRange = new TextRange(+ scene,+ documentOffsetConfig,+ docSkeleton,+ anchorNodePosition,+ focusNodePosition,+ style+ );- textSelection.refresh(documentOffsetConfig, docSkeleton);+ textRange.refresh();- return textSelection;+ return textRange;}-export class TextSelection {+export class TextRange {+ // Identifies whether the range is the current one, most of which is the last range.private _current = false;-+ // The rendered range graphic when collapsed is falseprivate _rangeShape: Nullable<RegularPolygon>;-+ // The rendered range graphic when collapsed is trueprivate _anchorShape: Nullable<Rect>;- private _rangeList: ITextSelectionRange[] = [];+ private _cursorList: ITextRange[] = [];constructor(private _scene: ThinScene,- public startNodePosition?: Nullable<INodePosition>,- public endNodePosition?: Nullable<INodePosition>,+ private _documentOffsetConfig: IDocumentOffsetConfig,+ private _docSkeleton: DocumentSkeleton,+ public anchorNodePosition?: Nullable<INodePosition>,+ public focusNodePosition?: Nullable<INodePosition>,private _style: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE) {}- getRange(): Nullable<ITextSelectionRange> {- return getOneTextSelectionRange(this._rangeList);+ // The start position of the range+ get startOffset() {+ const { startOffset } = getOneTextSelectionRange(this._cursorList) ?? {};++ return startOffset;+ }++ // The end position of the range+ get endOffset() {+ const { endOffset } = getOneTextSelectionRange(this._cursorList) ?? {};++ return endOffset;+ }++ get collapsed() {+ const { startOffset, endOffset } = this;++ return startOffset != null && startOffset === endOffset;+ }++ get startNodePosition() {+ if (this.anchorNodePosition == null) {+ return null;+ }++ if (this.focusNodePosition == null) {+ return this.anchorNodePosition;+ }++ const { start } = compareNodePosition(this.anchorNodePosition, this.focusNodePosition);++ return start;+ }++ get endNodePosition() {+ if (this.anchorNodePosition == null) {+ return this.focusNodePosition;+ }++ if (this.focusNodePosition == null) {+ return null;+ }++ const { end } = compareNodePosition(this.anchorNodePosition, this.focusNodePosition);++ return end;}- getRangeList() {- return this._rangeList;+ get direction() {+ const { collapsed, anchorNodePosition, focusNodePosition } = this;++ if (collapsed || anchorNodePosition == null || focusNodePosition == null) {+ return RANGE_DIRECTION.NONE;+ }++ const compare = compareNodePositionLogic(anchorNodePosition, focusNodePosition);++ return compare ? RANGE_DIRECTION.FORWARD : RANGE_DIRECTION.BACKWARD;}getAnchor() {@@ -98,38 +162,6 @@ export class TextSelection {this._current = false;}- isEmpty() {- return this.startNodePosition == null && this.endNodePosition == null;- }-- isCollapsed() {- if (this.startNodePosition != null && this.endNodePosition == null) {- return true;- }-- if (this.isSamePosition()) {- return true;- }-- return false;- }-- isRange() {- const start = this.startNodePosition;-- const end = this.endNodePosition;-- if (start == null || end == null) {- return false;- }-- if (this.isSamePosition()) {- return false;- }-- return true;- }-dispose() {this._rangeShape?.dispose();this._rangeShape = null;@@ -137,100 +169,77 @@ export class TextSelection {this._anchorShape = null;}- isIntersection(textSelection: TextSelection) {- const activeRange = this.getRange();+ isIntersection(compareRange: TextRange) {+ const { startOffset: activeStart, endOffset: activeEnd } = this;+ const { startOffset: compareStart, endOffset: compareEnd } = compareRange;- const compareRange = textSelection.getRange();-- if (compareRange == null || activeRange == null) {+ if (activeStart == null || activeEnd == null || compareStart == null || compareEnd == null) {return false;}- const { cursorStart: activeStart, cursorEnd: activeEnd } = activeRange;- const { cursorStart: compareStart, cursorEnd: compareEnd } = compareRange;-return activeStart <= compareEnd && activeEnd >= compareStart;}- refresh(documentOffsetConfig: IDocumentOffsetConfig, docSkeleton: DocumentSkeleton) {- const start = this.startNodePosition;- const end = this.endNodePosition;+ refresh() {+ const { _documentOffsetConfig, _docSkeleton } = this;+ const anchor = this.anchorNodePosition;+ const focus = this.focusNodePosition;this._anchorShape?.hide();this._rangeShape?.hide();- if (this.isEmpty()) {+ if (this._isEmpty()) {return;}- const { docsLeft, docsTop } = documentOffsetConfig;+ const { docsLeft, docsTop } = _documentOffsetConfig;- const convertor = new NodePositionConvertToCursor(documentOffsetConfig, docSkeleton);+ const convertor = new NodePositionConvertToCursor(_documentOffsetConfig, _docSkeleton);- if (this.isCollapsed()) {- const { pointGroup, cursorList } = convertor.getRangePointData(start, start);+ if (this._isCollapsed()) {+ const { pointGroup, cursorList } = convertor.getRangePointData(anchor, anchor);- this._setRangeList(cursorList);+ this._setCursorList(cursorList);pointGroup.length > 0 && this._createOrUpdateAnchor(pointGroup, docsLeft, docsTop);return;}- const { pointGroup, cursorList } = convertor.getRangePointData(start, end);+ const { pointGroup, cursorList } = convertor.getRangePointData(anchor, focus);++ this._setCursorList(cursorList);- this._setRangeList(cursorList);pointGroup.length > 0 && this._createOrUpdateRange(pointGroup, docsLeft, docsTop);}- getStart() {- if (this.startNodePosition == null) {- return null;- }-- if (this.endNodePosition == null) {- return this.startNodePosition;- }-- const { start } = compareNodePosition(this.startNodePosition, this.endNodePosition);-- return start;+ private _isEmpty() {+ return this.anchorNodePosition == null && this.focusNodePosition == null;}- getEnd() {- if (this.startNodePosition == null) {- return this.endNodePosition;- }+ private _isCollapsed() {+ const anchor = this.anchorNodePosition;+ const focus = this.focusNodePosition;- if (this.endNodePosition == null) {- return null;+ if (anchor != null && focus == null) {+ return true;}- const { end } = compareNodePosition(this.startNodePosition, this.endNodePosition);-- return end;- }-- private isSamePosition() {- const start = this.startNodePosition;-- const end = this.endNodePosition;-- if (start == null || end == null) {+ if (anchor == null || focus == null) {return false;}const keys = Object.keys(NodePositionMap);for (const key of keys) {- const startNodeValue = start[key as keyof INodePosition] as number;- const endNodeValue = end[key as keyof INodePosition] as number;+ const startNodeValue = anchor[key as keyof INodePosition] as number;+ const endNodeValue = focus[key as keyof INodePosition] as number;if (startNodeValue !== endNodeValue) {return false;}}- if (start.isBack !== end.isBack) {+ if (anchor.isBack !== focus.isBack) {return false;}@@ -303,13 +312,11 @@ export class TextSelection {this._scene.addObject(anchor, 2);}- private _setRangeList(rangeList: ITextSelectionRange[]) {- if (rangeList.length === 0) {+ private _setCursorList(cursorList: ITextRange[]) {+ if (cursorList.length === 0) {return;}- // const firstCursor = cursorList[0];-- this._rangeList = rangeList;+ this._cursorList = cursorList;}}diff --git a/packages/base-render/src/Component/Docs/Common/convert-cursor.ts b/packages/base-render/src/Component/Docs/Common/convert-cursor.tsindex 9fccd5066a..7c81bd2190 100644--- a/packages/base-render/src/Component/Docs/Common/convert-cursor.ts+++ b/packages/base-render/src/Component/Docs/Common/convert-cursor.ts@@ -1,4 +1,4 @@-import { IPosition, ITextSelectionRange, Nullable } from '@univerjs/core';+import { IPosition, ITextRange, Nullable } from '@univerjs/core';import {IDocumentSkeletonColumn,@@ -115,7 +115,7 @@ export function compareNodePosition(pos1: INodePosition, pos2: INodePosition) {};}-export function getOneTextSelectionRange(rangeList: ITextSelectionRange[]): Nullable<ITextSelectionRange> {+export function getOneTextSelectionRange(rangeList: ITextRange[]): Nullable<ITextRange> {const rangeCount = rangeList.length;if (rangeCount === 0) {return;@@ -125,12 +125,12 @@ export function getOneTextSelectionRange(rangeList: ITextSelectionRange[]): Nullconst lastCursor = rangeList[rangeCount - 1];- const isCollapse = rangeList.length === 1 && firstCursor.isCollapse;+ const collapsed = rangeList.length === 1 && firstCursor.collapsed;return {- cursorStart: firstCursor.cursorStart,- cursorEnd: lastCursor.cursorEnd,- isCollapse,+ startOffset: firstCursor.startOffset,+ endOffset: lastCursor.endOffset,+ collapsed,};}@@ -168,7 +168,7 @@ export class NodePositionConvertToCursor {getRangePointData(startOrigin: Nullable<INodePosition>, endOrigin: Nullable<INodePosition>) {const pointGroup: IPoint[][] = [];- const cursorList: ITextSelectionRange[] = [];+ const cursorList: ITextRange[] = [];if (startOrigin == null || endOrigin == null) {return {@@ -202,18 +202,18 @@ export class NodePositionConvertToCursor {const hasList = spanGroup[0]?.spanType === SpanType.LIST;- let cursorStart = start_sp + st;+ let startOffset = start_sp + st;- let cursorEnd = end_sp + st;+ let endOffset = end_sp + st;const isStartBack = start.span === start_sp && isFirst ? start.isBack : true;const isEndBack = end.span === end_sp && isLast ? end.isBack : false;- const isCollapse = start === end;+ const collapsed = start === end;if (start_sp === 0 && end_sp === spanGroup.length - 1) {- cursorEnd -= hasList ? 1 : 0;+ endOffset -= hasList ? 1 : 0;position = {startX: startX + firstSpanLeft + (isCurrentList ? firstSpanWidth : 0),@@ -226,13 +226,13 @@ export class NodePositionConvertToCursor {// isEndBackFin = isEndBack;- // cursorStart += isStartBackFin ? 0 : 1;+ // startOffset += isStartBackFin ? 0 : 1;- cursorStart -= hasList && !isCurrentList ? 1 : 0;+ startOffset -= hasList && !isCurrentList ? 1 : 0;- // cursorEnd += isEndBackFin ? 0 : 1;+ // endOffset += isEndBackFin ? 0 : 1;- cursorEnd -= hasList && !isCurrentList ? 1 : 0;+ endOffset -= hasList && !isCurrentList ? 1 : 0;position = {startX: startX + firstSpanLeft + (isStartBackFin ? 0 : firstSpanWidth),@@ -250,9 +250,9 @@ export class NodePositionConvertToCursor {pointGroup.push(this._pushToPoints(position));cursorList.push({- cursorStart: isStartBack ? cursorStart : cursorStart + 1,- cursorEnd: isEndBack ? cursorEnd : cursorEnd + 1,- isCollapse,+ startOffset: isStartBack ? startOffset : startOffset + 1,+ endOffset: isEndBack ? endOffset : endOffset + 1,+ collapsed,});});diff --git a/packages/base-render/src/Component/Docs/Common/index.ts b/packages/base-render/src/Component/Docs/Common/index.tsindex 5c8f58912e..ab5e785467 100644--- a/packages/base-render/src/Component/Docs/Common/index.ts+++ b/packages/base-render/src/Component/Docs/Common/index.ts@@ -3,7 +3,7 @@ export * from './convert-cursor';export * from './Line';export * from './Liquid';export * from './Page';+export * from './Range';export * from './Section';export * from './Span';-export * from './TextSelection';export * from './Tools';diff --git a/packages/base-render/src/Component/Docs/DocSkeleton.ts b/packages/base-render/src/Component/Docs/DocSkeleton.tsindex 517ac262a4..cf01e569be 100644--- a/packages/base-render/src/Component/Docs/DocSkeleton.ts+++ b/packages/base-render/src/Component/Docs/DocSkeleton.ts@@ -740,7 +740,7 @@ export class DocumentSkeleton extends Skeleton {}for (const line of lines) {- const { divides, lineHeight, st, ed } = line;+ const { divides, st, ed } = line;const divideLength = divides.length;if (charIndex < st || charIndex > ed) {diff --git a/packages/base-render/src/Component/Docs/Document.ts b/packages/base-render/src/Component/Docs/Document.tsindex ff51d8c18f..3bcd071841 100644--- a/packages/base-render/src/Component/Docs/Document.ts+++ b/packages/base-render/src/Component/Docs/Document.ts@@ -107,13 +107,22 @@ export class Documents extends DocComponent {}getOffsetConfig(): IDocumentOffsetConfig {+ const {+ transform: documentTransform,+ pageLayoutType,+ pageMarginLeft,+ pageMarginTop,+ left: docsLeft,+ top: docsTop,+ } = this;+return {- documentTransform: this.transform,- pageLayoutType: this.pageLayoutType,- pageMarginLeft: this.pageMarginLeft,- pageMarginTop: this.pageMarginTop,- docsLeft: this.left,- docsTop: this.top,+ documentTransform,+ pageLayoutType,+ pageMarginLeft,+ pageMarginTop,+ docsLeft,+ docsTop,};}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.tsindex a492a5e0d8..69faf6ff09 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@@ -7,12 +7,13 @@ import { PageLayoutType } from '../../Basics/IDocumentSkeletonCached';import { IMouseEvent, IPointerEvent } from '../../Basics/IEvents';import { INodeInfo, INodePosition } from '../../Basics/Interfaces';import { getOffsetRectForDom, transformBoundingCoord } from '../../Basics/Position';-import { getCurrentScrollXY } from '../../Basics/ScrollXY';import {- ITextSelectionRangeWithStyle,+ ITextRangeWithStyle,ITextSelectionStyle,NORMAL_TEXT_SELECTION_PLUGIN_STYLE,-} from '../../Basics/TextSelection';+ RANGE_DIRECTION,+} from '../../Basics/range';+import { getCurrentScrollXY } from '../../Basics/ScrollXY';import { checkStyle, injectStyle } from '../../Basics/Tools';import { Transform } from '../../Basics/Transform';import { Vector2 } from '../../Basics/Vector2';@@ -20,7 +21,7 @@ import { Engine } from '../../Engine';import { Scene } from '../../Scene';import { ScrollTimer } from '../../ScrollTimer';import { IScrollObserverParam, Viewport } from '../../Viewport';-import { TextSelection } from './Common/TextSelection';+import { TextRange } from './Common/Range';import { DocumentSkeleton } from './DocSkeleton';import { IDocumentOffsetConfig } from './Document';@@ -52,7 +53,7 @@ export interface ITextSelectionRenderManager {readonly onSelectionStart$: Observable<Nullable<INodePosition>>;readonly onPaste$: Observable<Nullable<IEditorInputConfig>>;- readonly textSelection$: Observable<TextSelection[]>;+ readonly textSelection$: Observable<TextRange[]>;getViewPort(): Viewport;@@ -66,13 +67,9 @@ export interface ITextSelectionRenderManager {resetStyle(): void;- getActiveTextSelection(): Nullable<TextSelection>;-- getTextSelectionList(): TextSelection[];-- add(textSelection: Nullable<TextSelection>): void;+ getAllTextRanges(): TextRange[];- remain(): Nullable<TextSelection>;+ add(textSelection: Nullable<TextRange>): void;sync(): void;@@ -92,9 +89,13 @@ export interface ITextSelectionRenderManager {reset(): void;- getRanges(): Array<Nullable<ITextSelectionRangeWithStyle>>;-- getActiveRange(): Nullable<ITextSelectionRangeWithStyle>;+ getActiveRange(): Nullable<+ ITextRangeWithStyle & {+ startNodePosition: Nullable<INodePosition>;+ endNodePosition: Nullable<INodePosition>;+ direction: RANGE_DIRECTION;+ }+ >;eventTrigger(evt: IPointerEvent | IMouseEvent,@@ -106,8 +107,8 @@ export interface ITextSelectionRenderManager {export interface IEditorInputConfig {event: Event | CompositionEvent | KeyboardEvent;content?: string;- activeRange?: Nullable<ITextSelectionRangeWithStyle>;- selectionList?: TextSelection[];+ activeRange?: Nullable<ITextRangeWithStyle>;+ rangeList?: TextRange[];}export class TextSelectionRenderManager extends RxDisposable implements ITextSelectionRenderManager {@@ -155,7 +156,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelreadonly onPaste$ = this._onPaste$.asObservable();- private readonly _textSelection$ = new BehaviorSubject<TextSelection[]>([]);+ private readonly _textSelection$ = new BehaviorSubject<TextRange[]>([]);readonly textSelection$ = this._textSelection$.asObservable();@@ -179,7 +180,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelprivate _viewportScrollY: number = 0;- private _textSelectionList: TextSelection[] = [];+ private _rangeList: TextRange[] = [];private _currentSegmentId: string = '';@@ -195,6 +196,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelprivate _selectionStyle: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE;private _isSelectionEnabled: boolean = true;+private _viewPortObserverMap = new Map<string,{@@ -215,17 +217,12 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelsuper();this._initDOM();- // this.activeViewport = this._documents?.getFirstViewport();+if (this._docSkeleton && this._scene) {this.changeRuntime(this._docSkeleton, this._scene, viewport);}}- // set activeViewport(viewport: Nullable<Viewport>) {- // this._attachScrollEvent(viewport);- // this._activeViewport = viewport;- // }-getViewPort() {return this._activeViewport;}@@ -250,38 +247,41 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._isSelectionEnabled = false;}- getActiveTextSelection() {- const list = this._textSelectionList;+ getActiveRange() {+ const activeRange = this._rangeList.find((range) => range.isActive());- for (const textSelection of list) {- if (textSelection.isActive()) {- return textSelection;- }+ if (activeRange == null) {+ return null;}- }- getTextSelectionList() {- return this._textSelectionList;- }+ const { startOffset, endOffset, collapsed, startNodePosition, endNodePosition, direction } = activeRange;- add(textSelection: Nullable<TextSelection>) {- if (textSelection == null) {- return;+ if (startOffset == null || endOffset == null) {+ return null;}- this._addTextSelection(textSelection);+ return {+ startOffset,+ endOffset,+ collapsed,+ startNodePosition,+ endNodePosition,+ direction,+ segmentId: this._currentSegmentId,+ style: this._selectionStyle,+ };+ }++ getAllTextRanges() {+ return this._rangeList;}- // @jocs, what's the meaning of this method? and it is not being used anywhere- remain() {- const activeSelection = this.getActiveTextSelection();- if (activeSelection == null) {+ add(textSelection: Nullable<TextRange>) {+ if (textSelection == null) {return;}- const index = this._textSelectionList.indexOf(activeSelection);-- return this._textSelectionList.splice(index, 1)[0];+ this._addTextRange(textSelection);}sync() {@@ -292,38 +292,6 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._scrollToSelection();}- getRanges(): Array<Nullable<ITextSelectionRangeWithStyle>> {- return this.getTextSelectionList()- .map((textSelection) => {- const range = textSelection.getRange();-- if (range == null) {- return;- }-- return {- ...range,- segmentId: this._currentSegmentId,- style: this._selectionStyle,- };- })- .filter((x) => x != null);- }-- getActiveRange(): Nullable<ITextSelectionRangeWithStyle> {- const range = this.getActiveTextSelection()?.getRange();-- if (range == null) {- return;- }-- return {- ...range,- segmentId: this._currentSegmentId,- style: this._selectionStyle,- };- }-activate(x: number, y: number) {this._container.style.left = `${x}px`;this._container.style.top = `${y}px`;@@ -350,10 +318,6 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._cursor.style.animation = '';this._cursor.style.display = 'none';-- // if (!withoutBlur) {- // this._input.blur();- // }}changeRuntime(docSkeleton: DocumentSkeleton, scene: Scene, viewport?: Nullable<Viewport>) {@@ -374,19 +338,6 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSeldocumentOffsetConfig: IDocumentOffsetConfig,viewportMain: Nullable<Viewport>) {- // this._moveInObserver = documents.onPointerEnterObserver.add(() => {- // documents.cursor = CURSOR_TYPE.TEXT;- // });-- // this._moveOutObserver = documents.onPointerLeaveObserver.add(() => {- // documents.cursor = CURSOR_TYPE.DEFAULT;- // this._scene?.resetCursor();- // });-- // this._downObserver = documents.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {-- // });-if (!this._scene || !this._isSelectionEnabled) {return;}@@ -395,6 +346,8 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._activeViewport = viewportMain;}+ this._documentOffsetConfig = documentOffsetConfig;+const scene = this._scene;const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;@@ -403,8 +356,6 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelviewportMain || scene.getActiveViewportByCoord(Vector2.FromArray([evtOffsetX, evtOffsetY])));- this._documentOffsetConfig = documentOffsetConfig;-const startNode = this._findNodeByCoord(evtOffsetX, evtOffsetY);const position = this._getNodePosition(startNode);@@ -412,7 +363,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelconsole.log('startNode', startNode, position, evtOffsetX, evtOffsetY);if (position == null) {- this._deleteAllTextSelection();+ this._removeAllTextRanges();return;}@@ -420,12 +371,12 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelposition.isBack = true;}- if (evt.ctrlKey || this._isEmptyTextSelection()) {- const newTextSelection = new TextSelection(scene, position);+ if (evt.ctrlKey || this._isEmpty()) {+ const newTextSelection = new TextRange(scene, documentOffsetConfig, this._docSkeleton!, position);- this._addTextSelection(newTextSelection);+ this._addTextRange(newTextSelection);} else {- this._updateTextSelection(position);+ this._updateTextRangePosition(position);}this._activeSelectionRefresh();@@ -440,7 +391,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._viewportScrollX = scrollX;this._viewportScrollY = scrollY;- this._onSelectionStart$.next(this.getActiveTextSelection()?.getStart());+ this._onSelectionStart$.next(this.getActiveRangeInstance()?.startNodePosition);let preMoveOffsetX = evtOffsetX;@@ -470,20 +421,22 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelscene.enableEvent();- this._textSelection$.next(this.getTextSelectionList());+ this._textSelection$.next(this.getAllTextRanges());scrollTimer.dispose();this._syncDomToSelection();});-- // state.stopPropagation();}reset() {- this._deleteAllTextSelection();+ this._removeAllTextRanges();this.deactivate();}+ private getActiveRangeInstance() {+ return this._rangeList.find((range) => range.isActive());+ }+override dispose() {super.dispose();@@ -632,20 +585,20 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel};}- private _interactTextSelection(activeTextSelection: TextSelection) {- const newTextSelection: TextSelection[] = [];+ private _interactTextRange(textRange: TextRange) {+ const newTextSelection: TextRange[] = [];let hasIntersection = false;- this._textSelectionList.forEach((textSelection) => {- if (textSelection === activeTextSelection) {+ this._rangeList.forEach((range) => {+ if (range === textRange) {return true;}- if (!activeTextSelection.isIntersection(textSelection)) {- newTextSelection.push(textSelection);+ if (!textRange.isIntersection(range)) {+ newTextSelection.push(range);} else {hasIntersection = true;- textSelection.dispose();+ range.dispose();}});@@ -653,46 +606,52 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelreturn;}- newTextSelection.push(activeTextSelection);- this._textSelectionList = newTextSelection;+ newTextSelection.push(textRange);++ this._rangeList = newTextSelection;}- private _deleteAllTextSelection() {- this._textSelectionList.forEach((textSelection) => {- textSelection.dispose();+ private _removeAllTextRanges() {+ this._rangeList.forEach((range) => {+ range.dispose();});- this._textSelectionList = [];++ this._rangeList = [];}- private _deactivateTextSelection() {- this._textSelectionList.forEach((textSelection) => {- textSelection.deactivate();+ private _deactivateAllTextRanges() {+ this._rangeList.forEach((range) => {+ range.deactivate();});}- private _addTextSelection(textSelection: TextSelection) {- this._deactivateTextSelection();- textSelection.activate();- this._textSelectionList.push(textSelection);+ private _addTextRange(textRange: TextRange) {+ this._deactivateAllTextRanges();+ textRange.activate();++ this._rangeList.push(textRange);}- private _updateTextSelection(position: INodePosition) {+ private _updateTextRangePosition(position: INodePosition) {if (!this._scene) {return;}- let lastTextSelection = this._textSelectionList.pop();- if (!lastTextSelection) {- lastTextSelection = new TextSelection(this._scene, position);++ let lastRange = this._rangeList.pop();++ if (!lastRange) {+ lastRange = new TextRange(this._scene, this._documentOffsetConfig, this._docSkeleton!, position);}- this._deleteAllTextSelection();- lastTextSelection.activate();- lastTextSelection.startNodePosition = position;- lastTextSelection.endNodePosition = null;- this._textSelectionList = [lastTextSelection];++ this._removeAllTextRanges();+ lastRange.activate();+ lastRange.anchorNodePosition = position;+ lastRange.focusNodePosition = null;+ this._rangeList = [lastRange];}- private _isEmptyTextSelection() {- return this._textSelectionList.length === 0;+ private _isEmpty() {+ return this._rangeList.length === 0;}private _getCanvasOffset() {@@ -702,8 +661,8 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel// Let the selection show on the current screen.private _scrollToSelection() {- const activeTextSelection = this.getActiveTextSelection();- const anchor = activeTextSelection?.getAnchor();+ const activeRangeInstance = this.getActiveRangeInstance();+ const anchor = activeRangeInstance?.getAnchor();if (!anchor || (anchor && !anchor.visible) || this._activeViewport == null) {return;}@@ -745,8 +704,8 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel}private _syncDomToSelection() {- const activeTextSelection = this.getActiveTextSelection();- const anchor = activeTextSelection?.getAnchor();+ const activeRangeInstance = this.getActiveRangeInstance();+ const anchor = activeRangeInstance?.getAnchor();if (!anchor || (anchor && !anchor.visible) || this._activeViewport == null) {this.focus();return;@@ -774,37 +733,33 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel}private _moving(moveOffsetX: number, moveOffsetY: number, scrollTimer: ScrollTimer) {- const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);- // const endX = moveOffsetX - this._viewportScrollX + scrollX;- // const endY = moveOffsetY - this._viewportScrollY + scrollY;-if (this._docSkeleton == null) {return;}const endNode = this._findNodeByCoord(moveOffsetX, moveOffsetY);- const endPosition = this._getNodePosition(endNode);+ const focusNodePosition = this._getNodePosition(endNode);- // console.log('endNode', endNode, endPosition, { moveOffsetX, moveOffsetY, _viewportScrollY: this._viewportScrollY, scrollX });+ // console.log('endNode', endNode, focusNodePosition, { moveOffsetX, moveOffsetY, _viewportScrollY: this._viewportScrollY, scrollX });- if (!endPosition) {+ if (!focusNodePosition) {return;}- const activeTextSelection = this.getActiveTextSelection();+ const activeRangeInstance = this.getActiveRangeInstance();- if (!activeTextSelection) {+ if (!activeRangeInstance) {return;}- activeTextSelection.endNodePosition = endPosition;+ activeRangeInstance.focusNodePosition = focusNodePosition;- activeTextSelection.refresh(this._documentOffsetConfig, this._docSkeleton);+ activeRangeInstance.refresh();this.deactivate();- this._interactTextSelection(activeTextSelection);+ this._interactTextRange(activeRangeInstance);}private _attachScrollEvent(viewport: Nullable<Viewport>) {@@ -822,9 +777,9 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelreturn;}- const textSelection = this.getActiveTextSelection();+ const activeRangeInstance = this.getActiveRangeInstance();- textSelection?.activeStatic();+ activeRangeInstance?.activeStatic();this._cursor.style.display = 'none';});@@ -837,9 +792,9 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelconst bounds = viewport.getBounding();- const textSelection = this.getActiveTextSelection();+ const activeRangeInstance = this.getActiveRangeInstance();- const anchor = textSelection?.getAnchor();+ const anchor = activeRangeInstance?.getAnchor();if (!anchor || (anchor && !anchor.visible)) {return;@@ -855,7 +810,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._syncDomToSelection();- textSelection?.deactivateStatic();+ activeRangeInstance?.deactivateStatic();this._cursor.style.display = 'revert';});@@ -927,13 +882,13 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._input.innerHTML = '';const activeRange = this.getActiveRange();- const selectionList = this.getTextSelectionList();+ const rangeList = this.getAllTextRanges();func({event: e,content,activeRange,- selectionList,+ rangeList,});}@@ -986,11 +941,9 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelif (this._docSkeleton == null) {return;}- const activeSelection = this.getActiveTextSelection();-- activeSelection?.refresh(this._documentOffsetConfig, this._docSkeleton);+ const activeRangeInstance = this.getActiveRangeInstance();- // this._activeSelectionRefresh$.next(activeSelection);+ activeRangeInstance?.refresh();}}diff --git a/packages/base-ui/src/services/shortcut/shortcut-experience.service.ts b/packages/base-ui/src/services/shortcut/shortcut-experience.service.tsindex 646eda3b8b..2c79c910a0 100644--- a/packages/base-ui/src/services/shortcut/shortcut-experience.service.ts+++ b/packages/base-ui/src/services/shortcut/shortcut-experience.service.ts@@ -1,4 +1,4 @@-import { ISelection, ITextSelectionRangeParam, IUniverInstanceService, LocaleService, Nullable } from '@univerjs/core';+import { ISelection, ITextRangeParam, IUniverInstanceService, LocaleService, Nullable } from '@univerjs/core';import { IDisposable, Inject } from '@wendellhu/redi';import { KeyCode } from './keycode';@@ -11,7 +11,7 @@ export interface IShortcutExperienceSearch {export interface IShortcutExperienceParam extends IShortcutExperienceSearch {selection?: ISelection;- textSelection?: ITextSelectionRangeParam;+ textSelection?: ITextRangeParam;}/**diff --git a/packages/core/src/Types/Interfaces/ISelectionData.ts b/packages/core/src/Types/Interfaces/ISelectionData.tsindex f09cd722e6..66fcd095f8 100644--- a/packages/core/src/Types/Interfaces/ISelectionData.ts+++ b/packages/core/src/Types/Interfaces/ISelectionData.ts@@ -36,19 +36,15 @@ export interface ISelectionWithCoord {primaryWithCoord: Nullable<ISelectionCellWithCoord>;}-export interface ITextSelectionRangeStart {- cursorStart: number;+export interface ITextRangeStart {+ startOffset: number;}-export interface ITextSelectionRange extends ITextSelectionRangeStart {- cursorEnd: number;- isCollapse: boolean;+export interface ITextRange extends ITextRangeStart {+ endOffset: number;+ collapsed: boolean;}-export interface ITextSelectionRangeParam extends ITextSelectionRange {+export interface ITextRangeParam extends ITextRange {segmentId?: string; //The ID of the header, footer or footnote the location is in. An empty segment ID signifies the document's body.}--export interface ITextSelectionRangeStartParam extends ITextSelectionRangeStart {- segmentId?: string;-}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.tsindex b902494d47..7aa18dceac 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@@ -163,9 +163,9 @@ export class StartEditController extends Disposable {this._textSelectionManagerService.replace([{- cursorStart: 0,- cursorEnd: 0,- isCollapse: true,+ startOffset: 0,+ endOffset: 0,+ collapsed: true,},]);@@ -227,8 +227,6 @@ export class StartEditController extends Disposable {documentSkeleton.calculate();this._editAreaProcessing(editorWidth, editorHeight, actualRangeWithCoord, canvasOffset, fill);-- // this._textSelectionRenderManager.sync();}/**@@ -458,9 +456,9 @@ export class StartEditController extends Disposable {this._textSelectionManagerService.replace([{- cursorStart: 0,- cursorEnd: 0,- isCollapse: true,+ startOffset: 0,+ endOffset: 0,+ collapsed: true,},]);} else {@@ -473,9 +471,9 @@ export class StartEditController extends Disposable {this._textSelectionManagerService.replace([{- cursorStart: cursor,- cursorEnd: cursor,- isCollapse: true,+ startOffset: cursor,+ endOffset: cursor,+ collapsed: true,},]);}