Skip to content

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

feat(formula): range selector deactivation (#494)

Dushusir639c2a37ad00
diff --git a/packages/base-formula-engine/src/basics/common.ts b/packages/base-formula-engine/src/basics/common.ts
index 0947e81d76..552caf84b7 100644
--- a/packages/base-formula-engine/src/basics/common.ts
+++ b/packages/base-formula-engine/src/basics/common.ts
@@ -58,6 +58,8 @@ export interface IUnitSheetNameMap {
*/
export interface IFormulaDataItem {
f: string; // formulaString
+ x?: number; // Offset from x direction
+ y?: number; // Offset from y direction
// si: string; // formulaId,
// row: number;
// column: number;
diff --git a/packages/base-ui/src/views/App.tsx b/packages/base-ui/src/views/App.tsx
index 349a593d0e..2ee6acf691 100644
--- a/packages/base-ui/src/views/App.tsx
+++ b/packages/base-ui/src/views/App.tsx
@@ -104,7 +104,7 @@ export function App(props: IUniverAppProps) {
{/* <ComponentContainer components={sidebarComponents} /> */}
<ContextMenu>
- <section ref={contentRef} className={styles.appContainerContent}>
+ <section ref={contentRef} className={styles.appContainerContent} data-range-selector>
<ComponentContainer components={contentComponents} />
</section>
</ContextMenu>
diff --git a/packages/common-plugin-data/src/sheets/demo/default-workbook-data-demo.ts b/packages/common-plugin-data/src/sheets/demo/default-workbook-data-demo.ts
index f7feca314f..662b90876e 100644
--- a/packages/common-plugin-data/src/sheets/demo/default-workbook-data-demo.ts
+++ b/packages/common-plugin-data/src/sheets/demo/default-workbook-data-demo.ts
@@ -24164,6 +24164,29 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
v: 3,
m: '3',
},
+ 3: {
+ v: 2,
+ m: '2',
+ f: '=SUM(A1)',
+ },
+ },
+ 1: {
+ 0: {
+ v: 4,
+ m: '4',
+ },
+ },
+ 2: {
+ 0: {
+ v: 44,
+ m: '44',
+ },
+ },
+ 3: {
+ 0: {
+ v: 444,
+ m: '444',
+ },
},
},
},
diff --git a/packages/core/src/types/interfaces/i-cell-data.ts b/packages/core/src/types/interfaces/i-cell-data.ts
index e0745717ea..10f70ad93b 100644
--- a/packages/core/src/types/interfaces/i-cell-data.ts
+++ b/packages/core/src/types/interfaces/i-cell-data.ts
@@ -23,6 +23,9 @@ export interface ICellData {
* Origin value
*/
v?: Nullable<ICellV>;
+ /**
+ * @deprecated
+ */
m?: Nullable<string>; // formatted value
// Usually the type is automatically determined based on the data, or the user directly specifies
t?: Nullable<CellValueType>; // 0 string, 1 number, 2 boolean, 3 force string, green icon, set null for cell clear all
@@ -62,3 +65,18 @@ export function isICellData(value: any): value is ICellData {
(value as ICellData).f !== undefined
);
}
+
+export function getCellValueType(cell: ICellData) {
+ if (cell.t !== undefined) {
+ return cell.t;
+ }
+ if (typeof cell.v === 'string') {
+ return CellValueType.STRING;
+ }
+ if (typeof cell.v === 'number') {
+ return CellValueType.NUMBER;
+ }
+ if (typeof cell.v === 'boolean') {
+ return CellValueType.BOOLEAN;
+ }
+}
diff --git a/packages/sheets-plugin-formula-ui/src/commands/commands/insert-function.command.ts b/packages/sheets-plugin-formula-ui/src/commands/commands/insert-function.command.ts
new file mode 100644
index 0000000000..4f52af43a9
--- /dev/null
+++ b/packages/sheets-plugin-formula-ui/src/commands/commands/insert-function.command.ts
@@ -0,0 +1,64 @@
+import { ISetRangeValuesCommandParams, SetRangeValuesCommand } from '@univerjs/base-sheets';
+import { CommandType, ICellData, ICommand, ICommandService, IRange, ObjectMatrix, Tools } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+interface IInsertFunction {
+ /**
+ * The range into which the function is to be inserted
+ */
+ range: IRange;
+
+ /**
+ * Where there is a function id, other locations reference this function id
+ */
+ primary: {
+ row: number;
+ column: number;
+ };
+
+ /**
+ * Function name
+ */
+ formula: string;
+}
+
+export interface IInsertFunctionCommandParams {
+ list: IInsertFunction[];
+}
+
+export const InsertFunctionCommand: ICommand = {
+ id: 'formula-ui.command.insert-function',
+ type: CommandType.OPERATION,
+ handler: async (accessor: IAccessor, params: IInsertFunctionCommandParams) => {
+ const { list } = params;
+ const commandService = accessor.get(ICommandService);
+ const cellMatrix = new ObjectMatrix<ICellData>();
+
+ list.forEach((item) => {
+ const { range, primary, formula } = item;
+ const { row, column } = primary;
+ const formulaId = Tools.generateRandomId(6);
+ cellMatrix.setValue(row, column, {
+ f: formula,
+ si: formulaId,
+ });
+
+ const { startRow, startColumn, endRow, endColumn } = range;
+ for (let i = startRow; i <= endRow; i++) {
+ for (let j = startColumn; j <= endColumn; j++) {
+ if (i !== row || j !== column) {
+ cellMatrix.setValue(i, j, {
+ si: formulaId,
+ });
+ }
+ }
+ }
+ });
+
+ const setRangeValuesParams: ISetRangeValuesCommandParams = {
+ value: cellMatrix.getData(),
+ };
+
+ return commandService.executeCommand(SetRangeValuesCommand.id, setRangeValuesParams);
+ },
+};
diff --git a/packages/sheets-plugin-formula-ui/src/commands/operations/help-function.operation.ts b/packages/sheets-plugin-formula-ui/src/commands/operations/help-function.operation.ts
index 4621195c9b..26a8673fed 100644
--- a/packages/sheets-plugin-formula-ui/src/commands/operations/help-function.operation.ts
+++ b/packages/sheets-plugin-formula-ui/src/commands/operations/help-function.operation.ts
@@ -1,12 +1,12 @@
import { CommandType, ICommand } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-import { IFormulaPromptService, IHelpFunctionCommandParams } from '../../services/prompt.service';
+import { IFormulaPromptService, IHelpFunctionOperationParams } from '../../services/prompt.service';
export const HelpFunctionOperation: ICommand = {
id: 'formula-ui.operation.help-function',
type: CommandType.OPERATION,
- handler: async (accessor: IAccessor, params: IHelpFunctionCommandParams) => {
+ handler: async (accessor: IAccessor, params: IHelpFunctionOperationParams) => {
const promptService = accessor.get(IFormulaPromptService);
promptService.help(params);
diff --git a/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts b/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts
index 2bd9000269..fdcbeb2602 100644
--- a/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts
+++ b/packages/sheets-plugin-formula-ui/src/commands/operations/insert-function.operation.ts
@@ -1,7 +1,22 @@
-import { CommandType, ICommand } from '@univerjs/core';
+import { SelectionManagerService } from '@univerjs/base-sheets';
+import {
+ CellValueType,
+ CommandType,
+ getCellValueType,
+ ICellData,
+ ICommand,
+ ICommandService,
+ IRange,
+ IUniverInstanceService,
+ Nullable,
+ ObjectMatrix,
+ serializeRange,
+} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-export interface IInsertFunctionCommandParams {
+import { InsertFunctionCommand } from '../commands/insert-function.command';
+
+export interface IInsertFunctionOperationParams {
/**
* function name
*/
@@ -11,5 +26,128 @@ export interface IInsertFunctionCommandParams {
export const InsertFunctionOperation: ICommand = {
id: 'formula-ui.operation.insert-function',
type: CommandType.OPERATION,
- handler: async (accessor: IAccessor, params: IInsertFunctionCommandParams) => true,
+ handler: async (accessor: IAccessor, params: IInsertFunctionOperationParams) => {
+ const selectionManagerService = accessor.get(SelectionManagerService);
+ const currentSelections = selectionManagerService.getSelections();
+ if (!currentSelections || !currentSelections.length) {
+ return false;
+ }
+
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const cellMatrix = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getCellMatrix();
+
+ // Select a single range to insert a formula:
+ // 1. The entire row or column, first get the judgment result of the primary position, and then set the formula ID of other positions in sequence;
+ // 2. For multiple rows and multiple columns, only get the judgment result of the primary position, and enter the edit mode
+ if (currentSelections.length === 1) {
+ const { startRow, endRow, startColumn, endColumn } = currentSelections[0].range;
+ if (startRow !== endRow && startColumn !== endColumn) {
+ // TODO@Dushusir: Enter the editing mode
+ return false;
+ }
+ }
+
+ const { value } = params;
+
+ const commandService = accessor.get(ICommandService);
+
+ // In each range (whether it is an entire row or column or multiple rows and columns),
+ // 1. First get the judgment result of the primary position, and then set the formula id of other positions;
+ // 2. If there is no primary range, just judge the upper left corner cell.
+ const list = currentSelections.map((selection) => {
+ const { range, primary } = selection;
+
+ const row = primary?.actualRow ?? range.startRow;
+ const column = primary?.actualColumn ?? range.startColumn;
+
+ const refRange = findRefRange(cellMatrix, row, column);
+ const rangeString = refRange ? serializeRange(refRange) : '';
+ const formulaString = `=${value}(${rangeString})`;
+
+ return {
+ range,
+ primary: {
+ row,
+ column,
+ },
+ formula: formulaString,
+ };
+ });
+
+ return commandService.executeCommand(InsertFunctionCommand.id, {
+ list,
+ });
+ },
};
+
+/**
+ * 1. Starting from the first position on the left or top and ending with a continuous number (the first non-blank cell is allowed to be text)
+ * 2. Match the upper part first, then the left part. If not, insert a function with empty parameters.
+ */
+function findRefRange(cellMatrix: ObjectMatrix<ICellData>, row: number, column: number): Nullable<IRange> {
+ const startRow = findStartRow(cellMatrix, row, column);
+ if (startRow !== row) {
+ return {
+ startRow,
+ endRow: row - 1,
+ startColumn: column,
+ endColumn: column,
+ };
+ }
+
+ const startColumn = findStartColumn(cellMatrix, row, column);
+ if (startColumn !== column) {
+ return {
+ startRow: row,
+ endRow: row,
+ startColumn,
+ endColumn: column - 1,
+ };
+ }
+ return null;
+}
+
+function findStartRow(cellMatrix: ObjectMatrix<ICellData>, row: number, column: number) {
+ let isFirstNumber = false;
+
+ if (row === 0) return row;
+
+ for (let r = row - 1; r >= 0; r--) {
+ const cell = cellMatrix.getValue(r, column);
+
+ if (!cell) continue;
+
+ if (getCellValueType(cell) === CellValueType.NUMBER && !isFirstNumber) {
+ if (r === 0) return 0;
+ isFirstNumber = true;
+ } else if (isFirstNumber && getCellValueType(cell) !== CellValueType.NUMBER) {
+ return r - 1;
+ } else if (isFirstNumber && r === 0) {
+ return 0;
+ }
+ }
+
+ return row;
+}
+
+function findStartColumn(cellMatrix: ObjectMatrix<ICellData>, row: number, column: number) {
+ let isFirstNumber = false;
+
+ if (column === 0) return column;
+
+ for (let c = column - 1; c >= 0; c--) {
+ const cell = cellMatrix.getValue(row, c);
+ if (!cell) continue;
+
+ if (getCellValueType(cell) === CellValueType.NUMBER && !isFirstNumber) {
+ if (c === 0) return 0;
+ isFirstNumber = true;
+ } else if (isFirstNumber && getCellValueType(cell) !== CellValueType.NUMBER) {
+ return c - 1;
+ } else if (isFirstNumber && c === 0) {
+ return 0;
+ }
+ }
+
+ return column;
+}
diff --git a/packages/sheets-plugin-formula-ui/src/commands/operations/search-function.operation.ts b/packages/sheets-plugin-formula-ui/src/commands/operations/search-function.operation.ts
index 0915b76ad3..6898f76aca 100644
--- a/packages/sheets-plugin-formula-ui/src/commands/operations/search-function.operation.ts
+++ b/packages/sheets-plugin-formula-ui/src/commands/operations/search-function.operation.ts
@@ -1,12 +1,12 @@
import { CommandType, ICommand } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-import { IFormulaPromptService, ISearchFunctionParams } from '../../services/prompt.service';
+import { IFormulaPromptService, ISearchFunctionOperationParams } from '../../services/prompt.service';
export const SearchFunctionOperation: ICommand = {
id: 'formula-ui.operation.search-function',
type: CommandType.OPERATION,
- handler: async (accessor: IAccessor, params: ISearchFunctionParams) => {
+ handler: async (accessor: IAccessor, params: ISearchFunctionOperationParams) => {
const promptService = accessor.get(IFormulaPromptService);
promptService.search(params);
diff --git a/packages/sheets-plugin-formula-ui/src/controllers/formula-ui.controller.ts b/packages/sheets-plugin-formula-ui/src/controllers/formula-ui.controller.ts
index 01d71c40d4..60a6deeb2b 100644
--- a/packages/sheets-plugin-formula-ui/src/controllers/formula-ui.controller.ts
+++ b/packages/sheets-plugin-formula-ui/src/controllers/formula-ui.controller.ts
@@ -9,6 +9,7 @@ import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univ
import { Inject, Injector } from '@wendellhu/redi';
import { connectInjector } from '@wendellhu/redi/react-bindings';
+import { InsertFunctionCommand } from '../commands/commands/insert-function.command';
import { SelectEditorFormulaOperation } from '../commands/operations/editor-formula.operation';
import { HelpFunctionOperation } from '../commands/operations/help-function.operation';
import { InsertFunctionOperation } from '../commands/operations/insert-function.operation';
@@ -57,6 +58,7 @@ export class FormulaUIController extends Disposable {
private _registerCommands(): void {
[
+ InsertFunctionCommand,
InsertFunctionOperation,
MoreFunctionsOperation,
SearchFunctionOperation,
diff --git a/packages/sheets-plugin-formula-ui/src/formula-ui-plugin.ts b/packages/sheets-plugin-formula-ui/src/formula-ui-plugin.ts
index d81c90a1b4..b614a3b169 100644
--- a/packages/sheets-plugin-formula-ui/src/formula-ui-plugin.ts
+++ b/packages/sheets-plugin-formula-ui/src/formula-ui-plugin.ts
@@ -32,13 +32,17 @@ export class FormulaUIPlugin extends Plugin {
enUS,
});
- const descriptionService = this._injector.createInstance(DescriptionService, this._config?.description || []);
-
const dependencies: Dependency[] = [
// services
[IFormulaPromptService, { useClass: FormulaPromptService }],
- [IDescriptionService, { useValue: descriptionService }],
[IFormulaInputService, { useClass: FormulaInputService }],
+ [
+ IDescriptionService,
+ {
+ useFactory: () =>
+ this._injector.createInstance(DescriptionService, this._config?.description || []), // TODO@Dusuhir: initialize config with asynchronous method?
+ },
+ ],
// controllers
[FormulaUIController],
[PromptController],
diff --git a/packages/sheets-plugin-formula-ui/src/locale/en-US.ts b/packages/sheets-plugin-formula-ui/src/locale/en-US.ts
index 82ce080f79..c6abebe27b 100644
--- a/packages/sheets-plugin-formula-ui/src/locale/en-US.ts
+++ b/packages/sheets-plugin-formula-ui/src/locale/en-US.ts
@@ -1,18 +1,18 @@
-import arrayEnUS from './function-list/array/en-US';
-import compatibilityEnUS from './function-list/compatibility/en-US';
-import cubeEnUS from './function-list/cube/en-US';
-import databaseEnUS from './function-list/database/en-US';
-import dateEnUS from './function-list/date/en-US';
-import engineeringEnUS from './function-list/engineering/en-US';
-import financialEnUS from './function-list/financial/en-US';
-import informationEnUS from './function-list/information/en-US';
-import logicalEnUS from './function-list/logical/en-US';
-import lookupEnUS from './function-list/lookup/en-US';
-import mathEnUS from './function-list/math/en-US';
-import statisticalEnUS from './function-list/statistical/en-US';
-import textEnUS from './function-list/text/en-US';
-import univerEnUS from './function-list/univer/en-US';
-import webEnUS from './function-list/web/en-US';
+import array from './function-list/array/en-US';
+import compatibility from './function-list/compatibility/en-US';
+import cube from './function-list/cube/en-US';
+import database from './function-list/database/en-US';
+import date from './function-list/date/en-US';
+import engineering from './function-list/engineering/en-US';
+import financial from './function-list/financial/en-US';
+import information from './function-list/information/en-US';
+import logical from './function-list/logical/en-US';
+import lookup from './function-list/lookup/en-US';
+import math from './function-list/math/en-US';
+import statistical from './function-list/statistical/en-US';
+import text from './function-list/text/en-US';
+import univer from './function-list/univer/en-US';
+import web from './function-list/web/en-US';
export default {
formula: {
@@ -26,21 +26,21 @@ export default {
more: 'More Functions...',
},
functionList: {
- ...financialEnUS,
- ...dateEnUS,
- ...mathEnUS,
- ...statisticalEnUS,
- ...lookupEnUS,
- ...databaseEnUS,
- ...textEnUS,
- ...logicalEnUS,
- ...informationEnUS,
- ...engineeringEnUS,
- ...cubeEnUS,
- ...compatibilityEnUS,
- ...webEnUS,
- ...arrayEnUS,
- ...univerEnUS,
+ ...financial,
+ ...date,
+ ...math,
+ ...statistical,
+ ...lookup,
+ ...database,
+ ...text,
+ ...logical,
+ ...information,
+ ...engineering,
+ ...cube,
+ ...compatibility,
+ ...web,
+ ...array,
+ ...univer,
},
prompt: {
helpExample: 'EXAMPLE',
diff --git a/packages/sheets-plugin-formula-ui/src/locale/zh-CN.ts b/packages/sheets-plugin-formula-ui/src/locale/zh-CN.ts
index 1c0b3a8419..06b7f34fb9 100644
--- a/packages/sheets-plugin-formula-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-plugin-formula-ui/src/locale/zh-CN.ts
@@ -1,18 +1,18 @@
-import arrayZhCN from './function-list/array/zh-CN';
-import compatibilityZhCN from './function-list/compatibility/zh-CN';
-import cubeZhCN from './function-list/cube/zh-CN';
-import databaseZhCN from './function-list/database/zh-CN';
-import dateZhCN from './function-list/date/zh-CN';
-import engineeringZhCN from './function-list/engineering/zh-CN';
-import financialZhCN from './function-list/financial/zh-CN';
-import informationZhCN from './function-list/information/zh-CN';
-import logicalZhCN from './function-list/logical/zh-CN';
-import lookupZhCN from './function-list/lookup/zh-CN';
-import mathZhCN from './function-list/math/zh-CN';
-import statisticalZhCN from './function-list/statistical/zh-CN';
-import textZhCN from './function-list/text/zh-CN';
-import univerZhCN from './function-list/univer/zh-CN';
-import webZhCN from './function-list/web/zh-CN';
+import array from './function-list/array/zh-CN';
+import compatibility from './function-list/compatibility/zh-CN';
+import cube from './function-list/cube/zh-CN';
+import database from './function-list/database/zh-CN';
+import date from './function-list/date/zh-CN';
+import engineering from './function-list/engineering/zh-CN';
+import financial from './function-list/financial/zh-CN';
+import information from './function-list/information/zh-CN';
+import logical from './function-list/logical/zh-CN';
+import lookup from './function-list/lookup/zh-CN';
+import math from './function-list/math/zh-CN';
+import statistical from './function-list/statistical/zh-CN';
+import text from './function-list/text/zh-CN';
+import univer from './function-list/univer/zh-CN';
+import web from './function-list/web/zh-CN';
export default {
formula: {
@@ -26,21 +26,21 @@ export default {
more: '更多函数...',
},
functionList: {
- ...financialZhCN,
- ...dateZhCN,
- ...mathZhCN,
- ...statisticalZhCN,
- ...lookupZhCN,
- ...databaseZhCN,
- ...textZhCN,
- ...logicalZhCN,
- ...informationZhCN,
- ...engineeringZhCN,
- ...cubeZhCN,
- ...compatibilityZhCN,
- ...webZhCN,
- ...arrayZhCN,
- ...univerZhCN,
+ ...financial,
+ ...date,
+ ...math,
+ ...statistical,
+ ...lookup,
+ ...database,
+ ...text,
+ ...logical,
+ ...information,
+ ...engineering,
+ ...cube,
+ ...compatibility,
+ ...web,
+ ...array,
+ ...univer,
},
prompt: {
diff --git a/packages/sheets-plugin-formula-ui/src/services/prompt.service.ts b/packages/sheets-plugin-formula-ui/src/services/prompt.service.ts
index fe1848162c..936834d993 100644
--- a/packages/sheets-plugin-formula-ui/src/services/prompt.service.ts
+++ b/packages/sheets-plugin-formula-ui/src/services/prompt.service.ts
@@ -5,7 +5,7 @@ import { Observable, Subject } from 'rxjs';
import { ISearchItem } from './description.service';
-export interface ISearchFunctionParams {
+export interface ISearchFunctionOperationParams {
/**
* show SearchFunction Component or not
*/
@@ -22,7 +22,7 @@ export interface ISearchFunctionParams {
searchList: ISearchItem[];
}
-export interface IHelpFunctionCommandParams {
+export interface IHelpFunctionOperationParams {
/**
* show HelpFunction Component or not
*/
@@ -47,23 +47,23 @@ export interface IFormulaPromptService {
/**
* listen search function open
*/
- search$: Observable<ISearchFunctionParams>;
+ search$: Observable<ISearchFunctionOperationParams>;
/**
* open search function
*/
- search(param: ISearchFunctionParams): void;
+ search(param: ISearchFunctionOperationParams): void;
/**
* listen help function open
*/
- help$: Observable<IHelpFunctionCommandParams>;
+ help$: Observable<IHelpFunctionOperationParams>;
/**
* open help function
*/
- help(param: IHelpFunctionCommandParams): void;
+ help(param: IHelpFunctionOperationParams): void;
/**
* listen navigate shortcut, UP and DOWN
@@ -105,9 +105,9 @@ export interface IFormulaPromptService {
export const IFormulaPromptService = createIdentifier<FormulaPromptService>('formula-ui.prompt-service');
export class FormulaPromptService implements IFormulaPromptService, IDisposable {
- private readonly _search$ = new Subject<ISearchFunctionParams>();
+ private readonly _search$ = new Subject<ISearchFunctionOperationParams>();
- private readonly _help$ = new Subject<IHelpFunctionCommandParams>();
+ private readonly _help$ = new Subject<IHelpFunctionOperationParams>();
private readonly _navigate$ = new Subject<INavigateParam>();
@@ -138,7 +138,7 @@ export class FormulaPromptService implements IFormulaPromptService, IDisposable
this._acceptFormulaName$.complete();
}
- search(param: ISearchFunctionParams) {
+ search(param: ISearchFunctionOperationParams) {
this._searching = param.visible;
this._search$.next(param);
}
@@ -147,7 +147,7 @@ export class FormulaPromptService implements IFormulaPromptService, IDisposable
return this._searching;
}
- help(param: IHelpFunctionCommandParams) {
+ help(param: IHelpFunctionOperationParams) {
this._helping = param.visible;
this._help$.next(param);
}
diff --git a/packages/sheets-plugin-formula-ui/src/views/FormulaPromptContainer.tsx b/packages/sheets-plugin-formula-ui/src/views/FormulaPromptContainer.tsx
index 113d5de8c3..7b27f93387 100644
--- a/packages/sheets-plugin-formula-ui/src/views/FormulaPromptContainer.tsx
+++ b/packages/sheets-plugin-formula-ui/src/views/FormulaPromptContainer.tsx
@@ -1,5 +1,6 @@
import React from 'react';
+import { ErrorFunction } from './prompt/error-function/error-function';
import { HelpFunction } from './prompt/help-function/HelpFunction';
import { SearchFunction } from './prompt/search-function/SearchFunction';
@@ -8,6 +9,7 @@ export function RenderFormulaPromptContent() {
<>
<SearchFunction />
<HelpFunction />
+ <ErrorFunction />
</>
);
}
diff --git a/packages/sheets-plugin-formula-ui/src/views/more-functions/MoreFunctions.tsx b/packages/sheets-plugin-formula-ui/src/views/more-functions/MoreFunctions.tsx
index ee0abb379a..b87b21cd14 100644
--- a/packages/sheets-plugin-formula-ui/src/views/more-functions/MoreFunctions.tsx
+++ b/packages/sheets-plugin-formula-ui/src/views/more-functions/MoreFunctions.tsx
@@ -36,7 +36,8 @@ export function MoreFunctions() {
{selectFunction && <SelectFunction onChange={setFunctionInfo}></SelectFunction>}
{inputParams && <InputParams functionInfo={functionInfo} onChange={setParams}></InputParams>}
<div className={styles.formulaMoreFunctionsOperation}>
- {selectFunction && (
+ {/* TODO@Dushusir: open input params after range selector refactor */}
+ {inputParams && (
<Button type="primary" onClick={handleClickNextPrev}>
{localeService.t('formula.moreFunctions.next')}
</Button>
@@ -44,7 +45,7 @@ export function MoreFunctions() {
{inputParams && (
<Button onClick={handleClickNextPrev}>{localeService.t('formula.moreFunctions.prev')}</Button>
)}
- {inputParams && (
+ {selectFunction && (
<Button type="primary" onClick={handleConfirm}>
{localeService.t('formula.moreFunctions.confirm')}
</Button>
diff --git a/packages/sheets-plugin-formula-ui/src/views/more-functions/function-help/FunctionHelp.tsx b/packages/sheets-plugin-formula-ui/src/views/more-functions/function-help/FunctionHelp.tsx
new file mode 100644
index 0000000000..9e247ad16b
--- /dev/null
+++ b/packages/sheets-plugin-formula-ui/src/views/more-functions/function-help/FunctionHelp.tsx
@@ -0,0 +1,24 @@
+import { IFunctionParam } from '@univerjs/base-formula-engine';
+import React from 'react';
+
+interface IFunctionHelpProps {
+ prefix?: string;
+ value?: IFunctionParam[];
+}
+
+export function FunctionHelp(props: IFunctionHelpProps) {
+ const { prefix, value } = props;
+ return (
+ <div>
+ <span>{prefix}(</span>
+ {value &&
+ value.map((item: IFunctionParam, i: number) => (
+ <span key={i}>
+ <span>{item.repeat ? `[${item.name},...]` : item.name}</span>
+ {i === value.length - 1 ? '' : ','}
+ </span>
+ ))}
+ )
+ </div>
+ );
+}
diff --git a/packages/sheets-plugin-formula-ui/src/views/more-functions/function-params/FunctionParams.tsx b/packages/sheets-plugin-formula-ui/src/views/more-functions/function-params/FunctionParams.tsx
index fce185afa9..c1e9f66fd9 100644
--- a/packages/sheets-plugin-formula-ui/src/views/more-functions/function-params/FunctionParams.tsx
+++ b/packages/sheets-plugin-formula-ui/src/views/more-functions/function-params/FunctionParams.tsx
@@ -4,15 +4,16 @@ import styles from './index.module.less';
interface IParamsProps {
className?: string;
- title?: string;
+ title?: string | React.ReactElement;
value?: string | React.ReactElement;
}
export function FunctionParams(props: IParamsProps) {
+ const { className, value, title } = props;
return (
<div className={styles.formulaFunctionParams}>
- <div className={`${styles.formulaFunctionParamsTitle} ${props.className}`}>{props.title}</div>
- <div className={styles.formulaFunctionParamsDetail}>{props.value}</div>
+ <div className={`${styles.formulaFunctionParamsTitle} ${className}`}>{title}</div>
+ <div className={styles.formulaFunctionParamsDetail}>{value}</div>
</div>
);
}
diff --git a/packages/sheets-plugin-formula-ui/src/views/more-functions/index.module.less b/packages/sheets-plugin-formula-ui/src/views/more-functions/index.module.less
index c61f4f4566..fbcf6dad12 100644
--- a/packages/sheets-plugin-formula-ui/src/views/more-functions/index.module.less
+++ b/packages/sheets-plugin-formula-ui/src/views/more-functions/index.module.less
@@ -2,8 +2,11 @@
display: flex;
flex-direction: column;
justify-content: space-between;
+
height: 100%;
+ line-height: 20px;
+
&-operation {
display: flex;
justify-content: flex-end;
diff --git a/packages/sheets-plugin-formula-ui/src/views/more-functions/input-params/InputParams.tsx b/packages/sheets-plugin-formula-ui/src/views/more-functions/input-params/InputParams.tsx
index ae6af085ab..4f10293f4b 100644
--- a/packages/sheets-plugin-formula-ui/src/views/more-functions/input-params/InputParams.tsx
+++ b/packages/sheets-plugin-formula-ui/src/views/more-functions/input-params/InputParams.tsx
@@ -2,6 +2,7 @@ import { IFunctionInfo, IFunctionParam } from '@univerjs/base-formula-engine';
import { RangeSelector } from '@univerjs/ui-plugin-sheets';
import React, { useState } from 'react';
+import { FunctionHelp } from '../function-help/FunctionHelp';
import { FunctionParams } from '../function-params/FunctionParams';
import styles from './index.module.less';
@@ -12,39 +13,57 @@ export interface IInputParamsProps {
export function InputParams(props: IInputParamsProps) {
const { functionInfo, onChange } = props;
+ if (!functionInfo) return null;
+
const [params, setParams] = useState<string[]>([]);
- const [activeIndex, setActiveIndex] = useState(0);
+ const [functionParameter, setFunctionParameter] = useState<IFunctionParam[]>(functionInfo.functionParameter);
+ const [activeIndex, setActiveIndex] = useState(-1);
- function handleRangeChange(range: string, paramIndex: number) {
+ // TODO@Dushusir: Display description when all range selectors is canceled
+ function handleChange(range: string, paramIndex: number) {
const newParams = [...params];
newParams[paramIndex] = range;
setParams(newParams);
onChange(newParams);
}
+ function handleActive(i: number) {
+ if (i === functionParameter.length - 1 && functionParameter[i].repeat) {
+ const newFunctionParameter = [...functionParameter];
+ newFunctionParameter.push(functionParameter[i]);
+ setFunctionParameter(newFunctionParameter);
+ }
+
+ setActiveIndex(i);
+ }
+
return (
<div className={styles.formulaInputParams}>
<div className={styles.formulaInputParamsList}>
- {functionInfo &&
- functionInfo.functionParameter &&
- functionInfo.functionParameter.map((item: IFunctionParam, i: number) => (
- <div key={i}>
- <div className={styles.formulaInputParamsListItemName}>{item.name}</div>
-
- <div className={styles.formulaInputParamsListItemSelector}>
- <RangeSelector
- onChange={(range: string) => handleRangeChange(range, i)}
- onActive={() => setActiveIndex(i)}
- />
- </div>
+ {functionParameter.map((item: IFunctionParam, i: number) => (
+ <div key={i}>
+ <div className={styles.formulaInputParamsListItemName}>{item.name}</div>
+
+ <div className={styles.formulaInputParamsListItemSelector}>
+ <RangeSelector
+ onChange={(range: string) => handleChange(range, i)}
+ onActive={() => handleActive(i)}
+ />
</div>
- ))}
+ </div>
+ ))}
</div>
<div className={styles.formulaInputParamsInfo}>
<FunctionParams
- title={functionInfo?.functionParameter[activeIndex].name}
- value={functionInfo?.functionParameter[activeIndex].detail}
+ title={
+ activeIndex === -1 ? (
+ <FunctionHelp prefix={functionInfo.functionName} value={functionParameter} />
+ ) : (
+ functionParameter[activeIndex].name
+ )
+ }
+ value={activeIndex === -1 ? functionInfo.description : functionParameter[activeIndex].detail}
/>
</div>
</div>
diff --git a/packages/sheets-plugin-formula-ui/src/views/more-functions/input-params/index.module.less b/packages/sheets-plugin-formula-ui/src/views/more-functions/input-params/index.module.less
index 7b4e71873a..b52419ac6c 100644
--- a/packages/sheets-plugin-formula-ui/src/views/more-functions/input-params/index.module.less
+++ b/packages/sheets-plugin-formula-ui/src/views/more-functions/input-params/index.module.less
@@ -1,11 +1,19 @@
+@params-list-height: 364px;
+
.formula-input-params {
- &-list-item{
- &-name{
- font-size: var(--font-size-sm);
- }
+ &-list {
+ overflow-y: auto;
+ height: @params-list-height;
- &-selector{
- margin: var(--margin-xxs) 0 var(--margin-xs) 0;
+ &-item {
+ &-name {
+ font-size: var(--font-size-sm);
+ }
+
+ &-selector {
+ margin: var(--margin-xxs) 0 var(--margin-xs) 0;
+ }
}
}
+
}
\ No newline at end of file
diff --git a/packages/sheets-plugin-formula-ui/src/views/more-functions/select-function/SelectFunction.tsx b/packages/sheets-plugin-formula-ui/src/views/more-functions/select-function/SelectFunction.tsx
index 9e3a69b559..fe650edebb 100644
--- a/packages/sheets-plugin-formula-ui/src/views/more-functions/select-function/SelectFunction.tsx
+++ b/packages/sheets-plugin-formula-ui/src/views/more-functions/select-function/SelectFunction.tsx
@@ -7,6 +7,7 @@ import React, { useEffect, useState } from 'react';
import { IDescriptionService, ISearchItem } from '../../../services/description.service';
import { getFunctionTypeValues } from '../../../services/utils';
+import { FunctionHelp } from '../function-help/FunctionHelp';
import { FunctionParams } from '../function-params/FunctionParams';
import styles from './index.module.less';
@@ -152,7 +153,9 @@ export function SelectFunction(props: ISelectFunctionProps) {
<FunctionParams
title={localeService.t('formula.moreFunctions.syntax')}
- value={<Help prefix={functionInfo.functionName} value={functionInfo.functionParameter} />}
+ value={
+ <FunctionHelp prefix={functionInfo.functionName} value={functionInfo.functionParameter} />
+ }
/>
<FunctionParams
@@ -175,25 +178,3 @@ export function SelectFunction(props: ISelectFunctionProps) {
</div>
);
}
-
-interface IHelpProps {
- prefix?: string;
- value?: IFunctionParam[];
-}
-
-const Help = (props: IHelpProps) => {
- const { prefix, value } = props;
- return (
- <div>
- <span>{prefix}(</span>
- {value &&
- value.map((item: IFunctionParam, i: number) => (
- <span key={i}>
- <span>{item.repeat ? `[${item.name},...]` : item.name}</span>
- {i === value.length - 1 ? '' : ','}
- </span>
- ))}
- )
- </div>
- );
-};
diff --git a/packages/sheets-plugin-formula-ui/src/views/more-functions/select-function/index.module.less b/packages/sheets-plugin-formula-ui/src/views/more-functions/select-function/index.module.less
index ae7dcbc95f..be8bfe9978 100644
--- a/packages/sheets-plugin-formula-ui/src/views/more-functions/select-function/index.module.less
+++ b/packages/sheets-plugin-formula-ui/src/views/more-functions/select-function/index.module.less
@@ -14,6 +14,8 @@
&-result {
user-select: none;
+ overflow-y: auto;
+
box-sizing: border-box;
width: 100%;
height: @result-height;
@@ -33,7 +35,7 @@
position: relative;
box-sizing: border-box;
- padding: var(--padding-sm) @result-item-padding-left;
+ padding: var(--padding-xs) @result-item-padding-left;
font-size: var(--font-size-xs);
color: rgb(var(--text-color));
diff --git a/packages/sheets-plugin-formula-ui/src/views/prompt/error-function/error-function.tsx b/packages/sheets-plugin-formula-ui/src/views/prompt/error-function/error-function.tsx
new file mode 100644
index 0000000000..f5d4a1c341
--- /dev/null
+++ b/packages/sheets-plugin-formula-ui/src/views/prompt/error-function/error-function.tsx
@@ -0,0 +1,40 @@
+import { ICellEditorManagerService } from '@univerjs/ui-plugin-sheets';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+
+import { IFormulaPromptService, IHelpFunctionOperationParams } from '../../../services/prompt.service';
+import styles from './index.module.less';
+
+export function ErrorFunction() {
+ const [visible, setVisible] = useState(false);
+ const [position, setPosition] = useState({ left: 0, top: 0 });
+ const promptService = useDependency(IFormulaPromptService);
+ const cellEditorManagerService = useDependency(ICellEditorManagerService);
+ useEffect(() => {
+ // TODO@Dushusir: use cell notification service
+ const subscription = promptService.help$.subscribe((params: IHelpFunctionOperationParams) => {
+ const selection = cellEditorManagerService.getState();
+ if (!selection) return;
+
+ const { visible } = params;
+ if (!visible) {
+ setVisible(visible);
+ return;
+ }
+
+ const { endX = 0, startY = 0 } = selection;
+ setPosition({ left: endX, top: startY });
+ setVisible(visible);
+ });
+
+ return () => {
+ subscription?.unsubscribe();
+ };
+ }, []);
+ return visible ? (
+ <div className={styles.formulaErrorFunction} style={{ left: position.left, top: position.top }}>
+ {/* TODO@Dushusir replace with CellError Component */}
+ {/* CellError */}
+ </div>
+ ) : null;
+}
diff --git a/packages/sheets-plugin-formula-ui/src/views/prompt/error-function/index.module.less b/packages/sheets-plugin-formula-ui/src/views/prompt/error-function/index.module.less
new file mode 100644
index 0000000000..3e136dcb14
--- /dev/null
+++ b/packages/sheets-plugin-formula-ui/src/views/prompt/error-function/index.module.less
@@ -0,0 +1,3 @@
+.formula-error-function {
+ position: absolute;
+}
\ No newline at end of file
diff --git a/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/HelpFunction.tsx b/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/HelpFunction.tsx
index 63e92db3cb..cfaa7a5d15 100644
--- a/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/HelpFunction.tsx
+++ b/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/HelpFunction.tsx
@@ -6,7 +6,7 @@ import { ICellEditorManagerService } from '@univerjs/ui-plugin-sheets';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useEffect, useState } from 'react';
-import { IFormulaPromptService, IHelpFunctionCommandParams } from '../../../services/prompt.service';
+import { IFormulaPromptService, IHelpFunctionOperationParams } from '../../../services/prompt.service';
import styles from './index.module.less';
export function HelpFunction() {
@@ -24,7 +24,7 @@ export function HelpFunction() {
const optional = localeService.t('formula.prompt.optional');
useEffect(() => {
- const subscription = promptService.help$.subscribe((params: IHelpFunctionCommandParams) => {
+ const subscription = promptService.help$.subscribe((params: IHelpFunctionOperationParams) => {
const selection = cellEditorManagerService.getState();
if (!selection) return;
diff --git a/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/index.module.less b/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/index.module.less
index ac874da181..9cef14ebfb 100644
--- a/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/index.module.less
+++ b/packages/sheets-plugin-formula-ui/src/views/prompt/help-function/index.module.less
@@ -9,7 +9,7 @@
margin: 0;
padding: var(--padding-xl);
- font-size: var(--font-size-sm);
+ line-height: 20px;
list-style: none;
background-color: rgb(var(--bg-color-secondary));
diff --git a/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/SearchFunction.tsx b/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/SearchFunction.tsx
index f09fe0886f..c36d4fe072 100644
--- a/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/SearchFunction.tsx
+++ b/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/SearchFunction.tsx
@@ -5,7 +5,11 @@ import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useEffect, useState } from 'react';
import { ISearchItem } from '../../../services/description.service';
-import { IFormulaPromptService, INavigateParam, ISearchFunctionParams } from '../../../services/prompt.service';
+import {
+ IFormulaPromptService,
+ INavigateParam,
+ ISearchFunctionOperationParams,
+} from '../../../services/prompt.service';
import styles from './index.module.less';
export function SearchFunction() {
@@ -21,7 +25,7 @@ export function SearchFunction() {
// TODO@Dushusir: How to get updated values in subscribe callback better
let updatedSearchList: ISearchItem[] = [];
let updatedActive = 0;
- const subscribeSearch = promptService.search$.subscribe((params: ISearchFunctionParams) => {
+ const subscribeSearch = promptService.search$.subscribe((params: ISearchFunctionOperationParams) => {
const selection = cellEditorManagerService.getState();
if (!selection) return;
diff --git a/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/index.module.less b/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/index.module.less
index a4a586aa66..b73f215255 100644
--- a/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/index.module.less
+++ b/packages/sheets-plugin-formula-ui/src/views/prompt/search-function/index.module.less
@@ -6,7 +6,7 @@
margin: 0;
padding: var(--padding-base);
- font-size: var(--font-size-sm);
+ line-height: 20px;
list-style: none;
background-color: rgb(var(--bg-color-secondary));
@@ -19,7 +19,7 @@
cursor: pointer;
box-sizing: border-box;
- padding: var(--padding-sm);
+ padding: var(--padding-xs) var(--padding-sm);
color: rgb(var(--text-color));
@@ -28,6 +28,8 @@
transition: background .2s;
&-name {
+ font-size: var(--font-size-xs);
+
&-light {
color: rgb(var(--error-color));
}
@@ -35,7 +37,7 @@
&-desc{
display: block;
- margin-top: var(--margin-xs);
+ font-size: var(--font-size-xxs);
}
&-active {
diff --git a/packages/sheets-plugin-formula/src/controllers/calculate.controller.ts b/packages/sheets-plugin-formula/src/controllers/calculate.controller.ts
index 4389eec0a2..17a6b0fa87 100644
--- a/packages/sheets-plugin-formula/src/controllers/calculate.controller.ts
+++ b/packages/sheets-plugin-formula/src/controllers/calculate.controller.ts
@@ -74,7 +74,7 @@ export class CalculateController extends Disposable {
const cellData = new ObjectMatrix(formulaData[unitId][sheetId]);
const rangeMatrix = new ObjectMatrix(cellValue);
- const formulaIdMap = new Map<string, string>(); // Connect the formula and ID
+ const formulaIdMap = new Map<string, { f: string; r: number; c: number }>(); // Connect the formula and ID
let isArrayFormula = false;
// update formula string,Any modification to cellData will be linked to formulaData
@@ -83,10 +83,11 @@ export class CalculateController extends Disposable {
const formulaString = cell?.f || '';
const formulaId = cell?.si || '';
+ const formulaValue = cell?.v;
if (!formulaString && formulaId) {
isCalculate = true;
- cellData.setValue(r, c, { f: formulaId });
- } else if (arrayFormCellRangeData && formulaString === '') {
+ cellData.setValue(r, c, { f: formulaId }); // IFormulaDataItem only has f field
+ } else if (arrayFormCellRangeData && Tools.isBlank(formulaValue)) {
isArrayFormula = true;
isCalculate = true;
@@ -104,7 +105,7 @@ export class CalculateController extends Disposable {
cellData.setValue(r, c, { f: formulaString });
if (isFormulaId(formulaId)) {
- formulaIdMap.set(formulaId, formulaString);
+ formulaIdMap.set(formulaId, { f: formulaString, r, c });
}
}
});
@@ -112,8 +113,16 @@ export class CalculateController extends Disposable {
// Convert the formula ID to formula string
cellData.forValue((r, c, cell) => {
const formulaId = cell?.f || '';
+ // TODO@Dushusir: remove formulaIdMap
if (formulaIdMap.has(formulaId)) {
- cellData.setValue(r, c, { f: formulaIdMap.get(formulaId) as string });
+ const formulaInfo = formulaIdMap.get(formulaId);
+ if (!formulaInfo) return false;
+
+ const f = formulaInfo.f;
+ const x = r - formulaInfo.r;
+ const y = c - formulaInfo.c;
+
+ cellData.setValue(r, c, { f, x, y });
}
});
diff --git a/packages/ui-plugin-sheets/src/components/range-selector/RangeSelector.tsx b/packages/ui-plugin-sheets/src/components/range-selector/RangeSelector.tsx
index 1a0c1a7ae7..f166746d5f 100644
--- a/packages/ui-plugin-sheets/src/components/range-selector/RangeSelector.tsx
+++ b/packages/ui-plugin-sheets/src/components/range-selector/RangeSelector.tsx
@@ -33,14 +33,33 @@ export function RangeSelector(props: IRangeSelectorProps) {
}
});
+ document.addEventListener('click', handleActiveClick);
+
return () => {
+ document.removeEventListener('click', handleActiveClick);
subscribe.unsubscribe();
};
}
-
onChange(editableRef.current?.innerHTML || '');
}, [active]);
+ function handleActiveClick(e: MouseEvent) {
+ // content and footer area, used to select the area
+ const selector = (e.target as Element)?.closest('[data-range-selector="true"]');
+ if (selector) return;
+
+ // Current editor area
+ if (e.target === editableRef.current) return;
+
+ // Right button
+ const editorContainer = (e.target as Element)?.closest(`.${styles.rangeSelector}`);
+ const editor = editorContainer?.querySelector(`.${styles.rangeSelectorEditor}`);
+ if (editor === editableRef.current) return;
+
+ setActive(false);
+ editableRef.current?.blur();
+ }
+
function handleKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {
e.stopPropagation();
if (e.key === 'Enter') {
@@ -55,6 +74,10 @@ export function RangeSelector(props: IRangeSelectorProps) {
}
function handleClick() {
+ if (!active) {
+ editableRef.current?.focus();
+ return;
+ }
setActive(!active);
}
diff --git a/packages/ui-plugin-sheets/src/components/range-selector/index.module.less b/packages/ui-plugin-sheets/src/components/range-selector/index.module.less
index 69c25128b6..f616534f16 100644
--- a/packages/ui-plugin-sheets/src/components/range-selector/index.module.less
+++ b/packages/ui-plugin-sheets/src/components/range-selector/index.module.less
@@ -9,7 +9,7 @@
align-items: center;
justify-content: space-between;
- padding: @padding-top-bottom var(--padding-sm) @padding-top-bottom var(--padding-base);
+ padding: 0 var(--padding-sm) 0 var(--padding-base);
border: 1px solid rgb(var(--border-color));
@@ -23,6 +23,7 @@
width: @width;
height: @height;
+ padding: @padding-top-bottom 0;
font-size: var(--font-size-xs);
line-height: @height;
diff --git a/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.ts b/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.ts
index 56e82ee8dd..c3efee6bd0 100644
--- a/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.ts
@@ -254,7 +254,8 @@ export class AutoFillController extends Disposable {
}
isReverse && data.reverse();
// special rules must provide custom SERIES apply functions, or will be applied as copy
- return fillCopy(data, len);
+ const copyFunc = customApplyFunctions?.[APPLY_TYPE.COPY] || fillCopy;
+ return copyFunc(data, len, direction);
}
if (applyType === APPLY_TYPE.ONLY_FORMAT) {
const custom = customApplyFunctions?.[APPLY_TYPE.ONLY_FORMAT];
@@ -581,7 +582,10 @@ export class AutoFillController extends Disposable {
private _hasSeries(copyData: ICopyDataPiece[]) {
return copyData.some((copyDataPiece) => {
const res = Object.keys(copyDataPiece).some((type) => {
- if (copyDataPiece[type as DATA_TYPE]?.length && type !== DATA_TYPE.OTHER) {
+ if (
+ copyDataPiece[type as DATA_TYPE]?.length &&
+ ![DATA_TYPE.OTHER, DATA_TYPE.FORMULA].includes(type as DATA_TYPE)
+ ) {
return true;
}
return false;
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.ts
index 3abb5db0ff..2d2f746239 100644
--- 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.ts
@@ -15,6 +15,7 @@ import {
chnWeek2Rule,
chnWeek3Rule,
extendNumberRule,
+ formulaRule,
loopSeriesRule,
numberRule,
otherRule,
@@ -84,6 +85,7 @@ export class AutoFillService extends Disposable implements IAutoFillService {
private _init() {
this._rules = [
+ formulaRule,
numberRule,
extendNumberRule,
chnNumberRule,
diff --git a/packages/ui-plugin-sheets/src/services/auto-fill/rules.ts b/packages/ui-plugin-sheets/src/services/auto-fill/rules.ts
index a58feb03bf..a23912d1b3 100644
--- a/packages/ui-plugin-sheets/src/services/auto-fill/rules.ts
+++ b/packages/ui-plugin-sheets/src/services/auto-fill/rules.ts
@@ -1,10 +1,11 @@
-import { Direction } from '@univerjs/core';
+import { Direction, isFormulaString } from '@univerjs/core';
import {
chineseToNumber,
fillChnNumber,
fillChnWeek,
fillCopy,
+ fillCopyFormula,
fillExtendNumber,
fillLoopSeries,
fillSeries,
@@ -333,3 +334,21 @@ export const loopSeriesRule: IAutoFillRule = {
},
},
};
+
+/**
+ * TODO@Dushusir: move to formula plugin after register function is supported
+ */
+export const formulaRule: IAutoFillRule = {
+ type: DATA_TYPE.FORMULA,
+ match: (cellData) => isFormulaString(cellData?.f),
+ isContinue: (prev, cur) => {
+ if (prev.type === DATA_TYPE.FORMULA) {
+ return true;
+ }
+ return false;
+ },
+ applyFunctions: {
+ // FIXME@Dushusir: COPY not work
+ [APPLY_TYPE.COPY]: (data, len, direction) => fillCopyFormula(data, len, direction),
+ },
+};
diff --git a/packages/ui-plugin-sheets/src/services/auto-fill/tools.ts b/packages/ui-plugin-sheets/src/services/auto-fill/tools.ts
index 3fcae9ffed..f6fab19425 100644
--- a/packages/ui-plugin-sheets/src/services/auto-fill/tools.ts
+++ b/packages/ui-plugin-sheets/src/services/auto-fill/tools.ts
@@ -30,6 +30,7 @@ export function getEmptyCopyDataPiece(): ICopyDataPiece {
[DATA_TYPE.CHN_NUMBER]: [],
[DATA_TYPE.CHN_WEEK2]: [],
[DATA_TYPE.CHN_WEEK3]: [],
+ [DATA_TYPE.FORMULA]: [],
[DATA_TYPE.OTHER]: [],
};
}
@@ -632,3 +633,105 @@ export function fillLoopSeries(data: Array<Nullable<ICellData>>, len: number, st
return applyData;
}
+
+/**
+ * TODO@Dushusir: add step
+ * @param data
+ * @param len
+ * @param direction
+ * @returns
+ */
+export function fillCopyFormula(data: Array<Nullable<ICellData>>, len: number, direction: Direction) {
+ const applyData = [];
+ let formulaId: string = '';
+
+ for (let i = 1; i <= len; i++) {
+ const index = (i - 1) % data.length;
+ const d = Tools.deepClone(data[index]);
+
+ if (d) {
+ const originalFormula = data[index]?.f;
+
+ if (originalFormula) {
+ // The first position setting formula and formulaId
+ if (i === 1) {
+ const shiftedFormula = shiftFormula(originalFormula, i, direction);
+ d.si = d.si || Tools.generateRandomId(6);
+ formulaId = d.si;
+ d.f = shiftedFormula;
+ d.v = null;
+ } else {
+ // At the beginning of the second formula, set formulaId only
+ d.si = formulaId;
+ d.f = null;
+ d.v = null;
+ }
+
+ if (direction === Direction.DOWN || direction === Direction.RIGHT) {
+ applyData.push(d);
+ } else {
+ applyData.unshift(d);
+ }
+ }
+ }
+ }
+
+ return applyData;
+}
+
+function shiftFormula(originalFormula: string, shift: number, direction: Direction): string {
+ const tokens = tokenizeFormula(originalFormula);
+ const shiftedTokens = [];
+
+ for (const token of tokens) {
+ if (isCellReference(token)) {
+ const shiftedReference = shiftCellReference(token, shift, direction);
+ shiftedTokens.push(shiftedReference);
+ } else {
+ shiftedTokens.push(token);
+ }
+ }
+
+ return shiftedTokens.join('');
+}
+
+function tokenizeFormula(formula: string): string[] {
+ const regex = /([A-Z]+\d+|[A-Z]+|\d+|\S)/g;
+ return formula.match(regex) || [];
+}
+
+function isCellReference(token: string): boolean {
+ const cellReferenceRegex = /^[A-Z]+\d+$/;
+ return cellReferenceRegex.test(token);
+}
+
+function shiftCellReference(cellReference: string, shift: number, direction: Direction): string {
+ const [col, row] = extractColRow(cellReference);
+
+ let shiftedCol = col;
+ let shiftedRow = row;
+
+ if (direction === Direction.DOWN) {
+ shiftedRow += shift;
+ } else if (direction === Direction.RIGHT) {
+ shiftedCol = shiftColumn(col, shift);
+ } else if (direction === Direction.UP) {
+ shiftedRow -= shift;
+ } else if (direction === Direction.LEFT) {
+ shiftedCol = shiftColumn(col, -shift);
+ }
+
+ return shiftedCol + shiftedRow;
+}
+
+function extractColRow(cellReference: string): [string, number] {
+ const col = cellReference.replace(/\d/g, '');
+ const row = parseInt(cellReference.replace(/[A-Z]+/g, ''), 10);
+ return [col, row];
+}
+
+function shiftColumn(col: string, shift: number): string {
+ const currentCharCode = col.charCodeAt(0);
+ const shiftedCharCode = currentCharCode + shift;
+ return String.fromCharCode(shiftedCharCode);
+}
diff --git a/packages/ui-plugin-sheets/src/services/auto-fill/type.ts b/packages/ui-plugin-sheets/src/services/auto-fill/type.ts
index 5771ff8c6a..cddf752e45 100644
--- a/packages/ui-plugin-sheets/src/services/auto-fill/type.ts
+++ b/packages/ui-plugin-sheets/src/services/auto-fill/type.ts
@@ -8,6 +8,7 @@ export enum DATA_TYPE {
CHN_WEEK2 = 'chnWeek2',
CHN_WEEK3 = 'chnWeek3',
LOOP_SERIES = 'loopSeries',
+ FORMULA = 'formula',
OTHER = 'other',
}
diff --git a/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx b/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx
index 19c00d0691..badfa76634 100644
--- a/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx
+++ b/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx
@@ -17,7 +17,7 @@ export interface BaseSheetContainerProps {
export function RenderSheetFooter() {
return (
- <section className={styles.sheetContainer}>
+ <section className={styles.sheetContainer} data-range-selector>
<SheetBar />
<StatusBar />
<CountBar />