Skip to content

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

fix(sheets-ui): select editable cell content on double-click (#7774)

白熱20e13ed3db8b
diff --git a/packages/docs-ui/src/commands/commands/__tests__/clipboard.inner.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/clipboard.inner.command.spec.ts
index 5c26f5794d..07a2f12daa 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/clipboard.inner.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/clipboard.inner.command.spec.ts
@@ -21,6 +21,7 @@ import {
DocumentFlavor,
HorizontalAlign,
ICommandService,
+ Injector,
IUniverInstanceService,
JSONX,
RedoCommand,
@@ -33,6 +34,7 @@ import {
DocSelectionManagerService,
DocStateChangeManagerService,
DocStateEmitService,
+ InsertTextCommand,
RichTextEditingMutation,
} from '@univerjs/docs';
import {
@@ -42,12 +44,14 @@ import {
RenderManagerService,
} from '@univerjs/engine-render';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
import { createInternalClipboardDocData } from '../../../services/clipboard/internal-fragment';
import { getCutActionsFromDocRanges, InnerPasteCommand } from '../clipboard.inner.command';
describe('getCutActionsFromDocRanges', () => {
it.each([false, true])('keeps formatting only for embedded-editor clearing (%s), with reversible actions', (preserveFormatting) => {
- const model = new DocumentDataModel({
+ const injector = new Injector();
+ const model = injector.createInstance(DocumentDataModel, {
id: 'shape-text',
body: {
dataStream: 'AB\rCD\r\n',
@@ -66,7 +70,7 @@ describe('getCutActionsFromDocRanges', () => {
[{ startOffset: 0, endOffset: 6, collapsed: false }],
[],
model,
- new DocumentViewModel(model),
+ injector.createInstance(DocumentViewModel, model),
'',
true,
preserveFormatting
@@ -82,6 +86,7 @@ describe('getCutActionsFromDocRanges', () => {
model.apply(actions);
expect(model.getSnapshot()).toEqual(cleared);
model.dispose();
+ injector.dispose();
});
});
@@ -103,7 +108,7 @@ const SOURCE: IDocumentData = {
},
};
-describe('InnerPasteCommand notes', () => {
+describe('InnerPasteCommand', () => {
let univer: Univer;
let document: DocumentDataModel;
let commands: ICommandService;
@@ -117,7 +122,7 @@ describe('InnerPasteCommand notes', () => {
injector.add([DocStateChangeManagerService]);
injector.get(DocStateChangeManagerService);
commands = injector.get(ICommandService);
- [InnerPasteCommand, RichTextEditingMutation].forEach((command) => commands.registerCommand(command));
+ [InnerPasteCommand, InsertTextCommand, RichTextEditingMutation].forEach((command) => commands.registerCommand(command));
document = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
id: 'target',
documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
@@ -166,6 +171,45 @@ describe('InnerPasteCommand notes', () => {
expect(SOURCE.notes!.note.body.paragraphs![0].paragraphId).toBe('source-paragraph');
});
+ it('can replace an explicit range while undo restores the original selection', () => {
+ document.reset({
+ ...document.getSnapshot(),
+ body: {
+ dataStream: '25%\r\n',
+ paragraphs: [{ startIndex: 3, paragraphId: 'target-paragraph' }],
+ sectionBreaks: [{ startIndex: 4, sectionId: 'target-section' }],
+ },
+ });
+ selections.replaceSelectionInfoWithoutRefresh({
+ textRanges: [{ startOffset: 0, endOffset: 2, collapsed: false, isActive: true }],
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: -1,
+ isEditing: true,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ });
+ commands.syncExecuteCommand(InnerPasteCommand.id, {
+ unitId: 'target',
+ doc: { body: { dataStream: '7%' } },
+ segmentId: '',
+ selections: [{ startOffset: 0, endOffset: 3, collapsed: false }],
+ textRanges: [{ startOffset: 2, endOffset: 2, collapsed: true }],
+ });
+ expect(document.getBody()?.dataStream).toBe('7%\r\n');
+
+ commands.syncExecuteCommand(UndoCommand.id);
+ expect(document.getBody()?.dataStream).toBe('25%\r\n');
+ commands.syncExecuteCommand(RedoCommand.id);
+ expect(document.getBody()?.dataStream).toBe('7%\r\n');
+ commands.syncExecuteCommand(UndoCommand.id);
+ commands.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: 'target',
+ body: { dataStream: '3' },
+ range: selections.getActiveTextRange(),
+ });
+ expect(document.getBody()?.dataStream).toBe('3%\r\n');
+ });
+
it('drops references in modern mode and adjusts following text styles', async () => {
document.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
expect(await paste(0)).toBe(true);
diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
index 013e28abb7..dc47703a20 100644
--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
@@ -59,6 +59,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
+
import { getCustomDecorationAtPosition, getCustomRangeAtPosition } from '../../basics/paragraph';
import {
IDocClipboardPasteAdapterService,
@@ -80,6 +81,8 @@ export interface IInnerPasteCommandParams {
unitId?: string;
segmentId: string;
doc: Partial<IDocumentData>;
+ /** Ranges to replace, without changing the selection recorded for undo. */
+ selections?: ITextRangeWithStyle[];
textRanges: ITextRangeWithStyle[];
customRangeMappings?: IDocClipboardPasteCustomRangeMapping[];
}
@@ -110,7 +113,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
? currentSelection
: { unitId: targetUnitId, subUnitId: targetUnitId };
}
- const selections = docSelectionManagerService.getTextRanges(selectionParams) ?? [];
+ const selections = params.selections ?? docSelectionManagerService.getTextRanges(selectionParams) ?? [];
const rectRanges = docSelectionManagerService.getRectRanges(selectionParams) ?? [];
const selectionInfo = docSelectionManagerService.getSelectionInfo(selectionParams);
const { body: sourceBody, tableSource, drawings } = doc;
diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
index 25008f34a7..377af971c7 100644
--- a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
@@ -1864,46 +1864,42 @@ describe('DocSelectionRenderService', () => {
pageMarginTop: 0,
}),
};
- const { renderUnit, service, univer } = createRealSelectionRenderService({ mainComponent, scene });
+ const { renderUnit, service, univer } = createRealSelectionRenderService({
+ mainComponent,
+ scene,
+ documentData: {
+ id: 'word-selection-doc',
+ body: { dataStream: 'Hello world\r\n', paragraphs: [{ startIndex: 11, paragraphId: 'word-selection-paragraph' }] },
+ documentStyle: {},
+ },
+ });
cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
const column = { lines: [] as unknown[] };
- const line = { paragraphIndex: 5, st: 0, parent: column, divides: [] as unknown[] };
+ const line = { paragraphIndex: 11, st: 0, parent: column, divides: [] as unknown[] };
const divide = { parent: line, glyphGroup: [] as Array<{ content: string; count: number; glyphType: GlyphType; parent?: unknown }> };
const glyphs: Array<{ content: string; count: number; glyphType: GlyphType; parent?: unknown }> = [];
- for (const content of ['H', 'e', 'l', 'l', 'o']) {
+ for (const content of 'Hello world') {
glyphs.push({ content, count: 1, glyphType: GlyphType.WORD, parent: divide });
}
divide.glyphGroup = glyphs;
line.divides = [divide];
column.lines = [line];
- (service as unknown as { _findNodeByCoord: () => unknown })._findNodeByCoord = () => ({ node: glyphs[1], ratioX: 0.4, segmentPage: -1 });
- const wordRange = {
- ...createTextRange({ isActive: vi.fn(() => true) }),
- startOffset: 0,
- endOffset: 5,
- collapsed: false,
- rangeType: DOC_RANGE_TYPE.TEXT,
- segmentId: '',
- segmentPage: -1,
- direction: 'forward',
- startNodePosition: null,
- endNodePosition: null,
- };
- const paragraphRange = {
- ...createTextRange({ isActive: vi.fn(() => true) }),
- startOffset: 0,
- endOffset: 5,
- collapsed: false,
- rangeType: DOC_RANGE_TYPE.TEXT,
- segmentId: '',
- segmentPage: -1,
- direction: 'forward',
- startNodePosition: null,
- endNodePosition: null,
- };
- getRangeListFromCharIndexMock
- .mockReturnValueOnce({ textRanges: [wordRange], rectRanges: [] })
- .mockReturnValueOnce({ textRanges: [paragraphRange], rectRanges: [] });
+ (service as unknown as { _findNodeByCoord: () => unknown })._findNodeByCoord = () => ({ node: glyphs[7], ratioX: 0.4, segmentPage: -1 });
+ getRangeListFromCharIndexMock.mockImplementation((startOffset, endOffset) => ({
+ textRanges: [{
+ ...createTextRange({ isActive: vi.fn(() => true) }),
+ startOffset,
+ endOffset,
+ collapsed: startOffset === endOffset,
+ rangeType: DOC_RANGE_TYPE.TEXT,
+ segmentId: '',
+ segmentPage: -1,
+ direction: 'forward',
+ startNodePosition: null,
+ endNodePosition: null,
+ }],
+ rectRanges: [],
+ }));
const selections: string[] = [];
const subscription = service.textSelectionInner$.subscribe((selection) => {
if (!selection) {
@@ -1918,7 +1914,7 @@ describe('DocSelectionRenderService', () => {
service.__handleDblClick({ offsetX: 10, offsetY: 12 } as never);
service.__handleTripleClick({ offsetX: 10, offsetY: 12 } as never);
- expect(selections).toEqual(['0:5', '0:5']);
+ expect(selections).toEqual(['6:11', '0:11']);
});
it('moves the hidden editor to the active visible selection when syncing canvas selection to DOM input', () => {
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts
deleted file mode 100644
index 203324d458..0000000000
--- a/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts
+++ /dev/null
@@ -1,599 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IDocumentBody } from '@univerjs/core';
-import {
- Direction,
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- EDITOR_ACTIVATED,
- FOCUSING_EDITOR_INPUT_FORMULA,
- FOCUSING_FX_BAR_EDITOR,
- LocaleType,
- Styles,
- UniverInstanceType,
-} from '@univerjs/core';
-import { InsertTextCommand } from '@univerjs/docs';
-import { MoveCursorOperation, MoveSelectionOperation, SetDocInputStyleCommand, VIEWPORT_KEY } from '@univerjs/docs-ui';
-import { LexerTreeBuilder } from '@univerjs/engine-formula';
-import { DeviceInputEventType } from '@univerjs/engine-render';
-import { SetRangeValuesCommand } from '@univerjs/sheets';
-import { KeyCode } from '@univerjs/ui';
-import { Subject } from 'rxjs';
-import { describe, expect, it, vi } from 'vitest';
-import {
- MoveSelectionCommand,
- MoveSelectionEnterAndTabCommand,
-} from '../../../commands/commands/set-selection.command';
-import { EditingRenderController, emptyBody } from '../editing.render-controller';
-
-describe('emptyBody', () => {
- it('keeps an empty text-run collection initialized', () => {
- const body: IDocumentBody = { dataStream: 'value\r\n', textRuns: [] };
-
- emptyBody(body);
-
- expect(body.textRuns).toEqual([]);
- });
-
- it('keeps one inherited style when resetting the editor', () => {
- const body: IDocumentBody = {
- dataStream: 'value\r\n',
- textRuns: [{ st: 0, ed: 5, ts: { fs: 11 } }],
- };
-
- emptyBody(body);
-
- expect(body.textRuns).toEqual([{ st: 0, ed: 1, ts: { fs: 11 } }]);
- });
-
- it('removes an inherited style when style removal is requested', () => {
- const body: IDocumentBody = {
- dataStream: 'value\r\n',
- textRuns: [{ st: 0, ed: 5, ts: { fs: 11 } }],
- };
-
- emptyBody(body, true);
-
- expect(body.textRuns).toBeUndefined();
- });
-});
-
-function createController(initialDataStream = 'new value\r\n', isPercentFormat = false, isInArrayFormulaRange = false) {
- const worksheet = {
- getSheetId: vi.fn(() => 'sheet-1'),
- getCellRaw: vi.fn(() => ({ v: 'old' })),
- getComposedCellStyleWithoutSelf: vi.fn(() => ({})),
- };
- const styles = new Styles();
- const workbook = {
- getUnitId: vi.fn(() => 'unit-1'),
- getActiveSheet: vi.fn(() => worksheet),
- getSheetBySheetId: vi.fn(() => worksheet),
- getStyles: vi.fn(() => styles),
- };
- let normalSnapshot = {
- body: { dataStream: initialDataStream, paragraphs: [{ startIndex: 9, paragraphId: 'normal-para' }] },
- documentStyle: {},
- };
- let formulaSnapshot = {
- body: { dataStream: initialDataStream, paragraphs: [{ startIndex: 9, paragraphId: 'formula-para' }] },
- documentStyle: {},
- };
- const docModel = {
- getUnitId: vi.fn(() => DOCS_NORMAL_EDITOR_UNIT_ID_KEY),
- getBody: vi.fn(() => normalSnapshot.body),
- getSnapshot: vi.fn(() => normalSnapshot),
- reset: vi.fn((snapshot) => {
- normalSnapshot = snapshot;
- }),
- };
- const formulaDocModel = {
- getUnitId: vi.fn(() => DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY),
- getSnapshot: vi.fn(() => formulaSnapshot),
- reset: vi.fn((snapshot) => {
- formulaSnapshot = snapshot;
- }),
- };
- const documentModel = {
- getBody: vi.fn((): IDocumentBody => ({ dataStream: 'new value\r\n' })),
- getSnapshot: vi.fn(() => ({
- body: { dataStream: 'new value\r\n' },
- documentStyle: {},
- })),
- };
- const controller = Object.create(EditingRenderController.prototype) as any;
- const formulaBarEditor = {
- setSelectionRanges: vi.fn(),
- blur: vi.fn(),
- };
- controller._editingUnit = 'unit-1';
- controller._lexerTreeBuilder = new LexerTreeBuilder();
- controller._localService = { getCurrentLocale: vi.fn(() => LocaleType.EN_US) };
- controller._functionService = { getDescriptions: vi.fn(() => ({})) };
- controller._undoRedoService = {
- rollback: vi.fn(),
- clearUndoRedo: vi.fn(),
- };
- controller._docStateChangeManagerService = {
- clearHistory: vi.fn(),
- };
- controller._contextService = {
- setContextValue: vi.fn(),
- getContextValue: vi.fn(() => false),
- };
- controller._cellEditorManagerService = { setState: vi.fn() };
- controller._sheetCellEditorResizeService = {
- fitTextSize: vi.fn((callback?: () => void) => callback?.()),
- };
- controller._editorService = {
- isSheetEditor: vi.fn(() => true),
- getEditor: vi.fn((editorId: string) => editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY ? formulaBarEditor : null),
- };
- controller._editorBridgeService = {
- getEditCellState: vi.fn(() => ({
- unitId: 'unit-1',
- sheetId: 'sheet-1',
- row: 2,
- column: 3,
- documentLayoutObject: { documentModel },
- isInArrayFormulaRange,
- isPercentFormat,
- })),
- getEditLocation: vi.fn(() => ({
- unitId: 'unit-1',
- sheetId: 'sheet-1',
- row: 2,
- column: 3,
- documentLayoutObject: { documentModel },
- isInArrayFormulaRange,
- isPercentFormat,
- })),
- getCurrentEditorId: vi.fn(() => DOCS_NORMAL_EDITOR_UNIT_ID_KEY),
- isVisible: vi.fn(() => ({ visible: true, eventType: DeviceInputEventType.Keyboard, unitId: 'unit-1' })),
- getEditorDirty: vi.fn(() => true),
- isForceKeepVisible: vi.fn(() => false),
- disableForceKeepVisible: vi.fn(),
- refreshEditCellState: vi.fn(),
- refreshEditCellPosition: vi.fn(),
- changeEditorDirty: vi.fn(),
- };
- controller._sheetInterceptorService = {
- onWriteCell: vi.fn((_workbook, _worksheet, _row, _column, cellData) => cellData),
- onValidateCell: vi.fn(() => true),
- };
- controller._commandService = {
- syncExecuteCommand: vi.fn(() => true),
- executeCommand: vi.fn(),
- };
- controller._univerInstanceService = {
- getUnit: vi.fn((unitId: string) => {
- if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
- return docModel;
- }
- if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
- return formulaDocModel;
- }
-
- return workbook;
- }),
- getCurrentUnitOfType: vi.fn(() => workbook),
- setCurrentUnitForType: vi.fn(),
- };
- controller._textSelectionManagerService = {
- replaceDocRanges: vi.fn(),
- refreshSelection: vi.fn(),
- };
- const workbookSelections = {
- getCurrentLastSelection: vi.fn(() => ({ range: { startRow: 1, startColumn: 1, endRow: 4, endColumn: 4 } })),
- getSelectionsOfWorksheet: vi.fn(() => [{ range: { startRow: 2, startColumn: 3, endRow: 2, endColumn: 3 } }]),
- };
- controller._selectionManagerService = {
- getWorkbookSelections: vi.fn(() => workbookSelections),
- };
- controller._renderManagerService = {
- getRenderUnitById: vi.fn(() => ({
- scene: {
- getViewport: vi.fn((key) => key === VIEWPORT_KEY.VIEW_MAIN
- ? { scrollToViewportPos: vi.fn() }
- : null),
- resetCursor: vi.fn(),
- },
- with: vi.fn(() => ({ resetInitialWidth: vi.fn() })),
- })),
- };
- controller._getEditorObject = vi.fn(() => ({
- document: {
- makeDirty: vi.fn(),
- },
- scene: {
- getViewport: vi.fn((key) => key === VIEWPORT_KEY.VIEW_MAIN
- ? { scrollToViewportPos: vi.fn() }
- : null),
- resetCursor: vi.fn(),
- },
- }));
- controller._getEditorSkeleton = vi.fn(() => ({ calculate: vi.fn(), resetInitialWidth: vi.fn() }));
- controller._getEditorViewModel = vi.fn(() => ({ reset: vi.fn() }));
-
- return {
- controller,
- docModel,
- formulaBarEditor,
- documentModel,
- getFormulaSnapshot: () => formulaSnapshot,
- getNormalSnapshot: () => normalSnapshot,
- workbook,
- worksheet,
- };
-}
-
-describe('EditingRenderController business methods', () => {
- it('bypasses parsing, interceptors, and commands when the editor is clean', async () => {
- const { controller, worksheet } = createController();
- controller._editorBridgeService.getEditorDirty.mockReturnValue(false);
-
- const result = await controller._submitEdit({
- body: { dataStream: 'canonical display value\r\n' },
- documentStyle: {},
- });
-
- expect(result).toBe(true);
- expect(worksheet.getCellRaw).not.toHaveBeenCalled();
- expect(controller._sheetInterceptorService.onWriteCell).not.toHaveBeenCalled();
- expect(controller._commandService.syncExecuteCommand).not.toHaveBeenCalled();
- });
-
- it('reuses an empty cell style for the next editor input', () => {
- const { controller, documentModel } = createController();
- documentModel.getBody.mockReturnValue({
- dataStream: '\r\n',
- textRuns: [{ st: 0, ed: 0, ts: { fs: 20, cl: { rgb: '#f05252' } } }],
- });
-
- controller._cacheEmptyCellTextStyle();
-
- expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDocInputStyleCommand.id, {
- style: {
- fs: 20,
- cl: { rgb: '#f05252' },
- },
- });
- });
-
- it('submits edited cell content and rolls back when validation rejects the value', async () => {
- const { controller } = createController();
- controller._sheetInterceptorService.onValidateCell.mockResolvedValue(false);
-
- const result = await controller._submitEdit({
- body: { dataStream: 'new value\r\n' },
- documentStyle: {},
- });
-
- expect(result).toBe(false);
- expect(controller._sheetInterceptorService.onWriteCell).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), 2, 3, {
- v: 'new value',
- f: null,
- si: null,
- p: null,
- });
- expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, expect.objectContaining({
- unitId: 'unit-1',
- subUnitId: 'sheet-1',
- range: { startRow: 2, startColumn: 3, endRow: 2, endColumn: 3 },
- value: { v: 'new value', f: null, si: null, p: null },
- }));
- expect(controller._undoRedoService.rollback).toHaveBeenCalledWith(expect.any(String), 'unit-1');
- });
-
- it('captures rich-text cell data independently from the reusable editor snapshot', async () => {
- const { controller } = createController();
- const snapshot = {
- body: {
- dataStream: 'rich text\r\n',
- textRuns: [{ st: 5, ed: 9, ts: { bl: 1 } }],
- },
- documentStyle: {},
- };
-
- await controller._submitEdit(snapshot);
- const submitted = controller._commandService.syncExecuteCommand.mock.calls
- .find(([id]: [string]) => id === SetRangeValuesCommand.id)?.[1];
- snapshot.body.textRuns = [];
-
- expect(submitted?.value.p).not.toBe(snapshot);
- expect(submitted?.value.p?.body?.textRuns).toEqual([{ st: 5, ed: 9, ts: { bl: 1 } }]);
- });
-
- it('uses the whole current selection when committing an array edit', async () => {
- const { controller } = createController();
-
- await controller._submitEdit({
- body: { dataStream: 'fill\r\n' },
- documentStyle: {},
- }, true);
-
- expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, expect.objectContaining({
- range: { startRow: 1, startColumn: 1, endRow: 4, endColumn: 4 },
- }));
- expect(controller._undoRedoService.rollback).not.toHaveBeenCalled();
- });
-
- it('moves sheet selection after finishing edit and switches back to the edited workbook when needed', () => {
- const { controller } = createController();
- controller._univerInstanceService.getCurrentUnitOfType.mockReturnValue({ getUnitId: () => 'other-unit' });
-
- controller._moveSelection(KeyCode.ENTER, 'unit-1', 'sheet-1');
- controller._moveSelection(KeyCode.ARROW_LEFT, 'unit-1', 'sheet-1');
- controller._moveSelection(undefined, 'unit-1', 'sheet-1');
-
- expect(controller._univerInstanceService.setCurrentUnitForType).toHaveBeenCalledWith('unit-1');
- expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionEnterAndTabCommand.id, {
- keycode: KeyCode.ENTER,
- direction: 2,
- });
- expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionCommand.id, {
- direction: 3,
- });
- expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({
- subUnitId: 'sheet-1',
- }));
- });
-
- it.each([
- ['Enter', KeyCode.ENTER, Direction.UP],
- ['Tab', KeyCode.TAB, Direction.LEFT],
- ])('moves the sheet selection in reverse after finishing edit with Shift+%s', async (_name, keycode, direction) => {
- const { controller } = createController();
- controller._editorBridgeService.getEditorDirty.mockReturnValue(false);
-
- await controller._handleEditorInvisible({
- visible: false,
- eventType: DeviceInputEventType.Keyboard,
- unitId: 'unit-1',
- keycode,
- isShift: true,
- });
-
- expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionEnterAndTabCommand.id, {
- keycode,
- direction,
- });
- });
-
- it('refreshes editor content when Esc cancels editing', async () => {
- const { controller } = createController();
-
- await controller._handleEditorInvisible({
- visible: false,
- eventType: DeviceInputEventType.Keyboard,
- unitId: 'unit-1',
- keycode: KeyCode.ESC,
- });
-
- expect(controller._editorBridgeService.refreshEditCellState).toHaveBeenCalledTimes(1);
- });
-
- it('moves the cursor inside the editor and resets editor state on exit', () => {
- const { controller, formulaBarEditor } = createController();
-
- controller._moveInEditor(KeyCode.ARROW_RIGHT, false);
- controller._moveInEditor(KeyCode.ARROW_UP, true);
- controller._exitInput({ visible: false });
-
- expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveCursorOperation.id, { direction: 1 });
- expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionOperation.id, { direction: 0 });
- expect(controller._contextService.setContextValue).toHaveBeenCalledWith(FOCUSING_EDITOR_INPUT_FORMULA, false);
- expect(controller._contextService.setContextValue).toHaveBeenCalledWith(EDITOR_ACTIVATED, false);
- expect(controller._contextService.setContextValue).toHaveBeenCalledWith(FOCUSING_FX_BAR_EDITOR, false);
- expect(controller._cellEditorManagerService.setState).toHaveBeenCalledWith({ show: false });
- expect(controller._undoRedoService.clearUndoRedo).toHaveBeenCalledWith(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
- expect(controller._undoRedoService.clearUndoRedo).toHaveBeenCalledWith(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
- expect(formulaBarEditor.setSelectionRanges).toHaveBeenCalledWith([], false);
- expect(formulaBarEditor.blur).toHaveBeenCalled();
- });
-
- it('leaves initial keyboard input to the doc input pipeline when opening the cell editor', () => {
- const { controller, getFormulaSnapshot, getNormalSnapshot } = createController();
-
- controller._handleEditorVisible({
- visible: true,
- eventType: DeviceInputEventType.Keyboard,
- keycode: 187,
- initialValue: '=',
- unitId: 'unit-1',
- });
-
- expect(getNormalSnapshot().body.dataStream).toBe('\r\n');
- expect(getFormulaSnapshot().body.dataStream).toBe('\r\n');
- expect(controller._textSelectionManagerService.replaceDocRanges).toHaveBeenCalledWith(
- [{ startOffset: 0, endOffset: 0 }],
- {
- unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- }
- );
- expect(controller._editorBridgeService.changeEditorDirty).not.toHaveBeenCalled();
- });
-
- it.each(['3', '35', '0.35', '35%'])('preserves the percent suffix when input starts with a digit: %s', (initialValue) => {
- const { controller, getFormulaSnapshot, getNormalSnapshot } = createController('25%\r\n', true);
-
- controller._handleEditorVisible({
- visible: true,
- eventType: DeviceInputEventType.Keyboard,
- keycode: KeyCode.Digit3,
- initialValue,
- unitId: 'unit-1',
- });
-
- expect(getNormalSnapshot().body.dataStream).toBe('25%\r\n');
- expect(getFormulaSnapshot().body.dataStream).toBe('25%\r\n');
- expect(controller._textSelectionManagerService.replaceDocRanges).toHaveBeenCalledWith(
- [{ startOffset: 0, endOffset: 2, collapsed: false }],
- {
- unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- }
- );
- });
-
- it.each(['$30', '=1', 'text', '+', '-', '.', ','])('replaces percent content when input does not start with a digit: %s', (initialValue) => {
- const { controller, getNormalSnapshot } = createController('25%\r\n', true);
-
- controller._handleEditorVisible({
- visible: true,
- eventType: DeviceInputEventType.Keyboard,
- keycode: KeyCode.Digit3,
- initialValue,
- unitId: 'unit-1',
- });
-
- expect(getNormalSnapshot().body.dataStream).toBe('\r\n');
- });
-
- it.each([KeyCode.BACKSPACE, KeyCode.DELETE])('keeps full-clear behavior for keycode %s', (keycode) => {
- const { controller, getNormalSnapshot } = createController('25%\r\n', true);
-
- controller._handleEditorVisible({
- visible: true,
- eventType: DeviceInputEventType.Keyboard,
- keycode,
- unitId: 'unit-1',
- });
-
- expect(getNormalSnapshot().body.dataStream).toBe('\r\n');
- });
-
- it('keeps full-clear behavior for array formula cells', () => {
- const { controller, getNormalSnapshot } = createController('25%\r\n', true, true);
-
- controller._handleEditorVisible({
- visible: true,
- eventType: DeviceInputEventType.Keyboard,
- keycode: KeyCode.Digit3,
- initialValue: '3',
- unitId: 'unit-1',
- });
-
- expect(getNormalSnapshot().body.dataStream).toBe('\r\n');
- });
-
- it.each([
- ['F2', { eventType: DeviceInputEventType.Keyboard, keycode: KeyCode.F2 }],
- ['double-click', { eventType: DeviceInputEventType.Dblclick }],
- ])('places the caret before the percent suffix for %s editing', (_name, input) => {
- const { controller } = createController('25%\r\n', true);
- const selection = { startOffset: 2, endOffset: 2, collapsed: true };
-
- controller._handleEditorVisible({
- visible: true,
- unitId: 'unit-1',
- ...input,
- });
-
- expect(controller._textSelectionManagerService.replaceDocRanges).toHaveBeenLastCalledWith(
- [selection],
- {
- unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- }
- );
- });
-
- it('overtypes a preserved percent suffix on subsequent percent input', () => {
- const { controller } = createController('0.35%\r\n', true);
- const beforeCommandListeners: Array<(command: { id: string; params: unknown }) => void> = [];
- controller._commandService.beforeCommandExecuted = vi.fn((listener) => {
- beforeCommandListeners.push(listener);
- return { dispose: vi.fn() };
- });
- controller._commandService.onCommandExecuted = vi.fn(() => ({ dispose: vi.fn() }));
- controller._commandExecutedListener({ add: vi.fn() });
- const params = {
- unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- body: { dataStream: '%' },
- range: { startOffset: 4, endOffset: 4, collapsed: true },
- };
-
- expect(beforeCommandListeners).toHaveLength(1);
- beforeCommandListeners[0]({ id: InsertTextCommand.id, params });
-
- expect(params.range).toEqual({ startOffset: 4, endOffset: 5, collapsed: false });
- });
-
- it('overtypes the original percent value on initial digit input', () => {
- const { controller } = createController('25%\r\n', true);
- controller._editorBridgeService.getEditorDirty.mockReturnValue(false);
- const beforeCommandListeners: Array<(command: { id: string; params: unknown }) => void> = [];
- controller._editorBridgeService.isVisible.mockReturnValue({
- visible: true,
- eventType: DeviceInputEventType.Keyboard,
- initialValue: '3',
- unitId: 'unit-1',
- });
- controller._commandService.beforeCommandExecuted = vi.fn((listener) => {
- beforeCommandListeners.push(listener);
- return { dispose: vi.fn() };
- });
- controller._commandService.onCommandExecuted = vi.fn(() => ({ dispose: vi.fn() }));
- controller._commandExecutedListener({ add: vi.fn() });
- const params = {
- unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- body: { dataStream: '3' },
- range: { startOffset: 0, endOffset: 0, collapsed: true },
- };
-
- beforeCommandListeners[0]({ id: InsertTextCommand.id, params });
-
- expect(params.range).toEqual({ startOffset: 0, endOffset: 2, collapsed: false });
- });
-
- it('syncs the active sheet editor selection instead of the host document selection on focus', () => {
- const { controller, workbook } = createController();
- const focus$ = new Subject<boolean>();
- const hostSelectionSync = vi.fn();
- const cellEditorSelectionSync = vi.fn();
- const disposableCollection = { add: vi.fn() };
-
- controller._cellEditorManagerService.focus$ = focus$;
- controller._univerInstanceService.getCurrentUnitOfType.mockImplementation((type: UniverInstanceType) => {
- if (type === UniverInstanceType.UNIVER_DOC) {
- return { getUnitId: () => 'host-doc' };
- }
-
- return workbook;
- });
- controller._renderManagerService.getRenderUnitById.mockImplementation((unitId: string) => ({
- with: vi.fn(() => {
- if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
- return { sync: cellEditorSelectionSync };
- }
- if (unitId === 'host-doc') {
- return { sync: hostSelectionSync };
- }
-
- return undefined;
- }),
- }));
-
- controller._initialCursorSync(disposableCollection);
- focus$.next(true);
-
- expect(cellEditorSelectionSync).toHaveBeenCalledTimes(1);
- expect(hostSelectionSync).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts
index 463c3b93ae..9a393c1537 100644
--- a/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts
@@ -14,21 +14,56 @@
* limitations under the License.
*/
-import type { ICellData } from '@univerjs/core';
+import type { Dependency, ICellData, IDocumentBody } from '@univerjs/core';
import {
BooleanNumber,
CellValueType,
+ CommandService,
+ ConfigService,
+ DesktopLogService,
+ Direction,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ DocumentDataModel,
+ EDITOR_ACTIVATED,
+ FOCUSING_EDITOR_INPUT_FORMULA,
+ FOCUSING_FX_BAR_EDITOR,
FormulaType,
+ ICommandService,
+ IConfigService,
+ IContextService,
+ ILogService,
+ Injector,
+ IUndoRedoService,
+ IUniverInstanceService,
LocaleService,
LocaleType,
Styles,
Tools,
+ UndoCommandId,
+ UniverInstanceType,
} from '@univerjs/core';
+import { DocSelectionManagerService, DocStateChangeManagerService, DocStateEmitService, InsertTextCommand, RichTextEditingMutation } from '@univerjs/docs';
+import { IEditorService, InnerPasteCommand, MoveCursorOperation, MoveSelectionOperation, SetDocInputStyleCommand, VIEWPORT_KEY } from '@univerjs/docs-ui';
import { FunctionService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';
-import { describe, expect, it } from 'vitest';
-import { getCellDataByInput, getComparableCellData } from '../editing.render-controller';
+import { DeviceInputEventType, IRenderManagerService, NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '@univerjs/engine-render';
+import { SetRangeValuesCommand, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
+import { KeyCode } from '@univerjs/ui';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../../commands/commands/set-selection.command';
+import { IEditorBridgeService } from '../../../services/editor-bridge.service';
+import { ICellEditorManagerService } from '../../../services/editor/cell-editor-manager.service';
+import { SheetCellEditorResizeService } from '../../../services/editor/cell-editor-resize.service';
+import { EditingRenderController, emptyBody, getCellDataByInput, getComparableCellData } from '../editing.render-controller';
import { createTestBed } from './create-test-bed';
+const injectors: Injector[] = [];
+afterEach(() => {
+ injectors.splice(0).forEach((injector) => injector.dispose());
+});
+
describe('imported formula metadata when editing', () => {
it.each([BooleanNumber.FALSE, BooleanNumber.TRUE])('clears copied metadata on edits and keeps unchanged formulas (fd=%s)', (fd) => {
const testBed = createTestBed(undefined, [[LexerTreeBuilder], [IFunctionService, { useClass: FunctionService }]]);
@@ -93,3 +128,724 @@ describe('cell editor commit comparison', () => {
expect(getComparableCellData(incoming, styles, previous)).not.toEqual(getComparableCellData(previous, styles, previous));
});
});
+
+describe('emptyBody', () => {
+ it('keeps an empty text-run collection initialized', () => {
+ const body: IDocumentBody = { dataStream: 'value\r\n', textRuns: [] };
+
+ emptyBody(body);
+
+ expect(body.textRuns).toEqual([]);
+ });
+
+ it('keeps one inherited style when resetting the editor', () => {
+ const body: IDocumentBody = {
+ dataStream: 'value\r\n',
+ textRuns: [{ st: 0, ed: 5, ts: { fs: 11 } }],
+ };
+
+ emptyBody(body);
+
+ expect(body.textRuns).toEqual([{ st: 0, ed: 1, ts: { fs: 11 } }]);
+ });
+
+ it('removes an inherited style when style removal is requested', () => {
+ const body: IDocumentBody = {
+ dataStream: 'value\r\n',
+ textRuns: [{ st: 0, ed: 5, ts: { fs: 11 } }],
+ };
+
+ emptyBody(body, true);
+
+ expect(body.textRuns).toBeUndefined();
+ });
+});
+
+function createController(initialDataStream = 'new value\r\n', isPercentFormat = false, isInArrayFormulaRange = false) {
+ const worksheet = {
+ getSheetId: vi.fn(() => 'sheet-1'),
+ getCellRaw: vi.fn(() => ({ v: 'old' })),
+ getComposedCellStyleWithoutSelf: vi.fn(() => ({})),
+ };
+ const styles = new Styles();
+ const workbook = {
+ getUnitId: vi.fn(() => 'unit-1'),
+ getActiveSheet: vi.fn(() => worksheet),
+ getSheetBySheetId: vi.fn(() => worksheet),
+ getStyles: vi.fn(() => styles),
+ };
+ const injector = new Injector();
+ injectors.push(injector);
+ const normalSnapshot = {
+ id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: initialDataStream, paragraphs: [...initialDataStream.matchAll(/\r/g)].map((match) => ({ startIndex: match.index, paragraphId: `normal-${match.index}` })) },
+ documentStyle: {},
+ };
+ const formulaSnapshot = {
+ id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: initialDataStream, paragraphs: [...initialDataStream.matchAll(/\r/g)].map((match) => ({ startIndex: match.index, paragraphId: `formula-${match.index}` })) },
+ documentStyle: {},
+ };
+ const docModel = injector.createInstance(DocumentDataModel, normalSnapshot);
+ const formulaDocModel = injector.createInstance(DocumentDataModel, formulaSnapshot);
+ const documentModel = {
+ getBody: vi.fn((): IDocumentBody => ({ dataStream: 'new value\r\n' })),
+ getSnapshot: vi.fn(() => ({
+ body: { dataStream: 'new value\r\n' },
+ documentStyle: {},
+ })),
+ };
+ const formulaBarEditor = {
+ setSelectionRanges: vi.fn(),
+ blur: vi.fn(),
+ };
+ const functionService = { getDescriptions: vi.fn(() => ({})) };
+ const undoRedoService = {
+ rollback: vi.fn(),
+ clearUndoRedo: vi.fn(),
+ };
+ const docStateChangeManagerService = {
+ clearHistory: vi.fn(),
+ };
+ const contextService = {
+ setContextValue: vi.fn(),
+ getContextValue: vi.fn(() => false),
+ };
+ const cellEditorManagerService = { setState: vi.fn(), focus$: new Subject<boolean>() };
+ const sheetCellEditorResizeService = {
+ fitTextSize: vi.fn((callback?: () => void) => callback?.()),
+ };
+ const editorService = {
+ isSheetEditor: vi.fn(() => true),
+ getEditor: vi.fn((editorId: string) => editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY ? formulaBarEditor : null),
+ };
+ const editorBridgeService = {
+ currentEditCellState$: new Subject(),
+ visible$: new Subject(),
+ getEditCellState: vi.fn(() => ({
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ row: 2,
+ column: 3,
+ documentLayoutObject: { documentModel },
+ isInArrayFormulaRange,
+ isPercentFormat,
+ })),
+ getEditLocation: vi.fn(() => ({
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ row: 2,
+ column: 3,
+ documentLayoutObject: { documentModel },
+ isInArrayFormulaRange,
+ isPercentFormat,
+ })),
+ getCurrentEditorId: vi.fn(() => DOCS_NORMAL_EDITOR_UNIT_ID_KEY),
+ isVisible: vi.fn(() => ({ visible: true, eventType: DeviceInputEventType.Keyboard, unitId: 'unit-1' })),
+ getEditorDirty: vi.fn(() => true),
+ isForceKeepVisible: vi.fn(() => false),
+ disableForceKeepVisible: vi.fn(),
+ refreshEditCellState: vi.fn(),
+ refreshEditCellPosition: vi.fn(),
+ changeEditorDirty: vi.fn(),
+ };
+ const sheetInterceptorService = {
+ onWriteCell: vi.fn((_workbook, _worksheet, _row, _column, cellData) => cellData),
+ onValidateCell: vi.fn(() => true),
+ };
+ const univerInstanceService = {
+ getCurrentTypeOfUnit$: vi.fn((type) => new BehaviorSubject(type === UniverInstanceType.UNIVER_DOC ? docModel : workbook)),
+ getUnit: vi.fn((unitId: string) => {
+ if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ return docModel;
+ }
+ if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+ return formulaDocModel;
+ }
+
+ return workbook;
+ }),
+ getCurrentUnitOfType: vi.fn(() => workbook),
+ setCurrentUnitForType: vi.fn(),
+ };
+ const workbookSelections = {
+ getCurrentLastSelection: vi.fn(() => ({ range: { startRow: 1, startColumn: 1, endRow: 4, endColumn: 4 } })),
+ getSelectionsOfWorksheet: vi.fn(() => [{ range: { startRow: 2, startColumn: 3, endRow: 2, endColumn: 3 } }]),
+ };
+ const selectionManagerService = {
+ getWorkbookSelections: vi.fn(() => workbookSelections),
+ };
+ const skeleton = { calculate: vi.fn(), resetInitialWidth: vi.fn() };
+ const viewModel = { reset: vi.fn() };
+ const renderManagerService = {
+ getRenderUnitById: vi.fn(() => ({
+ components: new Map(),
+ mainComponent: {
+ makeDirty: vi.fn(),
+ onPointerDown$: { subscribeEvent: vi.fn(() => ({ dispose: vi.fn() })) },
+ },
+ scene: {
+ getViewport: vi.fn((key) => key === VIEWPORT_KEY.VIEW_MAIN
+ ? { scrollToViewportPos: vi.fn() }
+ : null),
+ resetCursor: vi.fn(),
+ },
+ with: vi.fn(() => ({ getSkeleton: () => skeleton, getViewModel: () => viewModel })),
+ })),
+ };
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([ILogService, { useClass: DesktopLogService }]);
+ injector.add([ICommandService, { useClass: CommandService }]);
+ injector.add([LocaleService]);
+ injector.get(LocaleService).setLocale(LocaleType.EN_US);
+ injector.add([LexerTreeBuilder]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([DocStateEmitService]);
+ for (const dependency of [
+ [IUndoRedoService, { useValue: undoRedoService }],
+ [IContextService, { useValue: contextService }],
+ [IRenderManagerService, { useValue: renderManagerService }],
+ [IEditorBridgeService, { useValue: editorBridgeService }],
+ [ICellEditorManagerService, { useValue: cellEditorManagerService }],
+ [IFunctionService, { useValue: functionService }],
+ [IEditorService, { useValue: editorService }],
+ [IUniverInstanceService, { useValue: univerInstanceService }],
+ [SheetInterceptorService, { useValue: sheetInterceptorService }],
+ [SheetCellEditorResizeService, { useValue: sheetCellEditorResizeService }],
+ [SheetsSelectionsService, { useValue: selectionManagerService }],
+ [DocStateChangeManagerService, { useValue: docStateChangeManagerService }],
+ ] as Dependency[]) {
+ injector.add(dependency);
+ }
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(InsertTextCommand);
+ commandService.registerCommand(InnerPasteCommand);
+ commandService.registerCommand(RichTextEditingMutation);
+ const syncExecuteCommand = commandService.syncExecuteCommand.bind(commandService);
+ vi.spyOn(commandService, 'syncExecuteCommand').mockImplementation((id, params, options) =>
+ commandService.hasCommand(id) ? syncExecuteCommand(id, params, options) : true as never
+ );
+ vi.spyOn(commandService, 'executeCommand').mockResolvedValue(true as never);
+ const selectionManager = injector.get(DocSelectionManagerService);
+ vi.spyOn(selectionManager, 'replaceDocRanges');
+ vi.spyOn(selectionManager, 'refreshSelection');
+ // The render boundary publishes the resolved selection back to the logical selection manager.
+ selectionManager.refreshSelection$.subscribe((selection) => {
+ if (selection) {
+ selectionManager.replaceSelectionInfoWithoutRefresh({
+ textRanges: selection.docRanges.map(({ startOffset, endOffset }) => ({
+ startOffset: startOffset!,
+ endOffset: endOffset!,
+ collapsed: startOffset === endOffset,
+ isActive: true,
+ })),
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: -1,
+ isEditing: selection.isEditing,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ }, selection);
+ }
+ });
+ injector.add([EditingRenderController]);
+ const controller = injector.get(EditingRenderController) as any;
+ controller._editingUnit = 'unit-1';
+
+ return {
+ controller,
+ commandService,
+ selectionManager,
+ docModel,
+ docStateEmitService: injector.get(DocStateEmitService),
+ formulaBarEditor,
+ documentModel,
+ getFormulaSnapshot: () => formulaDocModel.getSnapshot(),
+ getNormalSnapshot: () => docModel.getSnapshot(),
+ workbook,
+ worksheet,
+ };
+}
+
+describe('EditingRenderController business methods', () => {
+ it('bypasses parsing, interceptors, and commands when the editor is clean', async () => {
+ const { controller, worksheet } = createController();
+ controller._editorBridgeService.getEditorDirty.mockReturnValue(false);
+
+ const result = await controller._submitEdit({
+ body: { dataStream: 'canonical display value\r\n' },
+ documentStyle: {},
+ });
+
+ expect(result).toBe(true);
+ expect(worksheet.getCellRaw).not.toHaveBeenCalled();
+ expect(controller._sheetInterceptorService.onWriteCell).not.toHaveBeenCalled();
+ expect(controller._commandService.syncExecuteCommand).not.toHaveBeenCalled();
+ });
+
+ it('reuses an empty cell style for the next editor input', () => {
+ const { controller, documentModel } = createController();
+ documentModel.getBody.mockReturnValue({
+ dataStream: '\r\n',
+ textRuns: [{ st: 0, ed: 0, ts: { fs: 20, cl: { rgb: '#f05252' } } }],
+ });
+
+ controller._cacheEmptyCellTextStyle();
+
+ expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDocInputStyleCommand.id, {
+ style: {
+ fs: 20,
+ cl: { rgb: '#f05252' },
+ },
+ });
+ });
+
+ it('submits edited cell content and rolls back when validation rejects the value', async () => {
+ const { controller } = createController();
+ controller._sheetInterceptorService.onValidateCell.mockResolvedValue(false);
+
+ const result = await controller._submitEdit({
+ body: { dataStream: 'new value\r\n' },
+ documentStyle: {},
+ });
+
+ expect(result).toBe(false);
+ expect(controller._sheetInterceptorService.onWriteCell).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), 2, 3, {
+ v: 'new value',
+ f: null,
+ si: null,
+ p: null,
+ });
+ expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, expect.objectContaining({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { startRow: 2, startColumn: 3, endRow: 2, endColumn: 3 },
+ value: { v: 'new value', f: null, si: null, p: null },
+ }));
+ expect(controller._undoRedoService.rollback).toHaveBeenCalledWith(expect.any(String), 'unit-1');
+ });
+
+ it('captures rich-text cell data independently from the reusable editor snapshot', async () => {
+ const { controller } = createController();
+ const snapshot = {
+ body: {
+ dataStream: 'rich text\r\n',
+ textRuns: [{ st: 5, ed: 9, ts: { bl: 1 } }],
+ },
+ documentStyle: {},
+ };
+
+ await controller._submitEdit(snapshot);
+ const submitted = controller._commandService.syncExecuteCommand.mock.calls
+ .find(([id]: [string]) => id === SetRangeValuesCommand.id)?.[1];
+ snapshot.body.textRuns = [];
+
+ expect(submitted?.value.p).not.toBe(snapshot);
+ expect(submitted?.value.p?.body?.textRuns).toEqual([{ st: 5, ed: 9, ts: { bl: 1 } }]);
+ });
+
+ it('uses the whole current selection when committing an array edit', async () => {
+ const { controller } = createController();
+
+ await controller._submitEdit({
+ body: { dataStream: 'fill\r\n' },
+ documentStyle: {},
+ }, true);
+
+ expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, expect.objectContaining({
+ range: { startRow: 1, startColumn: 1, endRow: 4, endColumn: 4 },
+ }));
+ expect(controller._undoRedoService.rollback).not.toHaveBeenCalled();
+ });
+
+ it('moves sheet selection after finishing edit and switches back to the edited workbook when needed', () => {
+ const { controller } = createController();
+ controller._univerInstanceService.getCurrentUnitOfType.mockReturnValue({ getUnitId: () => 'other-unit' });
+
+ controller._moveSelection(KeyCode.ENTER, 'unit-1', 'sheet-1');
+ controller._moveSelection(KeyCode.ARROW_LEFT, 'unit-1', 'sheet-1');
+ controller._moveSelection(undefined, 'unit-1', 'sheet-1');
+
+ expect(controller._univerInstanceService.setCurrentUnitForType).toHaveBeenCalledWith('unit-1');
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionEnterAndTabCommand.id, {
+ keycode: KeyCode.ENTER,
+ direction: 2,
+ });
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionCommand.id, {
+ direction: 3,
+ });
+ expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({
+ subUnitId: 'sheet-1',
+ }));
+ });
+
+ it.each([
+ ['Enter', KeyCode.ENTER, Direction.UP],
+ ['Tab', KeyCode.TAB, Direction.LEFT],
+ ])('moves the sheet selection in reverse after finishing edit with Shift+%s', async (_name, keycode, direction) => {
+ const { controller } = createController();
+ controller._editorBridgeService.getEditorDirty.mockReturnValue(false);
+
+ await controller._handleEditorInvisible({
+ visible: false,
+ eventType: DeviceInputEventType.Keyboard,
+ unitId: 'unit-1',
+ keycode,
+ isShift: true,
+ });
+
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionEnterAndTabCommand.id, {
+ keycode,
+ direction,
+ });
+ });
+
+ it('refreshes editor content when Esc cancels editing', async () => {
+ const { controller } = createController();
+
+ await controller._handleEditorInvisible({
+ visible: false,
+ eventType: DeviceInputEventType.Keyboard,
+ unitId: 'unit-1',
+ keycode: KeyCode.ESC,
+ });
+
+ expect(controller._editorBridgeService.refreshEditCellState).toHaveBeenCalledTimes(1);
+ });
+
+ it('moves the cursor inside the editor and resets editor state on exit', () => {
+ const { controller, formulaBarEditor } = createController();
+
+ controller._moveInEditor(KeyCode.ARROW_RIGHT, false);
+ controller._moveInEditor(KeyCode.ARROW_UP, true);
+ controller._exitInput({ visible: false });
+
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveCursorOperation.id, { direction: 1 });
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionOperation.id, { direction: 0 });
+ expect(controller._contextService.setContextValue).toHaveBeenCalledWith(FOCUSING_EDITOR_INPUT_FORMULA, false);
+ expect(controller._contextService.setContextValue).toHaveBeenCalledWith(EDITOR_ACTIVATED, false);
+ expect(controller._contextService.setContextValue).toHaveBeenCalledWith(FOCUSING_FX_BAR_EDITOR, false);
+ expect(controller._cellEditorManagerService.setState).toHaveBeenCalledWith({ show: false });
+ expect(controller._undoRedoService.clearUndoRedo).toHaveBeenCalledWith(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ expect(controller._undoRedoService.clearUndoRedo).toHaveBeenCalledWith(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+ expect(formulaBarEditor.setSelectionRanges).toHaveBeenCalledWith([], false);
+ expect(formulaBarEditor.blur).toHaveBeenCalled();
+ });
+
+ it('leaves initial keyboard input to the doc input pipeline when opening the cell editor', () => {
+ const { controller, getFormulaSnapshot, getNormalSnapshot } = createController();
+
+ controller._handleEditorVisible({
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: 187,
+ initialValue: '=',
+ unitId: 'unit-1',
+ });
+
+ expect(getNormalSnapshot().body?.dataStream).toBe('\r\n');
+ expect(getFormulaSnapshot().body?.dataStream).toBe('\r\n');
+ expect(controller._textSelectionManagerService.replaceDocRanges).toHaveBeenCalledWith(
+ [{ startOffset: 0, endOffset: 0 }],
+ {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ }
+ );
+ expect(controller._editorBridgeService.changeEditorDirty).not.toHaveBeenCalled();
+ });
+
+ it.each(['3', '35', '0.35', '35%'])('preserves the percent suffix when input starts with a digit: %s', (initialValue) => {
+ const { controller, getFormulaSnapshot, getNormalSnapshot } = createController('25%\r\n', true);
+
+ controller._handleEditorVisible({
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: KeyCode.Digit3,
+ initialValue,
+ unitId: 'unit-1',
+ });
+
+ expect(getNormalSnapshot().body?.dataStream).toBe('25%\r\n');
+ expect(getFormulaSnapshot().body?.dataStream).toBe('25%\r\n');
+ expect(controller._textSelectionManagerService.replaceDocRanges).toHaveBeenCalledWith(
+ [{ startOffset: 0, endOffset: 2, collapsed: false }],
+ {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ }
+ );
+ });
+
+ it.each(['$30', '=1', 'text', '+', '-', '.', ','])('replaces percent content when input does not start with a digit: %s', (initialValue) => {
+ const { controller, getNormalSnapshot } = createController('25%\r\n', true);
+
+ controller._handleEditorVisible({
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: KeyCode.Digit3,
+ initialValue,
+ unitId: 'unit-1',
+ });
+
+ expect(getNormalSnapshot().body?.dataStream).toBe('\r\n');
+ });
+
+ it.each([KeyCode.BACKSPACE, KeyCode.DELETE])('keeps full-clear behavior for keycode %s', (keycode) => {
+ const { controller, getNormalSnapshot } = createController('25%\r\n', true);
+
+ controller._handleEditorVisible({
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode,
+ unitId: 'unit-1',
+ });
+
+ expect(getNormalSnapshot().body?.dataStream).toBe('\r\n');
+ });
+
+ it('keeps full-clear behavior for array formula cells', () => {
+ const { controller, getNormalSnapshot } = createController('25%\r\n', true, true);
+
+ controller._handleEditorVisible({
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: KeyCode.Digit3,
+ initialValue: '3',
+ unitId: 'unit-1',
+ });
+
+ expect(getNormalSnapshot().body?.dataStream).toBe('\r\n');
+ });
+
+ it.each([
+ { content: '25%', percent: true, input: '3', expected: '3%' },
+ { content: '25%', percent: true, input: '7%', expected: '7%' },
+ { content: '-12.5%', percent: true, input: '3', expected: '3%' },
+ { content: 'hello world', percent: false, input: '3', expected: '3' },
+ { content: '=SUM(A1:A3)', percent: false, input: '=2+3', expected: '=2+3' },
+ { content: '=1/4', percent: true, input: '=2+3', expected: '=2+3' },
+ { content: '=25%', percent: true, input: '=30%', expected: '=30%' },
+ { content: 'hello\rworld', percent: false, input: '3', expected: '3' },
+ { content: '25%', percent: false, input: '3', expected: '3' },
+ { content: '', percent: false, input: '3', expected: '3' },
+ ])('replaces the editable content of "$content" on double click', ({ content, percent, input, expected }) => {
+ const { controller, commandService, docModel, selectionManager } = createController(`${content}\r\n`, percent);
+
+ controller._editorBridgeService.visible$.next({
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId: 'unit-1',
+ });
+ commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: input },
+ range: selectionManager.getActiveTextRange(),
+ });
+
+ expect(docModel.getBody()?.dataStream).toBe(`${expected}\r\n`);
+ });
+
+ it.each([
+ { content: '25%', percent: true, input: '3', expected: '253%' },
+ { content: 'hello', percent: false, input: '3', expected: 'hello3' },
+ { content: '=25%', percent: true, input: '+1', expected: '=25%+1' },
+ ])('keeps the insertion caret for F2 editing of "$content"', ({ content, percent, input, expected }) => {
+ const { controller, commandService, docModel, selectionManager } = createController(`${content}\r\n`, percent);
+
+ controller._editorBridgeService.visible$.next({
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: KeyCode.F2,
+ unitId: 'unit-1',
+ });
+ commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: input },
+ range: selectionManager.getActiveTextRange(),
+ });
+
+ expect(docModel.getBody()?.dataStream).toBe(`${expected}\r\n`);
+ });
+
+ it.each([
+ { content: '25%', percent: true, input: '7%', expected: '7%' },
+ { content: '25%', percent: true, input: '7', expected: '7%' },
+ { content: '=25%', percent: true, input: '=30%', expected: '=30%' },
+ { content: '25%', percent: false, input: '7%', expected: '7%' },
+ ])('pastes "$input" over the double-click selection of "$content" (percent=$percent)', ({ content, percent, input, expected }) => {
+ const { controller, commandService, docModel } = createController(`${content}\r\n`, percent);
+ controller._editorBridgeService.visible$.next({
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId: 'unit-1',
+ });
+
+ commandService.syncExecuteCommand(InnerPasteCommand.id, {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ segmentId: '',
+ doc: { body: { dataStream: input } },
+ textRanges: [{ startOffset: input.length, endOffset: input.length, collapsed: true }],
+ });
+
+ expect(docModel.getBody()?.dataStream).toBe(`${expected}\r\n`);
+ });
+
+ it.each([
+ { eventType: DeviceInputEventType.Dblclick, percent: false, expected: '3' },
+ { eventType: DeviceInputEventType.Dblclick, percent: true, expected: '3%' },
+ { eventType: DeviceInputEventType.Keyboard, percent: false, expected: 'hello3' },
+ { eventType: DeviceInputEventType.Keyboard, percent: true, expected: '253%' },
+ ])('preserves the host Docs selection when opening an embedded cell editor ($eventType, percent=$percent)', ({ eventType, percent, expected }) => {
+ const { controller, commandService, docModel, selectionManager } = createController(percent ? '25%\r\n' : 'hello\r\n', percent);
+ const host = { unitId: 'host-doc', subUnitId: 'host-doc' };
+ const hostRange = { startOffset: 4, endOffset: 8, collapsed: false, isActive: true };
+ selectionManager.__TEST_ONLY_setCurrentSelection(host);
+ selectionManager.__TEST_ONLY_add([hostRange]);
+
+ controller._editorBridgeService.visible$.next({
+ visible: true,
+ eventType,
+ keycode: KeyCode.F2,
+ unitId: 'unit-1',
+ });
+
+ commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: '3' },
+ range: selectionManager.getTextRanges({
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ })?.find((range) => range.isActive),
+ });
+ expect(docModel.getBody()?.dataStream).toBe(`${expected}\r\n`);
+ expect(selectionManager.getTextRanges(host)).toEqual([hostRange]);
+ });
+
+ it('keeps percentage replacement after undoing a paste inside the editor', () => {
+ const { controller, commandService, docModel, docStateEmitService, selectionManager } = createController('25%\r\n', true);
+ const emit = vi.spyOn(docStateEmitService, 'emitStateChangeInfo');
+ controller._editorBridgeService.visible$.next({
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId: 'unit-1',
+ });
+ commandService.syncExecuteCommand(InnerPasteCommand.id, {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ segmentId: '',
+ doc: { body: { dataStream: '7%' } },
+ textRanges: [{ startOffset: 2, endOffset: 2, collapsed: true }],
+ });
+ const { undoState } = emit.mock.calls[0][0];
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, {
+ ...undoState,
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ trigger: UndoCommandId,
+ });
+ commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: '3' },
+ range: selectionManager.getActiveTextRange(),
+ });
+
+ expect(docModel.getBody()?.dataStream).toBe('3%\r\n');
+ });
+
+ it('keeps one percent suffix when typing a complete percentage after double click', () => {
+ const { controller, commandService, docModel, selectionManager } = createController('25%\r\n', true);
+ controller._editorBridgeService.visible$.next({
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId: 'unit-1',
+ });
+ for (const input of ['3', '%']) {
+ commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: input },
+ range: selectionManager.getActiveTextRange(),
+ });
+ }
+ expect(docModel.getBody()?.dataStream).toBe('3%\r\n');
+ });
+
+ it('inserts percent operators inside a formula without overtyping an existing operator', () => {
+ const { controller, commandService, docModel, selectionManager } = createController('=25%\r\n', true);
+ controller._editorBridgeService.visible$.next({
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: KeyCode.F2,
+ unitId: 'unit-1',
+ });
+ selectionManager.replaceDocRanges([{ startOffset: 3, endOffset: 3, collapsed: true }], {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ });
+ commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: '%' },
+ range: selectionManager.getActiveTextRange(),
+ });
+
+ expect(docModel.getBody()?.dataStream).toBe('=25%%\r\n');
+ });
+
+ it.each([
+ { content: '25%', input: '3', expected: '3%' },
+ { content: '25%', input: '35%', expected: '35%' },
+ { content: '=25%', input: '3', expected: '3%' },
+ { content: '=25%', input: '35%', expected: '35%' },
+ ])('replaces "$content" on initial digit input "$input" despite the stale input range', ({ content, input, expected }) => {
+ const { controller, commandService, docModel } = createController(`${content}\r\n`, true);
+ const visible = {
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ initialValue: input,
+ unitId: 'unit-1',
+ };
+ controller._editorBridgeService.getEditorDirty.mockReturnValue(false);
+ controller._editorBridgeService.isVisible.mockReturnValue(visible);
+ controller._editorBridgeService.visible$.next(visible);
+
+ commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: input },
+ range: { startOffset: 0, endOffset: 0, collapsed: true },
+ });
+
+ expect(docModel.getBody()?.dataStream).toBe(`${expected}\r\n`);
+ });
+
+ it('syncs the active sheet editor selection instead of the host document selection on focus', () => {
+ const { controller, workbook } = createController();
+ const focus$ = new Subject<boolean>();
+ const hostSelectionSync = vi.fn();
+ const cellEditorSelectionSync = vi.fn();
+ const disposableCollection = { add: vi.fn() };
+
+ controller._cellEditorManagerService.focus$ = focus$;
+ controller._univerInstanceService.getCurrentUnitOfType.mockImplementation((type: UniverInstanceType) => {
+ if (type === UniverInstanceType.UNIVER_DOC) {
+ return { getUnitId: () => 'host-doc' };
+ }
+
+ return workbook;
+ });
+ controller._renderManagerService.getRenderUnitById.mockImplementation((unitId: string) => ({
+ with: vi.fn(() => {
+ if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ return { sync: cellEditorSelectionSync };
+ }
+ if (unitId === 'host-doc') {
+ return { sync: hostSelectionSync };
+ }
+
+ return undefined;
+ }),
+ }));
+
+ controller._initialCursorSync(disposableCollection);
+ focus$.next(true);
+
+ expect(cellEditorSelectionSync).toHaveBeenCalledTimes(1);
+ expect(hostSelectionSync).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
index 14c89da0ef..18bc4cac95 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
@@ -14,8 +14,6 @@
* limitations under the License.
*/
-/* eslint-disable max-lines-per-function */
-
import type {
DocumentDataModel,
ICellData,
@@ -32,6 +30,7 @@ import type {
Workbook,
} from '@univerjs/core';
import type { IInsertTextCommandParams, IRichTextEditingMutationParams } from '@univerjs/docs';
+import type { IInnerPasteCommandParams } from '@univerjs/docs-ui';
import type {
ISetRangeValuesCommandParams,
ISetWorksheetActivateCommandParams,
@@ -78,6 +77,7 @@ import {
import {
DocSelectionRenderService,
IEditorService,
+ InnerPasteCommand,
MoveCursorOperation,
MoveSelectionOperation,
ReplaceSnapshotCommand,
@@ -108,6 +108,7 @@ import {
} from '@univerjs/sheets';
import { DISABLE_AUTO_FOCUS_KEY, KeyCode, MetaKeys } from '@univerjs/ui';
import { distinctUntilChanged, filter } from 'rxjs';
+
import { getEditorObject } from '../../basics/editor/get-editor-object';
import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../commands/commands/set-selection.command';
import {
@@ -148,18 +149,22 @@ function getPercentEditorSelection(
}
const { eventType, initialValue, keycode } = visibleParam;
- if (
- eventType === DeviceInputEventType.Dblclick ||
- (eventType === DeviceInputEventType.Keyboard && keycode === KeyCode.F2)
- ) {
+ // A formula's trailing percent sign is an operator, not a retained number-format suffix.
+ if (isFormulaString(dataStream) && (eventType === DeviceInputEventType.Dblclick || keycode === KeyCode.F2)) {
+ return null;
+ }
+
+ if (eventType === DeviceInputEventType.Keyboard && keycode === KeyCode.F2) {
return { startOffset: percentOffset, endOffset: percentOffset, collapsed: true };
}
if (
- eventType !== DeviceInputEventType.Keyboard ||
- keycode === KeyCode.BACKSPACE ||
- keycode === KeyCode.DELETE ||
- !/^\d/.test(initialValue ?? '')
+ eventType !== DeviceInputEventType.Dblclick && (
+ eventType !== DeviceInputEventType.Keyboard ||
+ keycode === KeyCode.BACKSPACE ||
+ keycode === KeyCode.DELETE ||
+ !/^\d/.test(initialValue ?? '')
+ )
) {
return null;
}
@@ -432,14 +437,16 @@ export class EditingRenderController extends Disposable {
*/
private _commandExecutedListener(d: DisposableCollection) {
d.add(this._commandService.beforeCommandExecuted((command: ICommandInfo) => {
- if (command.id !== InsertTextCommand.id) {
+ if (command.id !== InsertTextCommand.id && command.id !== InnerPasteCommand.id) {
return;
}
- const params = command.params as IInsertTextCommandParams;
+ const insertParams = command.id === InsertTextCommand.id ? command.params as IInsertTextCommandParams : null;
+ const pasteParams = command.id === InnerPasteCommand.id ? command.params as IInnerPasteCommandParams : null;
+ const unitId = insertParams?.unitId ?? pasteParams?.unitId;
const visibleParam = this._editorBridgeService.isVisible();
const editCellState = this._editorBridgeService.getEditLocation();
- if (params.unitId !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY || !visibleParam.visible || editCellState == null) {
+ if (unitId !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY || !visibleParam.visible || editCellState == null) {
return;
}
@@ -449,27 +456,42 @@ export class EditingRenderController extends Disposable {
}
const percentOffset = getPercentOffset(editCellState, dataStream);
+ if (percentOffset == null) {
+ return;
+ }
+
// The input event captures its range before the editor opens, so the first digit still carries a stale range.
if (
- percentOffset != null &&
+ insertParams &&
!this._editorBridgeService.getEditorDirty() &&
visibleParam.eventType === DeviceInputEventType.Keyboard &&
/^\d/.test(visibleParam.initialValue ?? '') &&
- /^\d/.test(params.body.dataStream)
+ /^\d/.test(insertParams.body.dataStream)
) {
- params.range = { startOffset: 0, endOffset: percentOffset, collapsed: false };
- return;
+ insertParams.range = {
+ startOffset: 0,
+ endOffset: percentOffset + (insertParams.body.dataStream.endsWith('%') ? 1 : 0),
+ collapsed: false,
+ };
}
- // Overtype the preserved suffix so entering `35%` does not produce `35%%`.
+ const selectionParams = { unitId, subUnitId: unitId };
+ const ranges = insertParams ? [insertParams.range] : this._textSelectionManagerService.getTextRanges(selectionParams);
+ const input = insertParams?.body.dataStream ?? pasteParams?.doc.body?.dataStream;
+ // Overtype the preserved suffix for typed and pasted percentages, but keep formula operators.
if (
- percentOffset != null &&
- params.body.dataStream === '%' &&
- params.range.collapsed &&
- params.range.startOffset === percentOffset &&
- params.range.endOffset === percentOffset
+ !isFormulaString(dataStream) &&
+ input?.endsWith('%') &&
+ ranges?.length === 1 &&
+ ranges[0].endOffset === percentOffset &&
+ (!pasteParams || !this._textSelectionManagerService.getRectRanges(selectionParams)?.length)
) {
- params.range = { ...params.range, endOffset: percentOffset + 1, collapsed: false };
+ const range = { ...ranges[0], endOffset: percentOffset + 1, collapsed: false };
+ if (insertParams) {
+ insertParams.range = range;
+ } else if (pasteParams) {
+ pasteParams.selections = [range];
+ }
}
}));
@@ -528,7 +550,6 @@ export class EditingRenderController extends Disposable {
}
// You can double-click on the cell or input content by keyboard to put the cell into the edit state.
- // eslint-disable-next-line complexity
private _handleEditorVisible(param: IEditorBridgeServiceVisibleParam) {
const { eventType, keycode } = param;
// Change `CursorChange` to changed status, when formula bar clicked.
@@ -603,6 +624,7 @@ export class EditingRenderController extends Disposable {
);
};
const replaceSelection = (selection: ITextRange) => {
+ // An embedded sheet may open its editor while the host document retains global focus.
this._textSelectionManagerService.replaceDocRanges(
[selection],
{
@@ -620,27 +642,9 @@ export class EditingRenderController extends Disposable {
} else if (eventType === DeviceInputEventType.Keyboard && keycode === KeyCode.F2) {
// f2, continue to edit
document.makeDirty();
- this._textSelectionManagerService.replaceDocRanges([
- {
- startOffset: 0,
- endOffset: 0,
- },
- ]);
+ replaceSelection({ startOffset: 0, endOffset: 0, collapsed: true });
const endOffset = (documentDataModel.getBody()?.dataStream.length ?? 2) - 2;
- if (percentSelection) {
- replaceSelection(percentSelection);
- } else {
- this._textSelectionManagerService.replaceDocRanges(
- [{
- startOffset: endOffset,
- endOffset,
- }],
- {
- unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- }
- );
- }
+ replaceSelection(percentSelection ?? { startOffset: endOffset, endOffset, collapsed: true });
} else if (
// clear and edit
eventType === DeviceInputEventType.Keyboard ||
@@ -656,17 +660,8 @@ export class EditingRenderController extends Disposable {
return;
}
- const cursor = documentDataModel.getBody()!.dataStream.length - 2 || 0;
- if (percentSelection) {
- replaceSelection(percentSelection);
- } else {
- this._textSelectionManagerService.replaceDocRanges([
- {
- startOffset: cursor,
- endOffset: cursor,
- },
- ]);
- }
+ const endOffset = documentDataModel.getBody()!.dataStream.length - 2 || 0;
+ replaceSelection(percentSelection ?? { startOffset: 0, endOffset, collapsed: endOffset === 0 });
}
this._renderManagerService.getRenderUnitById(unitId)?.scene.resetCursor();
@@ -1028,7 +1023,6 @@ export class EditingRenderController extends Disposable {
}
}
-// eslint-disable-next-line complexity
export function getCellDataByInput(
cellData: ICellData,
snapshot: Nullable<IDocumentData>,