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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(sheet): auto fill by drag (#369)
YuHonge9e01eca4c8e
diff --git a/packages/base-sheets/src/Basics/getApplyData.ts b/packages/base-sheets/src/Basics/getApplyData.tsnew file mode 100644index 0000000000..e69de29bb2diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.tsindex b93fc7866c..412d228630 100644--- a/packages/base-sheets/src/index.ts+++ b/packages/base-sheets/src/index.ts@@ -22,6 +22,7 @@ export {AddWorksheetMergeCommand,AddWorksheetMergeHorizontalCommand,AddWorksheetMergeVerticalCommand,+ getAddMergeMutationRangeByType,} from './commands/commands/add-worksheet-merge.command';export { ClearSelectionAllCommand } from './commands/commands/clear-selection-all.command';export { ClearSelectionContentCommand } from './commands/commands/clear-selection-content.command';@@ -119,7 +120,10 @@ export {getCellAtRowCol,getStartRange,} from './commands/commands/utils/selection-util';-export { AddWorksheetMergeMutation } from './commands/mutations/add-worksheet-merge.mutation';+export {+ AddMergeUndoMutationFactory,+ AddWorksheetMergeMutation,+} from './commands/mutations/add-worksheet-merge.mutation';export {InsertColMutation,InsertColMutationUndoFactory,diff --git a/packages/ui-plugin-sheets/src/commands/commands/auto-fill.command.ts b/packages/ui-plugin-sheets/src/commands/commands/auto-fill.command.tsnew file mode 100644index 0000000000..42c5f93abe--- /dev/null+++ b/packages/ui-plugin-sheets/src/commands/commands/auto-fill.command.ts@@ -0,0 +1,236 @@+import {+ AddMergeUndoMutationFactory,+ AddWorksheetMergeMutation,+ getAddMergeMutationRangeByType,+ IAddWorksheetMergeMutationParams,+ IRemoveWorksheetMergeMutationParams,+ ISetRangeValuesMutationParams,+ RemoveMergeUndoMutationFactory,+ RemoveWorksheetMergeMutation,+ SetRangeValuesMutation,+ SetRangeValuesUndoMutationFactory,+} from '@univerjs/base-sheets';+import { SetSelectionsOperation } from '@univerjs/base-sheets/commands/operations/selection.operation.js';+import {+ CommandType,+ ICellData,+ ICommand,+ ICommandInfo,+ ICommandService,+ IRange,+ IUndoRedoService,+ IUniverInstanceService,+ ObjectMatrix,+ ObjectMatrixPrimitiveType,+} from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++export interface IAutoFillCommandParams {+ worksheetId?: string;+ workbookId?: string;+ applyRange: IRange;+ selectionRange: IRange;+ applyDatas: ICellData[][];+ applyMergeRanges?: IRange[];+}++export const AutoFillCommand: ICommand = {+ type: CommandType.COMMAND,+ id: 'sheet.command.auto-fill',+ // eslint-disable-next-line max-lines-per-function+ handler: async (accessor: IAccessor, params?: IAutoFillCommandParams) => {+ const commandService = accessor.get(ICommandService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const undoRedoService = accessor.get(IUndoRedoService);++ const {+ applyRange,+ selectionRange,+ applyDatas,+ workbookId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId(),+ worksheetId = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId(),+ applyMergeRanges,+ } = params || {};+ if (!applyRange || !applyDatas || !selectionRange) {+ return false;+ }++ // set range value+ const cellValue = new ObjectMatrix<ICellData>();+ const { startRow, startColumn, endRow, endColumn } = applyRange;++ for (let r = 0; r <= endRow - startRow; r++) {+ for (let c = 0; c <= endColumn - startColumn; c++) {+ cellValue.setValue(r + startRow, c + startColumn, applyDatas[r][c]);+ }+ }++ const setRangeValuesMutationParams: ISetRangeValuesMutationParams = {+ range: [selectionRange],+ worksheetId,+ workbookId,+ cellValue: cellValue.getMatrix(),+ };++ const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(+ accessor,+ setRangeValuesMutationParams+ );++ const setRangeResult = commandService.syncExecuteCommand(+ SetRangeValuesMutation.id,+ setRangeValuesMutationParams+ );++ // set selection+ const selectionResult = commandService.syncExecuteCommand(SetSelectionsOperation.id, {+ selections: [+ {+ primary: {+ ...selectionRange,+ },+ range: {+ ...selectionRange,+ },+ },+ ],+ workbookId,+ worksheetId,+ });++ const undoSeq: ICommandInfo[] = [{ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams }];+ const redoSeq: ICommandInfo[] = [{ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams }];++ let removeMergeResult = true;+ let addMergeResult = true;++ // add worksheet merge+ if (applyMergeRanges) {+ const ranges = getAddMergeMutationRangeByType(applyMergeRanges);+ const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {+ workbookId,+ worksheetId,+ ranges,+ };+ const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(+ accessor,+ removeMergeMutationParams+ );+ removeMergeResult = commandService.syncExecuteCommand(+ RemoveWorksheetMergeMutation.id,+ removeMergeMutationParams+ );+ const addMergeMutationParams: IAddWorksheetMergeMutationParams = {+ workbookId,+ worksheetId,+ ranges,+ };+ const undoRemoveMutationParams: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(+ accessor,+ addMergeMutationParams+ );+ addMergeResult = commandService.syncExecuteCommand(AddWorksheetMergeMutation.id, addMergeMutationParams);++ undoSeq.push({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams });+ undoSeq.push({ id: RemoveWorksheetMergeMutation.id, params: undoRemoveMutationParams });+ redoSeq.push({ id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams });+ redoSeq.push({ id: AddWorksheetMergeMutation.id, params: addMergeMutationParams });+ }++ if (setRangeResult && removeMergeResult && addMergeResult && selectionResult) {+ undoRedoService.pushUndoRedo({+ unitID: workbookId,+ undoMutations: undoSeq,+ redoMutations: redoSeq,+ });++ return true;+ }+ return true;+ },+};++export interface IAutoClearContentCommand {+ clearRange: IRange;+ selectionRange: IRange;+}++export const AutoClearContentCommand: ICommand = {+ id: 'sheet.command.auto-clear-content',+ type: CommandType.COMMAND,+ handler: async (accessor: IAccessor, params: IAutoClearContentCommand) => {+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);++ const workbook = univerInstanceService.getCurrentUniverSheetInstance();+ const workbookId = workbook.getUnitId();+ const worksheet = workbook.getActiveSheet();+ const worksheetId = worksheet.getSheetId();+ const { clearRange, selectionRange } = params;++ const clearMutationParams: ISetRangeValuesMutationParams = {+ range: [clearRange],+ worksheetId,+ workbookId,+ cellValue: generateNullCellValue([clearRange]),+ };+ const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(+ accessor,+ clearMutationParams+ );+ commandService.executeCommand(SetSelectionsOperation.id, {+ selections: [+ {+ primary: {+ ...selectionRange,+ },+ range: {+ ...selectionRange,+ },+ },+ ],+ workbookId,+ worksheetId,+ });++ const result = commandService.syncExecuteCommand(SetRangeValuesMutation.id, clearMutationParams);+ if (result) {+ 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: workbookId,+ undoMutations: [{ id: SetRangeValuesMutation.id, params: undoClearMutationParams }],+ redoMutations: [{ id: SetRangeValuesMutation.id, params: clearMutationParams }],+ undo() {+ return commandService.syncExecuteCommand(SetRangeValuesMutation.id, undoClearMutationParams);+ },+ redo() {+ return commandService.syncExecuteCommand(SetRangeValuesMutation.id, clearMutationParams);+ },+ });++ return true;+ }++ return false;+ },+};++// Generate cellValue from range and set v/m to null+function generateNullCellValue(range: IRange[]): ObjectMatrixPrimitiveType<ICellData> {+ const cellValue = new ObjectMatrix<ICellData>();+ range.forEach((r: IRange) => {+ const { startRow, startColumn, endRow, endColumn } = r;+ for (let i = startRow; i <= endRow; i++) {+ for (let j = startColumn; j <= endColumn; j++) {+ cellValue.setValue(i, j, {+ v: null,+ m: null,+ });+ }+ }+ });++ return cellValue.getData();+}diff --git a/packages/ui-plugin-sheets/src/commands/commands/refill.command.ts b/packages/ui-plugin-sheets/src/commands/commands/refill.command.tsnew file mode 100644index 0000000000..7b93e18769--- /dev/null+++ b/packages/ui-plugin-sheets/src/commands/commands/refill.command.ts@@ -0,0 +1,19 @@+import { CommandType, ICommand } from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++import { IAutoFillService } from '../../services/auto-fill/auto-fill.service';+import { APPLY_TYPE } from '../../services/auto-fill/type';++interface IRefillCommandParams {+ type: APPLY_TYPE;+}++export const RefillCommand: ICommand = {+ id: 'sheet.command.refill',+ type: CommandType.COMMAND,+ handler: async (accessor: IAccessor, params: IRefillCommandParams) => {+ const autoFillService = accessor.get(IAutoFillService);+ autoFillService.setApplyType(params.type);+ return true;+ },+};diff --git a/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.ts b/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.tsnew file mode 100644index 0000000000..f61931470b--- /dev/null+++ b/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.ts@@ -0,0 +1,513 @@+import { getCellInfoInMergeData } from '@univerjs/base-render';+import {+ Direction,+ Disposable,+ ICellData,+ ICommandService,+ IRange,+ IUniverInstanceService,+ LifecycleStages,+ Nullable,+ OnLifecycle,+ toDisposable,+ Tools,+} from '@univerjs/core';++import { AutoClearContentCommand, AutoFillCommand } from '../commands/commands/auto-fill.command';+import { IAutoFillService } from '../services/auto-fill/auto-fill.service';+import { otherRule } from '../services/auto-fill/rules';+import { fillCopy, fillCopyStyles, getDataIndex, getLenS } from '../services/auto-fill/tools';+import {+ APPLY_FUNCTIONS,+ APPLY_TYPE,+ APPLY_TYPE_IN_USE,+ ICopyDataPiece,+ IRuleConfirmedData,+} from '../services/auto-fill/type';+import { IControlFillConfig, ISelectionRenderService } from '../services/selection/selection-render.service';++@OnLifecycle(LifecycleStages.Ready, AutoFillController)+export class AutoFillController extends Disposable {+ private _direction: Direction | null = null;+ private _beforeApplyData: Array<Array<Nullable<ICellData>>> = [];+ private _applyType: APPLY_TYPE_IN_USE = APPLY_TYPE.SERIES;+ private _hasFillingStyle: boolean = true;+ constructor(+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,+ @ICommandService private readonly _commandService: ICommandService,+ @IAutoFillService private readonly _autoFillService: IAutoFillService+ ) {+ super();+ this._init();+ }++ private _init() {+ this._onSelectionControlFillChanged();+ this._onApplyTypeChanged();+ [AutoFillCommand, AutoClearContentCommand].forEach((command) => {+ this.disposeWithMe(this._commandService.registerCommand(command));+ });+ }++ private _onSelectionControlFillChanged() {+ this.disposeWithMe(+ toDisposable(+ this._selectionRenderService.controlFillConfig$.subscribe((config: IControlFillConfig | null) => {+ if (!config) {+ return;+ }+ this._handleFillDrag(config.oldRange, config.newRange);+ })+ )+ );+ }++ private _handleFillDrag(sourceRange: IRange, destRange: IRange) {+ // situation 1: drag to smaller range, horizontally.+ if (destRange.endColumn < sourceRange.endColumn && destRange.endColumn > sourceRange.startColumn) {+ this._commandService.executeCommand(AutoClearContentCommand.id, {+ clearRange: {+ startRow: destRange.startRow,+ endRow: destRange.endRow,+ startColumn: destRange.endColumn + 1,+ endColumn: sourceRange.endColumn,+ },+ selectionRange: destRange,+ });+ return;+ }+ // situation 2: drag to smaller range, vertically.+ if (destRange.endRow < sourceRange.endRow && destRange.endRow > sourceRange.startRow) {+ this._commandService.executeCommand(AutoClearContentCommand.id, {+ clearRange: {+ startRow: destRange.endRow + 1,+ endRow: sourceRange.endRow,+ startColumn: destRange.startColumn,+ endColumn: destRange.endColumn,+ },+ selectionRange: destRange,+ });+ return;+ }+ // situation 3: drag to larger range, expand to fill+ this._presetAndCacheData(sourceRange, destRange);+ }++ // refill when apply type changed+ private _onApplyTypeChanged() {+ this.disposeWithMe(+ toDisposable(+ this._autoFillService.applyType$.subscribe((applyType: APPLY_TYPE | null) => {+ if (applyType === APPLY_TYPE.NO_FORMAT) {+ this._applyType = APPLY_TYPE.SERIES;+ this._hasFillingStyle = false;+ } else {+ this._applyType = applyType || APPLY_TYPE.SERIES;+ this._hasFillingStyle = true;+ }+ this._fillData();+ })+ )+ );+ }++ // calc apply data according to copy data and direction+ private _getApplyData(+ copyDataPiece: ICopyDataPiece,+ csLen: number,+ asLen: number,+ direction: Direction,+ applyType: APPLY_TYPE_IN_USE,+ hasStyle: boolean = true+ ) {+ const applyData: Array<Nullable<ICellData>> = [];+ const num = Math.floor(asLen / csLen);+ const rsd = asLen % csLen;+ const rules = this._autoFillService.getRules();++ if (!hasStyle && applyType === APPLY_TYPE.ONLY_FORMAT) {+ console.error('ERROR: only format can not be applied when hasStyle is false');+ return [];+ }++ const applyDataInTypes: { [key: string]: any[] } = {};++ rules.forEach((r) => {+ applyDataInTypes[r.type] = [];+ });++ // calc cell data to apply+ rules.forEach((r) => {+ const { type, applyFunctions: customApplyFunctions } = r;+ const copyDataInType = copyDataPiece[type];+ if (!copyDataInType) {+ return;+ }+ // copyDataInType is an array of copy-squads in same types+ // a copy-squad is an array of continuous cells that has the same type, e.g. [1, 3, 5] is a copy squad, but [1, 3, ab, 5] will be divided into two copy-squads+ copyDataInType.forEach((copySquad) => {+ const s = getLenS(copySquad.index, rsd);+ const len = copySquad.index.length * num + s;+ const arrData = this._applyFunctions(copySquad.data, len, direction, applyType, customApplyFunctions);+ const arrIndex = getDataIndex(csLen, asLen, copySquad.index);+ applyDataInTypes[type].push({ data: arrData, index: arrIndex });+ });+ });++ // calc index+ for (let x = 1; x <= asLen; x++) {+ rules.forEach((r) => {+ const { type } = r;+ const applyDataInType = applyDataInTypes[type];+ for (let y = 0; y < applyDataInType.length; y++) {+ if (x in applyDataInType[y].index) {+ applyData.push(applyDataInType[y].data[applyDataInType[y].index[x]]);+ }+ }+ });+ }++ return applyData;+ }++ private _applyFunctions(+ data: Array<Nullable<ICellData>>,+ len: number,+ direction: Direction,+ applyType: APPLY_TYPE_IN_USE,+ customApplyFunctions?: APPLY_FUNCTIONS+ ) {+ 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 (custom) {+ return custom(data, len, direction);+ }+ isReverse && data.reverse();+ return fillCopy(data, len);+ }+ if (applyType === APPLY_TYPE.SERIES) {+ const custom = customApplyFunctions?.[APPLY_TYPE.SERIES];+ if (custom) {+ return custom(data, len, direction);+ }+ isReverse && data.reverse();+ // special rules must provide custom SERIES apply functions, or will be applied as copy+ return fillCopy(data, len);+ }+ if (applyType === APPLY_TYPE.ONLY_FORMAT) {+ const custom = customApplyFunctions?.[APPLY_TYPE.ONLY_FORMAT];+ if (custom) {+ return custom(data, len, direction);+ }+ return fillCopyStyles(data, len);+ }+ }++ private _getCopyData(sourceRange: IRange, direction: Direction) {+ const {+ startRow: copyStartRow,+ startColumn: copyStartColumn,+ endRow: copyEndRow,+ endColumn: copyEndColumn,+ } = sourceRange;+ const currentCellDatas = this._univerInstanceService+ .getCurrentUniverSheetInstance()+ .getActiveSheet()+ .getCellMatrix();+ const rules = this._autoFillService.getRules();+ const copyData = [];+ const isVertical = direction === Direction.DOWN || direction === Direction.UP;+ let a1: number;+ let a2: number;+ let b1: number;+ let b2: number;+ if (isVertical) {+ a1 = copyStartColumn;+ a2 = copyEndColumn;+ b1 = copyStartRow;+ b2 = copyEndRow;+ } else {+ a1 = copyStartRow;+ a2 = copyEndRow;+ b1 = copyStartColumn;+ b2 = copyEndColumn;+ }+ for (let a = a1; a <= a2; 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 = {+ type: undefined,+ cellData: undefined,+ };+ for (let b = b1; b <= b2; b++) {+ let data: Nullable<ICellData>;+ if (isVertical) {+ data = currentCellDatas.getValue(b, a);+ } else {+ data = currentCellDatas.getValue(a, b);+ }+ const { type, isContinue } = rules.find((r) => r.match(data)) || otherRule;+ if (isContinue(prevData, data)) {+ const typeInfo = copyDataPiece[type];++ const last = typeInfo![typeInfo!.length - 1];+ last.data.push(data);+ last.index.push(b - b1 + 1);+ } else {+ const typeInfo = copyDataPiece[type];+ if (typeInfo) {+ typeInfo.push({+ data: [data],+ index: [b - b1 + 1],+ });+ } else {+ copyDataPiece[type] = [+ {+ data: [data],+ index: [b - b1 + 1],+ },+ ];+ }+ }+ prevData.type = type;+ prevData.cellData = data;+ }+ copyData.push(copyDataPiece);+ }+ return copyData;+ }++ private _getEmptyCopyDataPiece() {+ const copyDataPiece: ICopyDataPiece = {};+ this._autoFillService.getRules().forEach((r) => {+ copyDataPiece[r.type] = [];+ });+ return copyDataPiece;+ }++ private _getMergeApplyData(sourceRange: IRange, destRange: IRange, direction: Direction, csLen: number) {+ const mergeData = this._univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getMergeData();+ const applyMergeRanges = [];+ for (let i = sourceRange.startRow; i <= sourceRange.endRow; i++) {+ for (let j = sourceRange.startColumn; j <= sourceRange.endColumn; j++) {+ const { isMergedMainCell, startRow, startColumn, endRow, endColumn } = getCellInfoInMergeData(+ i,+ j,+ mergeData+ );+ if (isMergedMainCell) {+ if (direction === Direction.DOWN) {+ let windowStartRow = startRow + csLen;+ let windowEndRow = endRow + csLen;+ while (windowEndRow <= destRange.endRow) {+ applyMergeRanges.push({+ startRow: windowStartRow,+ startColumn,+ endRow: windowEndRow,+ endColumn,+ });+ windowStartRow += csLen;+ windowEndRow += csLen;+ }+ } else if (direction === Direction.UP) {+ let windowStartRow = startRow - csLen;+ let windowEndRow = endRow - csLen;+ while (windowStartRow >= destRange.startRow) {+ applyMergeRanges.push({+ startRow: windowStartRow,+ startColumn,+ endRow: windowEndRow,+ endColumn,+ });+ windowStartRow -= csLen;+ windowEndRow -= csLen;+ }+ } else if (direction === Direction.RIGHT) {+ let windowStartColumn = startColumn + csLen;+ let windowEndColumn = endColumn + csLen;+ while (windowEndColumn <= destRange.endColumn) {+ applyMergeRanges.push({+ startRow,+ startColumn: windowStartColumn,+ endRow,+ endColumn: windowEndColumn,+ });+ windowStartColumn += csLen;+ windowEndColumn += csLen;+ }+ } else if (direction === Direction.LEFT) {+ const windowStartColumn = startColumn - csLen;+ const windowEndColumn = endColumn - csLen;+ while (windowStartColumn >= destRange.startColumn) {+ applyMergeRanges.push({+ startRow,+ startColumn: windowStartColumn,+ endRow,+ endColumn: windowEndColumn,+ });+ }+ }+ }+ }+ }+ return applyMergeRanges;+ }++ private _presetAndCacheData(sourceRange: IRange, destRange: IRange) {+ // save ranges+ const applyRange = {+ startRow: destRange.startRow,+ endRow: destRange.endRow,+ startColumn: destRange.startColumn,+ endColumn: destRange.endColumn,+ };+ let direction = null;+ if (destRange.startRow < sourceRange.startRow) {+ direction = Direction.UP;+ applyRange.endRow = sourceRange.startRow - 1;+ } else if (destRange.endRow > sourceRange.endRow) {+ direction = Direction.DOWN;+ applyRange.startRow = sourceRange.endRow + 1;+ } else if (destRange.startColumn < sourceRange.startColumn) {+ direction = Direction.LEFT;+ applyRange.endColumn = sourceRange.startColumn - 1;+ } else if (destRange.endColumn > sourceRange.endColumn) {+ direction = Direction.RIGHT;+ applyRange.startColumn = sourceRange.endColumn + 1;+ }+ this._direction = direction;++ // cache original data of apply range+ const currentCellDatas = this._univerInstanceService+ .getCurrentUniverSheetInstance()+ .getActiveSheet()+ .getCellMatrix();+ // cache the original data in currentCellDatas in apply range for later use / refill+ const applyData = [];+ for (let i = applyRange.startRow; i <= applyRange.endRow; i++) {+ const row = [];+ for (let j = applyRange.startColumn; j <= applyRange.endColumn; j++) {+ row.push(Tools.deepClone(currentCellDatas.getValue(i, j)));+ }+ applyData.push(row);+ }+ this._beforeApplyData = applyData;+ this._autoFillService.setRanges(destRange, sourceRange, applyRange);+ this._autoFillService.setApplyType(APPLY_TYPE.SERIES);+ }++ // auto fill entry+ private _fillData() {+ const { destRange, sourceRange, applyRange } = this._autoFillService.getRanges();+ const applyType = this._applyType;+ const hasStyle = this._hasFillingStyle;+ const direction = this._direction;++ if (!destRange || !sourceRange || !applyRange || direction == null) {+ return;+ }++ const {+ startRow: copyStartRow,+ startColumn: copyStartColumn,+ endRow: copyEndRow,+ endColumn: copyEndColumn,+ } = sourceRange;++ const {+ startRow: applyStartRow,+ startColumn: applyStartColumn,+ endRow: applyEndRow,+ endColumn: applyEndColumn,+ } = applyRange;++ const copyData = this._getCopyData(sourceRange, direction);++ let csLen;+ if (direction === Direction.DOWN || direction === Direction.UP) {+ csLen = copyEndRow - copyStartRow + 1;+ } else {+ csLen = copyEndColumn - copyStartColumn + 1;+ }++ const applyDatas: Array<Array<Nullable<ICellData>>> = [];++ if (direction === Direction.DOWN || direction === Direction.UP) {+ const asLen = applyEndRow - applyStartRow + 1;+ const untransformedApplyDatas = [];+ for (let i = applyStartColumn; i <= applyEndColumn; i++) {+ const copyD = copyData[i - applyStartColumn];++ const applyData = this._getApplyData(copyD, csLen, asLen, direction, applyType, hasStyle);+ untransformedApplyDatas.push(applyData);+ }+ for (let i = 0; i < untransformedApplyDatas[0].length; i++) {+ const row: Array<Nullable<ICellData>> = [];+ for (let j = 0; j < untransformedApplyDatas.length; j++) {+ row.push({+ v: null,+ m: null,+ s: null,+ ...this._beforeApplyData[i][j],+ ...untransformedApplyDatas[j][i],+ });+ }+ applyDatas.push(row);+ }+ } else {+ const asLen = applyEndColumn - applyStartColumn + 1;+ for (let i = applyStartRow; i <= applyEndRow; i++) {+ const copyD = copyData[i - applyStartRow];+ const applyData = this._getApplyData(copyD, csLen, asLen, direction, applyType, hasStyle);+ const row: Array<Nullable<ICellData>> = [];+ for (let j = 0; j < applyData.length; j++) {+ row.push({+ v: null,+ m: null,+ s: null,+ ...this._beforeApplyData[i - applyStartRow][j],+ ...applyData[j],+ });+ }+ applyDatas.push(row);+ }+ }++ // deal with styles+ let applyMergeRanges;+ const style = this._univerInstanceService.getCurrentUniverSheetInstance().getStyles();+ if (hasStyle) {+ applyMergeRanges = this._getMergeApplyData(sourceRange, destRange, direction, csLen);+ applyDatas.forEach((row) => {+ row.forEach((cellData) => {+ if (cellData && style) {+ if (style) {+ cellData.s = style.getStyleByCell(cellData);+ }+ }+ });+ });+ } else {+ applyDatas.forEach((row, rowIndex) => {+ row.forEach((cellData, colIndex) => {+ if (cellData && style) {+ cellData.s = style.getStyleByCell(this._beforeApplyData[rowIndex][colIndex]) || null;+ }+ });+ });+ }++ this._commandService.executeCommand(AutoFillCommand.id, {+ selectionRange: destRange,+ applyRange,+ applyDatas,+ workbookId: this._univerInstanceService.getCurrentUniverSheetInstance().getUnitId(),+ worksheetId: this._univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId(),+ applyMergeRanges,+ });+ }+}diff --git a/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts b/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.tsindex f2dbecb3e1..1a055b6c18 100644--- a/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts+++ b/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts@@ -28,6 +28,7 @@ import {SetRangeTextColorCommand,SetRangeUnderlineCommand,} from '../commands/commands/inline-format.command';+import { RefillCommand } from '../commands/commands/refill.command';import { RenameSheetOperation } from '../commands/commands/rename.command';import {SetCopySelectionCommand,@@ -229,6 +230,7 @@ export class SheetUIController extends Disposable {SetZoomRatioCommand,SetZoomRatioOperation,ShowMenuListCommand,+ RefillCommand,].forEach((c) => {this.disposeWithMe(this._commandService.registerCommand(c));});diff --git a/packages/ui-plugin-sheets/src/services/auto-fill/auto-fill.service.ts b/packages/ui-plugin-sheets/src/services/auto-fill/auto-fill.service.tsnew file mode 100644index 0000000000..0fa08430cb--- /dev/null+++ b/packages/ui-plugin-sheets/src/services/auto-fill/auto-fill.service.ts@@ -0,0 +1,85 @@+import { SelectionManagerService } from '@univerjs/base-sheets';+import {+ Disposable,+ IRange,+ IUniverInstanceService,+ LifecycleStages,+ OnLifecycle,+ SheetInterceptorService,+} from '@univerjs/core';+import { createIdentifier, Inject } from '@wendellhu/redi';+import { BehaviorSubject, Observable } from 'rxjs';++import { chnNumberRule, chnWeek2Rule, chnWeek3Rule, extendNumberRule, numberRule, otherRule } from './rules';+import { APPLY_TYPE, IAutoFillRule } from './type';++export interface IAutoFillService {+ getRules(): IAutoFillRule[];+ getApplyType(): APPLY_TYPE;+ isFillingStyle(): boolean;+ setApplyType(type: APPLY_TYPE): void;+ setRanges(sourceRange: IRange, destRange: IRange, applyRange: IRange): void;+ getRanges(): { sourceRange: IRange | null; destRange: IRange | null; applyRange: IRange | null };+ setFillingStyle(isFillingStyle: boolean): void;+ applyType$: Observable<APPLY_TYPE>;+}+@OnLifecycle(LifecycleStages.Rendered, AutoFillService)+export class AutoFillService extends Disposable implements IAutoFillService {+ private _rules: IAutoFillRule[] = [];+ private readonly _applyType$: BehaviorSubject<APPLY_TYPE> = new BehaviorSubject<APPLY_TYPE>(APPLY_TYPE.SERIES);+ private _isFillingStyle: boolean = true;+ private _sourceRange: IRange | null = null;+ private _destRange: IRange | null = null;+ private _applyRange: IRange | null = null;+ readonly applyType$ = this._applyType$.asObservable();+ constructor(+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,+ @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,+ @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService+ ) {+ super();+ this._init();+ }++ private _init() {+ this._rules = [numberRule, extendNumberRule, chnNumberRule, chnWeek2Rule, chnWeek3Rule, otherRule];+ // this._applyType = APPLY_TYPE.SERIES;+ this._isFillingStyle = true;+ }++ getRules() {+ return this._rules;+ }++ getApplyType() {+ return this._applyType$.getValue();+ }++ setApplyType(type: APPLY_TYPE) {+ this._applyType$.next(type);+ }++ isFillingStyle(): boolean {+ return this._isFillingStyle;+ }++ setFillingStyle(isFillingStyle: boolean) {+ this._isFillingStyle = isFillingStyle;+ }++ setRanges(destRange: IRange, sourceRange: IRange, applyRange: IRange) {+ this._sourceRange = sourceRange;+ this._destRange = destRange;+ this._applyRange = applyRange;+ }++ getRanges() {+ return {+ sourceRange: this._sourceRange,+ destRange: this._destRange,+ applyRange: this._applyRange,+ };+ }+}++export const IAutoFillService = createIdentifier<AutoFillService>('univer.auto-fill-service');diff --git a/packages/ui-plugin-sheets/src/services/auto-fill/rules.ts b/packages/ui-plugin-sheets/src/services/auto-fill/rules.tsnew file mode 100644index 0000000000..92a4c34cdb--- /dev/null+++ b/packages/ui-plugin-sheets/src/services/auto-fill/rules.ts@@ -0,0 +1,275 @@+import { Direction } from '@univerjs/core';++import {+ chineseToNumber,+ fillChnNumber,+ fillChnWeek,+ fillCopy,+ fillExtendNumber,+ fillSeries,+ isChnNumber,+ isChnWeek2,+ isEqualDiff,+ matchExtendNumber,+} from './tools';+import { APPLY_TYPE, DATA_TYPE, IAutoFillRule } from './type';++export const numberRule: IAutoFillRule = {+ type: DATA_TYPE.NUMBER,+ match: (cellData) => typeof cellData?.v === 'number',+ isContinue: (prev, cur) => {+ if (prev.type === DATA_TYPE.NUMBER) {+ return true;+ }+ return false;+ },+ applyFunctions: {+ [APPLY_TYPE.SERIES]: (data, len, direction) => {+ if (direction === Direction.LEFT || direction === Direction.UP) {+ data.reverse();+ }+ return fillSeries(data, len, direction);+ },+ },+};++export const otherRule: IAutoFillRule = {+ type: DATA_TYPE.OTHER,+ match: () => true,+ isContinue: (prev, cur) => {+ if (prev.type === DATA_TYPE.OTHER) {+ return true;+ }+ return false;+ },+};++export const extendNumberRule: IAutoFillRule = {+ type: DATA_TYPE.EXTEND_NUMBER,+ match: (cellData) => matchExtendNumber(cellData?.m || '').isExtendNumber,+ isContinue: (prev, cur) => {+ if (prev.type === DATA_TYPE.EXTEND_NUMBER) {+ const { beforeTxt, afterTxt } = matchExtendNumber(prev.cellData?.m || '');+ const { beforeTxt: curBeforeTxt, afterTxt: curAfterTxt } = matchExtendNumber(cur?.m || '');+ if (beforeTxt === curBeforeTxt && afterTxt === curAfterTxt) {+ return true;+ }+ }+ return false;+ },+ applyFunctions: {+ [APPLY_TYPE.SERIES]: (data, len, direction) => {+ let step;+ if (data.length === 1) {+ step = direction === Direction.DOWN || direction === Direction.RIGHT ? 1 : -1;+ return fillExtendNumber(data, len, step);+ }+ const dataNumArr = [];++ for (let i = 0; i < data.length; i++) {+ const txt = data[i]?.m;+ txt && dataNumArr.push(Number(matchExtendNumber(txt).matchTxt));+ }++ if (direction === Direction.UP || direction === Direction.LEFT) {+ data.reverse();+ dataNumArr.reverse();+ }++ if (isEqualDiff(dataNumArr)) {+ step = dataNumArr[1] - dataNumArr[0];+ return fillExtendNumber(data, len, step);+ }+ return fillCopy(data, len);+ },+ },+};++export const chnNumberRule: IAutoFillRule = {+ type: DATA_TYPE.CHN_NUMBER,+ match: (cellData) => {+ if (isChnNumber(cellData?.m || '')) {+ return true;+ }+ return false;+ },+ isContinue: (prev, cur) => {+ if (prev.type === DATA_TYPE.CHN_NUMBER) {+ return true;+ }+ return false;+ },+ applyFunctions: {+ [APPLY_TYPE.SERIES]: (data, len, direction) => {+ const isReverse = direction === Direction.LEFT || direction === Direction.UP;+ if (data.length === 1) {+ const formattedValue = data[0]?.m;+ let step;+ if (!isReverse) {+ step = 1;+ } else {+ step = -1;+ }+ if (formattedValue && (formattedValue === '日' || chineseToNumber(formattedValue) < 7)) {+ return fillChnWeek(data, len, step);+ }++ return fillChnNumber(data, len, step);+ }+ let hasWeek = false;+ for (let i = 0; i < data.length; i++) {+ const formattedValue = data[i]?.m;++ if (formattedValue === '日') {+ hasWeek = true;+ break;+ }+ }++ const dataNumArr = [];+ let weekIndex = 0;+ for (let i = 0; i < data.length; i++) {+ const formattedValue = data[i]?.m;+ if (formattedValue === '日') {+ if (i === 0) {+ dataNumArr.push(0);+ } else {+ weekIndex++;+ dataNumArr.push(weekIndex * 7);+ }+ } else if (hasWeek && chineseToNumber(formattedValue) > 0 && chineseToNumber(formattedValue) < 7) {+ dataNumArr.push(chineseToNumber(formattedValue) + weekIndex * 7);+ } else {+ dataNumArr.push(chineseToNumber(formattedValue));+ }+ }++ if (isReverse) {+ data.reverse();+ dataNumArr.reverse();+ }++ if (isEqualDiff(dataNumArr)) {+ if (+ hasWeek ||+ (dataNumArr[dataNumArr.length - 1] < 6 && dataNumArr[0] > 0) ||+ (dataNumArr[0] < 6 && dataNumArr[dataNumArr.length - 1] > 0)+ ) {+ // Fill with sequence of Monday~Sunday+ const step = dataNumArr[1] - dataNumArr[0];+ return fillChnWeek(data, len, step);+ }+ // Fill with sequence of Chinese lowercase numbers+ const step = dataNumArr[1] - dataNumArr[0];+ return fillChnNumber(data, len, step);+ }+ // Not an arithmetic progression, copy data+ return fillCopy(data, len);+ },+ },+};++export const chnWeek2Rule: IAutoFillRule = {+ type: DATA_TYPE.CHN_WEEK2,+ match: (cellData) => {+ if (isChnWeek2(cellData?.m || '')) {+ return true;+ }+ return false;+ },+ isContinue: (prev, cur) => prev.type === DATA_TYPE.CHN_WEEK2,+ applyFunctions: {+ [APPLY_TYPE.SERIES]: (data, len, direction) => {+ const isReverse = direction === Direction.LEFT || direction === Direction.UP;+ if (data.length === 1) {+ let step;+ if (!isReverse) {+ step = 1;+ } else {+ step = -1;+ }++ return fillChnWeek(data, len, step, 1);+ }+ const dataNumArr = [];+ let weekIndex = 0;++ for (let i = 0; i < data.length; i++) {+ const formattedValue = data[i]?.m;+ const lastTxt = formattedValue?.substr(formattedValue.length - 1, 1);+ if (formattedValue === '周日') {+ if (i === 0) {+ dataNumArr.push(0);+ } else {+ weekIndex++;+ dataNumArr.push(weekIndex * 7);+ }+ } else {+ dataNumArr.push(chineseToNumber(lastTxt) + weekIndex * 7);+ }+ }++ if (isReverse) {+ data.reverse();+ dataNumArr.reverse();+ }++ if (isEqualDiff(dataNumArr)) {+ const step = dataNumArr[1] - dataNumArr[0];+ return fillChnWeek(data, len, step, 1);+ }+ return fillCopy(data, len);+ },+ },+};++export const chnWeek3Rule: IAutoFillRule = {+ type: DATA_TYPE.CHN_WEEK3,+ match: (cellData) => isChnWeek2(cellData?.m || ''),+ isContinue: (prev, cur) => prev.type === DATA_TYPE.CHN_WEEK3,+ applyFunctions: {+ [APPLY_TYPE.SERIES]: (data, len, direction) => {+ const isReverse = direction === Direction.LEFT || direction === Direction.UP;+ if (data.length === 1) {+ let step;+ if (!isReverse) {+ step = 1;+ } else {+ step = -1;+ }++ return fillChnWeek(data, len, step, 2);+ }+ const dataNumArr = [];+ let weekIndex = 0;++ for (let i = 0; i < data.length; i++) {+ const formattedValue = data[i]?.m;+ if (formattedValue) {+ const lastTxt = formattedValue.substr(formattedValue.length - 1, 1);+ if (formattedValue === '星期日') {+ if (i === 0) {+ dataNumArr.push(0);+ } else {+ weekIndex++;+ dataNumArr.push(weekIndex * 7);+ }+ } else {+ dataNumArr.push(chineseToNumber(lastTxt) + weekIndex * 7);+ }+ }+ }++ if (isReverse) {+ data.reverse();+ dataNumArr.reverse();+ }++ if (isEqualDiff(dataNumArr)) {+ const step = dataNumArr[1] - dataNumArr[0];+ return fillChnWeek(data, len, step, 2);+ }+ return fillCopy(data, len);+ },+ },+};diff --git a/packages/ui-plugin-sheets/src/services/auto-fill/tools.ts b/packages/ui-plugin-sheets/src/services/auto-fill/tools.tsnew file mode 100644index 0000000000..a69c578646--- /dev/null+++ b/packages/ui-plugin-sheets/src/services/auto-fill/tools.ts@@ -0,0 +1,562 @@+import { Direction, ICellData, Nullable, Tools } from '@univerjs/core';++import { DATA_TYPE, ICopyDataPiece } from './type';++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;+}++export type ICopyDataInTypeIndexInfo = number[];++export const chnNameValue = {+ 十: { value: 10, secUnit: false },+ 百: { value: 100, secUnit: false },+ 千: { value: 1000, secUnit: false },+ 万: { value: 10000, secUnit: true },+ 亿: { value: 100000000, secUnit: true },+};++export function getEmptyCopyDataPiece(): ICopyDataPiece {+ return {+ [DATA_TYPE.NUMBER]: [],+ [DATA_TYPE.DATE]: [],+ [DATA_TYPE.EXTEND_NUMBER]: [],+ [DATA_TYPE.CHN_NUMBER]: [],+ [DATA_TYPE.CHN_WEEK2]: [],+ [DATA_TYPE.CHN_WEEK3]: [],+ [DATA_TYPE.OTHER]: [],+ };+}+export function chineseToNumber(chnStr?: Nullable<string>) {+ if (!chnStr) {+ return 0;+ }+ let rtn = 0;+ let section = 0;+ let number = 0;+ let secUnit = false;+ const str = chnStr.split('');++ for (let i = 0; i < str.length; i++) {+ const num = chnNumChar[str[i] as keyof typeof chnNumChar];++ if (typeof num !== 'undefined') {+ number = num;++ if (i === str.length - 1) {+ section += number;+ }+ } else {+ const obj = chnNameValue[str[i] as keyof typeof chnNameValue];+ const unit = obj.value;+ secUnit = obj.secUnit;++ if (secUnit) {+ section = (section + number) * unit;+ rtn += section;+ section = 0;+ } else {+ section += number * unit;+ }++ number = 0;+ }+ }++ return rtn + section;+}++export function sectionToChinese(section: number) {+ let strIns = '';+ let chnStr = '';+ let unitPos = 0;+ let zero = true;++ while (section > 0) {+ const v = section % 10;++ if (v === 0) {+ if (!zero) {+ zero = true;+ chnStr = chnNumChar2[v] + chnStr;+ }+ } else {+ zero = false;+ strIns = chnNumChar2[v];+ strIns += chnUnitChar[unitPos];+ chnStr = strIns + chnStr;+ }++ unitPos++;+ section = Math.floor(section / 10);+ }++ return chnStr;+}++export function numberToChinese(num: number) {+ let unitPos = 0;+ let strIns = '';+ let chnStr = '';+ let needZero = false;++ if (num === 0) {+ return chnNumChar2[0];+ }+ while (num > 0) {+ const section = num % 10000;++ if (needZero) {+ chnStr = chnNumChar2[0] + chnStr;+ }++ strIns = sectionToChinese(section);+ strIns += section !== 0 ? chnUnitSection[unitPos] : chnUnitSection[0];+ chnStr = strIns + chnStr;+ needZero = section < 1000 && section > 0;+ num = Math.floor(num / 10000);+ unitPos++;+ }++ return chnStr;+}++export function isChnNumber(txt?: string) {+ if (!txt) {+ return false;+ }+ let isChnNumber = true;++ if (txt) {+ if (txt.length === 1) {+ if (txt === '日' || txt in chnNumChar) {+ isChnNumber = true;+ } else {+ isChnNumber = false;+ }+ } else {+ const str = txt.split('');+ for (let i = 0; i < str.length; i++) {+ if (!(str[i] in chnNumChar || str[i] in chnNameValue)) {+ isChnNumber = false;+ break;+ }+ }+ }+ }+ return isChnNumber;+}++export function matchExtendNumber(txt?: string) {+ if (!txt) {+ return {+ isExtendNumber: false,+ };+ }+ const reg = /0|([1-9]+[0-9]*)/g;+ const isExtendNumber = reg.test(txt);++ if (isExtendNumber) {+ const match = txt.match(reg);+ if (match && match.length > 0) {+ const matchTxt = match[match.length - 1];+ const matchIndex = txt.lastIndexOf(matchTxt);+ const beforeTxt = txt.substr(0, matchIndex);+ const afterTxt = txt.substr(matchIndex + matchTxt.length);++ return {+ isExtendNumber: true,+ matchTxt: Number(matchTxt),+ beforeTxt,+ afterTxt,+ };+ }+ return {+ isExtendNumber: false,+ };+ }++ return {+ isExtendNumber,+ };+}++export function isChnWeek1(txt: string) {+ let isChnWeek1;+ if (txt.length === 1) {+ if (txt === '日' || chineseToNumber(txt) < 7) {+ isChnWeek1 = true;+ } else {+ isChnWeek1 = false;+ }+ } else {+ isChnWeek1 = false;+ }++ return isChnWeek1;+}++export function isChnWeek2(txt: string) {+ let isChnWeek2;+ if (txt.length === 2) {+ if (+ txt === '周一' ||+ txt === '周二' ||+ txt === '周三' ||+ txt === '周四' ||+ txt === '周五' ||+ txt === '周六' ||+ txt === '周日'+ ) {+ isChnWeek2 = true;+ } else {+ isChnWeek2 = false;+ }+ } else {+ isChnWeek2 = false;+ }++ return isChnWeek2;+}++export function isChnWeek3(txt: string) {+ let isChnWeek3;+ if (txt.length === 3) {+ if (+ txt === '星期一' ||+ txt === '星期二' ||+ txt === '星期三' ||+ txt === '星期四' ||+ txt === '星期五' ||+ txt === '星期六' ||+ txt === '星期日'+ ) {+ isChnWeek3 = true;+ } else {+ isChnWeek3 = false;+ }+ } else {+ isChnWeek3 = false;+ }++ return isChnWeek3;+}++export function getLenS(indexArr: any[], rsd: number) {+ let s = 0;++ for (let j = 0; j < indexArr.length; j++) {+ if (indexArr[j] <= rsd) {+ s++;+ } else {+ break;+ }+ }++ return s;+}++/**+ * equal diff+ * @param arr+ * @returns+ */+export function isEqualDiff(arr: number[]) {+ let diff = true;+ const step = arr[1] - arr[0];++ for (let i = 1; i < arr.length; i++) {+ if (arr[i] - arr[i - 1] !== step) {+ diff = false;+ break;+ }+ }++ return diff;+}++export function getDataIndex(csLen: number, asLen: number, indexArr: number[]) {+ const obj: ICopyDataInTypeIndexInfo = [];++ const num = Math.floor(asLen / csLen);+ const rsd = asLen % csLen;++ let sum = 0;+ if (num > 0) {+ for (let i = 1; i <= num; i++) {+ for (let j = 0; j < indexArr.length; j++) {+ obj[indexArr[j] + (i - 1) * csLen] = sum;+ sum++;+ }+ }+ for (let a = 0; a < indexArr.length; a++) {+ if (indexArr[a] <= rsd) {+ obj[indexArr[a] + csLen * num] = sum;+ sum++;+ } else {+ break;+ }+ }+ } else {+ for (let a = 0; a < indexArr.length; a++) {+ if (indexArr[a] <= rsd) {+ obj[indexArr[a]] = sum;+ sum++;+ } else {+ break;+ }+ }+ }++ return obj;+}++export function fillCopy(data: Array<Nullable<ICellData>>, len: number) {+ const applyData = [];++ for (let i = 1; i <= len; i++) {+ const index = (i - 1) % data.length;+ const d = Tools.deepClone(data[index]);++ applyData.push(d);+ }++ return applyData;+}++export function fillCopyStyles(data: Array<Nullable<ICellData>>, len: number) {+ const applyData = [];+ for (let i = 1; i <= len; i++) {+ const index = (i - 1) % data.length;+ const d = { s: data[index]?.s };++ applyData.push(d);+ }++ return applyData;+}++export function isEqualRatio(arr: number[]) {+ let ratio = true;+ const step = arr[1] / arr[0];++ for (let i = 1; i < arr.length; i++) {+ if (arr[i] / arr[i - 1] !== step) {+ ratio = false;+ break;+ }+ }++ return ratio;+}++export function getXArr(len: number) {+ const xArr = [];++ for (let i = 1; i <= len; i++) {+ xArr.push(i);+ }++ return xArr;+}++export function fillSeries(data: Array<Nullable<ICellData>>, len: number, direction: Direction) {+ const applyData = [];++ const dataNumArr = [];+ for (let j = 0; j < data.length; j++) {+ dataNumArr.push(Number(data[j]?.v));+ }++ if (data.length > 2 && isEqualRatio(dataNumArr)) {+ for (let i = 1; i <= len; i++) {+ const index = (i - 1) % data.length;+ const d = Tools.deepClone(data[index]);++ let num;+ if (direction === Direction.DOWN || direction === Direction.RIGHT) {+ num = Number(data[data.length - 1]?.v) * (Number(data[1]?.v) / Number(data[0]?.v)) ** i;+ } else if (direction === Direction.UP || direction === Direction.LEFT) {+ num = Number(data[0]?.v) / (Number(data[1]?.v) / Number(data[0]?.v)) ** i;+ }++ if (d) {+ d.v = num;+ d.m = `${num}`;+ applyData.push(d);+ }+ }+ } else {+ const xArr = getXArr(data.length);+ for (let i = 1; i <= len; i++) {+ const index = (i - 1) % data.length;+ const d = Tools.deepClone(data[index]);++ let y;+ if (direction === Direction.DOWN || direction === Direction.RIGHT) {+ y = forecast(data.length + i, dataNumArr, xArr);+ } else {+ y = forecast(1 - i, dataNumArr, xArr);+ }++ if (d) {+ d.v = y;+ d.m = `${y}`;+ applyData.push(d);+ }+ }+ }+ return applyData;+}++export function forecast(x: number, yArr: number[], xArr: number[]) {+ function getAverage(arr: number[]) {+ let sum = 0;++ for (let i = 0; i < arr.length; i++) {+ sum += arr[i];+ }++ return sum / arr.length;+ }++ const ax = getAverage(xArr);+ const ay = getAverage(yArr);++ let sum_d = 0;+ let sum_n = 0;+ for (let j = 0; j < xArr.length; j++) {+ sum_d += (xArr[j] - ax) * (yArr[j] - ay);+ sum_n += (xArr[j] - ax) * (xArr[j] - ax);+ }++ let b;+ if (sum_n === 0) {+ b = 1;+ } else {+ b = sum_d / sum_n;+ }++ const a = ay - b * ax;++ return Math.round((a + b * x) * 100000) / 100000;+}++export function fillExtendNumber(data: Array<Nullable<ICellData>>, len: number, step: number) {+ const applyData = [];+ const reg = /0|([1-9]+[0-9]*)/g;++ for (let i = 1; i <= len; i++) {+ const index = (i - 1) % data.length;+ const d = Tools.deepClone(data[index]);++ const last = data[data.length - 1]?.m;+ const match = last?.match(reg);+ const lastTxt = match?.[match.length - 1];++ const num = Math.abs(Number(lastTxt) + step * i);+ if (!last || !lastTxt) continue;+ const lastIndex = last.lastIndexOf(lastTxt);+ const valueTxt = last.substr(0, lastIndex) + num.toString() + last.substr(lastIndex + lastTxt.length);++ if (d) {+ d.v = valueTxt;+ d.m = valueTxt;++ applyData.push(d);+ }+ }++ return applyData;+}+export function fillOnlyFormat(data: Array<Nullable<ICellData>>, len: number) {+ const applyData = [];++ for (let i = 1; i <= len; i++) {+ const index = (i - 1) % data.length;+ const d = Tools.deepClone(data[index]);++ if (d) {+ delete d.m;+ delete d.v;++ applyData.push(d);+ }+ }++ return applyData;+}++// weektype: 0-日 1-周 2-星期+export function fillChnWeek(data: Array<Nullable<ICellData>>, len: number, step: number, weekType: number = 0) {+ const keywordMap = [+ ['日', '一', '二', '三', '四', '五', '六'],+ ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],+ ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五'],+ ];+ if (weekType >= keywordMap.length) return [];+ const keyword = keywordMap[weekType];+ const applyData = [];++ for (let i = 1; i <= len; i++) {+ const index = (i - 1) % data.length;+ const d = Tools.deepClone(data[index]);++ let num = 0;+ if (data[data.length - 1]?.m === keyword[0]) {+ num = 7 + step * i;+ } else {+ const last = data[data.length - 1]?.m;+ if (last) {+ const txt = last.substr(last.length - 1, 1);+ num = chineseToNumber(txt) + step * i;+ }+ }++ if (num < 0) {+ num = Math.ceil(Math.abs(num) / 7) * 7 + num;+ }++ const rsd = num % 7;+ if (d) {+ d.m = keyword[rsd];+ d.v = keyword[rsd];++ applyData.push(d);+ }+ }++ return applyData;+}++export function fillChnNumber(data: Array<Nullable<ICellData>>, len: number, step: number) {+ const applyData = [];++ for (let i = 1; i <= len; i++) {+ const index = (i - 1) % data.length;+ const d = Tools.deepClone(data[index]);++ const formattedValue = data[data.length - 1]?.m;+ const num = chineseToNumber(formattedValue) + step * i;+ let txt;+ if (num <= 0) {+ txt = '零';+ } else {+ txt = numberToChinese(num);+ }++ if (d) {+ d.v = txt;+ d.m = txt.toString();+ applyData.push(d);+ }+ }++ return applyData;+}diff --git a/packages/ui-plugin-sheets/src/services/auto-fill/type.ts b/packages/ui-plugin-sheets/src/services/auto-fill/type.tsnew file mode 100644index 0000000000..e001ea1af4--- /dev/null+++ b/packages/ui-plugin-sheets/src/services/auto-fill/type.ts@@ -0,0 +1,51 @@+import { Direction, ICellData, Nullable } from '@univerjs/core';++export enum DATA_TYPE {+ NUMBER = 'number',+ DATE = 'date',+ EXTEND_NUMBER = 'extendNumber',+ CHN_NUMBER = 'chnNumber',+ CHN_WEEK2 = 'chnWeek2',+ CHN_WEEK3 = 'chnWeek3',+ OTHER = 'other',+}++export type ICopyDataPiece = {+ [key in DATA_TYPE]?: ICopyDataInType[];+};++export interface ICopyDataInType {+ data: Array<Nullable<ICellData>>;+ index: ICopyDataInTypeIndexInfo;+}++export type ICopyDataInTypeIndexInfo = number[];++export interface IAutoFillRule {+ type: DATA_TYPE;+ match: (cellData: Nullable<ICellData>) => boolean;+ isContinue: (prev: IRuleConfirmedData, cur: Nullable<ICellData>) => boolean;+ applyFunctions?: APPLY_FUNCTIONS;+}++export interface IRuleConfirmedData {+ type?: DATA_TYPE;+ cellData: Nullable<ICellData>;+}++export type APPLY_FUNCTIONS = {+ [key in APPLY_TYPE]?: (+ data: Array<Nullable<ICellData>>,+ len: number,+ direction: Direction+ ) => Array<Nullable<ICellData>>;+};++export enum APPLY_TYPE {+ COPY = '0',+ SERIES = '1',+ ONLY_FORMAT = '2',+ NO_FORMAT = '3',+}++export type APPLY_TYPE_IN_USE = Omit<APPLY_TYPE, APPLY_TYPE.NO_FORMAT>;diff --git a/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts b/packages/ui-plugin-sheets/src/services/selection/selection-render.service.tsindex 13a1f15c2e..4980b02192 100644--- a/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts+++ b/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts@@ -32,8 +32,14 @@ import { SelectionRenderModel } from './selection-render-model';import { SelectionShape } from './selection-shape';import { SelectionShapeExtension } from './selection-shape-extension';+export interface IControlFillConfig {+ oldRange: IRange;+ newRange: IRange;+}+export interface ISelectionRenderService {readonly selectionRangeWithStyle$: Observable<ISelectionWithCoordAndStyle[]>;+ readonly controlFillConfig$: Observable<IControlFillConfig | null>;enableHeaderHighlight(): void;disableHeaderHighlight(): void;@@ -80,6 +86,10 @@ export class SelectionRenderService implements ISelectionRenderService {private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;+ private _controlFillConfig$: BehaviorSubject<IControlFillConfig | null> =+ new BehaviorSubject<IControlFillConfig | null>(null);+ readonly controlFillConfig$ = this._controlFillConfig$.asObservable();+private _selectionControls: SelectionShape[] = []; // sheetID:Controlsprivate _startSelectionRange: IRangeWithCoord = {@@ -217,6 +227,42 @@ export class SelectionRenderService implements ISelectionRenderService {} else {control.disableHeaderHighlight();}+ // update drag observer+ control.selectionFilled$.subscribe((filled) => {+ if (filled == null) {+ return;+ }+ const { startColumn, endColumn, startRow, endRow } = control.model;+ const {+ startColumn: newStartColumn,+ endColumn: newEndColumn,+ startRow: newStartRow,+ endRow: newEndRow,+ } = filled || {};+ // if no change happened, return+ if (+ startColumn === newStartColumn &&+ endColumn === newEndColumn &&+ startRow === newStartRow &&+ endRow === newEndRow+ ) {+ return;+ }+ this._controlFillConfig$.next({+ oldRange: {+ startColumn,+ endColumn,+ startRow,+ endRow,+ },+ newRange: {+ startColumn: newStartColumn || startColumn,+ endColumn: newEndColumn || endColumn,+ startRow: newStartRow || startRow,+ endRow: newEndRow || endRow,+ },+ });+ });currentControls.push(control);}diff --git a/packages/ui-plugin-sheets/src/services/selection/selection-shape-extension.ts b/packages/ui-plugin-sheets/src/services/selection/selection-shape-extension.tsindex 69c4ccb323..11acce0fdc 100644--- a/packages/ui-plugin-sheets/src/services/selection/selection-shape-extension.ts+++ b/packages/ui-plugin-sheets/src/services/selection/selection-shape-extension.ts@@ -759,7 +759,7 @@ export class SelectionShapeExtension {this._clearObserverEvent();scene.enableEvent();this._scrollTimer?.dispose();- this._control.selectionFilled$.next(this._targetSelection);+ this._control.refreshSelectionFilled(this._targetSelection);this._isInMergeState = false;this._controlHandler((o, index) => {o.setProps({diff --git a/packages/ui-plugin-sheets/src/services/selection/selection-shape.ts b/packages/ui-plugin-sheets/src/services/selection/selection-shape.tsindex 2c74f23c52..0c67c3292c 100644--- a/packages/ui-plugin-sheets/src/services/selection/selection-shape.ts+++ b/packages/ui-plugin-sheets/src/services/selection/selection-shape.ts@@ -104,7 +104,10 @@ export class SelectionShape {readonly selectionScaling$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);readonly selectionScaled$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);readonly selectionFilling$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);- readonly selectionFilled$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);++ private readonly _selectionFilled$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);++ readonly selectionFilled$ = this._selectionFilled$.asObservable();private _defaultStyle!: ISelectionStyle;@@ -213,6 +216,10 @@ export class SelectionShape {this._isHeaderHighlight = false;}+ refreshSelectionFilled(val: IRangeWithCoord) {+ this._selectionFilled$.next(val);+ }+/*** just handle the view*diff --git a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts b/packages/ui-plugin-sheets/src/sheet-ui-plugin.tsindex 6a84a5af75..23acbfe356 100644--- a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts+++ b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts@@ -3,6 +3,7 @@ import { Dependency, Inject, Injector } from '@wendellhu/redi';import { filter } from 'rxjs/operators';import { SHEET_UI_PLUGIN_NAME } from './Basics';+import { AutoFillController } from './controllers/auto-fill.controller';import { AutoHeightController } from './controllers/auto-height.controller';import { SheetClipboardController } from './controllers/clipboard/clipboard.controller';import { SheetContextMenuController } from './controllers/contextmenu/contextmenu.controller';@@ -25,6 +26,7 @@ import { SheetRenderController } from './controllers/sheet-render.controller';import { SheetUIController } from './controllers/sheet-ui.controller';import { ZoomController } from './controllers/zoom.controller';import { enUS } from './locale';+import { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';import { ISheetClipboardService, SheetClipboardService } from './services/clipboard/clipboard.service';import { CellEditorManagerService, ICellEditorManagerService } from './services/editor/cell-editor-manager.service';import { EditorBridgeService, IEditorBridgeService } from './services/editor-bridge.service';@@ -63,6 +65,7 @@ export class SheetUIPlugin extends Plugin {[ISheetBarService, { useClass: SheetBarService }],[IFormatPainterService, { useClass: FormatPainterService }],[ICellEditorManagerService, { useClass: CellEditorManagerService }],+ [IAutoFillService, { useClass: AutoFillService }],[ScrollManagerService],[SheetSkeletonManagerService],[@@ -94,6 +97,7 @@ export class SheetUIPlugin extends Plugin {[SheetUIController],[StartEditController],[ZoomController],+ [AutoFillController],] as Dependency[]).forEach((d) => injector.add(d));}diff --git a/packages/ui-plugin-sheets/src/views/OperateContainer/OperateContainer.tsx b/packages/ui-plugin-sheets/src/views/OperateContainer/OperateContainer.tsxnew file mode 100644index 0000000000..a9e4eb37d2--- /dev/null+++ b/packages/ui-plugin-sheets/src/views/OperateContainer/OperateContainer.tsx@@ -0,0 +1,8 @@+import styles from './index.module.less';+import { SmartButton } from './SmartButton';++export const OperateContainer: React.FC = () => (+ <div className={styles.operateContainer}>+ <SmartButton></SmartButton>+ </div>+);diff --git a/packages/ui-plugin-sheets/src/views/OperateContainer/SmartButton.tsx b/packages/ui-plugin-sheets/src/views/OperateContainer/SmartButton.tsxnew file mode 100644index 0000000000..c4d400064c--- /dev/null+++ b/packages/ui-plugin-sheets/src/views/OperateContainer/SmartButton.tsx@@ -0,0 +1,159 @@+import { IRenderManagerService } from '@univerjs/base-render';+import { ICommandInfo, ICommandService, IUniverInstanceService, toDisposable } from '@univerjs/core';+import { Button, Dropdown } from '@univerjs/design';+import { CheckMarkSingle, Paste } from '@univerjs/icons';+import { useDependency } from '@wendellhu/redi/react-bindings';+import React, { useCallback, useEffect, useState } from 'react';++import {+ AutoClearContentCommand,+ AutoFillCommand,+ IAutoFillCommandParams,+} from '../../commands/commands/auto-fill.command';+import { RefillCommand } from '../../commands/commands/refill.command';+import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';+import { SetScrollOperation } from '../../commands/operations/scroll.operation';+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 { SelectionRenderService } from '../../services/selection/selection-render.service';+import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';+import styles from './index.module.less';++export interface IAnchorPoint {+ row: number;+ col: number;+}++export interface ISmartButtonMenuItem {+ label: string;+ value?: any;+ selected?: boolean;+ index: number;+}++const useUpdate = () => {+ const [_, setState] = useState({});+ return useCallback(() => setState({}), []);+};++const menu = [+ {+ index: 0,+ label: 'copy',+ value: APPLY_TYPE.COPY,+ },+ {+ index: 1,+ label: 'series',+ value: APPLY_TYPE.SERIES,+ },+ {+ index: 2,+ label: 'format only',+ value: APPLY_TYPE.ONLY_FORMAT,+ },+ {+ index: 3,+ label: 'no format',+ value: APPLY_TYPE.NO_FORMAT,+ },+];++export const SmartButton: React.FC<{}> = () => {+ const commandService = useDependency(ICommandService);+ const sheetSkeletonManagerService = useDependency(SheetSkeletonManagerService);+ const currentUniverService = useDependency(IUniverInstanceService);+ const renderManagerService = useDependency(IRenderManagerService);+ const selectionRenderService = useDependency(SelectionRenderService);+ const autoFillService = useDependency(IAutoFillService);++ const [visible, setVisible] = useState(false);+ const [anchor, setAnchor] = useState<IAnchorPoint>({ row: -1, col: -1 });+ const [selected, setSelected] = useState<number>(1);+ const forceUpdate = useUpdate();++ const sheetObject = getSheetObject(currentUniverService, renderManagerService);++ if (sheetObject == null) {+ return null;+ }+ const { scene } = sheetObject;++ useEffect(() => {+ const disposable = commandService.onCommandExecuted((command: ICommandInfo) => {+ if (command.id === AutoFillCommand.id) {+ const { endColumn, endRow } = (command?.params as IAutoFillCommandParams).selectionRange;+ setAnchor({ row: endRow, col: endColumn });+ }+ if (command.id === SetScrollOperation.id) {+ forceUpdate();+ }+ if (command.id === SetCellEditVisibleOperation.id || command.id === AutoClearContentCommand.id) {+ setAnchor({ row: -1, col: -1 });+ }+ });+ return disposable.dispose;+ }, [forceUpdate, commandService]);++ useEffect(() => {+ const disposable = toDisposable(+ autoFillService.applyType$.subscribe((type) => {+ setSelected(menu.find((i) => i.value === type)?.index ?? 0);+ })+ );+ return disposable.dispose;+ }, [autoFillService]);++ if (anchor.col < 0 || anchor.row < 0) {+ return null;+ }+ const skeleton = sheetSkeletonManagerService.getCurrent()?.skeleton;+ const viewport = selectionRenderService.getViewPort();+ const scaleX = scene?.scaleX;+ const scaleY = scene?.scaleY;+ const scrollXY = scene?.getScrollXY(viewport);+ if (!scaleX || !scene || !scaleX || !scaleY || !scrollXY) return null;+ const x = skeleton?.getNoMergeCellPositionByIndex(anchor.row, anchor.col, scaleX, scaleY).endX || 0;+ const y = skeleton?.getNoMergeCellPositionByIndex(anchor.row, anchor.col, scaleX, scaleY).endY || 0;+ const relativeX = skeleton?.convertTransformToOffsetX(x, scaleX, scrollXY);+ const relativeY = skeleton?.convertTransformToOffsetY(y, scaleY, scrollXY);++ const onVisibleChange = (visible: boolean) => {+ setVisible(visible);+ };++ const handleClick = (item: ISmartButtonMenuItem) => {+ commandService.executeCommand(RefillCommand.id, { type: item.value });+ };+ return (+ <div style={{ left: `${relativeX}px`, top: `${relativeY}px`, position: 'absolute' }}>+ <Dropdown+ placement="bottomRight"+ trigger={['click']}+ overlay={+ <ul className={styles.smartButtonMenu} style={{ ...styles }}>+ {menu.map((item) => (+ <li+ key={item.index}+ onClick={(e) => handleClick(item)}+ className={styles.smartButtonMenuItem}+ >+ <span className={styles.smartButtonMenuItemIcon}>+ {item.index === selected ? <CheckMarkSingle /> : ''}+ </span>+ <span className={styles.smartButtonMenuItemTitle}>{item.label}</span>+ </li>+ ))}+ </ul>+ }+ visible={visible}+ onVisibleChange={onVisibleChange}+ >+ <Button size="small">+ <Paste style={{ color: 'green' }}></Paste>+ </Button>+ </Dropdown>+ </div>+ );+};diff --git a/packages/ui-plugin-sheets/src/views/OperateContainer/index.module.less b/packages/ui-plugin-sheets/src/views/OperateContainer/index.module.lessnew file mode 100644index 0000000000..d139a046af--- /dev/null+++ b/packages/ui-plugin-sheets/src/views/OperateContainer/index.module.less@@ -0,0 +1,63 @@+.operate-container {+ left: 0px;+ right: 0px;+ width: 0px;+ height: 0px;+ position: absolute;+ z-index: 10;++}+@item-padding-left:36px;+@smart-button-menu-min-width:128px;++.smart-button-menu {+ min-width: @smart-button-menu-min-width;+ padding: var(--padding-sm);+ font-size: var(--font-size-base);+ background-color: rgb(var(--bg-color-secondary));+ border: 1px solid rgb(var(--border-color));+ border-radius: var(--border-radius-lg);+ box-shadow: var(--box-shadow-lg);+ box-sizing: border-box;+ display: grid;+ align-items: center;+ gap: var(--margin-xxs);++ li {+ list-style: none;+ }++ &-item {+ position: relative;+ text-align: left;++ position: relative;+ padding: var(--padding-xs) 0 var(--padding-xs) @item-padding-left;+ color: rgb(var(--text-color));+ border-radius: var(--border-radius-base);+ box-sizing: border-box;+ cursor: pointer;+ transition: background .2s;++ &:hover {+ background-color: rgb(var(--bg-color-hover));+ }+++ &-icon {+ position: absolute;+ left: var(--padding-xs);+ top: 50%;+ transform: translateY(-50%);+ }++ &-title {+ vertical-align: middle;+ padding: var(--padding-xs) var(--padding-xs) var(--padding-xs) 0;+ }++ &-hide {+ color: rgb(var(--text-color-secondary));+ }+ }+}\ No newline at end of filediff --git a/packages/ui-plugin-sheets/src/views/OperateContainer/index.ts b/packages/ui-plugin-sheets/src/views/OperateContainer/index.tsnew file mode 100644index 0000000000..3604f3c3d9--- /dev/null+++ b/packages/ui-plugin-sheets/src/views/OperateContainer/index.ts@@ -0,0 +1 @@+export * from './OperateContainer';diff --git a/packages/ui-plugin-sheets/src/views/SheetContainer/SheetContainer.tsx b/packages/ui-plugin-sheets/src/views/SheetContainer/SheetContainer.tsxindex 6c5ba443fc..91f0611c15 100644--- a/packages/ui-plugin-sheets/src/views/SheetContainer/SheetContainer.tsx+++ b/packages/ui-plugin-sheets/src/views/SheetContainer/SheetContainer.tsx@@ -2,6 +2,7 @@ import { ISheetUIPluginConfig } from '../../Basics';import { CountBar } from '../CountBar';import { EditorContainer } from '../EditorContainer/EditorContainer';import { FormulaBar } from '../FormulaBar/FormulaBar';+import { OperateContainer } from '../OperateContainer';import { SheetBar } from '../SheetBar/SheetBar';import styles from './index.module.less';@@ -32,6 +33,7 @@ export function RenderSheetContent() {return (<><EditorContainer />+ <OperateContainer /></>);}