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): move the autofill function from the sheets-ui package to the sheets package (#6566)

wpxp123456b29a92ee82c8
diff --git a/packages/action-recorder/src/controllers/action-recorder.controller.tsx b/packages/action-recorder/src/controllers/action-recorder.controller.tsx
index 10e1acd89e..804cb8fa3d 100644
--- a/packages/action-recorder/src/controllers/action-recorder.controller.tsx
+++ b/packages/action-recorder/src/controllers/action-recorder.controller.tsx
@@ -21,6 +21,7 @@ import {
AddWorksheetMergeCommand,
AddWorksheetMergeHorizontalCommand,
AddWorksheetMergeVerticalCommand,
+ AutoFillCommand,
CancelFrozenCommand,
CopySheetCommand,
DeleteRangeMoveLeftCommand,
@@ -32,6 +33,7 @@ import {
InsertRowAfterCommand,
InsertRowBeforeCommand,
InsertSheetCommand,
+ RefillCommand,
RemoveSheetCommand,
SetFrozenCommand,
SetHorizontalTextAlignCommand,
@@ -49,8 +51,6 @@ import {
} from '@univerjs/sheets';
import { RemoveSheetFilterCommand, SetSheetFilterRangeCommand, SetSheetsFilterCriteriaCommand } from '@univerjs/sheets-filter';
import {
- AutoFillCommand,
- RefillCommand,
SetRangeBoldCommand,
SetRangeFontFamilyCommand,
SetRangeFontSizeCommand,
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts
index 32f1c46a8e..b83641b65b 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts
@@ -15,12 +15,12 @@
*/
import type { IMutationInfo, IRange, Workbook } from '@univerjs/core';
+import type { IDiscreteRange, ISheetAutoFillHook } from '@univerjs/sheets';
import type { IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';
-import type { IDiscreteRange, ISheetAutoFillHook } from '@univerjs/sheets-ui';
import { Disposable, Inject, Injector, IUniverInstanceService, ObjectMatrix, Range, Rectangle, UniverInstanceType } from '@univerjs/core';
-import { createTopMatrixFromMatrix, findAllRectangle } from '@univerjs/sheets';
+import { AUTO_FILL_APPLY_TYPE, AutoFillTools, createTopMatrixFromMatrix, findAllRectangle, IAutoFillService } from '@univerjs/sheets';
import { ConditionalFormattingRuleModel, ConditionalFormattingViewModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
-import { APPLY_TYPE, getAutoFillRepeatRange, IAutoFillService, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
+import { virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
export class ConditionalFormattingAutoFillController extends Disposable {
constructor(
@@ -160,7 +160,7 @@ export class ConditionalFormattingAutoFillController extends Disposable {
col: vSourceRange.startColumn,
};
- const repeats = getAutoFillRepeatRange(vSourceRange, vTargetRange);
+ const repeats = AutoFillTools.getAutoFillRepeatRange(vSourceRange, vTargetRange);
repeats.forEach((repeat) => {
loopFunc(sourceStartCell, repeat.repeatStartCell, repeat.relativeRange, matrixMap, mapFunc);
});
@@ -197,7 +197,7 @@ export class ConditionalFormattingAutoFillController extends Disposable {
const hook: ISheetAutoFillHook = {
id: SHEET_CONDITIONAL_FORMATTING_PLUGIN,
onFillData: (location, direction, applyType) => {
- if (applyType === APPLY_TYPE.COPY || applyType === APPLY_TYPE.ONLY_FORMAT || applyType === APPLY_TYPE.SERIES) {
+ if (applyType === AUTO_FILL_APPLY_TYPE.COPY || applyType === AUTO_FILL_APPLY_TYPE.ONLY_FORMAT || applyType === AUTO_FILL_APPLY_TYPE.SERIES) {
const { source, target } = location;
return generalApplyFunc(source, target);
}
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts
index cfccc6fe5a..0827c1d5a8 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts
@@ -15,8 +15,9 @@
*/
import type { IRange, Nullable, Workbook } from '@univerjs/core';
+import type { IDiscreteRange } from '@univerjs/sheets';
import type { IAddConditionalRuleMutationParams, IConditionalFormattingRuleConfig, IConditionFormattingRule, IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';
-import type { IDiscreteRange, IPasteHookValueType } from '@univerjs/sheets-ui';
+import type { IPasteHookValueType } from '@univerjs/sheets-ui';
import {
Disposable,
Inject,
diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-auto-fill.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-auto-fill.controller.ts
index e9d341ac5b..849c16bfdf 100644
--- a/packages/sheets-data-validation-ui/src/controllers/dv-auto-fill.controller.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/dv-auto-fill.controller.ts
@@ -14,10 +14,11 @@
* limitations under the License.
*/
-import type { IAutoFillLocation, ISheetAutoFillHook } from '@univerjs/sheets-ui';
+import type { IAutoFillLocation, ISheetAutoFillHook } from '@univerjs/sheets';
import { DataValidationType, Disposable, Inject, Injector, ObjectMatrix, queryObjectMatrix, Range, Rectangle } from '@univerjs/core';
+import { AUTO_FILL_APPLY_TYPE, AutoFillTools, IAutoFillService } from '@univerjs/sheets';
import { DATA_VALIDATION_PLUGIN_NAME, getDataValidationDiffMutations, SheetDataValidationModel } from '@univerjs/sheets-data-validation';
-import { APPLY_TYPE, getAutoFillRepeatRange, IAutoFillService, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
+import { virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
// TODO: adjust imports
@@ -35,7 +36,7 @@ export class DataValidationAutoFillController extends Disposable {
private _initAutoFill() {
const noopReturnFunc = () => ({ redos: [], undos: [] });
- const generalApplyFunc = (location: IAutoFillLocation, applyType: APPLY_TYPE) => {
+ const generalApplyFunc = (location: IAutoFillLocation, applyType: AUTO_FILL_APPLY_TYPE) => {
const { source: sourceRange, target: targetRange, unitId, subUnitId } = location;
const ruleMatrixCopy = this._sheetDataValidationModel.getRuleObjectMatrix(unitId, subUnitId).clone();
@@ -46,7 +47,7 @@ export class DataValidationAutoFillController extends Disposable {
row: vSourceRange.startRow,
col: vSourceRange.startColumn,
};
- const repeats = getAutoFillRepeatRange(vSourceRange, vTargetRange);
+ const repeats = AutoFillTools.getAutoFillRepeatRange(vSourceRange, vTargetRange);
const additionMatrix = new ObjectMatrix();
const additionRules = new Set<string>();
repeats.forEach((repeat) => {
@@ -95,7 +96,7 @@ export class DataValidationAutoFillController extends Disposable {
const additions = Array.from(additionRules).map((id) => ({ id, ranges: queryObjectMatrix(additionMatrix, (value) => value === id) }));
ruleMatrixCopy.addRangeRules(additions);
const diffs = ruleMatrixCopy.diff(this._sheetDataValidationModel.getRules(unitId, subUnitId));
- const { redoMutations, undoMutations } = getDataValidationDiffMutations(unitId, subUnitId, diffs, this._injector, 'patched', applyType === APPLY_TYPE.ONLY_FORMAT);
+ const { redoMutations, undoMutations } = getDataValidationDiffMutations(unitId, subUnitId, diffs, this._injector, 'patched', applyType === AUTO_FILL_APPLY_TYPE.ONLY_FORMAT);
return {
undos: undoMutations,
redos: redoMutations,
@@ -109,7 +110,7 @@ export class DataValidationAutoFillController extends Disposable {
for (const col of sourceRange.cols) {
const dv = this._sheetDataValidationModel.getRuleByLocation(unitId, subUnitId, row, col);
if (dv && dv.type === DataValidationType.CHECKBOX) {
- this._autoFillService.setDisableApplyType(APPLY_TYPE.SERIES, true);
+ this._autoFillService.setDisableApplyType(AUTO_FILL_APPLY_TYPE.SERIES, true);
return;
}
}
@@ -117,9 +118,9 @@ export class DataValidationAutoFillController extends Disposable {
},
onFillData: (location, direction, applyType) => {
if (
- applyType === APPLY_TYPE.COPY ||
- applyType === APPLY_TYPE.ONLY_FORMAT ||
- applyType === APPLY_TYPE.SERIES
+ applyType === AUTO_FILL_APPLY_TYPE.COPY ||
+ applyType === AUTO_FILL_APPLY_TYPE.ONLY_FORMAT ||
+ applyType === AUTO_FILL_APPLY_TYPE.SERIES
) {
return generalApplyFunc(location, applyType);
}
diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-copy-paste.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-copy-paste.controller.ts
index 7d3a8af883..ec268f693a 100644
--- a/packages/sheets-data-validation-ui/src/controllers/dv-copy-paste.controller.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/dv-copy-paste.controller.ts
@@ -15,7 +15,8 @@
*/
import type { IRange, ISheetDataValidationRule, Nullable } from '@univerjs/core';
-import type { IDiscreteRange, IPasteHookValueType } from '@univerjs/sheets-ui';
+import type { IDiscreteRange } from '@univerjs/sheets';
+import type { IPasteHookValueType } from '@univerjs/sheets-ui';
import { Disposable, Inject, Injector, ObjectMatrix, queryObjectMatrix, Rectangle } from '@univerjs/core';
import { rangeToDiscreteRange } from '@univerjs/sheets';
import { DATA_VALIDATION_PLUGIN_NAME, getDataValidationDiffMutations, SheetDataValidationModel } from '@univerjs/sheets-data-validation';
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-cell-image-autofill.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-cell-image-autofill.controller.ts
index 21b3c2e42b..1720e90ee9 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-cell-image-autofill.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-cell-image-autofill.controller.ts
@@ -15,7 +15,7 @@
*/
import { Disposable, Inject, Injector, ObjectMatrix } from '@univerjs/core';
-import { IAutoFillService } from '@univerjs/sheets-ui';
+import { IAutoFillService } from '@univerjs/sheets';
import { resizeImageByCell } from './sheet-cell-image.controller';
export class SheetCellImageAutofillController extends Disposable {
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
index f5dd746ec8..4c11188f13 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
@@ -16,16 +16,17 @@
import type { IMutationInfo, IRange, Nullable } from '@univerjs/core';
import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import type { IDiscreteRange } from '@univerjs/sheets';
import type { ISheetDrawing, ISheetImage } from '@univerjs/sheets-drawing';
-import type { IDiscreteRange, IPasteHookValueType, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
+import type { IPasteHookValueType, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
import type { IDeleteDrawingCommandParams } from '../commands/commands/interfaces';
import { Disposable, DrawingTypeEnum, generateRandomId, ICommandService } from '@univerjs/core';
import { IDrawingManagerService, ImageSourceType } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
+import { discreteRangeToRange } from '@univerjs/sheets';
import { DrawingApplyType, SetDrawingApplyMutation, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
import {
COPY_TYPE,
- discreteRangeToRange,
ISheetClipboardService,
ISheetSelectionRenderService,
PREDEFINED_HOOK_NAME_PASTE,
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-auto-fill.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
index 2986da2c8e..5ed082fe7e 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
@@ -26,6 +26,10 @@ import {
} from '@univerjs/core';
import {
AddWorksheetMergeMutation,
+ AutoFillCommand,
+ AutoFillController,
+ AutoFillService,
+ IAutoFillService,
RangeProtectionRenderModel,
RangeProtectionService,
RemoveWorksheetMergeMutation,
@@ -34,10 +38,7 @@ import {
SheetsSelectionsService,
} from '@univerjs/sheets';
import {
- AutoFillCommand,
- AutoFillController,
- AutoFillService,
- IAutoFillService,
+ AutoFillUIController,
ISheetSelectionRenderService,
SheetSelectionRenderService,
SheetsRenderService,
@@ -67,14 +68,15 @@ describe('Test auto fill with formula', () => {
beforeEach(() => {
const testBed = createCommandTestBed(undefined, [
[ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }],
- [AutoFillController],
[IAutoFillService, { useClass: AutoFillService }],
[IShortcutService, { useClass: ShortcutService }],
[IPlatformService, { useClass: PlatformService }],
+ [SheetsRenderService, { useClass: mockSheetsRenderService }],
+ [AutoFillController],
+ [AutoFillUIController],
[FormulaAutoFillController],
[RangeProtectionService],
[RangeProtectionRenderModel],
- [SheetsRenderService, { useClass: mockSheetsRenderService }],
]);
univer = testBed.univer;
@@ -87,6 +89,7 @@ describe('Test auto fill with formula', () => {
themeService.setTheme(newTheme);
get(AutoFillController);
+ get(AutoFillUIController);
commandService.registerCommand(SetRangeValuesMutation);
commandService.registerCommand(SetSelectionsOperation);
diff --git a/packages/sheets-formula-ui/src/controllers/formula-auto-fill.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-auto-fill.controller.ts
index efcf1a18b7..d3f90f0f93 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-auto-fill.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-auto-fill.controller.ts
@@ -15,7 +15,7 @@
*/
import type { ICellData, Nullable } from '@univerjs/core';
-import type { AutoFillService, IAutoFillLocation, IAutoFillRule, ICopyDataInTypeIndexInfo, ICopyDataPiece } from '@univerjs/sheets-ui';
+import type { AutoFillService, IAutoFillCopyDataInTypeIndexInfo, IAutoFillCopyDataPiece, IAutoFillLocation, IAutoFillRule } from '@univerjs/sheets';
import {
Direction,
Disposable,
@@ -26,7 +26,7 @@ import {
Tools,
} from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
-import { APPLY_TYPE, DATA_TYPE, IAutoFillService } from '@univerjs/sheets-ui';
+import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_DATA_TYPE, IAutoFillService } from '@univerjs/sheets';
export class FormulaAutoFillController extends Disposable {
constructor(
@@ -40,17 +40,17 @@ export class FormulaAutoFillController extends Disposable {
private _registerAutoFill(): void {
const formulaRule: IAutoFillRule = {
- type: DATA_TYPE.FORMULA,
+ type: AUTO_FILL_DATA_TYPE.FORMULA,
priority: 1001,
match: (cellData) => isFormulaString(cellData?.f) || isFormulaId(cellData?.si),
isContinue: (prev, cur) => {
- if (prev.type === DATA_TYPE.FORMULA) {
+ if (prev.type === AUTO_FILL_DATA_TYPE.FORMULA) {
return true;
}
return false;
},
applyFunctions: {
- [APPLY_TYPE.COPY]: (dataWithIndex, len, direction, copyDataPiece, location) => {
+ [AUTO_FILL_APPLY_TYPE.COPY]: (dataWithIndex, len, direction, copyDataPiece, location) => {
const { data, index } = dataWithIndex;
return this._fillCopyFormula(data, len, direction, index, copyDataPiece, location as IAutoFillLocation);
},
@@ -63,8 +63,8 @@ export class FormulaAutoFillController extends Disposable {
data: Array<Nullable<ICellData>>,
len: number,
direction: Direction,
- index: ICopyDataInTypeIndexInfo,
- copyDataPiece: ICopyDataPiece,
+ index: IAutoFillCopyDataInTypeIndexInfo,
+ copyDataPiece: IAutoFillCopyDataPiece,
location: IAutoFillLocation
) {
const step = getDataLength(copyDataPiece);
@@ -160,7 +160,7 @@ function directionToOffset(step: number, len: number, direction: Direction, loca
return { offsetX, offsetY };
}
-function getDataLength(copyDataPiece: ICopyDataPiece) {
+function getDataLength(copyDataPiece: IAutoFillCopyDataPiece) {
let length = 0;
for (const t in copyDataPiece) {
copyDataPiece[t].forEach((item) => {
diff --git a/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts
index 3d03ed2582..c0238535d1 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-clipboard.controller.ts
@@ -15,8 +15,8 @@
*/
import type { IAccessor, ICellData, ICellDataWithSpanAndDisplay, IMutationInfo, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';
-import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import type { ICellDataWithSpanInfo, ICopyPastePayload, IDiscreteRange, IPasteHookValueType, ISheetClipboardHook, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
+import type { IDiscreteRange, ISetRangeValuesMutationParams } from '@univerjs/sheets';
+import type { ICellDataWithSpanInfo, ICopyPastePayload, IPasteHookValueType, ISheetClipboardHook, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
import {
DEFAULT_EMPTY_DOCUMENT_VALUE,
Disposable,
diff --git a/packages/sheets-hyper-link-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/auto-fill.controller.ts
index 70e4197db5..4f96cadfc6 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/auto-fill.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/auto-fill.controller.ts
@@ -15,10 +15,11 @@
*/
import type { IMutationInfo } from '@univerjs/core';
-import type { IAutoFillLocation, ISheetAutoFillHook } from '@univerjs/sheets-ui';
+import type { IAutoFillLocation, ISheetAutoFillHook } from '@univerjs/sheets';
import { Disposable, generateRandomId, Inject, Range, Rectangle } from '@univerjs/core';
+import { AUTO_FILL_APPLY_TYPE, AutoFillTools, IAutoFillService } from '@univerjs/sheets';
import { AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
-import { APPLY_TYPE, getAutoFillRepeatRange, IAutoFillService, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
+import { virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
import { SHEET_HYPER_LINK_UI_PLUGIN } from '../types/const';
export class SheetsHyperLinkAutoFillController extends Disposable {
@@ -35,7 +36,7 @@ export class SheetsHyperLinkAutoFillController extends Disposable {
const noopReturnFunc = () => ({ redos: [], undos: [] });
// eslint-disable-next-line max-lines-per-function
- const generalApplyFunc = (location: IAutoFillLocation, applyType: APPLY_TYPE) => {
+ const generalApplyFunc = (location: IAutoFillLocation, applyType: AUTO_FILL_APPLY_TYPE) => {
const { source: sourceRange, target: targetRange, unitId, subUnitId } = location;
const virtualRange = virtualizeDiscreteRanges([sourceRange, targetRange]);
@@ -45,7 +46,7 @@ export class SheetsHyperLinkAutoFillController extends Disposable {
row: vSourceRange.startRow,
col: vSourceRange.startColumn,
};
- const repeats = getAutoFillRepeatRange(vSourceRange, vTargetRange);
+ const repeats = AutoFillTools.getAutoFillRepeatRange(vSourceRange, vTargetRange);
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
@@ -99,7 +100,7 @@ export class SheetsHyperLinkAutoFillController extends Disposable {
},
});
}
- if ((APPLY_TYPE.COPY === applyType || APPLY_TYPE.SERIES === applyType) && link) {
+ if ((AUTO_FILL_APPLY_TYPE.COPY === applyType || AUTO_FILL_APPLY_TYPE.SERIES === applyType) && link) {
redos.push({
id: AddHyperLinkMutation.id,
params: {
@@ -143,9 +144,9 @@ export class SheetsHyperLinkAutoFillController extends Disposable {
id: SHEET_HYPER_LINK_UI_PLUGIN,
onFillData: (location, direction, applyType) => {
if (
- applyType === APPLY_TYPE.COPY ||
- applyType === APPLY_TYPE.ONLY_FORMAT ||
- applyType === APPLY_TYPE.SERIES
+ applyType === AUTO_FILL_APPLY_TYPE.COPY ||
+ applyType === AUTO_FILL_APPLY_TYPE.ONLY_FORMAT ||
+ applyType === AUTO_FILL_APPLY_TYPE.SERIES
) {
return generalApplyFunc(location, applyType);
}
diff --git a/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts
index 8f899cce84..2501fe72e8 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/copy-paste.controller.ts
@@ -15,7 +15,8 @@
*/
import type { IMutationInfo, IRange, Nullable } from '@univerjs/core';
-import type { IDiscreteRange, IPasteHookValueType, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
+import type { IDiscreteRange } from '@univerjs/sheets';
+import type { IPasteHookValueType, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
import { Disposable, generateRandomId, Inject, Injector, ObjectMatrix, Range, Rectangle } from '@univerjs/core';
import { rangeToDiscreteRange } from '@univerjs/sheets';
import { AddHyperLinkMutation, HyperLinkModel, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
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 bc594a8f73..d6152a5c31 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
@@ -31,6 +31,13 @@ import { EditorService, IEditorService } from '@univerjs/docs-ui';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import {
AddWorksheetMergeMutation,
+ AUTO_FILL_APPLY_TYPE,
+ AutoClearContentCommand,
+ AutoFillCommand,
+ AutoFillController,
+ AutoFillService,
+ IAutoFillService,
+ RefillCommand,
RemoveWorksheetMergeMutation,
SetRangeValuesMutation,
SetSelectionsOperation,
@@ -38,22 +45,14 @@ import {
} from '@univerjs/sheets';
import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';
import { beforeEach, describe, expect, it } from 'vitest';
-import { AutoFillController } from '../../../controllers/auto-fill.controller';
-import { AutoFillService, IAutoFillService } from '../../../services/auto-fill/auto-fill.service';
-import { APPLY_TYPE } from '../../../services/auto-fill/type';
+import { AutoFillUIController } from '../../../controllers/auto-fill-ui.controller';
import { EditorBridgeService, IEditorBridgeService } from '../../../services/editor-bridge.service';
import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
import { SheetSelectionRenderService } from '../../../services/selection/selection-render.service';
import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
import { SheetsRenderService } from '../../../services/sheets-render.service';
-import { AutoClearContentCommand, AutoFillCommand } from '../auto-fill.command';
-import { RefillCommand } from '../refill.command';
import { createCommandTestBed } from './create-command-test-bed';
-const theme = {
- colorBlack: '#35322b',
-};
-
class mockSheetsRenderService {
registerSkeletonChangingMutations(id: string) {
}
@@ -266,7 +265,7 @@ describe('Test auto fill rules in controller', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
- let autoFillController: AutoFillController;
+ let autoFillController: AutoFillUIController;
let themeService: ThemeService;
let getValues: (
@@ -294,9 +293,10 @@ describe('Test auto fill rules in controller', () => {
[IEditorBridgeService, { useClass: EditorBridgeService }],
[IEditorService, { useClass: EditorService }],
[IRenderManagerService, { useClass: RenderManagerService }],
+ [SheetsRenderService, { useClass: mockSheetsRenderService }],
[SheetSkeletonManagerService],
[AutoFillController],
- [SheetsRenderService, { useClass: mockSheetsRenderService }],
+ [AutoFillUIController],
]);
univer = testBed.univer;
get = testBed.get;
@@ -307,7 +307,7 @@ describe('Test auto fill rules in controller', () => {
const newTheme = set(theme, 'black', '#35322b');
themeService.setTheme(newTheme);
- autoFillController = get(AutoFillController);
+ autoFillController = get(AutoFillUIController);
selectionManagerService = get(SheetsSelectionsService);
commandService.registerCommand(SetRangeValuesMutation);
commandService.registerCommand(SetSelectionsOperation);
@@ -785,7 +785,7 @@ describe('Test auto fill rules in controller', () => {
vt: 2,
});
- commandService.executeCommand(RefillCommand.id, { type: APPLY_TYPE.NO_FORMAT });
+ commandService.executeCommand(RefillCommand.id, { type: AUTO_FILL_APPLY_TYPE.NO_FORMAT });
expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 4)?.v).toBe(6);
const styles_refill = getStyles(14, 4, 14, 4);
diff --git a/packages/sheets-ui/src/controllers/auto-fill-ui.controller.ts b/packages/sheets-ui/src/controllers/auto-fill-ui.controller.ts
new file mode 100644
index 0000000000..6542a543f2
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/auto-fill-ui.controller.ts
@@ -0,0 +1,278 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo, IExecutionOptions, IMutationCommonParams, IRange, Nullable, UnitModel, Workbook } from '@univerjs/core';
+import type { IAutoFillLocation, IRemoveSheetMutationParams } from '@univerjs/sheets';
+import {
+ Disposable,
+ DisposableCollection,
+ ICommandService,
+ Inject,
+ IUniverInstanceService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DeviceInputEventType, getCurrentTypeOfRenderer, IRenderManagerService } from '@univerjs/engine-render';
+import {
+ AUTO_FILL_HOOK_TYPE,
+ AutoClearContentCommand,
+ AutoFillCommand,
+ AutoFillController,
+ IAutoFillService,
+ InsertColMutation,
+ InsertRowMutation,
+ MoveColsMutation,
+ MoveRangeMutation,
+ MoveRowsMutation,
+ RefillCommand,
+ RemoveColMutation,
+ RemoveRowMutation,
+ RemoveSheetMutation,
+ SetRangeValuesCommand,
+ SetRangeValuesMutation,
+ SetSelectionsOperation,
+ SetWorksheetActiveOperation,
+ SetWorksheetColWidthMutation,
+ SetWorksheetRowHeightMutation,
+} from '@univerjs/sheets';
+import { SetCellEditVisibleOperation } from '../commands/operations/cell-edit.operation';
+import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';
+import { IEditorBridgeService } from '../services/editor-bridge.service';
+import { ISheetSelectionRenderService } from '../services/selection/base-selection-render.service';
+import { SheetsRenderService } from '../services/sheets-render.service';
+
+export class AutoFillUIController extends Disposable {
+ private _currentLocation: Nullable<IAutoFillLocation> = null;
+
+ constructor(
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IAutoFillService private readonly _autoFillService: IAutoFillService,
+ @Inject(AutoFillController) private _autoFillController: AutoFillController,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @Inject(SheetsRenderService) private _sheetsRenderService: SheetsRenderService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init() {
+ this._initDefaultHook();
+ this._initSelectionControlFillChanged();
+ this._initQuitListener();
+ this._initSkeletonChange();
+ }
+
+ private _initSkeletonChange() {
+ this.disposeWithMe(this._sheetsRenderService.registerSkeletonChangingMutations(AutoFillCommand.id));
+ }
+
+ private _initDefaultHook() {
+ this.disposeWithMe(this._autoFillService.addHook({
+ id: 'default-ui',
+ type: AUTO_FILL_HOOK_TYPE.DEFAULT,
+ priority: 0,
+ onBeforeFillData: (location: IAutoFillLocation) => {
+ this._currentLocation = location;
+ },
+ }));
+ }
+
+ private _initQuitListener() {
+ const quitCommands = [
+ SetCellEditVisibleOperation.id,
+ AutoClearContentCommand.id,
+ SetRangeValuesCommand.id,
+ SetZoomRatioOperation.id,
+ SetWorksheetActiveOperation.id,
+ MoveRangeMutation.id,
+ RemoveRowMutation.id,
+ RemoveColMutation.id,
+ InsertRowMutation.id,
+ InsertColMutation.id,
+ MoveRowsMutation.id,
+ MoveColsMutation.id,
+ SetWorksheetColWidthMutation.id,
+ SetWorksheetRowHeightMutation.id,
+ SetRangeValuesMutation.id,
+ ];
+
+ this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {
+ const fromCollab = options?.fromCollab;
+ const fromSync = options?.fromSync;
+ const fromFormula = options?.fromFormula;
+ if (quitCommands.includes(command.id)
+ && !fromCollab
+ && !fromSync
+ && !fromFormula
+ && (command.params as IMutationCommonParams).trigger !== AutoFillCommand.id
+ && (command.params as IMutationCommonParams).trigger !== RefillCommand.id
+ ) {
+ this._quit();
+ }
+ if (command.id === RemoveSheetMutation.id) {
+ if ((command.params as IRemoveSheetMutationParams).unitId === this._currentLocation?.unitId &&
+ (command.params as IRemoveSheetMutationParams).subUnitId === this._currentLocation?.subUnitId) {
+ this._quit();
+ }
+ }
+ }));
+ this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe((unit: UnitModel) => {
+ if (unit.getUnitId() === this._currentLocation?.unitId) {
+ this._quit();
+ }
+ }));
+ }
+
+ private _quit() {
+ this._currentLocation = null;
+ this._autoFillController.quit();
+ this._autoFillService.setShowMenu(false);
+ }
+
+ private _initSelectionControlFillChanged() {
+ const disposableCollection = new DisposableCollection();
+ const updateListener = () => {
+ // Each range change requires re-listening.
+ disposableCollection.dispose();
+
+ const currentRenderer = getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET, this._univerInstanceService, this._renderManagerService);
+ if (!currentRenderer) return;
+
+ const selectionRenderService = currentRenderer.with(ISheetSelectionRenderService);
+ const selectionControls = selectionRenderService.getSelectionControls();
+ selectionControls.forEach((controlSelection) => {
+ disposableCollection.add(controlSelection.selectionFilled$.subscribe((filled) => {
+ if (
+ filled == null ||
+ filled.startColumn === -1 ||
+ filled.startRow === -1 ||
+ filled.endColumn === -1 ||
+ filled.endRow === -1
+ ) {
+ return;
+ }
+ const source: IRange = {
+ startColumn: controlSelection.model.startColumn,
+ endColumn: controlSelection.model.endColumn,
+ startRow: controlSelection.model.startRow,
+ endRow: controlSelection.model.endRow,
+ };
+ const selection: IRange = {
+ startColumn: filled.startColumn,
+ endColumn: filled.endColumn,
+ startRow: filled.startRow,
+ endRow: filled.endRow,
+ };
+
+ this._commandService.executeCommand(AutoFillCommand.id, { sourceRange: source, targetRange: selection });
+ }));
+
+ // double click to fill range, range length will align to left or right column.
+ // fill results will be as same as drag operation
+ disposableCollection.add(controlSelection.fillControl.onDblclick$.subscribeEvent(() => {
+ const source = {
+ startColumn: controlSelection.model.startColumn,
+ endColumn: controlSelection.model.endColumn,
+ startRow: controlSelection.model.startRow,
+ endRow: controlSelection.model.endRow,
+ };
+ this._handleDbClickFill(source);
+ }));
+
+ disposableCollection.add(controlSelection.fillControl.onPointerDown$.subscribeEvent(() => {
+ const visibleState = this._editorBridgeService.isVisible();
+ if (visibleState.visible) {
+ this._commandService.syncExecuteCommand(
+ SetCellEditVisibleOperation.id,
+ {
+ visible: false,
+ eventType: DeviceInputEventType.PointerDown,
+ unitId: currentRenderer.unitId,
+ }
+ );
+ }
+ }));
+ });
+ };
+
+ updateListener();
+
+ // Should subscribe current current renderer change as well.
+ // TODO@yuhongz: this seems not ideal. This should be an `IRenderModule` for running with multiple renderers?
+ this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id === SetSelectionsOperation.id) {
+ updateListener();
+ }
+ }));
+
+ this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET)
+ .subscribe(() => updateListener()));
+ }
+
+ 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._commandService.executeCommand(AutoFillCommand.id, { sourceRange: source, targetRange: selection });
+ }
+
+ private _detectFillRange(source: IRange) {
+ const { startRow, endRow, startColumn, endColumn } = source;
+ const worksheet = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();
+ if (!worksheet) {
+ return source;
+ }
+ const matrix = worksheet.getCellMatrix();
+ const maxRow = worksheet.getMaxRows();
+ const maxColumn = worksheet.getMaxColumns();
+ let detectEndRow = endRow + 1;
+ // left column first, or consider right column.
+ if (startColumn > 0 && matrix.getValue(detectEndRow, startColumn - 1)?.v != null) {
+ while (matrix.getValue(detectEndRow + 1, startColumn - 1)?.v != null && detectEndRow < maxRow) {
+ detectEndRow += 1;
+ }
+ } else if (endColumn < maxColumn - 1 && matrix.getValue(detectEndRow, endColumn + 1)?.v != null) {
+ while (matrix.getValue(detectEndRow + 1, endColumn + 1)?.v != null && detectEndRow < maxRow) {
+ detectEndRow += 1;
+ }
+ } else {
+ detectEndRow = endRow;
+ }
+
+ // If the fill range contains data, stop filling at the first row of data.
+ 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,
+ };
+ }
+}
diff --git a/packages/sheets-ui/src/controllers/auto-height.controller.ts b/packages/sheets-ui/src/controllers/auto-height.controller.ts
index 917e5acc9d..b14bac4150 100644
--- a/packages/sheets-ui/src/controllers/auto-height.controller.ts
+++ b/packages/sheets-ui/src/controllers/auto-height.controller.ts
@@ -30,8 +30,6 @@ import {
} from '@univerjs/sheets';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
-export const AFFECT_LAYOUT_STYLES = ['ff', 'fs', 'tr', 'tb'];
-
interface IAutoHeightParams {
cellHeights?: ObjectMatrix<number>;
autoHeightRanges?: IRange[];
diff --git a/packages/sheets-ui/src/controllers/auto-width.controller.ts b/packages/sheets-ui/src/controllers/auto-width.controller.ts
index 8bb53f5ebb..9723bfbe9b 100644
--- a/packages/sheets-ui/src/controllers/auto-width.controller.ts
+++ b/packages/sheets-ui/src/controllers/auto-width.controller.ts
@@ -28,8 +28,6 @@ import {
} from '@univerjs/sheets';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
-export const AFFECT_LAYOUT_STYLES = ['ff', 'fs', 'tr', 'tb'];
-
export const createAutoColWidthUndoMutationsByRedos = (
params: ISetWorksheetColWidthMutationParams,
worksheet: Worksheet
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index 0291046909..20952f5a3b 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -19,13 +19,13 @@
import type { IAccessor, IBorderData, ICellData, ICustomRange, IDocumentBody, IMutationInfo, IParagraph, IRange, IStyleData, Nullable } from '@univerjs/core';
import type {
IAddWorksheetMergeMutationParams,
+ IDiscreteRange,
IMoveRangeMutationParams,
IRemoveWorksheetMergeMutationParams,
ISetRangeValuesMutationParams,
ISetSelectionsOperationParams,
} from '@univerjs/sheets';
import type { ICellDataWithSpanInfo, ICopyPastePayload, ISheetDiscreteRangeLocation } from '../../services/clipboard/type';
-import type { IDiscreteRange } from '../utils/range-tools';
import {
cellToRange,
CellValueType,
@@ -48,6 +48,7 @@ import { DEFAULT_PADDING_DATA } from '@univerjs/engine-render';
import {
AddMergeUndoMutationFactory,
AddWorksheetMergeMutation,
+ discreteRangeToRange,
getAddMergeMutationRangeByType,
getPrimaryForRange,
getSheetCommandTarget,
@@ -63,7 +64,7 @@ import {
} from '@univerjs/sheets';
import { COPY_TYPE } from '../../services/clipboard/type';
import { isRichText } from '../editor/editing.render-controller';
-import { discreteRangeToRange, virtualizeDiscreteRanges } from '../utils/range-tools';
+import { virtualizeDiscreteRanges } from '../utils/range-tools';
// if special paste need append mutations instead of replace the default, it can use this function to generate default mutations.
/**
diff --git a/packages/sheets-ui/src/controllers/mobile/mobile-sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/mobile/mobile-sheet-ui.controller.ts
index d5fb2669c5..e821a7a96e 100644
--- a/packages/sheets-ui/src/controllers/mobile/mobile-sheet-ui.controller.ts
+++ b/packages/sheets-ui/src/controllers/mobile/mobile-sheet-ui.controller.ts
@@ -35,7 +35,6 @@ import {
IShortcutService,
IUIPartsService,
} from '@univerjs/ui';
-import { AutoClearContentCommand, AutoFillCommand } from '../../commands/commands/auto-fill.command';
import { DeleteRangeMoveLeftConfirmCommand } from '../../commands/commands/delete-range-move-left-confirm.command';
import { DeleteRangeMoveUpConfirmCommand } from '../../commands/commands/delete-range-move-up-confirm.command';
import { SetColumnHeaderHeightCommand, SetRowHeaderWidthCommand } from '../../commands/commands/headersize-changed.command';
@@ -55,7 +54,6 @@ import {
import { InsertRangeMoveDownConfirmCommand } from '../../commands/commands/insert-range-move-down-confirm.command';
import { InsertRangeMoveRightConfirmCommand } from '../../commands/commands/insert-range-move-right-confirm.command';
import { AddRangeProtectionFromContextMenuCommand, AddRangeProtectionFromSheetBarCommand, AddRangeProtectionFromToolbarCommand, DeleteRangeProtectionFromContextMenuCommand, SetRangeProtectionFromContextMenuCommand, ViewSheetPermissionFromContextMenuCommand, ViewSheetPermissionFromSheetBarCommand } from '../../commands/commands/range-protection.command';
-import { RefillCommand } from '../../commands/commands/refill.command';
import { RemoveColConfirmCommand, RemoveRowConfirmCommand } from '../../commands/commands/remove-row-col-confirm.command';
import { RemoveSheetConfirmCommand } from '../../commands/commands/remove-sheet-confirm.command';
import {
@@ -249,14 +247,11 @@ export class SheetUIMobileController extends Disposable {
SetZoomRatioCommand,
SetZoomRatioOperation,
ShowMenuListCommand,
- RefillCommand,
InsertRangeMoveDownConfirmCommand,
DeleteRangeMoveUpConfirmCommand,
InsertRangeMoveRightConfirmCommand,
DeleteRangeMoveLeftConfirmCommand,
SidebarDefinedNameOperation,
- AutoFillCommand,
- AutoClearContentCommand,
// permission
SheetPermissionOpenPanelOperation,
diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-check-ui.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-check-ui.controller.ts
index f87fa84b83..a87d867767 100644
--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-check-ui.controller.ts
+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-check-ui.controller.ts
@@ -17,27 +17,24 @@
/* eslint-disable complexity */
/* eslint-disable max-lines-per-function */
-import type { ICellDataForSheetInterceptor, ICommandInfo, IRange, Workbook } from '@univerjs/core';
+import type { ICommandInfo, IRange, Workbook } from '@univerjs/core';
+import type { UnitAction } from '@univerjs/protocol';
import type { IMoveColsCommandParams, IMoveRangeCommandParams, IMoveRowsCommandParams, ISetRangeValuesCommandParams, ISetSpecificRowsVisibleCommandParams } from '@univerjs/sheets';
-import type { IAutoFillCommandParams } from '../../commands/commands/auto-fill.command';
import type { ISheetPasteParams } from '../../commands/commands/clipboard.command';
import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
-import { Disposable, DisposableCollection, FOCUSING_COMMENT_EDITOR, FOCUSING_EDITOR_STANDALONE, ICommandService, IContextService, Inject, IPermissionService, IUniverInstanceService, LocaleService, Rectangle, UniverInstanceType } from '@univerjs/core';
+import { Disposable, DisposableCollection, FOCUSING_COMMENT_EDITOR, FOCUSING_EDITOR_STANDALONE, ICommandService, IContextService, Inject, IPermissionService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
import { IMEInputCommand, InsertCommand } from '@univerjs/docs-ui';
-import { UnitAction } from '@univerjs/protocol';
-import { getSheetCommandTarget, RangeProtectionPermissionEditPoint, RangeProtectionPermissionViewPoint, RangeProtectionRuleModel, SetBackgroundColorCommand, SheetPermissionCheckController, WorkbookCopyPermission, WorkbookEditablePermission, WorksheetCopyPermission, WorksheetEditPermission, WorksheetSetCellStylePermission, WorksheetSetCellValuePermission, WorksheetSetColumnStylePermission } from '@univerjs/sheets';
+import { RangeProtectionPermissionEditPoint, RangeProtectionPermissionViewPoint, RangeProtectionRuleModel, SetBackgroundColorCommand, SheetPermissionCheckController, WorkbookCopyPermission, WorkbookEditablePermission, WorksheetCopyPermission, WorksheetEditPermission, WorksheetSetCellStylePermission, WorksheetSetCellValuePermission, WorksheetSetColumnStylePermission } from '@univerjs/sheets';
import { IDialogService } from '@univerjs/ui';
-import { AutoFillCommand } from '../../commands/commands/auto-fill.command';
import { SheetCopyCommand, SheetCutCommand, SheetPasteColWidthCommand, SheetPasteShortKeyCommand } from '../../commands/commands/clipboard.command';
import { SetRangeBoldCommand, SetRangeItalicCommand, SetRangeStrickThroughCommand, SetRangeUnderlineCommand } from '../../commands/commands/inline-format.command';
import { ApplyFormatPainterCommand } from '../../commands/commands/set-format-painter.command';
import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';
-import { IAutoFillService } from '../../services/auto-fill/auto-fill.service';
import { PREDEFINED_HOOK_NAME_PASTE } from '../../services/clipboard/clipboard.service';
import { UNIVER_SHEET_PERMISSION_ALERT_DIALOG, UNIVER_SHEET_PERMISSION_ALERT_DIALOG_ID } from '../../views/permission/error-msg-dialog/interface';
type ICellPermission = Record<UnitAction, boolean> & { ruleId?: string; ranges?: IRange[] };
-type ICheckPermissionCommandParams = IEditorBridgeServiceVisibleParam | IMoveRowsCommandParams | IMoveColsCommandParams | IMoveRangeCommandParams | ISetRangeValuesCommandParams | ISheetPasteParams | ISetSpecificRowsVisibleCommandParams | IAutoFillCommandParams;
+type ICheckPermissionCommandParams = IEditorBridgeServiceVisibleParam | IMoveRowsCommandParams | IMoveColsCommandParams | IMoveRangeCommandParams | ISetRangeValuesCommandParams | ISheetPasteParams | ISetSpecificRowsVisibleCommandParams;
export class SheetPermissionCheckUIController extends Disposable {
disposableCollection = new DisposableCollection();
@@ -48,7 +45,6 @@ export class SheetPermissionCheckUIController extends Disposable {
@IPermissionService private readonly _permissionService: IPermissionService,
@IDialogService private readonly _dialogService: IDialogService,
@Inject(RangeProtectionRuleModel) private _rangeProtectionRuleModel: RangeProtectionRuleModel,
- @IAutoFillService private _autoFillService: IAutoFillService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@IContextService private readonly _contextService: IContextService,
@@ -175,11 +171,6 @@ export class SheetPermissionCheckUIController extends Disposable {
}
break;
- case AutoFillCommand.id:
- permission = this._permissionCheckByAutoFillCommand(params as IAutoFillCommandParams);
- errorMsg = this._localeService.t('permission.dialog.autoFillErr');
- break;
-
default:
break;
}
@@ -222,38 +213,4 @@ export class SheetPermissionCheckUIController extends Disposable {
});
}
}
-
- private _permissionCheckByAutoFillCommand(params?: IAutoFillCommandParams) {
- if (!params) {
- return false;
- }
-
- const { targetRange } = params;
-
- const target = getSheetCommandTarget(this._univerInstanceService, params);
- if (!target) {
- return false;
- }
- const { worksheet, unitId, subUnitId } = target;
-
- const permissionLapRanges = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).reduce((p, c) => {
- return [...p, ...c.ranges];
- }, [] as IRange[]).filter((range) => {
- return Rectangle.intersects(range, targetRange);
- });
-
- const hasNotPermission = permissionLapRanges.some((range) => {
- for (let row = range.startRow; row <= range.endRow; row++) {
- for (let col = range.startColumn; col <= range.endColumn; col++) {
- const permission = (worksheet.getCell(row, col) as (ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }))?.selectionProtection?.[0];
- if (permission?.[UnitAction.Edit] === false) {
- return true;
- }
- }
- }
- return false;
- });
-
- return !hasNotPermission;
- }
}
diff --git a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
index 2a94e1c4e2..893b54a232 100644
--- a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
+++ b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
@@ -27,7 +27,6 @@ import {
SetUnderlineCommand,
} from '@univerjs/sheets';
import { BuiltInUIPart, ComponentManager, connectInjector, ILayoutService, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';
-import { AutoClearContentCommand, AutoFillCommand } from '../commands/commands/auto-fill.command';
import { DeleteRangeMoveLeftConfirmCommand } from '../commands/commands/delete-range-move-left-confirm.command';
import { DeleteRangeMoveUpConfirmCommand } from '../commands/commands/delete-range-move-up-confirm.command';
import { SetColumnHeaderHeightCommand, SetRowHeaderWidthCommand } from '../commands/commands/headersize-changed.command';
@@ -49,7 +48,6 @@ import {
import { InsertRangeMoveDownConfirmCommand } from '../commands/commands/insert-range-move-down-confirm.command';
import { InsertRangeMoveRightConfirmCommand } from '../commands/commands/insert-range-move-right-confirm.command';
import { AddRangeProtectionFromContextMenuCommand, AddRangeProtectionFromSheetBarCommand, AddRangeProtectionFromToolbarCommand, DeleteRangeProtectionFromContextMenuCommand, SetRangeProtectionFromContextMenuCommand, ViewSheetPermissionFromContextMenuCommand, ViewSheetPermissionFromSheetBarCommand } from '../commands/commands/range-protection.command';
-import { RefillCommand } from '../commands/commands/refill.command';
import { RemoveColConfirmCommand, RemoveRowConfirmCommand } from '../commands/commands/remove-row-col-confirm.command';
import { RemoveSheetConfirmCommand } from '../commands/commands/remove-sheet-confirm.command';
import {
@@ -244,14 +242,11 @@ export class SheetUIController extends Disposable {
SetZoomRatioCommand,
SetZoomRatioOperation,
ShowMenuListCommand,
- RefillCommand,
InsertRangeMoveDownConfirmCommand,
DeleteRangeMoveUpConfirmCommand,
InsertRangeMoveRightConfirmCommand,
DeleteRangeMoveLeftConfirmCommand,
SidebarDefinedNameOperation,
- AutoFillCommand,
- AutoClearContentCommand,
// permission
SheetPermissionOpenPanelOperation,
diff --git a/packages/sheets-ui/src/controllers/utils/range-tools.ts b/packages/sheets-ui/src/controllers/utils/range-tools.ts
index 93ac2c2e95..d461eda3f1 100644
--- a/packages/sheets-ui/src/controllers/utils/range-tools.ts
+++ b/packages/sheets-ui/src/controllers/utils/range-tools.ts
@@ -14,23 +14,8 @@
* limitations under the License.
*/
-import type { ICellData, IObjectMatrixPrimitiveType, IRange } from '@univerjs/core';
-import { ObjectMatrix } from '@univerjs/core';
-
-export interface IDiscreteRange {
- rows: number[];
- cols: number[];
-}
-
-export function discreteRangeToRange(discreteRange: IDiscreteRange): IRange {
- const { rows, cols } = discreteRange;
- return {
- startRow: rows[0],
- endRow: rows[rows.length - 1],
- startColumn: cols[0],
- endColumn: cols[cols.length - 1],
- };
-}
+import type { IRange } from '@univerjs/core';
+import type { IDiscreteRange } from '@univerjs/sheets';
export function virtualizeDiscreteRanges(ranges: IDiscreteRange[]): {
ranges: IRange[];
@@ -68,23 +53,3 @@ export function virtualizeDiscreteRanges(ranges: IDiscreteRange[]): {
),
};
}
-
-export function generateNullCellValueRowCol(range: IDiscreteRange[]): IObjectMatrixPrimitiveType<ICellData> {
- const cellValue = new ObjectMatrix<ICellData>();
- range.forEach((r) => {
- const { rows, cols } = r;
- rows.forEach((i) => {
- cols.forEach((j) => {
- cellValue.setValue(i, j, {
- v: null,
- p: null,
- f: null,
- si: null,
- custom: null,
- });
- });
- });
- });
-
- return cellValue.getData();
-}
diff --git a/packages/sheets-ui/src/facade/f-range.ts b/packages/sheets-ui/src/facade/f-range.ts
index 5535f91cf3..6d5f31b9df 100644
--- a/packages/sheets-ui/src/facade/f-range.ts
+++ b/packages/sheets-ui/src/facade/f-range.ts
@@ -16,11 +16,11 @@
import type { ICellWithCoord, IDisposable, ISelectionCell, Nullable } from '@univerjs/core';
import type { ISelectionStyle, ISheetLocation } from '@univerjs/sheets';
-import type { APPLY_TYPE, ICanvasPopup, ICellAlert, IDropdownParam } from '@univerjs/sheets-ui';
+import type { ICanvasPopup, ICellAlert, IDropdownParam } from '@univerjs/sheets-ui';
import type { ComponentType } from '@univerjs/ui';
-import { DisposableCollection, generateRandomId, ILogService, Rectangle, toDisposable } from '@univerjs/core';
+import { DisposableCollection, generateRandomId, ILogService, toDisposable } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { AutoFillCommand, CellAlertManagerService, IMarkSelectionService, ISheetCellDropdownManagerService, ISheetClipboardService, SheetCanvasPopManagerService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { CellAlertManagerService, IMarkSelectionService, ISheetCellDropdownManagerService, ISheetClipboardService, SheetCanvasPopManagerService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { FRange } from '@univerjs/sheets/facade';
import { ComponentManager } from '@univerjs/ui';
@@ -225,46 +225,6 @@ interface IFRangeSheetsUIMixin {
* ```
*/
showDropdown(param: IDropdownParam): IDisposable;
-
- /**
- * Fills the target range with data based on the data in the current range.
- * @param {FRange} targetRange - The range to be filled with data.
- * @param {APPLY_TYPE} [applyType] - The type of data fill to be applied.
- * @returns {Promise<boolean>} A promise that resolves to true if the fill operation was successful, false otherwise.
- * @example
- * ```ts
- * // Auto-fill the range D1:D10 based on the data in the range C1:C2
- * const fWorkbook = univerAPI.getActiveWorkbook();
- * const fWorksheet = fWorkbook.getActiveSheet();
- * const fRange = fWorksheet.getRange('A1:A4');
- *
- * // Auto-fill without specifying applyType (default behavior)
- * await fRange.autoFill(fWorksheet.getRange('A1:A20'))
- *
- * // Auto-fill with 'COPY' type
- * await fRange.autoFill(fWorksheet.getRange('A1:A20'), 'COPY')
- *
- * // Auto-fill with 'SERIES' type
- * await fRange.autoFill(fWorksheet.getRange('A1:A20'), 'SERIES')
- * ```
- *
- * ```ts
- * // Operate on a specific worksheet
- * const fWorkbook = univerAPI.getActiveWorkbook();
- * const fWorksheet = fWorkbook.getSheetBySheetId('sheetId');
- * const fRange = fWorksheet.getRange('A1:A4');
- *
- * // Auto-fill without specifying applyType (default behavior)
- * await fRange.autoFill(fWorksheet.getRange('A1:A20'))
- *
- * // Auto-fill with 'COPY' type
- * await fRange.autoFill(fWorksheet.getRange('A1:A20'), 'COPY')
- *
- * // Auto-fill with 'SERIES' type
- * await fRange.autoFill(fWorksheet.getRange('A1:A20'), 'SERIES')
- * ```
- */
- autoFill(targetRange: FRange, applyType?: APPLY_TYPE): Promise<boolean>;
}
class FRangeSheetsUIMixin extends FRange implements IFRangeSheetsUIMixin {
@@ -395,49 +355,6 @@ class FRangeSheetsUIMixin extends FRange implements IFRangeSheetsUIMixin {
const cellDropdownManagerService = this._injector.get(ISheetCellDropdownManagerService);
return cellDropdownManagerService.showDropdown(param);
}
-
- override async autoFill(targetRange: FRange, applyType?: APPLY_TYPE): Promise<boolean> {
- const _sourceRange = this.getRange();
- const _targetRange = targetRange.getRange();
-
- if (!Rectangle.contains(_targetRange, _sourceRange)) {
- throw new Error('AutoFill target range must contain source range');
- }
-
- const { startRow: sourceStartRow, startColumn: sourceStartColumn, endRow: sourceEndRow, endColumn: sourceEndColumn } = _sourceRange;
- const { startRow: targetStartRow, startColumn: targetStartColumn, endRow: targetEndRow, endColumn: targetEndColumn } = _targetRange;
-
- // If both row and column count are different, throw error
- if ((sourceEndRow - sourceStartRow) !== (targetEndRow - targetStartRow) && (sourceEndColumn - sourceStartColumn) !== (targetEndColumn - targetStartColumn)) {
- throw new Error('AutoFill can only fill in one direction');
- }
-
- // If the direction includes both left and right, throw error
- if (
- (sourceEndRow - sourceStartRow) === (targetEndRow - targetStartRow) &&
- sourceStartColumn !== targetStartColumn &&
- sourceEndColumn !== targetEndColumn
- ) {
- throw new Error('AutoFill can only fill in one direction');
- }
-
- // If the direction includes both up and down, throw error
- if (
- (sourceEndColumn - sourceStartColumn) === (targetEndColumn - targetStartColumn) &&
- sourceStartRow !== targetStartRow &&
- sourceEndRow !== targetEndRow
- ) {
- throw new Error('AutoFill can only fill in one direction');
- }
-
- return this._commandService.executeCommand(AutoFillCommand.id, {
- sourceRange: _sourceRange,
- targetRange: _targetRange,
- unitId: this.getUnitId(),
- subUnitId: this.getSheetId(),
- applyType,
- });
- }
}
FRange.extend(FRangeSheetsUIMixin);
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 0e1a77f0fa..c0855d2eec 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -17,7 +17,6 @@
import './global.css';
export { getEditorObject } from './basics/editor/get-editor-object';
-export { AutoClearContentCommand, AutoFillCommand } from './commands/commands/auto-fill.command';
export {
type ISheetPasteByShortKeyParams,
type ISheetPasteParams,
@@ -59,7 +58,6 @@ export {
ViewSheetPermissionFromContextMenuCommand,
ViewSheetPermissionFromSheetBarCommand,
} from './commands/commands/range-protection.command';
-export { RefillCommand } from './commands/commands/refill.command';
export { RemoveColConfirmCommand, RemoveRowConfirmCommand } from './commands/commands/remove-row-col-confirm.command';
export { RemoveSheetConfirmCommand } from './commands/commands/remove-sheet-confirm.command';
export { ApplyFormatPainterCommand, SetInfiniteFormatPainterCommand, SetOnceFormatPainterCommand } from './commands/commands/set-format-painter.command';
@@ -94,8 +92,8 @@ export { useActiveWorkbook, useActiveWorksheet, useWorkbooks } from './component
export { UNIVER_SHEET_PERMISSION_USER_PART } from './consts/permission';
export { SHEET_UI_PLUGIN_NAME } from './consts/plugin-name';
export { SheetsUIPart } from './consts/ui-name';
-export { AutoFillController } from './controllers/auto-fill.controller';
-export { AFFECT_LAYOUT_STYLES, AutoHeightController } from './controllers/auto-height.controller';
+export { AutoFillUIController } from './controllers/auto-fill-ui.controller';
+export { AutoHeightController } from './controllers/auto-height.controller';
export { AutoWidthController } from './controllers/auto-width.controller';
export { CellCustomRenderController } from './controllers/cell-custom-render.controller';
export { type IUniverSheetsUIConfig } from './controllers/config.schema';
@@ -118,16 +116,11 @@ export { SheetUIController } from './controllers/sheet-ui.controller';
export { whenFormulaEditorActivated, whenSheetEditorFocused } from './controllers/shortcuts/utils';
export { StatusBarController } from './controllers/status-bar.controller';
export { getCoordByCell, getCoordByOffset, getSheetObject, getTransformCoord } from './controllers/utils/component-tools';
-export type { IDiscreteRange } from './controllers/utils/range-tools';
-export { discreteRangeToRange, virtualizeDiscreteRanges } from './controllers/utils/range-tools';
+export { virtualizeDiscreteRanges } from './controllers/utils/range-tools';
export { matchedSelectionByRowColIndex as checkInHeaderRanges } from './controllers/utils/selections-tools';
export { useHighlightRange } from './hooks/use-highlight-range';
export { UniverSheetsMobileUIPlugin } from './mobile-plugin';
export { UniverSheetsUIPlugin } from './plugin';
-export { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';
-export { getAutoFillRepeatRange } from './services/auto-fill/tools';
-export { APPLY_TYPE, DATA_TYPE, type IAutoFillRule, type ICopyDataInTypeIndexInfo } from './services/auto-fill/type';
-export type { IAutoFillLocation, ICopyDataPiece, ISheetAutoFillHook } from './services/auto-fill/type';
export { type ICanvasPopup, SheetCanvasPopManagerService } from './services/canvas-pop-manager.service';
export { CellAlertManagerService, CellAlertType, type ICellAlert } from './services/cell-alert-manager.service';
export { type IDropdownParam, ISheetCellDropdownManagerService, SheetCellDropdownManagerService } from './services/cell-dropdown-manager.service';
diff --git a/packages/sheets-ui/src/mobile-plugin.ts b/packages/sheets-ui/src/mobile-plugin.ts
index 350a6533b8..06cd874f89 100644
--- a/packages/sheets-ui/src/mobile-plugin.ts
+++ b/packages/sheets-ui/src/mobile-plugin.ts
@@ -23,7 +23,7 @@ import { IRefSelectionsService, RefSelectionsService, UniverSheetsPlugin } from
import { ComponentManager, UI_PLUGIN_CONFIG_KEY, UniverMobileUIPlugin } from '@univerjs/ui';
import { filter } from 'rxjs/operators';
import { UNIVER_SHEET_PERMISSION_USER_PART } from './consts/permission';
-import { AutoFillController } from './controllers/auto-fill.controller';
+import { AutoFillUIController } from './controllers/auto-fill-ui.controller';
import { AutoHeightController } from './controllers/auto-height.controller';
import { AutoWidthController } from './controllers/auto-width.controller';
import { CellAlertRenderController } from './controllers/cell-alert.controller';
@@ -65,7 +65,6 @@ import { SheetRenderController } from './controllers/render-controllers/sheet.re
import { SheetSkeletonRenderController } from './controllers/render-controllers/skeleton.render-controller';
import { SheetsZoomRenderController } from './controllers/render-controllers/zoom.render-controller';
import { StatusBarController } from './controllers/status-bar.controller';
-import { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';
import { AutoHeightService } from './services/auto-height.service';
import { SheetCanvasPopManagerService } from './services/canvas-pop-manager.service';
import { CellAlertManagerService } from './services/cell-alert-manager.service';
@@ -147,7 +146,6 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
[ICellEditorManagerService, { useClass: CellEditorManagerService }],
[IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }],
[IRefSelectionsService, { useClass: RefSelectionsService }],
- [IAutoFillService, { useClass: AutoFillService }],
[SheetPrintInterceptorService],
[IStatusBarService, { useClass: StatusBarService }],
[IMarkSelectionService, { useClass: MarkSelectionService }],
@@ -167,7 +165,7 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
[SheetsRenderService],
[SheetUIMobileController],
[StatusBarController],
- [AutoFillController],
+ [AutoFillUIController],
[FormatPainterController],
[SheetsDefinedNameController],
[EditorDataSyncController],
@@ -224,7 +222,7 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
override onSteady(): void {
touchDependencies(this._injector, [
[FormatPainterController],
- [AutoFillController],
+ [AutoFillUIController],
[SheetPermissionInterceptorClipboardController],
]);
}
diff --git a/packages/sheets-ui/src/plugin.ts b/packages/sheets-ui/src/plugin.ts
index 11b0e515d6..b6a82c220e 100644
--- a/packages/sheets-ui/src/plugin.ts
+++ b/packages/sheets-ui/src/plugin.ts
@@ -23,7 +23,7 @@ import { IRefSelectionsService, RefSelectionsService, UniverSheetsPlugin } from
import { ComponentManager, UI_PLUGIN_CONFIG_KEY } from '@univerjs/ui';
import { filter } from 'rxjs/operators';
import { UNIVER_SHEET_PERMISSION_USER_PART } from './consts/permission';
-import { AutoFillController } from './controllers/auto-fill.controller';
+import { AutoFillUIController } from './controllers/auto-fill-ui.controller';
import { AutoHeightController } from './controllers/auto-height.controller';
import { AutoWidthController } from './controllers/auto-width.controller';
import { CellAlertRenderController } from './controllers/cell-alert.controller';
@@ -64,7 +64,6 @@ import { SheetSkeletonRenderController } from './controllers/render-controllers/
import { SheetsZoomRenderController } from './controllers/render-controllers/zoom.render-controller';
import { SheetUIController } from './controllers/sheet-ui.controller';
import { StatusBarController } from './controllers/status-bar.controller';
-import { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';
import { AutoHeightService } from './services/auto-height.service';
import { SheetCanvasPopManagerService } from './services/canvas-pop-manager.service';
import { CellAlertManagerService } from './services/cell-alert-manager.service';
@@ -150,7 +149,6 @@ export class UniverSheetsUIPlugin extends Plugin {
[ICellEditorManagerService, { useClass: CellEditorManagerService }],
[IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }],
[IRefSelectionsService, { useClass: RefSelectionsService }],
- [IAutoFillService, { useClass: AutoFillService }],
[SheetPrintInterceptorService],
[IStatusBarService, { useClass: StatusBarService }],
[IMarkSelectionService, { useClass: MarkSelectionService }],
@@ -170,7 +168,7 @@ export class UniverSheetsUIPlugin extends Plugin {
[SheetsRenderService],
[SheetUIController],
[StatusBarController],
- [AutoFillController],
+ [AutoFillUIController],
[FormatPainterController],
[SheetsDefinedNameController],
[EditorDataSyncController],
@@ -228,7 +226,7 @@ export class UniverSheetsUIPlugin extends Plugin {
override onSteady(): void {
touchDependencies(this._injector, [
[FormatPainterController],
- [AutoFillController],
+ [AutoFillUIController],
[SheetPermissionInterceptorClipboardController],
]);
}
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
index f308af0acc..df99af71a7 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
@@ -19,6 +19,7 @@ import type { IClipboardItem } from './mock-clipboard';
import { ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle, RedoCommand, UndoCommand } from '@univerjs/core';
import {
AddWorksheetMergeMutation,
+ discreteRangeToRange,
MoveRangeMutation,
RemoveWorksheetMergeMutation,
SetRangeValuesMutation,
@@ -29,7 +30,6 @@ import {
SheetsSelectionsService,
} from '@univerjs/sheets';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { discreteRangeToRange } from '../../../controllers/utils/range-tools';
import { ISheetClipboardService, PREDEFINED_HOOK_NAME_PASTE } from '../clipboard.service';
import { COPY_TYPE } from '../type';
import { clipboardTestBed } from './clipboard-test-bed';
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index 7d77fbee1f..50a043da84 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -24,9 +24,8 @@ import type {
Workbook,
Worksheet,
} from '@univerjs/core';
-import type { ISetRangeValuesMutationParams, ISetSelectionsOperationParams, ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';
+import type { IDiscreteRange, ISetRangeValuesMutationParams, ISetSelectionsOperationParams, ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';
import type { Observable } from 'rxjs';
-import type { IDiscreteRange } from '../../controllers/utils/range-tools';
import type {
ICellDataWithSpanInfo,
IClipboardPropertyItem,
diff --git a/packages/sheets-ui/src/services/clipboard/copy-content-cache.ts b/packages/sheets-ui/src/services/clipboard/copy-content-cache.ts
index 39c7ec4953..caa489bd02 100644
--- a/packages/sheets-ui/src/services/clipboard/copy-content-cache.ts
+++ b/packages/sheets-ui/src/services/clipboard/copy-content-cache.ts
@@ -15,7 +15,7 @@
*/
import type { Nullable, ObjectMatrix } from '@univerjs/core';
-import type { IDiscreteRange } from '../../controllers/utils/range-tools';
+import type { IDiscreteRange } from '@univerjs/sheets';
import type { COPY_TYPE, ICellDataWithSpanInfo } from './type';
import { generateRandomId, LRUMap } from '@univerjs/core';
import { BehaviorSubject } from 'rxjs';
diff --git a/packages/sheets-ui/src/services/clipboard/type.ts b/packages/sheets-ui/src/services/clipboard/type.ts
index 6953b98bc3..6102b85876 100644
--- a/packages/sheets-ui/src/services/clipboard/type.ts
+++ b/packages/sheets-ui/src/services/clipboard/type.ts
@@ -15,7 +15,7 @@
*/
import type { ICellData, ICellDataWithSpanAndDisplay, IDocumentData, IMutationInfo, IRange, ObjectMatrix } from '@univerjs/core';
-import type { IDiscreteRange } from '../../controllers/utils/range-tools';
+import type { IDiscreteRange } from '@univerjs/sheets';
import type { PREDEFINED_HOOK_NAME_COPY, PREDEFINED_HOOK_NAME_PASTE } from './clipboard.service';
export enum COPY_TYPE {
diff --git a/packages/sheets-ui/src/services/clipboard/usm-to-html/convertor.ts b/packages/sheets-ui/src/services/clipboard/usm-to-html/convertor.ts
index 62041135df..22c7d53eb8 100644
--- a/packages/sheets-ui/src/services/clipboard/usm-to-html/convertor.ts
+++ b/packages/sheets-ui/src/services/clipboard/usm-to-html/convertor.ts
@@ -15,8 +15,7 @@
*/
import type { ICellData, ObjectMatrix } from '@univerjs/core';
-
-import type { IDiscreteRange } from '../../../controllers/utils/range-tools';
+import type { IDiscreteRange } from '@univerjs/sheets';
import type { ICellDataWithSpanInfo, IClipboardPropertyItem, ISheetClipboardHook } from '../type';
/**
diff --git a/packages/sheets-ui/src/services/clipboard/utils.ts b/packages/sheets-ui/src/services/clipboard/utils.ts
index 3e287e190a..b4db54d9c3 100644
--- a/packages/sheets-ui/src/services/clipboard/utils.ts
+++ b/packages/sheets-ui/src/services/clipboard/utils.ts
@@ -15,8 +15,7 @@
*/
import type { ICellData, IMutationInfo, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';
-import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import type { IDiscreteRange } from '../../controllers/utils/range-tools';
+import type { IDiscreteRange, ISetRangeValuesMutationParams } from '@univerjs/sheets';
import { ObjectMatrix } from '@univerjs/core';
import { SetRangeValuesMutation } from '@univerjs/sheets';
diff --git a/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx b/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx
index 3f77e0885a..d74831366e 100644
--- a/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx
+++ b/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx
@@ -19,14 +19,12 @@ import { ICommandService, IUniverInstanceService, LocaleService, toDisposable }
import { borderClassName, clsx, DropdownMenu } from '@univerjs/design';
import { convertTransformToOffsetX, convertTransformToOffsetY, IRenderManagerService } from '@univerjs/engine-render';
import { AutofillDoubleIcon, MoreDownIcon } from '@univerjs/icons';
+import { AUTO_FILL_APPLY_TYPE, IAutoFillService, RefillCommand } from '@univerjs/sheets';
import { useDependency } from '@univerjs/ui';
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { RefillCommand } from '../../commands/commands/refill.command';
import { SetScrollOperation } from '../../commands/operations/scroll.operation';
import { useActiveWorkbook } from '../../components/hook';
import { getSheetObject } from '../../controllers/utils/component-tools';
-import { IAutoFillService } from '../../services/auto-fill/auto-fill.service';
-import { APPLY_TYPE } from '../../services/auto-fill/type';
import { ISheetSelectionRenderService } from '../../services/selection/base-selection-render.service';
import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';
@@ -37,7 +35,7 @@ export interface IAnchorPoint {
export interface IAutoFillPopupMenuItem {
label: string;
- value: APPLY_TYPE;
+ value: AUTO_FILL_APPLY_TYPE;
index: number;
disable: boolean;
}
@@ -56,7 +54,7 @@ export function AutoFillPopupMenu() {
const [menu, setMenu] = useState<IAutoFillPopupMenuItem[]>([]);
const [visible, setVisible] = useState(false);
const [anchor, setAnchor] = useState<IAnchorPoint>({ row: -1, col: -1 });
- const [selected, setSelected] = useState<APPLY_TYPE>(APPLY_TYPE.SERIES);
+ const [selected, setSelected] = useState<AUTO_FILL_APPLY_TYPE>(AUTO_FILL_APPLY_TYPE.SERIES);
const [isHovered, setHovered] = useState(false);
const workbook = useActiveWorkbook();
const { sheetSkeletonManagerService, selectionRenderService } = useMemo(() => {
diff --git a/packages/sheets-ui/src/views/clipboard/ClipboardPopupMenu.tsx b/packages/sheets-ui/src/views/clipboard/ClipboardPopupMenu.tsx
index 8560e8582c..4c38fad757 100644
--- a/packages/sheets-ui/src/views/clipboard/ClipboardPopupMenu.tsx
+++ b/packages/sheets-ui/src/views/clipboard/ClipboardPopupMenu.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDiscreteRange } from '../../controllers/utils/range-tools';
+import type { IDiscreteRange } from '@univerjs/sheets';
import type { IPasteHookKeyType } from '../../services/clipboard/type';
import { ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';
import { borderClassName, clsx, DropdownMenu } from '@univerjs/design';
diff --git a/packages/sheets/src/basics/utils.ts b/packages/sheets/src/basics/utils.ts
index 909cd5669e..fbd89f1c1c 100644
--- a/packages/sheets/src/basics/utils.ts
+++ b/packages/sheets/src/basics/utils.ts
@@ -142,6 +142,16 @@ export function getActiveWorksheet(instanceService: UniverInstanceService): [Nul
return [workbook, worksheet];
}
+export function discreteRangeToRange(discreteRange: IDiscreteRange): IRange {
+ const { rows, cols } = discreteRange;
+ return {
+ startRow: rows[0],
+ endRow: rows[rows.length - 1],
+ startColumn: cols[0],
+ endColumn: cols[cols.length - 1],
+ };
+}
+
export function rangeToDiscreteRange(range: IRange, accessor: IAccessor, unitId?: string, subUnitId?: string): IDiscreteRange | null {
const univerInstanceService = accessor.get(IUniverInstanceService);
const workbook = unitId
diff --git a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts b/packages/sheets/src/commands/commands/auto-fill.command.ts
similarity index 54%
rename from packages/sheets-ui/src/commands/commands/auto-fill.command.ts
rename to packages/sheets/src/commands/commands/auto-fill.command.ts
index 33a28383c8..4c913bff34 100644
--- a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
+++ b/packages/sheets/src/commands/commands/auto-fill.command.ts
@@ -15,34 +15,35 @@
*/
import type { IAccessor, ICommand, IRange } from '@univerjs/core';
-import type { ISetRangeValuesMutationParams, ISetSelectionsOperationParams } from '@univerjs/sheets';
-import type { APPLY_TYPE } from '../../services/auto-fill/type';
+import type { AUTO_FILL_APPLY_TYPE } from '../../services/auto-fill/type';
+import type { ISetRangeValuesMutationParams } from '../mutations/set-range-values.mutation';
import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecute } from '@univerjs/core';
-import { generateNullCellValue, getSheetCommandTarget, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SetSelectionsOperation, SheetInterceptorService } from '@univerjs/sheets';
+import { generateNullCellValue } from '../../basics/utils';
import { IAutoFillService } from '../../services/auto-fill/auto-fill.service';
+import { SheetsSelectionsService } from '../../services/selections';
+import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
+import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
+import { SetSelectionsOperation } from '../operations/selection.operation';
+import { getSheetCommandTarget } from './utils/target-util';
export interface IAutoFillCommandParams {
sourceRange: IRange;
targetRange: IRange;
unitId?: string; // if not provided, use current unitId
subUnitId?: string; // if not provided, use current subUnitId
- applyType?: APPLY_TYPE; // manual apply type
+ applyType?: AUTO_FILL_APPLY_TYPE; // manual apply type
}
export const AutoFillCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.auto-fill',
-
handler: async (accessor: IAccessor, params: IAutoFillCommandParams) => {
- const autoFillService = accessor.get(IAutoFillService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), params);
+ if (!target) return false;
+ const { unitId, subUnitId } = target;
const { sourceRange, targetRange, applyType } = params;
-
- const commandTarget = getSheetCommandTarget(univerInstanceService, params);
- if (!commandTarget) return false;
-
- const { subUnitId, unitId } = commandTarget;
+ const autoFillService = accessor.get(IAutoFillService);
return autoFillService.triggerAutoFill(unitId, subUnitId, sourceRange, targetRange, applyType);
},
};
@@ -55,17 +56,19 @@ export interface IAutoClearContentCommand {
export const AutoClearContentCommand: ICommand = {
id: 'sheet.command.auto-clear-content',
type: CommandType.COMMAND,
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params: IAutoClearContentCommand) => {
- const univerInstanceService = accessor.get(IUniverInstanceService);
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
+ if (!target) return false;
+
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
-
- const target = getSheetCommandTarget(univerInstanceService);
- if (!target) return false;
+ const selectionsService = accessor.get(SheetsSelectionsService);
const { unitId, subUnitId } = target;
const { clearRange, selectionRange } = params;
+ const { startColumn, startRow } = selectionRange;
const clearMutationParams: ISetRangeValuesMutationParams = {
subUnitId,
@@ -76,31 +79,53 @@ export const AutoClearContentCommand: ICommand = {
accessor,
clearMutationParams
);
- const { startColumn, startRow } = selectionRange;
- const param: ISetSelectionsOperationParams = {
- selections: [
- {
- primary: {
- startColumn,
- startRow,
- endColumn: startColumn,
- endRow: startRow,
- actualRow: startRow,
- actualColumn: startColumn,
- isMerged: false,
- isMergedMainCell: false,
- },
- range: {
- ...selectionRange,
- },
+
+ const redos = [
+ {
+ id: SetRangeValuesMutation.id,
+ params: clearMutationParams,
+ },
+ {
+ id: SetSelectionsOperation.id,
+ params: {
+ selections: [
+ {
+ primary: {
+ startColumn,
+ startRow,
+ endColumn: startColumn,
+ endRow: startRow,
+ actualRow: startRow,
+ actualColumn: startColumn,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ range: {
+ ...selectionRange,
+ },
+ },
+ ],
+ unitId,
+ subUnitId,
},
- ],
- unitId,
- subUnitId,
- };
- commandService.executeCommand(SetSelectionsOperation.id, param);
+ },
+ ];
+ const undos = [
+ {
+ id: SetRangeValuesMutation.id,
+ params: undoClearMutationParams,
+ },
+ {
+ id: SetSelectionsOperation.id,
+ params: {
+ selections: [selectionsService.getCurrentLastSelection()],
+ unitId,
+ subUnitId,
+ },
+ },
+ ];
- const result = commandService.syncExecuteCommand(SetRangeValuesMutation.id, clearMutationParams);
+ const result = sequenceExecute(redos, commandService);
if (result) {
const afterInterceptors = sheetInterceptorService.afterCommandExecute({
id: SetRangeValuesMutation.id,
@@ -108,12 +133,13 @@ export const AutoClearContentCommand: ICommand = {
});
sequenceExecute(afterInterceptors.redos, commandService);
+
undoRedoService.pushUndoRedo({
// If there are multiple mutations that form an encapsulated project, they must be encapsulated in the same undo redo element.
// Hooks can be used to hook the code of external controllers to add new actions.
unitID: unitId,
- undoMutations: [{ id: SetRangeValuesMutation.id, params: undoClearMutationParams }, ...afterInterceptors.undos],
- redoMutations: [{ id: SetRangeValuesMutation.id, params: clearMutationParams }, ...afterInterceptors.redos],
+ undoMutations: [...undos, ...afterInterceptors.undos],
+ redoMutations: [...redos, ...afterInterceptors.redos],
});
return true;
diff --git a/packages/sheets-ui/src/commands/commands/refill.command.ts b/packages/sheets/src/commands/commands/refill.command.ts
similarity index 88%
rename from packages/sheets-ui/src/commands/commands/refill.command.ts
rename to packages/sheets/src/commands/commands/refill.command.ts
index e3efbdde8d..dad884b858 100644
--- a/packages/sheets-ui/src/commands/commands/refill.command.ts
+++ b/packages/sheets/src/commands/commands/refill.command.ts
@@ -15,13 +15,12 @@
*/
import type { IAccessor, ICommand } from '@univerjs/core';
-import type { APPLY_TYPE } from '../../services/auto-fill/type';
-
+import type { AUTO_FILL_APPLY_TYPE } from '../../services/auto-fill/type';
import { CommandType } from '@univerjs/core';
import { IAutoFillService } from '../../services/auto-fill/auto-fill.service';
-interface IRefillCommandParams {
- type: APPLY_TYPE;
+export interface IRefillCommandParams {
+ type: AUTO_FILL_APPLY_TYPE;
}
export const RefillCommand: ICommand = {
diff --git a/packages/sheets-ui/src/controllers/auto-fill.controller.ts b/packages/sheets/src/controllers/auto-fill.controller.ts
similarity index 59%
rename from packages/sheets-ui/src/controllers/auto-fill.controller.ts
rename to packages/sheets/src/controllers/auto-fill.controller.ts
index aba02fa6f8..c3baeede11 100644
--- a/packages/sheets-ui/src/controllers/auto-fill.controller.ts
+++ b/packages/sheets/src/controllers/auto-fill.controller.ts
@@ -14,308 +14,107 @@
* limitations under the License.
*/
-import type { ICellData, ICommandInfo, IExecutionOptions, IMutationCommonParams, IMutationInfo, IRange, Nullable, UnitModel, Workbook } from '@univerjs/core';
-import type {
- IAddWorksheetMergeMutationParams,
- IRemoveSheetMutationParams,
- IRemoveWorksheetMergeMutationParams,
- ISetRangeValuesMutationParams,
-} from '@univerjs/sheets';
-import type {
- APPLY_FUNCTIONS,
- IAutoFillLocation,
- ICopyDataInType,
- ICopyDataPiece,
- IRuleConfirmedData,
- ISheetAutoFillHook,
-} from '../services/auto-fill/type';
+import type { ICellData, IMutationInfo, IRange, Nullable, Workbook } from '@univerjs/core';
+import type { IAddWorksheetMergeMutationParams, IRemoveWorksheetMergeMutationParams } from '../basics';
+import type { ISetRangeValuesMutationParams } from '../commands/mutations/set-range-values.mutation';
+import type { AUTO_FILL_APPLY_FUNCTIONS, IAutoFillCopyDataInType, IAutoFillCopyDataPiece, IAutoFillLocation, IAutoFillRuleConfirmedData } from '../services/auto-fill/type';
import {
Direction,
Disposable,
- DisposableCollection,
- ICommandService,
Inject,
Injector,
IUniverInstanceService,
ObjectMatrix,
Rectangle,
Tools,
- UniverInstanceType,
} from '@univerjs/core';
-
-import { DeviceInputEventType, getCurrentTypeOfRenderer, IRenderManagerService } from '@univerjs/engine-render';
-import {
- AddMergeUndoMutationFactory,
- AddWorksheetMergeMutation,
- getAddMergeMutationRangeByType,
- InsertColMutation,
- InsertRowMutation,
- MoveColsMutation,
- MoveRangeMutation,
- MoveRowsMutation,
- RemoveColMutation,
- RemoveMergeUndoMutationFactory,
- RemoveRowMutation,
- RemoveSheetMutation,
- RemoveWorksheetMergeMutation,
- SetRangeValuesCommand,
- SetRangeValuesMutation,
- SetRangeValuesUndoMutationFactory,
- SetSelectionsOperation,
- SetWorksheetActiveOperation,
- SetWorksheetColWidthMutation,
- SetWorksheetRowHeightMutation,
-} from '@univerjs/sheets';
-import { AutoClearContentCommand, AutoFillCommand } from '../commands/commands/auto-fill.command';
-import { RefillCommand } from '../commands/commands/refill.command';
-import { SetCellEditVisibleOperation } from '../commands/operations/cell-edit.operation';
-import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';
+import { discreteRangeToRange } from '../basics/utils';
+import { AddMergeUndoMutationFactory, AddWorksheetMergeMutation } from '../commands/mutations/add-worksheet-merge.mutation';
+import { RemoveMergeUndoMutationFactory, RemoveWorksheetMergeMutation } from '../commands/mutations/remove-worksheet-merge.mutation';
+import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../commands/mutations/set-range-values.mutation';
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 { APPLY_TYPE, AutoFillHookType, DATA_TYPE } from '../services/auto-fill/type';
-import { IEditorBridgeService } from '../services/editor-bridge.service';
-import { ISheetSelectionRenderService } from '../services/selection/base-selection-render.service';
-import { SheetsRenderService } from '../services/sheets-render.service';
-import { discreteRangeToRange, generateNullCellValueRowCol } from './utils/range-tools';
+import AutoFillRules from '../services/auto-fill/rules';
+import AutoFillTools from '../services/auto-fill/tools';
+import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_DATA_TYPE, AUTO_FILL_HOOK_TYPE } from '../services/auto-fill/type';
+import { getAddMergeMutationRangeByType } from './merge-cell.controller';
+
+const { getLenS, getDataIndex, fillCopy, fillCopyStyles, generateNullCellValueRowCol } = AutoFillTools;
+const { otherRule } = AutoFillRules;
export class AutoFillController extends Disposable {
private _beforeApplyData: Array<Array<Nullable<ICellData>>> = [];
- private _currentLocation: Nullable<IAutoFillLocation> = null;
+ private _copyData: IAutoFillCopyDataPiece[] = [];
- private _copyData: ICopyDataPiece[] = [];
- private _defaultHook: ISheetAutoFillHook;
constructor(
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @ICommandService private readonly _commandService: ICommandService,
@IAutoFillService private readonly _autoFillService: IAutoFillService,
- @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(Injector) private readonly _injector: Injector,
- @Inject(SheetsRenderService) private _sheetsRenderService: SheetsRenderService
+ @Inject(Injector) private readonly _injector: Injector
) {
super();
- this._defaultHook = {
- id: 'default',
- type: AutoFillHookType.Default,
- priority: 0,
- onBeforeFillData: (location: IAutoFillLocation, direction: Direction) => {
- return 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._initSelectionControlFillChanged();
- this._initQuitListener();
- this._initSkeletonChange();
- }
-
- private _initSkeletonChange() {
- this.disposeWithMe(this._sheetsRenderService.registerSkeletonChangingMutations(AutoFillCommand.id));
}
- private _initDefaultHook() {
- this.disposeWithMe(this._autoFillService.addHook(this._defaultHook));
- }
-
- private _initQuitListener() {
- const quitCommands = [
- SetCellEditVisibleOperation.id,
- AutoClearContentCommand.id,
- SetRangeValuesCommand.id,
- SetZoomRatioOperation.id,
- SetWorksheetActiveOperation.id,
- MoveRangeMutation.id,
- RemoveRowMutation.id,
- RemoveColMutation.id,
- InsertRowMutation.id,
- InsertColMutation.id,
- MoveRowsMutation.id,
- MoveColsMutation.id,
- SetWorksheetColWidthMutation.id,
- SetWorksheetRowHeightMutation.id,
- SetRangeValuesMutation.id,
- ];
-
- this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {
- const fromCollab = options?.fromCollab;
- const fromSync = options?.fromSync;
- const fromFormula = options?.fromFormula;
- if (quitCommands.includes(command.id)
- && !fromCollab
- && !fromSync
- && !fromFormula
- && (command.params as IMutationCommonParams).trigger !== AutoFillCommand.id
- && (command.params as IMutationCommonParams).trigger !== RefillCommand.id
- ) {
- this._quit();
- }
- if (command.id === RemoveSheetMutation.id) {
- if ((command.params as IRemoveSheetMutationParams).unitId === this._currentLocation?.unitId &&
- (command.params as IRemoveSheetMutationParams).subUnitId === this._currentLocation?.subUnitId) {
- this._quit();
- }
- }
- }));
- this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe((unit: UnitModel) => {
- if (unit.getUnitId() === this._currentLocation?.unitId) {
- this._quit();
- }
- }));
- }
-
- private _quit() {
- this._currentLocation = null;
+ quit() {
this._beforeApplyData = [];
this._copyData = [];
- this._autoFillService.setShowMenu(false);
}
- private _initSelectionControlFillChanged() {
- const disposableCollection = new DisposableCollection();
- const updateListener = () => {
- // Each range change requires re-listening.
- disposableCollection.dispose();
-
- const currentRenderer = getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET, this._univerInstanceService, this._renderManagerService);
- if (!currentRenderer) return;
-
- const selectionRenderService = currentRenderer.with(ISheetSelectionRenderService);
- const selectionControls = selectionRenderService.getSelectionControls();
- selectionControls.forEach((controlSelection) => {
- disposableCollection.add(controlSelection.selectionFilled$.subscribe((filled) => {
- if (
- filled == null ||
- filled.startColumn === -1 ||
- filled.startRow === -1 ||
- filled.endColumn === -1 ||
- filled.endRow === -1
- ) {
- return;
- }
- const source: IRange = {
- startColumn: controlSelection.model.startColumn,
- endColumn: controlSelection.model.endColumn,
- startRow: controlSelection.model.startRow,
- endRow: controlSelection.model.endRow,
- };
- const selection: IRange = {
- startColumn: filled.startColumn,
- endColumn: filled.endColumn,
- startRow: filled.startRow,
- endRow: filled.endRow,
- };
-
- this._commandService.executeCommand(AutoFillCommand.id, { sourceRange: source, targetRange: selection });
- }));
-
- // double click to fill range, range length will align to left or right column.
- // fill results will be as same as drag operation
- disposableCollection.add(controlSelection.fillControl.onDblclick$.subscribeEvent(() => {
- const source = {
- startColumn: controlSelection.model.startColumn,
- endColumn: controlSelection.model.endColumn,
- startRow: controlSelection.model.startRow,
- endRow: controlSelection.model.endRow,
- };
- this._handleDbClickFill(source);
- }));
-
- disposableCollection.add(controlSelection.fillControl.onPointerDown$.subscribeEvent(() => {
- const visibleState = this._editorBridgeService.isVisible();
- if (visibleState.visible) {
- this._commandService.syncExecuteCommand(
- SetCellEditVisibleOperation.id,
- {
- visible: false,
- eventType: DeviceInputEventType.PointerDown,
- unitId: currentRenderer.unitId,
- }
- );
- }
- }));
- });
- };
-
- updateListener();
-
- // Should subscribe current current renderer change as well.
- // TODO@yuhongz: this seems not ideal. This should be an `IRenderModule` for running with multiple renderers?
- this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (command.id === SetSelectionsOperation.id) {
- updateListener();
- }
+ private _initDefaultHook() {
+ this.disposeWithMe(this._autoFillService.addHook({
+ id: 'default',
+ type: AUTO_FILL_HOOK_TYPE.DEFAULT,
+ priority: 0,
+ onBeforeFillData: (location: IAutoFillLocation, direction: Direction) => {
+ return this._presetAndCacheData(location, direction);
+ },
+ onFillData: (location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE) => {
+ return this._fillData(location, direction, applyType);
+ },
}));
-
- this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET)
- .subscribe(() => updateListener()));
}
- 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._commandService.executeCommand(AutoFillCommand.id, { sourceRange: source, targetRange: selection });
- }
+ private _presetAndCacheData(location: IAutoFillLocation, direction: Direction) {
+ const { unitId, subUnitId, target } = location;
+ // cache original data of apply range
+ const worksheet = this._univerInstanceService.getUnit<Workbook>(unitId)?.getSheetBySheetId(subUnitId);
- private _detectFillRange(source: IRange) {
- const { startRow, endRow, startColumn, endColumn } = source;
- const worksheet = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();
if (!worksheet) {
- return source;
- }
- const matrix = worksheet.getCellMatrix();
- const maxRow = worksheet.getMaxRows();
- const maxColumn = worksheet.getMaxColumns();
- let detectEndRow = endRow + 1;
- // left column first, or consider right column.
- if (startColumn > 0 && matrix.getValue(detectEndRow, startColumn - 1)?.v != null) {
- while (matrix.getValue(detectEndRow + 1, startColumn - 1)?.v != null && detectEndRow < maxRow) {
- detectEndRow += 1;
- }
- } else if (endColumn < maxColumn - 1 && matrix.getValue(detectEndRow, endColumn + 1)?.v != null) {
- while (matrix.getValue(detectEndRow + 1, endColumn + 1)?.v != null && detectEndRow < maxRow) {
- detectEndRow += 1;
- }
- } else {
- detectEndRow = endRow;
+ throw new Error(`Worksheet not found for unitId: ${unitId}, subUnitId: ${subUnitId}`);
}
- // If the fill range contains data, stop filling at the first row of data.
- 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;
- }
- }
+ const currentCellDatas = worksheet.getCellMatrix();
+ // cache the original data in currentCellDatas in apply range for later use / refill
+ const applyData: Nullable<ICellData>[][] = [];
+ target.rows.forEach((i) => {
+ const row: Nullable<ICellData>[] = [];
+ target.cols.forEach((j) => {
+ row.push(Tools.deepClone(currentCellDatas.getValue(i, j)));
+ });
+ applyData.push(row);
+ });
+ this._beforeApplyData = applyData;
+ this._copyData = this._getCopyData(location, direction);
+ if (this._shouldDisableSeries(this._copyData)) {
+ this._autoFillService.setDisableApplyType(AUTO_FILL_APPLY_TYPE.SERIES, true);
+ return AUTO_FILL_APPLY_TYPE.COPY;
+ } else {
+ this._autoFillService.setDisableApplyType(AUTO_FILL_APPLY_TYPE.SERIES, false);
}
-
- return {
- startColumn,
- endColumn,
- startRow,
- endRow: detectEndRow,
- };
+ return this._getPreferredApplyType(this._copyData);
}
// calc apply data according to copy data and direction
private _getApplyData(
- copyDataPiece: ICopyDataPiece,
+ copyDataPiece: IAutoFillCopyDataPiece,
csLen: number,
asLen: number,
direction: Direction,
- applyType: APPLY_TYPE,
+ applyType: AUTO_FILL_APPLY_TYPE,
hasStyle: boolean = true,
location: IAutoFillLocation
) {
@@ -324,7 +123,7 @@ export class AutoFillController extends Disposable {
const rsd = asLen % csLen;
const rules = this._autoFillService.getRules();
- if (!hasStyle && applyType === APPLY_TYPE.ONLY_FORMAT) {
+ if (!hasStyle && applyType === AUTO_FILL_APPLY_TYPE.ONLY_FORMAT) {
console.error('ERROR: only format can not be applied when hasStyle is false');
return [];
}
@@ -381,40 +180,40 @@ export class AutoFillController extends Disposable {
}
private _applyFunctions(
- copySquad: ICopyDataInType,
+ copySquad: IAutoFillCopyDataInType,
len: number,
direction: Direction,
- applyType: APPLY_TYPE,
- customApplyFunctions: APPLY_FUNCTIONS,
- copyDataPiece: ICopyDataPiece,
+ applyType: AUTO_FILL_APPLY_TYPE,
+ customApplyFunctions: AUTO_FILL_APPLY_FUNCTIONS,
+ copyDataPiece: IAutoFillCopyDataPiece,
location: IAutoFillLocation
) {
const { data } = copySquad;
const isReverse = direction === Direction.UP || direction === Direction.LEFT;
// according to applyType, apply functions. if customApplyFunctions is provided, use it instead of default apply functions
- if (applyType === APPLY_TYPE.COPY) {
- const custom = customApplyFunctions?.[APPLY_TYPE.COPY];
+ if (applyType === AUTO_FILL_APPLY_TYPE.COPY) {
+ const custom = customApplyFunctions?.[AUTO_FILL_APPLY_TYPE.COPY];
if (custom) {
return custom(copySquad, len, direction, copyDataPiece, location);
}
isReverse && data.reverse();
return fillCopy(data, len);
}
- if (applyType === APPLY_TYPE.SERIES) {
- const custom = customApplyFunctions?.[APPLY_TYPE.SERIES];
+ if (applyType === AUTO_FILL_APPLY_TYPE.SERIES) {
+ const custom = customApplyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES];
if (custom) {
return custom(copySquad, len, direction, copyDataPiece);
}
isReverse && data.reverse();
// special rules, if not provide custom SERIES apply functions, will be applied as copy
- if (customApplyFunctions?.[APPLY_TYPE.COPY]) {
- return customApplyFunctions[APPLY_TYPE.COPY](copySquad, len, direction, copyDataPiece, location);
+ if (customApplyFunctions?.[AUTO_FILL_APPLY_TYPE.COPY]) {
+ return customApplyFunctions[AUTO_FILL_APPLY_TYPE.COPY](copySquad, len, direction, copyDataPiece, location);
}
return fillCopy(data, len);
}
- if (applyType === APPLY_TYPE.ONLY_FORMAT) {
- const custom = customApplyFunctions?.[APPLY_TYPE.ONLY_FORMAT];
+ if (applyType === AUTO_FILL_APPLY_TYPE.ONLY_FORMAT) {
+ const custom = customApplyFunctions?.[AUTO_FILL_APPLY_TYPE.ONLY_FORMAT];
if (custom) {
return custom(copySquad, len, direction, copyDataPiece);
}
@@ -432,7 +231,7 @@ export class AutoFillController extends Disposable {
const currentCellDatas = worksheet.getCellMatrix();
const rules = this._autoFillService.getRules();
- const copyData: ICopyDataPiece[] = [];
+ const copyData: IAutoFillCopyDataPiece[] = [];
const isVertical = direction === Direction.DOWN || direction === Direction.UP;
let aArray: number[];
let bArray: number[];
@@ -447,7 +246,7 @@ export class AutoFillController extends Disposable {
aArray.forEach((a) => {
// a copyDataPiece is an array of original cells in same column or row, depending on direction (horizontal or vertical)
const copyDataPiece = this._getEmptyCopyDataPiece();
- const prevData: IRuleConfirmedData = {
+ const prevData: IAutoFillRuleConfirmedData = {
type: undefined,
cellData: undefined,
};
@@ -490,7 +289,7 @@ export class AutoFillController extends Disposable {
}
private _getEmptyCopyDataPiece() {
- const copyDataPiece: ICopyDataPiece = {};
+ const copyDataPiece: IAutoFillCopyDataPiece = {};
this._autoFillService.getRules().forEach((r) => {
copyDataPiece[r.type] = [];
});
@@ -570,47 +369,16 @@ export class AutoFillController extends Disposable {
return applyMergeRanges;
}
- private _presetAndCacheData(location: IAutoFillLocation, direction: Direction) {
- const { unitId, subUnitId, target } = location;
- // cache original data of apply range
- const worksheet = this._univerInstanceService.getUnit<Workbook>(unitId)?.getSheetBySheetId(subUnitId);
-
- if (!worksheet) {
- throw new Error('No active sheet found');
- }
-
- const currentCellDatas = worksheet.getCellMatrix();
- // cache the original data in currentCellDatas in apply range for later use / refill
- const applyData: Nullable<ICellData>[][] = [];
- target.rows.forEach((i) => {
- const row: Nullable<ICellData>[] = [];
- target.cols.forEach((j) => {
- row.push(Tools.deepClone(currentCellDatas.getValue(i, j)));
- });
- applyData.push(row);
- });
- this._beforeApplyData = applyData;
- this._copyData = this._getCopyData(location, direction);
- this._currentLocation = location;
- if (this._shouldDisableSeries(this._copyData)) {
- this._autoFillService.setDisableApplyType(APPLY_TYPE.SERIES, true);
- return APPLY_TYPE.COPY;
- } else {
- this._autoFillService.setDisableApplyType(APPLY_TYPE.SERIES, false);
- }
- return this._getPreferredApplyType(this._copyData);
- }
-
// auto fill entry
- // eslint-disable-next-line max-lines-per-function
- private _fillData(location: IAutoFillLocation, direction: Direction, applyType: APPLY_TYPE) {
+ // eslint-disable-next-line max-lines-per-function, complexity
+ private _fillData(location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE) {
const undos: IMutationInfo[] = [];
const redos: IMutationInfo[] = [];
let hasStyle = true;
- if (applyType === APPLY_TYPE.NO_FORMAT) {
+ if (applyType === AUTO_FILL_APPLY_TYPE.NO_FORMAT) {
hasStyle = false;
- applyType = APPLY_TYPE.SERIES;
+ applyType = AUTO_FILL_APPLY_TYPE.SERIES;
}
const { source, target, unitId, subUnitId } = location;
@@ -698,7 +466,7 @@ export class AutoFillController extends Disposable {
});
}
- if (applyType === APPLY_TYPE.ONLY_FORMAT) {
+ if (applyType === AUTO_FILL_APPLY_TYPE.ONLY_FORMAT) {
applyDatas.forEach((row, rowIndex) => {
row.forEach((cellData, colIndex) => {
if (cellData) {
@@ -719,6 +487,7 @@ export class AutoFillController extends Disposable {
.getUniverSheetInstance(unitId)
?.getSheetBySheetId(subUnitId)
?.getMergeData();
+
if (mergeData) {
mergeData.forEach((merge) => {
if (Rectangle.intersects(merge, targetRange)) {
@@ -726,18 +495,19 @@ export class AutoFillController extends Disposable {
}
});
}
- const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {
- unitId,
- subUnitId,
- ranges: deleteMergeRanges,
- };
-
- const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = this._injector.invoke(
- RemoveMergeUndoMutationFactory,
- removeMergeMutationParams
- );
if (deleteMergeRanges.length) {
+ const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {
+ unitId,
+ subUnitId,
+ ranges: deleteMergeRanges,
+ };
+
+ const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = this._injector.invoke(
+ RemoveMergeUndoMutationFactory,
+ removeMergeMutationParams
+ );
+
redos.push({ id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams });
undos.unshift({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams });
}
@@ -812,28 +582,32 @@ export class AutoFillController extends Disposable {
};
}
- private _shouldDisableSeries(copyData: ICopyDataPiece[]) {
+ private _shouldDisableSeries(copyData: IAutoFillCopyDataPiece[]) {
// only formula or other type data, disable series
return copyData.every((copyDataPiece) =>
Object.keys(copyDataPiece).every((type) => (
- copyDataPiece[type as DATA_TYPE]?.length === 0
- || [DATA_TYPE.OTHER, DATA_TYPE.FORMULA].includes(type as DATA_TYPE)
+ copyDataPiece[type as AUTO_FILL_DATA_TYPE]?.length === 0
+ || [AUTO_FILL_DATA_TYPE.OTHER, AUTO_FILL_DATA_TYPE.FORMULA].includes(type as AUTO_FILL_DATA_TYPE)
)
)
);
}
- private _getPreferredApplyType(copyData: ICopyDataPiece[]) {
+ private _getPreferredApplyType(copyData: IAutoFillCopyDataPiece[]) {
// if all data is number and only one cell in piece, prefer copy
- const preferCopy = copyData.every((copyDataPiece) =>
- Object.keys(copyDataPiece).every((type) => (
- copyDataPiece[type as DATA_TYPE]?.length === 0
- || (copyDataPiece[type as DATA_TYPE]?.length === 1
- && copyDataPiece[type as DATA_TYPE][0].data.length === 1
- && DATA_TYPE.NUMBER === type as DATA_TYPE)
- )
- )
+ const preferCopy = copyData.every(
+ (copyDataPiece) =>
+ Object.keys(copyDataPiece).every(
+ (type) => (
+ copyDataPiece[type as AUTO_FILL_DATA_TYPE]?.length === 0 ||
+ (
+ copyDataPiece[type as AUTO_FILL_DATA_TYPE]?.length === 1 &&
+ copyDataPiece[type as AUTO_FILL_DATA_TYPE][0].data.length === 1 &&
+ AUTO_FILL_DATA_TYPE.NUMBER === type as AUTO_FILL_DATA_TYPE
+ )
+ )
+ )
);
- return preferCopy ? APPLY_TYPE.COPY : APPLY_TYPE.SERIES;
+ return preferCopy ? AUTO_FILL_APPLY_TYPE.COPY : AUTO_FILL_APPLY_TYPE.SERIES;
}
}
diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.ts
index f020fe4bcc..545cf9e4c2 100644
--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts
+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts
@@ -22,6 +22,7 @@ import { AddWorksheetMergeAllCommand, AddWorksheetMergeCommand, AddWorksheetMerg
import { AddWorksheetProtectionCommand } from '../commands/commands/add-worksheet-protection.command';
import { SetWorksheetRangeThemeStyleCommand } from '../commands/commands/add-worksheet-range-theme.command';
import { AppendRowCommand } from '../commands/commands/append-row.command';
+import { AutoClearContentCommand, AutoFillCommand } from '../commands/commands/auto-fill.command';
import { ClearSelectionAllCommand } from '../commands/commands/clear-selection-all.command';
import { ClearSelectionContentCommand } from '../commands/commands/clear-selection-content.command';
import { ClearSelectionFormatCommand } from '../commands/commands/clear-selection-format.command';
@@ -51,6 +52,7 @@ import {
import { InsertSheetCommand } from '../commands/commands/insert-sheet.command';
import { MoveRangeCommand } from '../commands/commands/move-range.command';
import { MoveColsCommand, MoveRowsCommand } from '../commands/commands/move-rows-cols.command';
+import { RefillCommand } from '../commands/commands/refill.command';
import { RegisterWorksheetRangeThemeStyleCommand } from '../commands/commands/register-range-theme.command';
import { RemoveDefinedNameCommand } from '../commands/commands/remove-defined-name.command';
import { RemoveColByRangeCommand, RemoveColCommand, RemoveRowByRangeCommand, RemoveRowCommand } from '../commands/commands/remove-row-col.command';
@@ -368,6 +370,10 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetRangeThemeMutation,
RemoveRangeThemeMutation,
+ AutoFillCommand,
+ AutoClearContentCommand,
+ RefillCommand,
+
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
}
diff --git a/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts b/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts
index e50815d0d7..6edc63c2d6 100644
--- a/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts
+++ b/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts
@@ -15,6 +15,7 @@
*/
import type { ICellData, ICellDataForSheetInterceptor, ICommandInfo, IObjectMatrixPrimitiveType, IPermissionTypes, IRange, Nullable, Workbook, WorkbookPermissionPointConstructor, Worksheet } from '@univerjs/core';
+import type { IAutoFillCommandParams } from '../../commands/commands/auto-fill.command';
import type { IClearSelectionContentCommandParams } from '../../commands/commands/clear-selection-content.command';
import type { IMoveRangeCommandParams } from '../../commands/commands/move-range.command';
import type { IMoveColsCommandParams, IMoveRowsCommandParams } from '../../commands/commands/move-rows-cols.command';
@@ -27,6 +28,7 @@ import { CustomCommandExecutionError, Disposable, DisposableCollection, ICommand
import { deserializeRangeWithSheet, deserializeRangeWithSheetWithCache, IDefinedNamesService, LexerTreeBuilder, operatorToken, sequenceNodeType } from '@univerjs/engine-formula';
import { UnitAction } from '@univerjs/protocol';
import { Subject } from 'rxjs';
+import { AutoFillCommand } from '../../commands/commands/auto-fill.command';
import { ClearSelectionContentCommand } from '../../commands/commands/clear-selection-content.command';
import { DeleteRangeMoveLeftCommand } from '../../commands/commands/delete-range-move-left.command';
import { DeleteRangeMoveUpCommand } from '../../commands/commands/delete-range-move-up.command';
@@ -53,7 +55,7 @@ import { SheetsSelectionsService } from '../../services/selections';
/* eslint-disable max-lines-per-function */
type ICellPermission = Record<UnitAction, boolean> & { ruleId?: string; ranges?: IRange[] };
-type ICheckPermissionCommandParams = IMoveRowsCommandParams | IMoveColsCommandParams | IMoveRangeCommandParams | ISetRangeValuesCommandParams | ISetSpecificRowsVisibleCommandParams;
+type ICheckPermissionCommandParams = IMoveRowsCommandParams | IMoveColsCommandParams | IMoveRangeCommandParams | ISetRangeValuesCommandParams | ISetSpecificRowsVisibleCommandParams | IAutoFillCommandParams;
export class SheetPermissionCheckController extends Disposable {
disposableCollection = new DisposableCollection();
@@ -223,6 +225,10 @@ export class SheetPermissionCheckController extends Disposable {
permission = this._permissionCheckWithInsertRangeMove('top');
errorMsg = this._localeService.t('permission.dialog.insertOrDeleteMoveRangeErr');
break;
+ case AutoFillCommand.id:
+ permission = this._permissionCheckByAutoFillCommand(params as IAutoFillCommandParams);
+ errorMsg = this._localeService.t('permission.dialog.autoFillErr');
+ break;
default:
break;
@@ -573,4 +579,38 @@ export class SheetPermissionCheckController extends Disposable {
}
return true;
}
+
+ private _permissionCheckByAutoFillCommand(params?: IAutoFillCommandParams) {
+ if (!params) {
+ return false;
+ }
+
+ const { targetRange } = params;
+
+ const target = getSheetCommandTarget(this._univerInstanceService, params);
+ if (!target) {
+ return false;
+ }
+ const { worksheet, unitId, subUnitId } = target;
+
+ const permissionLapRanges = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).reduce((p, c) => {
+ return [...p, ...c.ranges];
+ }, [] as IRange[]).filter((range) => {
+ return Rectangle.intersects(range, targetRange);
+ });
+
+ const hasNotPermission = permissionLapRanges.some((range) => {
+ for (let row = range.startRow; row <= range.endRow; row++) {
+ for (let col = range.startColumn; col <= range.endColumn; col++) {
+ const permission = (worksheet.getCell(row, col) as (ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }))?.selectionProtection?.[0];
+ if (permission?.[UnitAction.Edit] === false) {
+ return true;
+ }
+ }
+ }
+ return false;
+ });
+
+ return !hasNotPermission;
+ }
}
diff --git a/packages/sheets/src/facade/f-range.ts b/packages/sheets/src/facade/f-range.ts
index ed18f07775..78f4ed8347 100644
--- a/packages/sheets/src/facade/f-range.ts
+++ b/packages/sheets/src/facade/f-range.ts
@@ -16,6 +16,7 @@
import type { AbsoluteRefType, BorderStyleTypes, BorderType, CellValue, CustomData, ICellData, IColorStyle, IDocumentData, IObjectMatrixPrimitiveType, IRange, IStyleData, ITextDecoration, Nullable, Workbook, Worksheet } from '@univerjs/core';
import type {
+ AUTO_FILL_APPLY_TYPE,
IMergeCellsUtilOptions,
ISetBorderBasicCommandParams,
ISetHorizontalTextAlignCommandParams,
@@ -36,6 +37,7 @@ import { FBaseInitialable } from '@univerjs/core/facade';
import { FormulaDataModel, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';
import {
addMergeCellsUtil,
+ AutoFillCommand,
ClearSelectionAllCommand,
ClearSelectionContentCommand,
ClearSelectionFormatCommand,
@@ -2714,4 +2716,85 @@ export class FRange extends FBaseInitialable {
fWorksheet
);
}
+
+ /**
+ * Fills the target range with data based on the data in the current range.
+ * @param {FRange} targetRange - The range to be filled with data.
+ * @param {AUTO_FILL_APPLY_TYPE} [applyType] - The type of data fill to be applied.
+ * @returns {Promise<boolean>} A promise that resolves to true if the fill operation was successful, false otherwise.
+ * @example
+ * ```ts
+ * // Auto-fill the range D1:D10 based on the data in the range C1:C2
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:A4');
+ *
+ * // Auto-fill without specifying applyType (default behavior)
+ * await fRange.autoFill(fWorksheet.getRange('A1:A20'))
+ *
+ * // Auto-fill with 'COPY' type
+ * await fRange.autoFill(fWorksheet.getRange('A1:A20'), 'COPY')
+ *
+ * // Auto-fill with 'SERIES' type
+ * await fRange.autoFill(fWorksheet.getRange('A1:A20'), 'SERIES')
+ * ```
+ *
+ * ```ts
+ * // Operate on a specific worksheet
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getSheetBySheetId('sheetId');
+ * const fRange = fWorksheet.getRange('A1:A4');
+ *
+ * // Auto-fill without specifying applyType (default behavior)
+ * await fRange.autoFill(fWorksheet.getRange('A1:A20'))
+ *
+ * // Auto-fill with 'COPY' type
+ * await fRange.autoFill(fWorksheet.getRange('A1:A20'), 'COPY')
+ *
+ * // Auto-fill with 'SERIES' type
+ * await fRange.autoFill(fWorksheet.getRange('A1:A20'), 'SERIES')
+ * ```
+ */
+ autoFill(targetRange: FRange, applyType?: AUTO_FILL_APPLY_TYPE): Promise<boolean> {
+ const _sourceRange = this.getRange();
+ const _targetRange = targetRange.getRange();
+
+ if (!Rectangle.contains(_targetRange, _sourceRange)) {
+ throw new Error('AutoFill target range must contain source range');
+ }
+
+ const { startRow: sourceStartRow, startColumn: sourceStartColumn, endRow: sourceEndRow, endColumn: sourceEndColumn } = _sourceRange;
+ const { startRow: targetStartRow, startColumn: targetStartColumn, endRow: targetEndRow, endColumn: targetEndColumn } = _targetRange;
+
+ // If both row and column count are different, throw error
+ if ((sourceEndRow - sourceStartRow) !== (targetEndRow - targetStartRow) && (sourceEndColumn - sourceStartColumn) !== (targetEndColumn - targetStartColumn)) {
+ throw new Error('AutoFill can only fill in one direction');
+ }
+
+ // If the direction includes both left and right, throw error
+ if (
+ (sourceEndRow - sourceStartRow) === (targetEndRow - targetStartRow) &&
+ sourceStartColumn !== targetStartColumn &&
+ sourceEndColumn !== targetEndColumn
+ ) {
+ throw new Error('AutoFill can only fill in one direction');
+ }
+
+ // If the direction includes both up and down, throw error
+ if (
+ (sourceEndColumn - sourceStartColumn) === (targetEndColumn - targetStartColumn) &&
+ sourceStartRow !== targetStartRow &&
+ sourceEndRow !== targetEndRow
+ ) {
+ throw new Error('AutoFill can only fill in one direction');
+ }
+
+ return this._commandService.executeCommand(AutoFillCommand.id, {
+ sourceRange: _sourceRange,
+ targetRange: _targetRange,
+ unitId: this.getUnitId(),
+ subUnitId: this.getSheetId(),
+ applyType,
+ });
+ };
}
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index 386bc0258b..563f2bbb0c 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -30,6 +30,7 @@ export { expandToContinuousRange } from './basics/expand-range';
export {
type IAddWorksheetMergeMutationParams,
type IDeleteRangeMutationParams,
+ type IDiscreteRange,
type IInsertColMutationParams,
type IInsertRangeMutationParams,
type IInsertRowMutationParams,
@@ -39,7 +40,7 @@ export {
type IRemoveSheetMutationParams,
type IRemoveWorksheetMergeMutationParams,
type IWorksheetRangeThemeStyleMutationParams,
-} from './basics/interfaces/mutation-interface';
+} from './basics/interfaces';
export { createTopMatrixFromMatrix, createTopMatrixFromRanges, findAllRectangle, rangeMerge, RangeMergeUtil } from './basics/range-merge';
export {
convertPrimaryWithCoordToPrimary,
@@ -54,7 +55,7 @@ export {
} from './basics/selection';
export { SplitDelimiterEnum, splitRangeText } from './basics/split-range-text';
export { findFirstNonEmptyCell } from './basics/utils';
-export { generateNullCell, generateNullCellValue, getVisibleRanges, rangeToDiscreteRange } from './basics/utils';
+export { discreteRangeToRange, generateNullCell, generateNullCellValue, getVisibleRanges, rangeToDiscreteRange } from './basics/utils';
export { AddRangeProtectionCommand, type IAddRangeProtectionCommandParams } from './commands/commands/add-range-protection.command';
export {
addMergeCellsUtil,
@@ -69,6 +70,7 @@ export {
export { AddWorksheetProtectionCommand } from './commands/commands/add-worksheet-protection.command';
export { SetWorksheetRangeThemeStyleCommand } from './commands/commands/add-worksheet-range-theme.command';
export { AppendRowCommand, type IAppendRowCommandParams } from './commands/commands/append-row.command';
+export { AutoClearContentCommand, AutoFillCommand, type IAutoClearContentCommand, type IAutoFillCommandParams } from './commands/commands/auto-fill.command';
export { ClearSelectionAllCommand } from './commands/commands/clear-selection-all.command';
export { ClearSelectionContentCommand, type IClearSelectionContentCommandParams } from './commands/commands/clear-selection-content.command';
export { ClearSelectionFormatCommand } from './commands/commands/clear-selection-format.command';
@@ -106,11 +108,11 @@ export {
MoveColsCommand,
MoveRowsCommand,
} from './commands/commands/move-rows-cols.command';
+export { type IRefillCommandParams, RefillCommand } from './commands/commands/refill.command';
export { RegisterWorksheetRangeThemeStyleCommand } from './commands/commands/register-range-theme.command';
export type { IRegisterWorksheetRangeThemeStyleCommandParams } from './commands/commands/register-range-theme.command';
export { RemoveDefinedNameCommand } from './commands/commands/remove-defined-name.command';
export { type IRemoveColByRangeCommandParams, type IRemoveRowByRangeCommandParams, type IRemoveRowColCommandInterceptParams, type IRemoveRowColCommandParams, RemoveColByRangeCommand, RemoveColCommand, RemoveRowByRangeCommand, RemoveRowCommand } from './commands/commands/remove-row-col.command';
-
export { type IRemoveSheetCommandParams, RemoveSheetCommand } from './commands/commands/remove-sheet.command';
export { RemoveWorksheetMergeCommand } from './commands/commands/remove-worksheet-merge.command';
export { type IReorderRangeCommandParams, ReorderRangeCommand } from './commands/commands/reorder-range.command';
@@ -148,6 +150,7 @@ export {
SetSpecificRowsVisibleCommand,
} from './commands/commands/set-row-visible.command';
export {
+ AFFECT_LAYOUT_STYLES,
type ISetColorCommandParams,
type ISetFontFamilyCommandParams,
type ISetFontSizeCommandParams,
@@ -286,7 +289,6 @@ export {
SetRowVisibleMutation,
} from './commands/mutations/set-row-visible.mutation';
export { type ISetTabColorMutationParams, SetTabColorMutation } from './commands/mutations/set-tab-color.mutation';
-
export { type ISetWorkbookNameMutationParams, SetWorkbookNameMutation } from './commands/mutations/set-workbook-name.mutation';
export {
type ISetWorksheetColWidthMutationParams,
@@ -326,6 +328,7 @@ export { getInsertRangeMutations, getRemoveRangeMutations } from './commands/uti
export { handleInsertRangeMutation } from './commands/utils/handle-range-mutation';
export { type ISheetCommandSharedParams } from './commands/utils/interface';
export { getSelectionsService } from './commands/utils/selection-command-util';
+export { AutoFillController } from './controllers/auto-fill.controller';
export { defaultLargeSheetOperationConfig, type ILargeSheetOperationConfig, type IUniverSheetsConfig, SHEETS_PLUGIN_CONFIG_KEY } from './controllers/config.schema';
export { MAX_CELL_PER_SHEET_KEY } from './controllers/config/config';
export { DefinedNameDataController } from './controllers/defined-name-data.controller';
@@ -344,6 +347,22 @@ export type { IRangeThemeStyleJSON } from './model/range-theme-util';
export { RangeThemeStyle } from './model/range-theme-util';
export type { IRangeThemeStyleItem } from './model/range-theme-util';
export { UniverSheetsPlugin } from './plugin';
+export { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';
+export { default as AutoFillRules } from './services/auto-fill/rules';
+export { default as AutoFillTools } from './services/auto-fill/tools';
+export {
+ type AUTO_FILL_APPLY_FUNCTIONS,
+ AUTO_FILL_APPLY_TYPE,
+ AUTO_FILL_DATA_TYPE,
+ AUTO_FILL_HOOK_TYPE,
+ type IAutoFillCopyDataInType,
+ type IAutoFillCopyDataInTypeIndexInfo,
+ type IAutoFillCopyDataPiece,
+ type IAutoFillLocation,
+ type IAutoFillRule,
+ type IAutoFillRuleConfirmedData,
+ type ISheetAutoFillHook,
+} from './services/auto-fill/type';
export { BorderStyleManagerService, type IBorderInfo } from './services/border-style-manager.service';
export { ExclusiveRangeService, IExclusiveRangeService } from './services/exclusive-range/exclusive-range-service';
export { SheetLazyExecuteScheduleService } from './services/lazy-execute-schedule.service';
diff --git a/packages/sheets/src/plugin.ts b/packages/sheets/src/plugin.ts
index f4a3d35dc9..bb64e752ab 100644
--- a/packages/sheets/src/plugin.ts
+++ b/packages/sheets/src/plugin.ts
@@ -19,6 +19,7 @@ import type { IUniverSheetsConfig } from './controllers/config.schema';
import { AUTO_HEIGHT_FOR_MERGED_CELLS, DependentOn, IConfigService, Inject, Injector, IS_ROW_STYLE_PRECEDE_COLUMN_STYLE, merge, mergeOverrideWithDependencies, Plugin, registerDependencies, touchDependencies, UniverInstanceType } from '@univerjs/core';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { ActiveWorksheetController } from './controllers/active-worksheet.controller';
+import { AutoFillController } from './controllers/auto-fill.controller';
import { BasicWorksheetController } from './controllers/basic-worksheet.controller';
import { CalculateResultApplyController } from './controllers/calculate-result-apply.controller';
import { ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY } from './controllers/config';
@@ -35,6 +36,7 @@ import { RangeProtectionRenderModel } from './model/range-protection-render.mode
import { RangeProtectionRuleModel } from './model/range-protection-rule.model';
import { RangeProtectionCache } from './model/range-protection.cache';
import { SheetRangeThemeModel } from './model/range-theme-model';
+import { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';
import { BorderStyleManagerService } from './services/border-style-manager.service';
import { ExclusiveRangeService, IExclusiveRangeService } from './services/exclusive-range/exclusive-range-service';
import { SheetLazyExecuteScheduleService } from './services/lazy-execute-schedule.service';
@@ -130,6 +132,8 @@ export class UniverSheetsPlugin extends Plugin {
useClass: ExclusiveRangeService,
deps: [SheetsSelectionsService],
}],
+ [IAutoFillService, { useClass: AutoFillService }],
+ [AutoFillController],
];
if (!this._config?.notExecuteFormula) {
@@ -155,6 +159,7 @@ export class UniverSheetsPlugin extends Plugin {
[WorksheetPermissionService],
[SheetPermissionViewModelController],
[SheetSkeletonService],
+ [AutoFillController],
]);
if (!this._config?.onlyRegisterFormulaRelatedMutations) {
diff --git a/packages/sheets-ui/src/services/auto-fill/__tests__/tool.spec.ts b/packages/sheets/src/services/auto-fill/__tests__/tool.spec.ts
similarity index 92%
rename from packages/sheets-ui/src/services/auto-fill/__tests__/tool.spec.ts
rename to packages/sheets/src/services/auto-fill/__tests__/tool.spec.ts
index e1835999c9..ff3352c487 100644
--- a/packages/sheets-ui/src/services/auto-fill/__tests__/tool.spec.ts
+++ b/packages/sheets/src/services/auto-fill/__tests__/tool.spec.ts
@@ -16,7 +16,9 @@
import { CellValueType } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
-import { needsUpdateCellValue } from '../tools';
+import AutoFillTools from '../tools';
+
+const { needsUpdateCellValue } = AutoFillTools;
describe('Test tool', () => {
it('Function needsUpdateCellValue', () => {
diff --git a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts b/packages/sheets/src/services/auto-fill/auto-fill.service.ts
similarity index 73%
rename from packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
rename to packages/sheets/src/services/auto-fill/auto-fill.service.ts
index 01fbb72063..89458bbf28 100644
--- a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
+++ b/packages/sheets/src/services/auto-fill/auto-fill.service.ts
@@ -14,21 +14,24 @@
* limitations under the License.
*/
-import type { IAccessor, IDisposable, IMutationInfo, IRange, Nullable, Workbook } from '@univerjs/core';
-import type { RenderManagerService } from '@univerjs/engine-render';
-import type { ISetRangeValuesMutationParams, ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';
+import type { IAccessor, IDisposable, IMutationInfo, IRange, IRowAutoHeightInfo, Nullable, Workbook, Worksheet } from '@univerjs/core';
import type { Observable } from 'rxjs';
+import type { ISetRangeValuesMutationParams } from '../../commands/mutations/set-range-values.mutation';
+import type { ISetWorksheetRowAutoHeightMutationParams } from '../../commands/mutations/set-worksheet-row-height.mutation';
import type { IAutoFillLocation, IAutoFillRule, ISheetAutoFillHook } from './type';
import { createIdentifier, Direction, Disposable, ICommandService, Inject, Injector, IUndoRedoService, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, Rectangle, toDisposable, UniverInstanceType } from '@univerjs/core';
-
-import { IRenderManagerService } from '@univerjs/engine-render';
-import { rangeToDiscreteRange, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetRowAutoHeightMutation, SetWorksheetRowAutoHeightMutationFactory, SheetsSelectionsService } from '@univerjs/sheets';
import { BehaviorSubject } from 'rxjs';
+import { discreteRangeToRange, rangeToDiscreteRange } from '../../basics/utils';
import { AutoClearContentCommand } from '../../commands/commands/auto-fill.command';
-import { AFFECT_LAYOUT_STYLES } from '../../controllers/auto-height.controller';
-import { discreteRangeToRange } from '../../controllers/utils/range-tools';
-import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
-import {
+import { AFFECT_LAYOUT_STYLES } from '../../commands/commands/set-style.command';
+import { getPrimaryForRange } from '../../commands/commands/utils/selection-utils';
+import { SetRangeValuesMutation } from '../../commands/mutations/set-range-values.mutation';
+import { SetWorksheetRowAutoHeightMutation, SetWorksheetRowAutoHeightMutationFactory } from '../../commands/mutations/set-worksheet-row-height.mutation';
+import { SetSelectionsOperation } from '../../commands/operations/selection.operation';
+import AutoFillRules from './rules';
+import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_HOOK_TYPE } from './type';
+
+const {
chnNumberRule,
chnWeek2Rule,
chnWeek3Rule,
@@ -37,12 +40,11 @@ import {
loopSeriesRule,
numberRule,
otherRule,
-} from './rules';
-import { APPLY_TYPE, AutoFillHookType } from './type';
+} = AutoFillRules;
export interface IAutoFillService {
- applyType$: Observable<APPLY_TYPE>;
- applyType: APPLY_TYPE;
+ applyType$: Observable<AUTO_FILL_APPLY_TYPE>;
+ applyType: AUTO_FILL_APPLY_TYPE;
direction: Direction;
@@ -52,7 +54,7 @@ export interface IAutoFillService {
showMenu$: Observable<boolean>;
setShowMenu: (show: boolean) => void;
- setDisableApplyType: (type: APPLY_TYPE, disable: boolean) => void;
+ setDisableApplyType: (type: AUTO_FILL_APPLY_TYPE, disable: boolean) => void;
getRules(): IAutoFillRule[];
isFillingStyle(): boolean;
@@ -66,21 +68,21 @@ export interface IAutoFillService {
getAllHooks(): ISheetAutoFillHook[];
getActiveHooks(): ISheetAutoFillHook[];
addHook(hook: ISheetAutoFillHook): IDisposable;
- fillData(applyType: APPLY_TYPE): boolean;
+ fillData(applyType: AUTO_FILL_APPLY_TYPE): boolean;
- triggerAutoFill(unitId: string, subUnitId: string, source: IRange, target: IRange, manualApplyType?: APPLY_TYPE): Promise<boolean>;
+ triggerAutoFill(unitId: string, subUnitId: string, source: IRange, target: IRange, manualApplyType?: AUTO_FILL_APPLY_TYPE): Promise<boolean>;
}
export interface IApplyMenuItem {
label: string;
- value: APPLY_TYPE;
+ value: AUTO_FILL_APPLY_TYPE;
disable: boolean;
}
export class AutoFillService extends Disposable implements IAutoFillService {
private _rules: IAutoFillRule[] = [];
private _hooks: ISheetAutoFillHook[] = [];
- private readonly _applyType$: BehaviorSubject<APPLY_TYPE> = new BehaviorSubject<APPLY_TYPE>(APPLY_TYPE.SERIES);
+ private readonly _applyType$: BehaviorSubject<AUTO_FILL_APPLY_TYPE> = new BehaviorSubject<AUTO_FILL_APPLY_TYPE>(AUTO_FILL_APPLY_TYPE.SERIES);
private _isFillingStyle: boolean = true;
private _prevUndos: IMutationInfo[] = [];
@@ -100,22 +102,22 @@ export class AutoFillService extends Disposable implements IAutoFillService {
private readonly _menu$: BehaviorSubject<IApplyMenuItem[]> = new BehaviorSubject<IApplyMenuItem[]>([
{
label: 'autoFill.copy',
- value: APPLY_TYPE.COPY,
+ value: AUTO_FILL_APPLY_TYPE.COPY,
disable: false,
},
{
label: 'autoFill.series',
- value: APPLY_TYPE.SERIES,
+ value: AUTO_FILL_APPLY_TYPE.SERIES,
disable: false,
},
{
label: 'autoFill.formatOnly',
- value: APPLY_TYPE.ONLY_FORMAT,
+ value: AUTO_FILL_APPLY_TYPE.ONLY_FORMAT,
disable: false,
},
{
label: 'autoFill.noFormat',
- value: APPLY_TYPE.NO_FORMAT,
+ value: AUTO_FILL_APPLY_TYPE.NO_FORMAT,
disable: false,
},
]);
@@ -124,9 +126,7 @@ export class AutoFillService extends Disposable implements IAutoFillService {
constructor(
@ICommandService private _commandService: ICommandService,
@IUndoRedoService private _undoRedoService: IUndoRedoService,
- @IRenderManagerService private readonly _renderManagerService: RenderManagerService,
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
- @Inject(SheetsSelectionsService) private _selectionManagerService: SheetsSelectionsService,
@Inject(Injector) private readonly _injector: Injector
) {
super();
@@ -163,13 +163,13 @@ export class AutoFillService extends Disposable implements IAutoFillService {
}
// eslint-disable-next-line max-lines-per-function, complexity
- async triggerAutoFill(unitId: string, subUnitId: string, source: IRange, selection: IRange, manualApplyType?: APPLY_TYPE) {
+ async triggerAutoFill(unitId: string, subUnitId: string, source: IRange, selection: IRange, manualApplyType?: AUTO_FILL_APPLY_TYPE) {
// if source range === dest range, do nothing;
if (
source.startColumn === selection.startColumn &&
- source.startRow === selection.startRow &&
- source.endColumn === selection.endColumn &&
- source.endRow === selection.endRow
+ source.startRow === selection.startRow &&
+ source.endColumn === selection.endColumn &&
+ source.endRow === selection.endRow
) {
return false;
}
@@ -239,7 +239,7 @@ export class AutoFillService extends Disposable implements IAutoFillService {
subUnitId,
};
- const preferTypes: APPLY_TYPE[] = [];
+ const preferTypes: AUTO_FILL_APPLY_TYPE[] = [];
const activeHooks = this.getActiveHooks();
activeHooks.forEach((hook) => {
const type = hook?.onBeforeFillData?.({ source: autoFillSource, target: autoFillTarget, unitId, subUnitId }, direction!);
@@ -281,7 +281,7 @@ export class AutoFillService extends Disposable implements IAutoFillService {
}
if (hook.type === undefined) {
- hook.type = AutoFillHookType.Append;
+ hook.type = AUTO_FILL_HOOK_TYPE.APPEND;
}
this._hooks.push(hook);
return toDisposable(() => {
@@ -318,14 +318,14 @@ export class AutoFillService extends Disposable implements IAutoFillService {
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);
+ const onlyHooks = enabledHooks.filter((h) => h.type === AUTO_FILL_HOOK_TYPE.ONLY);
if (onlyHooks.length > 0) {
return this._getOneByPriority(onlyHooks);
}
- const defaultHooks = this._getOneByPriority(enabledHooks.filter((h) => h.type === AutoFillHookType.Default));
+ const defaultHooks = this._getOneByPriority(enabledHooks.filter((h) => h.type === AUTO_FILL_HOOK_TYPE.DEFAULT));
- const appendHooks = enabledHooks.filter((h) => h.type === AutoFillHookType.Append) || [];
+ const appendHooks = enabledHooks.filter((h) => h.type === AUTO_FILL_HOOK_TYPE.APPEND) || [];
return [...defaultHooks, ...appendHooks];
}
@@ -334,7 +334,7 @@ export class AutoFillService extends Disposable implements IAutoFillService {
return this._applyType$.getValue();
}
- set applyType(type: APPLY_TYPE) {
+ set applyType(type: AUTO_FILL_APPLY_TYPE) {
this._applyType$.next(type);
}
@@ -366,7 +366,7 @@ export class AutoFillService extends Disposable implements IAutoFillService {
this._autoFillLocation$.next(location);
}
- setDisableApplyType(type: APPLY_TYPE, disable: boolean) {
+ setDisableApplyType(type: AUTO_FILL_APPLY_TYPE, disable: boolean) {
this._menu$.next(
this._menu$.getValue().map((item) => {
if (item.value === type) {
@@ -385,9 +385,9 @@ export class AutoFillService extends Disposable implements IAutoFillService {
}
// eslint-disable-next-line max-lines-per-function
- fillData(applyType: APPLY_TYPE) {
+ fillData(applyType: AUTO_FILL_APPLY_TYPE) {
this.applyType = applyType;
- const activeWorkbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const activeWorkbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
const activeUnitId = activeWorkbook?.getUnitId();
const activeSubUnitId = activeWorkbook?.getActiveSheet()?.getSheetId();
const { source, target, unitId = activeUnitId, subUnitId = activeSubUnitId } = this.autoFillLocation || {};
@@ -396,6 +396,11 @@ export class AutoFillService extends Disposable implements IAutoFillService {
return false;
}
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ if (!workbook) return false;
+ const worksheet = workbook.getSheetBySheetId(subUnitId);
+ if (!worksheet) return false;
+
const direction = this.direction;
if (this._prevUndos.length > 0) {
@@ -407,14 +412,18 @@ export class AutoFillService extends Disposable implements IAutoFillService {
const selection = Rectangle.union(discreteRangeToRange(source), discreteRangeToRange(target));
const activeHooks = this.getActiveHooks();
- const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)!;
// If filling the active sheet, update the selection immediately
if (unitId === activeUnitId && subUnitId === activeSubUnitId) {
this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
selections: [
{
- primary: { ...(this._selectionManagerService.getCurrentLastSelection()?.primary ?? selection) },
+ primary: getPrimaryForRange({
+ startRow: source.rows[0],
+ endRow: source.rows[source.rows.length - 1],
+ startColumn: source.cols[0],
+ endColumn: source.cols[source.cols.length - 1],
+ }, worksheet),
range: {
...selection,
rangeType: RANGE_TYPE.NORMAL,
@@ -441,28 +450,10 @@ export class AutoFillService extends Disposable implements IAutoFillService {
const result = redos.every((m) => this._commandService.syncExecuteCommand(m.id, m.params));
// deal with auto-height
- const autoHeightRanges: IRange[] = [];
- if (applyType !== APPLY_TYPE.NO_FORMAT) {
- redos.forEach((m) => {
- if (m.id === SetRangeValuesMutation.id) {
- const { cellValue } = m.params as ISetRangeValuesMutationParams;
- const matrix = new ObjectMatrix(cellValue);
- matrix.forValue((row, col, value) => {
- const style = Object.keys(workbook.getStyles().get(value?.s) || {});
- if (value?.p || (style.length && AFFECT_LAYOUT_STYLES.some((s) => style.includes(s)))) {
- autoHeightRanges.push({ startRow: row, endRow: row, startColumn: col, endColumn: col });
- }
- });
- }
- });
- }
+ const { redos: autoHeightRedos, undos: autoHeightUndos } = this._getAutoHeightUndoRedos(redos, workbook, worksheet);
+ redos.push(...autoHeightRedos);
+ undos.push(...autoHeightUndos);
- const autoHeightUndoRedos = this._getAutoHeightUndoRedos(unitId, subUnitId, autoHeightRanges);
- const autoHeightResult = autoHeightUndoRedos.redos.every((m) => this._commandService.syncExecuteCommand(m.id, m.params));
- if (autoHeightResult) {
- undos.push(...autoHeightUndoRedos.undos);
- redos.push(...autoHeightUndoRedos.redos);
- }
if (result) {
this._prevUndos = undos;
// add to undo redo services
@@ -479,18 +470,64 @@ export class AutoFillService extends Disposable implements IAutoFillService {
return true;
}
- private _getAutoHeightUndoRedos(unitId: string, subUnitId: string, ranges: IRange[]) {
- const sheetSkeletonService = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService);
- const skeleton = sheetSkeletonService?.getCurrentParam()?.skeleton;
- if (!skeleton) return { redos: [], undos: [] };
+ private _getAutoHeightUndoRedos(executedRedos: IMutationInfo[], workbook: Workbook, worksheet: Worksheet) {
+ if (this.applyType === AUTO_FILL_APPLY_TYPE.NO_FORMAT) {
+ return { undos: [], redos: [] };
+ }
- const rowsAutoHeightInfo = skeleton.calculateAutoHeightInRange(ranges);
- const redoParams: ISetWorksheetRowAutoHeightMutationParams = { subUnitId, unitId, rowsAutoHeightInfo };
- const worksheet = skeleton.worksheet;
+ const rowsAutoHeightInfo: IRowAutoHeightInfo[] = [];
+ const defaultRowHeight = worksheet.getConfig().defaultRowHeight;
+ const rowManager = worksheet.getRowManager();
+
+ executedRedos.forEach((m) => {
+ if (m.id === SetRangeValuesMutation.id) {
+ const { cellValue } = m.params as ISetRangeValuesMutationParams;
+ const matrix = new ObjectMatrix(cellValue);
+ matrix.forValue((row, col, value) => {
+ const style = Object.keys(workbook.getStyles().get(value?.s) || {});
+ if (value?.p || (style.length && AFFECT_LAYOUT_STYLES.some((s) => style.includes(s)))) {
+ const cellHeight = worksheet.getCellHeight(row, col);
+ const rowData = rowManager.getRow(row);
+ if ((!rowData && cellHeight !== defaultRowHeight) || (rowData && cellHeight !== rowManager.getRowHeight(row))) {
+ rowsAutoHeightInfo.push({
+ row,
+ autoHeight: cellHeight,
+ });
+ }
+ }
+ });
+ }
+ });
+
+ if (rowsAutoHeightInfo.length === 0) {
+ return { undos: [], redos: [] };
+ }
+
+ const redoParams: ISetWorksheetRowAutoHeightMutationParams = {
+ unitId: workbook.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ rowsAutoHeightInfo,
+ };
const undoParams = SetWorksheetRowAutoHeightMutationFactory(redoParams, worksheet);
+
+ const redo = {
+ id: SetWorksheetRowAutoHeightMutation.id,
+ params: redoParams,
+ };
+ const result = this._commandService.syncExecuteCommand(redo.id, redo.params);
+
+ if (!result) {
+ return { undos: [], redos: [] };
+ }
+
return {
- undos: [{ id: SetWorksheetRowAutoHeightMutation.id, params: undoParams }],
- redos: [{ id: SetWorksheetRowAutoHeightMutation.id, params: redoParams }],
+ redos: [redo],
+ undos: [
+ {
+ id: SetWorksheetRowAutoHeightMutation.id,
+ params: undoParams,
+ },
+ ],
};
}
}
diff --git a/packages/sheets-ui/src/services/auto-fill/rules.ts b/packages/sheets/src/services/auto-fill/rules.ts
similarity index 86%
rename from packages/sheets-ui/src/services/auto-fill/rules.ts
rename to packages/sheets/src/services/auto-fill/rules.ts
index af962aca62..6d296c7f03 100644
--- a/packages/sheets-ui/src/services/auto-fill/rules.ts
+++ b/packages/sheets/src/services/auto-fill/rules.ts
@@ -16,9 +16,11 @@
import type { Workbook } from '@univerjs/core';
import type { IAutoFillRule } from './type';
-
import { CellValueType, Direction, IUniverInstanceService, numfmt } from '@univerjs/core';
-import {
+import AutoFillTools from './tools';
+import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_DATA_TYPE } from './type';
+
+const {
chineseToNumber,
fillChnNumber,
fillChnWeek,
@@ -33,11 +35,11 @@ import {
isEqualDiff,
isLoopSeries,
matchExtendNumber,
-} from './tools';
-import { APPLY_TYPE, DATA_TYPE } from './type';
+ reverseIfNeed,
+} = AutoFillTools;
-export const dateRule: IAutoFillRule = {
- type: DATA_TYPE.DATE,
+const dateRule: IAutoFillRule = {
+ type: AUTO_FILL_DATA_TYPE.DATE,
priority: 1100,
match: (cellData, accessor) => {
if (cellData?.f || cellData?.si) {
@@ -60,13 +62,13 @@ export const dateRule: IAutoFillRule = {
return false;
},
isContinue: (prev, cur) => {
- if (prev.type === DATA_TYPE.DATE) {
+ if (prev.type === AUTO_FILL_DATA_TYPE.DATE) {
return true;
}
return false;
},
applyFunctions: {
- [APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
+ [AUTO_FILL_APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
const { data } = dataWithIndex;
if (direction === Direction.LEFT || direction === Direction.UP) {
data.reverse();
@@ -77,18 +79,18 @@ export const dateRule: IAutoFillRule = {
},
};
-export const numberRule: IAutoFillRule = {
- type: DATA_TYPE.NUMBER,
+const numberRule: IAutoFillRule = {
+ type: AUTO_FILL_DATA_TYPE.NUMBER,
priority: 1000,
match: (cellData) => typeof cellData?.v === 'number' || cellData?.t === CellValueType.NUMBER,
isContinue: (prev, cur) => {
- if (prev.type === DATA_TYPE.NUMBER) {
+ if (prev.type === AUTO_FILL_DATA_TYPE.NUMBER) {
return true;
}
return false;
},
applyFunctions: {
- [APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
+ [AUTO_FILL_APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
const { data } = dataWithIndex;
if (direction === Direction.LEFT || direction === Direction.UP) {
data.reverse();
@@ -99,24 +101,12 @@ export const numberRule: IAutoFillRule = {
},
};
-export const otherRule: IAutoFillRule = {
- type: DATA_TYPE.OTHER,
- priority: 0,
- match: () => true,
- isContinue: (prev, cur) => {
- if (prev.type === DATA_TYPE.OTHER) {
- return true;
- }
- return false;
- },
-};
-
-export const extendNumberRule: IAutoFillRule = {
- type: DATA_TYPE.EXTEND_NUMBER,
+const extendNumberRule: IAutoFillRule = {
+ type: AUTO_FILL_DATA_TYPE.EXTEND_NUMBER,
priority: 900,
match: (cellData) => matchExtendNumber(`${cellData?.v}` || '').isExtendNumber,
isContinue: (prev, cur) => {
- if (prev.type === DATA_TYPE.EXTEND_NUMBER) {
+ if (prev.type === AUTO_FILL_DATA_TYPE.EXTEND_NUMBER) {
const { beforeTxt, afterTxt } = matchExtendNumber(`${prev.cellData?.v}` || '');
const { beforeTxt: curBeforeTxt, afterTxt: curAfterTxt } = matchExtendNumber(`${cur?.v}` || '');
if (beforeTxt === curBeforeTxt && afterTxt === curAfterTxt) {
@@ -126,7 +116,7 @@ export const extendNumberRule: IAutoFillRule = {
return false;
},
applyFunctions: {
- [APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
+ [AUTO_FILL_APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
const { data } = dataWithIndex;
const isReverse = direction === Direction.UP || direction === Direction.LEFT;
@@ -156,8 +146,8 @@ export const extendNumberRule: IAutoFillRule = {
},
};
-export const chnNumberRule: IAutoFillRule = {
- type: DATA_TYPE.CHN_NUMBER,
+const chnNumberRule: IAutoFillRule = {
+ type: AUTO_FILL_DATA_TYPE.CHN_NUMBER,
priority: 830,
match: (cellData) => {
if (isChnNumber(`${cellData?.v}` || '')) {
@@ -166,13 +156,13 @@ export const chnNumberRule: IAutoFillRule = {
return false;
},
isContinue: (prev, cur) => {
- if (prev.type === DATA_TYPE.CHN_NUMBER) {
+ if (prev.type === AUTO_FILL_DATA_TYPE.CHN_NUMBER) {
return true;
}
return false;
},
applyFunctions: {
- [APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
+ [AUTO_FILL_APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
const { data } = dataWithIndex;
const isReverse = direction === Direction.LEFT || direction === Direction.UP;
@@ -243,8 +233,8 @@ export const chnNumberRule: IAutoFillRule = {
},
};
-export const chnWeek2Rule: IAutoFillRule = {
- type: DATA_TYPE.CHN_WEEK2,
+const chnWeek2Rule: IAutoFillRule = {
+ type: AUTO_FILL_DATA_TYPE.CHN_WEEK2,
priority: 820,
match: (cellData) => {
if (isChnWeek2(`${cellData?.v}` || '')) {
@@ -252,9 +242,9 @@ export const chnWeek2Rule: IAutoFillRule = {
}
return false;
},
- isContinue: (prev, cur) => prev.type === DATA_TYPE.CHN_WEEK2,
+ isContinue: (prev, cur) => prev.type === AUTO_FILL_DATA_TYPE.CHN_WEEK2,
applyFunctions: {
- [APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
+ [AUTO_FILL_APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
const { data } = dataWithIndex;
const isReverse = direction === Direction.LEFT || direction === Direction.UP;
@@ -300,13 +290,13 @@ export const chnWeek2Rule: IAutoFillRule = {
},
};
-export const chnWeek3Rule: IAutoFillRule = {
- type: DATA_TYPE.CHN_WEEK3,
+const chnWeek3Rule: IAutoFillRule = {
+ type: AUTO_FILL_DATA_TYPE.CHN_WEEK3,
priority: 810,
match: (cellData) => isChnWeek3(`${cellData?.v}` || ''),
- isContinue: (prev, cur) => prev.type === DATA_TYPE.CHN_WEEK3,
+ isContinue: (prev, cur) => prev.type === AUTO_FILL_DATA_TYPE.CHN_WEEK3,
applyFunctions: {
- [APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
+ [AUTO_FILL_APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
const { data } = dataWithIndex;
const isReverse = direction === Direction.LEFT || direction === Direction.UP;
@@ -354,18 +344,18 @@ export const chnWeek3Rule: IAutoFillRule = {
},
};
-export const loopSeriesRule: IAutoFillRule = {
- type: DATA_TYPE.LOOP_SERIES,
+const loopSeriesRule: IAutoFillRule = {
+ type: AUTO_FILL_DATA_TYPE.LOOP_SERIES,
priority: 800,
match: (cellData) => isLoopSeries(`${cellData?.v}` || ''),
isContinue: (prev, cur) => {
- if (prev.type === DATA_TYPE.LOOP_SERIES) {
+ if (prev.type === AUTO_FILL_DATA_TYPE.LOOP_SERIES) {
return getLoopSeriesInfo(`${prev.cellData?.v}` || '').name === getLoopSeriesInfo(`${cur?.v}` || '').name;
}
return false;
},
applyFunctions: {
- [APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
+ [AUTO_FILL_APPLY_TYPE.SERIES]: (dataWithIndex, len, direction) => {
const { data } = dataWithIndex;
const isReverse = direction === Direction.LEFT || direction === Direction.UP;
const { series } = getLoopSeriesInfo(`${data[0]?.v}` || '');
@@ -411,6 +401,27 @@ export const loopSeriesRule: IAutoFillRule = {
},
};
-export function reverseIfNeed<T>(data: T[], reverse: boolean): T[] {
- return reverse ? data.reverse() : data;
-}
+const otherRule: IAutoFillRule = {
+ type: AUTO_FILL_DATA_TYPE.OTHER,
+ priority: 0,
+ match: () => true,
+ isContinue: (prev, cur) => {
+ if (prev.type === AUTO_FILL_DATA_TYPE.OTHER) {
+ return true;
+ }
+ return false;
+ },
+};
+
+const AutoFillRules = {
+ dateRule,
+ numberRule,
+ extendNumberRule,
+ chnNumberRule,
+ chnWeek2Rule,
+ chnWeek3Rule,
+ loopSeriesRule,
+ otherRule,
+};
+
+export default AutoFillRules;
diff --git a/packages/sheets-ui/src/services/auto-fill/tools.ts b/packages/sheets/src/services/auto-fill/tools.ts
similarity index 84%
rename from packages/sheets-ui/src/services/auto-fill/tools.ts
rename to packages/sheets/src/services/auto-fill/tools.ts
index b53b21687c..2bb8f88f47 100644
--- a/packages/sheets-ui/src/services/auto-fill/tools.ts
+++ b/packages/sheets/src/services/auto-fill/tools.ts
@@ -14,22 +14,29 @@
* limitations under the License.
*/
-import type { ICellData, IRange, Nullable } from '@univerjs/core';
-import { CellValueType, Direction, isFormulaId, isFormulaString, Tools } from '@univerjs/core';
-
-export const chnNumChar = { 零: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 };
-export const chnNumChar2 = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
-export const chnUnitSection = ['', '万', '亿', '万亿', '亿亿'];
-export const chnUnitChar = ['', '十', '百', '千'];
-
-export interface ICopyDataInType {
- data: Array<Nullable<ICellData>>;
- index: ICopyDataInTypeIndexInfo;
-}
+import type { ICellData, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';
+import type { IDiscreteRange } from '../../basics';
+import type { IAutoFillCopyDataInTypeIndexInfo } from './type';
+import { CellValueType, Direction, isFormulaId, isFormulaString, ObjectMatrix, Tools } from '@univerjs/core';
+
+const chnNumChar = {
+ 零: 0,
+ 一: 1,
+ 二: 2,
+ 三: 3,
+ 四: 4,
+ 五: 5,
+ 六: 6,
+ 七: 7,
+ 八: 8,
+ 九: 9,
+};
-export type ICopyDataInTypeIndexInfo = number[];
+const chnNumChar2 = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
+const chnUnitSection = ['', '万', '亿', '万亿', '亿亿'];
+const chnUnitChar = ['', '十', '百', '千'];
-export const chnNameValue = {
+const chnNameValue = {
十: { value: 10, secUnit: false },
百: { value: 100, secUnit: false },
千: { value: 1000, secUnit: false },
@@ -37,7 +44,7 @@ export const chnNameValue = {
亿: { value: 100000000, secUnit: true },
};
-export function chineseToNumber(chnStr?: Nullable<string>) {
+function chineseToNumber(chnStr?: Nullable<string>) {
if (!chnStr) {
return 0;
}
@@ -76,7 +83,7 @@ export function chineseToNumber(chnStr?: Nullable<string>) {
return rtn + section;
}
-export function sectionToChinese(section: number) {
+function sectionToChinese(section: number) {
let strIns = '';
let chnStr = '';
let unitPos = 0;
@@ -104,7 +111,7 @@ export function sectionToChinese(section: number) {
return chnStr;
}
-export function numberToChinese(num: number) {
+function numberToChinese(num: number) {
let unitPos = 0;
let strIns = '';
let chnStr = '';
@@ -131,7 +138,7 @@ export function numberToChinese(num: number) {
return chnStr;
}
-export function isChnNumber(txt?: string) {
+function isChnNumber(txt?: string) {
if (!txt) {
return false;
}
@@ -157,7 +164,7 @@ export function isChnNumber(txt?: string) {
return isChnNumber;
}
-export function matchExtendNumber(txt?: string) {
+function matchExtendNumber(txt?: string) {
if (!txt) {
return {
isExtendNumber: false,
@@ -191,7 +198,7 @@ export function matchExtendNumber(txt?: string) {
};
}
-export function isChnWeek1(txt: string) {
+function isChnWeek1(txt: string) {
let isChnWeek1;
if (txt.length === 1) {
if (txt === '日' || chineseToNumber(txt) < 7) {
@@ -206,7 +213,7 @@ export function isChnWeek1(txt: string) {
return isChnWeek1;
}
-export function isChnWeek2(txt: string) {
+function isChnWeek2(txt: string) {
let isChnWeek2;
if (txt.length === 2) {
if (
@@ -229,7 +236,7 @@ export function isChnWeek2(txt: string) {
return isChnWeek2;
}
-export function isChnWeek3(txt: string) {
+function isChnWeek3(txt: string) {
let isChnWeek3;
if (txt.length === 3) {
if (
@@ -252,7 +259,7 @@ export function isChnWeek3(txt: string) {
return isChnWeek3;
}
-export function getLenS(indexArr: any[], rsd: number) {
+function getLenS(indexArr: any[], rsd: number) {
let s = 0;
for (let j = 0; j < indexArr.length; j++) {
@@ -268,10 +275,8 @@ export function getLenS(indexArr: any[], rsd: number) {
/**
* equal diff
- * @param arr
- * @returns
*/
-export function isEqualDiff(arr: number[]) {
+function isEqualDiff(arr: number[]) {
let diff = true;
const step = arr[1] - arr[0];
@@ -285,8 +290,8 @@ export function isEqualDiff(arr: number[]) {
return diff;
}
-export function getDataIndex(csLen: number, asLen: number, indexArr: number[]) {
- const obj: ICopyDataInTypeIndexInfo = [];
+function getDataIndex(csLen: number, asLen: number, indexArr: number[]) {
+ const obj: IAutoFillCopyDataInTypeIndexInfo = [];
const num = Math.floor(asLen / csLen);
const rsd = asLen % csLen;
@@ -321,7 +326,7 @@ export function getDataIndex(csLen: number, asLen: number, indexArr: number[]) {
return obj;
}
-export function fillCopy(data: Array<Nullable<ICellData>>, len: number) {
+function fillCopy(data: Array<Nullable<ICellData>>, len: number) {
const applyData = [];
for (let i = 1; i <= len; i++) {
@@ -344,7 +349,7 @@ export function fillCopy(data: Array<Nullable<ICellData>>, len: number) {
return applyData;
}
-export function fillCopyStyles(data: Array<Nullable<ICellData>>, len: number) {
+function fillCopyStyles(data: Array<Nullable<ICellData>>, len: number) {
const applyData = [];
for (let i = 1; i <= len; i++) {
const index = (i - 1) % data.length;
@@ -356,7 +361,7 @@ export function fillCopyStyles(data: Array<Nullable<ICellData>>, len: number) {
return applyData;
}
-export function isEqualRatio(arr: number[]) {
+function isEqualRatio(arr: number[]) {
let ratio = true;
const step = arr[1] / arr[0];
@@ -370,7 +375,7 @@ export function isEqualRatio(arr: number[]) {
return ratio;
}
-export function getXArr(len: number) {
+function getXArr(len: number) {
const xArr = [];
for (let i = 1; i <= len; i++) {
@@ -380,7 +385,7 @@ export function getXArr(len: number) {
return xArr;
}
-export function fillSeries(data: Array<Nullable<ICellData>>, len: number, direction: Direction) {
+function fillSeries(data: Array<Nullable<ICellData>>, len: number, direction: Direction) {
const applyData = [];
const dataNumArr = [];
@@ -427,7 +432,7 @@ export function fillSeries(data: Array<Nullable<ICellData>>, len: number, direct
return applyData;
}
-export function forecast(x: number, yArr: number[], xArr: number[], forward = true) {
+function forecast(x: number, yArr: number[], xArr: number[], forward = true) {
function getAverage(arr: number[]) {
let sum = 0;
@@ -460,7 +465,7 @@ export function forecast(x: number, yArr: number[], xArr: number[], forward = tr
return Math.round((a + b * x) * 100000) / 100000;
}
-export function fillExtendNumber(data: Array<Nullable<ICellData>>, len: number, step: number) {
+function fillExtendNumber(data: Array<Nullable<ICellData>>, len: number, step: number) {
const applyData = [];
const reg = /0|([1-9]+[0-9]*)/g;
@@ -490,7 +495,8 @@ export function fillExtendNumber(data: Array<Nullable<ICellData>>, len: number,
return applyData;
}
-export function fillOnlyFormat(data: Array<Nullable<ICellData>>, len: number) {
+
+function fillOnlyFormat(data: Array<Nullable<ICellData>>, len: number) {
const applyData = [];
for (let i = 1; i <= len; i++) {
@@ -509,8 +515,8 @@ export function fillOnlyFormat(data: Array<Nullable<ICellData>>, len: number) {
return applyData;
}
-// weektype: 0-日 1-周 2-星期
-export function fillChnWeek(data: Array<Nullable<ICellData>>, len: number, step: number, weekType: number = 0) {
+// weekType: 0-日 1-周 2-星期
+function fillChnWeek(data: Array<Nullable<ICellData>>, len: number, step: number, weekType: number = 0) {
const keywordMap = [
['日', '一', '二', '三', '四', '五', '六'],
['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
@@ -552,7 +558,7 @@ export function fillChnWeek(data: Array<Nullable<ICellData>>, len: number, step:
return applyData;
}
-export function fillChnNumber(data: Array<Nullable<ICellData>>, len: number, step: number) {
+function fillChnNumber(data: Array<Nullable<ICellData>>, len: number, step: number) {
const applyData = [];
for (let i = 1; i <= len; i++) {
@@ -606,7 +612,7 @@ const LOOP_SERIES: { [key: string]: string[] } = {
chSeason2: ['春季', '夏季', '秋季', '冬季'],
};
-export function isLoopSeries(txt: string) {
+function isLoopSeries(txt: string) {
let isLoopSeries = false;
Object.keys(LOOP_SERIES).forEach((key) => {
if (LOOP_SERIES[key].includes(txt)) {
@@ -616,7 +622,7 @@ export function isLoopSeries(txt: string) {
return isLoopSeries;
}
-export function getLoopSeriesInfo(txt: string) {
+function getLoopSeriesInfo(txt: string) {
let name = '';
const series: string[] = [];
Object.keys(LOOP_SERIES).forEach((key) => {
@@ -628,7 +634,7 @@ export function getLoopSeriesInfo(txt: string) {
return { name, series };
}
-export function fillLoopSeries(data: Array<Nullable<ICellData>>, len: number, step: number, series: string[]) {
+function fillLoopSeries(data: Array<Nullable<ICellData>>, len: number, step: number, series: string[]) {
const seriesLen = series.length;
const applyData = [];
@@ -655,7 +661,8 @@ export function fillLoopSeries(data: Array<Nullable<ICellData>>, len: number, st
return applyData;
}
-export function getAutoFillRepeatRange(sourceRange: IRange, targetRange: IRange) {
+// eslint-disable-next-line max-lines-per-function
+function getAutoFillRepeatRange(sourceRange: IRange, targetRange: IRange) {
const repeats: Array<{
repeatStartCell: { col: number; row: number };
relativeRange: IRange;
@@ -802,10 +809,8 @@ export function getAutoFillRepeatRange(sourceRange: IRange, targetRange: IRange)
/**
* Formulas or Boolean values do not need to update cell.v
- * @param cell
- * @returns
*/
-export function needsUpdateCellValue(cell: ICellData) {
+function needsUpdateCellValue(cell: ICellData) {
if (isFormulaString(cell.f) || isFormulaId(cell.si)) {
return false;
}
@@ -819,10 +824,72 @@ export function needsUpdateCellValue(cell: ICellData) {
/**
* Remove cell.custom
- * @param cell
*/
-export function removeCellCustom(cell: Nullable<ICellData>) {
+function removeCellCustom(cell: Nullable<ICellData>) {
if (cell && 'custom' in cell) {
delete cell.custom;
}
}
+
+function reverseIfNeed<T>(data: T[], reverse: boolean): T[] {
+ return reverse ? data.reverse() : data;
+}
+
+function generateNullCellValueRowCol(range: IDiscreteRange[]): IObjectMatrixPrimitiveType<ICellData> {
+ const cellValue = new ObjectMatrix<ICellData>();
+ range.forEach((r) => {
+ const { rows, cols } = r;
+ rows.forEach((i) => {
+ cols.forEach((j) => {
+ cellValue.setValue(i, j, {
+ v: null,
+ p: null,
+ f: null,
+ si: null,
+ custom: null,
+ });
+ });
+ });
+ });
+
+ return cellValue.clone();
+}
+
+const AutoFillTools = {
+ chnNumChar,
+ chnNumChar2,
+ chnUnitSection,
+ chnUnitChar,
+ chnNameValue,
+ chineseToNumber,
+ sectionToChinese,
+ numberToChinese,
+ isChnNumber,
+ matchExtendNumber,
+ isChnWeek1,
+ isChnWeek2,
+ isChnWeek3,
+ getLenS,
+ isEqualDiff,
+ getDataIndex,
+ fillCopy,
+ fillCopyStyles,
+ isEqualRatio,
+ getXArr,
+ fillSeries,
+ forecast,
+ fillExtendNumber,
+ fillOnlyFormat,
+ fillChnWeek,
+ fillChnNumber,
+ isLoopSeries,
+ getLoopSeriesInfo,
+ fillLoopSeries,
+ getAutoFillRepeatRange,
+ needsUpdateCellValue,
+ removeCellCustom,
+ reverseIfNeed,
+ generateNullCellValueRowCol,
+};
+
+export default AutoFillTools;
diff --git a/packages/sheets-ui/src/services/auto-fill/type.ts b/packages/sheets/src/services/auto-fill/type.ts
similarity index 65%
rename from packages/sheets-ui/src/services/auto-fill/type.ts
rename to packages/sheets/src/services/auto-fill/type.ts
index 5aab8d8c06..4544934f70 100644
--- a/packages/sheets-ui/src/services/auto-fill/type.ts
+++ b/packages/sheets/src/services/auto-fill/type.ts
@@ -15,12 +15,31 @@
*/
import type { Direction, IAccessor, ICellData, IMutationInfo, IObjectMatrixPrimitiveType, Nullable } from '@univerjs/core';
-import type { IDiscreteRange } from '../../controllers/utils/range-tools';
+import type { IDiscreteRange } from '../../basics';
-export enum AutoFillHookType {
- Append = 'APPEND',
- Default = 'DEFAULT',
- Only = 'ONLY',
+export enum AUTO_FILL_APPLY_TYPE {
+ COPY = 'COPY',
+ SERIES = 'SERIES',
+ ONLY_FORMAT = 'ONLY_FORMAT',
+ NO_FORMAT = 'NO_FORMAT',
+}
+
+export enum AUTO_FILL_DATA_TYPE {
+ NUMBER = 'number',
+ DATE = 'date',
+ EXTEND_NUMBER = 'extendNumber',
+ CHN_NUMBER = 'chnNumber',
+ CHN_WEEK2 = 'chnWeek2',
+ CHN_WEEK3 = 'chnWeek3',
+ LOOP_SERIES = 'loopSeries',
+ FORMULA = 'formula',
+ OTHER = 'other',
+}
+
+export enum AUTO_FILL_HOOK_TYPE {
+ APPEND = 'APPEND',
+ DEFAULT = 'DEFAULT',
+ ONLY = 'ONLY',
}
export interface IAutoFillLocation {
@@ -29,79 +48,56 @@ export interface IAutoFillLocation {
unitId: string;
subUnitId: string;
}
+
export interface ISheetAutoFillHook {
id: string;
priority?: number;
- type?: AutoFillHookType;
+ type?: AUTO_FILL_HOOK_TYPE;
bindUnit?: string;
- disable?: (location: IAutoFillLocation, direction: Direction, applyType: APPLY_TYPE) => boolean;
- onBeforeFillData?(location: IAutoFillLocation, direction: Direction): APPLY_TYPE | void;
+ disable?: (location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE) => boolean;
+ onBeforeFillData?(location: IAutoFillLocation, direction: Direction): AUTO_FILL_APPLY_TYPE | void;
onFillData?(
location: IAutoFillLocation,
direction: Direction,
- applyType: APPLY_TYPE
+ applyType: AUTO_FILL_APPLY_TYPE
): {
undos: IMutationInfo[];
redos: IMutationInfo[];
};
- onAfterFillData?(location: IAutoFillLocation, direction: Direction, applyType: APPLY_TYPE): boolean | void;
- onBeforeSubmit?: (location: IAutoFillLocation, direction: Direction, applyType: APPLY_TYPE, cellValue: IObjectMatrixPrimitiveType<Nullable<ICellData>>) => void;
+ onAfterFillData?(location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE): boolean | void;
+ onBeforeSubmit?: (location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE, cellValue: IObjectMatrixPrimitiveType<Nullable<ICellData>>) => void;
}
-export enum DATA_TYPE {
- NUMBER = 'number',
- DATE = 'date',
- EXTEND_NUMBER = 'extendNumber',
- CHN_NUMBER = 'chnNumber',
- CHN_WEEK2 = 'chnWeek2',
- CHN_WEEK3 = 'chnWeek3',
- LOOP_SERIES = 'loopSeries',
- FORMULA = 'formula',
- OTHER = 'other',
-}
+export type IAutoFillCopyDataInTypeIndexInfo = number[];
-export interface ICopyDataPiece {
- [key: string]: ICopyDataInType[];
-}
-
-export interface ICopyDataInType {
+export interface IAutoFillCopyDataInType {
data: Array<Nullable<ICellData>>;
- index: ICopyDataInTypeIndexInfo;
-}
-
-export type ICopyDataInTypeIndexInfo = number[];
-
-export interface IAutoFillRule {
- type: string;
- match: (cellData: Nullable<ICellData>, accessor: IAccessor) => boolean;
- isContinue: (prev: IRuleConfirmedData, cur: Nullable<ICellData>) => boolean;
- applyFunctions?: APPLY_FUNCTIONS;
- priority: number;
+ index: IAutoFillCopyDataInTypeIndexInfo;
}
-export interface IMutations {
- redos: IMutationInfo[];
- undos: IMutationInfo[];
+export interface IAutoFillCopyDataPiece {
+ [key: string]: IAutoFillCopyDataInType[];
}
-export interface IRuleConfirmedData {
+export interface IAutoFillRuleConfirmedData {
type?: string;
cellData: Nullable<ICellData>;
}
-export type APPLY_FUNCTIONS = {
- [key in APPLY_TYPE]?: (
- dataWithIndex: ICopyDataInType,
+export type AUTO_FILL_APPLY_FUNCTIONS = {
+ [key in AUTO_FILL_APPLY_TYPE]?: (
+ dataWithIndex: IAutoFillCopyDataInType,
len: number,
direction: Direction,
- copyDataPiece: ICopyDataPiece,
+ copyDataPiece: IAutoFillCopyDataPiece,
location?: IAutoFillLocation
) => Array<Nullable<ICellData>>;
};
-export enum APPLY_TYPE {
- COPY = 'COPY',
- SERIES = 'SERIES',
- ONLY_FORMAT = 'ONLY_FORMAT',
- NO_FORMAT = 'NO_FORMAT',
+export interface IAutoFillRule {
+ type: string;
+ match: (cellData: Nullable<ICellData>, accessor: IAccessor) => boolean;
+ isContinue: (prev: IAutoFillRuleConfirmedData, cur: Nullable<ICellData>) => boolean;
+ applyFunctions?: AUTO_FILL_APPLY_FUNCTIONS;
+ priority: number;
}