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.

feat(sheet): formula show and add selection move (#676)

Univerd5be1cbd654c
diff --git a/packages/core/src/shared/array-search.ts b/packages/core/src/shared/array-search.ts
index fbe8111223..2c9397ce0c 100644
--- a/packages/core/src/shared/array-search.ts
+++ b/packages/core/src/shared/array-search.ts
@@ -36,7 +36,7 @@ export function orderSearchArray(arr: number[], pos: number) {
cur_pre = arr[i_ed - 1];
}
- if (pos >= cur_pre && pos < cur) {
+ if (pos >= cur_pre && pos <= cur) {
cur_index = i_ed;
break;
}
diff --git a/packages/core/src/sheets/styles.ts b/packages/core/src/sheets/styles.ts
index f073b8f1bf..a7c36f9813 100644
--- a/packages/core/src/sheets/styles.ts
+++ b/packages/core/src/sheets/styles.ts
@@ -1,6 +1,6 @@
import type { IKeyType, Nullable } from '../shared';
import { Tools } from '../shared';
-import type { ICellData, IStyleData } from '../types/interfaces';
+import type { ICellDataForSheetInterceptor, IStyleData } from '../types/interfaces';
/**
* Styles in a workbook, cells locate styles based on style IDs
@@ -88,7 +88,7 @@ export class Styles {
return this._styles;
}
- getStyleByCell(cell: Nullable<ICellData>): Nullable<IStyleData> {
+ getStyleByCell(cell: Nullable<ICellDataForSheetInterceptor>): Nullable<IStyleData> {
let style;
if (cell && Tools.isObject(cell.s)) {
style = cell.s as IStyleData;
@@ -96,6 +96,15 @@ export class Styles {
style = cell?.s && this.get(cell.s);
}
+ const interceptStyle = cell?.interceptorStyle;
+
+ if (interceptStyle) {
+ return {
+ ...style,
+ ...interceptStyle,
+ } as IStyleData;
+ }
+
return style as IStyleData;
}
diff --git a/packages/core/src/sheets/view-model.ts b/packages/core/src/sheets/view-model.ts
index bebdf38d3c..ff2bb8d677 100644
--- a/packages/core/src/sheets/view-model.ts
+++ b/packages/core/src/sheets/view-model.ts
@@ -3,10 +3,10 @@ import type { IDisposable } from '@wendellhu/redi';
import { remove } from '../common/array';
import type { Nullable } from '../common/type-utils';
import { Disposable, toDisposable } from '../shared/lifecycle';
-import type { ICellData } from '../types/interfaces/i-cell-data';
+import type { ICellDataForSheetInterceptor } from '../types/interfaces/i-cell-data';
export interface ICellContentInterceptor {
- getCell(row: number, col: number): Nullable<ICellData>;
+ getCell(row: number, col: number): Nullable<ICellDataForSheetInterceptor>;
}
export interface IRowFilteredInterceptor {}
@@ -21,7 +21,7 @@ export interface ISheetViewModel {
registerRowVisibleInterceptor(interceptor: IRowVisibleInterceptor): IDisposable;
registerColVisibleInterceptor(interceptor: IColVisibleInterceptor): IDisposable;
- getCell(row: number, col: number): Nullable<ICellData>;
+ getCell(row: number, col: number): Nullable<ICellDataForSheetInterceptor>;
}
/**
@@ -42,7 +42,7 @@ export class SheetViewModel extends Disposable implements ISheetViewModel {
this._colVisibleInterceptors.length = 0;
}
- getCell(row: number, col: number): Nullable<ICellData> {
+ getCell(row: number, col: number): Nullable<ICellDataForSheetInterceptor> {
for (const interceptor of this._cellContentInterceptors) {
const result = interceptor.getCell(row, col);
if (typeof result !== 'undefined') {
diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.ts
index 144e0edb8b..31e5eda29c 100644
--- a/packages/core/src/sheets/worksheet.ts
+++ b/packages/core/src/sheets/worksheet.ts
@@ -4,7 +4,7 @@ import { createRowColIter } from '../shared/row-col-iter';
import { DEFAULT_WORKSHEET } from '../types/const';
import type { SheetTypes } from '../types/enum';
import { BooleanNumber } from '../types/enum';
-import type { ICellData, IFreeze, IRange, IWorksheetData } from '../types/interfaces';
+import type { ICellData, ICellDataForSheetInterceptor, IFreeze, IRange, IWorksheetData } from '../types/interfaces';
import { ColumnManager } from './column-manager';
import { Range } from './range';
import { RowManager } from './row-manager';
@@ -165,7 +165,7 @@ export class Worksheet {
return null;
}
- getCell(row: number, col: number): Nullable<ICellData> {
+ getCell(row: number, col: number): Nullable<ICellDataForSheetInterceptor> {
if (row < 0 || col < 0) {
return null;
}
diff --git a/packages/core/src/types/interfaces/i-cell-data.ts b/packages/core/src/types/interfaces/i-cell-data.ts
index c37d2d4acf..35e95cbbd5 100644
--- a/packages/core/src/types/interfaces/i-cell-data.ts
+++ b/packages/core/src/types/interfaces/i-cell-data.ts
@@ -29,6 +29,11 @@ export interface ICellData {
si?: Nullable<string>; // formula id
}
+export interface ICellDataForSheetInterceptor extends ICellData {
+ interceptorStyle?: Nullable<IStyleData>;
+ isInArrayFormulaRange?: Nullable<boolean>;
+}
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isICellData(value: any): value is ICellData {
return (
diff --git a/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts
index 9b74030ad5..6e72b3fde3 100644
--- a/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts
+++ b/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts
@@ -1,5 +1,5 @@
import type { IWorkbookData } from '@univerjs/core';
-import { ILogService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';
+import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, PluginType, Univer } from '@univerjs/core';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
@@ -101,7 +101,7 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencie
univerInstanceService.focusUniverInstance('test');
const logService = get(ILogService);
- logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
+ logService.setLogLevel(LogLevel.SILENT); // change this to `true` to debug tests via logs
return {
univer,
diff --git a/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts
index e30df2464a..6dbb8c09a5 100644
--- a/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts
+++ b/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts
@@ -1,5 +1,5 @@
import type { IWorkbookData } from '@univerjs/core';
-import { ILogService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';
+import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, PluginType, Univer } from '@univerjs/core';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
@@ -73,7 +73,7 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencie
univerInstanceService.focusUniverInstance('test');
const logService = get(ILogService);
- logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
+ logService.setLogLevel(LogLevel.SILENT); // change this to `true` to debug tests via logs
return {
univer,
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index de507165da..44b03139aa 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -1,4 +1,4 @@
-import type { ICellData, IRange, ObjectMatrixPrimitiveType } from '@univerjs/core';
+import type { ICellData, IRange, Nullable, ObjectMatrixPrimitiveType } from '@univerjs/core';
import {
Disposable,
ICommandService,
@@ -21,12 +21,6 @@ import type {
} from '../basics/common';
import { FormulaEngineService } from '../services/formula-engine.service';
-export interface IFormulaConfig {
- notExecuteFormula?: boolean;
-
- formulaData: IFormulaData;
-}
-
export class FormulaDataModel extends Disposable {
private _formulaData: IFormulaData = {};
@@ -344,6 +338,37 @@ export class FormulaDataModel extends Disposable {
}
});
}
+
+ getFormulaItemBySId(sId: string, sheetId: string, unitId: string): Nullable<IFormulaDataItem> {
+ const formulaData = this._formulaData;
+ if (formulaData[unitId] == null) {
+ return null;
+ }
+ const workbookFormulaData = formulaData[unitId];
+
+ if (workbookFormulaData[sheetId] == null) {
+ return null;
+ }
+
+ const cellMatrix = new ObjectMatrix(workbookFormulaData[sheetId]);
+
+ let formulaDataItem: Nullable<IFormulaDataItem> = null;
+
+ cellMatrix.forValue((row, column, item) => {
+ const { f, si } = item;
+
+ if (si === sId && f.length > 0) {
+ formulaDataItem = item;
+ return false;
+ }
+ });
+
+ return formulaDataItem;
+ }
+
+ getFormulaDataItem(row: number, column: number, sheetId: string, unitId: string) {
+ return this._formulaData?.[unitId]?.[sheetId]?.[row]?.[column];
+ }
}
export function initSheetFormulaData(
diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.ts
index 2d2fc2b683..061d36a966 100644
--- a/packages/engine-render/src/basics/tools.ts
+++ b/packages/engine-render/src/basics/tools.ts
@@ -458,10 +458,10 @@ export function getCellPositionByIndex(
const startColumn = column - 1;
const startY = rowHeightAccumulation[startRow] || 0;
- const endY = rowHeightAccumulation[row];
+ const endY = rowHeightAccumulation[row] || rowHeightAccumulation[rowHeightAccumulation.length - 1];
const startX = columnWidthAccumulation[startColumn] || 0;
- const endX = columnWidthAccumulation[column];
+ const endX = columnWidthAccumulation[column] || columnWidthAccumulation[columnWidthAccumulation.length - 1];
return {
startY,
@@ -503,12 +503,17 @@ export function getCellByIndex(
startX: 0,
endX: 0,
};
+
+ const rowAccumulationCount = rowHeightAccumulation.length - 1;
+
+ const columnAccumulationCount = columnWidthAccumulation.length - 1;
+
if (isMerged && startRow !== -1 && startColumn !== -1) {
const mergeStartY = rowHeightAccumulation[startRow - 1] || 0;
- const mergeEndY = rowHeightAccumulation[endRow];
+ const mergeEndY = rowHeightAccumulation[endRow] || rowHeightAccumulation[rowAccumulationCount];
const mergeStartX = columnWidthAccumulation[startColumn - 1] || 0;
- const mergeEndX = columnWidthAccumulation[endColumn];
+ const mergeEndX = columnWidthAccumulation[endColumn] || columnWidthAccumulation[columnAccumulationCount];
mergeInfo = {
...mergeInfo,
startY: mergeStartY,
@@ -517,8 +522,8 @@ export function getCellByIndex(
endX: mergeEndX,
};
} else if (!isMerged && endRow !== -1 && endColumn !== -1) {
- const mergeEndY = rowHeightAccumulation[endRow] || 0;
- const mergeEndX = columnWidthAccumulation[endColumn] || 0;
+ const mergeEndY = rowHeightAccumulation[endRow] || rowHeightAccumulation[rowAccumulationCount];
+ const mergeEndX = columnWidthAccumulation[endColumn] || columnWidthAccumulation[columnAccumulationCount];
mergeInfo = {
...mergeInfo,
diff --git a/packages/engine-render/src/components/sheets/extensions/border-auxiliary.ts b/packages/engine-render/src/components/sheets/extensions/border-auxiliary.ts
index f2b56d0138..f906d372ed 100644
--- a/packages/engine-render/src/components/sheets/extensions/border-auxiliary.ts
+++ b/packages/engine-render/src/components/sheets/extensions/border-auxiliary.ts
@@ -144,10 +144,16 @@ export class BorderAuxiliary extends SheetExtension {
const { startRow, endRow, startColumn, endColumn } = dataCache;
const startY = fixLineWidthByScale(rowHeightAccumulation[startRow - 1] || 0, scale);
- const endY = fixLineWidthByScale(rowHeightAccumulation[endRow], scale);
+ const endY = fixLineWidthByScale(
+ rowHeightAccumulation[endRow] || rowHeightAccumulation[rowHeightAccumulation.length - 1],
+ scale
+ );
const startX = fixLineWidthByScale(columnWidthAccumulation[startColumn - 1] || 0, scale);
- const endX = fixLineWidthByScale(columnWidthAccumulation[endColumn], scale);
+ const endX = fixLineWidthByScale(
+ columnWidthAccumulation[endColumn] || columnWidthAccumulation[columnWidthAccumulation.length - 1],
+ scale
+ );
ctx.clearRect(startX, startY, endX - startX, endY - startY);
diff --git a/packages/engine-render/src/components/sheets/extensions/font.ts b/packages/engine-render/src/components/sheets/extensions/font.ts
index ac735cabf0..0290a6f7f6 100644
--- a/packages/engine-render/src/components/sheets/extensions/font.ts
+++ b/packages/engine-render/src/components/sheets/extensions/font.ts
@@ -186,10 +186,16 @@ export class Font extends SheetExtension {
columnWidthAccumulation: number[]
) {
const startY = fixLineWidthByScale(rowHeightAccumulation[startRow - 1] || 0, scale);
- const endY = fixLineWidthByScale(rowHeightAccumulation[endRow], scale);
+ const endY = fixLineWidthByScale(
+ rowHeightAccumulation[endRow] || rowHeightAccumulation[rowHeightAccumulation.length - 1],
+ scale
+ );
const startX = fixLineWidthByScale(columnWidthAccumulation[startColumn - 1] || 0, scale);
- const endX = fixLineWidthByScale(columnWidthAccumulation[endColumn], scale);
+ const endX = fixLineWidthByScale(
+ columnWidthAccumulation[endColumn] || columnWidthAccumulation[columnWidthAccumulation.length - 1],
+ scale
+ );
ctx.rect(startX, startY, endX - startX, endY - startY);
}
diff --git a/packages/engine-render/src/scene.input-manager.ts b/packages/engine-render/src/scene.input-manager.ts
index a4b5971e43..28b589649e 100644
--- a/packages/engine-render/src/scene.input-manager.ts
+++ b/packages/engine-render/src/scene.input-manager.ts
@@ -10,13 +10,13 @@ import type { Viewport } from './viewport';
export class InputManager {
/** The distance in pixel that you have to move to prevent some events */
- static DragMovementThreshold = 10; // in pixels
+ static DragMovementThreshold = 2; // in pixels
/** Time in milliseconds to wait to raise long press events if button is still pressed */
static LongPressDelay = 500; // in milliseconds
/** Time in milliseconds with two consecutive clicks will be considered as a double or triple click */
- static DoubleOrTripleClickDelay = 600; // in milliseconds
+ static DoubleOrTripleClickDelay = 500; // in milliseconds
/** If you need to check double click without raising a single click at first click, enable this flag */
static ExclusiveDoubleClickMode = false;
@@ -330,28 +330,18 @@ export class InputManager {
private _prePointerDoubleOrTripleClick(evt: IPointerEvent) {
const { clientX, clientY } = evt;
- if (this._doubleClickOccurred === 0) {
- this._startingPosition.x = clientX;
- this._startingPosition.y = clientY;
- }
-
- this._doubleClickOccurred += 1;
-
this._delayedTimeout = setTimeout(() => {
this._resetDoubleClickParam();
}, InputManager.DoubleOrTripleClickDelay);
- if (this._doubleClickOccurred < 2) {
- return;
- }
-
const isMoveThreshold = this._isPointerSwiping(clientX, clientY);
if (isMoveThreshold) {
this._resetDoubleClickParam();
- return;
}
+ this._doubleClickOccurred += 1;
+
if (this._doubleClickOccurred === 2) {
this._scene?.pick(Vector2.FromArray([evt.offsetX, evt.offsetY]))?.triggerDblclick(evt);
@@ -370,12 +360,13 @@ export class InputManager {
this._resetDoubleClickParam();
}
+
+ this._startingPosition.x = clientX;
+ this._startingPosition.y = clientY;
}
private _resetDoubleClickParam() {
this._doubleClickOccurred = 0;
- this._startingPosition.x = Infinity;
- this._startingPosition.y = Infinity;
clearTimeout(this._delayedTimeout);
}
}
diff --git a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
index 6799ca1048..731fc5cf68 100644
--- a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
@@ -90,84 +90,3 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencie
sheet,
};
}
-
-// import type { IWorkbookData } from '@univerjs/core';
-// import { ILogService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';
-// import { FormulaEngineService } from '@univerjs/engine-formula';
-// import { SelectionManagerService } from '@univerjs/sheets';
-// import type { Dependency } from '@wendellhu/redi';
-// import { Inject, Injector } from '@wendellhu/redi';
-
-// const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
-// id: 'test',
-// appVersion: '3.0.0-alpha',
-// sheets: {
-// sheet1: {
-// id: 'sheet1',
-// cellData: {
-// '1': {
-// '1': {
-// v: 1,
-// },
-// },
-// },
-// },
-// },
-// locale: LocaleType.EN_US,
-// name: '',
-// sheetOrder: [],
-// styles: {},
-// };
-
-// export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencies?: Dependency[]) {
-// const univer = new Univer();
-
-// let get: Injector['get'] | undefined;
-
-// /**
-// * This plugin hooks into Sheet's DI system to expose API to test scripts
-// */
-// class TestSpyPlugin extends Plugin {
-// static override type = PluginType.Sheet;
-
-// constructor(
-// _config: undefined,
-// @Inject(Injector) override readonly _injector: Injector
-// ) {
-// super('test-plugin');
-
-// this._injector = _injector;
-// get = this._injector.get.bind(this._injector);
-// }
-
-// override onStarting(injector: Injector): void {
-// injector.add([SelectionManagerService]);
-// injector.add([FormulaEngineService]);
-
-// dependencies?.forEach((d) => injector.add(d));
-// }
-
-// override onDestroy(): void {
-// get = undefined;
-// }
-// }
-
-// univer.registerPlugin(TestSpyPlugin);
-// const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA_DEMO);
-
-// if (get === undefined) {
-// throw new Error('[TestPlugin]: not hooked on!');
-// }
-
-// const univerInstanceService = get(IUniverInstanceService);
-// univerInstanceService.focusUniverInstance('test');
-
-// const logService = get(ILogService);
-// logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
-
-// return {
-// univer,
-// get,
-// sheet,
-// };
-// }
diff --git a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
new file mode 100644
index 0000000000..58ba015627
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
@@ -0,0 +1,194 @@
+import { TinyColor } from '@ctrl/tinycolor';
+import type { ICellDataForSheetInterceptor, ICommandInfo, IRange, Nullable } from '@univerjs/core';
+import {
+ Disposable,
+ ICommandService,
+ LifecycleStages,
+ ObjectMatrix,
+ OnLifecycle,
+ ThemeService,
+ toDisposable,
+} from '@univerjs/core';
+import { FormulaDataModel, FormulaEngineService, SetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import {
+ IEditorBridgeService,
+ ISelectionRenderService,
+ SelectionShape,
+ SheetSkeletonManagerService,
+} from '@univerjs/sheets-ui';
+import { Inject } from '@wendellhu/redi';
+
+@OnLifecycle(LifecycleStages.Rendered, FormulaEditorShowController)
+export class FormulaEditorShowController extends Disposable {
+ private _previousShape: Nullable<SelectionShape>;
+
+ constructor(
+ @Inject(IEditorBridgeService) private _editorBridgeService: IEditorBridgeService,
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+ this._initInterceptorEditorStart();
+
+ this._commandExecutedListener();
+ }
+
+ private _initInterceptorEditorStart() {
+ this.disposeWithMe(
+ toDisposable(
+ this._editorBridgeService.interceptor.intercept(
+ this._editorBridgeService.interceptor.getInterceptPoints().BEFORE_CELL_EDIT,
+ {
+ handler: (value, context, next) => {
+ const { row, col, workbookId, worksheetId } = context;
+ const arrayFormulaMatrixRange = this._formulaDataModel.getArrayFormulaRange();
+
+ this._removeArrayFormulaRangeShape();
+
+ if (value == null) {
+ return next(value);
+ }
+
+ let cellInfo: Nullable<ICellDataForSheetInterceptor> = null;
+
+ const formulaDataItem = this._formulaDataModel.getFormulaDataItem(
+ row,
+ col,
+ worksheetId,
+ workbookId
+ );
+
+ if (formulaDataItem != null) {
+ const { f, si, x = 0, y = 0 } = formulaDataItem;
+
+ if (si != null && (x > 0 || y > 0)) {
+ let formulaString = '';
+ if (f.length > 0) {
+ formulaString = f;
+ } else {
+ const originItem = this._formulaDataModel.getFormulaItemBySId(
+ si,
+ worksheetId,
+ workbookId
+ );
+
+ if (originItem == null || originItem.f.length === 0) {
+ return next(value);
+ }
+
+ formulaString = originItem.f;
+ }
+
+ const newFormulaString = this._formulaEngineService.moveFormulaRefOffset(
+ formulaString,
+ x,
+ y
+ );
+
+ cellInfo = { f: newFormulaString };
+ }
+ }
+
+ const matrixRange = arrayFormulaMatrixRange?.[workbookId]?.[worksheetId];
+ if (matrixRange != null) {
+ new ObjectMatrix(matrixRange).forValue((rowIndex, columnIndex, range) => {
+ if (range == null) {
+ return true;
+ }
+ const { startRow, startColumn, endRow, endColumn } = range;
+ if (rowIndex === row && columnIndex === col) {
+ this._createArrayFormulaRangeShape(range, workbookId);
+ return false;
+ }
+ if (row >= startRow && row <= endRow && col >= startColumn && col <= endColumn) {
+ const formulaDataItem = this._formulaDataModel.getFormulaDataItem(
+ rowIndex,
+ columnIndex,
+ worksheetId,
+ workbookId
+ );
+
+ if (formulaDataItem == null || formulaDataItem.f == null) {
+ return true;
+ }
+
+ if (cellInfo == null) {
+ cellInfo = {
+ f: formulaDataItem.f,
+ isInArrayFormulaRange: true,
+ };
+ }
+
+ this._createArrayFormulaRangeShape(range, workbookId);
+ return false;
+ }
+ });
+ }
+
+ if (cellInfo) {
+ return cellInfo;
+ }
+
+ return next(value);
+ },
+ }
+ )
+ )
+ );
+ }
+
+ private _commandExecutedListener() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id === SetFormulaCalculationResultMutation.id) {
+ this._removeArrayFormulaRangeShape();
+ }
+ })
+ );
+ }
+
+ private _createArrayFormulaRangeShape(arrayRange: IRange, unitId: string) {
+ const styleSheet = this._themeService.getCurrentTheme();
+ const fill = new TinyColor(styleSheet.colorWhite).setAlpha(0).toString();
+ const style = {
+ strokeWidth: 1,
+ stroke: styleSheet.hyacinth700,
+ fill,
+ widgets: {},
+
+ hasAutoFill: false,
+
+ hasRowHeader: false,
+
+ hasColumnHeader: false,
+ };
+
+ const { scene } = this._renderManagerService.getRenderById(unitId) || {};
+ const { rangeWithCoord, primaryWithCoord } = this._selectionRenderService.convertSelectionRangeToData({
+ range: arrayRange,
+ primary: null,
+ style,
+ });
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
+ if (!scene || !skeleton) return;
+ const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+ const control = new SelectionShape(scene, 100, false, this._themeService);
+ control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
+
+ this._previousShape = control;
+ }
+
+ private _removeArrayFormulaRangeShape() {
+ if (this._previousShape == null) {
+ return;
+ }
+ this._previousShape.dispose();
+ this._previousShape = null;
+ }
+}
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index 0fca83f649..3ae40796d4 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -1,4 +1,4 @@
-import type { ICommandInfo, IRange, IRangeWithCoord, ITextRun, Nullable } from '@univerjs/core';
+import type { ICommandInfo, IRangeWithCoord, ITextRun, Nullable } from '@univerjs/core';
import {
deserializeRangeWithSheet,
Direction,
@@ -35,7 +35,12 @@ import {
normalizeSheetName,
sequenceNodeType,
} from '@univerjs/engine-formula';
-import { DeviceInputEventType, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';
+import {
+ DeviceInputEventType,
+ getCellInfoInMergeData,
+ IRenderManagerService,
+ ITextSelectionRenderManager,
+} from '@univerjs/engine-render';
import type { ISelectionWithStyle } from '@univerjs/sheets';
import {
convertSelectionDataToRange,
@@ -327,7 +332,7 @@ export class PromptController extends Disposable {
this.disposeWithMe(
toDisposable(
- this._selectionManagerService.selectionInfo$.subscribe(() => {
+ this._selectionManagerService.selectionMoveEnd$.subscribe(() => {
// Each range change requires re-listening
disposableCollection.dispose();
@@ -393,8 +398,8 @@ export class PromptController extends Disposable {
);
}
- private _selectionChanging(ranges: Nullable<IRange[]>, isSync: boolean = false) {
- if (ranges == null) {
+ private _selectionChanging(selectionWithStyles: ISelectionWithStyle[], isSync: boolean = false) {
+ if (selectionWithStyles.length === 0) {
return;
}
@@ -404,24 +409,37 @@ export class PromptController extends Disposable {
this._formulaInputService.enableSelectionMoving();
- this._inertControlSelection(ranges);
+ this._inertControlSelection(selectionWithStyles);
- if (ranges == null || isSync === false) {
+ if (isSync === false) {
return;
}
- const currentRange = ranges[ranges.length - 1];
- this._inertControlSelectionReplace(currentRange);
+ const currentSelection = selectionWithStyles[selectionWithStyles.length - 1];
+ this._inertControlSelectionReplace(currentSelection);
}
private _initialRefSelectionInsertEvent() {
this.disposeWithMe(
- toDisposable(this._selectionRenderService.selectionMoving$.subscribe(this._selectionChanging.bind(this)))
+ toDisposable(
+ this._selectionRenderService.selectionMoving$.subscribe((selectionWithCoordAndStyles) => {
+ this._selectionChanging(
+ selectionWithCoordAndStyles.map((selectionDataWithStyle) =>
+ convertSelectionDataToRange(selectionDataWithStyle)
+ )
+ );
+ })
+ )
);
this.disposeWithMe(
toDisposable(
- this._selectionRenderService.selectionMoveStart$.subscribe((ranges) => {
- this._selectionChanging(ranges, true);
+ this._selectionRenderService.selectionMoveStart$.subscribe((selectionWithCoordAndStyles) => {
+ this._selectionChanging(
+ selectionWithCoordAndStyles.map((selectionDataWithStyle) =>
+ convertSelectionDataToRange(selectionDataWithStyle)
+ ),
+ true
+ );
})
)
);
@@ -825,7 +843,7 @@ export class PromptController extends Disposable {
themeColor = this._stringColor;
}
- if (themeColor.length > 0) {
+ if (themeColor && themeColor.length > 0) {
textRuns.push({
st: startIndex + 1,
ed: endIndex + 2,
@@ -890,11 +908,39 @@ export class PromptController extends Disposable {
) {
return true;
}
+ if (
+ startRow === range.startRow &&
+ startColumn === range.startColumn &&
+ range.startRow === range.endRow &&
+ range.startColumn === range.endColumn
+ ) {
+ return true;
+ }
return false;
})?.primary;
if (primary != null) {
+ const {
+ isMerged,
+ isMergedMainCell,
+ startRow: mergeStartRow,
+ endRow: mergeEndRow,
+ startColumn: mergeStartColumn,
+ endColumn: mergeEndColumn,
+ } = primary;
+
+ if (
+ (isMerged || isMergedMainCell) &&
+ mergeStartRow === range.startRow &&
+ mergeStartColumn === range.startColumn &&
+ range.startRow === range.endRow &&
+ range.startColumn === range.endColumn
+ ) {
+ range.endRow = mergeEndRow;
+ range.endColumn = mergeEndColumn;
+ }
+
lastRange = {
range,
primary,
@@ -952,11 +998,12 @@ export class PromptController extends Disposable {
};
}
- const { unitId, sheetId } = current;
+ const { unitId, sheetId, skeleton } = current;
return {
unitId,
sheetId,
+ skeleton,
};
}
@@ -965,7 +1012,7 @@ export class PromptController extends Disposable {
* @param range
* @returns
*/
- private _getRefString(range: IRange) {
+ private _getRefString(currentSelection: ISelectionWithStyle) {
const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
let refUnitId = '';
@@ -983,7 +1030,34 @@ export class PromptController extends Disposable {
refSheetName = this._getSheetNameById(unitId, sheetId);
}
- const { startRow, endRow, startColumn, endColumn } = range;
+ const { range, primary } = currentSelection;
+
+ let { startRow, endRow, startColumn, endColumn } = range;
+
+ if (primary) {
+ const {
+ isMerged,
+ isMergedMainCell,
+ startRow: mergeStartRow,
+ endRow: mergeEndRow,
+ startColumn: mergeStartColumn,
+ endColumn: mergeEndColumn,
+ } = primary;
+
+ if (
+ (isMerged || isMergedMainCell) &&
+ mergeStartRow === startRow &&
+ mergeStartColumn === startColumn &&
+ mergeEndRow === endRow &&
+ mergeEndColumn === endColumn
+ ) {
+ startRow = mergeStartRow;
+ startColumn = mergeStartColumn;
+ endRow = mergeStartRow;
+ endColumn = mergeStartColumn;
+ }
+ }
+
return serializeRangeToRefString({
sheetName: refSheetName,
unitId: refUnitId,
@@ -1099,7 +1173,7 @@ export class PromptController extends Disposable {
docViewModel.reset(documentDataModel);
}
- private _inertControlSelectionReplace(currentRange: IRange) {
+ private _inertControlSelectionReplace(currentSelection: ISelectionWithStyle) {
if (this._previousSequenceNodes == null) {
this._previousSequenceNodes = this._formulaInputService.getSequenceNodes();
}
@@ -1114,7 +1188,7 @@ export class PromptController extends Disposable {
return;
}
- const refString = this._getRefString(currentRange);
+ const refString = this._getRefString(currentSelection);
this._formulaInputService.setSequenceNodes(insertNodes);
@@ -1138,14 +1212,14 @@ export class PromptController extends Disposable {
// }
}
- private _inertControlSelection(ranges: IRange[]) {
- const currentRange = ranges[ranges.length - 1];
+ private _inertControlSelection(selectionWithStyles: ISelectionWithStyle[]) {
+ const currentSelection = selectionWithStyles[selectionWithStyles.length - 1];
if (
- (ranges.length === this._previousRangesCount || this._previousRangesCount === 0) &&
+ (selectionWithStyles.length === this._previousRangesCount || this._previousRangesCount === 0) &&
this._previousSequenceNodes != null
) {
- this._inertControlSelectionReplace(currentRange);
+ this._inertControlSelectionReplace(currentSelection);
} else {
// Holding down ctrl causes an addition, requiring the ref string to be increased.
let insertNodes = this._formulaInputService.getSequenceNodes();
@@ -1172,7 +1246,7 @@ export class PromptController extends Disposable {
this._previousSequenceNodes = Tools.deepClone(insertNodes);
- const refString = this._getRefString(currentRange);
+ const refString = this._getRefString(currentSelection);
this._formulaInputService.setSequenceNodes(insertNodes);
@@ -1185,7 +1259,7 @@ export class PromptController extends Disposable {
this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
- this._previousRangesCount = ranges.length;
+ this._previousRangesCount = selectionWithStyles.length;
}
private _updateRefSelectionStyle(refSelections: IRefSelection[]) {
@@ -1222,6 +1296,14 @@ export class PromptController extends Disposable {
) {
return true;
}
+ if (
+ startRow === range.startRow &&
+ startColumn === range.startColumn &&
+ range.startRow === range.endRow &&
+ range.startColumn === range.endColumn
+ ) {
+ return true;
+ }
return false;
});
@@ -1241,6 +1323,8 @@ export class PromptController extends Disposable {
return;
}
+ const { unitId, sheetId, skeleton } = this._getCurrentUnitIdAndSheetId();
+
this._formulaInputService.enableLockedSelectionChange();
const id = controlSelection.selectionStyle?.id;
@@ -1249,12 +1333,43 @@ export class PromptController extends Disposable {
return;
}
- const { startRow, endRow, startColumn, endColumn } = toRange;
+ let { startRow, endRow, startColumn, endColumn } = toRange;
+
+ const primary = getCellInfoInMergeData(startRow, startColumn, skeleton?.mergeData);
+
+ if (primary) {
+ const {
+ isMerged,
+ isMergedMainCell,
+ startRow: mergeStartRow,
+ endRow: mergeEndRow,
+ startColumn: mergeStartColumn,
+ endColumn: mergeEndColumn,
+ } = primary;
+
+ if (
+ (isMerged || isMergedMainCell) &&
+ mergeStartRow === startRow &&
+ mergeStartColumn === startColumn &&
+ mergeEndRow === endRow &&
+ mergeEndColumn === endColumn
+ ) {
+ startRow = mergeStartRow;
+ startColumn = mergeStartColumn;
+ endRow = mergeStartRow;
+ endColumn = mergeStartColumn;
+ }
+ }
+
const refString = this._getRefString({
- startRow,
- endRow,
- startColumn,
- endColumn,
+ range: {
+ startRow,
+ endRow,
+ startColumn,
+ endColumn,
+ },
+ primary,
+ style: null,
});
const nodeIndex = Number(id);
@@ -1427,11 +1542,11 @@ export class PromptController extends Disposable {
});
}
- const ranges = this._selectionManagerService.getSelectionRanges() || [];
+ const selectionWithStyles = this._selectionManagerService.getSelections() || [];
- const currentRange = ranges[ranges.length - 1];
+ const currentSelection = selectionWithStyles[selectionWithStyles.length - 1];
- this._inertControlSelectionReplace(currentRange);
+ this._inertControlSelectionReplace(currentSelection);
}
})
);
diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.ts
index eb2afb0a81..535f674ecd 100644
--- a/packages/sheets-formula/src/formula-ui-plugin.ts
+++ b/packages/sheets-formula/src/formula-ui-plugin.ts
@@ -7,6 +7,7 @@ import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';
import { ArrayFormulaDisplayController } from './controllers/array-formula-display.controller';
import { FormulaAutoFillController } from './controllers/formula-auto-fill.controller';
import { FormulaClipboardController } from './controllers/formula-clipboard.controller';
+import { FormulaEditorShowController } from './controllers/formula-editor-show.controller';
import { FormulaInputController } from './controllers/formula-input.controller';
import { FormulaUIController } from './controllers/formula-ui.controller';
import { PromptController } from './controllers/prompt.controller';
@@ -58,6 +59,7 @@ export class FormulaUIPlugin extends Plugin {
[ArrayFormulaDisplayController],
[TriggerCalculationController],
[UpdateFormulaController],
+ [FormulaEditorShowController],
];
dependencies.forEach((dependency) => this._injector.add(dependency));
diff --git a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.controller.ts
index fb7b7f98d6..4f1ded8544 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt.controller.ts
@@ -1,4 +1,4 @@
-import type { ICellData, IRange } from '@univerjs/core';
+import type { ICellData, ICellDataForSheetInterceptor, IRange } from '@univerjs/core';
import {
CellValueType,
Disposable,
@@ -265,13 +265,13 @@ export class NumfmtController extends Disposable implements INumfmtController {
return next(cell);
}
- const res: ICellData = { v: numfmtRes };
+ const res: ICellDataForSheetInterceptor = { v: numfmtRes };
if (info.color) {
const color = this._themeService.getCurrentTheme()[`${info.color}500`];
if (color) {
- res.s = { cl: { rgb: color } };
+ res.interceptorStyle = { cl: { rgb: color } };
}
}
@@ -323,7 +323,7 @@ export class NumfmtController extends Disposable implements INumfmtController {
});
const combineOpenAndSelection$ = combineLatest([
isPanelOpenObserver,
- this._selectionManagerService.selectionInfo$.pipe(
+ this._selectionManagerService.selectionMoveEnd$.pipe(
map((selectionInfos) => {
if (!selectionInfos) {
return [];
diff --git a/packages/sheets-numfmt/src/menu/menu.ts b/packages/sheets-numfmt/src/menu/menu.ts
index e958c9b52b..6a5cbfa30f 100644
--- a/packages/sheets-numfmt/src/menu/menu.ts
+++ b/packages/sheets-numfmt/src/menu/menu.ts
@@ -72,7 +72,7 @@ export const FactoryOtherMenuItem = (componentManager: ComponentManager) => {
const selectionManagerService = _accessor.get(SelectionManagerService);
const value$ = new Observable((subscribe) =>
merge(
- selectionManagerService.selectionInfo$,
+ selectionManagerService.selectionMoveEnd$,
new Observable<null>((commandSubscribe) => {
const disposable = commandService.onCommandExecuted((commandInfo) => {
if (commandInfo.id === SetNumfmtMutation.id) {
diff --git a/packages/sheets-ui/src/components/range-selector/RangeSelector.tsx b/packages/sheets-ui/src/components/range-selector/RangeSelector.tsx
index 0b4d89ffce..4ff5ed1f7a 100644
--- a/packages/sheets-ui/src/components/range-selector/RangeSelector.tsx
+++ b/packages/sheets-ui/src/components/range-selector/RangeSelector.tsx
@@ -22,7 +22,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
useEffect(() => {
if (active) {
onActive(active);
- const subscribe = textSelectionManagerService.selectionInfo$.subscribe((selectionInfo) => {
+ const subscribe = textSelectionManagerService.selectionMoveEnd$.subscribe((selectionInfo) => {
// TODO@Dushusir: get range text info from selectionInfo
const rangeTextList = ['A1', 'B2:C3', 'Sheet2!A1:B2', 'D10:E11,F1:G2,H3:I4'];
const randomIndex = Math.floor(Math.random() * rangeTextList.length);
diff --git a/packages/sheets-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
index 2868a12710..8c5c7808a8 100644
--- a/packages/sheets-ui/src/controllers/auto-fill.controller.ts
+++ b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
@@ -145,7 +145,7 @@ export class AutoFillController extends Disposable {
const disposableCollection = new DisposableCollection();
this.disposeWithMe(
toDisposable(
- this._selectionManagerService.selectionInfo$.subscribe(() => {
+ this._selectionManagerService.selectionMoveEnd$.subscribe(() => {
// Each range change requires re-listening
disposableCollection.dispose();
diff --git a/packages/sheets-ui/src/controllers/editor-bridge.controller.ts b/packages/sheets-ui/src/controllers/editor-bridge.controller.ts
index a585ff35ee..1c77d5616f 100644
--- a/packages/sheets-ui/src/controllers/editor-bridge.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor-bridge.controller.ts
@@ -1,4 +1,4 @@
-import type { ICommandInfo } from '@univerjs/core';
+import type { ICommandInfo, Nullable } from '@univerjs/core';
import {
Disposable,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
@@ -7,8 +7,10 @@ import {
LifecycleStages,
makeCellToSelection,
OnLifecycle,
+ ThemeService,
} from '@univerjs/core';
import { DeviceInputEventType, getCanvasOffsetByEngine, IRenderManagerService } from '@univerjs/engine-render';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
import {
COMMAND_LISTENER_SKELETON_CHANGE,
NORMAL_SELECTION_PLUGIN_NAME,
@@ -33,7 +35,8 @@ export class EditorBridgeController extends Disposable {
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService
+ @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService
) {
super();
@@ -51,109 +54,134 @@ export class EditorBridgeController extends Disposable {
}
private _initialSelectionListener() {
- this._selectionManagerService.selectionInfo$.subscribe((params) => {
- const current = this._selectionManagerService.getCurrent();
-
- /**
- * The editor only responds to regular selections.
- */
- if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return;
- }
+ this._selectionManagerService.selectionMoveEnd$.subscribe((params) => {
+ this._selectionListener(params);
+ });
+ this._selectionManagerService.selectionMoveStart$.subscribe((params) => {
+ this._selectionListener(params);
+ });
+ }
- const currentSkeleton = this._sheetSkeletonManagerService.getCurrent();
+ private _selectionListener(params: Nullable<ISelectionWithStyle[]>) {
+ const current = this._selectionManagerService.getCurrent();
- const sheetObject = this._getSheetObject();
+ /**
+ * The editor only responds to regular selections.
+ */
+ if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
+ return;
+ }
- if (currentSkeleton == null || sheetObject == null) {
- return;
- }
+ const currentSkeleton = this._sheetSkeletonManagerService.getCurrent();
- const { skeleton, unitId, sheetId } = currentSkeleton;
+ const sheetObject = this._getSheetObject();
- const { scene, engine } = sheetObject;
+ if (currentSkeleton == null || sheetObject == null) {
+ return;
+ }
- if (params == null || params.length === 0 || skeleton == null || params[params.length - 1] == null) {
- return;
- }
+ const { skeleton, unitId, sheetId } = currentSkeleton;
- const { primary } = params[params.length - 1];
+ const { scene, engine } = sheetObject;
- if (primary == null) {
- return;
- }
+ if (params == null || params.length === 0 || skeleton == null || params[params.length - 1] == null) {
+ return;
+ }
- const { startRow, startColumn } = primary;
+ const { primary } = params[params.length - 1];
- const primaryWithCoord = this._selectionRenderService.convertCellRangeToInfo(primary);
+ if (primary == null) {
+ return;
+ }
- if (primaryWithCoord == null) {
- return;
- }
+ const { startRow, startColumn } = primary;
- const actualRangeWithCoord = makeCellToSelection(primaryWithCoord);
+ const primaryWithCoord = this._selectionRenderService.convertCellRangeToInfo(primary);
- if (actualRangeWithCoord == null) {
- return;
- }
+ if (primaryWithCoord == null) {
+ return;
+ }
- const canvasOffset = getCanvasOffsetByEngine(engine);
+ const actualRangeWithCoord = makeCellToSelection(primaryWithCoord);
- let { startX, startY, endX, endY } = actualRangeWithCoord;
+ if (actualRangeWithCoord == null) {
+ return;
+ }
+
+ const canvasOffset = getCanvasOffsetByEngine(engine);
- const { scaleX, scaleY } = scene.getAncestorScale();
+ let { startX, startY, endX, endY } = actualRangeWithCoord;
- const scrollXY = scene.getScrollXY(this._selectionRenderService.getViewPort());
+ const { scaleX, scaleY } = scene.getAncestorScale();
- startX = skeleton.convertTransformToOffsetX(startX, scaleX, scrollXY);
+ const scrollXY = scene.getScrollXY(this._selectionRenderService.getViewPort());
- startY = skeleton.convertTransformToOffsetY(startY, scaleY, scrollXY);
+ startX = skeleton.convertTransformToOffsetX(startX, scaleX, scrollXY);
- endX = skeleton.convertTransformToOffsetX(endX, scaleX, scrollXY);
+ startY = skeleton.convertTransformToOffsetY(startY, scaleY, scrollXY);
- endY = skeleton.convertTransformToOffsetY(endY, scaleY, scrollXY);
+ endX = skeleton.convertTransformToOffsetX(endX, scaleX, scrollXY);
- const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ endY = skeleton.convertTransformToOffsetY(endY, scaleY, scrollXY);
- const worksheet = workbook.getActiveSheet();
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
- const location = {
- workbook,
- worksheet,
- workbookId: workbook.getUnitId(),
- worksheetId: worksheet.getSheetId(),
- row: startRow,
- col: startColumn,
- };
- const cell = this._editorBridgeService.interceptor.fetchThroughInterceptors(
- this._editorBridgeService.interceptor.getInterceptPoints().BEFORE_CELL_EDIT
- )(worksheet.getCell(startRow, startColumn), location);
+ const worksheet = workbook.getActiveSheet();
- let documentLayoutObject = cell && skeleton.getCellDocumentModelWithFormula(cell);
+ const location = {
+ workbook,
+ worksheet,
+ workbookId: workbook.getUnitId(),
+ worksheetId: worksheet.getSheetId(),
+ row: startRow,
+ col: startColumn,
+ };
+ const cell = this._editorBridgeService.interceptor.fetchThroughInterceptors(
+ this._editorBridgeService.interceptor.getInterceptPoints().BEFORE_CELL_EDIT
+ )(worksheet.getCell(startRow, startColumn), location);
- if (!documentLayoutObject || documentLayoutObject.documentModel == null) {
- documentLayoutObject = skeleton.getBlankCellDocumentModel(cell);
+ let documentLayoutObject = cell && skeleton.getCellDocumentModelWithFormula(cell);
+
+ if (!documentLayoutObject || documentLayoutObject.documentModel == null) {
+ documentLayoutObject = skeleton.getBlankCellDocumentModel(cell);
+ }
+
+ documentLayoutObject.documentModel?.setZoomRatio(Math.max(scaleX, scaleY));
+
+ if (cell?.isInArrayFormulaRange === true) {
+ const body = documentLayoutObject.documentModel?.getBody();
+ if (body) {
+ body.textRuns = [
+ {
+ st: 0,
+ ed: body.dataStream.length - 2,
+ ts: {
+ cl: {
+ rgb: this._themeService.getCurrentTheme().textColorSecondary,
+ },
+ },
+ },
+ ];
}
+ }
- documentLayoutObject.documentModel?.setZoomRatio(Math.max(scaleX, scaleY));
-
- this._commandService.executeCommand(SetActivateCellEditOperation.id, {
- position: {
- startX,
- startY,
- endX,
- endY,
- },
- scaleX,
- scaleY,
- canvasOffset,
- row: startRow,
- column: startColumn,
- unitId,
- sheetId,
- documentLayoutObject,
- editorUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- });
+ this._commandService.executeCommand(SetActivateCellEditOperation.id, {
+ position: {
+ startX,
+ startY,
+ endX,
+ endY,
+ },
+ scaleX,
+ scaleY,
+ canvasOffset,
+ row: startRow,
+ column: startColumn,
+ unitId,
+ sheetId,
+ documentLayoutObject,
+ editorUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ isInArrayFormulaRange: cell?.isInArrayFormulaRange,
});
}
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 5d07cead1c..ab21e53ea1 100644
--- a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
@@ -1,4 +1,4 @@
-import type { ICommandInfo, IParagraph, Nullable } from '@univerjs/core';
+import type { ICommandInfo, IParagraph, ITextRun, Nullable } from '@univerjs/core';
import {
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
@@ -32,6 +32,7 @@ import { takeUntil } from 'rxjs';
import { getEditorObject } from '../../basics/editor/get-editor-object';
import { SetEditorResizeOperation } from '../../commands/operations/set-editor-resize.operation';
import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
+import type { IEditorBridgeServiceParam } from '../../services/editor-bridge.service';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
@OnLifecycle(LifecycleStages.Steady, FormulaEditorController)
@@ -197,21 +198,55 @@ export class FormulaEditorController extends RxDisposable {
return;
}
- const body = param.documentLayoutObject.documentModel?.getBody();
- const dataStream = body?.dataStream;
- const paragraphs = body?.paragraphs;
+ this._editorSyncHandler(param);
+ });
- if (dataStream == null || paragraphs == null) {
+ this._editorBridgeService.visible$.pipe(takeUntil(this.dispose$)).subscribe((state) => {
+ if (state == null || state.visible === false || this._editorBridgeService.isForceKeepVisible()) {
return;
}
- this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, dataStream, paragraphs);
+ const param = this._editorBridgeService.getState();
- // Also need to resize document and scene after sync content.
- this._autoScroll();
+ if (param == null) {
+ return;
+ }
+
+ this._editorSyncHandler(param);
});
}
+ private _editorSyncHandler(param: IEditorBridgeServiceParam) {
+ const body = param.documentLayoutObject.documentModel?.getBody();
+
+ let dataStream = body?.dataStream;
+ let paragraphs = body?.paragraphs;
+ let textRuns: ITextRun[] = [];
+
+ if (dataStream == null || paragraphs == null) {
+ return;
+ }
+
+ if (
+ param.isInArrayFormulaRange === true &&
+ this._editorBridgeService.isVisible().eventType === DeviceInputEventType.Dblclick
+ ) {
+ dataStream = '\r\n';
+ paragraphs = [
+ {
+ startIndex: 0,
+ },
+ ];
+ } else if (param.isInArrayFormulaRange === true) {
+ textRuns = body?.textRuns || [];
+ }
+
+ this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, dataStream, paragraphs, textRuns);
+
+ // Also need to resize document and scene after sync content.
+ this._autoScroll();
+ }
+
private _commandExecutedListener() {
const updateCommandList = [RichTextEditingMutation.id, SetEditorResizeOperation.id];
@@ -257,7 +292,12 @@ export class FormulaEditorController extends RxDisposable {
);
}
- private _syncContentAndRender(unitId: string, dataStream: string, paragraphs: IParagraph[]) {
+ private _syncContentAndRender(
+ unitId: string,
+ dataStream: string,
+ paragraphs: IParagraph[],
+ textRuns: ITextRun[] = []
+ ) {
const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
const docsSkeletonObject = this._docSkeletonManagerService.getSkeletonByUnitId(unitId);
@@ -276,6 +316,10 @@ export class FormulaEditorController extends RxDisposable {
docDataModel.getBody()!.textRuns = [];
}
+ if (textRuns.length > 0) {
+ docDataModel.getBody()!.textRuns = textRuns;
+ }
+
docViewModel.reset(docDataModel);
const { skeleton } = docsSkeletonObject;
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 7f99c26c35..5345bcb5c3 100644
--- a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
@@ -441,7 +441,16 @@ export class StartEditController extends Disposable {
return;
}
- const { position, documentLayoutObject, canvasOffset, scaleX, scaleY, editorUnitId, unitId } = state;
+ const {
+ position,
+ documentLayoutObject,
+ canvasOffset,
+ scaleX,
+ scaleY,
+ editorUnitId,
+ unitId,
+ isInArrayFormulaRange = false,
+ } = state;
const editorObject = this._getEditorObject();
@@ -466,7 +475,10 @@ export class StartEditController extends Disposable {
this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);
// move selection
- if (eventType === DeviceInputEventType.Keyboard) {
+ if (
+ eventType === DeviceInputEventType.Keyboard ||
+ (eventType === DeviceInputEventType.Dblclick && isInArrayFormulaRange)
+ ) {
const snapshot = Tools.deepClone(documentDataModel.snapshot) as IDocumentData;
const documentViewModel = this._docViewModelManagerService.getCurrent()?.docViewModel!;
this._resetBodyStyle(snapshot.body!);
@@ -477,7 +489,7 @@ export class StartEditController extends Disposable {
document.makeDirty();
// @JOCS, Why calculate here?
- if (keycode === KeyCode.BACKSPACE) {
+ if (keycode === KeyCode.BACKSPACE || eventType === DeviceInputEventType.Dblclick) {
skeleton.calculate();
}
diff --git a/packages/sheets-ui/src/controllers/move-range.controller.ts b/packages/sheets-ui/src/controllers/move-range.controller.ts
index 9d05bab575..48bb579e65 100644
--- a/packages/sheets-ui/src/controllers/move-range.controller.ts
+++ b/packages/sheets-ui/src/controllers/move-range.controller.ts
@@ -29,7 +29,7 @@ export class MoveRangeController extends Disposable {
this.disposeWithMe(
toDisposable(
- this._selectionManagerService.selectionInfo$.subscribe(() => {
+ this._selectionManagerService.selectionMoveEnd$.subscribe(() => {
// Each range change requires re-listening
disposableCollection.dispose();
diff --git a/packages/sheets-ui/src/controllers/selection.controller.ts b/packages/sheets-ui/src/controllers/selection.controller.ts
index 116556caae..6208d1f94b 100644
--- a/packages/sheets-ui/src/controllers/selection.controller.ts
+++ b/packages/sheets-ui/src/controllers/selection.controller.ts
@@ -11,11 +11,13 @@ import {
} from '@univerjs/core';
import type { IMouseEvent, IPointerEvent, SpreadsheetSkeleton } from '@univerjs/engine-render';
import { IRenderManagerService, ScrollTimerType } from '@univerjs/engine-render';
+import type { ISelectionWithCoordAndStyle } from '@univerjs/sheets';
import {
convertSelectionDataToRange,
getNormalSelectionStyle,
NORMAL_SELECTION_PLUGIN_NAME,
SelectionManagerService,
+ SelectionMoveType,
SetSelectionsOperation,
transformCellDataToSelectionData,
} from '@univerjs/sheets';
@@ -174,7 +176,7 @@ export class SelectionController extends Disposable {
private _initSelectionChangeListener() {
this.disposeWithMe(
toDisposable(
- this._selectionManagerService.selectionInfo$.subscribe((param) => {
+ this._selectionManagerService.selectionMoveEnd$.subscribe((param) => {
this._selectionRenderService.reset();
if (param == null) {
return;
@@ -194,24 +196,37 @@ export class SelectionController extends Disposable {
}
private _initUserActionSyncListener() {
- this._selectionRenderService.selectionRangeWithStyle$.subscribe((selectionDataWithStyleList) => {
- const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
- const unitId = workbook.getUnitId();
- const sheetId = workbook.getActiveSheet().getSheetId();
- const current = this._selectionManagerService.getCurrent();
+ this._selectionRenderService.selectionMoveStart$.subscribe((params) => {
+ this._move(params, SelectionMoveType.MOVE_START);
+ });
- if (selectionDataWithStyleList == null || selectionDataWithStyleList.length === 0) {
- return;
- }
+ this._selectionRenderService.selectionMoving$.subscribe((params) => {
+ this._move(params, SelectionMoveType.MOVING);
+ });
- this._commandService.executeCommand(SetSelectionsOperation.id, {
- unitId,
- sheetId,
- pluginName: current?.pluginName || NORMAL_SELECTION_PLUGIN_NAME,
- selections: selectionDataWithStyleList.map((selectionDataWithStyle) =>
- convertSelectionDataToRange(selectionDataWithStyle)
- ),
- });
+ this._selectionRenderService.selectionMoveEnd$.subscribe((params) => {
+ this._move(params, SelectionMoveType.MOVE_END);
+ });
+ }
+
+ private _move(selectionDataWithStyleList: ISelectionWithCoordAndStyle[], type: SelectionMoveType) {
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const unitId = workbook.getUnitId();
+ const sheetId = workbook.getActiveSheet().getSheetId();
+ const current = this._selectionManagerService.getCurrent();
+
+ if (selectionDataWithStyleList == null || selectionDataWithStyleList.length === 0) {
+ return;
+ }
+
+ this._commandService.executeCommand(SetSelectionsOperation.id, {
+ unitId,
+ sheetId,
+ type,
+ pluginName: current?.pluginName || NORMAL_SELECTION_PLUGIN_NAME,
+ selections: selectionDataWithStyleList.map((selectionDataWithStyle) =>
+ convertSelectionDataToRange(selectionDataWithStyle)
+ ),
});
}
diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.ts
index 0922c7bc42..bb0f5a37f1 100644
--- a/packages/sheets-ui/src/controllers/status-bar.controller.ts
+++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts
@@ -12,7 +12,6 @@ import { FormulaEngineService, RangeReferenceObject } from '@univerjs/engine-for
import { SelectionManagerService } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
-import { ISelectionRenderService } from '..';
import type { IStatusBarServiceStatus } from '../services/status-bar.service';
import { IStatusBarService } from '../services/status-bar.service';
@@ -22,8 +21,7 @@ export class StatusBarController extends Disposable {
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
@Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
- @IStatusBarService private readonly _statusBarService: IStatusBarService,
- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService
+ @IStatusBarService private readonly _statusBarService: IStatusBarService
) {
super();
@@ -37,16 +35,16 @@ export class StatusBarController extends Disposable {
private _registerSelectionListener(): void {
this.disposeWithMe(
toDisposable(
- this._selectionRenderService.selectionMoving$.subscribe((selections) => {
+ this._selectionManagerService.selectionMoving$.subscribe((selections) => {
if (selections) {
- this._calculateSelection(selections);
+ this._calculateSelection(selections.map((selection) => selection.range));
}
})
)
);
this.disposeWithMe(
toDisposable(
- this._selectionManagerService.selectionInfo$.subscribe((selections) => {
+ this._selectionManagerService.selectionMoveEnd$.subscribe((selections) => {
if (selections) {
this._calculateSelection(selections.map((selection) => selection.range));
}
diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.ts
index 172dcfba75..12989f5a07 100644
--- a/packages/sheets-ui/src/services/editor-bridge.service.ts
+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts
@@ -1,4 +1,4 @@
-import type { ICellData, IPosition, Nullable } from '@univerjs/core';
+import type { ICellDataForSheetInterceptor, IPosition, Nullable } from '@univerjs/core';
import { createInterceptorKey, Disposable, InterceptorManager, toDisposable } from '@univerjs/core';
import type { IDocumentLayoutObject } from '@univerjs/engine-render';
import { DeviceInputEventType } from '@univerjs/engine-render';
@@ -26,9 +26,10 @@ export interface IEditorBridgeServiceParam {
scaleX: number;
scaleY: number;
editorUnitId: string;
+ isInArrayFormulaRange?: Nullable<boolean>;
}
-const BEFORE_CELL_EDIT = createInterceptorKey<ICellData, ISheetLocation>('BEFORE_CELL_EDIT');
-const AFTER_CELL_EDIT = createInterceptorKey<ICellData, ISheetLocation>('AFTER_CELL_EDIT');
+const BEFORE_CELL_EDIT = createInterceptorKey<ICellDataForSheetInterceptor, ISheetLocation>('BEFORE_CELL_EDIT');
+const AFTER_CELL_EDIT = createInterceptorKey<ICellDataForSheetInterceptor, ISheetLocation>('AFTER_CELL_EDIT');
export interface IEditorBridgeService {
state$: Observable<Nullable<IEditorBridgeServiceParam>>;
visible$: Observable<IEditorBridgeServiceVisibleParam>;
diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.ts
index e9bae8160d..6648549193 100644
--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts
@@ -1,6 +1,7 @@
import type {
IRange,
IRangeWithCoord,
+ ISelection,
ISelectionCell,
ISelectionCellWithCoord,
ISelectionWithCoord,
@@ -27,10 +28,10 @@ export interface IControlFillConfig {
}
export interface ISelectionRenderService {
- readonly selectionRangeWithStyle$: Observable<ISelectionWithCoordAndStyle[]>;
+ readonly selectionMoveEnd$: Observable<ISelectionWithCoordAndStyle[]>;
readonly controlFillConfig$: Observable<IControlFillConfig | null>;
- readonly selectionMoving$: Observable<Nullable<IRange[]>>;
- readonly selectionMoveStart$: Observable<Nullable<IRange[]>>;
+ readonly selectionMoving$: Observable<ISelectionWithCoordAndStyle[]>;
+ readonly selectionMoveStart$: Observable<ISelectionWithCoordAndStyle[]>;
enableHeaderHighlight(): void;
disableHeaderHighlight(): void;
@@ -51,7 +52,7 @@ export interface ISelectionRenderService {
changeRuntime(skeleton: SpreadsheetSkeleton, scene: Scene, viewport?: Viewport): void;
getViewPort(): Viewport;
getCurrentControls(): SelectionShape[];
- getActiveRangeList(): Nullable<IRange[]>;
+ getActiveSelections(): Nullable<ISelection[]>;
getActiveRange(): Nullable<IRange>;
getActiveSelection(): Nullable<SelectionShape>;
getSelectionDataWithStyle(): ISelectionWithCoordAndStyle[];
@@ -141,19 +142,19 @@ export class SelectionRenderService implements ISelectionRenderService {
private _isSkipRemainLastEnable: boolean = false;
- private readonly _selectionRangeWithStyle$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
+ private readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
// When the user draws a selection area in the canvas content area, this event is broadcasted when the drawing ends.
- readonly selectionRangeWithStyle$ = this._selectionRangeWithStyle$.asObservable();
+ readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
- private readonly _selectionMoving$ = new Subject<Nullable<IRange[]>>();
+ private readonly _selectionMoving$ = new Subject<ISelectionWithCoordAndStyle[]>();
/**
* Triggered during the drawing of the selection area.
*/
readonly selectionMoving$ = this._selectionMoving$.asObservable();
- private readonly _selectionMoveStart$ = new Subject<Nullable<IRange[]>>();
+ private readonly _selectionMoveStart$ = new Subject<ISelectionWithCoordAndStyle[]>();
/**
* Triggered during the start draw the selection area.
@@ -318,16 +319,33 @@ export class SelectionRenderService implements ISelectionRenderService {
*
* @returns
*/
- getActiveRangeList(): Nullable<IRange[]> {
+ getActiveSelections(): Nullable<ISelection[]> {
const controls = this.getCurrentControls();
if (controls && controls.length > 0) {
const selections = controls?.map((control: SelectionShape) => {
const model: SelectionRenderModel = control.model;
+ const currentCell = model.currentCell;
+ let primary: Nullable<ISelectionCell> = null;
+ if (currentCell) {
+ primary = {
+ actualRow: currentCell.actualRow,
+ actualColumn: currentCell.actualColumn,
+ isMerged: currentCell.isMerged,
+ isMergedMainCell: currentCell.isMergedMainCell,
+ startRow: currentCell.mergeInfo.startRow,
+ startColumn: currentCell.mergeInfo.startColumn,
+ endRow: currentCell.mergeInfo.endRow,
+ endColumn: currentCell.mergeInfo.endColumn,
+ };
+ }
return {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
+ range: {
+ startRow: model.startRow,
+ startColumn: model.startColumn,
+ endRow: model.endRow,
+ endColumn: model.endColumn,
+ },
+ primary,
};
});
return selections;
@@ -608,7 +626,7 @@ export class SelectionRenderService implements ISelectionRenderService {
curControls.push(selectionControl);
}
- this._selectionMoveStart$.next([...(this.getActiveRangeList() || [])]);
+ this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
this.hasSelection = true;
@@ -643,7 +661,7 @@ export class SelectionRenderService implements ISelectionRenderService {
this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
this._endSelection();
- this._selectionRangeWithStyle$.next(this.getSelectionDataWithStyle());
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
// when selection mouse up, enable the short cut service
this._shortcutService.setDisable(false);
@@ -849,7 +867,7 @@ export class SelectionRenderService implements ISelectionRenderService {
) {
selectionControl.update(newSelectionRange, rowHeaderWidth, columnHeaderHeight);
- this._selectionMoving$.next(this.getActiveRangeList());
+ this._selectionMoving$.next(this.getSelectionDataWithStyle());
}
}
diff --git a/packages/sheets/src/basics/selection.ts b/packages/sheets/src/basics/selection.ts
index 2552d39979..eebd3bd524 100644
--- a/packages/sheets/src/basics/selection.ts
+++ b/packages/sheets/src/basics/selection.ts
@@ -127,32 +127,32 @@ export interface ISelectionWithStyle extends ISelection {
// The default configuration of the selection.
export function getNormalSelectionStyle(themeService: ThemeService): ISelectionStyle {
- const style = themeService.getCurrentTheme();
- const fill = new TinyColor(style.colorBlack).setAlpha(0.1).toString();
+ const styleSheet = themeService.getCurrentTheme();
+ const fill = new TinyColor(styleSheet.colorBlack).setAlpha(0.1).toString();
return {
strokeWidth: 2,
- stroke: style.primaryColor,
+ stroke: styleSheet.primaryColor,
// strokeDash: 8,
fill,
// widgets: { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true },
widgets: {},
widgetSize: 6,
widgetStrokeWidth: 1,
- widgetStroke: style.colorWhite,
+ widgetStroke: styleSheet.colorWhite,
hasAutoFill: true,
AutofillSize: 6,
AutofillStrokeWidth: 1,
- AutofillStroke: style.colorWhite,
+ AutofillStroke: styleSheet.colorWhite,
hasRowHeader: true,
rowHeaderFill: fill,
- rowHeaderStroke: style.primaryColor,
+ rowHeaderStroke: styleSheet.primaryColor,
rowHeaderStrokeWidth: 1,
hasColumnHeader: true,
columnHeaderFill: fill,
- columnHeaderStroke: style.primaryColor,
+ columnHeaderStroke: styleSheet.primaryColor,
columnHeaderStrokeWidth: 1,
};
}
diff --git a/packages/sheets/src/commands/operations/selection.operation.ts b/packages/sheets/src/commands/operations/selection.operation.ts
index f807502ea6..04bb74796a 100644
--- a/packages/sheets/src/commands/operations/selection.operation.ts
+++ b/packages/sheets/src/commands/operations/selection.operation.ts
@@ -2,6 +2,7 @@ import type { IOperation } from '@univerjs/core';
import { CommandType } from '@univerjs/core';
import type { ISelectionWithStyle } from '../../basics/selection';
+import type { SelectionMoveType } from '../../services/selection-manager.service';
import { SelectionManagerService } from '../../services/selection-manager.service';
export interface ISetSelectionsOperationParams {
@@ -9,23 +10,26 @@ export interface ISetSelectionsOperationParams {
worksheetId: string;
pluginName: string;
selections: ISelectionWithStyle[];
+ type?: SelectionMoveType;
}
export const SetSelectionsOperation: IOperation<ISetSelectionsOperationParams> = {
id: 'sheet.operation.set-selections',
type: CommandType.OPERATION,
handler: (accessor, params) => {
const selectionManagerService = accessor.get(SelectionManagerService);
- const selections = params?.selections;
- if (!selections) {
+
+ if (!params) {
return false;
}
+ const { selections, type } = params;
+
// TODO@yuhongz: incorrect coupling
// if (params.pluginName === FORMAT_PAINTER_SELECTION_PLUGIN_NAME) {
// selections.length > 1 && selections.splice(1, selections.length - 2);
// }
- selectionManagerService.replace(selections);
+ selectionManagerService.replace(selections, type);
return true;
},
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index a2ac579090..216e4e92b4 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -38,7 +38,11 @@ export {
export { MAX_CELL_PER_SHEET_KEY } from './controllers/config/config';
export { BorderStyleManagerService, type IBorderInfo } from './services/border-style-manager.service';
export { SheetEditablePermission, SheetPermissionService } from './services/permission';
-export { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from './services/selection-manager.service';
+export {
+ NORMAL_SELECTION_PLUGIN_NAME,
+ SelectionManagerService,
+ SelectionMoveType,
+} from './services/selection-manager.service';
// #region commands
diff --git a/packages/sheets/src/services/selection-manager.service.ts b/packages/sheets/src/services/selection-manager.service.ts
index 7e89c44cf2..cb4ae1cda6 100644
--- a/packages/sheets/src/services/selection-manager.service.ts
+++ b/packages/sheets/src/services/selection-manager.service.ts
@@ -1,6 +1,6 @@
import type { IRange, ISelectionCell, Nullable } from '@univerjs/core';
import type { IDisposable } from '@wendellhu/redi';
-import { BehaviorSubject } from 'rxjs';
+import { BehaviorSubject, Subject } from 'rxjs';
import type { ISelectionStyle, ISelectionWithStyle } from '../basics/selection';
@@ -19,6 +19,12 @@ export interface ISelectionManagerInsertParam extends ISelectionManagerSearchPar
//{ [pluginName: string]: { [unitId: string]: { [sheetId: string]: ISelectionWithCoord[] } } }
export type ISelectionInfo = Map<string, Map<string, Map<string, ISelectionWithStyle[]>>>;
+export enum SelectionMoveType {
+ MOVE_START,
+ MOVING,
+ MOVE_END,
+}
+
/**
* This service is responsible for managing the selection data.
*
@@ -41,24 +47,17 @@ export class SelectionManagerService implements IDisposable {
private _currentSelection: Nullable<ISelectionManagerSearchParam> = null;
- // private _isSelectionEnabled: boolean = true;
+ private readonly _selectionMoveStart$ = new Subject<Nullable<ISelectionWithStyle[]>>();
+ readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
- private readonly _selectionInfo$ = new BehaviorSubject<Nullable<ISelectionWithStyle[]>>(null);
- private readonly _copySelectionInfo$ = new BehaviorSubject<Nullable<ISelectionWithStyle[]>>(null);
+ private readonly _selectionMoving$ = new Subject<Nullable<ISelectionWithStyle[]>>();
+ readonly selectionMoving$ = this._selectionMoving$.asObservable();
- // eslint-disable-next-line @typescript-eslint/member-ordering
- readonly selectionInfo$ = this._selectionInfo$.asObservable();
+ private readonly _selectionMoveEnd$ = new BehaviorSubject<Nullable<ISelectionWithStyle[]>>(null);
+ readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
private _dirty: boolean = true;
- // get isSelectionEnabled() {
- // return this._isSelectionEnabled;
- // }
-
- // get currentStyle() {
- // return this._currentStyle;
- // }
-
getCurrent() {
return this._currentSelection;
}
@@ -80,7 +79,7 @@ export class SelectionManagerService implements IDisposable {
sheetId: this._currentSelection?.sheetId,
};
- this.refresh(this._currentSelection);
+ this._refresh(this._currentSelection);
}
changePluginNoRefresh(pluginName: string) {
@@ -105,7 +104,7 @@ export class SelectionManagerService implements IDisposable {
};
this._selectionInfo.clear();
- this.refresh(this._currentSelection);
+ this._refresh(this._currentSelection);
}
resetPlugin() {
@@ -114,12 +113,13 @@ export class SelectionManagerService implements IDisposable {
}
this._currentSelection.pluginName = NORMAL_SELECTION_PLUGIN_NAME;
- this.refresh(this._currentSelection);
+ this._refresh(this._currentSelection);
}
dispose(): void {
- this._selectionInfo$.complete();
- // this._currentSelection$.complete();
+ this._selectionMoveEnd$.complete();
+ this._selectionMoveStart$.complete();
+ this._selectionMoving$.complete();
}
makeDirty(dirty: boolean = true) {
@@ -131,7 +131,7 @@ export class SelectionManagerService implements IDisposable {
return;
}
- this.refresh(this._currentSelection);
+ this._refresh(this._currentSelection);
}
setCurrentSelection(param: ISelectionManagerSearchParam) {
@@ -140,7 +140,7 @@ export class SelectionManagerService implements IDisposable {
}
this._currentSelection = param;
- this.refresh(param);
+ this._refresh(param);
}
setCurrentSelectionNotRefresh(param: ISelectionManagerSearchParam) {
@@ -202,7 +202,7 @@ export class SelectionManagerService implements IDisposable {
});
}
- replace(selectionDatas: ISelectionWithStyle[]) {
+ replace(selectionDatas: ISelectionWithStyle[], type: SelectionMoveType = SelectionMoveType.MOVE_END) {
if (this._currentSelection == null) {
return;
}
@@ -210,7 +210,14 @@ export class SelectionManagerService implements IDisposable {
...this._currentSelection,
selectionDatas,
});
- this.refresh(this._currentSelection);
+
+ if (type === SelectionMoveType.MOVE_START) {
+ this._refreshStart(this._currentSelection);
+ } else if (type === SelectionMoveType.MOVING) {
+ this._refreshMoving(this._currentSelection);
+ } else {
+ this._refresh(this._currentSelection);
+ }
}
replaceWithNoRefresh(selectionDatas: ISelectionWithStyle[]) {
@@ -301,8 +308,16 @@ export class SelectionManagerService implements IDisposable {
return this._selectionInfo.get(pluginName)?.get(unitId)?.get(sheetId);
}
- private refresh(param?: ISelectionManagerSearchParam): void {
- this._selectionInfo$.next(this._getSelectionDatas(param));
+ private _refresh(param?: ISelectionManagerSearchParam): void {
+ this._selectionMoveEnd$.next(this._getSelectionDatas(param));
+ }
+
+ private _refreshStart(param?: ISelectionManagerSearchParam): void {
+ this._selectionMoveStart$.next(this._getSelectionDatas(param));
+ }
+
+ private _refreshMoving(param?: ISelectionManagerSearchParam): void {
+ this._selectionMoving$.next(this._getSelectionDatas(param));
}
private _getFirstByParam(param: Nullable<ISelectionManagerSearchParam>): Readonly<Nullable<ISelectionWithStyle>> {
@@ -340,7 +355,7 @@ export class SelectionManagerService implements IDisposable {
}
if (isRefresh) {
- this.refresh({ pluginName, unitId, sheetId });
+ this._refresh({ pluginName, unitId, sheetId });
}
}
@@ -374,7 +389,7 @@ export class SelectionManagerService implements IDisposable {
selectionData?.splice(0);
- this.refresh(param);
+ this._refresh(param);
}
private _removeByParam(index: number, param: ISelectionManagerSearchParam): void {
@@ -382,7 +397,7 @@ export class SelectionManagerService implements IDisposable {
selectionData?.splice(index, 1);
- this.refresh(param);
+ this._refresh(param);
}
// private refreshCurrentSelection(): void {
diff --git a/packages/sheets/src/services/sheet-interceptor/interceptor-const.ts b/packages/sheets/src/services/sheet-interceptor/interceptor-const.ts
index 989aa94a79..8cb73011d8 100644
--- a/packages/sheets/src/services/sheet-interceptor/interceptor-const.ts
+++ b/packages/sheets/src/services/sheet-interceptor/interceptor-const.ts
@@ -1,9 +1,9 @@
-import type { ICellData, ICommandInfo } from '@univerjs/core';
+import type { ICellDataForSheetInterceptor, ICommandInfo } from '@univerjs/core';
import { createInterceptorKey } from '@univerjs/core';
import type { ISheetLocation } from './utils/interceptor';
-const CELL_CONTENT = createInterceptorKey<ICellData, ISheetLocation>('CELL_CONTENT');
+const CELL_CONTENT = createInterceptorKey<ICellDataForSheetInterceptor, ISheetLocation>('CELL_CONTENT');
const PERMISSION = createInterceptorKey<boolean, ICommandInfo>('PERMISSION');
export const INTERCEPTOR_POINT = {