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(sheet): undo formula and selection header (#537)

Univerd1d2be3efb6c
diff --git a/packages/base-formula-engine/src/basics/common.ts b/packages/base-formula-engine/src/basics/common.ts
index 552caf84b7..6508076957 100644
--- a/packages/base-formula-engine/src/basics/common.ts
+++ b/packages/base-formula-engine/src/basics/common.ts
@@ -89,7 +89,7 @@ export interface IFormulaDatasetConfig {
formulaData: IFormulaData;
sheetNameMap: IUnitSheetNameMap;
forceCalculate: boolean;
- updateRangeList: IUnitRange[];
+ dirtyRanges: IUnitRange[];
}
export enum ConcatenateType {
diff --git a/packages/base-formula-engine/src/dependency/formula-dependency.ts b/packages/base-formula-engine/src/dependency/formula-dependency.ts
index a5fa950ce2..798f8bece0 100644
--- a/packages/base-formula-engine/src/dependency/formula-dependency.ts
+++ b/packages/base-formula-engine/src/dependency/formula-dependency.ts
@@ -38,13 +38,13 @@ export class FormulaDependencyGenerator extends Disposable {
updateRangeFlatten() {
const forceCalculate = this._currentConfigService.isForceCalculate();
- const updateRangeList = this._currentConfigService.getUpdateRangeList();
+ const dirtyRanges = this._currentConfigService.getDirtyRanges();
if (forceCalculate) {
return;
}
this._updateRangeFlattenCache = new Map<string, Map<string, IRange>>();
- for (let i = 0; i < updateRangeList.length; i++) {
- const gridRange = updateRangeList[i];
+ for (let i = 0; i < dirtyRanges.length; i++) {
+ const gridRange = dirtyRanges[i];
const range = gridRange.range;
const sheetId = gridRange.sheetId;
const unitId = gridRange.unitId;
diff --git a/packages/base-formula-engine/src/services/current-data.service.ts b/packages/base-formula-engine/src/services/current-data.service.ts
index b2d666c061..80f45b3cd4 100644
--- a/packages/base-formula-engine/src/services/current-data.service.ts
+++ b/packages/base-formula-engine/src/services/current-data.service.ts
@@ -12,7 +12,7 @@ export interface IFormulaCurrentConfigService {
isForceCalculate(): boolean;
- getUpdateRangeList(): IUnitRange[];
+ getDirtyRanges(): IUnitRange[];
registerUnitData(unitData: IUnitData): void;
@@ -28,13 +28,13 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
private _forceCalculate: boolean = false;
- private _updateRangeList: IUnitRange[] = [];
+ private _dirtyRanges: IUnitRange[] = [];
override dispose(): void {
this._unitData = {};
this._formulaData = {};
this._sheetNameMap = {};
- this._updateRangeList = [];
+ this._dirtyRanges = [];
}
getUnitData() {
@@ -53,8 +53,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
return this._forceCalculate;
}
- getUpdateRangeList() {
- return this._updateRangeList;
+ getDirtyRanges() {
+ return this._dirtyRanges;
}
load(config: IFormulaDatasetConfig) {
@@ -64,7 +64,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._forceCalculate = config.forceCalculate;
- this._updateRangeList = config.updateRangeList;
+ this._dirtyRanges = config.dirtyRanges;
}
registerUnitData(unitData: IUnitData) {
diff --git a/packages/base-formula-engine/src/services/formula-engine.service.ts b/packages/base-formula-engine/src/services/formula-engine.service.ts
index 11f2861fbe..03f9ee97ee 100644
--- a/packages/base-formula-engine/src/services/formula-engine.service.ts
+++ b/packages/base-formula-engine/src/services/formula-engine.service.ts
@@ -161,7 +161,7 @@ export class FormulaEngineService extends Disposable {
* @param formulaData
* @param interpreterDatasetConfig
* @param forceCalculate force calculate all formula, and ignore dependency relationship
- * @param updateRangeList input external unit data for multi workbook
+ * @param dirtyRanges input external unit data for multi workbook
* @returns
*/
async execute(unitId: string, formulaDatasetConfig: IFormulaDatasetConfig) {
diff --git a/packages/base-render/src/scroll-timer.ts b/packages/base-render/src/scroll-timer.ts
index add1eb65a4..b09e2518c0 100644
--- a/packages/base-render/src/scroll-timer.ts
+++ b/packages/base-render/src/scroll-timer.ts
@@ -4,6 +4,13 @@ import { RENDER_CLASS_TYPE } from './basics/const';
import { cancelRequestFrame, requestNewFrame } from './basics/tools';
import { Vector2 } from './basics/vector2';
+export enum ScrollTimerType {
+ ALL,
+ X,
+ Y,
+ NONE,
+}
+
export class ScrollTimer {
private _requestNewFrameNumber: number = -1;
@@ -25,6 +32,7 @@ export class ScrollTimer {
constructor(
private _scene: any,
+ private _scrollTimerType: ScrollTimerType = ScrollTimerType.ALL,
private _padding?: IPaddingData,
private _smoothRatioX = 0.05,
private _smoothRatioY = 0.05
@@ -34,8 +42,8 @@ export class ScrollTimer {
}
}
- static create(scene: any, padding?: IPaddingData) {
- return new ScrollTimer(scene, padding);
+ static create(scene: any, scrollTimerType: ScrollTimerType = ScrollTimerType.ALL, padding?: IPaddingData) {
+ return new ScrollTimer(scene, scrollTimerType, padding);
}
startScroll(offsetX: number, offsetY: number, targetViewport?: any) {
@@ -67,24 +75,28 @@ export class ScrollTimer {
let shouldScroll = false;
- if (this._moveX < leftBounding + l) {
- x = (this._moveX - leftBounding - l) * this._smoothRatioX;
- shouldScroll = true;
- }
+ if (this._scrollTimerType !== ScrollTimerType.Y) {
+ if (this._moveX < leftBounding + l) {
+ x = (this._moveX - leftBounding - l) * this._smoothRatioX;
+ shouldScroll = true;
+ }
- if (this._moveX > rightBounding - r) {
- x = (this._moveX - rightBounding + r) * this._smoothRatioX;
- shouldScroll = true;
+ if (this._moveX > rightBounding - r) {
+ x = (this._moveX - rightBounding + r) * this._smoothRatioX;
+ shouldScroll = true;
+ }
}
- if (this._moveY < topBounding + t) {
- y = (this._moveY - topBounding - t) * this._smoothRatioY;
- shouldScroll = true;
- }
+ if (this._scrollTimerType !== ScrollTimerType.X) {
+ if (this._moveY < topBounding + t) {
+ y = (this._moveY - topBounding - t) * this._smoothRatioY;
+ shouldScroll = true;
+ }
- if (this._moveY > bottomBounding - b) {
- y = (this._moveY - bottomBounding + b) * this._smoothRatioY;
- shouldScroll = true;
+ if (this._moveY > bottomBounding - b) {
+ y = (this._moveY - bottomBounding + b) * this._smoothRatioY;
+ shouldScroll = true;
+ }
}
if (!shouldScroll) {
diff --git a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
index 2a5985e2aa..3b844e1dc6 100644
--- a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
@@ -33,6 +33,11 @@ export interface ISetRangeValuesMutationParams {
* @deprecated not a good design
*/
options?: ICopyToOptionsData;
+
+ /**
+ * for formula calculate
+ */
+ isFormulaUpdate?: boolean;
}
export interface ISetRangeValuesRangeMutationParams extends ISetRangeValuesMutationParams {
diff --git a/packages/core/src/shared/object-matrix.ts b/packages/core/src/shared/object-matrix.ts
index 9041e029af..92a1971bf5 100644
--- a/packages/core/src/shared/object-matrix.ts
+++ b/packages/core/src/shared/object-matrix.ts
@@ -366,6 +366,45 @@ export class ObjectMatrix<T> {
};
}
+ getDiscreteRanges() {
+ const ranges: IRange[] = [];
+
+ // Traverse row by row
+ this.forEach((r, row) => {
+ // Traverse column by column
+ row.forEach((c, cell) => {
+ let merged = false;
+ // Check if it can be merged with any of the existing ranges
+ for (const range of ranges) {
+ if (
+ r >= range.startRow &&
+ r <= range.endRow + 1 &&
+ c >= range.startColumn &&
+ c <= range.endColumn + 1
+ ) {
+ // Extend the range
+ range.endRow = Math.max(r, range.endRow);
+ range.endColumn = Math.max(c, range.endColumn);
+ merged = true;
+ break;
+ }
+ }
+
+ // If not merged, then create a new range
+ if (!merged) {
+ ranges.push({
+ startRow: r,
+ endRow: r,
+ startColumn: c,
+ endColumn: c,
+ });
+ }
+ });
+ });
+
+ return ranges;
+ }
+
private _setOriginValue(matrix: ObjectMatrixPrimitiveType<T> = {}) {
this._matrix = matrix;
this._option = new ObjectArray<ObjectArrayPrimitiveType<T>>(matrix);
diff --git a/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts b/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts
index fdcbeb2602..e32e539a69 100644
--- a/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts
+++ b/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts
@@ -14,6 +14,7 @@ import {
} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+import { IFormulaInputService } from '../../services/formula-input.service';
import { InsertFunctionCommand } from '../commands/insert-function.command';
export interface IInsertFunctionOperationParams {
@@ -28,6 +29,7 @@ export const InsertFunctionOperation: ICommand = {
type: CommandType.OPERATION,
handler: async (accessor: IAccessor, params: IInsertFunctionOperationParams) => {
const selectionManagerService = accessor.get(SelectionManagerService);
+ const formulaInputService = accessor.get(IFormulaInputService);
const currentSelections = selectionManagerService.getSelections();
if (!currentSelections || !currentSelections.length) {
return false;
@@ -36,6 +38,8 @@ export const InsertFunctionOperation: ICommand = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const cellMatrix = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getCellMatrix();
+ const { value } = params;
+
// Select a single range to insert a formula:
// 1. The entire row or column, first get the judgment result of the primary position, and then set the formula ID of other positions in sequence;
// 2. For multiple rows and multiple columns, only get the judgment result of the primary position, and enter the edit mode
@@ -43,12 +47,11 @@ export const InsertFunctionOperation: ICommand = {
const { startRow, endRow, startColumn, endColumn } = currentSelections[0].range;
if (startRow !== endRow && startColumn !== endColumn) {
// TODO@Dushusir: Enter the editing mode
+ formulaInputService.inputFormula(value);
return false;
}
}
- const { value } = params;
-
const commandService = accessor.get(ICommandService);
// In each range (whether it is an entire row or column or multiple rows and columns),
diff --git a/packages/sheets-plugin-formula-ui/src/controllers/formula-input.controller.ts b/packages/sheets-plugin-formula-ui/src/controllers/formula-input.controller.ts
index f2af6a194f..7a2109aeca 100644
--- a/packages/sheets-plugin-formula-ui/src/controllers/formula-input.controller.ts
+++ b/packages/sheets-plugin-formula-ui/src/controllers/formula-input.controller.ts
@@ -1,7 +1,5 @@
-import { TextSelectionManagerService } from '@univerjs/base-docs';
import { FormulaEngineService, matchToken, sequenceNodeType } from '@univerjs/base-formula-engine';
-import { IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/base-render';
-import { SelectionManagerService } from '@univerjs/base-sheets';
+import { DeviceInputEventType, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/base-render';
import { KeyCode } from '@univerjs/base-ui';
import {
AbsoluteRefType,
@@ -11,28 +9,16 @@ import {
getAbsoluteRefTypeWitString,
ICommandInfo,
ICommandService,
- IContextService,
- IUniverInstanceService,
LifecycleStages,
- LocaleService,
OnLifecycle,
serializeRange,
- ThemeService,
toDisposable,
} from '@univerjs/core';
-import {
- EditorBridgeService,
- getEditorObject,
- IEditorBridgeService,
- ISelectionRenderService,
- SheetSkeletonManagerService,
-} from '@univerjs/ui-plugin-sheets';
+import { EditorBridgeService, getEditorObject, IEditorBridgeService } from '@univerjs/ui-plugin-sheets';
import { Inject } from '@wendellhu/redi';
import { ReferenceAbsoluteOperation } from '../commands/operations/reference-absolute.operation';
-import { IDescriptionService } from '../services/description.service';
import { IFormulaInputService } from '../services/formula-input.service';
-import { IFormulaPromptService } from '../services/prompt.service';
@OnLifecycle(LifecycleStages.Steady, FormulaInputController)
export class FormulaInputController extends Disposable {
@@ -40,20 +26,10 @@ export class FormulaInputController extends Disposable {
constructor(
@ICommandService private readonly _commandService: ICommandService,
- @Inject(LocaleService) private readonly _localeService: LocaleService,
- @IContextService private readonly _contextService: IContextService,
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(IEditorBridgeService) private readonly _editorBridgeService: EditorBridgeService,
- @Inject(IFormulaPromptService) private readonly _formulaPromptService: IFormulaPromptService,
@Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(ThemeService) private readonly _themeService: ThemeService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
- @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @Inject(ISelectionRenderService) private readonly _selectionRenderService: ISelectionRenderService,
- @Inject(IDescriptionService) private readonly _descriptionService: IDescriptionService,
- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@IFormulaInputService private readonly _formulaInputService: IFormulaInputService
) {
super();
@@ -67,6 +43,8 @@ export class FormulaInputController extends Disposable {
this._initialEditorInputChange();
this._userMouseListener();
+
+ this._inputFormulaListener();
}
private _initialEditorInputChange() {
@@ -102,6 +80,30 @@ export class FormulaInputController extends Disposable {
);
}
+ private _inputFormulaListener() {
+ this.disposeWithMe(
+ toDisposable(
+ this._formulaInputService.inputFormula$.subscribe((formulaString) => {
+ const visibleState = this._editorBridgeService.isVisible();
+ if (visibleState.visible === false) {
+ this._editorBridgeService.changeVisible({
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ });
+ }
+
+ const dataStream = `=${formulaString}(`;
+
+ const lastSequenceNodes = this._formulaEngineService.buildSequenceNodes(dataStream) || [];
+
+ this._formulaInputService.setSequenceNodes(lastSequenceNodes);
+
+ this._formulaInputService.syncToEditor(dataStream.length - 1);
+ })
+ )
+ );
+ }
+
private _changeRefString() {
const activeRange = this._textSelectionRenderManager.getActiveRange();
diff --git a/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts b/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
index 58a220505a..be75e2ae2a 100644
--- a/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
+++ b/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
@@ -1,4 +1,4 @@
-import { MoveCursorOperation, TextSelectionManagerService } from '@univerjs/base-docs';
+import { MoveCursorOperation, ReplaceContentCommand, TextSelectionManagerService } from '@univerjs/base-docs';
import {
FormulaEngineService,
includeFormulaLexerToken,
@@ -392,7 +392,7 @@ export class PromptController extends Disposable {
);
}
- private _selectionChanging(ranges: Nullable<IRange[]>) {
+ private _selectionChanging(ranges: Nullable<IRange[]>, isSync: boolean = false) {
if (ranges == null) {
return;
}
@@ -404,6 +404,12 @@ export class PromptController extends Disposable {
this._formulaInputService.enableSelectionMoving();
this._inertControlSelection(ranges);
+
+ if (ranges == null || isSync === false) {
+ return;
+ }
+ const currentRange = ranges[ranges.length - 1];
+ this._inertControlSelectionReplace(currentRange);
}
private _initialRefSelectionInsertEvent() {
@@ -412,7 +418,11 @@ export class PromptController extends Disposable {
);
this.disposeWithMe(
- toDisposable(this._selectionRenderService.selectionMoveStart$.subscribe(this._selectionChanging.bind(this)))
+ toDisposable(
+ this._selectionRenderService.selectionMoveStart$.subscribe((ranges) => {
+ this._selectionChanging(ranges, true);
+ })
+ )
);
}
@@ -967,15 +977,17 @@ export class PromptController extends Disposable {
* @param textSelectionOffset
* @returns
*/
- private async _syncToEditor(sequenceNodes: Array<string | ISequenceNode>, textSelectionOffset: number) {
+ private async _syncToEditor(
+ sequenceNodes: Array<string | ISequenceNode>,
+ textSelectionOffset: number,
+ canUndo: boolean = true
+ ) {
const dataStream = this._generateStringWithSequence(sequenceNodes);
const { textRuns, refSelections } = this._buildTextRuns(sequenceNodes);
this._isSelectionMovingRefSelections = refSelections;
- this._updateEditorModel(`=${dataStream}\r\n`, textRuns);
-
const activeRange = this._textSelectionManagerService.getLast();
if (activeRange == null) {
@@ -984,18 +996,38 @@ export class PromptController extends Disposable {
const { collapsed, style } = activeRange;
+ if (canUndo) {
+ this._commandService.executeCommand(ReplaceContentCommand.id, {
+ unitId: this._editorBridgeService.getCurrentEditorId(),
+ body: {
+ dataStream: `=${dataStream}`,
+ textRuns,
+ },
+ textRanges: [
+ {
+ startOffset: textSelectionOffset + 1,
+ endOffset: textSelectionOffset + 1,
+ collapsed,
+ style,
+ },
+ ],
+ segmentId: null,
+ });
+ } else {
+ this._updateEditorModel(`=${dataStream}\r\n`, textRuns);
+ this._textSelectionManagerService.replaceTextRanges([
+ {
+ startOffset: textSelectionOffset + 1,
+ endOffset: textSelectionOffset + 1,
+ collapsed,
+ style,
+ },
+ ]);
+ }
+
this._currentInsertRefStringIndex = textSelectionOffset;
await this._fitEditorSize();
-
- this._textSelectionManagerService.replaceTextRanges([
- {
- startOffset: textSelectionOffset + 1,
- endOffset: textSelectionOffset + 1,
- collapsed,
- style,
- },
- ]);
}
private async _fitEditorSize() {
diff --git a/packages/sheets-plugin-formula-ui/src/services/formula-input.service.ts b/packages/sheets-plugin-formula-ui/src/services/formula-input.service.ts
index 9a7e68f91d..1f9be6552f 100644
--- a/packages/sheets-plugin-formula-ui/src/services/formula-input.service.ts
+++ b/packages/sheets-plugin-formula-ui/src/services/formula-input.service.ts
@@ -10,6 +10,8 @@ export interface ISyncToEditorParam {
export interface IFormulaInputService {
syncToEditor$: Observable<ISyncToEditorParam>;
+ inputFormula$: Observable<string>;
+
changeRef$: Observable<boolean>;
syncToEditor(textSelectionOffset: number): void;
@@ -51,6 +53,8 @@ export interface IFormulaInputService {
disableLockedSelectionInsert(): void;
isLockedSelectionInsert(): boolean;
+
+ inputFormula(formulaString: string): void;
}
export class FormulaInputService implements IFormulaInputService, IDisposable {
@@ -70,12 +74,20 @@ export class FormulaInputService implements IFormulaInputService, IDisposable {
readonly changeRef$ = this._changeRef$.asObservable();
+ private readonly _inputFormula$ = new Subject<string>();
+
+ readonly inputFormula$ = this._inputFormula$.asObservable();
+
constructor(@Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService) {}
dispose(): void {
this._sequenceNodes = [];
}
+ inputFormula(formulaString: string) {
+ this._inputFormula$.next(formulaString);
+ }
+
syncToEditor(textSelectionOffset: number) {
this._syncToEditor$.next({ sequences: this._sequenceNodes, textSelectionOffset });
}
diff --git a/packages/sheets-plugin-formula/src/controllers/calculate.controller.ts b/packages/sheets-plugin-formula/src/controllers/calculate.controller.ts
index 17a6b0fa87..c816ace943 100644
--- a/packages/sheets-plugin-formula/src/controllers/calculate.controller.ts
+++ b/packages/sheets-plugin-formula/src/controllers/calculate.controller.ts
@@ -1,20 +1,21 @@
-import { FormulaEngineService, IFormulaData, ISheetData } from '@univerjs/base-formula-engine';
+import {
+ FormulaEngineService,
+ IFormulaData,
+ ISheetData,
+ IUnitData,
+ IUnitSheetNameMap,
+} from '@univerjs/base-formula-engine';
import { ISetRangeValuesMutationParams, SetRangeValuesMutation } from '@univerjs/base-sheets';
import {
Disposable,
ICommandInfo,
ICommandService,
IConfigService,
- IRange,
- isFormulaId,
- isFormulaString,
IUnitRange,
IUniverInstanceService,
LifecycleStages,
- Nullable,
ObjectMatrix,
OnLifecycle,
- Tools,
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
@@ -55,101 +56,44 @@ export class CalculateController extends Disposable {
private _calculate(command: ICommandInfo<ISetRangeValuesMutationParams>) {
const { params } = command;
- if (!params) return;
+ if (!params || params.isFormulaUpdate === true) return;
const { worksheetId: sheetId, workbookId: unitId, cellValue } = params;
if (cellValue == null) return;
- const formulaData = this._formulaDataModel.getFormulaData();
-
- const unitRange: IUnitRange[] = [];
- let isCalculate = false;
+ // const formulaData = this._formulaDataModel.getFormulaData();
- if (!formulaData[unitId]) {
- formulaData[unitId] = {};
- }
- if (!formulaData[unitId][sheetId]) {
- formulaData[unitId][sheetId] = {};
- }
+ const dirtyRanges: IUnitRange[] = [];
- const cellData = new ObjectMatrix(formulaData[unitId][sheetId]);
- const rangeMatrix = new ObjectMatrix(cellValue);
- const formulaIdMap = new Map<string, { f: string; r: number; c: number }>(); // Connect the formula and ID
-
- let isArrayFormula = false;
- // update formula string,Any modification to cellData will be linked to formulaData
- rangeMatrix.forValue((r, c, cell) => {
- const arrayFormCellRangeData = this._checkArrayFormulaValue(r, c);
-
- const formulaString = cell?.f || '';
- const formulaId = cell?.si || '';
- const formulaValue = cell?.v;
- if (!formulaString && formulaId) {
- isCalculate = true;
- cellData.setValue(r, c, { f: formulaId }); // IFormulaDataItem only has f field
- } else if (arrayFormCellRangeData && Tools.isBlank(formulaValue)) {
- isArrayFormula = true;
- isCalculate = true;
-
- unitRange.push({ unitId, sheetId, range: arrayFormCellRangeData });
- } else if (Tools.isStringNumber(formulaString)) {
- isCalculate = true;
-
- // if change formula to number, remove formula
- const formulaCell = cellData.getRow(r)?.get(c);
- if (formulaCell) {
- cellData.deleteValue(r, c);
- }
- } else if (isFormulaString(formulaString)) {
- isCalculate = true;
- cellData.setValue(r, c, { f: formulaString });
+ const discreteRanges = new ObjectMatrix(cellValue).getDiscreteRanges();
- if (isFormulaId(formulaId)) {
- formulaIdMap.set(formulaId, { f: formulaString, r, c });
- }
- }
+ discreteRanges.forEach((range) => {
+ dirtyRanges.push({ unitId, sheetId, range });
});
- // Convert the formula ID to formula string
- cellData.forValue((r, c, cell) => {
- const formulaId = cell?.f || '';
- // TODO@Dushusir: remove formulaIdMap
- if (formulaIdMap.has(formulaId)) {
- const formulaInfo = formulaIdMap.get(formulaId);
- if (!formulaInfo) return false;
+ if (dirtyRanges.length === 0) return;
- const f = formulaInfo.f;
- const x = r - formulaInfo.r;
- const y = c - formulaInfo.c;
+ const { allUnitData, formulaData, unitSheetNameMap } = this._getCalculateData();
- cellData.setValue(r, c, { f, x, y });
- }
- });
-
- if (!isArrayFormula) {
- unitRange.push({ unitId, sheetId, range: rangeMatrix.getDataRange() });
- }
-
- if (unitRange.length === 0 || !isCalculate) return;
-
- this._executeFormula(unitId, formulaData, unitRange);
+ this._executeFormula(unitId, allUnitData, formulaData, unitSheetNameMap, false, dirtyRanges);
}
- private _executeFormula(unitId: string, formulaData: IFormulaData, unitRange: IUnitRange[]) {
- const engine = this._formulaEngineService;
- const { sheetData, sheetNameMap } = this._getSheetData();
+ private _executeFormula(
+ unitId: string,
+ allUnitData: IUnitData,
+ formulaData: IFormulaData,
+ unitSheetNameMap: IUnitSheetNameMap,
+ forceCalculate: boolean = false,
+ dirtyRanges: IUnitRange[]
+ ) {
// Add mutation after calculating the formula
- engine
+ this._formulaEngineService
.execute(unitId, {
- unitData: {
- [unitId]: sheetData,
- },
+ unitData: allUnitData,
formulaData,
- sheetNameMap: {
- [unitId]: sheetNameMap,
- },
- forceCalculate: true,
- updateRangeList: unitRange,
+ sheetNameMap: unitSheetNameMap,
+ forceCalculate,
+ dirtyRanges,
})
.then((data) => {
const { sheetData, arrayFormulaData } = data;
@@ -173,6 +117,7 @@ export class CalculateController extends Disposable {
worksheetId: sheetId,
workbookId: unitId,
cellValue: cellData.getData(),
+ isFormulaUpdate: true,
};
redoMutationsInfo.push({
@@ -186,48 +131,69 @@ export class CalculateController extends Disposable {
});
}
- private _checkArrayFormulaValue(row: number, column: number): Nullable<IRange> {
- let formula: Nullable<IRange>;
- const arrayFormulaData = this._formulaDataModel.getArrayFormulaData();
+ private _getCalculateData() {
+ const unitAllSheet = this._currentUniverService.getAllUniverSheetsInstance();
- if (!arrayFormulaData) return null;
+ const formulaData: IFormulaData = {};
- Object.keys(arrayFormulaData).forEach((sheetId) => {
- const sheetData = arrayFormulaData[sheetId];
+ const allUnitData: IUnitData = {};
- sheetData.forValue((rowIndex: number, columnIndex: number, value: IRange) => {
- const { startRow, startColumn, endRow, endColumn } = value;
- if (row >= startRow && row < endRow && column >= startColumn && column < endColumn) {
- formula = {
- startRow,
- endRow: startRow,
- startColumn,
- endColumn: startColumn,
- };
- return false;
+ const unitSheetNameMap: IUnitSheetNameMap = {};
+
+ for (const workbook of unitAllSheet) {
+ const unitId = workbook.getUnitId();
+ if (formulaData[unitId] == null) {
+ formulaData[unitId] = {};
+ }
+ const sheets = workbook.getSheets();
+
+ const workbookFormulaData = formulaData[unitId];
+
+ const sheetData: ISheetData = {};
+
+ const sheetNameMap: { [sheetName: string]: string } = {};
+
+ for (const sheet of sheets) {
+ const sheetId = sheet.getSheetId();
+ if (workbookFormulaData[sheetId] == null) {
+ workbookFormulaData[sheetId] = {};
}
- });
- });
- return formula;
- }
+ const sheetFormulaData = workbookFormulaData[sheetId];
+
+ const cellDatas = sheet.getCellMatrix();
+
+ cellDatas.forValue((row, column, cellData) => {
+ if (cellData.f != null) {
+ if (sheetFormulaData[row] == null) {
+ sheetFormulaData[row] = {};
+ }
+ sheetFormulaData[row][column] = {
+ f: cellData.f,
+ x: 0,
+ y: 0,
+ };
+ }
+ });
- private _getSheetData() {
- const sheetData: ISheetData = {};
- const sheetNameMap: { [sheetName: string]: string } = {};
- this._currentUniverService
- .getCurrentUniverSheetInstance()
- .getSheets()
- .forEach((sheet) => {
const sheetConfig = sheet.getConfig();
- sheetData[sheet.getSheetId()] = {
+ sheetData[sheetId] = {
cellData: new ObjectMatrix(sheetConfig.cellData),
rowCount: sheetConfig.rowCount,
columnCount: sheetConfig.columnCount,
};
sheetNameMap[sheet.getName()] = sheet.getSheetId();
- });
+ }
+
+ allUnitData[unitId] = sheetData;
+
+ unitSheetNameMap[unitId] = sheetNameMap;
+ }
- return { sheetData, sheetNameMap };
+ return {
+ formulaData,
+ allUnitData,
+ unitSheetNameMap,
+ };
}
}
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts
index 7d8267fa20..35925d4762 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts
@@ -106,7 +106,7 @@ export class EditingController extends Disposable {
// formulaData,
// sheetNameMap: {},
// forceCalculate: true,
- // updateRangeList: [],
+ // dirtyRanges: [],
// })
// .then((res) => {
// console.log(res.sheetData, res.arrayFormulaData);
diff --git a/packages/ui-plugin-sheets/src/controllers/selection.controller.ts b/packages/ui-plugin-sheets/src/controllers/selection.controller.ts
index fd32909131..094792f113 100644
--- a/packages/ui-plugin-sheets/src/controllers/selection.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/selection.controller.ts
@@ -1,4 +1,10 @@
-import { IMouseEvent, IPointerEvent, IRenderManagerService, SpreadsheetSkeleton } from '@univerjs/base-render';
+import {
+ IMouseEvent,
+ IPointerEvent,
+ IRenderManagerService,
+ ScrollTimerType,
+ SpreadsheetSkeleton,
+} from '@univerjs/base-render';
import {
convertSelectionDataToRange,
getNormalSelectionStyle,
@@ -133,7 +139,8 @@ export class SelectionController extends Disposable {
evt,
(spreadsheet?.zIndex || 1) + 1,
RANGE_TYPE.ROW,
- viewportMain
+ viewportMain,
+ ScrollTimerType.Y
);
if (evt.button !== 2) {
state.stopPropagation();
@@ -156,7 +163,8 @@ export class SelectionController extends Disposable {
evt,
(spreadsheet?.zIndex || 1) + 1,
RANGE_TYPE.COLUMN,
- viewportMain
+ viewportMain,
+ ScrollTimerType.X
);
if (evt.button !== 2) {
state.stopPropagation();
diff --git a/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts b/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts
index 7412fcc462..f129fde48a 100644
--- a/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts
+++ b/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts
@@ -3,6 +3,7 @@ import {
IPointerEvent,
Scene,
ScrollTimer,
+ ScrollTimerType,
SpreadsheetSkeleton,
Vector2,
Viewport,
@@ -69,7 +70,13 @@ export interface ISelectionRenderService {
convertSelectionRangeToData(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle;
convertRangeDataToSelection(range: IRange): Nullable<IRangeWithCoord>;
convertCellRangeToInfo(primary: Nullable<ISelectionCell>): Nullable<ISelectionCellWithCoord>;
- eventTrigger(evt: IPointerEvent | IMouseEvent, zIndex: number, rangeType: RANGE_TYPE, viewport?: Viewport): void;
+ eventTrigger(
+ evt: IPointerEvent | IMouseEvent,
+ zIndex: number,
+ rangeType: RANGE_TYPE,
+ viewport?: Viewport,
+ scrollTimerType?: ScrollTimerType
+ ): void;
// getMoveCellInfo(direction: Direction, selectionData: Nullable<ISelectionWithCoord>): Nullable<ISelectionWithCoord>;
// transformCellDataToSelectionData(row: number, column: number): Nullable<ISelectionWithCoord>;
reset(): void;
@@ -391,7 +398,8 @@ export class SelectionRenderService implements ISelectionRenderService {
evt: IPointerEvent | IMouseEvent,
zIndex = 0,
rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
- viewport?: Viewport
+ viewport?: Viewport,
+ scrollTimerType: ScrollTimerType = ScrollTimerType.ALL
) {
if (this._isSelectionEnabled === false) {
return;
@@ -574,7 +582,7 @@ export class SelectionRenderService implements ISelectionRenderService {
scene.disableEvent();
- const scrollTimer = ScrollTimer.create(this._scene);
+ const scrollTimer = ScrollTimer.create(this._scene, scrollTimerType);
scrollTimer.startScroll(newEvtOffsetX, newEvtOffsetY, viewport);
this._scrollTimer = scrollTimer;