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(sheet): defined name (#1737)

Univercfa9375720ac
diff --git a/packages/core/src/shared/tools.ts b/packages/core/src/shared/tools.ts
index 2fe9ada525..5ab4695b73 100644
--- a/packages/core/src/shared/tools.ts
+++ b/packages/core/src/shared/tools.ts
@@ -652,4 +652,23 @@ export class Tools {
) {
return range1End >= range2Start && range2End >= range1Start;
}
+
+ static isStartValidPosition(name: string): boolean {
+ const startsWithLetterOrUnderscore = /^[A-Za-z_]/.test(name);
+
+ return startsWithLetterOrUnderscore;
+ }
+
+ static isValidParameter(name: string): boolean {
+ /**
+ *Validates that the name does not contain spaces or disallowed characters
+ *Assuming the set of disallowed characters includes some special characters,
+ *you can modify the regex below according to the actual requirements
+ */
+ const containsInvalidChars = /[~!@#$%^&*()+=\-{}\[\]\|:;"'<>,?\/ ]+/.test(name);
+
+ const isValidLength = name.length <= 255;
+
+ return !containsInvalidChars && isValidLength;
+ }
}
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index b0d0affba7..9c1c5529a7 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -89,6 +89,10 @@ export interface IDirtyUnitSheetNameMap {
[unitId: string]: Nullable<{ [sheetId: string]: string }>;
}
+export interface IDirtyUnitSheetDefinedNameMap {
+ [unitId: string]: Nullable<{ [name: string]: string }>;
+}
+
export interface IDirtyUnitFeatureMap {
[unitId: string]: Nullable<{ [sheetId: string]: { [featureId: string]: boolean } }>;
}
@@ -157,6 +161,7 @@ export interface IFormulaDatasetConfig {
forceCalculate: boolean;
dirtyRanges: IUnitRange[];
dirtyNameMap: IDirtyUnitSheetNameMap;
+ dirtyDefinedNameMap: IDirtyUnitSheetNameMap;
dirtyUnitFeatureMap: IDirtyUnitFeatureMap;
dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap;
numfmtItemMap: INumfmtItemMap;
diff --git a/packages/engine-formula/src/basics/function.ts b/packages/engine-formula/src/basics/function.ts
index a8087818ca..d0e467980e 100644
--- a/packages/engine-formula/src/basics/function.ts
+++ b/packages/engine-formula/src/basics/function.ts
@@ -116,6 +116,11 @@ export enum FunctionType {
* User-defined functions
*/
User,
+
+ /**
+ * Defined name
+ */
+ DefinedName,
}
export interface IFunctionParam {
diff --git a/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts b/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts
index 430690b4d2..5c08605685 100644
--- a/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts
@@ -14,16 +14,22 @@
* limitations under the License.
*/
-import type { IMutation } from '@univerjs/core';
+import type { IMutation, IRange } from '@univerjs/core';
import { CommandType } from '@univerjs/core';
+import type { IAccessor } from '@wendellhu/redi';
+import { IDefinedNamesService } from '../../services/defined-names.service';
export interface ISetDefinedNameMutationSearchParam {
unitId: string;
- name: string;
+ id: string;
}
export interface ISetDefinedNameMutationParam extends ISetDefinedNameMutationSearchParam {
+ name: string;
formulaOrRefString: string;
+ comment?: string;
+ localSheetId?: string;
+ hidden?: boolean;
}
/**
* In the formula engine, the mutation is solely responsible for communication between the worker and the main thread.
@@ -35,8 +41,29 @@ export const SetDefinedNameMutation: IMutation<ISetDefinedNameMutationParam> = {
handler: () => true,
};
-export const RemoveDefinedNameMutation: IMutation<ISetDefinedNameMutationSearchParam> = {
+export const RemoveDefinedNameMutation: IMutation<ISetDefinedNameMutationParam> = {
id: 'formula.mutation.remove-defined-name',
type: CommandType.MUTATION,
handler: () => true,
};
+
+export interface ISetDefinedNameCurrentMutationParam {
+ unitId: string;
+ sheetId: string;
+ range: IRange;
+};
+
+export const SetDefinedNameCurrentMutation: IMutation<ISetDefinedNameCurrentMutationParam> = {
+ id: 'formula.mutation.set-defined-name-current',
+ type: CommandType.MUTATION,
+ handler: (accessor: IAccessor, params: ISetDefinedNameCurrentMutationParam) => {
+ const definedNamesService = accessor.get(IDefinedNamesService);
+ const { unitId, sheetId, range } = params;
+ definedNamesService.setCurrentRange({
+ range,
+ unitId,
+ sheetId,
+ });
+ return true;
+ },
+};
diff --git a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
index f3927d9a71..1e441ee134 100644
--- a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
@@ -20,6 +20,7 @@ import { CommandType } from '@univerjs/core';
import type {
IDirtyUnitFeatureMap,
IDirtyUnitOtherFormulaMap,
+ IDirtyUnitSheetDefinedNameMap,
IDirtyUnitSheetNameMap,
INumfmtItemMap,
IRuntimeOtherUnitDataType,
@@ -30,6 +31,7 @@ import type { FormulaExecutedStateType, IExecutionInProgressParams } from '../..
export interface ISetFormulaCalculationStartMutation {
dirtyRanges: IUnitRange[];
dirtyNameMap: IDirtyUnitSheetNameMap;
+ dirtyDefinedNameMap: IDirtyUnitSheetDefinedNameMap;
dirtyUnitFeatureMap: IDirtyUnitFeatureMap;
dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap;
options: Nullable<IExecutionOptions>;
diff --git a/packages/engine-formula/src/controller/calculate.controller.ts b/packages/engine-formula/src/controller/calculate.controller.ts
index 64185f805d..b769eb15f0 100644
--- a/packages/engine-formula/src/controller/calculate.controller.ts
+++ b/packages/engine-formula/src/controller/calculate.controller.ts
@@ -18,7 +18,7 @@ import type { ICommandInfo, IUnitRange } from '@univerjs/core';
import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, Tools } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import type { IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetNameMap, IFormulaData, INumfmtItemMap } from '../basics/common';
+import type { IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetDefinedNameMap, IDirtyUnitSheetNameMap, IFormulaData, INumfmtItemMap } from '../basics/common';
import type { ISetArrayFormulaDataMutationParams } from '../commands/mutations/set-array-formula-data.mutation';
import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';
import type { ISetFormulaCalculationStartMutation } from '../commands/mutations/set-formula-calculation.mutation';
@@ -71,9 +71,9 @@ export class CalculateController extends Disposable {
if (params.forceCalculation === true) {
this._calculate(true);
} else {
- const { dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap, numfmtItemMap } = params;
+ const { dirtyRanges, dirtyNameMap, dirtyDefinedNameMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap, numfmtItemMap } = params;
- this._calculate(false, dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap, numfmtItemMap);
+ this._calculate(false, dirtyRanges, dirtyNameMap, dirtyDefinedNameMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap, numfmtItemMap);
}
} else if (command.id === SetArrayFormulaDataMutation.id) {
const params = command.params as ISetArrayFormulaDataMutationParams;
@@ -94,6 +94,7 @@ export class CalculateController extends Disposable {
forceCalculate: boolean = false,
dirtyRanges: IUnitRange[] = [],
dirtyNameMap: IDirtyUnitSheetNameMap = {},
+ dirtyDefinedNameMap: IDirtyUnitSheetDefinedNameMap = {},
dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {},
dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {},
numfmtItemMap: INumfmtItemMap = {}
@@ -101,6 +102,7 @@ export class CalculateController extends Disposable {
if (
dirtyRanges.length === 0 &&
Object.keys(dirtyNameMap).length === 0 &&
+ Object.keys(dirtyDefinedNameMap).length === 0 &&
Object.keys(dirtyUnitFeatureMap).length === 0 &&
Object.keys(dirtyUnitOtherFormulaMap).length === 0 &&
forceCalculate === false
@@ -120,6 +122,7 @@ export class CalculateController extends Disposable {
forceCalculate,
dirtyRanges,
dirtyNameMap,
+ dirtyDefinedNameMap,
dirtyUnitFeatureMap,
dirtyUnitOtherFormulaMap,
numfmtItemMap,
diff --git a/packages/engine-formula/src/controller/formula.controller.ts b/packages/engine-formula/src/controller/formula.controller.ts
index 3291cbc3c9..40b3dba526 100644
--- a/packages/engine-formula/src/controller/formula.controller.ts
+++ b/packages/engine-formula/src/controller/formula.controller.ts
@@ -21,7 +21,7 @@ import { Inject, Injector } from '@wendellhu/redi';
import type { IFunctionNames } from '../basics/function';
import { RegisterFunctionMutation } from '../commands/mutations/register-function.mutation';
import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';
-import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '../commands/mutations/set-defined-name.mutation';
+import { RemoveDefinedNameMutation, SetDefinedNameCurrentMutation, SetDefinedNameMutation } from '../commands/mutations/set-defined-name.mutation';
import {
RemoveFeatureCalculationMutation,
SetFeatureCalculationMutation,
@@ -90,6 +90,7 @@ export class FormulaController extends Disposable {
SetDefinedNameMutation,
RemoveDefinedNameMutation,
+ SetDefinedNameCurrentMutation,
SetFeatureCalculationMutation,
RemoveFeatureCalculationMutation,
diff --git a/packages/engine-formula/src/controller/set-defined-name.controller.ts b/packages/engine-formula/src/controller/set-defined-name.controller.ts
index 464a0c2e02..b0ba87d270 100644
--- a/packages/engine-formula/src/controller/set-defined-name.controller.ts
+++ b/packages/engine-formula/src/controller/set-defined-name.controller.ts
@@ -47,15 +47,22 @@ export class SetDefinedNameController extends Disposable {
if (params == null) {
return;
}
- const { unitId, name, formulaOrRefString } = params;
- this._definedNamesService.registerDefinedName(unitId, name, formulaOrRefString);
+ const { id, unitId, name, formulaOrRefString, comment, hidden, localSheetId } = params;
+ this._definedNamesService.registerDefinedName(unitId, {
+ id,
+ name: name.trim(),
+ formulaOrRefString: formulaOrRefString.trim(),
+ comment: comment?.trim(),
+ hidden,
+ localSheetId,
+ });
} else if (command.id === RemoveDefinedNameMutation.id) {
const params = command.params as ISetDefinedNameMutationSearchParam;
if (params == null) {
return;
}
- const { unitId, name } = params;
- this._definedNamesService.removeDefinedName(unitId, name);
+ const { unitId, id } = params;
+ this._definedNamesService.removeDefinedName(unitId, id);
}
})
);
diff --git a/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts
index 4679935ceb..0edfb94aaf 100644
--- a/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts
+++ b/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts
@@ -16,6 +16,7 @@
import { describe, expect, it } from 'vitest';
+import { AbsoluteRefType } from '@univerjs/core';
import type { LexerNode } from '../lexer-node';
import { LexerTreeBuilder } from '../lexer-tree-builder';
import { ErrorType } from '../../../basics/error-type';
@@ -393,4 +394,41 @@ describe('lexer nodeMaker test', () => {
]);
});
});
+
+ describe('convertRefersToAbsolute', () => {
+ it('Formula All', () => {
+ const result = lexerTreeBuilder.convertRefersToAbsolute('=sum(A1:B1,A1:B1,A1:B1,A1:B1)', AbsoluteRefType.ALL, AbsoluteRefType.ALL);
+ expect(result).toStrictEqual('=sum($A$1:$B$1,$A$1:$B$1,$A$1:$B$1,$A$1:$B$1)');
+ });
+
+ it('Range All', () => {
+ const result = lexerTreeBuilder.convertRefersToAbsolute('A1:B1,A1:B1,A1:B1,A1:B1', AbsoluteRefType.ALL, AbsoluteRefType.ALL);
+ expect(result).toStrictEqual('$A$1:$B$1,$A$1:$B$1,$A$1:$B$1,$A$1:$B$1');
+ });
+
+ it('Formula Column', () => {
+ const result = lexerTreeBuilder.convertRefersToAbsolute('=sum(A1:B1,A1:B1,A1:B1,A1:B1)', AbsoluteRefType.COLUMN, AbsoluteRefType.COLUMN);
+ expect(result).toStrictEqual('=sum($A1:$B1,$A1:$B1,$A1:$B1,$A1:$B1)');
+ });
+
+ it('Range Column', () => {
+ const result = lexerTreeBuilder.convertRefersToAbsolute('A1:B1,A1:B1,A1:B1,A1:B1', AbsoluteRefType.COLUMN, AbsoluteRefType.COLUMN);
+ expect(result).toStrictEqual('$A1:$B1,$A1:$B1,$A1:$B1,$A1:$B1');
+ });
+
+ it('Formula Row', () => {
+ const result = lexerTreeBuilder.convertRefersToAbsolute('=sum(A1:B1,A1:B1,A1:B1,A1:B1)', AbsoluteRefType.ROW, AbsoluteRefType.ROW);
+ expect(result).toStrictEqual('=sum(A$1:B$1,A$1:B$1,A$1:B$1,A$1:B$1)');
+ });
+
+ it('Range Row', () => {
+ const result = lexerTreeBuilder.convertRefersToAbsolute('A1:B1,A1:B1,A1:B1,A1:B1', AbsoluteRefType.ROW, AbsoluteRefType.ROW);
+ expect(result).toStrictEqual('A$1:B$1,A$1:B$1,A$1:B$1,A$1:B$1');
+ });
+
+ it('Complex Formula', () => {
+ const result = lexerTreeBuilder.convertRefersToAbsolute('=SUM(A1:B10) + LAMBDA(x, y, x*y*x)(A1:B10, A10) + MAX(A1:B10,SUM(A2))', AbsoluteRefType.ALL, AbsoluteRefType.ALL);
+ expect(result).toStrictEqual('=SUM($A$1:$B$10) + LAMBDA(x, y, x*y*x)($A$1:$B$10,$A$10) + MAX($A$1:$B$10,SUM($A$2))');
+ });
+ });
});
diff --git a/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.ts
index 8654508908..39ebc2e3aa 100644
--- a/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.ts
+++ b/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.ts
@@ -20,10 +20,10 @@ import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { IDefinedNamesService } from '../../../services/defined-names.service';
-import { IFormulaRuntimeService } from '../../../services/runtime.service';
import { Lexer } from '../lexer';
import type { LexerNode } from '../lexer-node';
import { LexerTreeBuilder } from '../lexer-tree-builder';
+import { IFormulaCurrentConfigService } from '../../../services/current-data.service';
import { createCommandTestBed } from './create-command-test-bed';
const TEST_WORKBOOK_DATA: IWorkbookData = {
@@ -68,7 +68,7 @@ describe('lexer nodeMaker test', () => {
let get: Injector['get'];
let workbook: Workbook;
let definedNamesService: IDefinedNamesService;
- let runtimeService: IFormulaRuntimeService;
+ let formulaCurrentConfigService: IFormulaCurrentConfigService;
let lexerTreeBuilder: LexerTreeBuilder;
beforeEach(() => {
@@ -79,13 +79,16 @@ describe('lexer nodeMaker test', () => {
definedNamesService = get(IDefinedNamesService);
- runtimeService = get(IFormulaRuntimeService);
+ formulaCurrentConfigService = get(IFormulaCurrentConfigService);
lexerTreeBuilder = get(LexerTreeBuilder);
- runtimeService.setCurrent(0, 0, 4, 1, 'sheet1', 'test');
+ formulaCurrentConfigService.setExecuteUnitId('test');
+ formulaCurrentConfigService.setExecuteSubUnitId('sheet1');
- lexer = new Lexer(definedNamesService, runtimeService, lexerTreeBuilder);
+ // runtimeService.setCurrent(0, 0, 4, 1, 'sheet1', 'test');
+
+ lexer = new Lexer(definedNamesService, lexerTreeBuilder, formulaCurrentConfigService);
});
afterEach(() => {
@@ -94,7 +97,7 @@ describe('lexer nodeMaker test', () => {
describe('lexer definedName', () => {
it('simple', () => {
- definedNamesService.registerDefinedName('test', 'myName', '$A$10:$C$100');
+ definedNamesService.registerDefinedName('test', { id: 'test1', name: 'myName', formulaOrRefString: '$A$10:$C$100' });
const node = lexer.treeBuilder('=myName') as LexerNode;
@@ -104,7 +107,7 @@ describe('lexer nodeMaker test', () => {
});
it('lambda', () => {
- definedNamesService.registerDefinedName('test', 'myName', 'lambda(x, y , x*x*y)');
+ definedNamesService.registerDefinedName('test', { id: 'test2', name: 'myName', formulaOrRefString: 'lambda(x, y , x*x*y)' });
const node = lexer.treeBuilder('=myName(1+sum(A1:B1), 100)') as LexerNode;
diff --git a/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts
index 372ea2997b..ab40399809 100644
--- a/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts
+++ b/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts
@@ -64,6 +64,7 @@ describe('Test indirect', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
dirtyUnitOtherFormulaMap: {},
excludedCell: {},
diff --git a/packages/engine-formula/src/engine/analysis/lexer-node.ts b/packages/engine-formula/src/engine/analysis/lexer-node.ts
index b6bad08d6b..464b242322 100644
--- a/packages/engine-formula/src/engine/analysis/lexer-node.ts
+++ b/packages/engine-formula/src/engine/analysis/lexer-node.ts
@@ -46,6 +46,8 @@ export class LexerNode {
private _endIndex: number = -1;
+ private _definedNames: Array<string> = [];
+
dispose() {
this._children.forEach((node) => {
if (!(typeof node === 'string')) {
@@ -57,6 +59,10 @@ export class LexerNode {
this._parent = null;
}
+ getDefinedNames() {
+ return this._definedNames;
+ }
+
getStartIndex() {
return this._startIndex;
}
@@ -122,6 +128,14 @@ export class LexerNode {
this._endIndex = ed;
}
+ setDefinedNames(definedNames: Array<string>) {
+ this._definedNames = definedNames;
+ }
+
+ hasDefinedNames() {
+ return this._definedNames.length > 0;
+ }
+
replaceChild(lexerNode: LexerNode, newLexerNode: LexerNode) {
const i = this._getIndexInParent(lexerNode);
diff --git a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
index ccc987ddff..9ad5c8fe34 100644
--- a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
+++ b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
+import type { AbsoluteRefType, Nullable } from '@univerjs/core';
import { Disposable, isValidRange, Rectangle, Tools } from '@univerjs/core';
import { FormulaAstLRU } from '../../basics/cache-lru';
@@ -275,6 +275,70 @@ export class LexerTreeBuilder extends Disposable {
return bracketCount;
}
+ convertRefersToAbsolute(formulaString: string, startAbsoluteRefType: AbsoluteRefType, endAbsoluteRefType: AbsoluteRefType) {
+ const nodes = this.sequenceNodesBuilder(formulaString);
+ if (nodes == null) {
+ return formulaString;
+ }
+
+ let prefixToken = '';
+ if (formulaString.substring(0, 1) === operatorToken.EQUALS) {
+ prefixToken = operatorToken.EQUALS;
+ }
+
+ for (let i = 0, len = nodes.length; i < len; i++) {
+ const node = nodes[i];
+ if (typeof node === 'string') {
+ continue;
+ }
+
+ if (node.nodeType === sequenceNodeType.REFERENCE) {
+ const { token, endIndex } = node;
+ const sequenceGrid = deserializeRangeWithSheet(token);
+ if (sequenceGrid == null) {
+ continue;
+ }
+
+ const { range, sheetName, unitId } = sequenceGrid;
+
+ const newRange = {
+ ...range,
+ startAbsoluteRefType,
+ endAbsoluteRefType,
+ };
+
+ const newToken = serializeRangeToRefString({
+ range: newRange,
+ unitId,
+ sheetName,
+ });
+
+ const minusCount = newToken.length - token.length;
+
+ nodes[i] = {
+ ...node,
+ token: newToken,
+ endIndex: endIndex + minusCount,
+ };
+
+ /**
+ * Adjust the start and end indexes of the subsequent nodes.
+ */
+ for (let j = i + 1; j < len; j++) {
+ const nextNode = nodes[j];
+ if (typeof nextNode === 'string') {
+ continue;
+ }
+
+ nextNode.startIndex += minusCount;
+ nextNode.endIndex += minusCount;
+ }
+ }
+ }
+
+ return `${prefixToken}${generateStringWithSequence(nodes)}`;
+ }
+
sequenceNodesBuilder(formulaString: string) {
const sequenceNodesCache = FormulaSequenceNodeCache.get(formulaString);
if (sequenceNodesCache) {
@@ -519,11 +583,14 @@ export class LexerTreeBuilder extends Disposable {
injectDefinedName?: (sequenceArray: ISequenceArray[]) => {
sequenceString: string;
hasDefinedName: boolean;
- }
+ definedNames: string[];
+ },
+ simpleCheckDefinedName?: (formulaString: string) => boolean
) {
if (transformSuffix === true) {
const lexerNode = FormulaLexerNodeCache.get(formulaString);
- if (lexerNode) {
+ const simpleCheckDefinedNameResult = simpleCheckDefinedName?.(formulaString);
+ if (lexerNode && !simpleCheckDefinedNameResult) {
return lexerNode;
}
}
@@ -544,12 +611,16 @@ export class LexerTreeBuilder extends Disposable {
let currentSequenceString = '';
+ let currentDefinedNames: string[] = [];
+
if (injectDefinedName) {
- const { hasDefinedName, sequenceString } = injectDefinedName(sequenceArray);
+ const { hasDefinedName, sequenceString, definedNames } = injectDefinedName(sequenceArray);
currentHasDefinedName = hasDefinedName;
currentSequenceString = sequenceString;
+
+ currentDefinedNames = definedNames;
}
/**
@@ -583,6 +654,10 @@ export class LexerTreeBuilder extends Disposable {
FormulaLexerNodeCache.set(formulaString, this._currentLexerNode);
}
+ if (currentHasDefinedName) {
+ this._currentLexerNode.setDefinedNames(currentDefinedNames);
+ }
+
return this._currentLexerNode;
}
diff --git a/packages/engine-formula/src/engine/analysis/lexer.ts b/packages/engine-formula/src/engine/analysis/lexer.ts
index 1f615565ee..1ccc06b0af 100644
--- a/packages/engine-formula/src/engine/analysis/lexer.ts
+++ b/packages/engine-formula/src/engine/analysis/lexer.ts
@@ -18,37 +18,73 @@ import { Disposable } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import { IDefinedNamesService } from '../../services/defined-names.service';
-import { IFormulaRuntimeService } from '../../services/runtime.service';
import type { ISequenceArray } from '../utils/sequence';
import { sequenceNodeType } from '../utils/sequence';
+import { operatorToken } from '../../basics/token';
+import { IFormulaCurrentConfigService } from '../../services/current-data.service';
+import { ErrorType } from '../../basics/error-type';
import { LexerTreeBuilder } from './lexer-tree-builder';
export class Lexer extends Disposable {
constructor(
@IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,
- @IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService,
- @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder
+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
+ @IFormulaCurrentConfigService private readonly _formulaCurrentConfigService: IFormulaCurrentConfigService
) {
super();
}
treeBuilder(formulaString: string, transformSuffix = true) {
- return this._lexerTreeBuilder.treeBuilder(formulaString, transformSuffix, this._injectDefinedName.bind(this));
+ return this._lexerTreeBuilder.treeBuilder(formulaString, transformSuffix, this._injectDefinedName.bind(this), this._simpleCheckDefinedName.bind(this));
+ }
+
+ private _simpleCheckDefinedName(formulaString: string) {
+ const definedNameMap = this._formulaCurrentConfigService.getDirtyDefinedNameMap();
+ const executeUnitId = this._formulaCurrentConfigService.getExecuteUnitId();
+ if (executeUnitId != null && definedNameMap[executeUnitId] != null) {
+ const names = Object.keys(definedNameMap[executeUnitId]!);
+ for (let i = 0, len = names.length; i < len; i++) {
+ const name = names[i];
+ if (formulaString.indexOf(name) > -1) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private _checkDefinedNameDirty(token: string) {
+ const definedNameMap = this._formulaCurrentConfigService.getDirtyDefinedNameMap();
+ const executeUnitId = this._formulaCurrentConfigService.getExecuteUnitId();
+ if (executeUnitId != null && definedNameMap[executeUnitId] != null) {
+ const names = Object.keys(definedNameMap[executeUnitId]!);
+ for (let i = 0, len = names.length; i < len; i++) {
+ const name = names[i];
+ if (name === token) {
+ return true;
+ }
+ }
+ }
+
+ return false;
}
private _injectDefinedName(sequenceArray: ISequenceArray[]) {
- const unitId = this._runtimeService.currentUnitId;
+ const unitId = this._formulaCurrentConfigService.getExecuteUnitId();
- if (!this._definedNamesService.hasDefinedName(unitId)) {
+ if (unitId == null) {
return {
sequenceString: '',
hasDefinedName: false,
+ definedNames: [],
};
}
const sequenceNodes = this._lexerTreeBuilder.getSequenceNode(sequenceArray);
let sequenceString = '';
let hasDefinedName = false;
+ const definedNames: string[] = [];
for (let i = 0, len = sequenceNodes.length; i < len; i++) {
const node = sequenceNodes[i];
@@ -60,10 +96,19 @@ export class Lexer extends Disposable {
const { nodeType, token } = node;
if (nodeType === sequenceNodeType.REFERENCE || nodeType === sequenceNodeType.FUNCTION) {
- const definedContent = this._definedNamesService.getDefinedNameMap(unitId)?.get(token);
+ const definedContent = this._definedNamesService.getValueByName(unitId, token);
if (definedContent) {
- sequenceString += definedContent;
+ let refString = definedContent.formulaOrRefString;
+ if (refString.substring(0, 1) === operatorToken.EQUALS) {
+ refString = refString.substring(1);
+ }
+ sequenceString += refString;
+ definedNames.push(definedContent.name);
+ hasDefinedName = true;
+ } else if (this._checkDefinedNameDirty(token)) {
+ sequenceString += ErrorType.NAME;
hasDefinedName = true;
+ definedNames.push(token);
} else {
sequenceString += token;
}
@@ -75,6 +120,7 @@ export class Lexer extends Disposable {
return {
sequenceString,
hasDefinedName,
+ definedNames,
};
}
}
diff --git a/packages/engine-formula/src/engine/analysis/parser.ts b/packages/engine-formula/src/engine/analysis/parser.ts
index 976b53b74e..1d9ea6af3b 100644
--- a/packages/engine-formula/src/engine/analysis/parser.ts
+++ b/packages/engine-formula/src/engine/analysis/parser.ts
@@ -87,10 +87,20 @@ export class AstTreeBuilder extends Disposable {
this._refOffsetY = refOffsetY;
const node = this._parse(lexerNode, astNode);
+
+ /**
+ * If the lexer node has defined names, it means that the current formula contains a reference to the defined name.
+ */
+ if (lexerNode.hasDefinedNames()) {
+ node?.setDefinedNames(lexerNode.getDefinedNames());
+ }
return node;
}
private _lambdaParameterHandler(lexerNode: LexerNode, parent: LambdaNode) {
+ if (parent.getLambdaId == null) {
+ return ErrorNode.create(ErrorType.VALUE);
+ }
const lambdaId = parent.getLambdaId();
const parentAstNode = new AstRootNode(DEFAULT_TOKEN_TYPE_ROOT);
diff --git a/packages/engine-formula/src/engine/ast-node/base-ast-node.ts b/packages/engine-formula/src/engine/ast-node/base-ast-node.ts
index 707e8b22d0..e04c4392ba 100644
--- a/packages/engine-formula/src/engine/ast-node/base-ast-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/base-ast-node.ts
@@ -34,6 +34,8 @@ export type LambdaPrivacyVarType = Map<string, Nullable<BaseAstNode>>;
export class BaseAstNode extends Disposable {
private _children: BaseAstNode[] = [];
+ private _definedNames: Array<string> = [];
+
private _parent: Nullable<BaseAstNode>;
private _valueObject: Nullable<FunctionVariantType>;
@@ -166,6 +168,14 @@ export class BaseAstNode extends Disposable {
return result;
}
+
+ hasDefinedName(definedName: string) {
+ return this._definedNames.includes(definedName);
+ }
+
+ setDefinedNames(definedNames: Array<string>) {
+ this._definedNames = definedNames;
+ }
}
export class ErrorNode extends BaseAstNode {
diff --git a/packages/engine-formula/src/engine/ast-node/reference-node.ts b/packages/engine-formula/src/engine/ast-node/reference-node.ts
index 1edf334c14..57b78f20ea 100644
--- a/packages/engine-formula/src/engine/ast-node/reference-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/reference-node.ts
@@ -27,7 +27,6 @@ import {
} from '../../basics/regex';
import { matchToken } from '../../basics/token';
import { IFormulaCurrentConfigService } from '../../services/current-data.service';
-import { IDefinedNamesService } from '../../services/defined-names.service';
import { IFormulaRuntimeService } from '../../services/runtime.service';
import { ISuperTableService } from '../../services/super-table.service';
import { LexerNode } from '../analysis/lexer-node';
@@ -93,7 +92,6 @@ export class ReferenceNode extends BaseAstNode {
export class ReferenceNodeFactory extends BaseAstNodeFactory {
constructor(
- @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,
@ISuperTableService private readonly _superTableService: ISuperTableService,
@IFormulaRuntimeService private readonly _formulaRuntimeService: IFormulaRuntimeService,
@IFunctionService private readonly _functionService: IFunctionService,
diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
index 42161318e5..22753c8830 100644
--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
@@ -318,7 +318,7 @@ export class FormulaDependencyGenerator extends Disposable {
private _generateAstNode(formulaString: string, refOffsetX: number = 0, refOffsetY: number = 0) {
let astNode: Nullable<AstRootNode> = FormulaASTCache.get(`${formulaString}##${refOffsetX}${refOffsetY}`);
- if (astNode) {
+ if (astNode && !this._isDirtyDefinedForNode(astNode)) {
return astNode;
}
@@ -476,6 +476,22 @@ export class FormulaDependencyGenerator extends Disposable {
return rangeList;
}
+ private _isDirtyDefinedForNode(node: BaseAstNode) {
+ const definedNameMap = this._currentConfigService.getDirtyDefinedNameMap();
+ const executeUnitId = this._currentConfigService.getExecuteUnitId();
+ if (executeUnitId != null && definedNameMap[executeUnitId] != null) {
+ const names = Object.keys(definedNameMap[executeUnitId]!);
+ for (let i = 0, len = names.length; i < len; i++) {
+ const name = names[i];
+ if (node.hasDefinedName(name)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
/**
* Build a formula dependency tree based on the dependency relationships.
* @param treeList
@@ -567,6 +583,17 @@ export class FormulaDependencyGenerator extends Disposable {
}
}
+ /**
+ * Detect whether the dirty map contains a defined name.
+ */
+ const node = tree.node;
+ if (node != null) {
+ const dirtyDefinedName = this._isDirtyDefinedForNode(node);
+ if (dirtyDefinedName) {
+ return true;
+ }
+ }
+
const excludedCell = this._currentConfigService.getExcludedRange()?.[unitId]?.[subUnitId];
/**
diff --git a/packages/engine-formula/src/engine/utils/__tests__/reference.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/reference.spec.ts
index 45f65e5055..6cfdea9190 100644
--- a/packages/engine-formula/src/engine/utils/__tests__/reference.spec.ts
+++ b/packages/engine-formula/src/engine/utils/__tests__/reference.spec.ts
@@ -224,6 +224,20 @@ describe('Test Reference', () => {
sheetName: 'sheet-1',
unitId: 'workbook2',
});
+
+ expect(deserializeRangeWithSheet('[workbook1]sheet1!$A$5:$B$10')).toStrictEqual({
+ range: {
+ endAbsoluteRefType: 3,
+ endColumn: 1,
+ endRow: 9,
+ startAbsoluteRefType: 3,
+ startColumn: 0,
+ startRow: 4,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ sheetName: 'sheet1',
+ unitId: 'workbook1',
+ });
});
it('needsQuoting', () => {
@@ -265,35 +279,35 @@ describe('Test Reference', () => {
});
expect(handleRefStringInfo('sheet1!A1')).toStrictEqual({
- refBody: '!A1',
+ refBody: 'A1',
sheetName: 'sheet1',
unitId: '',
});
expect(handleRefStringInfo('[Book1]Sheet1!A1')).toStrictEqual({
- refBody: '!A1',
+ refBody: 'A1',
sheetName: 'Sheet1',
unitId: 'Book1',
});
expect(handleRefStringInfo("'[Book1]Sheet1'!R2C3")).toStrictEqual({
- refBody: '!R2C3',
+ refBody: 'R2C3',
sheetName: 'Sheet1',
unitId: 'Book1',
});
expect(handleRefStringInfo("'sheet-1'!A1")).toStrictEqual({
- refBody: '!A1',
+ refBody: 'A1',
sheetName: 'sheet-1',
unitId: '',
});
expect(handleRefStringInfo("'[Book-1.xlsx]Sheet1'!$A$4")).toStrictEqual({
- refBody: '!$A$4',
+ refBody: '$A$4',
sheetName: 'Sheet1',
unitId: 'Book-1.xlsx',
});
expect(handleRefStringInfo("'[Book-1.xlsx]sheet-1'!$A$4")).toStrictEqual({
- refBody: '!$A$4',
+ refBody: '$A$4',
sheetName: 'sheet-1',
unitId: 'Book-1.xlsx',
});
diff --git a/packages/engine-formula/src/engine/utils/reference.ts b/packages/engine-formula/src/engine/utils/reference.ts
index 8fb42443c0..bbb7501e1f 100644
--- a/packages/engine-formula/src/engine/utils/reference.ts
+++ b/packages/engine-formula/src/engine/utils/reference.ts
@@ -212,7 +212,7 @@ export function handleRefStringInfo(refString: string) {
if (sheetName[0] === "'" && sheetName[sheetName.length - 1] === "'") {
sheetName = sheetName.substring(1, sheetName.length - 1);
}
- refBody = refString.substring(sheetNameIndex);
+ refBody = refString.substring(sheetNameIndex + 1);
} else {
refBody = refString;
}
diff --git a/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts b/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
index 7c26e37656..3003f44669 100644
--- a/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
+++ b/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
@@ -276,6 +276,7 @@ describe('Test nested functions', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
dirtyUnitOtherFormulaMap: {},
excludedCell: {},
diff --git a/packages/engine-formula/src/functions/information/isref/__tests__/index.spec.ts b/packages/engine-formula/src/functions/information/isref/__tests__/index.spec.ts
index e8b0a053e6..d32a71ba83 100644
--- a/packages/engine-formula/src/functions/information/isref/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/information/isref/__tests__/index.spec.ts
@@ -169,6 +169,7 @@ describe('Test isref function', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
excludedCell: {},
allUnitData: {
diff --git a/packages/engine-formula/src/functions/lookup/column/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/column/__tests__/index.spec.ts
index c976486209..785c878829 100644
--- a/packages/engine-formula/src/functions/lookup/column/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/column/__tests__/index.spec.ts
@@ -60,6 +60,7 @@ describe('Test column', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
excludedCell: {},
allUnitData: {
diff --git a/packages/engine-formula/src/functions/lookup/columns/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/columns/__tests__/index.spec.ts
index 9ba99536d5..24e47a669c 100644
--- a/packages/engine-formula/src/functions/lookup/columns/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/columns/__tests__/index.spec.ts
@@ -59,6 +59,7 @@ describe('Test columns', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
excludedCell: {},
allUnitData: {
diff --git a/packages/engine-formula/src/functions/lookup/index/__test__/index.spec.ts b/packages/engine-formula/src/functions/lookup/index/__test__/index.spec.ts
index 57a1f63883..cf6b1e3fe8 100644
--- a/packages/engine-formula/src/functions/lookup/index/__test__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/index/__test__/index.spec.ts
@@ -168,6 +168,7 @@ describe('Test index', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
excludedCell: {},
allUnitData: {
diff --git a/packages/engine-formula/src/functions/lookup/indirect/__test__/index.spec.ts b/packages/engine-formula/src/functions/lookup/indirect/__test__/index.spec.ts
index 6189c6e13d..7ef6e6a75c 100644
--- a/packages/engine-formula/src/functions/lookup/indirect/__test__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/indirect/__test__/index.spec.ts
@@ -63,6 +63,7 @@ describe('Test indirect', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
dirtyUnitOtherFormulaMap: {},
excludedCell: {},
diff --git a/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts
index 665ca5c061..1839e1110a 100644
--- a/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts
@@ -163,6 +163,7 @@ describe('Test offset', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
dirtyUnitOtherFormulaMap: {},
excludedCell: {},
diff --git a/packages/engine-formula/src/functions/lookup/row/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/row/__tests__/index.spec.ts
index efcebc2416..d62a7db44d 100644
--- a/packages/engine-formula/src/functions/lookup/row/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/row/__tests__/index.spec.ts
@@ -60,6 +60,7 @@ describe('Test row', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
excludedCell: {},
allUnitData: {
diff --git a/packages/engine-formula/src/functions/lookup/rows/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/rows/__tests__/index.spec.ts
index 43becde594..cccfe01798 100644
--- a/packages/engine-formula/src/functions/lookup/rows/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/rows/__tests__/index.spec.ts
@@ -59,6 +59,7 @@ describe('Test rows', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
excludedCell: {},
allUnitData: {
diff --git a/packages/engine-formula/src/functions/math/subtotal/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/subtotal/__tests__/index.spec.ts
index 488d4db906..0e9faf9ab1 100644
--- a/packages/engine-formula/src/functions/math/subtotal/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/subtotal/__tests__/index.spec.ts
@@ -160,6 +160,7 @@ describe('Test subtotal', () => {
numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
excludedCell: {},
allUnitData: {
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 4020abe152..e72249b0a9 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -28,6 +28,7 @@ export type {
IUnitSheetNameMap,
INumfmtItemMap,
IDirtyUnitOtherFormulaMap,
+ IDirtyUnitSheetDefinedNameMap,
} from './basics/common';
export { isInDirtyRange } from './basics/dirty';
export { ErrorType } from './basics/error-type';
@@ -42,7 +43,7 @@ export {
SetArrayFormulaDataMutation,
SetArrayFormulaDataUndoMutationFactory,
} from './commands/mutations/set-array-formula-data.mutation';
-export { RemoveDefinedNameMutation, SetDefinedNameMutation } from './commands/mutations/set-defined-name.mutation';
+export { RemoveDefinedNameMutation, SetDefinedNameMutation, SetDefinedNameCurrentMutation, type ISetDefinedNameMutationSearchParam, type ISetDefinedNameMutationParam } from './commands/mutations/set-defined-name.mutation';
export {
RemoveFeatureCalculationMutation,
SetFeatureCalculationMutation,
@@ -139,8 +140,8 @@ export { SetNumfmtFormulaDataMutation } from './commands/mutations/set-numfmt-fo
export type { ISetNumfmtFormulaDataMutationParams } from './commands/mutations/set-numfmt-formula-data.mutation';
export { isReferenceString } from './basics/regex';
export { matchRefDrawToken } from './basics/match-token';
+export { IDefinedNamesService, DefinedNamesService, type IDefinedNamesServiceParam, type IDefinedNameMapItem } from './services/defined-names.service';
export { isFormulaTransformable, transformFormula } from './engine/utils/relative-formula';
-export { IDefinedNamesService, DefinedNamesService } from './services/defined-names.service';
export { IFormulaRuntimeService, FormulaRuntimeService } from './services/runtime.service';
export { IFormulaCurrentConfigService, FormulaCurrentConfigService } from './services/current-data.service';
diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.ts
index cece63c4fa..23ca7762c0 100644
--- a/packages/engine-formula/src/plugin.ts
+++ b/packages/engine-formula/src/plugin.ts
@@ -83,6 +83,7 @@ export class UniverFormulaEnginePlugin extends Plugin {
[IFeatureCalculationManagerService, { useClass: FeatureCalculationManagerService }],
[IDefinedNamesService, { useClass: DefinedNamesService }],
[IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],
+ [ISuperTableService, { useClass: SuperTableService }],
// Models
[FormulaDataModel],
@@ -98,6 +99,8 @@ export class UniverFormulaEnginePlugin extends Plugin {
},
],
[SetFeatureCalculationController],
+ [SetDefinedNameController],
+ [SetSuperTableController],
];
if (!this._config?.notExecuteFormula) {
@@ -106,15 +109,12 @@ export class UniverFormulaEnginePlugin extends Plugin {
// Services
[CalculateFormulaService],
[IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }],
- [ISuperTableService, { useClass: SuperTableService }],
[IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }],
[IFormulaRuntimeService, { useClass: FormulaRuntimeService }],
//Controller
[CalculateController],
- [SetDefinedNameController],
[SetOtherFormulaController],
- [SetSuperTableController],
[RegisterFunctionController],
// Calculation engine
diff --git a/packages/engine-formula/src/services/active-dirty-manager.service.ts b/packages/engine-formula/src/services/active-dirty-manager.service.ts
index 53331c0d33..a5c7aca0bd 100644
--- a/packages/engine-formula/src/services/active-dirty-manager.service.ts
+++ b/packages/engine-formula/src/services/active-dirty-manager.service.ts
@@ -16,14 +16,15 @@
import type { ICommandInfo, IUnitRange, Nullable } from '@univerjs/core';
import { Disposable } from '@univerjs/core';
-import type { IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetNameMap } from '@univerjs/engine-formula';
import { createIdentifier } from '@wendellhu/redi';
+import type { IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetDefinedNameMap, IDirtyUnitSheetNameMap } from '../basics/common';
export interface IDirtyConversionManagerParams {
commandId: string;
getDirtyData: (command: ICommandInfo) => {
dirtyRanges?: IUnitRange[];
dirtyNameMap?: IDirtyUnitSheetNameMap;
+ dirtyDefinedNameMap?: IDirtyUnitSheetDefinedNameMap;
dirtyUnitFeatureMap?: IDirtyUnitFeatureMap;
dirtyUnitOtherFormulaMap?: IDirtyUnitOtherFormulaMap;
};
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index 71a0fa80f0..bd0cde3da7 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -21,6 +21,7 @@ import { createIdentifier } from '@wendellhu/redi';
import type {
IDirtyUnitFeatureMap,
IDirtyUnitOtherFormulaMap,
+ IDirtyUnitSheetDefinedNameMap,
IDirtyUnitSheetNameMap,
IFormulaData,
IFormulaDatasetConfig,
@@ -51,6 +52,8 @@ export interface IFormulaCurrentConfigService {
getDirtyNameMap(): IDirtyUnitSheetNameMap;
+ getDirtyDefinedNameMap(): IDirtyUnitSheetDefinedNameMap;
+
getDirtyUnitFeatureMap(): IDirtyUnitFeatureMap;
registerUnitData(unitData: IUnitData): void;
@@ -68,6 +71,13 @@ export interface IFormulaCurrentConfigService {
getSheetName(unitId: string, sheetId: string): string;
getDirtyUnitOtherFormulaMap(): IDirtyUnitOtherFormulaMap;
+
+ getExecuteUnitId(): Nullable<string>;
+ getExecuteSubUnitId(): Nullable<string>;
+
+ setExecuteUnitId(unitId: string): void;
+ setExecuteSubUnitId(subUnitId: string): void;
+
}
export class FormulaCurrentConfigService extends Disposable implements IFormulaCurrentConfigService {
@@ -85,6 +95,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
private _dirtyNameMap: IDirtyUnitSheetNameMap = {};
+ private _dirtyDefinedNameMap: IDirtyUnitSheetDefinedNameMap = {};
+
private _numfmtItemMap: INumfmtItemMap = {};
private _dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
@@ -95,6 +107,9 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
private _sheetIdToNameMap: IUnitSheetIdToNameMap = {};
+ private _executeUnitId: Nullable<string> = '';
+ private _executeSubUnitId: Nullable<string> = '';
+
constructor(@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService) {
super();
}
@@ -106,6 +121,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._sheetNameMap = {};
this._dirtyRanges = [];
this._dirtyNameMap = {};
+ this._dirtyDefinedNameMap = {};
this._numfmtItemMap = {};
this._dirtyUnitFeatureMap = {};
this._excludedCell = {};
@@ -113,6 +129,22 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._dirtyUnitOtherFormulaMap = {};
}
+ getExecuteUnitId() {
+ return this._executeUnitId;
+ }
+
+ getExecuteSubUnitId() {
+ return this._executeSubUnitId;
+ }
+
+ setExecuteUnitId(unitId: string) {
+ this._executeUnitId = unitId;
+ }
+
+ setExecuteSubUnitId(subUnitId: string) {
+ this._executeSubUnitId = subUnitId;
+ }
+
getExcludedRange() {
return this._excludedCell;
}
@@ -145,6 +177,10 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
return this._dirtyNameMap;
}
+ getDirtyDefinedNameMap() {
+ return this._dirtyDefinedNameMap;
+ }
+
getNumfmtItemMap() {
return this._numfmtItemMap;
}
@@ -187,6 +223,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._dirtyNameMap = config.dirtyNameMap;
+ this._dirtyDefinedNameMap = config.dirtyDefinedNameMap;
+
this._numfmtItemMap = config.numfmtItemMap;
this._dirtyUnitFeatureMap = config.dirtyUnitFeatureMap;
@@ -325,6 +363,12 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
private _loadSheetData() {
const unitAllSheet = this._currentUniverService.getAllUniverSheetsInstance();
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const worksheet = workbook.getActiveSheet();
+
+ this._executeUnitId = workbook?.getUnitId();
+ this._executeSubUnitId = worksheet?.getSheetId();
+
const allUnitData: IUnitData = {};
const unitSheetNameMap: IUnitSheetNameMap = {};
diff --git a/packages/engine-formula/src/services/defined-names.service.ts b/packages/engine-formula/src/services/defined-names.service.ts
index 33cfe6cfc4..b629e75345 100644
--- a/packages/engine-formula/src/services/defined-names.service.ts
+++ b/packages/engine-formula/src/services/defined-names.service.ts
@@ -14,56 +14,165 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
+import type { IUnitRange, Nullable } from '@univerjs/core';
import { Disposable } from '@univerjs/core';
import { createIdentifier } from '@wendellhu/redi';
+import type { Observable } from 'rxjs';
+import { Subject } from 'rxjs';
+import { serializeRange } from '../engine/utils/reference';
+
+export interface IDefinedNamesServiceParam {
+ id: string;
+ name: string;
+ formulaOrRefString: string;
+ comment?: string;
+ localSheetId?: string;
+ hidden?: boolean;
+
+}
+
+export interface IDefinedNamesServiceFocusParam extends IDefinedNamesServiceParam {
+ unitId: string;
+}
+
+export interface IDefinedNameMap {
+ [unitId: string]: IDefinedNameMapItem;
+}
+
+export interface IDefinedNameMapItem {
+ [id: string]: IDefinedNamesServiceParam;
+}
export interface IDefinedNamesService {
- registerDefinedName(unitId: string, name: string, formulaOrRefString: string): void;
+ registerDefinedName(unitId: string, param: IDefinedNamesServiceParam): void;
+
+ registerDefinedNames(unitId: string, params: IDefinedNameMapItem): void;
+
+ getDefinedNameMap(unitId: string): Nullable<IDefinedNameMapItem>;
- getDefinedNameMap(unitId: string): Nullable<Map<string, string>>;
+ getValueByName(unitId: string, name: string): Nullable<IDefinedNamesServiceParam>;
- getValue(unitId: string, name: string): Nullable<string>;
+ getValueById(unitId: string, id: string): Nullable<IDefinedNamesServiceParam>;
removeDefinedName(unitId: string, name: string): void;
hasDefinedName(unitId: string): boolean;
+
+ setCurrentRange(range: IUnitRange): void;
+
+ getCurrentRange(): IUnitRange;
+
+ getCurrentRangeForString(): string;
+
+ currentRange$: Observable<IUnitRange>;
+
+ update$: Observable<unknown>;
+
+ focusRange$: Observable<IDefinedNamesServiceFocusParam>;
+
+ focusRange(unitId: string, id: string): void;
}
export class DefinedNamesService extends Disposable implements IDefinedNamesService {
// 18.2.6 definedNames (Defined Names)
- private _definedNameMap: Map<string, Map<string, string>> = new Map();
+ private _definedNameMap: IDefinedNameMap = {};
+
+ private readonly _update$ = new Subject();
+ readonly update$ = this._update$.asObservable();
+
+ private _currentRange: IUnitRange = { unitId: '', sheetId: '', range: {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ } };
+
+ private readonly _currentRange$ = new Subject<IUnitRange>();
+ readonly currentRange$ = this._currentRange$.asObservable();
+
+ private readonly _focusRange$ = new Subject<IDefinedNamesServiceFocusParam>();
+ readonly focusRange$ = this._focusRange$.asObservable();
+
+ constructor() {
+ super();
+ // this.registerDefinedName('workbook-01', { id: 'test1', name: 'name-01', formulaOrRefString: '=sum(A1:B10)', comment: 'this is comment', localSheetId: 'sheet-0011', hidden: false });
+ }
override dispose(): void {
- this._definedNameMap.clear();
+ this._definedNameMap = {};
+ }
+
+ focusRange(unitId: string, id: string) {
+ const item = this.getValueById(unitId, id);
+ if (item == null) {
+ return;
+ }
+ this._focusRange$.next({ ...item, unitId });
+ }
+
+ setCurrentRange(range: IUnitRange) {
+ this._currentRange = range;
+ this._currentRange$.next(range);
+ }
+
+ getCurrentRange() {
+ return this._currentRange;
}
- registerDefinedName(unitId: string, name: string, formulaOrRefString: string) {
- const unitMap = this._definedNameMap.get(unitId);
+ getCurrentRangeForString() {
+ return serializeRange(this._currentRange.range);
+ }
+
+ registerDefinedNames(unitId: string, params: IDefinedNameMapItem) {
+ this._definedNameMap[unitId] = params;
+ this._update();
+ }
+
+ registerDefinedName(unitId: string, param: IDefinedNamesServiceParam) {
+ const unitMap = this._definedNameMap[unitId];
if (unitMap == null) {
- this._definedNameMap.set(unitId, new Map());
+ this._definedNameMap[unitId] = {};
}
+ this._definedNameMap[unitId][param.id] = param;
- this._definedNameMap.get(unitId)?.set(name, formulaOrRefString);
+ this._update();
}
- removeDefinedName(unitId: string, name: string) {
- this._definedNameMap.get(unitId)?.delete(name);
+ removeDefinedName(unitId: string, id: string) {
+ delete this._definedNameMap[unitId]?.[id];
+ this._update();
}
getDefinedNameMap(unitId: string) {
- return this._definedNameMap.get(unitId);
+ return this._definedNameMap[unitId];
+ }
+
+ getValueByName(unitId: string, name: string) {
+ const nameMap = this._definedNameMap[unitId];
+ if (nameMap == null) {
+ return null;
+ }
+ return Array.from(Object.values(nameMap)).filter((value) => {
+ return value.name === name;
+ })?.[0];
}
- getValue(unitId: string, name: string) {
- return this._definedNameMap.get(unitId)?.get(name);
+ getValueById(unitId: string, id: string) {
+ return this._definedNameMap[unitId]?.[id];
}
hasDefinedName(unitId: string) {
- const size = this._definedNameMap.get(unitId)?.size || 0;
+ if (this._definedNameMap[unitId] == null) {
+ return false;
+ }
+ const size = Array.from(Object.values(this._definedNameMap[unitId])).length || 0;
return size !== 0;
}
+
+ private _update() {
+ this._update$.next(null);
+ }
}
export const IDefinedNamesService = createIdentifier<DefinedNamesService>('univer.formula.defined-names.service');
diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
index 842dd4fae3..67e1409971 100644
--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts
+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
@@ -23,8 +23,8 @@ import {
ObjectMatrix,
OnLifecycle,
} from '@univerjs/core';
-import type { IDirtyUnitSheetNameMap } from '@univerjs/engine-formula';
-import { FormulaDataModel, IActiveDirtyManagerService } from '@univerjs/engine-formula';
+import type { IDirtyUnitSheetDefinedNameMap, IDirtyUnitSheetNameMap, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
+import { FormulaDataModel, IActiveDirtyManagerService, IDefinedNamesService, RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';
import type {
IDeleteRangeMutationParams,
IInsertSheetMutationParams,
@@ -54,7 +54,9 @@ export class ActiveDirtyController extends Disposable {
constructor(
@IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService
+
) {
super();
@@ -164,6 +166,22 @@ export class ActiveDirtyController extends Disposable {
},
});
+ this._activeDirtyManagerService.register(SetDefinedNameMutation.id, {
+ commandId: SetDefinedNameMutation.id,
+ getDirtyData: (command: ICommandInfo) => {
+ const params = command.params as ISetDefinedNameMutationParam;
+ return { dirtyDefinedNameMap: this._getDefinedNameMutation(params) };
+ },
+ });
+
+ this._activeDirtyManagerService.register(RemoveDefinedNameMutation.id, {
+ commandId: RemoveDefinedNameMutation.id,
+ getDirtyData: (command: ICommandInfo) => {
+ const params = command.params as ISetDefinedNameMutationParam;
+ return { dirtyDefinedNameMap: this._getDefinedNameMutation(params) };
+ },
+ });
+
/**
* Changing the name of a sheet triggers an adjustment of the formula references, but does not trigger formula calculation; therefore, this logic has been removed.
*/
@@ -176,6 +194,20 @@ export class ActiveDirtyController extends Disposable {
// });
}
+ private _getDefinedNameMutation(definedName: ISetDefinedNameMutationParam) {
+ const { unitId, name, formulaOrRefString } = definedName;
+ const result: IDirtyUnitSheetDefinedNameMap = {};
+ if (definedName == null) {
+ return {};
+ }
+
+ result[unitId] = {};
+
+ result[unitId]![name] = formulaOrRefString;
+
+ return result;
+ }
+
private _getSetRangeValuesMutationDirtyRange(params: ISetRangeValuesMutationParams) {
const { subUnitId: sheetId, unitId, cellValue } = params;
diff --git a/packages/sheets-formula/src/controllers/defined-name.controller.ts b/packages/sheets-formula/src/controllers/defined-name.controller.ts
new file mode 100644
index 0000000000..8d773e48db
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/defined-name.controller.ts
@@ -0,0 +1,220 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo, IExecutionOptions, Nullable } from '@univerjs/core';
+import {
+ Disposable,
+ ICommandService,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+ toDisposable,
+} from '@univerjs/core';
+import type { IFunctionInfo, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
+import { FunctionType, IDefinedNamesService } from '@univerjs/engine-formula';
+import type { ISetDefinedNameCommandParams } from '@univerjs/sheets';
+import { InsertDefinedNameCommand, RemoveDefinedNameCommand, SetDefinedNameCommand, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { IDescriptionService } from '../services/description.service';
+
+export const SCOPE_WORKBOOK_VALUE = 'AllDefaultWorkbook';
+/**
+ * header highlight
+ * column menu: show, hover and mousedown event
+ */
+@OnLifecycle(LifecycleStages.Rendered, DefinedNameController)
+export class DefinedNameController extends Disposable {
+ private _preUnitId: Nullable<string> = null;
+
+ constructor(
+ @IDescriptionService private readonly _descriptionService: IDescriptionService,
+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @ICommandService private readonly _commandService: ICommandService
+
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize() {
+ this._descriptionListener();
+
+ this._changeUnitListener();
+
+ this._changeSheetListener();
+ }
+
+ private _descriptionListener() {
+ toDisposable(
+ this._definedNamesService.update$.subscribe(() => {
+ this._registerDescriptions();
+ })
+ );
+ }
+
+ private _changeUnitListener() {
+ toDisposable(
+ this._univerInstanceService.currentSheet$.subscribe(() => {
+ this._unRegisterDescriptions();
+ this._registerDescriptions();
+ })
+ );
+ }
+
+ private _changeSheetListener() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {
+ if (options?.fromCollab) {
+ return;
+ }
+
+ if (command.id === SetWorksheetActiveOperation.id) {
+ this._unregisterDescriptionsForNotInSheetId();
+ this._registerDescriptions();
+ } else if (command.id === InsertDefinedNameCommand.id) {
+ const param = command.params as ISetDefinedNameMutationParam;
+ this._registerDescription(param);
+ } else if (command.id === RemoveDefinedNameCommand.id) {
+ const param = command.params as ISetDefinedNameMutationParam;
+ this._unregisterDescription(param);
+ } else if (command.id === SetDefinedNameCommand.id) {
+ const param = command.params as ISetDefinedNameCommandParams;
+ this._unregisterDescription(param.oldDefinedName);
+ this._registerDescription(param.newDefinedName);
+ }
+ })
+ );
+ }
+
+ private _registerDescription(param: ISetDefinedNameMutationParam) {
+ const { unitId, sheetId } = this._getUnitIdAndSheetId();
+
+ if (unitId == null || sheetId == null) {
+ return;
+ }
+
+ const { name, comment, formulaOrRefString, localSheetId } = param;
+ if (!this._descriptionService.hasDescription(name) && (localSheetId == null || localSheetId === SCOPE_WORKBOOK_VALUE || localSheetId === sheetId)) {
+ this._descriptionService.registerDescriptions([{
+ functionName: name,
+ description: formulaOrRefString + (comment || ''),
+ abstract: formulaOrRefString,
+ functionType: FunctionType.DefinedName,
+ functionParameter: [],
+ }]);
+ }
+ }
+
+ private _unregisterDescription(param: ISetDefinedNameMutationParam) {
+ const { name } = param;
+ this._descriptionService.unregisterDescriptions([name]);
+ }
+
+ private _unRegisterDescriptions() {
+ if (this._preUnitId == null) {
+ return;
+ }
+ const definedNames = this._definedNamesService.getDefinedNameMap(this._preUnitId);
+
+ if (definedNames == null) {
+ return;
+ }
+
+ const functionList: string[] = [];
+ Array.from(Object.values(definedNames)).forEach((value) => {
+ const { name } = value;
+ functionList.push(name);
+ });
+
+ this._descriptionService.unregisterDescriptions(functionList);
+
+ this._preUnitId = null;
+ }
+
+ private _getUnitIdAndSheetId() {
+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();
+ if (workbook == null) {
+ return {};
+ }
+ const worksheet = workbook.getActiveSheet();
+
+ if (worksheet == null) {
+ return {};
+ }
+
+ return {
+ unitId: workbook.getUnitId(),
+ sheetId: worksheet.getSheetId(),
+ };
+ }
+
+ private _registerDescriptions() {
+ const { unitId, sheetId } = this._getUnitIdAndSheetId();
+
+ if (unitId == null || sheetId == null) {
+ return;
+ }
+
+ const definedNames = this._definedNamesService.getDefinedNameMap(unitId);
+ if (!definedNames) {
+ return;
+ }
+
+ const functionList: IFunctionInfo[] = [];
+
+ this._preUnitId = unitId;
+
+ Array.from(Object.values(definedNames)).forEach((value) => {
+ const { name, comment, formulaOrRefString, localSheetId } = value;
+ if (!this._descriptionService.hasDescription(name) && (localSheetId == null || localSheetId === SCOPE_WORKBOOK_VALUE || localSheetId === sheetId)) {
+ functionList.push({
+ functionName: name,
+ description: formulaOrRefString + (comment || ''),
+ abstract: formulaOrRefString,
+ functionType: FunctionType.DefinedName,
+ functionParameter: [],
+ });
+ }
+ });
+
+ this._descriptionService.registerDescriptions(functionList);
+ }
+
+ private _unregisterDescriptionsForNotInSheetId() {
+ const { unitId, sheetId } = this._getUnitIdAndSheetId();
+
+ if (unitId == null || sheetId == null) {
+ return;
+ }
+
+ const definedNames = this._definedNamesService.getDefinedNameMap(unitId);
+ if (!definedNames) {
+ return;
+ }
+
+ const functionList: string[] = [];
+
+ Array.from(Object.values(definedNames)).forEach((value) => {
+ const { name, localSheetId } = value;
+ if (localSheetId !== SCOPE_WORKBOOK_VALUE && localSheetId !== sheetId) {
+ functionList.push(name);
+ }
+ });
+
+ this._descriptionService.unregisterDescriptions(functionList);
+ }
+}
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index df448fcb59..89b279befc 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -552,10 +552,18 @@ export class PromptController extends Disposable {
lastSequenceNodes[nodeIndex] = newNode;
- lastSequenceNodes.splice(nodeIndex + 1, 0, matchToken.OPEN_BRACKET);
+ const isDefinedName = this._descriptionService.hasDefinedNameDescription(formulaString);
+
+ const isFormulaDefinedName = this._descriptionService.isFormulaDefinedName(formulaString);
const formulaStringCount = formulaString.length + 1;
+ const mustAddBracket = !isDefinedName || isFormulaDefinedName;
+
+ if (mustAddBracket) {
+ lastSequenceNodes.splice(nodeIndex + 1, 0, matchToken.OPEN_BRACKET);
+ }
+
for (let i = nodeIndex + 2, len = lastSequenceNodes.length; i < len; i++) {
const node = lastSequenceNodes[i];
if (typeof node === 'string') {
@@ -573,7 +581,12 @@ export class PromptController extends Disposable {
lastSequenceNodes[i] = newNode;
}
- this._syncToEditor(lastSequenceNodes, newNode.endIndex + 2);
+ let selectionIndex = newNode.endIndex + 1;
+ if (mustAddBracket) {
+ selectionIndex += 1;
+ }
+
+ this._syncToEditor(lastSequenceNodes, selectionIndex);
})
)
);
@@ -596,7 +609,7 @@ export class PromptController extends Disposable {
return;
}
- if (typeof currentSequenceNode !== 'string' && currentSequenceNode.nodeType === sequenceNodeType.FUNCTION) {
+ if (typeof currentSequenceNode !== 'string' && currentSequenceNode.nodeType === sequenceNodeType.FUNCTION && !this._descriptionService.hasDefinedNameDescription(currentSequenceNode.token.trim())) {
const token = currentSequenceNode.token.toUpperCase();
if (this._inputPanelState === InputPanelState.keyNormal) {
@@ -611,7 +624,7 @@ export class PromptController extends Disposable {
searchText: token,
searchList,
});
- } else if (this._descriptionService.hasFunction(token)) {
+ } else {
// show help function panel
this._changeHelpFunctionPanelState(token, -1);
}
@@ -911,7 +924,7 @@ export class PromptController extends Disposable {
for (let i = 0, len = sequenceNodes.length; i < len; i++) {
const node = sequenceNodes[i];
- if (typeof node === 'string') {
+ if (typeof node === 'string' || this._descriptionService.hasDefinedNameDescription(node.token.trim())) {
continue;
}
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index 24526ac272..68719534dd 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -130,6 +130,7 @@ export class TriggerCalculationController extends Disposable {
private _generateDirty(commands: ICommandInfo[]) {
const allDirtyRanges: IUnitRange[] = [];
const allDirtyNameMap: IDirtyUnitSheetNameMap = {};
+ const allDirtyDefinedNameMap: IDirtyUnitSheetNameMap = {};
const allDirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
const allDirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {};
@@ -144,7 +145,7 @@ export class TriggerCalculationController extends Disposable {
const params = conversion.getDirtyData(command);
- const { dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap } = params;
+ const { dirtyRanges, dirtyNameMap, dirtyDefinedNameMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap } = params;
if (dirtyRanges != null) {
allDirtyRanges.push(...dirtyRanges);
@@ -154,6 +155,10 @@ export class TriggerCalculationController extends Disposable {
this._mergeDirtyNameMap(allDirtyNameMap, dirtyNameMap);
}
+ if (dirtyDefinedNameMap != null) {
+ this._mergeDirtyNameMap(allDirtyDefinedNameMap, dirtyDefinedNameMap);
+ }
+
if (dirtyUnitFeatureMap != null) {
this._mergeDirtyUnitFeatureOrOtherFormulaMap(allDirtyUnitFeatureMap, dirtyUnitFeatureMap);
}
@@ -199,6 +204,7 @@ export class TriggerCalculationController extends Disposable {
return {
dirtyRanges: allDirtyRanges,
dirtyNameMap: allDirtyNameMap,
+ dirtyDefinedNameMap: allDirtyDefinedNameMap,
dirtyUnitFeatureMap: allDirtyUnitFeatureMap,
dirtyUnitOtherFormulaMap: allDirtyUnitOtherFormulaMap,
numfmtItemMap,
diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.ts
index 475dbd2f84..b6a653b947 100644
--- a/packages/sheets-formula/src/formula-ui-plugin.ts
+++ b/packages/sheets-formula/src/formula-ui-plugin.ts
@@ -39,6 +39,7 @@ import {
import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';
import { IRegisterFunctionService, RegisterFunctionService } from './services/register-function.service';
import { NumfmtFormulaDisplayController } from './controllers/numfmt-formula-display.controller';
+import { DefinedNameController } from './controllers/defined-name.controller';
import { FormulaRefRangeService } from './services/formula-ref-range.service';
/**
@@ -90,6 +91,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {
[UpdateFormulaController],
[FormulaEditorShowController],
[ActiveDirtyController],
+ [DefinedNameController],
];
dependencies.forEach((dependency) => this._injector.add(dependency));
diff --git a/packages/sheets-formula/src/services/description.service.ts b/packages/sheets-formula/src/services/description.service.ts
index 204afb670d..c7357bc2bc 100644
--- a/packages/sheets-formula/src/services/description.service.ts
+++ b/packages/sheets-formula/src/services/description.service.ts
@@ -31,9 +31,11 @@ import {
functionMeta,
functionStatistical,
functionText,
+ FunctionType,
functionUniver,
functionWeb,
IFunctionService,
+ isReferenceString,
} from '@univerjs/engine-formula';
import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier, Inject } from '@wendellhu/redi';
@@ -92,6 +94,24 @@ export interface IDescriptionService {
* @param functionList
*/
unregisterDescriptions(functionNames: string[]): void;
+
+ /**
+ * check if has description
+ * @param name
+ */
+ hasDescription(name: string): boolean;
+
+ /**
+ * check if has defined name description
+ * @param name
+ */
+ hasDefinedNameDescription(name: string): boolean;
+
+ /**
+ * check if is formula defined name
+ * @param name
+ */
+ isFormulaDefinedName(name: string): boolean;
}
export const IDescriptionService = createIdentifier<IDescriptionService>('formula-ui.description-service');
@@ -131,7 +151,7 @@ export class DescriptionService implements IDescriptionService, IDisposable {
searchText = searchText.toLocaleUpperCase();
functionList.forEach((item) => {
const { functionName, abstract } = item;
- if (functionName.indexOf(searchText) > -1) {
+ if (functionName.toLocaleUpperCase().indexOf(searchText) > -1) {
searchList.push({ name: functionName, desc: abstract });
}
});
@@ -145,7 +165,7 @@ export class DescriptionService implements IDescriptionService, IDisposable {
searchText = searchText.toLocaleUpperCase();
functionList.forEach((item) => {
const { functionName, abstract } = item;
- if (functionName.indexOf(searchText) === 0) {
+ if (functionName.toLocaleUpperCase().indexOf(searchText) === 0) {
searchList.push({ name: functionName, desc: abstract });
}
});
@@ -177,6 +197,26 @@ export class DescriptionService implements IDescriptionService, IDisposable {
this._functionService.unregisterDescriptions(...functionNames);
}
+ hasDescription(name: string) {
+ return this._descriptions.some((item) => item.functionName === name);
+ }
+
+ hasDefinedNameDescription(name: string) {
+ return this._descriptions.some((item) => item.functionName === name && item.functionType === FunctionType.DefinedName);
+ }
+
+ isFormulaDefinedName(name: string) {
+ const items = this._descriptions.filter((item) => item.functionName === name && item.functionType === FunctionType.DefinedName);
+ if (items.length === 0) {
+ return false;
+ }
+
+ const token = items[0].description;
+ return !token.split(',').every((refString) => {
+ return isReferenceString(refString.trim());
+ });
+ }
+
private _initialize() {
this._localeService.localeChanged$.subscribe(() => {
this._registerDescriptions();
diff --git a/packages/sheets-formula/src/views/prompt/search-function/SearchFunction.tsx b/packages/sheets-formula/src/views/prompt/search-function/SearchFunction.tsx
index 0ddef25b4f..bd53f0a7bd 100644
--- a/packages/sheets-formula/src/views/prompt/search-function/SearchFunction.tsx
+++ b/packages/sheets-formula/src/views/prompt/search-function/SearchFunction.tsx
@@ -169,7 +169,7 @@ export function SearchFunction() {
onClick={() => promptService.acceptFormulaName(item.name)}
>
<span className={styles.formulaSearchFunctionItemName}>
- <span className={styles.formulaSearchFunctionItemNameLight}>{searchText}</span>
+ <span className={styles.formulaSearchFunctionItemNameLight}>{item.name.substring(0, searchText.length)}</span>
<span>{item.name.slice(searchText.length)}</span>
</span>
<span className={styles.formulaSearchFunctionItemDesc}>{item.desc}</span>
diff --git a/packages/sheets-formula/src/views/prompt/search-function/index.module.less b/packages/sheets-formula/src/views/prompt/search-function/index.module.less
index 5ad7899b7e..26b7116c17 100644
--- a/packages/sheets-formula/src/views/prompt/search-function/index.module.less
+++ b/packages/sheets-formula/src/views/prompt/search-function/index.module.less
@@ -19,6 +19,9 @@
outline: none;
box-shadow: var(--box-shadow-base);
+ overflow: hidden;
+ overflow-y: auto;
+
&-item {
cursor: pointer;
diff --git a/packages/sheets-ui/src/commands/operations/sidebar-defined-name.operation.ts b/packages/sheets-ui/src/commands/operations/sidebar-defined-name.operation.ts
new file mode 100644
index 0000000000..9d656aa9ad
--- /dev/null
+++ b/packages/sheets-ui/src/commands/operations/sidebar-defined-name.operation.ts
@@ -0,0 +1,56 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import { CommandType, IUniverInstanceService, LocaleService } from '@univerjs/core';
+import { IEditorService, ISidebarService } from '@univerjs/ui';
+import type { IAccessor } from '@wendellhu/redi';
+import { DEFINED_NAME_CONTAINER } from '../../views/defined-name/component-name';
+
+export interface IUIComponentCommandParams {
+ value: string;
+}
+
+export const SidebarDefinedNameOperation: ICommand = {
+ id: 'sidebar.operation.defined-name',
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor, params: IUIComponentCommandParams) => {
+ const sidebarService = accessor.get(ISidebarService);
+ const editorService = accessor.get(IEditorService);
+ const localeService = accessor.get(LocaleService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const unit = univerInstanceService.getCurrentUniverSheetInstance();
+ switch (params.value) {
+ case 'open':
+ editorService.setOperationSheetUnitId(unit.getUnitId());
+ sidebarService.open({
+ header: { title: localeService.t('definedName.featureTitle') },
+ children: { label: DEFINED_NAME_CONTAINER },
+ onClose: () => {
+ editorService.closeRangePrompt();
+ },
+ width: 333,
+ });
+ break;
+
+ case 'close':
+ default:
+ sidebarService.close();
+ break;
+ }
+ return true;
+ },
+};
diff --git a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
index db635ed7d5..f15c378cfb 100644
--- a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
@@ -154,12 +154,14 @@ export class EndEditController extends Disposable {
if (keycode === KeyCode.ESC) {
// Reselect the current selections, when exist cell editor by press ESC.
- this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
- unitId: workbookId,
- subUnitId: worksheetId,
- pluginName,
- selections,
- });
+ if (selections) {
+ this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId: workbookId,
+ subUnitId: worksheetId,
+ pluginName,
+ selections,
+ });
+ }
return;
}
diff --git a/packages/sheets-ui/src/controllers/scroll.controller.ts b/packages/sheets-ui/src/controllers/scroll.controller.ts
index 5342af2767..8daae2249e 100644
--- a/packages/sheets-ui/src/controllers/scroll.controller.ts
+++ b/packages/sheets-ui/src/controllers/scroll.controller.ts
@@ -16,6 +16,7 @@
import type { IFreeze, IRange, IWorksheetData, Nullable } from '@univerjs/core';
import {
+ Direction,
Disposable,
ICommandService,
IUniverInstanceService,
@@ -24,7 +25,7 @@ import {
toDisposable,
} from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { ScrollToCellOperation, SelectionManagerService } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import { ScrollCommand } from '../commands/commands/set-scroll.command';
@@ -32,7 +33,8 @@ import { VIEWPORT_KEY } from '../common/keys';
import { ScrollManagerService } from '../services/scroll-manager.service';
import type { ISheetSkeletonManagerParam } from '../services/sheet-skeleton-manager.service';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
-import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../commands/commands/set-selection.command';
+import type { IExpandSelectionCommandParams } from '../commands/commands/set-selection.command';
+import { ExpandSelectionCommand, MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../commands/commands/set-selection.command';
import { getSheetObject } from './utils/component-tools';
const SHEET_NAVIGATION_COMMANDS = [MoveSelectionCommand.id, MoveSelectionEnterAndTabCommand.id];
@@ -72,11 +74,66 @@ export class ScrollController extends Disposable {
this._commandService.onCommandExecuted((command) => {
if (SHEET_NAVIGATION_COMMANDS.includes(command.id)) {
this._scrollToSelection();
+ } else if (command.id === ScrollToCellOperation.id) {
+ const param = command.params as IRange;
+ this._scrollToSelectionByDirection(param);
+ } else if (command.id === ExpandSelectionCommand.id) {
+ const param = command.params as IExpandSelectionCommandParams;
+ this._scrollToSelectionForExpand(param);
}
})
);
}
+ private _scrollToSelectionForExpand(param: IExpandSelectionCommandParams) {
+ setTimeout(() => {
+ const selection = this._selectionManagerService.getLast();
+ if (selection == null) {
+ return;
+ }
+
+ const { startRow, startColumn, endRow, endColumn } = selection.range;
+
+ const bounds = this._getViewportBounding();
+ if (bounds == null) {
+ return;
+ }
+
+ const { startRow: viewportStartRow, startColumn: viewportStartColumn, endRow: viewportEndRow, endColumn: viewportEndColumn } = bounds;
+
+ let row = 0;
+ let column = 0;
+
+ if (startRow > viewportStartRow) {
+ row = endRow;
+ } else if (endRow < viewportEndRow) {
+ row = startRow;
+ } else {
+ row = viewportStartRow;
+ }
+
+ if (startColumn > viewportStartColumn) {
+ column = endColumn;
+ } else if (endColumn < viewportEndColumn) {
+ column = startColumn;
+ } else {
+ column = viewportStartColumn;
+ }
+
+ if (param.direction === Direction.DOWN) {
+ row = endRow;
+ } else if (param.direction === Direction.UP) {
+ row = startRow;
+ } else if (param.direction === Direction.RIGHT) {
+ column = endColumn;
+ } else if (param.direction === Direction.LEFT) {
+ column = startColumn;
+ }
+
+ this._scrollToCell(row, column);
+ }, 0);
+ }
+
private _getFreeze(): Nullable<IFreeze> {
const snapshot: IWorksheetData | undefined = this._sheetSkeletonManagerService.getCurrent()?.skeleton.getWorksheetConfig();
if (snapshot == null) {
@@ -251,6 +308,42 @@ export class ScrollController extends Disposable {
return getSheetObject(this._currentUniverService, this._renderManagerService);
}
+ private _scrollToSelectionByDirection(range: IRange) {
+ const bounds = this._getViewportBounding();
+ if (bounds == null) {
+ return false;
+ }
+ const {
+ startRow: viewportStartRow,
+ startColumn: viewportStartColumn,
+ endRow: viewportEndRow,
+ endColumn: viewportEndColumn,
+ } = bounds;
+
+ let row = 0;
+ let column = 0;
+
+ const { startRow, startColumn, endRow, endColumn } = range;
+
+ if (startRow >= viewportStartRow) {
+ row = endRow;
+ }
+
+ if (endRow <= viewportEndRow) {
+ row = startRow;
+ }
+
+ if (startColumn >= viewportStartColumn) {
+ column = endColumn;
+ }
+
+ if (endColumn <= viewportEndColumn) {
+ column = startColumn;
+ }
+
+ this._scrollToCell(row, column);
+ }
+
private _scrollToSelection(targetIsActualRowAndColumn = true) {
const selection = this._selectionManagerService.getLast();
if (selection == null) {
@@ -264,6 +357,26 @@ export class ScrollController extends Disposable {
this._scrollToCell(selectionStartRow, selectionStartColumn);
}
+ private _getViewportBounding() {
+ const scene = this._getSheetObject()?.scene;
+ if (scene == null) {
+ return;
+ }
+
+ const viewport = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ if (viewport == null) {
+ return;
+ }
+
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
+ if (skeleton == null) {
+ return;
+ }
+
+ const bounds = viewport.getBounding();
+ return skeleton.getRowColumnSegment(bounds);
+ }
+
private _scrollToCell(row: number, column: number): boolean {
const { rowHeightAccumulation, columnWidthAccumulation } = this._sheetSkeletonManagerService.getCurrent()?.skeleton ?? {};
@@ -299,13 +412,16 @@ export class ScrollController extends Disposable {
xSplit: freezeXSplit,
} = worksheet.getFreeze();
- const bounds = viewport.getBounding();
+ const bounds = this._getViewportBounding();
+ if (bounds == null) {
+ return false;
+ }
const {
startRow: viewportStartRow,
startColumn: viewportStartColumn,
endRow: viewportEndRow,
endColumn: viewportEndColumn,
- } = skeleton.getRowColumnSegment(bounds);
+ } = bounds;
let startSheetViewRow: number | undefined;
let startSheetViewColumn: number | undefined;
diff --git a/packages/sheets-ui/src/controllers/selection.controller.ts b/packages/sheets-ui/src/controllers/selection.controller.ts
index 2f8863e9f1..9567a620f3 100644
--- a/packages/sheets-ui/src/controllers/selection.controller.ts
+++ b/packages/sheets-ui/src/controllers/selection.controller.ts
@@ -31,20 +31,23 @@ import type { ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs
import {
convertSelectionDataToRange,
getNormalSelectionStyle,
+ getPrimaryForRange,
NORMAL_SELECTION_PLUGIN_NAME,
+ ScrollToCellOperation,
SelectionManagerService,
SelectionMoveType,
SetSelectionsOperation,
+ SetWorksheetActivateCommand,
transformCellDataToSelectionData,
} from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
+import { deserializeRangeWithSheet, IDefinedNamesService, isReferenceString, operatorToken, SetDefinedNameCurrentMutation } from '@univerjs/engine-formula';
import type { ISetZoomRatioOperationParams } from '../commands/operations/set-zoom-ratio.operation';
import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';
import { VIEWPORT_KEY } from '../common/keys';
import { ISelectionRenderService } from '../services/selection/selection-render.service';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
-import { ScrollController } from './scroll.controller';
import type { ISheetObjectParam } from './utils/component-tools';
import { getSheetObject } from './utils/component-tools';
@@ -59,7 +62,7 @@ export class SelectionController extends Disposable {
private readonly _selectionRenderService: ISelectionRenderService,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
@Inject(ThemeService) private readonly _themeService: ThemeService,
- @Inject(ScrollController) private readonly _scrollController: ScrollController
+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService
) {
super();
@@ -74,8 +77,6 @@ export class SelectionController extends Disposable {
return;
}
- // TODO@wzhudev: listen clicking event on the top-left corner to select all cells.
-
this._initViewMainListener(sheetObject);
this._initRowHeader(sheetObject);
this._initColumnHeader(sheetObject);
@@ -85,6 +86,7 @@ export class SelectionController extends Disposable {
this._initSkeletonChangeListener();
this._initCommandListener();
this._initUserActionSyncListener();
+ this._initDefinedNameListener();
const unitId = workbook.getUnitId();
const sheetId = worksheet.getSheetId();
@@ -95,6 +97,88 @@ export class SelectionController extends Disposable {
});
}
+ private _initDefinedNameListener() {
+ this.disposeWithMe(
+ toDisposable(
+ this._definedNamesService.focusRange$.subscribe(async (item) => {
+ if (item == null) {
+ return;
+ }
+
+ const { unitId } = item;
+ let { formulaOrRefString } = item;
+
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+
+ if (unitId !== workbook.getUnitId()) {
+ return;
+ }
+
+ if (formulaOrRefString.substring(0, 1) === operatorToken.EQUALS) {
+ formulaOrRefString = formulaOrRefString.substring(1);
+ }
+
+ const valueArray = formulaOrRefString.split(',');
+ const result = valueArray.every((refString) => {
+ return isReferenceString(refString.trim());
+ });
+
+ if (!result) {
+ return;
+ }
+
+ let worksheet = workbook.getActiveSheet();
+
+ const selections = [];
+
+ for (let i = 0; i < valueArray.length; i++) {
+ const refString = valueArray[i].trim();
+
+ const unitRange = deserializeRangeWithSheet(refString.trim());
+
+ if (i === 0) {
+ const worksheetCache = workbook.getSheetBySheetName(unitRange.sheetName);
+ if (worksheetCache && worksheet.getSheetId() !== worksheetCache.getSheetId()) {
+ worksheet = worksheetCache;
+ await this._commandService.executeCommand(SetWorksheetActivateCommand.id, {
+ subUnitId: worksheet.getSheetId(),
+ unitId,
+ });
+ }
+ }
+
+ if (worksheet.getName() !== unitRange.sheetName) {
+ continue;
+ }
+
+ let primary = null;
+ if (i === valueArray.length - 1) {
+ const range = unitRange.range;
+ const { startRow, startColumn, endRow, endColumn } = range;
+ primary = getPrimaryForRange({
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+
+ }, worksheet);
+ }
+
+ selections.push({
+ range: unitRange.range,
+ style: getNormalSelectionStyle(this._themeService),
+ primary,
+ });
+ }
+
+ this._selectionManagerService.replace(selections);
+
+ this._commandService.executeCommand(ScrollToCellOperation.id, selections[0].range);
+ })
+ )
+ );
+ }
+
private _getActiveViewport(evt: IPointerEvent | IMouseEvent) {
const sheetObject = this._getSheetObject();
@@ -233,13 +317,13 @@ export class SelectionController extends Disposable {
private _initSelectionChangeListener() {
this.disposeWithMe(
toDisposable(
- this._selectionManagerService.selectionMoveEnd$.subscribe((param) => {
+ this._selectionManagerService.selectionMoveEnd$.subscribe((params) => {
this._selectionRenderService.reset();
- if (param == null) {
+ if (params == null) {
return;
}
- for (const selectionWithStyle of param) {
+ for (const selectionWithStyle of params) {
if (selectionWithStyle == null) {
continue;
}
@@ -247,11 +331,53 @@ export class SelectionController extends Disposable {
this._selectionRenderService.convertSelectionRangeToData(selectionWithStyle);
this._selectionRenderService.addControlToCurrentByRangeData(selectionData);
}
+
+ this._syncDefinedNameRange(params);
+ })
+ )
+ );
+
+ this.disposeWithMe(
+ toDisposable(
+ this._selectionManagerService.selectionMoving$.subscribe((params) => {
+ if (params == null) {
+ return;
+ }
+
+ this._syncDefinedNameRange(params);
+ })
+ )
+ );
+
+ this.disposeWithMe(
+ toDisposable(
+ this._selectionManagerService.selectionMoveStart$.subscribe((params) => {
+ if (params == null) {
+ return;
+ }
+
+ this._syncDefinedNameRange(params);
})
)
);
}
+ private _syncDefinedNameRange(params: ISelectionWithStyle[]) {
+ if (params.length === 0) {
+ return;
+ }
+ const lastSelection = params[params.length - 1];
+
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const worksheet = workbook.getActiveSheet();
+
+ this._commandService.executeCommand(SetDefinedNameCurrentMutation.id, {
+ range: lastSelection.range,
+ unitId: workbook.getUnitId(),
+ sheetId: worksheet.getSheetId(),
+ });
+ }
+
private _initUserActionSyncListener() {
this._selectionRenderService.selectionMoveStart$.subscribe((params) => {
this._move(params, SelectionMoveType.MOVE_START);
diff --git a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
index a38cb6f989..d55ac51f4a 100644
--- a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
+++ b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
@@ -95,6 +95,9 @@ import {
import { FONT_SIZE_COMPONENT, FontSize } from '../components/font-size';
import { MENU_ITEM_INPUT_COMPONENT, MenuItemInput } from '../components/menu-item-input';
import { RenderSheetContent, RenderSheetFooter, RenderSheetHeader } from '../views/sheet-container/SheetContainer';
+import { DEFINED_NAME_CONTAINER } from '../views/defined-name/component-name';
+import { DefinedNameContainer } from '../views/defined-name/DefinedNameContainer';
+import { SidebarDefinedNameOperation } from '../commands/operations/sidebar-defined-name.operation';
import { CellBorderSelectorMenuItemFactory } from './menu/border.menu';
import {
ClearSelectionAllMenuItemFactory,
@@ -255,6 +258,7 @@ export class SheetUIController extends Disposable {
this.disposeWithMe(componentManager.register(FONT_FAMILY_COMPONENT, FontFamily));
this.disposeWithMe(componentManager.register(FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem));
this.disposeWithMe(componentManager.register(FONT_SIZE_COMPONENT, FontSize));
+ this.disposeWithMe(componentManager.register(DEFINED_NAME_CONTAINER, DefinedNameContainer));
}
private _initCommands(): void {
@@ -312,6 +316,7 @@ export class SheetUIController extends Disposable {
DeleteRangeMoveUpConfirmCommand,
InsertRangeMoveRightConfirmCommand,
DeleteRangeMoveLeftConfirmCommand,
+ SidebarDefinedNameOperation,
].forEach((c) => {
this.disposeWithMe(this._commandService.registerCommand(c));
});
diff --git a/packages/sheets-ui/src/locale/en-US.ts b/packages/sheets-ui/src/locale/en-US.ts
index f568666893..80a3a4d61b 100644
--- a/packages/sheets-ui/src/locale/en-US.ts
+++ b/packages/sheets-ui/src/locale/en-US.ts
@@ -490,9 +490,35 @@ const locale: typeof zhCN = {
'set-strike-through': 'Toggle strike through',
},
},
-
'sheet-view': 'Sheet View',
'sheet-edit': 'Sheet Edit',
+
+ definedName: {
+ managerTitle: 'Manager named',
+ managerDescription: 'Create a defined name by selecting cells or formulas, and entering the desired name into the text box.',
+ addButton: 'Add a defined name',
+ featureTitle: 'Defined names',
+ ratioRange: 'Range',
+ ratioFormula: 'Formula',
+ confirm: 'Confirm',
+ cancel: 'Cancel',
+ scopeWorkbook: 'Workbook',
+ inputNamePlaceholder: 'Please enter a name(No space allowed)',
+ inputCommentPlaceholder: 'Please enter a comment',
+ inputRangePlaceholder: 'Please input range(No space allowed)',
+ inputFormulaPlaceholder: 'Please input a formula(No space allowed)',
+ nameEmpty: 'Name cannot be empty',
+ nameDuplicate: 'Name already exists',
+ formulaOrRefStringEmpty: 'Formula or reference string cannot be empty',
+ formulaOrRefStringInvalid: 'Invalid formula or reference string',
+ defaultName: 'DefinedName',
+ updateButton: 'Update',
+ deleteButton: 'Delete',
+ deleteConfirmText: 'Are you sure you want to delete this defined name?',
+ nameConflict: 'The name conflicts with the function name',
+ nameInvalid: 'The name is invalid',
+ nameSheetConflict: 'The name conflicts with the sheet name',
+ },
};
export default locale;
diff --git a/packages/sheets-ui/src/locale/zh-CN.ts b/packages/sheets-ui/src/locale/zh-CN.ts
index 4a4d2976e8..23f6dc7326 100644
--- a/packages/sheets-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-ui/src/locale/zh-CN.ts
@@ -488,6 +488,32 @@ const locale = {
},
'sheet-view': '浏览表格',
'sheet-edit': '编辑表格',
+ definedName: {
+ managerTitle: '名称管理器',
+ managerDescription: '通过选择单元格或公式,并在文本框中输入您想要的名称来创建一个定义名称。',
+ addButton: '新建名称',
+ featureTitle: '定义名称',
+ ratioRange: '范围',
+ ratioFormula: '公式',
+ confirm: '确认',
+ cancel: '取消',
+ scopeWorkbook: '工作簿',
+ inputNamePlaceholder: '请输入名称(必填)',
+ inputCommentPlaceholder: '请输入备注',
+ inputRangePlaceholder: '请输入范围(必填)',
+ inputFormulaPlaceholder: '请输入公式(必填)',
+ nameEmpty: '名称不能为空',
+ nameDuplicate: '名称重复',
+ formulaOrRefStringEmpty: '公式或引用字符串不能为空',
+ formulaOrRefStringInvalid: '公式或引用字符串无效',
+ defaultName: 'DefinedName',
+ updateButton: '修改',
+ deleteButton: '删除',
+ deleteConfirmText: '确定删除定义名称?',
+ nameConflict: '与函数名称冲突',
+ nameInvalid: '名称不包含空格或不允许的字符',
+ nameSheetConflict: '名称与工作表名称冲突',
+ },
};
export default locale;
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedName.tsx b/packages/sheets-ui/src/views/defined-name/DefinedName.tsx
new file mode 100644
index 0000000000..dc006eecbb
--- /dev/null
+++ b/packages/sheets-ui/src/views/defined-name/DefinedName.tsx
@@ -0,0 +1,51 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import React, { useEffect } from 'react';
+
+import { Dropdown, Input } from '@univerjs/design';
+import { MoreDownSingle } from '@univerjs/icons';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import { IDefinedNamesService } from '@univerjs/engine-formula';
+import styles from './index.module.less';
+import { DefinedNameOverlay } from './DefinedNameOverlay';
+
+export function DefinedName() {
+ const [rangeString, setRangeString] = React.useState('');
+ const definedNamesService = useDependency(IDefinedNamesService);
+
+ useEffect(() => {
+ const subscription = definedNamesService.currentRange$.subscribe(() => {
+ setRangeString(definedNamesService.getCurrentRangeForString());
+ });
+
+ return () => {
+ subscription.unsubscribe();
+ };
+ }, []); // Empty dependency array means this effect runs once on mount and clean up on unmount
+
+ return (
+ <div className={styles.definedName}>
+ <Input value={rangeString} type="text" size="small" affixWrapperStyle={{ border: 'none', padding: '6px' }} />
+
+ <Dropdown overlay={<DefinedNameOverlay />}>
+ <div className={styles.definedNameDropDown}>
+ <MoreDownSingle />
+ </div>
+ </Dropdown>
+ </div>
+ );
+}
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
new file mode 100644
index 0000000000..d6a666a2ed
--- /dev/null
+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
@@ -0,0 +1,214 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import React, { useEffect, useState } from 'react';
+
+import type { Nullable } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, LocaleService, Tools } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import { CheckMarkSingle, DeleteSingle, IncreaseSingle } from '@univerjs/icons';
+import type { IDefinedNamesServiceParam } from '@univerjs/engine-formula';
+import { IDefinedNamesService, serializeRangeWithSheet } from '@univerjs/engine-formula';
+import clsx from 'clsx';
+import { InsertDefinedNameCommand, RemoveDefinedNameCommand, SelectionManagerService, SetDefinedNameCommand } from '@univerjs/sheets';
+import { Confirm, Tooltip } from '@univerjs/design';
+import styles from './index.module.less';
+import { DefinedNameInput } from './DefinedNameInput';
+import { SCOPE_WORKBOOK_VALUE } from './component-name';
+
+export const DefinedNameContainer = () => {
+ const commandService = useDependency(ICommandService);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ const localeService = useDependency(LocaleService);
+ const definedNamesService = useDependency(IDefinedNamesService);
+ const selectionManagerService = useDependency(SelectionManagerService);
+
+ if (workbook == null) {
+ return;
+ }
+
+ const unitId = workbook.getUnitId();
+
+ const getDefinedNameMap = () => {
+ const definedNameMap = definedNamesService.getDefinedNameMap(unitId);
+ if (definedNameMap) {
+ return Array.from(Object.values(definedNameMap));
+ }
+ return [];
+ };
+
+ const [editState, setEditState] = useState(false);
+ const [definedNames, setDefinedNames] = useState<IDefinedNamesServiceParam[]>(getDefinedNameMap());
+ const [editorKey, setEditorKey] = useState<Nullable<string>>(null);
+ const [deleteConformKey, setDeleteConformKey] = useState<Nullable<string>>();
+
+ useEffect(() => {
+ const definedNamesSubscription = definedNamesService.update$.subscribe(() => {
+ setDefinedNames(getDefinedNameMap());
+ });
+
+ return () => {
+ definedNamesSubscription.unsubscribe();
+ };
+ }, []);
+
+ const insertConfirm = (param: IDefinedNamesServiceParam) => {
+ const { name, formulaOrRefString, comment, localSheetId, hidden } = param;
+
+ let id = param.id;
+ if (id == null || id.length === 0) {
+ id = Tools.generateRandomId(10);
+ commandService.executeCommand(InsertDefinedNameCommand.id, { id, unitId, name, formulaOrRefString, comment, localSheetId, hidden });
+ } else {
+ const oldDefinedName = definedNamesService.getValueById(unitId, id);
+ const newDefinedName = { id, unitId, name, formulaOrRefString, comment, localSheetId, hidden };
+ commandService.executeCommand(SetDefinedNameCommand.id, { unitId, oldDefinedName, newDefinedName });
+ }
+ setEditState(false);
+ setEditorKey(null);
+ };
+
+ const deleteDefinedName = (id: string) => {
+ setDeleteConformKey(id);
+ };
+
+ function handleDeleteClose() {
+ setDeleteConformKey(null);
+ }
+
+ function handleDeleteConfirm(id: string) {
+ const item = definedNamesService.getValueById(unitId, id);
+ commandService.executeCommand(RemoveDefinedNameCommand.id, { ...item, unitId });
+ setDeleteConformKey(null);
+ }
+
+ const focusDefinedName = (definedName: IDefinedNamesServiceParam) => {
+ definedNamesService.focusRange(unitId, definedName.id);
+ };
+
+ const getInsertDefinedName = () => {
+ const count = definedNames.length + 1;
+ const name = localeService.t('definedName.defaultName') + count;
+ if (definedNamesService.getValueByName(unitId, name) == null) {
+ return name;
+ }
+
+ let i = count + 1;
+ while (true) {
+ const newName = localeService.t('definedName.defaultName') + i;
+ if (definedNamesService.getValueByName(unitId, newName) == null) {
+ return newName;
+ }
+ i++;
+ }
+ };
+
+ const getInertFormulaOrRefString = () => {
+ const sheetName = workbook.getActiveSheet().getName();
+
+ const selections = selectionManagerService.getSelections();
+ if (selections == null) {
+ return '';
+ }
+
+ const formulaOrRefs = selections.map((selection) => {
+ return serializeRangeWithSheet(sheetName, selection.range);
+ });
+
+ return formulaOrRefs.join(',');
+ };
+
+ const closeInput = () => {
+ setEditState(false);
+ setEditorKey(null);
+ };
+
+ const openInsertCloseKeyEditor = () => {
+ setEditState(true);
+ setEditorKey(null);
+ };
+
+ const closeInsertOpenKeyEditor = (id: string) => {
+ setEditState(false);
+ setEditorKey(id);
+ };
+
+ const getSheetNameBySheetId = (sheetId: string) => {
+ const sheet = workbook.getSheetBySheetId(sheetId);
+ if (sheet == null) {
+ return '';
+ }
+
+ return sheet.getName();
+ };
+
+ return (
+ <div className={styles.definedNameContainer}>
+ <div className={styles.definedNameContainerScroll}>
+ <div key="insertDefinedName">
+ <div onClick={openInsertCloseKeyEditor} className={styles.definedNameContainerAddButton} style={{ display: editState ? 'none' : 'flex' }}>
+ <IncreaseSingle />
+ <span className={styles.definedNameContainerAddButtonText}>{localeService.t('definedName.addButton')}</span>
+ </div>
+ <DefinedNameInput confirm={insertConfirm} cancel={closeInput} state={editState} inputId="insertDefinedName" name={getInsertDefinedName()} formulaOrRefString={getInertFormulaOrRefString()} />
+ </div>
+
+ {definedNames.map((definedName, index) => {
+ return (
+ <div key={index}>
+ <div onClick={() => { focusDefinedName(definedName); }} className={styles.definedNameContainerItem} style={{ display: definedName.id === editorKey ? 'none' : 'flex' }}>
+ <div title={definedName.comment}>
+ <div className={styles.definedNameContainerItemName}>
+ {definedName.name}
+ <span className={styles.definedNameContainerItemNameForSheet}>
+ {(definedName.localSheetId === SCOPE_WORKBOOK_VALUE || definedName.localSheetId == null) ? '' : getSheetNameBySheetId(definedName.localSheetId)}
+ </span>
+ </div>
+ <div className={styles.definedNameContainerItemFormulaOrRefString}>{definedName.formulaOrRefString}</div>
+ </div>
+ <Tooltip title={localeService.t('definedName.updateButton')} placement="top" style={{ pointerEvents: 'none' }}>
+ <div className={clsx(styles.definedNameContainerItemUpdate, styles.definedNameContainerItemShow)} onClick={() => { closeInsertOpenKeyEditor(definedName.id); }}>
+ <CheckMarkSingle />
+ </div>
+ </Tooltip>
+ <Tooltip title={localeService.t('definedName.deleteButton')} placement="top" style={{ pointerEvents: 'none' }}>
+ <div className={clsx(styles.definedNameContainerItemDelete, styles.definedNameContainerItemShow)} onClick={() => { deleteDefinedName(definedName.id); }}>
+ <DeleteSingle />
+ </div>
+ </Tooltip>
+ </div>
+ <Confirm visible={deleteConformKey === definedName.id} onClose={handleDeleteClose} onConfirm={() => { handleDeleteConfirm(definedName.id); }}>
+ {localeService.t('definedName.deleteConfirmText')}
+ </Confirm>
+ <DefinedNameInput
+ confirm={insertConfirm}
+ cancel={closeInput}
+ state={definedName.id === editorKey}
+ id={definedName.id}
+ inputId={definedName.id + index}
+ name={definedName.name}
+ formulaOrRefString={definedName.formulaOrRefString}
+ comment={definedName.comment}
+ localSheetId={definedName.localSheetId}
+ />
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
new file mode 100644
index 0000000000..01aa90f6af
--- /dev/null
+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
@@ -0,0 +1,252 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import React, { useEffect, useState } from 'react';
+
+import { RangeSelector, TextEditor } from '@univerjs/ui';
+import type { IUnitRange, Nullable } from '@univerjs/core';
+import { AbsoluteRefType, IUniverInstanceService, LocaleService, Tools } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import { Button, Input, Radio, RadioGroup, Select } from '@univerjs/design';
+import { IDefinedNamesService, type IDefinedNamesServiceParam, IFunctionService, isReferenceString, LexerTreeBuilder, operatorToken, serializeRangeToRefString } from '@univerjs/engine-formula';
+import { ErrorSingle } from '@univerjs/icons';
+import { hasCJKText } from '@univerjs/engine-render';
+import styles from './index.module.less';
+import { SCOPE_WORKBOOK_VALUE } from './component-name';
+
+export interface IDefinedNameInputProps extends Omit<IDefinedNamesServiceParam, 'id'> {
+ inputId: string;
+ type?: string;
+ state: boolean;
+ confirm?: (param: IDefinedNamesServiceParam) => void;
+ cancel?: () => void;
+ id?: string;
+}
+
+const widthStyle: React.CSSProperties = {
+ width: '100%',
+};
+
+export const DefinedNameInput = (props: IDefinedNameInputProps) => {
+ const {
+ inputId,
+ state = false,
+ type = 'range',
+ confirm,
+ cancel,
+ name,
+ formulaOrRefString,
+ comment = '',
+ localSheetId = SCOPE_WORKBOOK_VALUE,
+ hidden = false, // 是否对用户隐藏,与excel兼容,暂时用不上。
+ id,
+
+ } = props;
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ const localeService = useDependency(LocaleService);
+ const definedNamesService = useDependency(IDefinedNamesService);
+ const functionService = useDependency(IFunctionService);
+ const lexerTreeBuilder = useDependency(LexerTreeBuilder);
+
+ if (workbook == null) {
+ return;
+ }
+
+ const unitId = workbook.getUnitId();
+
+ const sheetId = workbook.getActiveSheet().getSheetId();
+
+ const [nameValue, setNameValue] = useState(name);
+ const [formulaOrRefStringValue, setFormulaOrRefStringValue] = useState(formulaOrRefString);
+ const [commentValue, setCommentValue] = useState(comment);
+ const [localSheetIdValue, setLocalSheetIdValue] = useState(localSheetId);
+
+ const [validString, setValidString] = useState('');
+
+ const [typeValue, setTypeValue] = useState(type);
+
+ const [validFormulaOrRange, setValidFormulaOrRange] = useState(true);
+
+ const [updateFormulaOrRefStringValue, setUpdateFormulaOrRefStringValue] = useState(formulaOrRefString);
+
+ const options = [{
+ label: localeService.t('definedName.scopeWorkbook'),
+ value: SCOPE_WORKBOOK_VALUE,
+ }];
+
+ useEffect(() => {
+ setValidFormulaOrRange(true);
+ setNameValue(name);
+ setCommentValue(comment);
+ setLocalSheetIdValue(localSheetId);
+ let formulaOrRefStringCache = formulaOrRefString;
+ if (formulaOrRefString.substring(0, 1) === operatorToken.EQUALS) {
+ setTypeValue('formula');
+ } else if (isFormula(formulaOrRefString)) {
+ setTypeValue('formula');
+ formulaOrRefStringCache = operatorToken.EQUALS + formulaOrRefString;
+ } else {
+ setTypeValue('range');
+ }
+
+ setFormulaOrRefStringValue(formulaOrRefStringCache);
+ setUpdateFormulaOrRefStringValue(formulaOrRefStringCache);
+
+ setValidString('');
+ }, [state]);
+
+ const isFormula = (token: string) => {
+ return !token.split(',').every((refString) => {
+ return isReferenceString(refString.trim());
+ });
+ };
+
+ workbook.getSheetOrders().forEach((sheetId) => {
+ const sheet = workbook.getSheetBySheetId(sheetId);
+ options.push({
+ label: sheet?.getName() || '',
+ value: sheetId,
+ });
+ });
+
+ const convertRangeToString = (ranges: IUnitRange[]) => {
+ const refs = ranges.map((range) => {
+ return serializeRangeToRefString({
+ ...range,
+ sheetName: workbook.getSheetBySheetId(range.sheetId)?.getName() || '',
+ });
+ });
+
+ return refs.join(',');
+ };
+
+ const rangeSelectorChange = (ranges: IUnitRange[]) => {
+ setUpdateFormulaOrRefStringValue(convertRangeToString(ranges));
+ };
+
+ const formulaEditorChange = (value: Nullable<string>) => {
+ setUpdateFormulaOrRefStringValue(value || '');
+ };
+
+ const confirmChange = () => {
+ if (nameValue.length === 0) {
+ setValidString(localeService.t('definedName.nameEmpty'));
+ return;
+ }
+
+ if (definedNamesService.getValueByName(unitId, nameValue) != null && (id == null || id.length === 0)) {
+ setValidString(localeService.t('definedName.nameDuplicate'));
+ return;
+ }
+
+ if (!Tools.isValidParameter(nameValue) || (!Tools.isStartValidPosition(nameValue) && !hasCJKText(nameValue.substring(0, 1)))) {
+ setValidString(localeService.t('definedName.nameInvalid'));
+ return;
+ }
+
+ const sheetNames = workbook.getSheetOrders().map((sheetId) => {
+ return workbook.getSheetBySheetId(sheetId)?.getName() || '';
+ });
+
+ if (sheetNames.includes(nameValue)) {
+ setValidString(localeService.t('definedName.nameSheetConflict'));
+ return;
+ }
+
+ if (updateFormulaOrRefStringValue.length === 0) {
+ setValidString(localeService.t('definedName.formulaOrRefStringEmpty'));
+ return;
+ }
+
+ if (!validFormulaOrRange) {
+ setValidString(localeService.t('definedName.formulaOrRefStringInvalid'));
+ return;
+ }
+
+ if (functionService.hasExecutor(nameValue.toUpperCase())) {
+ setValidString(localeService.t('definedName.nameConflict'));
+ return;
+ }
+
+ confirm && confirm({
+ id: id || '',
+ name: nameValue,
+ formulaOrRefString: lexerTreeBuilder.convertRefersToAbsolute(updateFormulaOrRefStringValue, AbsoluteRefType.ALL, AbsoluteRefType.ALL),
+ comment: commentValue,
+ localSheetId: localSheetIdValue,
+ });
+ };
+
+ const typeValueChange = (value: string | number | boolean) => {
+ const type = value as string;
+ if (type === 'formula' && formulaOrRefStringValue.substring(0, 1) !== operatorToken.EQUALS) {
+ setUpdateFormulaOrRefStringValue(`${operatorToken.EQUALS}`);
+ setFormulaOrRefStringValue(`${operatorToken.EQUALS}`);
+ } else if (formulaOrRefStringValue.substring(0, 1) === operatorToken.EQUALS) {
+ setUpdateFormulaOrRefStringValue('');
+ setFormulaOrRefStringValue('');
+ }
+ setTypeValue(type);
+ };
+
+ return (
+ <div className={styles.definedNameInput} style={{ display: state ? 'block' : 'none' }}>
+ <div>
+ <Input placeholder={localeService.t('definedName.inputNamePlaceholder')} value={nameValue} allowClear onChange={setNameValue} affixWrapperStyle={widthStyle} />
+ </div>
+ <div>
+ <RadioGroup value={typeValue} onChange={typeValueChange}>
+ <Radio value="range">{localeService.t('definedName.ratioRange')}</Radio>
+ <Radio value="formula">{localeService.t('definedName.ratioFormula')}</Radio>
+ </RadioGroup>
+ </div>
+ <div style={{ display: typeValue === 'range' ? 'block' : 'none' }}>
+ <RangeSelector key={`${inputId}-rangeSelector`} value={formulaOrRefStringValue} onValid={setValidFormulaOrRange} onChange={rangeSelectorChange} placeholder={localeService.t('definedName.inputRangePlaceholder')} id={`${inputId}-rangeSelector`} width="99%" openForSheetUnitId={unitId} />
+ </div>
+ <div style={{ display: typeValue === 'range' ? 'none' : 'block' }}>
+ <TextEditor key={`${inputId}-editor`} value={formulaOrRefStringValue} onValid={setValidFormulaOrRange} onChange={formulaEditorChange} id={`${inputId}-editor`} placeholder={localeService.t('definedName.inputFormulaPlaceholder')} openForSheetUnitId={unitId} onlyInputFormula={true} style={{ width: '99%' }} canvasStyle={{ fontSize: 10 }} />
+ </div>
+ <div>
+ <Select style={widthStyle} value={localSheetIdValue} options={options} onChange={setLocalSheetIdValue} />
+ </div>
+ <div>
+ <Input affixWrapperStyle={widthStyle} placeholder={localeService.t('definedName.inputCommentPlaceholder')} value={commentValue} onChange={setCommentValue} />
+ </div>
+ <div style={{ display: validString.length === 0 ? 'none' : 'flex' }} className={styles.definedNameInputValidation}>
+ <span>
+ {validString}
+ </span>
+ <ErrorSingle />
+ </div>
+ <div>
+ <Button onClick={() => {
+ cancel && cancel();
+ }}
+ >
+ {localeService.t('definedName.cancel')}
+ </Button>
+ <Button
+ style={{ marginLeft: 15 }}
+ type="primary"
+ onClick={confirmChange}
+ >
+ {localeService.t('definedName.confirm')}
+ </Button>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx
new file mode 100644
index 0000000000..bb6dfcce03
--- /dev/null
+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx
@@ -0,0 +1,84 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import React, { useEffect, useState } from 'react';
+
+import { ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import type { IDefinedNamesServiceParam } from '@univerjs/engine-formula';
+import { IDefinedNamesService } from '@univerjs/engine-formula';
+import { SidebarDefinedNameOperation } from '../../commands/operations/sidebar-defined-name.operation';
+import styles from './index.module.less';
+
+export interface IDefinedNameOverlayProps {
+
+}
+
+export function DefinedNameOverlay(props: IDefinedNameOverlayProps) {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const definedNamesService = useDependency(IDefinedNamesService);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ const unitId = workbook.getUnitId();
+
+ const getDefinedNameMap = () => {
+ const definedNameMap = definedNamesService.getDefinedNameMap(unitId);
+ if (definedNameMap) {
+ return Array.from(Object.values(definedNameMap));
+ }
+ return [];
+ };
+
+ const [definedNames, setDefinedNames] = useState<IDefinedNamesServiceParam[]>(getDefinedNameMap());
+
+ useEffect(() => {
+ const definedNamesSubscription = definedNamesService.update$.subscribe(() => {
+ setDefinedNames(getDefinedNameMap());
+ });
+
+ return () => {
+ definedNamesSubscription.unsubscribe();
+ };
+ }, []); // Empty dependency array means this effect runs once on mount and clean up on unmount
+
+ const openSlider = () => {
+ commandService.executeCommand(SidebarDefinedNameOperation.id, { value: 'open' });
+ };
+
+ const focusDefinedName = (definedName: IDefinedNamesServiceParam) => {
+ definedNamesService.focusRange(unitId, definedName.id);
+ };
+
+ return (
+ <div className={styles.definedNameOverlay}>
+ <div className={styles.definedNameOverlayContainer}>
+ {definedNames.map((definedName, index) => {
+ return (
+ <div key={index} className={styles.definedNameOverlayItem} onClick={() => { focusDefinedName(definedName); }}>
+ <div className={styles.definedNameOverlayItemName} title={definedName.name}>{definedName.name}</div>
+ <div className={styles.definedNameOverlayItemFormula} title={definedName.formulaOrRefString}>{definedName.formulaOrRefString}</div>
+ </div>
+ );
+ })}
+ </div>
+ <div className={styles.definedNameOverlayManager} onClick={openSlider}>
+ <div className={styles.definedNameOverlayManagerTitle}>{localeService.t('definedName.managerTitle')}</div>
+ <div className={styles.definedNameOverlayManagerContent}>{localeService.t('definedName.managerDescription')}</div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/sheets-ui/src/views/defined-name/component-name.ts b/packages/sheets-ui/src/views/defined-name/component-name.ts
new file mode 100644
index 0000000000..8595f8e23f
--- /dev/null
+++ b/packages/sheets-ui/src/views/defined-name/component-name.ts
@@ -0,0 +1,19 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const DEFINED_NAME_CONTAINER = 'DefinedNameContainer';
+
+export const SCOPE_WORKBOOK_VALUE = 'AllDefaultWorkbook';
diff --git a/packages/sheets-ui/src/views/defined-name/index.module.less b/packages/sheets-ui/src/views/defined-name/index.module.less
new file mode 100644
index 0000000000..f7fe4fc530
--- /dev/null
+++ b/packages/sheets-ui/src/views/defined-name/index.module.less
@@ -0,0 +1,269 @@
+.defined-name {
+ display: flex;
+
+ position: relative;
+
+ transition: height 0.15s;
+
+ height: 100%;
+
+ border-right: 1px solid rgb(var(--border-color));
+
+ &-drop-down {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ padding: 0 var(--padding-xs);
+
+ font-size: 10px;
+
+ cursor: pointer;
+
+ position: absolute;
+
+ right: 0;
+
+ height: 100%;
+
+ &:hover {
+ background-color: rgb(var(--grey-50));
+ color: rgb(var(--primary-color));
+ }
+ }
+
+ &-overlay {
+ position: relative;
+ border: 1px solid rgb(var(--border-color));
+ width: 300px;
+ background-color: rgb(var(--color-white));
+ transform: translateX(-75px);
+
+ &-container {
+ position: relative;
+ height: 100%;
+ max-height: 400px;
+ width: 100%;
+ overflow: hidden;
+ overflow-y: auto;
+ scrollbar-color: rgba(var(--scrollbar-color), 0.7) transparent;
+ scrollbar-gutter: auto;
+ scrollbar-width: thin;
+ }
+
+ &-item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: var(--padding-xs);
+ border-bottom: 1px solid rgb(var(--border-color));
+ user-select: none;
+ cursor: pointer;
+
+ &:hover {
+ background-color: rgb(var(--grey-50));
+ }
+
+ &-name {
+ font-size: var(--font-size-md);
+ color: rgb(var(--grey-900));
+ margin: 5px 0px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ flex: 1;
+
+ &-for-sheet {
+ font-size: var(--font-size-xxs);
+ color: rgb(var(--grey-400));
+ margin-left: 5px;
+ font-weight: normal;
+ }
+ }
+
+ &-formula {
+ font-size: var(--font-size-xs);
+ color: rgb(var(--grey-800));
+ margin: 5px 0px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ flex: 1;
+ }
+ }
+
+ &-manager {
+ position: absolute;
+ display: flex;
+ flex-direction: column;
+ overflow-y: auto;
+ height: 70px;
+ width: 100%;
+ cursor: pointer;
+ overflow: hidden;
+ bottom: -70px;
+ background-color: rgb(var(--color-white));
+
+ &:hover {
+ background-color: rgb(var(--grey-50));
+ }
+
+ &-title {
+ font-size: var(--font-size-xs);
+ font-weight: bold;
+ margin: var(--margin-xs);
+ margin-bottom: 0;
+ color: rgb(var(--grey-800));
+ }
+
+ &-content {
+ font-size: var(--font-size-xxs);
+ margin: var(--margin-xs);
+ color: rgb(var(--grey-500));
+ }
+ }
+ }
+
+ &-container {
+ height: 100%;
+ width: 100%;
+ position: relative;
+
+ &-scroll {
+ height: 100%;
+ width: 100%;
+ overflow: hidden;
+ overflow-y: auto;
+ position: absolute;
+ scrollbar-color: rgba(var(--scrollbar-color), 0.7) transparent;
+ scrollbar-gutter: auto;
+ scrollbar-width: thin;
+ }
+
+ &-addButton {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ height: 40px;
+ border-top: 1px solid rgb(var(--border-color));
+ border-bottom: 1px solid rgb(var(--border-color));
+ font-size: var(--font-size-md);
+
+ color: rgb(var(--primary-color));
+
+ &:hover {
+ background-color: rgb(var(--grey-50));
+ cursor: pointer;
+ }
+
+ &-text {
+ margin-left: 5px;
+ }
+ }
+
+ &-item {
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: var(--padding-xs);
+ border-bottom: 1px solid rgb(var(--border-color));
+ user-select: none;
+ cursor: default;
+
+ &-name {
+ font-size: var(--font-size-sm);
+ font-weight: 500;
+ color: rgb(var(--color-black));
+ margin: 5px 0px;
+ max-width: 190px;
+ max-height: 100px;
+ overflow: hidden;
+
+ &-for-sheet {
+ font-size: var(--font-size-xxs);
+ color: rgb(var(--grey-400));
+ margin-left: 5px;
+ font-weight: normal;
+ }
+ }
+
+ &-formula-or-refString {
+ font-size: var(--font-size-xs);
+ color: rgb(var(--grey-500));
+ font-weight: 400;
+ margin: 5px 0px;
+ max-height: 100px;
+ text-overflow: ellipsis;
+ overflow: hidden;
+ }
+
+ &-update {
+ position: absolute;
+ font-size: var(--font-size-xs);
+ color: rgb(var(--primary-color));
+ cursor: pointer;
+ padding: 4px;
+ &:hover {
+ background-color: rgb(var(--hyacinth-50));
+ }
+ transform: translate(0, -50%);
+ border-radius: var(--border-radius-base);
+ right: 60px;
+ top: 20px;
+ }
+
+ &-delete {
+ position: absolute;
+ font-size: var(--font-size-xs);
+ color: rgb(var(--error-color));
+ cursor: pointer;
+ padding: 4px;
+ right: 20px;
+ top: 20px;
+ transform: translate(0, -50%);
+ border-radius: var(--border-radius-base);
+ &:hover {
+ background-color: rgb(var(--hyacinth-50));
+ }
+ }
+
+ &-show {
+ display: none;
+ }
+
+ &:hover {
+ background-color: rgb(var(--grey-50));
+
+ .defined-name-container-item-show {
+ display: block;
+ }
+ }
+ }
+ }
+
+ &-input {
+ display: flex;
+ align-items: center;
+ justify-content: left;
+ border-bottom: 1px solid rgb(var(--border-color));
+ padding-bottom: 5px;
+
+ & > div {
+ width: 100%;
+ margin-top: 5px;
+ }
+
+ &-validation {
+ display: flex;
+ align-items: center;
+ justify-content: left;
+ color: rgb(var(--error-color));
+ font-size: var(--font-size-xs);
+
+ & > span {
+ margin-right: 2px;
+ }
+ }
+ }
+}
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index 9e4a4ac3f0..fd6ab2151d 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -25,6 +25,8 @@ import React, { useEffect, useState } from 'react';
import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
+
+import { DefinedName } from '../defined-name/DefinedName';
import styles from './index.module.less';
enum ArrowDirection {
@@ -124,7 +126,7 @@ export function FormulaBar() {
return (
<div className={styles.formulaBox} style={{ height: ArrowDirection.Down === arrowDirection ? '28px' : '82px' }}>
<div className={styles.nameRanges}>
- <div className={styles.nameRangesInput} />
+ <DefinedName />
</div>
<div className={styles.formulaBar}>
@@ -144,7 +146,7 @@ export function FormulaBar() {
<CheckMarkSingle />
</span>
- <span className={styles.iconContainer} onClick={handlerFxBtnClick}>
+ <span className={clsx(styles.iconContainer, styles.iconContainerFx)} onClick={handlerFxBtnClick}>
<FxSingle />
</span>
</div>
diff --git a/packages/sheets-ui/src/views/formula-bar/index.module.less b/packages/sheets-ui/src/views/formula-bar/index.module.less
index e0548bc446..8711fd81e4 100644
--- a/packages/sheets-ui/src/views/formula-bar/index.module.less
+++ b/packages/sheets-ui/src/views/formula-bar/index.module.less
@@ -11,15 +11,9 @@
.name-ranges {
box-sizing: border-box;
- width: 80px;
+ width: 100px;
height: 100%;
position: relative;
- flex-shrink: 0;
-
- &-input {
- height: 100%;
- border-right: 1px solid rgb(var(--border-color));
- }
}
.formula-bar {
@@ -34,7 +28,7 @@
position: relative;
display: flex;
- gap: var(--margin-xs);
+ // gap: var(--margin-xs);
align-items: center;
justify-content: center;
@@ -47,23 +41,40 @@
border-right: 1px solid rgb(var(--border-color));
.icon-container {
- cursor: pointer;
-
display: flex;
align-items: center;
justify-content: center;
+ padding: var(--padding-xs);
+
font-size: var(--font-size-lg);
+ border-radius: var(--border-radius-base);
+
&-success {
&.formula-active {
+ cursor: pointer;
color: rgb(var(--success-color));
+ &:hover {
+ background-color: rgb(var(--grey-50));
+ }
}
}
&-error {
&.formula-active {
+ cursor: pointer;
color: rgb(var(--error-color));
+ &:hover {
+ background-color: rgb(var(--grey-50));
+ }
+ }
+ }
+
+ &-fx {
+ cursor: pointer;
+ &:hover {
+ background-color: rgb(var(--grey-50));
}
}
}
diff --git a/packages/sheets/src/commands/commands/insert-defined-name.command.ts b/packages/sheets/src/commands/commands/insert-defined-name.command.ts
new file mode 100644
index 0000000000..4b83a7630b
--- /dev/null
+++ b/packages/sheets/src/commands/commands/insert-defined-name.command.ts
@@ -0,0 +1,58 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+import type { IAccessor } from '@wendellhu/redi';
+import { type ISetDefinedNameMutationParam, RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';
+
+/**
+ * The command to insert new defined name
+ */
+export const InsertDefinedNameCommand: ICommand = {
+ id: 'sheet.command.insert-defined-name',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: ISetDefinedNameMutationParam) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ if (!params) return false;
+
+ // prepare do mutations
+ const insertSheetMutationParams: ISetDefinedNameMutationParam = {
+ ...params,
+ };
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.syncExecuteCommand(SetDefinedNameMutation.id, insertSheetMutationParams);
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: params.unitId,
+ undoMutations: [{ id: RemoveDefinedNameMutation.id, params: insertSheetMutationParams }],
+ redoMutations: [{ id: SetDefinedNameMutation.id, params: insertSheetMutationParams }],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets/src/commands/commands/remove-defined-name.command.ts b/packages/sheets/src/commands/commands/remove-defined-name.command.ts
new file mode 100644
index 0000000000..4b0f1ab7c4
--- /dev/null
+++ b/packages/sheets/src/commands/commands/remove-defined-name.command.ts
@@ -0,0 +1,58 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+import type { IAccessor } from '@wendellhu/redi';
+import { type ISetDefinedNameMutationParam, RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';
+
+/**
+ * The command to remove new defined name
+ */
+export const RemoveDefinedNameCommand: ICommand = {
+ id: 'sheet.command.remove-defined-name',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: ISetDefinedNameMutationParam) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ if (!params) return false;
+
+ // prepare do mutations
+ const removeSheetMutationParams: ISetDefinedNameMutationParam = {
+ ...params,
+ };
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.syncExecuteCommand(RemoveDefinedNameMutation.id, removeSheetMutationParams);
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: params.unitId,
+ undoMutations: [{ id: SetDefinedNameMutation.id, params: removeSheetMutationParams }],
+ redoMutations: [{ id: RemoveDefinedNameMutation.id, params: removeSheetMutationParams }],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets/src/commands/commands/set-defined-name.command.ts b/packages/sheets/src/commands/commands/set-defined-name.command.ts
new file mode 100644
index 0000000000..4c47452071
--- /dev/null
+++ b/packages/sheets/src/commands/commands/set-defined-name.command.ts
@@ -0,0 +1,59 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+import type { IAccessor } from '@wendellhu/redi';
+import { type ISetDefinedNameMutationParam, SetDefinedNameMutation } from '@univerjs/engine-formula';
+
+export interface ISetDefinedNameCommandParams {
+ unitId: string;
+ oldDefinedName: ISetDefinedNameMutationParam;
+ newDefinedName: ISetDefinedNameMutationParam;
+}
+
+/**
+ * The command to update defined name
+ */
+export const SetDefinedNameCommand: ICommand = {
+ id: 'sheet.command.set-defined-name',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: ISetDefinedNameCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ if (!params) return false;
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.syncExecuteCommand(SetDefinedNameMutation.id, params.newDefinedName);
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: params.unitId,
+ undoMutations: [{ id: SetDefinedNameMutation.id, params: params.oldDefinedName }],
+ redoMutations: [{ id: SetDefinedNameMutation.id, params: params.newDefinedName }],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets/src/commands/operations/scroll-to-cell.operation.ts b/packages/sheets/src/commands/operations/scroll-to-cell.operation.ts
new file mode 100644
index 0000000000..a3f560a653
--- /dev/null
+++ b/packages/sheets/src/commands/operations/scroll-to-cell.operation.ts
@@ -0,0 +1,24 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IOperation, IRange } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+
+export const ScrollToCellOperation: IOperation<IRange> = {
+ id: 'sheet.operation.scroll-to-cell',
+ type: CommandType.OPERATION,
+ handler: () => true,
+};
diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.ts
index ee53b139c6..5fe3dc9d23 100644
--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts
+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts
@@ -109,6 +109,10 @@ import {
import { SetSelectionsOperation } from '../commands/operations/selection.operation';
import { SetWorksheetActiveOperation } from '../commands/operations/set-worksheet-active.operation';
import { EmptyMutation } from '../commands/mutations/empty.mutation';
+import { InsertDefinedNameCommand } from '../commands/commands/insert-defined-name.command';
+import { RemoveDefinedNameCommand } from '../commands/commands/remove-defined-name.command';
+import { SetDefinedNameCommand } from '../commands/commands/set-defined-name.command';
+import { ScrollToCellOperation } from '../commands/operations/scroll-to-cell.operation';
import { MAX_CELL_PER_SHEET_DEFAULT, MAX_CELL_PER_SHEET_KEY } from './config/config';
export interface IStyleTypeValue<T> {
@@ -214,6 +218,10 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetSelectionsOperation,
RemoveNumfmtMutation,
EmptyMutation,
+ InsertDefinedNameCommand,
+ RemoveDefinedNameCommand,
+ SetDefinedNameCommand,
+ ScrollToCellOperation,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
this._configService.setConfig(MAX_CELL_PER_SHEET_KEY, MAX_CELL_PER_SHEET_DEFAULT);
diff --git a/packages/sheets/src/controllers/defined-name-data.controller.ts b/packages/sheets/src/controllers/defined-name-data.controller.ts
new file mode 100644
index 0000000000..760c302861
--- /dev/null
+++ b/packages/sheets/src/controllers/defined-name-data.controller.ts
@@ -0,0 +1,93 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type {
+ Workbook } from '@univerjs/core';
+import {
+ Disposable,
+ ICommandService,
+ IResourceManagerService,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+ toDisposable,
+} from '@univerjs/core';
+import type { IDefinedNameMapItem } from '@univerjs/engine-formula';
+import { IDefinedNamesService } from '@univerjs/engine-formula';
+
+const SHEET_DEFINED_NAME_PLUGIN = 'SHEET_DEFINED_NAME_PLUGIN';
+
+@OnLifecycle(LifecycleStages.Ready, DefinedNameDataController)
+export class DefinedNameDataController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,
+ @IResourceManagerService private _resourceManagerService: IResourceManagerService
+
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize(): void {
+ this._initSnapshot();
+ }
+
+ private _initSnapshot() {
+ const toJson = (unitID: string) => {
+ const map = this._definedNamesService.getDefinedNameMap(unitID);
+ if (map) {
+ return JSON.stringify(map);
+ }
+ return '';
+ };
+ const parseJson = (json: string): IDefinedNameMapItem => {
+ if (!json) {
+ return {};
+ }
+ try {
+ return JSON.parse(json);
+ } catch (err) {
+ return {};
+ }
+ };
+ const handleWorkbookAdd = (workbook: Workbook) => {
+ const unitID = workbook.getUnitId();
+ this.disposeWithMe(
+ this._resourceManagerService.registerPluginResource<IDefinedNameMapItem>(unitID, SHEET_DEFINED_NAME_PLUGIN, {
+ toJson: (unitID) => toJson(unitID),
+ parseJson: (json) => parseJson(json),
+ onChange: (unitID, value) => {
+ this._definedNamesService.registerDefinedNames(unitID, value);
+ },
+ })
+ );
+ };
+ this.disposeWithMe(toDisposable(this._univerInstanceService.sheetAdded$.subscribe(handleWorkbookAdd)));
+ this.disposeWithMe(
+ toDisposable(
+ this._univerInstanceService.sheetDisposed$.subscribe((workbook) => {
+ const unitID = workbook.getUnitId();
+ this._resourceManagerService.disposePluginResource(unitID, SHEET_DEFINED_NAME_PLUGIN);
+ })
+ )
+ );
+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();
+ handleWorkbookAdd(workbook);
+ }
+}
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index a10689ef98..21c117b9e0 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -285,3 +285,8 @@ export { SheetInterceptorService } from './services/sheet-interceptor/sheet-inte
export type { ISheetLocation } from './services/sheet-interceptor/utils/interceptor';
export { MergeCellController } from './controllers/merge-cell.controller';
export { AddMergeRedoSelectionsOperationFactory, AddMergeUndoSelectionsOperationFactory } from './commands/utils/handle-merge-operation';
+
+export { InsertDefinedNameCommand } from './commands/commands/insert-defined-name.command';
+export { RemoveDefinedNameCommand } from './commands/commands/remove-defined-name.command';
+export { SetDefinedNameCommand, type ISetDefinedNameCommandParams } from './commands/commands/set-defined-name.command';
+export { ScrollToCellOperation } from './commands/operations/scroll-to-cell.operation';
diff --git a/packages/sheets/src/sheets-plugin.ts b/packages/sheets/src/sheets-plugin.ts
index 81d089b0ab..fbae4be929 100644
--- a/packages/sheets/src/sheets-plugin.ts
+++ b/packages/sheets/src/sheets-plugin.ts
@@ -30,6 +30,7 @@ import { SheetPermissionService } from './services/permission';
import { RefRangeService } from './services/ref-range/ref-range.service';
import { SelectionManagerService } from './services/selection-manager.service';
import { SheetInterceptorService } from './services/sheet-interceptor/sheet-interceptor.service';
+import { DefinedNameDataController } from './controllers/defined-name-data.controller';
const PLUGIN_NAME = 'sheet';
@@ -73,10 +74,14 @@ export class UniverSheetsPlugin extends Plugin {
// controllers
[BasicWorksheetController],
[MergeCellController],
+ [DefinedNameDataController],
];
if (!this._config?.notExecuteFormula) {
- dependencies.push([CalculateResultApplyController], [FeatureCalculationController]);
+ dependencies.push(
+ [CalculateResultApplyController],
+ [FeatureCalculationController]
+ );
}
dependencies.forEach((d) => {
diff --git a/packages/ui/src/components/range-selector/RangeSelector.tsx b/packages/ui/src/components/range-selector/RangeSelector.tsx
index 9e92947317..142b829707 100644
--- a/packages/ui/src/components/range-selector/RangeSelector.tsx
+++ b/packages/ui/src/components/range-selector/RangeSelector.tsx
@@ -38,8 +38,8 @@ export interface IRangeSelectorProps {
isReadonly?: boolean; // Set the selector to read-only state.
openForSheetUnitId?: Nullable<string>; // Configuring which workbook the selector defaults to opening in determines whether the ref includes a [unitId] prefix.
openForSheetSubUnitId?: Nullable<string>; // Configuring the default worksheet where the selector opens determines whether the ref includes a [unitId]sheet1 prefix.
- width?: number; // The width of the selector.
- size?: 'small' | 'middle' | 'large'; // The size of the selector.
+ width?: number | string; // The width of the selector.
+ size?: 'mini' | 'small' | 'middle' | 'large'; // The size of the selector.
placeholder?: string; // Placeholder text.
className?: string;
}
@@ -254,6 +254,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
setRangeValue(value || '');
if (value === '') {
+ onChange && onChange([]);
return;
}
@@ -279,7 +280,9 @@ export function RangeSelector(props: IRangeSelectorProps) {
}
let height = 32;
- if (size === 'small') {
+ if (size === 'mini') {
+ height = 24;
+ } else if (size === 'small') {
height = 28;
} else if (size === 'large') {
height = 36;
diff --git a/packages/ui/src/services/editor/editor.service.ts b/packages/ui/src/services/editor/editor.service.ts
index 58012eb5aa..f97a85c9a3 100644
--- a/packages/ui/src/services/editor/editor.service.ts
+++ b/packages/ui/src/services/editor/editor.service.ts
@@ -136,7 +136,7 @@ export class Editor {
}
isSingle() {
- return this._param.isSingle === true || this.onlyInputFormula() || this.onlyInputFormula();
+ return this._param.isSingle === true || this.onlyInputRange();
}
isReadOnly() {