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.

fix(definedName): optimize performance issues related to defined name (#6829)

wpxp1234568c15220ee9f3
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 7432753286..283de88d2a 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
@@ -34,18 +34,18 @@ export interface ISetDefinedNameMutationParam extends ISetDefinedNameMutationSea
/**
* Generate undo mutation of a `SetDefinedNameMutation`
- * @param accessor
- * @param params
- * @returns
*/
export const SetDefinedNameMutationFactory = (
accessor: IAccessor,
params: ISetDefinedNameMutationParam
-): ISetDefinedNameMutationParam => {
+): ISetDefinedNameMutationParam | null => {
const { unitId, id } = params;
const definedNamesService = accessor.get(IDefinedNamesService);
const definedName = definedNamesService.getValueById(unitId, id);
+ if (!definedName) {
+ return null;
+ }
return {
...definedName,
diff --git a/packages/engine-formula/src/controllers/formula.controller.ts b/packages/engine-formula/src/controllers/formula.controller.ts
index 56f22bea6d..0220e65469 100644
--- a/packages/engine-formula/src/controllers/formula.controller.ts
+++ b/packages/engine-formula/src/controllers/formula.controller.ts
@@ -46,22 +46,7 @@ import { SetImageFormulaDataMutation } from '../commands/mutations/set-image-for
import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../commands/mutations/set-other-formula.mutation';
import { RemoveSuperTableMutation, SetSuperTableMutation, SetSuperTableOptionMutation } from '../commands/mutations/set-super-table.mutation';
import { ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../config/config';
-import { functionArray } from '../functions/array/function-map';
-import { functionCompatibility } from '../functions/compatibility/function-map';
-import { functionCube } from '../functions/cube/function-map';
-import { functionDatabase } from '../functions/database/function-map';
-import { functionDate } from '../functions/date/function-map';
-import { functionEngineering } from '../functions/engineering/function-map';
-import { functionFinancial } from '../functions/financial/function-map';
-import { functionInformation } from '../functions/information/function-map';
-import { functionLogical } from '../functions/logical/function-map';
-import { functionLookup } from '../functions/lookup/function-map';
-import { functionMath } from '../functions/math/function-map';
-import { functionMeta } from '../functions/meta/function-map';
-import { functionStatistical } from '../functions/statistical/function-map';
-import { functionText } from '../functions/text/function-map';
-import { functionUniver } from '../functions/univer/function-map';
-import { functionWeb } from '../functions/web/function-map';
+import { ALL_IMPLEMENTED_FUNCTIONS } from '../functions';
import { IFunctionService } from '../services/function.service';
export class FormulaController extends Disposable {
@@ -123,27 +108,7 @@ export class FormulaController extends Disposable {
private _registerFunctions() {
const config = this._configService.getConfig<IUniverEngineFormulaConfig>(ENGINE_FORMULA_PLUGIN_CONFIG_KEY);
- const functions: BaseFunction[] = (
- [
- ...functionArray,
- ...functionCompatibility,
- ...functionCube,
- ...functionDatabase,
- ...functionDate,
- ...functionEngineering,
- ...functionFinancial,
- ...functionInformation,
- ...functionLogical,
- ...functionLookup,
- ...functionMath,
- ...functionMeta,
- ...functionStatistical,
- ...functionText,
- ...functionUniver,
- ...functionWeb,
- ] as Array<[Ctor<BaseFunction>, IFunctionNames]>
- )
- .concat(config?.function ?? [])
+ const functions: BaseFunction[] = ALL_IMPLEMENTED_FUNCTIONS.concat(config?.function ?? [])
.map((registerObject) => {
const Func = registerObject[0] as Ctor<BaseFunction>;
const name = registerObject[1] as IFunctionNames;
diff --git a/packages/engine-formula/src/functions/index.ts b/packages/engine-formula/src/functions/index.ts
new file mode 100644
index 0000000000..50a282344c
--- /dev/null
+++ b/packages/engine-formula/src/functions/index.ts
@@ -0,0 +1,56 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Ctor } from '@univerjs/core';
+import type { IFunctionNames } from '../basics/function';
+import type { BaseFunction } from './base-function';
+import { functionArray } from './array/function-map';
+import { functionCompatibility } from './compatibility/function-map';
+import { functionCube } from './cube/function-map';
+import { functionDatabase } from './database/function-map';
+import { functionDate } from './date/function-map';
+import { functionEngineering } from './engineering/function-map';
+import { functionFinancial } from './financial/function-map';
+import { functionInformation } from './information/function-map';
+import { functionLogical } from './logical/function-map';
+import { functionLookup } from './lookup/function-map';
+import { functionMath } from './math/function-map';
+import { functionMeta } from './meta/function-map';
+import { functionStatistical } from './statistical/function-map';
+import { functionText } from './text/function-map';
+import { functionUniver } from './univer/function-map';
+import { functionWeb } from './web/function-map';
+
+export const ALL_IMPLEMENTED_FUNCTIONS = [
+ ...functionArray,
+ ...functionCompatibility,
+ ...functionCube,
+ ...functionDatabase,
+ ...functionDate,
+ ...functionEngineering,
+ ...functionFinancial,
+ ...functionInformation,
+ ...functionLogical,
+ ...functionLookup,
+ ...functionMath,
+ ...functionMeta,
+ ...functionStatistical,
+ ...functionText,
+ ...functionUniver,
+ ...functionWeb,
+] as Array<[Ctor<BaseFunction>, IFunctionNames]>;
+
+export const ALL_IMPLEMENTED_FUNCTIONS_SET = new Set(ALL_IMPLEMENTED_FUNCTIONS.map(([_, name]) => name));
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 396919eeea..295d679800 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -161,6 +161,7 @@ export { functionEngineering } from './functions/engineering/function-map';
export { FUNCTION_NAMES_ENGINEERING } from './functions/engineering/function-names';
export { functionFinancial } from './functions/financial/function-map';
export { FUNCTION_NAMES_FINANCIAL } from './functions/financial/function-names';
+export { ALL_IMPLEMENTED_FUNCTIONS, ALL_IMPLEMENTED_FUNCTIONS_SET } from './functions/index';
export { functionInformation } from './functions/information/function-map';
export { FUNCTION_NAMES_INFORMATION } from './functions/information/function-names';
export { functionLogical } from './functions/logical/function-map';
@@ -188,7 +189,7 @@ export { ActiveDirtyManagerService, IActiveDirtyManagerService } from './service
export { CalculateFormulaService, ICalculateFormulaService } from './services/calculate-formula.service';
export { DEFAULT_INTERVAL_COUNT } from './services/calculate-formula.service';
export { FormulaCurrentConfigService, IFormulaCurrentConfigService, type IFormulaDirtyData } from './services/current-data.service';
-export { DefinedNamesService, type IDefinedNameMapItem, IDefinedNamesService, type IDefinedNamesServiceParam } from './services/defined-names.service';
+export { DefinedNamesService, type IDefinedNameMapItem, IDefinedNamesService, type IDefinedNamesServiceParam, type IDefinedNamesUpdateEvent } from './services/defined-names.service';
export { IDependencyManagerService } from './services/dependency-manager.service';
export { DependencyManagerService } from './services/dependency-manager.service';
export { DependencyManagerBaseService } from './services/dependency-manager.service';
@@ -201,11 +202,8 @@ export { IFunctionService } from './services/function.service';
export { GlobalComputingStatusService } from './services/global-computing-status.service';
export { HyperlinkEngineFormulaService, IHyperlinkEngineFormulaService } from './services/hyperlink-engine-formula.service';
export { IOtherFormulaManagerService, OtherFormulaManagerService } from './services/other-formula-manager.service';
-
export { OtherFormulaBizType, RegisterOtherFormulaService } from './services/register-other-formula.service';
export { FormulaExecutedStateType, FormulaExecuteStageType, FormulaRuntimeService, type IAllRuntimeData, type IExecutionInProgressParams, IFormulaRuntimeService } from './services/runtime.service';
export { ISheetRowFilteredService, SheetRowFilteredService } from './services/sheet-row-filtered.service';
-
export { ISuperTableService } from './services/super-table.service';
-
export { SuperTableService } from './services/super-table.service';
diff --git a/packages/engine-formula/src/services/defined-names.service.ts b/packages/engine-formula/src/services/defined-names.service.ts
index 98c355548d..62e929ecbd 100644
--- a/packages/engine-formula/src/services/defined-names.service.ts
+++ b/packages/engine-formula/src/services/defined-names.service.ts
@@ -42,6 +42,12 @@ export interface IDefinedNameMapItem {
[id: string]: IDefinedNamesServiceParam;
}
+export interface IDefinedNamesUpdateEvent {
+ type: 'update' | 'remove';
+ unitId: string;
+ definedNames: IDefinedNamesServiceParam[];
+}
+
export interface IDefinedNamesService {
registerDefinedName(unitId: string, param: IDefinedNamesServiceParam): void;
@@ -67,7 +73,7 @@ export interface IDefinedNamesService {
currentRange$: Observable<IUnitRange>;
- update$: Observable<unknown>;
+ update$: Observable<IDefinedNamesUpdateEvent>;
focusRange$: Observable<IDefinedNamesServiceFocusParam>;
@@ -78,13 +84,15 @@ export interface IDefinedNamesService {
getAllDefinedNames(): IDefinedNameMap;
}
+
export class DefinedNamesService extends Disposable implements IDefinedNamesService {
// 18.2.6 definedNames (Defined Names)
private _definedNameMap: IDefinedNameMap = {};
// Cache for name-to-definition mapping, here name key is ignored case sensitivity
private _nameCacheMap: { [unitId: string]: { [name: string]: IDefinedNamesServiceParam } } = {};
- private readonly _update$ = new Subject();
+ private readonly _update$ = new Subject<IDefinedNamesUpdateEvent>();
+
readonly update$ = this._update$.asObservable();
private _currentRange: IUnitRange = {
@@ -147,7 +155,11 @@ export class DefinedNamesService extends Disposable implements IDefinedNamesServ
registerDefinedNames(unitId: string, params: IDefinedNameMapItem) {
this._definedNameMap[unitId] = params;
this._updateCache(unitId);
- this._update();
+ this._update({
+ type: 'update',
+ unitId,
+ definedNames: Object.values(params),
+ });
}
registerDefinedName(unitId: string, param: IDefinedNamesServiceParam) {
@@ -159,19 +171,41 @@ export class DefinedNamesService extends Disposable implements IDefinedNamesServ
this._definedNameMap[unitId][param.id] = param;
this._updateCache(unitId);
- this._update();
+ this._update({
+ type: 'update',
+ unitId,
+ definedNames: [param],
+ });
}
removeDefinedName(unitId: string, id: string) {
- delete this._definedNameMap[unitId]?.[id];
+ const definedName = this._definedNameMap[unitId]?.[id];
+ if (!definedName) {
+ return;
+ }
+
+ delete this._definedNameMap[unitId][id];
this._updateCache(unitId);
- this._update();
+ this._update({
+ type: 'remove',
+ unitId,
+ definedNames: [definedName],
+ });
}
removeUnitDefinedName(unitId: string) {
+ const definedNames = this._definedNameMap[unitId];
+ if (!definedNames) {
+ return;
+ }
+
delete this._definedNameMap[unitId];
this._updateCache(unitId);
- this._update();
+ this._update({
+ type: 'remove',
+ unitId,
+ definedNames: Object.values(definedNames),
+ });
}
getDefinedNameMap(unitId: string) {
@@ -234,8 +268,8 @@ export class DefinedNamesService extends Disposable implements IDefinedNamesServ
}
}
- private _update() {
- this._update$.next(null);
+ private _update(event: IDefinedNamesUpdateEvent) {
+ this._update$.next(event);
}
private _updateCache(unitId: string) {
diff --git a/packages/engine-formula/src/services/function.service.ts b/packages/engine-formula/src/services/function.service.ts
index 731163c60a..527e1cd360 100644
--- a/packages/engine-formula/src/services/function.service.ts
+++ b/packages/engine-formula/src/services/function.service.ts
@@ -48,12 +48,14 @@ export interface IFunctionService {
getDescriptions(): Map<IFunctionNames, IFunctionInfo>;
- getDescription(functionToken: IFunctionNames): Nullable<IFunctionInfo>;
+ getDescription(functionToken: IFunctionNames): IFunctionInfo | undefined;
hasDescription(functionToken: IFunctionNames): boolean;
unregisterDescriptions(...functionTokens: IFunctionNames[]): void;
+ clearDescriptions(): void;
+
deleteFormulaAstCacheKey(...functionToken: IFunctionNames[]): void;
}
export const IFunctionService = createIdentifier<FunctionService>('univer.formula-function.service');
@@ -128,6 +130,10 @@ export class FunctionService extends Disposable implements IFunctionService {
}
}
+ clearDescriptions() {
+ this._functionDescriptions.clear();
+ }
+
deleteFormulaAstCacheKey(...functionToken: IFunctionNames[]) {
FORMULA_AST_CACHE.forEach((_, key) => {
functionToken.forEach((token) => {
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts
index 7f978ad298..77bc09de74 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts
@@ -56,7 +56,8 @@ export const useFormulaSearch = (isNeed: boolean, nodes: INode[] = [], editor?:
indexRef.current = currentNodeIndex;
const token = currentNode.token;
const list = descriptionService.getSearchListByNameFirstLetter(token);
- setSearchList(list);
+ // Here we limit the maximum number of search results to 10 to prevent performance issues caused by rendering too many items in the dropdown.
+ setSearchList(list.slice(0, 10));
setSearchText(token);
return;
}
diff --git a/packages/sheets-formula/src/controllers/defined-name.controller.ts b/packages/sheets-formula/src/controllers/defined-name.controller.ts
index 685f1cdd92..4ca6c2db27 100644
--- a/packages/sheets-formula/src/controllers/defined-name.controller.ts
+++ b/packages/sheets-formula/src/controllers/defined-name.controller.ts
@@ -14,8 +14,9 @@
* limitations under the License.
*/
-import type { ICommandInfo, IExecutionOptions, Nullable, Workbook } from '@univerjs/core';
-import type { IFunctionInfo, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
+import type { ICommandInfo, IExecutionOptions, Workbook } from '@univerjs/core';
+import type { IDefinedNamesUpdateEvent, IFunctionInfo, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
+import type { ISetWorksheetActiveOperationParams } from '@univerjs/sheets';
import {
Disposable,
ICommandService,
@@ -24,8 +25,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { FunctionType, IDefinedNamesService, RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';
-import { SCOPE_WORKBOOK_VALUE_DEFINED_NAME, SetWorksheetActiveOperation } from '@univerjs/sheets';
-
+import { getSheetCommandTarget, SCOPE_WORKBOOK_VALUE_DEFINED_NAME, SetWorksheetActiveOperation } from '@univerjs/sheets';
import { IDescriptionService } from '../services/description.service';
/**
@@ -33,7 +33,7 @@ import { IDescriptionService } from '../services/description.service';
* column menu: show, hover and mousedown event
*/
export class DefinedNameController extends Disposable {
- private _preUnitId: Nullable<string> = null;
+ private _preUnitId: string | null = null;
constructor(
@IDescriptionService private readonly _descriptionService: IDescriptionService,
@@ -49,28 +49,30 @@ export class DefinedNameController extends Disposable {
private _initialize() {
this._descriptionListener();
-
this._changeUnitListener();
-
this._changeSheetListener();
}
private _descriptionListener() {
- toDisposable(
- this._definedNamesService.update$.subscribe(() => {
- this._registerDescriptions();
- })
+ this.disposeWithMe(
+ toDisposable(
+ this._definedNamesService.update$.subscribe((event) => {
+ this._updateDescriptions(event);
+ })
+ )
);
}
private _changeUnitListener() {
- toDisposable(
- this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe((workbook) => {
- this._unRegisterDescriptions();
- if (workbook) {
- this._registerDescriptions();
- }
- })
+ this.disposeWithMe(
+ toDisposable(
+ this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe((workbook) => {
+ this._unRegisterDescriptions();
+ if (workbook) {
+ this._initRegisterDescriptions(workbook.getUnitId());
+ }
+ })
+ )
);
}
@@ -82,30 +84,73 @@ export class DefinedNameController extends Disposable {
}
if (command.id === SetWorksheetActiveOperation.id) {
- this._unregisterDescriptionsForNotInSheetId();
- this._registerDescriptions();
- }
- // Since command interception will supplement mutation, it is necessary to monitor mutation changes here
- // SetDefinedNameMutation and RemoveDefinedNameMutation already cover all possible Defined Name updates
- else if (command.id === SetDefinedNameMutation.id) {
- const param = command.params as ISetDefinedNameMutationParam;
- this._registerDescription(param);
+ const params = command.params as ISetWorksheetActiveOperationParams;
+ this._unregisterDescriptionsForNotInSheetId(params.unitId, params.subUnitId);
+ this._initRegisterDescriptions(params.unitId, params.subUnitId);
+ } else if (command.id === SetDefinedNameMutation.id) {
+ // Since command interception will supplement mutation, it is necessary to monitor mutation changes here
+ // SetDefinedNameMutation and RemoveDefinedNameMutation already cover all possible Defined Name updates
+ const params = command.params as ISetDefinedNameMutationParam;
+ this._registerDescription(params);
} else if (command.id === RemoveDefinedNameMutation.id) {
- const param = command.params as ISetDefinedNameMutationParam;
- this._unregisterDescription(param);
+ const params = command.params as ISetDefinedNameMutationParam;
+ this._unregisterDescription(params);
}
})
);
}
- private _registerDescription(param: ISetDefinedNameMutationParam) {
- const target = this._getUnitIdAndSheetId(param);
+ private _updateDescriptions(event: IDefinedNamesUpdateEvent) {
+ const target = getSheetCommandTarget(this._univerInstanceService);
+ if (!target) return;
+
+ const { unitId, subUnitId } = target;
+ const { type, unitId: updateUnitId, definedNames } = event;
+
+ if (updateUnitId !== unitId) {
+ return;
+ }
+
+ if (type === 'update') {
+ const functionList: IFunctionInfo[] = [];
+
+ definedNames.forEach((definedName) => {
+ const { name, comment, formulaOrRefString, localSheetId } = definedName;
+ if (localSheetId == null || localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME || localSheetId === subUnitId) {
+ functionList.push({
+ functionName: name,
+ description: formulaOrRefString + (comment || ''),
+ abstract: formulaOrRefString,
+ functionType: FunctionType.DefinedName,
+ functionParameter: [],
+ });
+ }
+ });
+
+ this._descriptionService.registerDescriptions(functionList);
+ } else if (type === 'remove') {
+ const functionList: string[] = [];
+
+ definedNames.forEach((definedName) => {
+ functionList.push(definedName.name);
+ });
+
+ this._descriptionService.unregisterDescriptions(functionList);
+ }
+ }
+
+ private _registerDescription(params: ISetDefinedNameMutationParam) {
+ const target = getSheetCommandTarget(this._univerInstanceService, params);
if (!target) return;
- const { sheetId } = target;
+ const { subUnitId } = target;
+ const { name, comment, formulaOrRefString, localSheetId } = params;
+
+ if (this._descriptionService.hasDescription(name)) {
+ return;
+ }
- const { name, comment, formulaOrRefString, localSheetId } = param;
- if (!this._descriptionService.hasDescription(name) && (localSheetId == null || localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME || localSheetId === sheetId)) {
+ if (localSheetId == null || localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME || localSheetId === subUnitId) {
this._descriptionService.registerDescriptions([{
functionName: name,
description: formulaOrRefString + (comment || ''),
@@ -122,12 +167,12 @@ export class DefinedNameController extends Disposable {
}
private _unRegisterDescriptions() {
- if (this._preUnitId == null) {
+ if (this._preUnitId === null) {
return;
}
- const definedNames = this._definedNamesService.getDefinedNameMap(this._preUnitId);
- if (definedNames == null) {
+ const definedNames = this._definedNamesService.getDefinedNameMap(this._preUnitId);
+ if (!definedNames) {
return;
}
@@ -142,43 +187,29 @@ export class DefinedNameController extends Disposable {
this._preUnitId = null;
}
- private _getUnitIdAndSheetId(params: { unitId?: string; subUnitId?: string } = {}) {
- const { unitId, subUnitId } = params;
-
- const workbook = unitId
- ? this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)
- : this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- if (!workbook) return null;
-
- const worksheet = subUnitId
- ? workbook.getSheetBySheetId(subUnitId)
- : workbook.getActiveSheet(true);
- if (!worksheet) return null;
-
- return {
- unitId: workbook.getUnitId(),
- sheetId: worksheet.getSheetId(),
- };
- }
-
- private _registerDescriptions() {
- const target = this._getUnitIdAndSheetId();
+ private _initRegisterDescriptions(unitId: string, subUnitId?: string) {
+ const target = getSheetCommandTarget(this._univerInstanceService, { unitId, subUnitId });
if (!target) return;
- const { unitId, sheetId } = target;
+ const { unitId: _unitId, subUnitId: _subUnitId } = target;
- const definedNames = this._definedNamesService.getDefinedNameMap(unitId);
+ const definedNames = this._definedNamesService.getDefinedNameMap(_unitId);
if (!definedNames) {
return;
}
const functionList: IFunctionInfo[] = [];
- this._preUnitId = unitId;
+ 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_DEFINED_NAME || localSheetId === sheetId)) {
+
+ if (this._descriptionService.hasDescription(name)) {
+ return;
+ }
+
+ if (localSheetId == null || localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME || localSheetId === _subUnitId) {
functionList.push({
functionName: name,
description: formulaOrRefString + (comment || ''),
@@ -192,12 +223,7 @@ export class DefinedNameController extends Disposable {
this._descriptionService.registerDescriptions(functionList);
}
- private _unregisterDescriptionsForNotInSheetId() {
- const target = this._getUnitIdAndSheetId();
- if (!target) return;
-
- const { unitId, sheetId } = target;
-
+ private _unregisterDescriptionsForNotInSheetId(unitId: string, subUnitId: string) {
const definedNames = this._definedNamesService.getDefinedNameMap(unitId);
if (!definedNames) {
return;
@@ -207,7 +233,7 @@ export class DefinedNameController extends Disposable {
Array.from(Object.values(definedNames)).forEach((value) => {
const { name, localSheetId } = value;
- if (localSheetId !== SCOPE_WORKBOOK_VALUE_DEFINED_NAME && localSheetId !== sheetId) {
+ if (localSheetId !== SCOPE_WORKBOOK_VALUE_DEFINED_NAME && localSheetId !== subUnitId) {
functionList.push(name);
}
});
diff --git a/packages/sheets-formula/src/services/__tests__/description.service.spec.ts b/packages/sheets-formula/src/services/__tests__/description.service.spec.ts
index 2119733e75..c8b8920d00 100644
--- a/packages/sheets-formula/src/services/__tests__/description.service.spec.ts
+++ b/packages/sheets-formula/src/services/__tests__/description.service.spec.ts
@@ -134,6 +134,20 @@ describe('DescriptionService', () => {
expect(descriptionService.isFormulaDefinedName('BOOK_RANGE')).toBe(false);
expect(descriptionService.isFormulaDefinedName('BOOK_FORMULA')).toBe(true);
expect(descriptionService.getSearchListByName('BOOK')).toEqual([]);
+ expect(descriptionService.getSearchListByNameFirstLetter('BOOK')).toEqual(
+ expect.arrayContaining([
+ {
+ name: 'BOOK_RANGE',
+ desc: 'Workbook range',
+ functionType: FunctionType.DefinedName,
+ },
+ {
+ name: 'BOOK_FORMULA',
+ desc: 'Workbook formula',
+ functionType: FunctionType.DefinedName,
+ },
+ ])
+ );
expect(descriptionService.getSearchListByType(-1)).not.toEqual(
expect.arrayContaining([
{ name: 'BOOK_RANGE', desc: 'Workbook range' },
@@ -149,6 +163,15 @@ describe('DescriptionService', () => {
localeService.setLocale(LocaleType.EN_US);
expect(descriptionService.hasFunction('CUSTOM_ALIAS')).toBe(true);
+ expect(descriptionService.getSearchListByName('ALIAS')).toContainEqual({
+ name: 'CUSTOM_ALIAS',
+ desc: 'Localized abstract',
+ });
+ expect(descriptionService.getSearchListByNameFirstLetter('CUSTOM_A')).toContainEqual({
+ name: 'CUSTOM_ALIAS',
+ desc: 'Localized abstract',
+ functionType: FunctionType.User,
+ });
expect(descriptionService.getFunctionInfo('CUSTOM_ALIAS')).toMatchObject({
functionName: 'CUSTOM_ALIAS',
description: 'Localized description',
diff --git a/packages/sheets-formula/src/services/description.service.ts b/packages/sheets-formula/src/services/description.service.ts
index 453497bc18..e8aa0980cc 100644
--- a/packages/sheets-formula/src/services/description.service.ts
+++ b/packages/sheets-formula/src/services/description.service.ts
@@ -17,29 +17,8 @@
import type { IDisposable } from '@univerjs/core';
import type { IFunctionInfo, IFunctionNames } from '@univerjs/engine-formula';
import type { IUniverSheetsFormulaBaseConfig } from '../config/config';
-import { createIdentifier, IConfigService, Inject, LocaleService, toDisposable } from '@univerjs/core';
-
-import {
- functionArray,
- functionCompatibility,
- functionCube,
- functionDatabase,
- functionDate,
- functionEngineering,
- functionFinancial,
- functionInformation,
- functionLogical,
- functionLookup,
- functionMath,
- functionMeta,
- functionStatistical,
- functionText,
- FunctionType,
- functionUniver,
- functionWeb,
- IFunctionService,
- isReferenceStrings,
-} from '@univerjs/engine-formula';
+import { createIdentifier, Disposable, IConfigService, Inject, LocaleService, toDisposable } from '@univerjs/core';
+import { ALL_IMPLEMENTED_FUNCTIONS_SET, FunctionType, IFunctionService, isReferenceStrings } from '@univerjs/engine-formula';
import { PLUGIN_CONFIG_KEY_BASE } from '../config/config';
import { FUNCTION_LIST } from './function-list/function-list';
import { getFunctionName } from './utils';
@@ -63,77 +42,148 @@ export interface IDescriptionService {
/**
* get function info by name
- * @param searchText
*/
getFunctionInfo(searchText: string): IFunctionInfo | undefined;
/**
* get search list by name
- * @param searchText
- * @returns
*/
getSearchListByName(searchText: string): ISearchItem[];
/**
* get search list by name, from first letter
- * @param searchText
- * @returns
*/
getSearchListByNameFirstLetter(searchText: string): ISearchItemWithType[];
/**
* get search list by type, if type is -1, return all
- * @param type
- * @returns
*/
getSearchListByType(type: number): ISearchItem[];
/**
* register descriptions
- * @param functionList
*/
registerDescriptions(functionList: IFunctionInfo[]): IDisposable;
/**
* unregister descriptions
- * @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.description-service');
-export class DescriptionService implements IDescriptionService, IDisposable {
- private _descriptions: IFunctionInfo[] = [];
+export class DescriptionService extends Disposable implements IDescriptionService {
+ private _descriptions: Map<IFunctionNames, IFunctionInfo> = new Map();
constructor(
@IFunctionService private readonly _functionService: IFunctionService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@IConfigService private readonly _configService: IConfigService
) {
+ super();
+
this._initialize();
}
- dispose(): void {
- this._localeService.localeChanged$.complete();
+ private _initialize() {
+ this.disposeWithMe(
+ toDisposable(
+ this._localeService.localeChanged$.subscribe(() => {
+ this._functionService.clearDescriptions();
+
+ const newDescriptions: Map<IFunctionNames, IFunctionInfo> = new Map();
+ this._descriptions.forEach((item) => {
+ const functionName = getFunctionName(item, this._localeService).toUpperCase();
+ newDescriptions.set(functionName, item);
+ });
+
+ this._descriptions = newDescriptions;
+ this._initRegisterDescriptions();
+ })
+ )
+ );
+
+ this._initDescriptions();
+ this._initRegisterDescriptions();
+ }
+
+ private _initDescriptions() {
+ const localeService = this._localeService;
+
+ FUNCTION_LIST.forEach((item) => {
+ if (ALL_IMPLEMENTED_FUNCTIONS_SET.has(item.functionName)) {
+ const functionName = getFunctionName(item, localeService).toUpperCase();
+ this._descriptions.set(functionName, item);
+ }
+ });
+
+ const config = this._configService.getConfig<IUniverSheetsFormulaBaseConfig>(PLUGIN_CONFIG_KEY_BASE);
+ config?.description?.forEach((item) => {
+ const functionName = getFunctionName(item, localeService).toUpperCase();
+ this._descriptions.set(functionName, item);
+ });
+ }
+
+ private _initRegisterDescriptions() {
+ const localeService = this._localeService;
+
+ const functionListLocale = Array.from(this._descriptions.values()).map((functionInfo) => ({
+ functionName: getFunctionName(functionInfo, localeService),
+ functionType: functionInfo.functionType,
+ description: localeService.t(functionInfo.description),
+ abstract: localeService.t(functionInfo.abstract),
+ functionParameter: functionInfo.functionParameter.map((item) => ({
+ name: localeService.t(item.name),
+ detail: localeService.t(item.detail),
+ example: item.example,
+ require: item.require,
+ repeat: item.repeat,
+ })),
+ }));
+
+ this._functionService.registerDescriptions(...functionListLocale);
+ }
+
+ private _registerDescriptions(descriptions: IFunctionInfo[]) {
+ const localeService = this._localeService;
+
+ const functionListLocale = descriptions.map((functionInfo) => ({
+ functionName: getFunctionName(functionInfo, localeService),
+ functionType: functionInfo.functionType,
+ description: localeService.t(functionInfo.description),
+ abstract: localeService.t(functionInfo.abstract),
+ functionParameter: functionInfo.functionParameter.map((item) => ({
+ name: localeService.t(item.name),
+ detail: localeService.t(item.detail),
+ example: item.example,
+ require: item.require,
+ repeat: item.repeat,
+ })),
+ }));
+
+ this._functionService.registerDescriptions(...functionListLocale);
+ }
+
+ override dispose(): void {
+ super.dispose();
+
+ this._descriptions.clear();
}
getDescriptions() {
@@ -141,23 +191,27 @@ export class DescriptionService implements IDescriptionService, IDisposable {
}
hasFunction(searchText: string) {
- const functionList = this._functionService.getDescriptions();
- return functionList.get(searchText.toLocaleUpperCase()) !== undefined;
+ return this._descriptions.has(searchText.toUpperCase());
}
getFunctionInfo(searchText: string) {
- const functionList = this._functionService.getDescriptions();
- return functionList.get(searchText.toLocaleUpperCase());
+ const item = this._descriptions.get(searchText.toUpperCase());
+ if (!item) {
+ return;
+ }
+ return this._functionService.getDescription(getFunctionName(item, this._localeService));
}
getSearchListByName(searchText: string) {
- const searchList: ISearchItem[] = [];
const functionList = this._functionService.getDescriptions();
- const _searchText = searchText.toLocaleUpperCase().trim();
+ const _searchText = searchText.toUpperCase().trim();
+
+ const searchList: ISearchItem[] = [];
+
functionList.forEach((item) => {
const { functionName, abstract, functionType } = item;
// Exclude DefinedName
- if ((functionName.toLocaleUpperCase().indexOf(_searchText) > -1) && functionType !== FunctionType.DefinedName) {
+ if ((functionName.toUpperCase().indexOf(_searchText) > -1) && functionType !== FunctionType.DefinedName) {
searchList.push({ name: functionName, desc: abstract });
}
});
@@ -166,12 +220,14 @@ export class DescriptionService implements IDescriptionService, IDisposable {
}
getSearchListByNameFirstLetter(searchText: string) {
- const searchList: ISearchItemWithType[] = [];
const functionList = this._functionService.getDescriptions();
- const _searchText = searchText.toLocaleUpperCase().trim();
+ const _searchText = searchText.toUpperCase().trim();
+
+ const searchList: ISearchItemWithType[] = [];
+
functionList.forEach((item) => {
const { functionName, abstract, functionType } = item;
- if (functionName.toLocaleUpperCase().indexOf(_searchText) === 0) {
+ if (functionName.toUpperCase().indexOf(_searchText) === 0) {
searchList.push({ name: functionName, desc: abstract, functionType });
}
});
@@ -180,8 +236,10 @@ export class DescriptionService implements IDescriptionService, IDisposable {
}
getSearchListByType(type: number) {
- const searchList: ISearchItem[] = [];
const functionList = this._functionService.getDescriptions();
+
+ const searchList: ISearchItem[] = [];
+
functionList.forEach((item) => {
const { functionName, functionType, abstract } = item;
// Exclude DefinedName
@@ -193,95 +251,62 @@ export class DescriptionService implements IDescriptionService, IDisposable {
return searchList;
}
- registerDescriptions(description: IFunctionInfo[]): IDisposable {
- this._descriptions = this._descriptions.concat(description);
- this._registerDescriptions();
+ registerDescriptions(descriptions: IFunctionInfo[]): IDisposable {
+ const localeService = this._localeService;
+ const functionNames: string[] = [];
+
+ descriptions.forEach((item) => {
+ const functionName = getFunctionName(item, localeService).toUpperCase();
+ functionNames.push(functionName);
+ this._descriptions.set(functionName, item);
+ });
+
+ this._registerDescriptions(descriptions);
return toDisposable(() => {
- const functionNames = description.map((item) => item.functionName);
this.unregisterDescriptions(functionNames);
});
}
unregisterDescriptions(functionNames: string[]) {
- this._descriptions = this._descriptions.filter((item) => !functionNames.includes(item.functionName));
+ const removeFunctionNames: string[] = [];
- this._functionService.unregisterDescriptions(...functionNames);
+ functionNames.forEach((name) => {
+ const functionName = name.toUpperCase();
+ const item = this._descriptions.get(functionName);
+ if (!item) {
+ return;
+ }
+
+ removeFunctionNames.push(getFunctionName(item, this._localeService));
+ this._descriptions.delete(functionName);
+ });
+
+ this._functionService.unregisterDescriptions(...removeFunctionNames);
}
hasDescription(name: string) {
- return this._descriptions.some((item) => item.functionName === name);
+ return this._descriptions.has(name.toUpperCase());
}
hasDefinedNameDescription(name: string) {
- return this._descriptions.some((item) => item.functionName === name && item.functionType === FunctionType.DefinedName);
+ const item = this._descriptions.get(name.toUpperCase());
+ if (!item) {
+ return false;
+ }
+ return item.functionType === FunctionType.DefinedName;
}
isFormulaDefinedName(name: string) {
- const items = this._descriptions.filter((item) => item.functionName === name && item.functionType === FunctionType.DefinedName);
- if (items.length === 0) {
+ const item = this._descriptions.get(name.toUpperCase());
+ if (!item) {
return false;
}
- const token = items[0].description;
- return !isReferenceStrings(token);
- }
-
- private _initialize() {
- this._localeService.localeChanged$.subscribe(() => {
- this._registerDescriptions();
- });
-
- this._initDescription();
- this._registerDescriptions();
- }
-
- private _initDescription() {
- // TODO@Dushusir: Remove filtering after all formulas have been implemented
- const functions = [
- ...functionArray,
- ...functionCompatibility,
- ...functionCube,
- ...functionDatabase,
- ...functionDate,
- ...functionEngineering,
- ...functionFinancial,
- ...functionInformation,
- ...functionLogical,
- ...functionLookup,
- ...functionMath,
- ...functionMeta,
- ...functionStatistical,
- ...functionText,
- ...functionUniver,
- ...functionWeb,
- ].map((item) => item[1]) as IFunctionNames[];
-
- const filterFunctionList = FUNCTION_LIST.filter((item) => {
- return functions.includes(item.functionName as IFunctionNames);
- });
-
- const config = this._configService.getConfig<IUniverSheetsFormulaBaseConfig>(PLUGIN_CONFIG_KEY_BASE);
- this._descriptions = filterFunctionList.concat(config?.description ?? []);
- }
-
- private _registerDescriptions() {
- const localeService = this._localeService;
-
- const functionListLocale = this._descriptions.map((functionInfo) => ({
- functionName: getFunctionName(functionInfo, localeService),
- functionType: functionInfo.functionType,
- description: localeService.t(functionInfo.description),
- abstract: localeService.t(functionInfo.abstract),
- functionParameter: functionInfo.functionParameter.map((item) => ({
- name: localeService.t(item.name),
- detail: localeService.t(item.detail),
- example: item.example,
- require: item.require,
- repeat: item.repeat,
- })),
- }));
+ if (item.functionType !== FunctionType.DefinedName) {
+ return false;
+ }
- this._functionService.registerDescriptions(...functionListLocale);
+ return !isReferenceStrings(item.description);
}
}
diff --git a/packages/sheets-formula/src/services/register-function.service.ts b/packages/sheets-formula/src/services/register-function.service.ts
index 8e7e3afd8c..9e170559cd 100644
--- a/packages/sheets-formula/src/services/register-function.service.ts
+++ b/packages/sheets-formula/src/services/register-function.service.ts
@@ -154,21 +154,18 @@ export class RegisterFunctionService extends Disposable implements IRegisterFunc
}
const disposables = new DisposableCollection();
- if (description) {
- disposables.add(this._descriptionService.registerDescriptions(description));
- } else {
- const descriptionList: IFunctionInfo[] = calculate.map(([_func, functionName, functionIntroduction]) => {
- return {
- functionName,
- functionType: FunctionType.User,
- description: '',
- abstract: functionIntroduction || '',
- functionParameter: [],
- };
- });
-
- disposables.add(this._functionService.registerDescriptions(...descriptionList));
- }
+
+ const descriptions: IFunctionInfo[] = description ?? calculate.map(([_func, functionName, functionIntroduction]) => {
+ return {
+ functionName,
+ functionType: FunctionType.User,
+ description: '',
+ abstract: functionIntroduction || '',
+ functionParameter: [],
+ };
+ });
+
+ disposables.add(this._descriptionService.registerDescriptions(descriptions));
// calculation
disposables.add(this._registerLocalExecutors(calculate));
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
index 479a6443c2..29111d6bb3 100644
--- a/packages/sheets-ui/src/commands/operations/sidebar-defined-name.operation.ts
+++ b/packages/sheets-ui/src/commands/operations/sidebar-defined-name.operation.ts
@@ -47,6 +47,10 @@ export const SidebarDefinedNameOperation: ICommand = {
onClose: () => {
},
width: 333,
+ bodyStyle: {
+ height: '100%',
+ overflow: 'hidden',
+ },
});
break;
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
index 5d9777bb17..4e2b572c8c 100644
--- a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
@@ -28,8 +28,8 @@ import {
SetWorksheetShowCommand,
SheetsSelectionsService,
} from '@univerjs/sheets';
-import { useDependency } from '@univerjs/ui';
-import { useEffect, useState } from 'react';
+import { useDependency, useVirtualList } from '@univerjs/ui';
+import { useEffect, useRef, useState } from 'react';
import { DefinedNameInput } from './DefinedNameInput';
export const DefinedNameContainer = () => {
@@ -57,6 +57,18 @@ export const DefinedNameContainer = () => {
const [editorKey, setEditorKey] = useState<Nullable<string>>(null);
const [deleteConformKey, setDeleteConformKey] = useState<Nullable<string>>();
+ const listContainerRef = useRef<HTMLDivElement>(undefined!);
+ const [virtualDefinedNames, virtualActions] = useVirtualList(definedNames, {
+ containerTarget: listContainerRef,
+ itemHeight: (index, item) => {
+ if (item.id === editorKey) {
+ return 240;
+ }
+ return 72;
+ },
+ overscan: 6,
+ });
+
useEffect(() => {
setDefinedNames(getDefinedNameMap());
@@ -181,144 +193,150 @@ export const DefinedNameContainer = () => {
return (
<div
data-u-comp="defined-name-container"
- className="univer-relative univer-box-border univer-w-full"
+ className="univer-relative univer-box-border univer-flex univer-h-full univer-w-full univer-flex-col"
>
- <div className={clsx('univer-w-full univer-overflow-hidden univer-overflow-y-auto', scrollbarClassName)}>
- <div key="insertDefinedName" className="univer-mb-4">
- <Button
- className={clsx(
- 'univer-w-full',
- {
- 'univer-hidden': editState,
- }
- )}
- onClick={openInsertCloseKeyEditor}
- >
- <IncreaseIcon />
- <span className="univer-ml-1">{localeService.t('definedName.addButton')}</span>
- </Button>
- {editState && (
- <DefinedNameInput
- confirm={insertConfirm}
- cancel={closeInput}
- state={editState}
- inputId="insertDefinedName"
- name={getInsertDefinedName()}
- formulaOrRefString={getInertFormulaOrRefString()}
- />
+ <div key="insertDefinedName" className="univer-mb-4">
+ <Button
+ className={clsx(
+ 'univer-w-full',
+ {
+ 'univer-hidden': editState,
+ }
)}
- </div>
+ onClick={openInsertCloseKeyEditor}
+ >
+ <IncreaseIcon />
+ <span className="univer-ml-1">{localeService.t('definedName.addButton')}</span>
+ </Button>
+ {editState && (
+ <DefinedNameInput
+ confirm={insertConfirm}
+ cancel={closeInput}
+ state={editState}
+ inputId="insertDefinedName"
+ name={getInsertDefinedName()}
+ formulaOrRefString={getInertFormulaOrRefString()}
+ />
+ )}
+ </div>
- {definedNames.map((definedName, index) => {
- return (
- <div
- key={index}
- className={`
- univer-relative univer-w-full univer-divide-x-0 univer-divide-y univer-divide-solid
- univer-divide-gray-200
- dark:!univer-divide-gray-600
- `}
- >
+ <div
+ ref={listContainerRef}
+ className={clsx('univer-min-h-0 univer-flex-1 univer-overflow-y-auto', scrollbarClassName)}
+ {...virtualActions.containerProps}
+ >
+ <div style={virtualActions.wrapperStyle}>
+ {virtualDefinedNames.map(({ data: definedName, index }) => {
+ return (
<div
- className={clsx(`
- univer-group univer-relative univer-flex univer-w-full univer-cursor-default
- univer-select-none univer-items-center univer-justify-between univer-rounded-md
- univer-p-2
- hover:univer-bg-gray-50
- dark:hover:!univer-bg-gray-700
- `, {
- 'univer-hidden': definedName.id === editorKey,
- })}
- onClick={() => { focusDefinedName(definedName); }}
+ key={index}
+ className={`
+ univer-relative univer-w-full univer-divide-x-0 univer-divide-y univer-divide-solid
+ univer-divide-gray-200
+ dark:!univer-divide-gray-600
+ `}
>
- <div title={definedName.comment}>
- <div
- className={`
- univer-my-1 univer-max-h-[100px] univer-max-w-[190px] univer-truncate
- univer-text-sm univer-font-medium univer-text-gray-900
- dark:!univer-text-white
- `}
- >
- {definedName.name}
- <span className="univer-text-xxs univer-ml-1 univer-text-gray-400">
- {(definedName.localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME || definedName.localSheetId == null) ? '' : getSheetNameBySheetId(definedName.localSheetId)}
- </span>
- </div>
- <div
- className={`
- univer-my-1 univer-max-h-[100px] univer-w-full univer-max-w-[190px]
- univer-truncate univer-text-xs univer-text-gray-500
- `}
- title={definedName.formulaOrRefString}
- >
- {definedName.formulaOrRefString}
- </div>
- </div>
<div
- className={`
- univer-absolute univer-right-5 univer-top-1/2 univer-hidden
- -univer-translate-y-1/2 univer-cursor-pointer univer-items-center
- univer-justify-end univer-gap-7 univer-text-xs univer-text-primary-600
- group-hover:univer-flex
- dark:hover:!univer-bg-gray-600
- `}
+ className={clsx(`
+ univer-group univer-relative univer-flex univer-w-full univer-cursor-default
+ univer-select-none univer-items-center univer-justify-between univer-rounded-md
+ univer-p-2
+ hover:univer-bg-gray-50
+ dark:hover:!univer-bg-gray-700
+ `, {
+ 'univer-hidden': definedName.id === editorKey,
+ })}
+ onClick={() => { focusDefinedName(definedName); }}
>
- <Tooltip title={localeService.t('definedName.updateButton')} placement="top">
- <a
+ <div title={definedName.comment}>
+ <div
className={`
- univer-rounded univer-p-1
- hover:univer-bg-gray-100
+ univer-my-1 univer-max-h-[100px] univer-max-w-[190px] univer-truncate
+ univer-text-sm univer-font-medium univer-text-gray-900
+ dark:!univer-text-white
`}
- onClick={(e) => {
- e.stopPropagation();
- closeInsertOpenKeyEditor(definedName.id);
- }}
>
- <PenIcon />
- </a>
- </Tooltip>
- <Tooltip title={localeService.t('definedName.deleteButton')} placement="top">
- <a
+ {definedName.name}
+ <span className="univer-text-xxs univer-ml-1 univer-text-gray-400">
+ {(definedName.localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME || definedName.localSheetId == null) ? '' : getSheetNameBySheetId(definedName.localSheetId)}
+ </span>
+ </div>
+ <div
className={`
- univer-rounded univer-p-1 univer-text-red-600
- hover:univer-bg-gray-100
+ univer-my-1 univer-max-h-[100px] univer-w-full univer-max-w-[190px]
+ univer-truncate univer-text-xs univer-text-gray-500
`}
- onClick={(e) => {
- e.stopPropagation();
- deleteDefinedName(definedName.id);
- }}
+ title={definedName.formulaOrRefString}
>
- <DeleteIcon />
- </a>
- </Tooltip>
+ {definedName.formulaOrRefString}
+ </div>
+ </div>
+ <div
+ className={`
+ univer-absolute univer-right-5 univer-top-1/2 univer-hidden
+ -univer-translate-y-1/2 univer-cursor-pointer univer-items-center
+ univer-justify-end univer-gap-7 univer-text-xs univer-text-primary-600
+ group-hover:univer-flex
+ dark:hover:!univer-bg-gray-600
+ `}
+ >
+ <Tooltip title={localeService.t('definedName.updateButton')} placement="top">
+ <a
+ className={`
+ univer-rounded univer-p-1
+ hover:univer-bg-gray-100
+ `}
+ onClick={(e) => {
+ e.stopPropagation();
+ closeInsertOpenKeyEditor(definedName.id);
+ }}
+ >
+ <PenIcon />
+ </a>
+ </Tooltip>
+ <Tooltip title={localeService.t('definedName.deleteButton')} placement="top">
+ <a
+ className={`
+ univer-rounded univer-p-1 univer-text-red-600
+ hover:univer-bg-gray-100
+ `}
+ onClick={(e) => {
+ e.stopPropagation();
+ deleteDefinedName(definedName.id);
+ }}
+ >
+ <DeleteIcon />
+ </a>
+ </Tooltip>
+ </div>
+
</div>
+ <Confirm
+ visible={deleteConformKey === definedName.id}
+ onClose={handleDeleteClose}
+ onConfirm={() => { handleDeleteConfirm(definedName.id); }}
+ >
+ {localeService.t('definedName.deleteConfirmText')}
+ </Confirm>
+
+ {definedName.id === editorKey && (
+ <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>
-
- <Confirm
- visible={deleteConformKey === definedName.id}
- onClose={handleDeleteClose}
- onConfirm={() => { handleDeleteConfirm(definedName.id); }}
- >
- {localeService.t('definedName.deleteConfirmText')}
- </Confirm>
-
- {definedName.id === editorKey && (
- <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>
</div>
);
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx
index 9a6d84b3a5..4848f9491f 100644
--- a/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx
+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx
@@ -15,14 +15,13 @@
*/
import type { Workbook } from '@univerjs/core';
-
import type { IDefinedNamesServiceParam } from '@univerjs/engine-formula';
import { ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
import { borderBottomClassName, clsx, scrollbarClassName } from '@univerjs/design';
import { IDefinedNamesService } from '@univerjs/engine-formula';
import { SetWorksheetShowCommand } from '@univerjs/sheets';
-import { ISidebarService, useDependency } from '@univerjs/ui';
-import { useEffect, useMemo, useState } from 'react';
+import { ISidebarService, useDependency, useVirtualList } from '@univerjs/ui';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { SidebarDefinedNameOperation } from '../../commands/operations/sidebar-defined-name.operation';
import { DEFINED_NAME_CONTAINER } from './component-name';
@@ -78,6 +77,13 @@ export function DefinedNameOverlay({ search, isInputEvent }: { search: string; i
: definedNames;
}, [search, isInputEvent, definedNames]);
+ const listContainerRef = useRef<HTMLDivElement>(undefined!);
+ const [virtualDefinedNames, virtualActions] = useVirtualList(filteredDefinedNames, {
+ containerTarget: listContainerRef,
+ itemHeight: 30,
+ overscan: 6,
+ });
+
const openSlider = () => {
commandService.executeCommand(SidebarDefinedNameOperation.id, { value: 'open' });
};
@@ -100,50 +106,55 @@ export function DefinedNameOverlay({ search, isInputEvent }: { search: string; i
return (
<div className="univer-w-[300px]">
- <ul
- className={clsx('univer-m-0 univer-max-h-[360px] univer-list-none univer-overflow-y-auto univer-p-0', scrollbarClassName)}
+ <div
+ ref={listContainerRef}
+ className={clsx('univer-max-h-[360px] univer-min-h-0 univer-overflow-y-auto', scrollbarClassName, {
+ 'univer-min-h-[30px]': filteredDefinedNames.length > 0,
+ })}
+ {...virtualActions.containerProps}
>
- {filteredDefinedNames.map((definedName, index) => {
- return (
- <li
- key={index}
- className={`
- univer-cursor-pointer univer-px-2 univer-transition-colors univer-duration-200
- hover:univer-bg-gray-100
- dark:hover:!univer-bg-gray-600
- `}
- onClick={() => { focusDefinedName(definedName); }}
- >
- <div
- className={clsx(`
- univer-flex univer-items-center univer-justify-between univer-gap-2 univer-py-1
- `, borderBottomClassName)}
+ <div style={virtualActions.wrapperStyle}>
+ {virtualDefinedNames.map(({ data: definedName, index }) => {
+ return (
+ <li
+ key={index}
+ className={`
+ univer-cursor-pointer univer-px-2 univer-transition-colors univer-duration-200
+ hover:univer-bg-gray-100
+ dark:hover:!univer-bg-gray-600
+ `}
+ onClick={() => { focusDefinedName(definedName); }}
>
<div
- className={`
- univer-w-[50%] univer-flex-shrink-0 univer-truncate univer-text-sm
- univer-text-gray-600
- dark:!univer-text-gray-200
- `}
- title={definedName.name}
+ className={clsx(`
+ univer-flex univer-items-center univer-justify-between univer-gap-2 univer-py-1
+ `, borderBottomClassName)}
>
- {definedName.name}
+ <div
+ className={`
+ univer-w-[50%] univer-flex-shrink-0 univer-truncate univer-text-sm
+ univer-text-gray-600
+ dark:!univer-text-gray-200
+ `}
+ title={definedName.name}
+ >
+ {definedName.name}
+ </div>
+ <div
+ className={`
+ univer-w-[50%] univer-flex-shrink-0 univer-truncate univer-text-xs
+ univer-text-gray-400
+ `}
+ title={definedName.formulaOrRefString}
+ >
+ {definedName.formulaOrRefString}
+ </div>
</div>
- <div
- className={`
- univer-w-[50%] univer-flex-shrink-0 univer-truncate univer-text-xs
- univer-text-gray-400
- `}
- title={definedName.formulaOrRefString}
- >
- {definedName.formulaOrRefString}
- </div>
- </div>
- </li>
- );
- })}
- </ul>
-
+ </li>
+ );
+ })}
+ </div>
+ </div>
<div
className={`
univer-cursor-pointer univer-p-2 univer-transition-colors univer-duration-200
diff --git a/packages/sheets/src/commands/commands/clear-selection-all.command.ts b/packages/sheets/src/commands/commands/clear-selection-all.command.ts
index df84566b3e..259ea07ca7 100644
--- a/packages/sheets/src/commands/commands/clear-selection-all.command.ts
+++ b/packages/sheets/src/commands/commands/clear-selection-all.command.ts
@@ -14,21 +14,14 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand, IMutationInfo, IRange, Workbook } from '@univerjs/core';
+import type { ICommand, IMutationInfo, IRange } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '../mutations/set-range-values.mutation';
-
-import {
- CommandType,
- ICommandService,
- IUndoRedoService,
- IUniverInstanceService,
- sequenceExecute,
- UniverInstanceType,
-} from '@univerjs/core';
+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecute } from '@univerjs/core';
import { generateNullCell, getVisibleRanges } from '../../basics/utils';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
+import { getSheetCommandTarget } from './utils/target-util';
export interface IClearSelectionAllCommandParams {
unitId?: string;
@@ -39,28 +32,22 @@ export interface IClearSelectionAllCommandParams {
/**
* The command to clear all in current selected ranges.
*/
-export const ClearSelectionAllCommand: ICommand = {
+export const ClearSelectionAllCommand: ICommand<IClearSelectionAllCommandParams> = {
id: 'sheet.command.clear-selection-all',
type: CommandType.COMMAND,
- handler: (accessor: IAccessor, params: IClearSelectionAllCommandParams) => {
- const univerInstanceService = accessor.get(IUniverInstanceService);
- const commandService = accessor.get(ICommandService);
+ handler: (accessor, params) => {
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), { unitId: params?.unitId, subUnitId: params?.subUnitId });
+ if (!target) return false;
+
const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const { unitId, subUnitId } = target;
+ const selections = params?.ranges || selectionManagerService.getCurrentSelections()?.map((s) => s.range);
+ if (!selections?.length) return false;
+
+ const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- if (!workbook) return false;
-
- const unitId = params?.unitId || workbook.getUnitId();
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) return false;
-
- const subUnitId = params?.subUnitId || worksheet.getSheetId();
- const selections = params?.ranges || selectionManagerService.getCurrentSelections()?.map((s) => s.range);
- if (!selections?.length) {
- return false;
- }
const visibleRanges = getVisibleRanges(selections, accessor, unitId, subUnitId);
const sequenceExecuteList: IMutationInfo[] = [];
@@ -86,7 +73,7 @@ export const ClearSelectionAllCommand: ICommand = {
params: undoClearMutationParams,
});
- const intercepted = sheetInterceptorService.onCommandExecute({ id: ClearSelectionAllCommand.id });
+ const intercepted = sheetInterceptorService.onCommandExecute({ id: ClearSelectionAllCommand.id, params });
sequenceExecuteList.push(...intercepted.redos);
sequenceExecuteUndoList.unshift(...intercepted.undos);
diff --git a/packages/sheets/src/commands/commands/clear-selection-content.command.ts b/packages/sheets/src/commands/commands/clear-selection-content.command.ts
index ce82bd5ec5..82777143b6 100644
--- a/packages/sheets/src/commands/commands/clear-selection-content.command.ts
+++ b/packages/sheets/src/commands/commands/clear-selection-content.command.ts
@@ -14,21 +14,14 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand, IRange, Workbook } from '@univerjs/core';
-
+import type { ICommand, IRange } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '../mutations/set-range-values.mutation';
-import {
- CommandType,
- ICommandService,
- IUndoRedoService,
- IUniverInstanceService,
- sequenceExecute,
- UniverInstanceType,
-} from '@univerjs/core';
+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecute } from '@univerjs/core';
import { generateNullCellValue, getVisibleRanges } from '../../basics/utils';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
+import { getSheetCommandTarget } from './utils/target-util';
export interface IClearSelectionContentCommandParams {
unitId?: string;
@@ -39,30 +32,24 @@ export interface IClearSelectionContentCommandParams {
/**
* The command to clear content in current selected ranges.
*/
-export const ClearSelectionContentCommand: ICommand = {
+export const ClearSelectionContentCommand: ICommand<IClearSelectionContentCommandParams> = {
id: 'sheet.command.clear-selection-content',
type: CommandType.COMMAND,
- handler: (accessor: IAccessor, params: IClearSelectionContentCommandParams) => {
- const univerInstanceService = accessor.get(IUniverInstanceService);
- const commandService = accessor.get(ICommandService);
+ handler: (accessor, params) => {
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), { unitId: params?.unitId, subUnitId: params?.subUnitId });
+ if (!target) return false;
+
const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const { unitId, subUnitId } = target;
+ const ranges = params?.ranges || selectionManagerService.getCurrentSelections()?.map((s) => s.range);
+ if (!ranges?.length) return false;
+
+ const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- if (!workbook) return false;
-
- const unitId = params?.unitId || workbook.getUnitId();
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) return false;
-
- const subUnitId = params?.subUnitId || worksheet.getSheetId();
- const ranges = params?.ranges || selectionManagerService.getCurrentSelections()?.map((s) => s.range);
- if (!ranges?.length) {
- return false;
- }
const visibleRanges = getVisibleRanges(ranges, accessor, unitId, subUnitId);
const clearMutationParams: ISetRangeValuesMutationParams = {
@@ -75,7 +62,7 @@ export const ClearSelectionContentCommand: ICommand = {
clearMutationParams
);
- const intercepted = sheetInterceptorService.onCommandExecute({ id: ClearSelectionContentCommand.id });
+ const intercepted = sheetInterceptorService.onCommandExecute({ id: ClearSelectionContentCommand.id, params });
const redos = [{ id: SetRangeValuesMutation.id, params: clearMutationParams }, ...intercepted.redos];
const undos = [...intercepted.undos, { id: SetRangeValuesMutation.id, params: undoClearMutationParams }];
diff --git a/packages/sheets/src/commands/commands/clear-selection-format.command.ts b/packages/sheets/src/commands/commands/clear-selection-format.command.ts
index d8e102828f..27e227eab1 100644
--- a/packages/sheets/src/commands/commands/clear-selection-format.command.ts
+++ b/packages/sheets/src/commands/commands/clear-selection-format.command.ts
@@ -14,21 +14,14 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand, IMutationInfo, IRange, Workbook } from '@univerjs/core';
+import type { ICommand, IMutationInfo, IRange } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '../mutations/set-range-values.mutation';
-
-import {
- CommandType,
- ICommandService,
- IUndoRedoService,
- IUniverInstanceService,
- sequenceExecute,
- UniverInstanceType,
-} from '@univerjs/core';
+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecute } from '@univerjs/core';
import { generateNullCellStyle, getVisibleRanges } from '../../basics/utils';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
+import { getSheetCommandTarget } from './utils/target-util';
export interface IClearSelectionFormatCommandParams {
unitId?: string;
@@ -39,30 +32,24 @@ export interface IClearSelectionFormatCommandParams {
/**
* The command to clear content in current selected ranges.
*/
-export const ClearSelectionFormatCommand: ICommand = {
+export const ClearSelectionFormatCommand: ICommand<IClearSelectionFormatCommandParams> = {
id: 'sheet.command.clear-selection-format',
type: CommandType.COMMAND,
- handler: (accessor: IAccessor, params: IClearSelectionFormatCommandParams) => {
- const univerInstanceService = accessor.get(IUniverInstanceService);
- const commandService = accessor.get(ICommandService);
+ handler: (accessor, params) => {
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), { unitId: params?.unitId, subUnitId: params?.subUnitId });
+ if (!target) return false;
+
const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const { unitId, subUnitId } = target;
+ const ranges = params?.ranges || selectionManagerService.getCurrentSelections()?.map((s) => s.range);
+ if (!ranges?.length) return false;
+
+ const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- if (!workbook) return false;
-
- const unitId = params?.unitId || workbook.getUnitId();
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) return false;
-
- const subUnitId = params?.subUnitId || worksheet.getSheetId();
- const ranges = params?.ranges || selectionManagerService.getCurrentSelections()?.map((s) => s.range);
- if (!ranges?.length) {
- return false;
- }
const visibleRanges = getVisibleRanges(ranges, accessor, unitId, subUnitId);
const sequenceExecuteList: IMutationInfo[] = [];
@@ -88,7 +75,7 @@ export const ClearSelectionFormatCommand: ICommand = {
params: undoClearMutationParams,
});
- const intercepted = sheetInterceptorService.onCommandExecute({ id: ClearSelectionFormatCommand.id });
+ const intercepted = sheetInterceptorService.onCommandExecute({ id: ClearSelectionFormatCommand.id, params });
sequenceExecuteList.push(...intercepted.redos);
sequenceExecuteUndoList.unshift(...intercepted.undos);
diff --git a/packages/sheets/src/commands/commands/set-defined-name.command.ts b/packages/sheets/src/commands/commands/set-defined-name.command.ts
index dd08c86e30..dd1558d174 100644
--- a/packages/sheets/src/commands/commands/set-defined-name.command.ts
+++ b/packages/sheets/src/commands/commands/set-defined-name.command.ts
@@ -16,21 +16,14 @@
import type { IAccessor, ICommand } from '@univerjs/core';
import type { ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
-import {
- CommandType,
- ICommandService,
- IUndoRedoService,
- sequenceExecute,
-} from '@univerjs/core';
+import { CommandType, ICommandService, IUndoRedoService, sequenceExecute } from '@univerjs/core';
import { RemoveDefinedNameMutation, SetDefinedNameMutation, SetDefinedNameMutationFactory } from '@univerjs/engine-formula';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
/**
- * The command to update defined name
- *
+ * The command to update defined name.
* 1. The old defined name can be obtained through IDefinedNamesService, and does not need to be passed in from the outside, making the command input more concise
-
- 2. Unlike InsertDefinedNameCommand, the old defined name needs to be deleted here at the same time. Because the command interception in UpdateDefinedNameController will add SetDefinedNameMutation or RemoveDefinedNameMutation, it results in that in DefinedNameController, only mutations can be listened to to update Function Description (commands cannot be listened to), so it is necessary to ensure that each mutation triggered by the command has completed all work.
+ * 2. Unlike InsertDefinedNameCommand, the old defined name needs to be deleted here at the same time. Because the command interception in UpdateDefinedNameController will add SetDefinedNameMutation or RemoveDefinedNameMutation, it results in that in DefinedNameController, only mutations can be listened to to update Function Description (commands cannot be listened to), so it is necessary to ensure that each mutation triggered by the command has completed all work.
*/
export const SetDefinedNameCommand: ICommand = {
id: 'sheet.command.set-defined-name',
@@ -45,13 +38,13 @@ export const SetDefinedNameCommand: ICommand = {
const newDefinedNameMutationParams: ISetDefinedNameMutationParam = {
...params,
};
- const oldDefinedNameMutationParams: ISetDefinedNameMutationParam = SetDefinedNameMutationFactory(accessor, params);
+ const oldDefinedNameMutationParams: ISetDefinedNameMutationParam | null = SetDefinedNameMutationFactory(accessor, params);
const interceptorCommands = sheetInterceptorService.onCommandExecute({ id: SetDefinedNameCommand.id, params });
const redos = [
...(interceptorCommands.preRedos ?? []),
- { id: RemoveDefinedNameMutation.id, params: oldDefinedNameMutationParams },
+ ...(oldDefinedNameMutationParams ? [{ id: RemoveDefinedNameMutation.id, params: oldDefinedNameMutationParams }] : []),
{ id: SetDefinedNameMutation.id, params: newDefinedNameMutationParams },
...interceptorCommands.redos,
];
@@ -59,7 +52,7 @@ export const SetDefinedNameCommand: ICommand = {
const undos = [
...(interceptorCommands.preUndos ?? []),
{ id: RemoveDefinedNameMutation.id, params: newDefinedNameMutationParams },
- { id: SetDefinedNameMutation.id, params: oldDefinedNameMutationParams },
+ ...(oldDefinedNameMutationParams ? [{ id: SetDefinedNameMutation.id, params: oldDefinedNameMutationParams }] : []),
...interceptorCommands.undos,
];
diff --git a/packages/sheets/src/commands/operations/set-worksheet-active.operation.ts b/packages/sheets/src/commands/operations/set-worksheet-active.operation.ts
index 34bd93692f..4d03cfb4e0 100644
--- a/packages/sheets/src/commands/operations/set-worksheet-active.operation.ts
+++ b/packages/sheets/src/commands/operations/set-worksheet-active.operation.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IOperation } from '@univerjs/core';
-import { CommandType, IUniverInstanceService } from '@univerjs/core';
+import type { IOperation, Workbook } from '@univerjs/core';
+import { CommandType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
export interface ISetWorksheetActiveOperationParams {
unitId: string;
@@ -26,11 +26,11 @@ export const SetWorksheetActiveOperation: IOperation<ISetWorksheetActiveOperatio
id: 'sheet.operation.set-worksheet-active',
type: CommandType.OPERATION,
handler: (accessor, params) => {
- const workbook = accessor.get(IUniverInstanceService).getUniverSheetInstance(params.unitId);
-
+ const workbook = accessor.get(IUniverInstanceService).getUnit<Workbook>(params.unitId, UniverInstanceType.UNIVER_SHEET);
if (!workbook) return false;
const worksheets = workbook.getWorksheets();
+
for (const [, worksheet] of worksheets) {
if (worksheet.getSheetId() === params.subUnitId) {
workbook.setActiveSheet(worksheet);
diff --git a/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts b/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts
index 3a72f029f1..47a0270f21 100644
--- a/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts
+++ b/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts
@@ -211,7 +211,7 @@ export class SheetPermissionCheckController extends Disposable {
// clear all/content/format
case ClearSelectionAllCommand.id:
- params = commandInfo.params as IClearSelectionAllCommandParams;
+ params = commandInfo.params as IClearSelectionAllCommandParams | undefined;
permission = this.permissionCheckWithRanges(
{
@@ -219,14 +219,14 @@ export class SheetPermissionCheckController extends Disposable {
worksheetTypes: [WorksheetSetCellValuePermission, WorksheetSetCellStylePermission, WorksheetEditPermission],
rangeTypes: [RangeProtectionPermissionEditPoint],
},
- params.ranges,
- params.unitId,
- params.subUnitId
+ params?.ranges,
+ params?.unitId,
+ params?.subUnitId
);
errorMsg = this._localeService.t('permission.dialog.editErr');
break;
case ClearSelectionContentCommand.id:
- params = commandInfo.params as IClearSelectionContentCommandParams;
+ params = commandInfo.params as IClearSelectionContentCommandParams | undefined;
permission = this.permissionCheckWithRanges(
{
@@ -234,14 +234,14 @@ export class SheetPermissionCheckController extends Disposable {
worksheetTypes: [WorksheetSetCellValuePermission, WorksheetEditPermission],
rangeTypes: [RangeProtectionPermissionEditPoint],
},
- params.ranges,
- params.unitId,
- params.subUnitId
+ params?.ranges,
+ params?.unitId,
+ params?.subUnitId
);
errorMsg = this._localeService.t('permission.dialog.editErr');
break;
case ClearSelectionFormatCommand.id:
- params = commandInfo.params as IClearSelectionFormatCommandParams;
+ params = commandInfo.params as IClearSelectionFormatCommandParams | undefined;
permission = this.permissionCheckWithRanges(
{
@@ -249,9 +249,9 @@ export class SheetPermissionCheckController extends Disposable {
worksheetTypes: [WorksheetSetCellStylePermission, WorksheetEditPermission],
rangeTypes: [RangeProtectionPermissionEditPoint],
},
- params.ranges,
- params.unitId,
- params.subUnitId
+ params?.ranges,
+ params?.unitId,
+ params?.subUnitId
);
errorMsg = this._localeService.t('permission.dialog.setStyleErr');
break;