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.

refactor(doc): text selection (#696)

Ran Luo749b11f33f55
diff --git a/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts
index 9bca4c26e6..918968edc4 100644
--- a/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts
+++ b/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts
@@ -17,15 +17,28 @@
import type { ICommand, IDocumentData, IStyleBase, Univer } from '@univerjs/core';
import { BooleanNumber, ICommandService, IUniverInstanceService, UndoCommand } from '@univerjs/core';
import type { Injector } from '@wendellhu/redi';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { NORMAL_TEXT_SELECTION_PLUGIN_NAME } from '../../../basics/docs-view-key';
import { TextSelectionManagerService } from '../../../services/text-selection-manager.service';
import { RichTextEditingMutation } from '../../mutations/core-editing.mutation';
+import { SetTextSelectionsOperation } from '../../operations/text-selection.operation';
import type { IInnerCutCommandParams, IInnerPasteCommandParams } from '../clipboard.inner.command';
import { CutContentCommand, InnerPasteCommand } from '../clipboard.inner.command';
import { createCommandTestBed } from './create-command-test-bed';
+vi.mock('@univerjs/engine-render', async () => {
+ const actual = await vi.importActual('@univerjs/engine-render');
+ const { ITextSelectionRenderManager, TextSelectionRenderManager } = await import(
+ './mock-text-selection-render-manager'
+ );
+
+ return {
+ ...actual,
+ ITextSelectionRenderManager,
+ TextSelectionRenderManager,
+ };
+});
+
const TEST_DOCUMENT_DATA_EN: IDocumentData = {
id: 'test-doc',
body: {
@@ -118,21 +131,20 @@ describe('test cases in clipboard', () => {
commandService = get(ICommandService);
commandService.registerCommand(InnerPasteCommand);
commandService.registerCommand(CutContentCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
const selectionManager = get(TextSelectionManagerService);
selectionManager.setCurrentSelection({
- pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
unitId: 'test-doc',
+ subUnitId: '',
});
selectionManager.add([
{
startOffset: 0,
endOffset: 5,
- collapsed: false,
- segmentId: '',
},
]);
@@ -140,8 +152,6 @@ describe('test cases in clipboard', () => {
{
startOffset: 10,
endOffset: 15,
- collapsed: false,
- segmentId: '',
},
]);
});
diff --git a/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts
index e45b740eac..a333ecd873 100644
--- a/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -29,6 +29,7 @@ import { Inject, Injector } from '@wendellhu/redi';
import { DocViewModelManagerService } from '../../../services/doc-view-model-manager.service';
import { TextSelectionManagerService } from '../../../services/text-selection-manager.service';
+import { ITextSelectionRenderManager, TextSelectionRenderManager } from './mock-text-selection-render-manager';
const TEST_DOCUMENT_DATA_EN: IDocumentData = {
id: 'test-doc',
@@ -109,6 +110,12 @@ export function createCommandTestBed(workbookConfig?: IDocumentData, dependencie
override onStarting(injector: Injector): void {
injector.add([TextSelectionManagerService]);
injector.add([DocViewModelManagerService]);
+ injector.add([
+ ITextSelectionRenderManager,
+ {
+ useClass: TextSelectionRenderManager,
+ },
+ ]);
dependencies?.forEach((d) => injector.add(d));
}
diff --git a/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts b/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts
index 522add76f3..28b8ba6544 100644
--- a/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts
+++ b/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts
@@ -17,11 +17,11 @@
import type { ICommand, IStyleBase, Univer } from '@univerjs/core';
import { BooleanNumber, ICommandService, IUniverInstanceService, RedoCommand, UndoCommand } from '@univerjs/core';
import type { Injector } from '@wendellhu/redi';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { NORMAL_TEXT_SELECTION_PLUGIN_NAME } from '../../../basics/docs-view-key';
import { TextSelectionManagerService } from '../../../services/text-selection-manager.service';
import { RichTextEditingMutation } from '../../mutations/core-editing.mutation';
+import { SetTextSelectionsOperation } from '../../operations/text-selection.operation';
import {
SetInlineFormatBoldCommand,
SetInlineFormatCommand,
@@ -34,6 +34,19 @@ import {
} from '../inline-format.command';
import { createCommandTestBed } from './create-command-test-bed';
+vi.mock('@univerjs/engine-render', async () => {
+ const actual = await vi.importActual('@univerjs/engine-render');
+ const { ITextSelectionRenderManager, TextSelectionRenderManager } = await import(
+ './mock-text-selection-render-manager'
+ );
+
+ return {
+ ...actual,
+ ITextSelectionRenderManager,
+ TextSelectionRenderManager,
+ };
+});
+
describe('Test inline format commands', () => {
let univer: Univer;
let get: Injector['get'];
@@ -63,21 +76,20 @@ describe('Test inline format commands', () => {
commandService = get(ICommandService);
commandService.registerCommand(SetInlineFormatCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
const selectionManager = get(TextSelectionManagerService);
selectionManager.setCurrentSelection({
- pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
unitId: 'test-doc',
+ subUnitId: '',
});
selectionManager.add([
{
startOffset: 0,
endOffset: 5,
- collapsed: false,
- segmentId: '',
},
]);
@@ -85,8 +97,6 @@ describe('Test inline format commands', () => {
{
startOffset: 20,
endOffset: 30,
- collapsed: false,
- segmentId: '',
},
]);
});
diff --git a/packages/docs/src/commands/commands/__tests__/mock-text-selection-render-manager.ts b/packages/docs/src/commands/commands/__tests__/mock-text-selection-render-manager.ts
new file mode 100644
index 0000000000..506084e39c
--- /dev/null
+++ b/packages/docs/src/commands/commands/__tests__/mock-text-selection-render-manager.ts
@@ -0,0 +1,32 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { Nullable } from '@univerjs/core';
+import type { ITextSelectionInnerParam } from '@univerjs/engine-render';
+import { createIdentifier } from '@wendellhu/redi';
+import { BehaviorSubject } from 'rxjs';
+
+export class TextSelectionRenderManager {
+ private readonly _textSelectionInner$ = new BehaviorSubject<Nullable<ITextSelectionInnerParam>>(null);
+
+ readonly textSelectionInner$ = this._textSelectionInner$.asObservable();
+ removeAllTextRanges() {}
+ addTextRanges() {}
+}
+
+export const ITextSelectionRenderManager = createIdentifier<TextSelectionRenderManager>(
+ 'mock.univer.doc.text-selection-render-manager'
+);
diff --git a/packages/docs/src/commands/commands/__tests__/replace-content.command.spec.ts b/packages/docs/src/commands/commands/__tests__/replace-content.command.spec.ts
index 001aad03cb..6720287138 100644
--- a/packages/docs/src/commands/commands/__tests__/replace-content.command.spec.ts
+++ b/packages/docs/src/commands/commands/__tests__/replace-content.command.spec.ts
@@ -17,14 +17,27 @@
import type { ICommand, IDocumentData, Univer } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, RedoCommand, UndoCommand } from '@univerjs/core';
import type { Injector } from '@wendellhu/redi';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { NORMAL_TEXT_SELECTION_PLUGIN_NAME } from '../../../basics/docs-view-key';
import { TextSelectionManagerService } from '../../../services/text-selection-manager.service';
import { RichTextEditingMutation } from '../../mutations/core-editing.mutation';
+import { SetTextSelectionsOperation } from '../../operations/text-selection.operation';
import { CoverContentCommand, ReplaceContentCommand } from '../replace-content.command';
import { createCommandTestBed } from './create-command-test-bed';
+vi.mock('@univerjs/engine-render', async () => {
+ const actual = await vi.importActual('@univerjs/engine-render');
+ const { ITextSelectionRenderManager, TextSelectionRenderManager } = await import(
+ './mock-text-selection-render-manager'
+ );
+
+ return {
+ ...actual,
+ ITextSelectionRenderManager,
+ TextSelectionRenderManager,
+ };
+});
+
const TEST_DOCUMENT_DATA_EN: IDocumentData = {
id: 'test-doc',
body: {
@@ -66,21 +79,20 @@ describe('replace or cover content of document', () => {
commandService = get(ICommandService);
commandService.registerCommand(ReplaceContentCommand);
commandService.registerCommand(CoverContentCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
const selectionManager = get(TextSelectionManagerService);
selectionManager.setCurrentSelection({
- pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
unitId: 'test-doc',
+ subUnitId: '',
});
selectionManager.add([
{
startOffset: 5,
endOffset: 5,
- collapsed: false,
- segmentId: '',
},
]);
});
diff --git a/packages/docs/src/commands/operations/select-all.operation.ts b/packages/docs/src/commands/operations/select-all.operation.ts
index 2277a9b3d3..501f7d43a9 100644
--- a/packages/docs/src/commands/operations/select-all.operation.ts
+++ b/packages/docs/src/commands/operations/select-all.operation.ts
@@ -16,7 +16,6 @@
import type { ICommand } from '@univerjs/core';
import { CommandType, IUniverInstanceService } from '@univerjs/core';
-import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
@@ -37,11 +36,10 @@ export const SelectAllOperation: ICommand<ISelectAllOperationParams> = {
return false;
}
- const textRanges: ITextRangeWithStyle[] = [
+ const textRanges = [
{
startOffset: 0,
endOffset: prevBody.dataStream.length - 2,
- collapsed: false,
},
];
diff --git a/packages/docs/src/commands/operations/text-selection.operation.ts b/packages/docs/src/commands/operations/text-selection.operation.ts
index e4b61d610c..148d992cfc 100644
--- a/packages/docs/src/commands/operations/text-selection.operation.ts
+++ b/packages/docs/src/commands/operations/text-selection.operation.ts
@@ -16,13 +16,13 @@
import type { IOperation } from '@univerjs/core';
import { CommandType } from '@univerjs/core';
-import type { TextRange } from '@univerjs/engine-render';
-
-import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
+import type { ITextSelectionStyle, TextRange } from '@univerjs/engine-render';
export interface ISetTextSelectionsOperationParams {
unitId: string;
- pluginName: string;
+ subUnitId: string;
+ segmentId: string;
+ style: ITextSelectionStyle;
ranges: TextRange[];
}
@@ -31,11 +31,8 @@ export const SetTextSelectionsOperation: IOperation<ISetTextSelectionsOperationP
type: CommandType.OPERATION,
- handler: (accessor, params) => {
- const textSelectionManagerService = accessor.get(TextSelectionManagerService);
-
- textSelectionManagerService.replaceTextRangesWithNoRefresh(params!.ranges);
-
+ handler: (accessor, prams) => {
+ // for live share only.
return true;
},
};
diff --git a/packages/docs/src/controllers/clipboard.controller.ts b/packages/docs/src/controllers/clipboard.controller.ts
index 72993688fc..b4ffab5ae2 100644
--- a/packages/docs/src/controllers/clipboard.controller.ts
+++ b/packages/docs/src/controllers/clipboard.controller.ts
@@ -27,11 +27,12 @@ import {
OnLifecycle,
Tools,
} from '@univerjs/core';
-import { ITextSelectionRenderManager } from '@univerjs/engine-render';
+import { Inject } from '@wendellhu/redi';
import { DocCopyCommand, DocCutCommand, DocPasteCommand } from '../commands/commands/clipboard.command';
import { CutContentCommand, InnerPasteCommand } from '../commands/commands/clipboard.inner.command';
import { IDocClipboardService } from '../services/clipboard/clipboard.service';
+import { TextSelectionManagerService } from '../services/text-selection-manager.service';
@OnLifecycle(LifecycleStages.Rendered, DocClipboardController)
export class DocClipboardController extends Disposable {
@@ -40,7 +41,7 @@ export class DocClipboardController extends Disposable {
@ICommandService private readonly _commandService: ICommandService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IDocClipboardService private readonly _docClipboardService: IDocClipboardService,
- @ITextSelectionRenderManager private _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@IContextService private readonly _contextService: IContextService
) {
super();
@@ -102,14 +103,14 @@ export class DocClipboardController extends Disposable {
segmentId,
endOffset: activeEndOffset,
style,
- } = this._textSelectionRenderManager.getActiveRange() ?? {};
- const ranges = this._textSelectionRenderManager.getAllTextRanges();
+ } = this._textSelectionManagerService.getActiveRange() ?? {};
+ const ranges = this._textSelectionManagerService.getSelections();
if (segmentId == null) {
this._logService.error('[DocClipboardController] segmentId is not existed');
}
- if (activeEndOffset == null) {
+ if (activeEndOffset == null || ranges == null) {
return;
}
@@ -134,7 +135,6 @@ export class DocClipboardController extends Disposable {
{
startOffset: cursor,
endOffset: cursor,
- collapsed: true,
style,
},
];
@@ -146,13 +146,17 @@ export class DocClipboardController extends Disposable {
}
private _getDocumentBodyInRanges(): IDocumentBody[] {
- const ranges = this._textSelectionRenderManager.getAllTextRanges();
+ const ranges = this._textSelectionManagerService.getSelections();
const docDataModel = this._currentUniverService.getCurrentUniverDocInstance();
const { dataStream, textRuns = [], paragraphs = [] } = docDataModel.getBody()!;
const results: IDocumentBody[] = [];
+ if (ranges == null) {
+ return results;
+ }
+
for (const range of ranges) {
const { startOffset, endOffset, collapsed } = range;
@@ -241,14 +245,14 @@ export class DocClipboardController extends Disposable {
segmentId,
endOffset: activeEndOffset,
style,
- } = this._textSelectionRenderManager.getActiveRange() ?? {};
- const ranges = this._textSelectionRenderManager.getAllTextRanges();
+ } = this._textSelectionManagerService.getActiveRange() ?? {};
+ const ranges = this._textSelectionManagerService.getSelections();
if (segmentId == null) {
this._logService.error('[DocClipboardController] segmentId is not existed');
}
- if (activeEndOffset == null) {
+ if (activeEndOffset == null || ranges == null) {
return;
}
@@ -273,7 +277,6 @@ export class DocClipboardController extends Disposable {
{
startOffset: cursor,
endOffset: cursor,
- collapsed: true,
style,
},
];
diff --git a/packages/docs/src/controllers/delete.controller.ts b/packages/docs/src/controllers/delete.controller.ts
index c3835919a5..9017625a5d 100644
--- a/packages/docs/src/controllers/delete.controller.ts
+++ b/packages/docs/src/controllers/delete.controller.ts
@@ -23,14 +23,7 @@ import {
OnLifecycle,
UpdateDocsAttributeType,
} from '@univerjs/core';
-import {
- getParagraphBySpan,
- hasListSpan,
- isFirstSpan,
- isIndentBySpan,
- isSameLine,
- ITextSelectionRenderManager,
-} from '@univerjs/engine-render';
+import { getParagraphBySpan, hasListSpan, isFirstSpan, isIndentBySpan, isSameLine } from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
import { CutContentCommand } from '../commands/commands/clipboard.inner.command';
@@ -42,14 +35,15 @@ import {
UpdateCommand,
} from '../commands/commands/core-editing.command';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+import { TextSelectionManagerService } from '../services/text-selection-manager.service';
@OnLifecycle(LifecycleStages.Rendered, DeleteController)
export class DeleteController extends Disposable {
constructor(
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
) {
super();
@@ -85,7 +79,7 @@ export class DeleteController extends Disposable {
// Use BACKSPACE to delete left.
private _handleDeleteLeft() {
- const activeRange = this._textSelectionRenderManager.getActiveRange();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
@@ -154,7 +148,6 @@ export class DeleteController extends Disposable {
{
startOffset: cursor,
endOffset: cursor,
- collapsed: true,
style,
},
];
@@ -168,7 +161,6 @@ export class DeleteController extends Disposable {
range: {
startOffset: paragraphIndex,
endOffset: paragraphIndex + 1,
- collapsed: false,
},
textRanges,
coverType: UpdateDocsAttributeType.REPLACE,
@@ -191,7 +183,6 @@ export class DeleteController extends Disposable {
{
startOffset: cursor,
endOffset: cursor,
- collapsed: true,
style,
},
];
@@ -219,7 +210,7 @@ export class DeleteController extends Disposable {
// Use DELETE to delete right.
private _handleDeleteRight() {
- const activeRange = this._textSelectionRenderManager.getActiveRange();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
@@ -241,7 +232,6 @@ export class DeleteController extends Disposable {
{
startOffset,
endOffset: startOffset,
- collapsed: true,
style,
},
];
@@ -271,8 +261,8 @@ export class DeleteController extends Disposable {
// get cursor position when BACKSPACE/DELETE excuse the CutContentCommand.
private _getTextRangesWhenDelete() {
- const activeRange = this._textSelectionRenderManager.getActiveRange()!;
- const ranges = this._textSelectionRenderManager.getAllTextRanges();
+ const activeRange = this._textSelectionManagerService.getActiveRange()!;
+ const ranges = this._textSelectionManagerService.getSelections()!;
let cursor = activeRange.endOffset;
@@ -292,7 +282,6 @@ export class DeleteController extends Disposable {
{
startOffset: cursor,
endOffset: cursor,
- collapsed: true,
style: activeRange.style,
},
];
diff --git a/packages/docs/src/controllers/ime-input.controller.ts b/packages/docs/src/controllers/ime-input.controller.ts
index af5244ef6d..445d16efb0 100644
--- a/packages/docs/src/controllers/ime-input.controller.ts
+++ b/packages/docs/src/controllers/ime-input.controller.ts
@@ -32,7 +32,6 @@ import { getDocObject } from '../basics/component-tools';
import { IMEInputCommand } from '../commands/commands/ime-input.command';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
import { IMEInputManagerService } from '../services/ime-input-manager.service';
-import { TextSelectionManagerService } from '../services/text-selection-manager.service';
@OnLifecycle(LifecycleStages.Rendered, IMEInputController)
export class IMEInputController extends Disposable {
@@ -51,7 +50,6 @@ export class IMEInputController extends Disposable {
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@Inject(IMEInputManagerService) private readonly _imeInputManagerService: IMEInputManagerService,
@ICommandService private readonly _commandService: ICommandService
) {
@@ -137,7 +135,6 @@ export class IMEInputController extends Disposable {
{
startOffset: startOffset + len,
endOffset: startOffset + len,
- collapsed: true,
style,
},
];
diff --git a/packages/docs/src/controllers/inline-format.controller.ts b/packages/docs/src/controllers/inline-format.controller.ts
index 44893950ce..d5115eeff3 100644
--- a/packages/docs/src/controllers/inline-format.controller.ts
+++ b/packages/docs/src/controllers/inline-format.controller.ts
@@ -15,8 +15,7 @@
*/
import type { ICommandInfo } from '@univerjs/core';
-import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
-import { ITextSelectionRenderManager } from '@univerjs/engine-render';
+import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import {
@@ -39,8 +38,6 @@ import { TextSelectionManagerService } from '../services/text-selection-manager.
@OnLifecycle(LifecycleStages.Rendered, InlineFormatController)
export class InlineFormatController extends Disposable {
constructor(
- @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@ICommandService private readonly _commandService: ICommandService
) {
@@ -72,7 +69,7 @@ export class InlineFormatController extends Disposable {
}
private _handleInlineFormat(command: ICommandInfo) {
- const { segmentId } = this._textSelectionRenderManager.getActiveRange() ?? {};
+ const { segmentId } = this._textSelectionManagerService.getActiveRange() ?? {};
if (segmentId == null) {
return;
diff --git a/packages/docs/src/controllers/line-break-input.controller.ts b/packages/docs/src/controllers/line-break-input.controller.ts
index e833a5ab50..58cabc404b 100644
--- a/packages/docs/src/controllers/line-break-input.controller.ts
+++ b/packages/docs/src/controllers/line-break-input.controller.ts
@@ -23,7 +23,7 @@ import {
LifecycleStages,
OnLifecycle,
} from '@univerjs/core';
-import { IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';
+import { IRenderManagerService } from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
import type { Subscription } from 'rxjs';
@@ -58,7 +58,6 @@ export class LineBreakInputController extends Disposable {
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@ICommandService private readonly _commandService: ICommandService
) {
@@ -92,7 +91,7 @@ export class LineBreakInputController extends Disposable {
private _handleBreakLine() {
const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
- const activeRange = this._textSelectionRenderManager.getActiveRange();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
if (activeRange == null || skeleton == null) {
return;
@@ -107,7 +106,6 @@ export class LineBreakInputController extends Disposable {
{
startOffset: startOffset + 1,
endOffset: startOffset + 1,
- collapsed: true,
style,
},
];
diff --git a/packages/docs/src/controllers/move-cursor.controller.ts b/packages/docs/src/controllers/move-cursor.controller.ts
index 2945e3d667..3377928545 100644
--- a/packages/docs/src/controllers/move-cursor.controller.ts
+++ b/packages/docs/src/controllers/move-cursor.controller.ts
@@ -30,12 +30,7 @@ import type {
INodePosition,
INodeSearch,
} from '@univerjs/engine-render';
-import {
- IRenderManagerService,
- ITextSelectionRenderManager,
- NodePositionConvertToCursor,
- RANGE_DIRECTION,
-} from '@univerjs/engine-render';
+import { IRenderManagerService, NodePositionConvertToCursor, RANGE_DIRECTION } from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
import type { Subscription } from 'rxjs';
@@ -53,7 +48,6 @@ export class MoveCursorController extends Disposable {
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@ICommandService private readonly _commandService: ICommandService
) {
@@ -99,8 +93,8 @@ export class MoveCursorController extends Disposable {
}
private _handleShiftMoveSelection(direction: Direction) {
- const activeRange = this._textSelectionRenderManager.getActiveRange();
- const allRanges = this._textSelectionRenderManager.getAllTextRanges();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
+ const allRanges = this._textSelectionManagerService.getSelections()!;
const docDataModel = this._currentUniverService.getCurrentUniverDocInstance();
const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
@@ -126,7 +120,6 @@ export class MoveCursorController extends Disposable {
{
startOffset: direction === Direction.LEFT || direction === Direction.UP ? max : min,
endOffset: direction === Direction.LEFT || direction === Direction.UP ? min : max,
- collapsed: false,
style,
},
]);
@@ -155,7 +148,6 @@ export class MoveCursorController extends Disposable {
{
startOffset: anchorOffset,
endOffset: focusOffset,
- collapsed: anchorOffset === focusOffset,
style,
},
]);
@@ -177,7 +169,6 @@ export class MoveCursorController extends Disposable {
{
startOffset: anchorOffset,
endOffset: newFocusOffset,
- collapsed: anchorOffset === newFocusOffset,
style,
},
]);
@@ -195,7 +186,6 @@ export class MoveCursorController extends Disposable {
{
startOffset: anchorOffset,
endOffset: newActiveRange.endOffset,
- collapsed: anchorOffset === newActiveRange.endOffset,
style,
},
]);
@@ -203,15 +193,15 @@ export class MoveCursorController extends Disposable {
}
private _handleMoveCursor(direction: Direction) {
- const activeRange = this._textSelectionRenderManager.getActiveRange();
- const allRanges = this._textSelectionRenderManager.getAllTextRanges();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
+ const allRanges = this._textSelectionManagerService.getSelections();
const docDataModel = this._currentUniverService.getCurrentUniverDocInstance();
const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
const docObject = this._getDocObject();
- if (activeRange == null || skeleton == null || docObject == null) {
+ if (activeRange == null || skeleton == null || docObject == null || allRanges == null) {
return;
}
@@ -248,7 +238,6 @@ export class MoveCursorController extends Disposable {
{
startOffset: cursor,
endOffset: cursor,
- collapsed: true,
style,
},
]);
@@ -281,7 +270,6 @@ export class MoveCursorController extends Disposable {
{
startOffset: cursor,
endOffset: cursor,
- collapsed: true,
style,
},
]);
diff --git a/packages/docs/src/controllers/normal-input.controller.ts b/packages/docs/src/controllers/normal-input.controller.ts
index 3f23d860cc..f6da9a084e 100644
--- a/packages/docs/src/controllers/normal-input.controller.ts
+++ b/packages/docs/src/controllers/normal-input.controller.ts
@@ -23,7 +23,6 @@ import type { Subscription } from 'rxjs';
import { getDocObject } from '../basics/component-tools';
import { InsertCommand } from '../commands/commands/core-editing.command';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
-import { TextSelectionManagerService } from '../services/text-selection-manager.service';
@OnLifecycle(LifecycleStages.Rendered, NormalInputController)
export class NormalInputController extends Disposable {
@@ -34,7 +33,6 @@ export class NormalInputController extends Disposable {
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@ICommandService private readonly _commandService: ICommandService
) {
super();
@@ -82,7 +80,6 @@ export class NormalInputController extends Disposable {
{
startOffset: startOffset + len,
endOffset: startOffset + len,
- collapsed: true,
style,
},
];
diff --git a/packages/docs/src/controllers/text-selection.controller.ts b/packages/docs/src/controllers/text-selection.controller.ts
index 41e9fb0a77..23b7a046b6 100644
--- a/packages/docs/src/controllers/text-selection.controller.ts
+++ b/packages/docs/src/controllers/text-selection.controller.ts
@@ -21,10 +21,9 @@ import { CURSOR_TYPE, IRenderManagerService, ITextSelectionRenderManager } from
import { Inject } from '@wendellhu/redi';
import { getDocObjectById } from '../basics/component-tools';
-import { NORMAL_TEXT_SELECTION_PLUGIN_NAME, VIEWPORT_KEY } from '../basics/docs-view-key';
+import { VIEWPORT_KEY } from '../basics/docs-view-key';
import type { ISetDocZoomRatioOperationParams } from '../commands/operations/set-doc-zoom-ratio.operation';
import { SetDocZoomRatioOperation } from '../commands/operations/set-doc-zoom-ratio.operation';
-import { SetTextSelectionsOperation } from '../commands/operations/text-selection.operation';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
import { TextSelectionManagerService } from '../services/text-selection-manager.service';
@@ -71,6 +70,12 @@ export class TextSelectionController extends Disposable {
this._initialize();
}
+ private _initialize() {
+ this._skeletonListener();
+
+ this._commandExecutedListener();
+ }
+
override dispose(): void {
this._renderManagerService.getRenderAll().forEach((docObject) => {
const { mainComponent } = docObject;
@@ -86,21 +91,6 @@ export class TextSelectionController extends Disposable {
});
}
- private _initialize() {
- this._onChangeListener();
-
- this._skeletonListener();
-
- this._userActionSyncListener();
-
- this._commandExecutedListener();
-
- // this._textSelectionManagerService.setCurrentSelection({
- // pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
- // unitId,
- // });
- }
-
private _initialMain(unitId: string) {
const docObject = this._getDocObjectById(unitId);
if (docObject == null) {
@@ -142,56 +132,6 @@ export class TextSelectionController extends Disposable {
});
}
- private _onChangeListener() {
- this._textSelectionManagerService.textSelectionInfo$.subscribe((param) => {
- const unitId = this._textSelectionManagerService.getCurrentSelection()?.unitId;
- // Remove all textRanges.
- this._textSelectionRenderManager.removeAllTextRanges();
-
- if (param == null || unitId == null) {
- return;
- }
-
- const docSkeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
-
- const currentRender = this._getDocObjectById(unitId);
-
- if (currentRender == null || docSkeleton == null) {
- return;
- }
-
- const { scene, document } = currentRender;
-
- this._textSelectionRenderManager.addTextRanges(param, {
- scene,
- skeleton: docSkeleton,
- documentOffsetConfig: document.getOffsetConfig(),
- });
- });
- }
-
- private _userActionSyncListener() {
- this._textSelectionRenderManager.textSelection$.subscribe((textRanges) => {
- const docsObject = this._docSkeletonManagerService.getCurrent();
-
- if (docsObject == null) {
- return;
- }
-
- const { unitId } = docsObject;
-
- this._commandService.executeCommand(SetTextSelectionsOperation.id, {
- unitId,
- pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
- ranges: textRanges,
- });
- });
- }
-
- private _getDocObjectById(unitId: string) {
- return getDocObjectById(unitId, this._renderManagerService);
- }
-
private _commandExecutedListener() {
const updateCommandList = [SetDocZoomRatioOperation.id];
@@ -238,9 +178,13 @@ export class TextSelectionController extends Disposable {
);
this._textSelectionManagerService.setCurrentSelectionNotRefresh({
- pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
unitId,
+ subUnitId: '',
});
});
}
+
+ private _getDocObjectById(unitId: string) {
+ return getDocObjectById(unitId, this._renderManagerService);
+ }
}
diff --git a/packages/docs/src/services/text-selection-manager.service.ts b/packages/docs/src/services/text-selection-manager.service.ts
index 2f196467cc..d6be8bac18 100644
--- a/packages/docs/src/services/text-selection-manager.service.ts
+++ b/packages/docs/src/services/text-selection-manager.service.ts
@@ -14,42 +14,70 @@
* limitations under the License.
*/
-import type { ISelectionCell, Nullable } from '@univerjs/core';
-import type { ITextRangeWithStyle, TextRange } from '@univerjs/engine-render';
-import type { IDisposable } from '@wendellhu/redi';
-import { BehaviorSubject } from 'rxjs';
-
-import { NORMAL_TEXT_SELECTION_PLUGIN_NAME } from '../basics/docs-view-key';
-
-export interface ITextSelectionManagerSearchParam {
- pluginName: string;
+import type { Nullable } from '@univerjs/core';
+import { ICommandService, RxDisposable } from '@univerjs/core';
+import type {
+ ISuccinctTextRangeParam,
+ ITextRangeWithStyle,
+ ITextSelectionInnerParam,
+ TextRange,
+} from '@univerjs/engine-render';
+import { ITextSelectionRenderManager, NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '@univerjs/engine-render';
+import { BehaviorSubject, takeUntil } from 'rxjs';
+
+import { SetTextSelectionsOperation } from '../commands/operations/text-selection.operation';
+
+interface ITextSelectionManagerSearchParam {
unitId: string;
+ subUnitId: string;
}
-export interface ITextSelectionManagerInsertParam extends ITextSelectionManagerSearchParam {
- textRanges: TextRange[];
-}
+interface ITextSelectionManagerInsertParam extends ITextSelectionManagerSearchParam, ITextSelectionInnerParam {}
+
+type ITextSelectionInfo = Map<string, Map<string, ITextSelectionInnerParam>>;
+
+function serializeTextRange(textRange: TextRange): ITextRangeWithStyle {
+ const { startOffset, endOffset, collapsed } = textRange;
-export type ITextSelectionInfo = Map<string, Map<string, TextRange[]>>;
+ return {
+ startOffset: startOffset!,
+ endOffset: endOffset!,
+ collapsed,
+ };
+}
/**
- * This service is for selection.
+ * This service is for text selection.
*/
-export class TextSelectionManagerService implements IDisposable {
+export class TextSelectionManagerService extends RxDisposable {
+ private _currentSelection: Nullable<ITextSelectionManagerSearchParam> = null;
+
private readonly _textSelectionInfo: ITextSelectionInfo = new Map();
- private _currentSelection: Nullable<ITextSelectionManagerSearchParam> = null;
+ private readonly _textSelection$ = new BehaviorSubject<Nullable<ITextSelectionManagerInsertParam>>(null);
- private readonly _textSelectionInfo$ = new BehaviorSubject<Nullable<ITextRangeWithStyle[]>>(null);
+ readonly textSelection$ = this._textSelection$.asObservable();
- readonly textSelectionInfo$ = this._textSelectionInfo$.asObservable();
+ constructor(
+ @ITextSelectionRenderManager private _textSelectionRenderManager: ITextSelectionRenderManager,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._syncSelectionFromRenderService();
+ }
getCurrentSelection() {
return this._currentSelection;
}
- dispose(): void {
- this._textSelectionInfo$.complete();
+ // Get textRanges, style, segmentId
+ getCurrentSelectionInfo() {
+ return this._getTextRanges(this._currentSelection);
+ }
+
+ override dispose(): void {
+ this._textSelection$.complete();
}
refreshSelection() {
@@ -60,6 +88,7 @@ export class TextSelectionManagerService implements IDisposable {
this._refresh(this._currentSelection);
}
+ // **Only used in test case** because this does not go through the render layer.
setCurrentSelection(param: ITextSelectionManagerSearchParam) {
this._currentSelection = param;
this._refresh(param);
@@ -69,121 +98,102 @@ export class TextSelectionManagerService implements IDisposable {
this._currentSelection = param;
}
- getTextSelectionInfo(): Readonly<ITextSelectionInfo> {
- return this._textSelectionInfo;
- }
-
- getTextRangesByParam(param: Nullable<ITextSelectionManagerSearchParam>): Readonly<Nullable<TextRange[]>> {
- return this._getTextRanges(param);
- }
-
getSelections(): Readonly<Nullable<TextRange[]>> {
- return this._getTextRanges(this._currentSelection);
+ return this._getTextRanges(this._currentSelection)?.textRanges;
}
- getFirst(): Readonly<Nullable<TextRange>> {
- return this._getFirstByParam(this._currentSelection);
- }
+ getActiveRange() {
+ const selectionInfo = this._getTextRanges(this._currentSelection);
+ if (selectionInfo == null) {
+ return;
+ }
- getLast(): Readonly<Nullable<TextRange & { primary: ISelectionCell }>> {
- // The last selection position must have a primary.
- return this._getLastByParam(this._currentSelection) as Readonly<
- Nullable<TextRange & { primary: ISelectionCell }>
- >;
- }
+ const { textRanges, segmentId, style } = selectionInfo;
+ const activeTextRange = textRanges.find((textRange) => textRange.isActive());
- // Only used in tests.
- add(textRanges: ITextRangeWithStyle[]) {
- if (this._currentSelection == null) {
- return;
+ if (activeTextRange == null) {
+ return null;
}
- this._addByParam({
- ...this._currentSelection,
- textRanges: textRanges as TextRange[],
- });
- }
- replaceTextRanges(textRanges: ITextRangeWithStyle[]) {
- if (this._currentSelection == null) {
- return;
+ const { startOffset, endOffset, collapsed, startNodePosition, endNodePosition, direction } = activeTextRange;
+
+ if (startOffset == null || endOffset == null) {
+ return null;
}
- this._textSelectionInfo$.next(textRanges);
+ return {
+ startOffset,
+ endOffset,
+ collapsed,
+ startNodePosition,
+ endNodePosition,
+ direction,
+ segmentId,
+ style,
+ };
}
- replaceTextRangesWithNoRefresh(textRanges: TextRange[]) {
+ // **Only used in test case** because this does not go through the render layer.
+ add(textRanges: ISuccinctTextRangeParam[]) {
if (this._currentSelection == null) {
return;
}
- this._replaceByParam({
+ this._addByParam({
...this._currentSelection,
- textRanges,
+ textRanges: textRanges as TextRange[],
+ segmentId: '',
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE, // mock style.
});
}
- private _addByParam(insertParam: ITextSelectionManagerInsertParam): void {
- const { pluginName, unitId, textRanges } = insertParam;
-
- if (!this._textSelectionInfo.has(pluginName)) {
- this._textSelectionInfo.set(pluginName, new Map());
- }
-
- const unitTextRange = this._textSelectionInfo.get(pluginName)!;
-
- if (!unitTextRange.has(unitId)) {
- unitTextRange.set(unitId, [...textRanges]);
- } else {
- const OldTextRanges = unitTextRange.get(unitId)!;
- OldTextRanges.push(...textRanges);
- }
-
- this._refresh({ pluginName, unitId });
- }
-
- // It is will being opened when it needs to be used
- private _clear(): void {
+ replaceTextRanges(textRanges: ISuccinctTextRangeParam[]) {
if (this._currentSelection == null) {
return;
}
- this._clearByParam(this._currentSelection);
+ // Remove all textRanges.
+ this._textSelectionRenderManager.removeAllTextRanges();
+ this._textSelectionRenderManager.addTextRanges(textRanges);
}
- // It is will being opened when it needs to be used
- private _remove(index: number): void {
- if (this._currentSelection == null) {
- return;
- }
+ // All textRanges should be synchronized from the render layer.
+ private _syncSelectionFromRenderService() {
+ this._textSelectionRenderManager.textSelectionInner$.pipe(takeUntil(this.dispose$)).subscribe((params) => {
+ if (params == null) {
+ return;
+ }
- this._removeByParam(index, this._currentSelection);
+ this._replaceTextRangesWithNoRefresh(params);
+ });
}
- // It is will being opened when it needs to be used
- private _reset() {
+ private _replaceTextRangesWithNoRefresh(textSelectionInfo: ITextSelectionInnerParam) {
if (this._currentSelection == null) {
return;
}
- this._currentSelection = {
- pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
- unitId: this._currentSelection?.unitId,
+ const params = {
+ ...this._currentSelection,
+ ...textSelectionInfo,
};
- this._textSelectionInfo.clear();
+ // Store the textSelectionInfo.
+ this._replaceByParam(params);
- this._refresh(this._currentSelection);
- }
-
- // It is will being opened when it needs to be used
- private _resetPlugin() {
- if (this._currentSelection == null) {
- return;
- }
+ // Broadcast textSelection changes, this should be used within the application.
+ this._textSelection$.next(params);
- this._currentSelection.pluginName = NORMAL_TEXT_SELECTION_PLUGIN_NAME;
+ const { unitId, subUnitId, segmentId, style, textRanges } = params;
- this._refresh(this._currentSelection);
+ // For live share only.
+ this._commandService.executeCommand(SetTextSelectionsOperation.id, {
+ unitId,
+ subUnitId,
+ segmentId,
+ style,
+ ranges: textRanges.map(serializeTextRange),
+ });
}
private _getTextRanges(param: Nullable<ITextSelectionManagerSearchParam>) {
@@ -191,68 +201,52 @@ export class TextSelectionManagerService implements IDisposable {
return;
}
- const { pluginName, unitId } = param;
+ const { unitId, subUnitId = '' } = param;
- return this._textSelectionInfo.get(pluginName)?.get(unitId);
+ return this._textSelectionInfo.get(unitId)?.get(subUnitId);
}
private _refresh(param: ITextSelectionManagerSearchParam): void {
- const allTextRanges = this._getTextRanges(param) ?? [];
-
- this._textSelectionInfo$.next(
- allTextRanges.map((textRange) => {
- const startOffset = textRange.startOffset!;
- const endOffset = textRange.endOffset!;
- const collapsed = textRange.collapsed!;
- const style = textRange.style!;
-
- return {
- startOffset,
- endOffset,
- collapsed,
- style,
- };
- })
- );
- }
+ const allTextSelectionInfo = this._getTextRanges(param);
- private _getFirstByParam(param: Nullable<ITextSelectionManagerSearchParam>): Readonly<Nullable<TextRange>> {
- const textRange = this._getTextRanges(param);
+ // Remove all textRanges.
+ this._textSelectionRenderManager.removeAllTextRanges();
- return textRange?.[0];
- }
-
- private _getLastByParam(param: Nullable<ITextSelectionManagerSearchParam>): Readonly<Nullable<TextRange>> {
- const textRange = this._getTextRanges(param);
-
- return textRange?.[textRange.length - 1];
+ if (
+ allTextSelectionInfo &&
+ Array.isArray(allTextSelectionInfo.textRanges) &&
+ allTextSelectionInfo.textRanges.length
+ ) {
+ this._textSelectionRenderManager.addTextRanges(allTextSelectionInfo.textRanges.map(serializeTextRange));
+ }
}
private _replaceByParam(insertParam: ITextSelectionManagerInsertParam) {
- const { pluginName, unitId, textRanges } = insertParam;
+ const { unitId, subUnitId, style, segmentId, textRanges } = insertParam;
- if (!this._textSelectionInfo.has(pluginName)) {
- this._textSelectionInfo.set(pluginName, new Map());
+ if (!this._textSelectionInfo.has(unitId)) {
+ this._textSelectionInfo.set(unitId, new Map());
}
- const unitTextRange = this._textSelectionInfo.get(pluginName)!;
+ const unitTextRange = this._textSelectionInfo.get(unitId)!;
- unitTextRange.set(unitId, textRanges);
+ unitTextRange.set(subUnitId, { textRanges, style, segmentId });
}
- private _clearByParam(param: ITextSelectionManagerSearchParam): void {
- const textRange = this._getTextRanges(param);
-
- textRange?.splice(0);
-
- this._refresh(param);
- }
+ private _addByParam(insertParam: ITextSelectionManagerInsertParam): void {
+ const { unitId, subUnitId, textRanges, style, segmentId } = insertParam;
- private _removeByParam(index: number, param: ITextSelectionManagerSearchParam): void {
- const textRange = this._getTextRanges(param);
+ if (!this._textSelectionInfo.has(unitId)) {
+ this._textSelectionInfo.set(unitId, new Map());
+ }
- textRange?.splice(index, 1);
+ const unitTextRange = this._textSelectionInfo.get(unitId)!;
- this._refresh(param);
+ if (!unitTextRange.has(subUnitId)) {
+ unitTextRange.set(subUnitId, { textRanges, style, segmentId });
+ } else {
+ const OldTextRanges = unitTextRange.get(subUnitId)!;
+ OldTextRanges.textRanges.push(...textRanges);
+ }
}
}
diff --git a/packages/engine-render/src/basics/range.ts b/packages/engine-render/src/basics/range.ts
index c916379470..5dabfe74fe 100644
--- a/packages/engine-render/src/basics/range.ts
+++ b/packages/engine-render/src/basics/range.ts
@@ -34,6 +34,13 @@ export interface ITextRangeWithStyle extends ITextRangeParam {
style?: ITextSelectionStyle;
}
+// Only use in add/replaceTextRanges methods.
+export interface ISuccinctTextRangeParam {
+ startOffset: number;
+ endOffset: number;
+ style?: ITextSelectionStyle;
+}
+
export enum RANGE_DIRECTION {
NONE = 'none',
BACKWARD = 'backward',
diff --git a/packages/engine-render/src/components/docs/common/range.ts b/packages/engine-render/src/components/docs/common/range.ts
index 44a5fba12a..86a50a09e5 100644
--- a/packages/engine-render/src/components/docs/common/range.ts
+++ b/packages/engine-render/src/components/docs/common/range.ts
@@ -19,7 +19,7 @@ import { Tools } from '@univerjs/core';
import { COLORS } from '../../../basics/const';
import type { INodePosition } from '../../../basics/interfaces';
-import type { ITextRangeWithStyle, ITextSelectionStyle } from '../../../basics/range';
+import type { ISuccinctTextRangeParam, ITextSelectionStyle } from '../../../basics/range';
import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RANGE_DIRECTION } from '../../../basics/range';
import { getColor } from '../../../basics/tools';
import type { IPoint } from '../../../basics/vector2';
@@ -45,7 +45,7 @@ const ID_LENGTH = 6;
export function cursorConvertToTextRange(
scene: Scene,
- range: ITextRangeWithStyle,
+ range: ISuccinctTextRangeParam,
docSkeleton: DocumentSkeleton,
documentOffsetConfig: IDocumentOffsetConfig
): Nullable<TextRange> {
diff --git a/packages/engine-render/src/components/docs/text-selection-render-manager.ts b/packages/engine-render/src/components/docs/text-selection-render-manager.ts
index 4dbc487fe6..939ba9c1df 100644
--- a/packages/engine-render/src/components/docs/text-selection-render-manager.ts
+++ b/packages/engine-render/src/components/docs/text-selection-render-manager.ts
@@ -22,11 +22,16 @@ import { BehaviorSubject } from 'rxjs';
import { CURSOR_TYPE } from '../../basics/const';
import type { IDocumentSkeletonSpan } from '../../basics/i-document-skeleton-cached';
-import { PageLayoutType, SpanType } from '../../basics/i-document-skeleton-cached';
+import { PageLayoutType } from '../../basics/i-document-skeleton-cached';
import type { IMouseEvent, IPointerEvent } from '../../basics/i-events';
import type { INodeInfo, INodePosition } from '../../basics/interfaces';
import { getOffsetRectForDom, transformBoundingCoord } from '../../basics/position';
-import type { ITextRangeWithStyle, ITextSelectionStyle, RANGE_DIRECTION } from '../../basics/range';
+import type {
+ ISuccinctTextRangeParam,
+ ITextRangeWithStyle,
+ ITextSelectionStyle,
+ RANGE_DIRECTION,
+} from '../../basics/range';
import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '../../basics/range';
import { getCurrentScrollXY } from '../../basics/scroll-xy';
import { checkStyle, injectStyle } from '../../basics/tools';
@@ -82,11 +87,7 @@ function getParagraphInfoBySpan(node: IDocumentSkeletonSpan) {
hasFound = true;
}
- if (span.spanType === SpanType.LIST) {
- continue;
- }
-
- content += span.content;
+ content += span.count > 0 ? span.content : '';
}
}
}
@@ -105,6 +106,23 @@ interface IAddTextRangesConfig {
documentOffsetConfig: IDocumentOffsetConfig;
}
+export interface ITextSelectionInnerParam {
+ textRanges: TextRange[];
+ segmentId: string;
+ style: ITextSelectionStyle;
+}
+
+export interface IActiveTextRange {
+ startOffset: number;
+ endOffset: number;
+ collapsed: boolean;
+ startNodePosition: Nullable<INodePosition>;
+ endNodePosition: Nullable<INodePosition>;
+ direction: RANGE_DIRECTION;
+ segmentId: string;
+ style: ITextSelectionStyle;
+}
+
export interface ITextSelectionRenderManager {
readonly onInputBefore$: Observable<Nullable<IEditorInputConfig>>;
readonly onKeydown$: Observable<Nullable<IEditorInputConfig>>;
@@ -114,8 +132,7 @@ export interface ITextSelectionRenderManager {
readonly onCompositionend$: Observable<Nullable<IEditorInputConfig>>;
readonly onSelectionStart$: Observable<Nullable<INodePosition>>;
readonly onPaste$: Observable<Nullable<IEditorInputConfig>>;
-
- readonly textSelection$: Observable<TextRange[]>;
+ readonly textSelectionInner$: Observable<Nullable<ITextSelectionInnerParam>>;
getViewPort(): Viewport;
@@ -129,11 +146,9 @@ export interface ITextSelectionRenderManager {
resetStyle(): void;
- getAllTextRanges(): TextRange[];
-
removeAllTextRanges(): void;
- addTextRanges(ranges: ITextRangeWithStyle[], config?: IAddTextRangesConfig): void;
+ addTextRanges(ranges: ISuccinctTextRangeParam[], config?: IAddTextRangesConfig): void;
sync(): void;
@@ -154,14 +169,6 @@ export interface ITextSelectionRenderManager {
dispose(): void;
- getActiveRange(): Nullable<
- ITextRangeWithStyle & {
- startNodePosition: Nullable<INodePosition>;
- endNodePosition: Nullable<INodePosition>;
- direction: RANGE_DIRECTION;
- }
- >;
-
handleDblClick(
evt: IPointerEvent | IMouseEvent,
documentOffsetConfig: IDocumentOffsetConfig,
@@ -233,9 +240,9 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
readonly onPaste$ = this._onPaste$.asObservable();
- private readonly _textSelection$ = new BehaviorSubject<TextRange[]>([]);
+ private readonly _textSelectionInner$ = new BehaviorSubject<Nullable<ITextSelectionInnerParam>>(null);
- readonly textSelection$ = this._textSelection$.asObservable();
+ readonly textSelectionInner$ = this._textSelectionInner$.asObservable();
private _container!: HTMLDivElement;
@@ -322,54 +329,20 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this._isSelectionEnabled = false;
}
- getActiveRange() {
- const activeRange = this._rangeList.find((range) => range.isActive());
-
- if (activeRange == null) {
- return null;
- }
-
- const { startOffset, endOffset, collapsed, startNodePosition, endNodePosition, direction } = activeRange;
-
- if (startOffset == null || endOffset == null) {
- return null;
- }
-
- return {
- startOffset,
- endOffset,
- collapsed,
- startNodePosition,
- endNodePosition,
- direction,
- segmentId: this._currentSegmentId,
- style: this._selectionStyle,
- };
- }
-
- getAllTextRanges() {
- return this._rangeList;
- }
-
- addTextRanges(ranges: ITextRangeWithStyle[], config?: IAddTextRangesConfig) {
- if (config != null) {
- const { scene, skeleton, documentOffsetConfig } = config;
-
- this.changeRuntime(skeleton, scene, null, documentOffsetConfig);
- }
+ addTextRanges(ranges: ISuccinctTextRangeParam[]) {
+ const { _scene: scene, _docSkeleton: docSkeleton, _documentOffsetConfig: documentOffsetConfig } = this;
for (const range of ranges) {
- const textSelection = cursorConvertToTextRange(
- this._scene!,
- range,
- this._docSkeleton!,
- this._documentOffsetConfig
- );
+ const textSelection = cursorConvertToTextRange(scene!, range, docSkeleton!, documentOffsetConfig);
this._add(textSelection);
}
- this._textSelection$.next(this.getAllTextRanges());
+ this._textSelectionInner$.next({
+ textRanges: this._getAllTextRanges(),
+ segmentId: this._currentSegmentId,
+ style: this._selectionStyle,
+ });
this._syncDomToSelection();
@@ -494,11 +467,10 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
if (Number.isFinite(startOffset) && Number.isFinite(endOffset)) {
this.removeAllTextRanges();
- const textRanges: ITextRangeWithStyle[] = [
+ const textRanges = [
{
startOffset,
endOffset,
- collapsed: startOffset === endOffset,
},
];
@@ -629,13 +601,17 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
preMoveOffsetY = moveOffsetY;
});
- this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
+ this._upObserver = scene.onPointerUpObserver.add(() => {
scene.onPointerMoveObserver.remove(this._moveObserver);
scene.onPointerUpObserver.remove(this._upObserver);
scene.enableEvent();
- this._textSelection$.next(this.getAllTextRanges());
+ this._textSelectionInner$.next({
+ textRanges: this._getAllTextRanges(),
+ segmentId: this._currentSegmentId,
+ style: this._selectionStyle,
+ });
scrollTimer.dispose();
this._syncDomToSelection();
@@ -647,6 +623,35 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this.deactivate();
}
+ private _getAllTextRanges() {
+ return this._rangeList;
+ }
+
+ private _getActiveRange(): Nullable<IActiveTextRange> {
+ const activeRange = this._rangeList.find((range) => range.isActive());
+
+ if (activeRange == null) {
+ return null;
+ }
+
+ const { startOffset, endOffset, collapsed, startNodePosition, endNodePosition, direction } = activeRange;
+
+ if (startOffset == null || endOffset == null) {
+ return null;
+ }
+
+ return {
+ startOffset,
+ endOffset,
+ collapsed,
+ startNodePosition,
+ endNodePosition,
+ direction,
+ segmentId: this._currentSegmentId,
+ style: this._selectionStyle,
+ };
+ }
+
private _add(textRange: Nullable<TextRange>) {
if (textRange == null) {
return;
@@ -1103,8 +1108,8 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this._input.innerHTML = '';
- const activeRange = this.getActiveRange();
- const rangeList = this.getAllTextRanges();
+ const activeRange = this._getActiveRange();
+ const rangeList = this._getAllTextRanges();
func({
event: e,
diff --git a/packages/sheets-formula/src/controllers/formula-input.controller.ts b/packages/sheets-formula/src/controllers/formula-input.controller.ts
index 25d8f60b5b..0b05aeaab9 100644
--- a/packages/sheets-formula/src/controllers/formula-input.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-input.controller.ts
@@ -25,6 +25,7 @@ import {
serializeRange,
toDisposable,
} from '@univerjs/core';
+import { TextSelectionManagerService } from '@univerjs/docs';
import { LexerTreeBuilder, matchToken, sequenceNodeType } from '@univerjs/engine-formula';
import { DeviceInputEventType, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';
import type { EditorBridgeService } from '@univerjs/sheets-ui';
@@ -45,7 +46,8 @@ export class FormulaInputController extends Disposable {
@Inject(IEditorBridgeService) private readonly _editorBridgeService: EditorBridgeService,
@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @IFormulaInputService private readonly _formulaInputService: IFormulaInputService
+ @IFormulaInputService private readonly _formulaInputService: IFormulaInputService,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
) {
super();
@@ -118,7 +120,7 @@ export class FormulaInputController extends Disposable {
}
private _changeRefString() {
- const activeRange = this._textSelectionRenderManager.getActiveRange();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
if (activeRange == null) {
return;
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index 81500d91d9..b00919fafa 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -28,7 +28,6 @@ import {
isFormulaString,
IUniverInstanceService,
LifecycleStages,
- LocaleService,
OnLifecycle,
serializeRangeToRefString,
ThemeService,
@@ -139,7 +138,6 @@ export class PromptController extends Disposable {
constructor(
@ICommandService private readonly _commandService: ICommandService,
- @Inject(LocaleService) private readonly _localeService: LocaleService,
@IContextService private readonly _contextService: IContextService,
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(IEditorBridgeService) private readonly _editorBridgeService: EditorBridgeService,
@@ -230,7 +228,7 @@ export class PromptController extends Disposable {
private _initialCursorSync() {
this.disposeWithMe(
toDisposable(
- this._textSelectionRenderManager.textSelection$.subscribe(() => {
+ this._textSelectionManagerService.textSelection$.subscribe(() => {
if (
this._editorBridgeService.isVisible().visible === false ||
this._formulaInputService.isSelectionMoving()
@@ -465,7 +463,7 @@ export class PromptController extends Disposable {
this.disposeWithMe(
toDisposable(
this._formulaPromptService.acceptFormulaName$.subscribe((formulaString: string) => {
- const activeRange = this._textSelectionRenderManager.getActiveRange();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
if (activeRange == null) {
this._hideFunctionPanel();
@@ -527,7 +525,7 @@ export class PromptController extends Disposable {
}
private _changeFunctionPanelState() {
- const activeRange = this._textSelectionRenderManager.getActiveRange();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
if (activeRange == null) {
this._hideFunctionPanel();
@@ -662,7 +660,7 @@ export class PromptController extends Disposable {
* @returns Return the character under the current cursor in the editor.
*/
private _getCurrentChar() {
- const activeRange = this._textSelectionRenderManager.getActiveRange();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
if (activeRange == null) {
return;
@@ -734,7 +732,7 @@ export class PromptController extends Disposable {
this._formulaInputService.setSequenceNodes(lastSequenceNodes);
- const activeRange = this._textSelectionRenderManager.getActiveRange();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
if (activeRange == null) {
return;
@@ -1102,7 +1100,7 @@ export class PromptController extends Disposable {
this._isSelectionMovingRefSelections = refSelections;
- const activeRange = this._textSelectionManagerService.getLast();
+ const activeRange = this._textSelectionManagerService.getActiveRange();
if (activeRange == null) {
return;
@@ -1137,7 +1135,6 @@ export class PromptController extends Disposable {
{
startOffset: textSelectionOffset + 1,
endOffset: textSelectionOffset + 1,
- collapsed,
style,
},
]);
diff --git a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
index b215114383..343624d028 100644
--- a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
@@ -30,17 +30,15 @@ import {
RxDisposable,
toDisposable,
} from '@univerjs/core';
-import type { IRichTextEditingMutationParams, ISetTextSelectionsOperationParams } from '@univerjs/docs';
+import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import {
CoverContentCommand,
DocSkeletonManagerService,
DocViewModelManagerService,
RichTextEditingMutation,
- SetTextSelectionsOperation,
TextSelectionManagerService,
VIEWPORT_KEY,
} from '@univerjs/docs';
-import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { DeviceInputEventType, IRenderManagerService, ScrollBar } from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
import { takeUntil } from 'rxjs';
@@ -88,6 +86,18 @@ export class FormulaEditorController extends RxDisposable {
this._loadedMap.add(unitId);
}
});
+
+ this._textSelectionManagerService.textSelection$.pipe(takeUntil(this.dispose$)).subscribe((param) => {
+ if (param == null) {
+ return;
+ }
+ const { unitId } = param;
+ // Mark formula editor as non-focused, when current selection is not in formula editor.
+ if (unitId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+ this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, false);
+ this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+ }
+ });
}
private _listenFxBtnClick() {
@@ -123,11 +133,10 @@ export class FormulaEditorController extends RxDisposable {
newContent = newContent.replace(/\r\n$/, '');
- const textRanges: ITextRangeWithStyle[] = [
+ const textRanges = [
{
startOffset: newContent.length,
endOffset: newContent.length,
- collapsed: true,
},
];
@@ -295,15 +304,6 @@ export class FormulaEditorController extends RxDisposable {
this._autoScroll();
}
}
-
- // Mark formula editor as non-focused, when current selection is not in formula editor.
- if (command.id === SetTextSelectionsOperation.id) {
- const { unitId } = command.params as ISetTextSelectionsOperationParams;
- if (unitId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
- this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, false);
- this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
- }
- }
})
);
}
diff --git a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
index 75329e2049..384aa8c67f 100644
--- a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
@@ -192,7 +192,6 @@ export class StartEditController extends Disposable {
{
startOffset: 0,
endOffset: 0,
- collapsed: true,
},
]);
@@ -513,7 +512,6 @@ export class StartEditController extends Disposable {
{
startOffset: 0,
endOffset: 0,
- collapsed: true,
},
]);
} else if (eventType === DeviceInputEventType.Dblclick) {
@@ -528,7 +526,6 @@ export class StartEditController extends Disposable {
{
startOffset: cursor,
endOffset: cursor,
- collapsed: true,
},
]);
}