Skip to content

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

refactor: auto fill hook (#921)

YuHongc13321167f63
diff --git a/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts
index f0578b214e..2269fd65bd 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts
@@ -23,7 +23,7 @@ import {
SetNumfmtMutation,
transformCellsToRange,
} from '@univerjs/sheets';
-import type { IAutoFillHook } from '@univerjs/sheets-ui';
+import type { ISheetAutoFillHook } from '@univerjs/sheets-ui';
import { APPLY_TYPE, getAutoFillRepeatRange, IAutoFillService } from '@univerjs/sheets-ui';
import { Inject, Injector } from '@wendellhu/redi';
@@ -132,13 +132,18 @@ export class NumfmtAutoFillController extends Disposable {
redos: mergeNumfmtMutations(totalRedos),
};
};
- const hook: IAutoFillHook = {
- hookName: SHEET_NUMFMT_PLUGIN,
- hook: {
- [APPLY_TYPE.COPY]: generalApplyFunc,
- [APPLY_TYPE.NO_FORMAT]: noopReturnFunc,
- [APPLY_TYPE.ONLY_FORMAT]: generalApplyFunc,
- [APPLY_TYPE.SERIES]: generalApplyFunc,
+ const hook: ISheetAutoFillHook = {
+ id: SHEET_NUMFMT_PLUGIN,
+ onFillData: (location, direction, applyType) => {
+ if (
+ applyType === APPLY_TYPE.COPY ||
+ applyType === APPLY_TYPE.ONLY_FORMAT ||
+ applyType === APPLY_TYPE.SERIES
+ ) {
+ const { source, target } = location;
+ return generalApplyFunc(source, target);
+ }
+ return noopReturnFunc();
},
};
this.disposeWithMe(this._autoFillService.addHook(hook));
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
index cfca271039..86c3ac07bd 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
@@ -262,7 +262,7 @@ describe('Test auto fill rules in controller', () => {
const workbook = get(IUniverInstanceService).getCurrentUniverSheetInstance();
if (!workbook) throw new Error('This is an error');
// test number
- (autoFillController as any)._handleFill(
+ (autoFillController as any)._triggerAutoFill(
{
startRow: 0,
startColumn: 0,
@@ -279,7 +279,7 @@ describe('Test auto fill rules in controller', () => {
expect(workbook.getSheetBySheetId('sheet1')?.getCell(0, 2)?.v).toBe(3);
expect(workbook.getSheetBySheetId('sheet1')?.getCell(0, 3)?.v).toBe(4);
// test number. descending
- (autoFillController as any)._handleFill(
+ (autoFillController as any)._triggerAutoFill(
{
startRow: 1,
startColumn: 0,
@@ -303,7 +303,7 @@ describe('Test auto fill rules in controller', () => {
const workbook = get(IUniverInstanceService).getCurrentUniverSheetInstance();
if (!workbook) throw new Error('This is an error');
// test extend number
- (autoFillController as any)._handleFill(
+ (autoFillController as any)._triggerAutoFill(
{
startRow: 2,
startColumn: 0,
@@ -327,7 +327,7 @@ describe('Test auto fill rules in controller', () => {
const workbook = get(IUniverInstanceService).getCurrentUniverSheetInstance();
if (!workbook) throw new Error('This is an error');
// test chinese number
- (autoFillController as any)._handleFill(
+ (autoFillController as any)._triggerAutoFill(
{
startRow: 3,
startColumn: 0,
@@ -352,7 +352,7 @@ describe('Test auto fill rules in controller', () => {
if (!workbook) throw new Error('This is an error');
// test chinese week
- (autoFillController as any)._handleFill(
+ (autoFillController as any)._triggerAutoFill(
{
startRow: 4,
startColumn: 0,
@@ -376,7 +376,7 @@ describe('Test auto fill rules in controller', () => {
const workbook = get(IUniverInstanceService).getCurrentUniverSheetInstance();
if (!workbook) throw new Error('This is an error');
// test loop series
- (autoFillController as any)._handleFill(
+ (autoFillController as any)._triggerAutoFill(
{
startRow: 5,
startColumn: 0,
@@ -400,7 +400,7 @@ describe('Test auto fill rules in controller', () => {
const workbook = get(IUniverInstanceService).getCurrentUniverSheetInstance();
if (!workbook) throw new Error('This is an error');
// test other string
- (autoFillController as any)._handleFill(
+ (autoFillController as any)._triggerAutoFill(
{
startRow: 6,
startColumn: 0,
@@ -424,7 +424,7 @@ describe('Test auto fill rules in controller', () => {
const workbook = get(IUniverInstanceService).getCurrentUniverSheetInstance();
if (!workbook) throw new Error('This is an error');
// test mixed mode
- (autoFillController as any)._handleFill(
+ (autoFillController as any)._triggerAutoFill(
{
startRow: 7,
startColumn: 0,
diff --git a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts b/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
index ba3335dc2e..07368299cb 100644
--- a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
+++ b/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
@@ -14,189 +14,19 @@
* limitations under the License.
*/
-import type { ICellData, ICommand, IMutationInfo, IObjectMatrixPrimitiveType, IRange } from '@univerjs/core';
-import {
- CommandType,
- ICommandService,
- IUndoRedoService,
- IUniverInstanceService,
- ObjectMatrix,
- RANGE_TYPE,
- Rectangle,
-} from '@univerjs/core';
-import type {
- IAddWorksheetMergeMutationParams,
- IRemoveWorksheetMergeMutationParams,
- ISetRangeValuesMutationParams,
-} from '@univerjs/sheets';
-import {
- AddMergeUndoMutationFactory,
- AddWorksheetMergeMutation,
- getAddMergeMutationRangeByType,
- RemoveMergeUndoMutationFactory,
- RemoveWorksheetMergeMutation,
- SetRangeValuesMutation,
- SetRangeValuesUndoMutationFactory,
- SetSelectionsOperation,
-} from '@univerjs/sheets';
+import type { ICellData, ICommand, IObjectMatrixPrimitiveType, IRange } from '@univerjs/core';
+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
+import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SetSelectionsOperation } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
-export interface IAutoFillCommandParams {
- subUnitId?: string;
- unitId?: string;
- applyRange: IRange;
- selectionRange: IRange;
- applyDatas: ICellData[][];
- extendMutations: { undo: IMutationInfo[]; redo: IMutationInfo[] };
- applyMergeRanges?: IRange[];
-}
+export interface IAutoFillCommandParams {}
export const AutoFillCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.auto-fill',
// eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params: IAutoFillCommandParams) => {
- const commandService = accessor.get(ICommandService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const {
- applyRange,
- selectionRange,
- applyDatas,
- unitId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId(),
- subUnitId = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId(),
- applyMergeRanges,
- } = params || {};
- if (!applyRange || !applyDatas || !selectionRange) {
- return false;
- }
-
- const undoSeq: IMutationInfo[] = [];
- const redoSeq: IMutationInfo[] = [];
-
- // delete cross merge
- let removeMergeResult = true;
- const deleteMergeRanges: IRange[] = [];
- const mergeData = univerInstanceService
- .getUniverSheetInstance(unitId)
- ?.getSheetBySheetId(subUnitId)
- ?.getMergeData();
- if (mergeData) {
- mergeData.forEach((merge) => {
- if (Rectangle.intersects(merge, applyRange)) {
- deleteMergeRanges.push(merge);
- }
- });
- }
- const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {
- unitId,
- subUnitId,
- ranges: deleteMergeRanges,
- };
- const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(
- accessor,
- removeMergeMutationParams
- );
- removeMergeResult = commandService.syncExecuteCommand(
- RemoveWorksheetMergeMutation.id,
- removeMergeMutationParams
- );
- undoSeq.push({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams });
- redoSeq.push({ id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams });
-
- // set range value
- const cellValue = new ObjectMatrix<ICellData>();
- const { startRow, startColumn, endRow, endColumn } = applyRange;
-
- for (let r = 0; r <= endRow - startRow; r++) {
- for (let c = 0; c <= endColumn - startColumn; c++) {
- cellValue.setValue(r + startRow, c + startColumn, applyDatas[r][c]);
- }
- }
-
- const setRangeValuesMutationParams: ISetRangeValuesMutationParams = {
- subUnitId,
- unitId,
- cellValue: cellValue.getMatrix(),
- };
-
- const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
- accessor,
- setRangeValuesMutationParams
- );
-
- const setRangeResult = commandService.syncExecuteCommand(
- SetRangeValuesMutation.id,
- setRangeValuesMutationParams
- );
-
- undoSeq.push({ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams });
- redoSeq.push({ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams });
-
- // set selection
- const selectionResult = commandService.syncExecuteCommand(SetSelectionsOperation.id, {
- selections: [
- {
- primary: {
- ...selectionRange,
- endColumn: selectionRange.startColumn,
- endRow: selectionRange.startRow,
- },
- range: {
- ...selectionRange,
- rangeType: RANGE_TYPE.NORMAL,
- },
- },
- ],
- unitId,
- subUnitId,
- });
-
- undoSeq.push({ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams });
- redoSeq.push({ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams });
-
- let addMergeResult = true;
-
- // add worksheet merge
- if (applyMergeRanges?.length) {
- const ranges = getAddMergeMutationRangeByType(applyMergeRanges);
-
- const addMergeMutationParams: IAddWorksheetMergeMutationParams = {
- unitId,
- subUnitId,
- ranges,
- };
- const undoRemoveMutationParams: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(
- accessor,
- addMergeMutationParams
- );
- addMergeResult = commandService.syncExecuteCommand(AddWorksheetMergeMutation.id, addMergeMutationParams);
-
- undoSeq.push({ id: RemoveWorksheetMergeMutation.id, params: undoRemoveMutationParams });
- redoSeq.push({ id: AddWorksheetMergeMutation.id, params: addMergeMutationParams });
- }
-
- // deal with extend mutations by hooks
- const { undo, redo } = params?.extendMutations;
- const extendResult = redo.every((item: IMutationInfo) =>
- commandService.syncExecuteCommand(item.id, item.params)
- );
- undo.forEach((item: IMutationInfo) => {
- undoSeq.push(item);
- });
- redo.forEach((item: IMutationInfo) => {
- redoSeq.push(item);
- });
-
- if (setRangeResult && removeMergeResult && addMergeResult && selectionResult && extendResult) {
- undoRedoService.pushUndoRedo({
- unitID: unitId,
- undoMutations: undoSeq,
- redoMutations: redoSeq,
- });
-
- return true;
- }
return true;
},
};
diff --git a/packages/sheets-ui/src/commands/commands/refill.command.ts b/packages/sheets-ui/src/commands/commands/refill.command.ts
index fa5f7b1093..420b7ffdc7 100644
--- a/packages/sheets-ui/src/commands/commands/refill.command.ts
+++ b/packages/sheets-ui/src/commands/commands/refill.command.ts
@@ -30,7 +30,7 @@ export const RefillCommand: ICommand = {
type: CommandType.COMMAND,
handler: async (accessor: IAccessor, params: IRefillCommandParams) => {
const autoFillService = accessor.get(IAutoFillService);
- autoFillService.setApplyType(params.type);
+ autoFillService.applyType = params.type;
return true;
},
};
diff --git a/packages/sheets-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
index 72a2947efd..6d29777ce8 100644
--- a/packages/sheets-ui/src/controllers/auto-fill.controller.ts
+++ b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
@@ -20,46 +20,85 @@ import {
Disposable,
DisposableCollection,
ICommandService,
+ IUndoRedoService,
IUniverInstanceService,
LifecycleStages,
+ ObjectMatrix,
OnLifecycle,
+ RANGE_TYPE,
+ Rectangle,
toDisposable,
Tools,
} from '@univerjs/core';
import { DeviceInputEventType, getCellInfoInMergeData } from '@univerjs/engine-render';
-import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '@univerjs/sheets';
-import { Inject } from '@wendellhu/redi';
+import type {
+ IAddWorksheetMergeMutationParams,
+ IRemoveWorksheetMergeMutationParams,
+ ISetRangeValuesMutationParams,
+} from '@univerjs/sheets';
+import {
+ AddMergeUndoMutationFactory,
+ AddWorksheetMergeMutation,
+ getAddMergeMutationRangeByType,
+ NORMAL_SELECTION_PLUGIN_NAME,
+ RemoveMergeUndoMutationFactory,
+ RemoveWorksheetMergeMutation,
+ SelectionManagerService,
+ SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
+ SetSelectionsOperation,
+} from '@univerjs/sheets';
+import { Inject, Injector } from '@wendellhu/redi';
import { AutoClearContentCommand, AutoFillCommand } from '../commands/commands/auto-fill.command';
import { IAutoFillService } from '../services/auto-fill/auto-fill.service';
import { otherRule } from '../services/auto-fill/rules';
import { fillCopy, fillCopyStyles, getDataIndex, getLenS } from '../services/auto-fill/tools';
-import type { APPLY_FUNCTIONS, ICopyDataInType, ICopyDataPiece, IRuleConfirmedData } from '../services/auto-fill/type';
-import { APPLY_TYPE, DATA_TYPE } from '../services/auto-fill/type';
+import type {
+ APPLY_FUNCTIONS,
+ IAutoFillLocation,
+ ICopyDataInType,
+ ICopyDataPiece,
+ IRuleConfirmedData,
+ ISheetAutoFillHook,
+} from '../services/auto-fill/type';
+import { APPLY_TYPE, AutoFillHookType, DATA_TYPE } from '../services/auto-fill/type';
import { IEditorBridgeService } from '../services/editor-bridge.service';
import { ISelectionRenderService } from '../services/selection/selection-render.service';
@OnLifecycle(LifecycleStages.Steady, AutoFillController)
export class AutoFillController extends Disposable {
- private _direction: Direction | null = null;
private _beforeApplyData: Array<Array<Nullable<ICellData>>> = [];
- private _applyType: APPLY_TYPE = APPLY_TYPE.SERIES;
- private _hasFillingStyle: boolean = true;
private _copyData: ICopyDataPiece[] = [];
+ private _defaultHook: ISheetAutoFillHook;
constructor(
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
@ICommandService private readonly _commandService: ICommandService,
+ @IUndoRedoService private readonly _undoRedoService: IUndoRedoService,
@IAutoFillService private readonly _autoFillService: IAutoFillService,
@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(Injector) private readonly _injector: Injector
) {
super();
+ this._defaultHook = {
+ id: 'default',
+ type: AutoFillHookType.Default,
+ priority: 0,
+ onBeforeFillData: (location: IAutoFillLocation, direction: Direction) => {
+ this._presetAndCacheData(location, direction);
+ },
+ onFillData: (location: IAutoFillLocation, direction: Direction, applyType: APPLY_TYPE) => {
+ return this._fillData(location, direction, applyType);
+ },
+ };
this._init();
}
private _init() {
+ this._initDefaultHook();
this._onSelectionControlFillChanged();
this._onApplyTypeChanged();
[AutoFillCommand, AutoClearContentCommand].forEach((command) => {
@@ -67,96 +106,8 @@ export class AutoFillController extends Disposable {
});
}
- private _handleDbClickFill(sourceRange: IRange) {
- const destRange = this._detectFillRange(sourceRange);
- // double click only works when dest range is longer than source range
- if (destRange.endRow <= sourceRange.endRow) {
- return;
- }
- // double click effect is the same as drag effect, but the apply area is automatically calculated (by method '_detectFillRange')
- this._handleFill(sourceRange, destRange);
- }
-
- private _detectFillRange(sourceRange: IRange) {
- const { startRow, endRow, startColumn, endColumn } = sourceRange;
- const worksheet = this._univerInstanceService.getCurrentUniverSheetInstance()?.getActiveSheet();
- if (!worksheet) {
- return sourceRange;
- }
- const matrix = worksheet.getCellMatrix();
- const maxRow = worksheet.getMaxRows() - 1;
- const maxColumn = worksheet.getMaxColumns() - 1;
- let detectEndRow = endRow;
- // left column first, or consider right column.
- if (startColumn > 0 && matrix.getValue(startRow, startColumn - 1)?.v != null) {
- let cur = startRow;
- while (matrix.getValue(cur, startColumn - 1)?.v != null && cur < maxRow) {
- cur += 1;
- }
- detectEndRow = cur;
- } else if (endColumn < maxColumn && matrix.getValue(endRow, endColumn + 1)?.v != null) {
- let cur = startRow;
- while (matrix.getValue(cur, endColumn + 1)?.v != null && cur < maxRow) {
- cur++;
- }
- detectEndRow = cur;
- }
-
- for (let i = endRow + 1; i <= detectEndRow; i++) {
- for (let j = startColumn; j <= endColumn; j++) {
- if (matrix.getValue(i, j)?.v != null) {
- detectEndRow = i - 1;
- break;
- }
- }
- }
-
- return {
- startColumn,
- endColumn,
- startRow,
- endRow: detectEndRow,
- };
- }
-
- private _handleFill(sourceRange: IRange, destRange: IRange) {
- // if source range === dest range, do nothing;
- if (
- sourceRange.startColumn === destRange.startColumn &&
- sourceRange.startRow === destRange.startRow &&
- sourceRange.endColumn === destRange.endColumn &&
- sourceRange.endRow === destRange.endRow
- ) {
- return;
- }
- // situation 1: drag to smaller range, horizontally.
- if (destRange.endColumn < sourceRange.endColumn && destRange.endColumn > sourceRange.startColumn) {
- this._commandService.executeCommand(AutoClearContentCommand.id, {
- clearRange: {
- startRow: destRange.startRow,
- endRow: destRange.endRow,
- startColumn: destRange.endColumn + 1,
- endColumn: sourceRange.endColumn,
- },
- selectionRange: destRange,
- });
- return;
- }
- // situation 2: drag to smaller range, vertically.
- if (destRange.endRow < sourceRange.endRow && destRange.endRow > sourceRange.startRow) {
- this._commandService.executeCommand(AutoClearContentCommand.id, {
- clearRange: {
- startRow: destRange.endRow + 1,
- endRow: sourceRange.endRow,
- startColumn: destRange.startColumn,
- endColumn: destRange.endColumn,
- },
- selectionRange: destRange,
- });
- return;
- }
- // situation 3: drag to larger range, expand to fill
- this._presetAndCacheData(sourceRange, destRange);
+ private _initDefaultHook() {
+ this._autoFillService.addHook(this._defaultHook);
}
private _onSelectionControlFillChanged() {
@@ -185,20 +136,20 @@ export class AutoFillController extends Disposable {
if (filled == null) {
return;
}
- const sourceRange: IRange = {
+ const source: IRange = {
startColumn: controlSelection.model.startColumn,
endColumn: controlSelection.model.endColumn,
startRow: controlSelection.model.startRow,
endRow: controlSelection.model.endRow,
};
- const destRange: IRange = {
+ const selection: IRange = {
startColumn: filled.startColumn,
endColumn: filled.endColumn,
startRow: filled.startRow,
endRow: filled.endRow,
};
- this._handleFill(sourceRange, destRange);
+ this._triggerAutoFill(source, selection);
})
)
);
@@ -208,13 +159,13 @@ export class AutoFillController extends Disposable {
disposableCollection.add(
toDisposable(
controlSelection.fillControl.onDblclickObserver.add(() => {
- const sourceRange = {
+ const source = {
startColumn: controlSelection.model.startColumn,
endColumn: controlSelection.model.endColumn,
startRow: controlSelection.model.startRow,
endRow: controlSelection.model.endRow,
};
- this._handleDbClickFill(sourceRange);
+ this._handleDbClickFill(source);
})
)
);
@@ -242,20 +193,212 @@ export class AutoFillController extends Disposable {
private _onApplyTypeChanged() {
this.disposeWithMe(
toDisposable(
- this._autoFillService.applyType$.subscribe((applyType: APPLY_TYPE | null) => {
- if (applyType === APPLY_TYPE.NO_FORMAT) {
- this._applyType = APPLY_TYPE.SERIES;
- this._hasFillingStyle = false;
- } else {
- this._applyType = applyType || APPLY_TYPE.SERIES;
- this._hasFillingStyle = true;
- }
- this._fillData();
+ this._autoFillService.applyType$.subscribe(() => {
+ this._handleFillData();
})
)
);
}
+ private _triggerAutoFill(source: IRange, selection: IRange) {
+ // if source range === dest range, do nothing;
+ if (
+ source.startColumn === selection.startColumn &&
+ source.startRow === selection.startRow &&
+ source.endColumn === selection.endColumn &&
+ source.endRow === selection.endRow
+ ) {
+ return;
+ }
+ // situation 1: drag to smaller range, horizontally.
+ if (selection.endColumn < source.endColumn && selection.endColumn > source.startColumn) {
+ this._commandService.executeCommand(AutoClearContentCommand.id, {
+ clearRange: {
+ startRow: selection.startRow,
+ endRow: selection.endRow,
+ startColumn: selection.endColumn + 1,
+ endColumn: source.endColumn,
+ },
+ selectionRange: selection,
+ });
+ return;
+ }
+ // situation 2: drag to smaller range, vertically.
+ if (selection.endRow < source.endRow && selection.endRow > source.startRow) {
+ this._commandService.executeCommand(AutoClearContentCommand.id, {
+ clearRange: {
+ startRow: selection.endRow + 1,
+ endRow: source.endRow,
+ startColumn: selection.startColumn,
+ endColumn: selection.endColumn,
+ },
+ selectionRange: selection,
+ });
+ return;
+ }
+ // situation 3: drag to larger range, expand to fill
+
+ // save ranges
+ const target = {
+ startRow: selection.startRow,
+ endRow: selection.endRow,
+ startColumn: selection.startColumn,
+ endColumn: selection.endColumn,
+ };
+ let direction: Nullable<Direction> = null;
+ if (selection.startRow < source.startRow) {
+ direction = Direction.UP;
+ target.endRow = source.startRow - 1;
+ } else if (selection.endRow > source.endRow) {
+ direction = Direction.DOWN;
+ target.startRow = source.endRow + 1;
+ } else if (selection.startColumn < source.startColumn) {
+ direction = Direction.LEFT;
+ target.endColumn = source.startColumn - 1;
+ } else if (selection.endColumn > source.endColumn) {
+ direction = Direction.RIGHT;
+ target.startColumn = source.endColumn + 1;
+ } else {
+ return;
+ }
+ const unitId = this._univerInstanceService.getCurrentUniverSheetInstance().getUnitId();
+ const subUnitId = this._univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId();
+ this._autoFillService.direction = direction;
+ this._autoFillService.autoFillLocation = {
+ source,
+ target,
+ unitId,
+ subUnitId,
+ };
+
+ const activeHooks = this._autoFillService.getActiveHooks();
+ activeHooks.forEach((hook) => {
+ hook?.onBeforeFillData?.({ source, target, unitId, subUnitId }, direction!);
+ });
+
+ // set apply type will trigger fillData
+ if (!this._autoFillService.menu.find((m) => m.value === APPLY_TYPE.SERIES)?.disable) {
+ this._autoFillService.applyType = APPLY_TYPE.SERIES;
+ } else {
+ this._autoFillService.applyType = APPLY_TYPE.COPY;
+ }
+ }
+
+ private _handleDbClickFill(source: IRange) {
+ const selection = this._detectFillRange(source);
+ // double click only works when dest range is longer than source range
+ if (selection.endRow <= source.endRow) {
+ return;
+ }
+ // double click effect is the same as drag effect, but the apply area is automatically calculated (by method '_detectFillRange')
+ this._triggerAutoFill(source, selection);
+ }
+
+ private _detectFillRange(source: IRange) {
+ const { startRow, endRow, startColumn, endColumn } = source;
+ const worksheet = this._univerInstanceService.getCurrentUniverSheetInstance()?.getActiveSheet();
+ if (!worksheet) {
+ return source;
+ }
+ const matrix = worksheet.getCellMatrix();
+ const maxRow = worksheet.getMaxRows() - 1;
+ const maxColumn = worksheet.getMaxColumns() - 1;
+ let detectEndRow = endRow;
+ // left column first, or consider right column.
+ if (startColumn > 0 && matrix.getValue(startRow, startColumn - 1)?.v != null) {
+ let cur = startRow;
+ while (matrix.getValue(cur, startColumn - 1)?.v != null && cur < maxRow) {
+ cur += 1;
+ }
+ detectEndRow = cur;
+ } else if (endColumn < maxColumn && matrix.getValue(endRow, endColumn + 1)?.v != null) {
+ let cur = startRow;
+ while (matrix.getValue(cur, endColumn + 1)?.v != null && cur < maxRow) {
+ cur++;
+ }
+ detectEndRow = cur;
+ }
+
+ for (let i = endRow + 1; i <= detectEndRow; i++) {
+ for (let j = startColumn; j <= endColumn; j++) {
+ if (matrix.getValue(i, j)?.v != null) {
+ detectEndRow = i - 1;
+ break;
+ }
+ }
+ }
+
+ return {
+ startColumn,
+ endColumn,
+ startRow,
+ endRow: detectEndRow,
+ };
+ }
+
+ private _handleFillData() {
+ const {
+ source,
+ target,
+ unitId = this._univerInstanceService.getCurrentUniverSheetInstance().getUnitId(),
+ subUnitId = this._univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId(),
+ } = this._autoFillService.autoFillLocation || {};
+ const direction = this._autoFillService.direction;
+ if (!source || !target) {
+ return;
+ }
+
+ const selection = Rectangle.union(source, target);
+ const applyType = this._autoFillService.applyType;
+ const activeHooks = this._autoFillService.getActiveHooks();
+
+ this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ selections: [
+ {
+ primary: {
+ ...selection,
+ endColumn: selection.startColumn,
+ endRow: selection.startRow,
+ },
+ range: {
+ ...selection,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ },
+ ],
+ unitId,
+ subUnitId,
+ });
+
+ const undos: IMutationInfo[] = [];
+ const redos: IMutationInfo[] = [];
+ activeHooks.forEach((hook) => {
+ const { undos: hookUndos, redos: hookRedos } =
+ hook.onFillData?.({ source, target, unitId, subUnitId }, direction, applyType) || {};
+ if (hookUndos) {
+ undos.push(...hookUndos);
+ }
+ if (hookRedos) {
+ redos.push(...hookRedos);
+ }
+ });
+
+ const result = redos.every((m) => this._commandService.syncExecuteCommand(m.id, m.params));
+ if (result) {
+ // add to undo redo services
+ this._undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: undos,
+ redoMutations: redos,
+ });
+ }
+ // this._commandService.executeCommand(AutoFillCommand.id);
+ activeHooks.forEach((hook) => {
+ hook.onAfterFillData?.({ source, target, unitId, subUnitId }, direction, applyType);
+ });
+ this._autoFillService.setShowMenu(true);
+ }
+
// calc apply data according to copy data and direction
private _getApplyData(
copyDataPiece: ICopyDataPiece,
@@ -363,13 +506,13 @@ export class AutoFillController extends Disposable {
}
}
- private _getCopyData(sourceRange: IRange, direction: Direction) {
+ private _getCopyData(source: IRange, direction: Direction) {
const {
startRow: copyStartRow,
startColumn: copyStartColumn,
endRow: copyEndRow,
endColumn: copyEndColumn,
- } = sourceRange;
+ } = source;
const currentCellDatas = this._univerInstanceService
.getCurrentUniverSheetInstance()
.getActiveSheet()
@@ -446,11 +589,11 @@ export class AutoFillController extends Disposable {
return copyDataPiece;
}
- private _getMergeApplyData(sourceRange: IRange, destRange: IRange, direction: Direction, csLen: number) {
+ private _getMergeApplyData(source: IRange, target: IRange, direction: Direction, csLen: number) {
const mergeData = this._univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getMergeData();
const applyMergeRanges = [];
- for (let i = sourceRange.startRow; i <= sourceRange.endRow; i++) {
- for (let j = sourceRange.startColumn; j <= sourceRange.endColumn; j++) {
+ for (let i = source.startRow; i <= source.endRow; i++) {
+ for (let j = source.startColumn; j <= source.endColumn; j++) {
const { isMergedMainCell, startRow, startColumn, endRow, endColumn } = getCellInfoInMergeData(
i,
j,
@@ -460,7 +603,7 @@ export class AutoFillController extends Disposable {
if (direction === Direction.DOWN) {
let windowStartRow = startRow + csLen;
let windowEndRow = endRow + csLen;
- while (windowEndRow <= destRange.endRow) {
+ while (windowEndRow <= target.endRow) {
applyMergeRanges.push({
startRow: windowStartRow,
startColumn,
@@ -473,7 +616,7 @@ export class AutoFillController extends Disposable {
} else if (direction === Direction.UP) {
let windowStartRow = startRow - csLen;
let windowEndRow = endRow - csLen;
- while (windowStartRow >= destRange.startRow) {
+ while (windowStartRow >= target.startRow) {
applyMergeRanges.push({
startRow: windowStartRow,
startColumn,
@@ -486,7 +629,7 @@ export class AutoFillController extends Disposable {
} else if (direction === Direction.RIGHT) {
let windowStartColumn = startColumn + csLen;
let windowEndColumn = endColumn + csLen;
- while (windowEndColumn <= destRange.endColumn) {
+ while (windowEndColumn <= target.endColumn) {
applyMergeRanges.push({
startRow,
startColumn: windowStartColumn,
@@ -499,7 +642,7 @@ export class AutoFillController extends Disposable {
} else if (direction === Direction.LEFT) {
const windowStartColumn = startColumn - csLen;
const windowEndColumn = endColumn - csLen;
- while (windowStartColumn >= destRange.startColumn) {
+ while (windowStartColumn >= target.startColumn) {
applyMergeRanges.push({
startRow,
startColumn: windowStartColumn,
@@ -514,32 +657,8 @@ export class AutoFillController extends Disposable {
return applyMergeRanges;
}
- private _presetAndCacheData(sourceRange: IRange, destRange: IRange) {
- // save ranges
- const applyRange = {
- startRow: destRange.startRow,
- endRow: destRange.endRow,
- startColumn: destRange.startColumn,
- endColumn: destRange.endColumn,
- };
- let direction = null;
- if (destRange.startRow < sourceRange.startRow) {
- direction = Direction.UP;
- applyRange.endRow = sourceRange.startRow - 1;
- } else if (destRange.endRow > sourceRange.endRow) {
- direction = Direction.DOWN;
- applyRange.startRow = sourceRange.endRow + 1;
- } else if (destRange.startColumn < sourceRange.startColumn) {
- direction = Direction.LEFT;
- applyRange.endColumn = sourceRange.startColumn - 1;
- } else if (destRange.endColumn > sourceRange.endColumn) {
- direction = Direction.RIGHT;
- applyRange.startColumn = sourceRange.endColumn + 1;
- } else {
- return;
- }
- this._direction = direction;
-
+ private _presetAndCacheData(location: IAutoFillLocation, direction: Direction) {
+ const { source, target } = location;
// cache original data of apply range
const currentCellDatas = this._univerInstanceService
.getCurrentUniverSheetInstance()
@@ -547,34 +666,39 @@ export class AutoFillController extends Disposable {
.getCellMatrix();
// cache the original data in currentCellDatas in apply range for later use / refill
const applyData = [];
- for (let i = applyRange.startRow; i <= applyRange.endRow; i++) {
+ for (let i = target.startRow; i <= target.endRow; i++) {
const row = [];
- for (let j = applyRange.startColumn; j <= applyRange.endColumn; j++) {
+ for (let j = target.startColumn; j <= target.endColumn; j++) {
row.push(Tools.deepClone(currentCellDatas.getValue(i, j)));
}
applyData.push(row);
}
this._beforeApplyData = applyData;
- this._autoFillService.setRanges(destRange, sourceRange, applyRange);
- this._copyData = this._getCopyData(sourceRange, direction);
+ this._copyData = this._getCopyData(source, direction);
if (this._hasSeries(this._copyData)) {
this._autoFillService.setDisableApplyType(APPLY_TYPE.SERIES, false);
- this._autoFillService.setApplyType(APPLY_TYPE.SERIES);
} else {
this._autoFillService.setDisableApplyType(APPLY_TYPE.SERIES, true);
- this._autoFillService.setApplyType(APPLY_TYPE.COPY);
}
}
// auto fill entry
- private _fillData() {
- const { destRange, sourceRange, applyRange } = this._autoFillService.getRanges();
- const applyType = this._applyType;
- const hasStyle = this._hasFillingStyle;
- const direction = this._direction;
+ private _fillData(location: IAutoFillLocation, direction: Direction, applyType: APPLY_TYPE) {
+ const undos: IMutationInfo[] = [];
+ const redos: IMutationInfo[] = [];
- if (!destRange || !sourceRange || !applyRange || direction == null) {
- return;
+ let hasStyle = true;
+ if (applyType === APPLY_TYPE.NO_FORMAT) {
+ hasStyle = false;
+ }
+
+ const { source, target, unitId, subUnitId } = location;
+
+ if (!source || !target || direction == null) {
+ return {
+ undos,
+ redos,
+ };
}
const {
@@ -582,14 +706,14 @@ export class AutoFillController extends Disposable {
startColumn: copyStartColumn,
endRow: copyEndRow,
endColumn: copyEndColumn,
- } = sourceRange;
+ } = source;
const {
startRow: applyStartRow,
startColumn: applyStartColumn,
endRow: applyEndRow,
endColumn: applyEndColumn,
- } = applyRange;
+ } = target;
const copyData = this._copyData;
@@ -642,10 +766,10 @@ export class AutoFillController extends Disposable {
}
// deal with styles
- let applyMergeRanges;
+ let applyMergeRanges: IRange[] = [];
const style = this._univerInstanceService.getCurrentUniverSheetInstance().getStyles();
if (hasStyle) {
- applyMergeRanges = this._getMergeApplyData(sourceRange, destRange, direction, csLen);
+ applyMergeRanges = this._getMergeApplyData(source, target, direction, csLen);
applyDatas.forEach((row) => {
row.forEach((cellData) => {
if (cellData && style) {
@@ -665,27 +789,86 @@ export class AutoFillController extends Disposable {
});
}
- // deal with hooks
- const hooks = this._autoFillService.getHooks();
- const extendRedos: IMutationInfo[] = [];
- const extendUndos: IMutationInfo[] = [];
- const hookApplyType: APPLY_TYPE = this._hasFillingStyle ? applyType : APPLY_TYPE.NO_FORMAT;
- hooks.forEach((h) => {
- const { hook } = h;
- const { redos, undos } = hook?.[hookApplyType](sourceRange, applyRange);
- extendRedos.push(...redos);
- extendUndos.push(...undos);
- });
+ const accessor = {
+ get: this._injector.get.bind(this._injector),
+ };
+ // delete cross merge
+ const deleteMergeRanges: IRange[] = [];
+ const mergeData = this._univerInstanceService
+ .getUniverSheetInstance(unitId)
+ ?.getSheetBySheetId(subUnitId)
+ ?.getMergeData();
+ if (mergeData) {
+ mergeData.forEach((merge) => {
+ if (Rectangle.intersects(merge, target)) {
+ deleteMergeRanges.push(merge);
+ }
+ });
+ }
+ const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {
+ unitId,
+ subUnitId,
+ ranges: deleteMergeRanges,
+ };
+ const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(
+ accessor,
+ removeMergeMutationParams
+ );
- this._commandService.executeCommand(AutoFillCommand.id, {
- selectionRange: destRange,
- applyRange,
- applyDatas,
- unitId: this._univerInstanceService.getCurrentUniverSheetInstance().getUnitId(),
- subUnitId: this._univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId(),
- extendMutations: { undo: extendUndos, redo: extendRedos },
- applyMergeRanges,
- });
+ redos.push({ id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams });
+ undos.push({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams });
+
+ // set range value
+ const cellValue = new ObjectMatrix<ICellData>();
+ const { startRow, startColumn, endRow, endColumn } = target;
+
+ for (let r = 0; r <= endRow - startRow; r++) {
+ for (let c = 0; c <= endColumn - startColumn; c++) {
+ if (applyDatas[r][c]) {
+ cellValue.setValue(r + startRow, c + startColumn, applyDatas[r][c]!);
+ }
+ }
+ }
+
+ const setRangeValuesMutationParams: ISetRangeValuesMutationParams = {
+ subUnitId,
+ unitId,
+ cellValue: cellValue.getMatrix(),
+ };
+
+ const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
+ accessor,
+ setRangeValuesMutationParams
+ );
+
+ undos.push({ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams });
+ redos.push({ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams });
+
+ undos.push({ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams });
+ redos.push({ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams });
+
+ // add worksheet merge
+ if (applyMergeRanges?.length) {
+ const ranges = getAddMergeMutationRangeByType(applyMergeRanges);
+
+ const addMergeMutationParams: IAddWorksheetMergeMutationParams = {
+ unitId,
+ subUnitId,
+ ranges,
+ };
+ const undoRemoveMutationParams: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(
+ accessor,
+ addMergeMutationParams
+ );
+
+ undos.push({ id: RemoveWorksheetMergeMutation.id, params: undoRemoveMutationParams });
+ redos.push({ id: AddWorksheetMergeMutation.id, params: addMergeMutationParams });
+ }
+
+ return {
+ undos,
+ redos,
+ };
}
private _hasSeries(copyData: ICopyDataPiece[]) {
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 83d24d1f41..af7250796f 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -38,7 +38,7 @@ export {
export { enUS, zhCN } from './locale';
export { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';
export { getAutoFillRepeatRange } from './services/auto-fill/tools';
-export type { IAutoFillHook, ICopyDataPiece } from './services/auto-fill/type';
+export type { ICopyDataPiece, ISheetAutoFillHook } from './services/auto-fill/type';
export { APPLY_TYPE, DATA_TYPE, type IAutoFillRule } from './services/auto-fill/type';
export { type ICopyDataInTypeIndexInfo } from './services/auto-fill/type';
export {
diff --git a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts b/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
index 75d9c2d777..2ba97d3680 100644
--- a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
+++ b/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
@@ -14,8 +14,15 @@
* limitations under the License.
*/
-import type { IRange } from '@univerjs/core';
-import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, toDisposable } from '@univerjs/core';
+import type { Nullable } from '@univerjs/core';
+import {
+ Direction,
+ Disposable,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+ toDisposable,
+} from '@univerjs/core';
import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier, Inject } from '@wendellhu/redi';
@@ -31,23 +38,35 @@ import {
numberRule,
otherRule,
} from './rules';
-import type { IAutoFillHook, IAutoFillRule } from './type';
-import { APPLY_TYPE } from './type';
+import type { IAutoFillLocation, IAutoFillRule, ISheetAutoFillHook } from './type';
+import { APPLY_TYPE, AutoFillHookType } from './type';
export interface IAutoFillService {
- getRules(): IAutoFillRule[];
- getApplyType(): APPLY_TYPE;
- isFillingStyle(): boolean;
- setApplyType(type: APPLY_TYPE): void;
- setRanges(sourceRange: IRange, destRange: IRange, applyRange: IRange): void;
- getRanges(): { sourceRange: IRange | null; destRange: IRange | null; applyRange: IRange | null };
- setFillingStyle(isFillingStyle: boolean): void;
applyType$: Observable<APPLY_TYPE>;
+ applyType: APPLY_TYPE;
+
+ direction: Direction;
+
menu$: Observable<IApplyMenuItem[]>;
+ menu: IApplyMenuItem[];
+
+ showMenu$: Observable<boolean>;
+ setShowMenu: (show: boolean) => void;
+
setDisableApplyType: (type: APPLY_TYPE, disable: boolean) => void;
+
+ getRules(): IAutoFillRule[];
+ isFillingStyle(): boolean;
+
+ autoFillLocation$: Observable<Nullable<IAutoFillLocation>>;
+ autoFillLocation: Nullable<IAutoFillLocation>;
+
+ setFillingStyle(isFillingStyle: boolean): void;
registerRule(rule: IAutoFillRule): void;
- getHooks(): IAutoFillHook[];
- addHook(hook: IAutoFillHook): IDisposable;
+
+ getAllHooks(): ISheetAutoFillHook[];
+ getActiveHooks(): ISheetAutoFillHook[];
+ addHook(hook: ISheetAutoFillHook): IDisposable;
}
export interface IApplyMenuItem {
@@ -59,12 +78,20 @@ export interface IApplyMenuItem {
@OnLifecycle(LifecycleStages.Rendered, AutoFillService)
export class AutoFillService extends Disposable implements IAutoFillService {
private _rules: IAutoFillRule[] = [];
- private _hooks: IAutoFillHook[] = [];
+ private _hooks: ISheetAutoFillHook[] = [];
private readonly _applyType$: BehaviorSubject<APPLY_TYPE> = new BehaviorSubject<APPLY_TYPE>(APPLY_TYPE.SERIES);
private _isFillingStyle: boolean = true;
- private _sourceRange: IRange | null = null;
- private _destRange: IRange | null = null;
- private _applyRange: IRange | null = null;
+
+ private readonly _autoFillLocation$: BehaviorSubject<Nullable<IAutoFillLocation>> = new BehaviorSubject<
+ Nullable<IAutoFillLocation>
+ >(null);
+
+ readonly autoFillLocation$ = this._autoFillLocation$.asObservable();
+
+ private readonly _showMenu$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
+ readonly showMenu$ = this._showMenu$.asObservable();
+
+ private _direction: Direction = Direction.DOWN;
readonly applyType$ = this._applyType$.asObservable();
private readonly _menu$: BehaviorSubject<IApplyMenuItem[]> = new BehaviorSubject<IApplyMenuItem[]>([
@@ -112,9 +139,26 @@ export class AutoFillService extends Disposable implements IAutoFillService {
this._isFillingStyle = true;
}
- addHook(hook: IAutoFillHook) {
- if (this._hooks.find((h) => h.hookName === hook.hookName)) {
- throw new Error(`Add hook failed, hook name '${hook.hookName}' already exist!`);
+ private getOneByPriority(items: ISheetAutoFillHook[]) {
+ if (items.length <= 0) {
+ return [];
+ }
+ const maxPriority = items.reduce((maxItem, currentItem) => {
+ return (currentItem.priority || 0) > (maxItem.priority || 0) ? currentItem : maxItem;
+ }, items[0]);
+ return [maxPriority];
+ }
+
+ addHook(hook: ISheetAutoFillHook) {
+ if (this._hooks.find((h) => h.id === hook.id)) {
+ throw new Error(`Add hook failed, hook id '${hook.id}' already exist!`);
+ }
+ if (hook.priority === undefined) {
+ hook.priority = 0;
+ }
+
+ if (hook.type === undefined) {
+ hook.type = AutoFillHookType.Append;
}
this._hooks.push(hook);
return toDisposable(() => {
@@ -139,18 +183,50 @@ export class AutoFillService extends Disposable implements IAutoFillService {
return this._rules;
}
- getHooks() {
+ getAllHooks() {
return this._hooks;
}
- getApplyType() {
+ getActiveHooks() {
+ const { source, target, unitId, subUnitId } = this.autoFillLocation || {};
+ if (!source || !target || !unitId || !subUnitId) {
+ return [];
+ }
+ const enabledHooks = this._hooks.filter(
+ (h) => !h.disable?.({ source, target, unitId, subUnitId }, this._direction, this.applyType) === true
+ );
+ const onlyHooks = enabledHooks.filter((h) => h.type === AutoFillHookType.Only);
+ if (onlyHooks.length > 0) {
+ return this.getOneByPriority(onlyHooks);
+ }
+
+ const defaultHooks = this.getOneByPriority(enabledHooks.filter((h) => h.type === AutoFillHookType.Default));
+
+ const appendHooks = enabledHooks.filter((h) => h.type === AutoFillHookType.Append) || [];
+
+ return [...defaultHooks, ...appendHooks];
+ }
+
+ get applyType() {
return this._applyType$.getValue();
}
- setApplyType(type: APPLY_TYPE) {
+ set applyType(type: APPLY_TYPE) {
this._applyType$.next(type);
}
+ get menu() {
+ return this._menu$.getValue();
+ }
+
+ get direction() {
+ return this._direction;
+ }
+
+ set direction(direction: Direction) {
+ this._direction = direction;
+ }
+
isFillingStyle(): boolean {
return this._isFillingStyle;
}
@@ -159,18 +235,12 @@ export class AutoFillService extends Disposable implements IAutoFillService {
this._isFillingStyle = isFillingStyle;
}
- setRanges(destRange: IRange, sourceRange: IRange, applyRange: IRange) {
- this._sourceRange = sourceRange;
- this._destRange = destRange;
- this._applyRange = applyRange;
+ get autoFillLocation() {
+ return this._autoFillLocation$.getValue();
}
- getRanges() {
- return {
- sourceRange: this._sourceRange,
- destRange: this._destRange,
- applyRange: this._applyRange,
- };
+ set autoFillLocation(location: Nullable<IAutoFillLocation>) {
+ this._autoFillLocation$.next(location);
}
setDisableApplyType(type: APPLY_TYPE, disable: boolean) {
@@ -186,6 +256,10 @@ export class AutoFillService extends Disposable implements IAutoFillService {
})
);
}
+
+ setShowMenu(show: boolean) {
+ this._showMenu$.next(show);
+ }
}
export const IAutoFillService = createIdentifier<AutoFillService>('univer.auto-fill-service');
diff --git a/packages/sheets-ui/src/services/auto-fill/type.ts b/packages/sheets-ui/src/services/auto-fill/type.ts
index 7d700d258b..cf807a88c6 100644
--- a/packages/sheets-ui/src/services/auto-fill/type.ts
+++ b/packages/sheets-ui/src/services/auto-fill/type.ts
@@ -16,6 +16,35 @@
import type { Direction, ICellData, IMutationInfo, IRange, Nullable } from '@univerjs/core';
+export enum AutoFillHookType {
+ Append = 'APPEND',
+ Default = 'DEFAULT',
+ Only = 'ONLY',
+}
+
+export interface IAutoFillLocation {
+ source: IRange;
+ target: IRange;
+ unitId: string;
+ subUnitId: string;
+}
+export interface ISheetAutoFillHook {
+ id: string;
+ priority?: number;
+ type?: AutoFillHookType;
+ disable?: (location: IAutoFillLocation, direction: Direction, applyType: APPLY_TYPE) => boolean;
+ onBeforeFillData?(location: IAutoFillLocation, direction: Direction): boolean | void;
+ onFillData?(
+ location: IAutoFillLocation,
+ direction: Direction,
+ applyType: APPLY_TYPE
+ ): {
+ undos: IMutationInfo[];
+ redos: IMutationInfo[];
+ };
+ onAfterFillData?(location: IAutoFillLocation, direction: Direction, applyType: APPLY_TYPE): boolean | void;
+}
+
export enum DATA_TYPE {
NUMBER = 'number',
DATE = 'date',
@@ -51,15 +80,6 @@ export interface IMutations {
redos: IMutationInfo[];
undos: IMutationInfo[];
}
-export interface IAutoFillHook {
- hookName: string;
- hook: {
- [APPLY_TYPE.SERIES]: (sourceRange: IRange, targetRange: IRange) => IMutations;
- [APPLY_TYPE.NO_FORMAT]: (sourceRange: IRange, targetRange: IRange) => IMutations;
- [APPLY_TYPE.ONLY_FORMAT]: (sourceRange: IRange, targetRange: IRange) => IMutations;
- [APPLY_TYPE.COPY]: (sourceRange: IRange, targetRange: IRange) => IMutations;
- };
-}
export interface IRuleConfirmedData {
type?: string;
diff --git a/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx b/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx
index f46be2f863..831aae6dbb 100644
--- a/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx
+++ b/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx
@@ -15,7 +15,7 @@
*/
import type { ICommandInfo } from '@univerjs/core';
-import { ICommandService, IUniverInstanceService, LocaleService, toDisposable } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, LocaleService, Rectangle, toDisposable } from '@univerjs/core';
import { Dropdown } from '@univerjs/design';
import { IRenderManagerService } from '@univerjs/engine-render';
import { Autofill, CheckMarkSingle, MoreDownSingle } from '@univerjs/icons';
@@ -24,8 +24,7 @@ import { useDependency } from '@wendellhu/redi/react-bindings';
import clsx from 'clsx';
import React, { useCallback, useEffect, useState } from 'react';
-import type { IAutoFillCommandParams } from '../../commands/commands/auto-fill.command';
-import { AutoClearContentCommand, AutoFillCommand } from '../../commands/commands/auto-fill.command';
+import { AutoClearContentCommand } from '../../commands/commands/auto-fill.command';
import { RefillCommand } from '../../commands/commands/refill.command';
import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';
import { SetScrollOperation } from '../../commands/operations/scroll.operation';
@@ -51,7 +50,7 @@ export interface IAutoFillPopupMenuItem {
const useUpdate = () => {
const [, setState] = useState({});
- return useCallback(() => setState({}), []);
+ return useCallback(() => setState((prevState) => !prevState), []);
};
export const AutoFillPopupMenu: React.FC<{}> = () => {
@@ -93,10 +92,6 @@ export const AutoFillPopupMenu: React.FC<{}> = () => {
SetRangeValuesMutation.id,
];
const disposable = commandService.onCommandExecuted((command: ICommandInfo) => {
- if (command.id === AutoFillCommand.id) {
- const { endColumn, endRow } = (command?.params as IAutoFillCommandParams).selectionRange;
- setAnchor({ row: endRow, col: endColumn });
- }
if (command.id === SetScrollOperation.id) {
forceUpdate();
}
@@ -116,6 +111,19 @@ export const AutoFillPopupMenu: React.FC<{}> = () => {
return disposable.dispose;
}, [autoFillService]);
+ useEffect(() => {
+ const disposable = toDisposable(
+ autoFillService.showMenu$.subscribe((show) => {
+ const { source, target } = autoFillService.autoFillLocation || { source: null, target: null };
+ if (show && source && target) {
+ const selection = Rectangle.union(source, target);
+ setAnchor({ row: selection.endRow, col: selection.endColumn });
+ }
+ })
+ );
+ return disposable.dispose;
+ }, [autoFillService]);
+
useEffect(() => {
const disposable = toDisposable(
autoFillService.applyType$.subscribe((type) => {