Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(facade): add Facade Worksheet row column API (#3163)
Dushusir7d903d71439f
diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.tsindex 325debb58d..aafc990014 100644--- a/packages/facade/src/apis/__tests__/create-test-bed.ts+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts@@ -30,7 +30,7 @@ import {Univer,UniverInstanceType,} from '@univerjs/core';-import { ActiveDirtyManagerService, AstRootNodeFactory, AstTreeBuilder, CalculateController, CalculateFormulaService, DefinedNamesService, DependencyManagerService, FeatureCalculationManagerService, FormulaCurrentConfigService, FormulaDataModel, FormulaDependencyGenerator, FormulaRuntimeService, FunctionNodeFactory, FunctionService, IActiveDirtyManagerService, IDefinedNamesService, IDependencyManagerService, IFeatureCalculationManagerService, IFormulaCurrentConfigService, IFormulaRuntimeService, IFunctionService, Interpreter, IOtherFormulaManagerService, ISuperTableService, LambdaNodeFactory, LambdaParameterNodeFactory, Lexer, LexerTreeBuilder, OperatorNodeFactory, OtherFormulaManagerService, PrefixNodeFactory, ReferenceNodeFactory, SuffixNodeFactory, SuperTableService, UnionNodeFactory, ValueNodeFactory } from '@univerjs/engine-formula';+import { ActiveDirtyManagerService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';import { ISocketService, WebSocketService } from '@univerjs/network';import {RangeProtectionRuleModel,@@ -145,7 +145,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:},]);- // injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([ISocketService, { useClass: WebSocketService }]);injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);injector.add([IRenderManagerService, { useClass: RenderManagerService }]);@@ -155,7 +155,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:injector.add([IPlatformService, { useClass: PlatformService }]);injector.add([SheetSkeletonManagerService]);injector.add([FormulaDataModel]);- // injector.add([LexerTreeBuilder]);+ injector.add([LexerTreeBuilder]);injector.add([RefRangeService]);injector.add([WorksheetPermissionService]);injector.add([WorkbookPermissionService]);@@ -163,8 +163,6 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:injector.add([RangeProtectionRuleModel]);injector.add([WorksheetProtectionRuleModel]);- registerFormulaDependencies(injector);-const renderManagerService = injector.get(IRenderManagerService);renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService] as Dependency);renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetRenderController] as Dependency);@@ -236,34 +234,3 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:injector,};}--function registerFormulaDependencies(injector: Injector) {- injector.add([CalculateFormulaService]);- injector.add([Lexer]);- injector.add([LexerTreeBuilder]);-- injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);- injector.add([IDependencyManagerService, { useClass: DependencyManagerService }]);- injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);- injector.add([IFunctionService, { useClass: FunctionService }]);- injector.add([IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([ISuperTableService, { useClass: SuperTableService }]);- injector.add([CalculateController]);-- injector.add([IFeatureCalculationManagerService, { useClass: FeatureCalculationManagerService }]);- injector.add([FormulaDependencyGenerator]);- injector.add([Interpreter]);- injector.add([AstTreeBuilder]);-- injector.add([AstRootNodeFactory]);- injector.add([FunctionNodeFactory]);- injector.add([LambdaNodeFactory]);- injector.add([LambdaParameterNodeFactory]);- injector.add([OperatorNodeFactory]);- injector.add([PrefixNodeFactory]);- injector.add([ReferenceNodeFactory]);- injector.add([SuffixNodeFactory]);- injector.add([UnionNodeFactory]);- injector.add([ValueNodeFactory]);-}diff --git a/packages/facade/src/apis/sheets/__tests__/create-formula-test-bed.ts b/packages/facade/src/apis/sheets/__tests__/create-formula-test-bed.tsnew file mode 100644index 0000000000..9e18c4869f--- /dev/null+++ b/packages/facade/src/apis/sheets/__tests__/create-formula-test-bed.ts@@ -0,0 +1,182 @@+/**+ * 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 { Dependency, IWorkbookData, Workbook } from '@univerjs/core';+import {+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { ActiveDirtyManagerService, AstRootNodeFactory, AstTreeBuilder, CalculateController, CalculateFormulaService, DefinedNamesService, DependencyManagerService, FeatureCalculationManagerService, FormulaCurrentConfigService, FormulaDataModel, FormulaDependencyGenerator, FormulaRuntimeService, FunctionNodeFactory, FunctionService, IActiveDirtyManagerService, IDefinedNamesService, IDependencyManagerService, IFeatureCalculationManagerService, IFormulaCurrentConfigService, IFormulaRuntimeService, IFunctionService, Interpreter, IOtherFormulaManagerService, ISuperTableService, LambdaNodeFactory, LambdaParameterNodeFactory, Lexer, LexerTreeBuilder, OperatorNodeFactory, OtherFormulaManagerService, PrefixNodeFactory, ReferenceNodeFactory, SuffixNodeFactory, SuperTableService, UnionNodeFactory, ValueNodeFactory } from '@univerjs/engine-formula';+import { ISocketService, WebSocketService } from '@univerjs/network';+import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';+import {+ DescriptionService,+ IDescriptionService,+ IRegisterFunctionService,+ RegisterFunctionService,+} from '@univerjs/sheets-formula';+import enUS from '@univerjs/sheets-formula/locale/en-US';+import zhCN from '@univerjs/sheets-formula/locale/zh-CN';++import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { FUniver } from '../../facade';++function getTestWorkbookDataDemo(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'sheet1',+ cellData: {+ 0: {+ 3: {+ f: '=SUM(A1)',+ si: '3e4r5t',+ },+ },+ 1: {+ 3: {+ f: '=SUM(A2)',+ si: 'OSPtzm',+ },+ },+ 2: {+ 3: {+ si: 'OSPtzm',+ },+ },+ 3: {+ 3: {+ si: 'OSPtzm',+ },+ },+ },+ },+ },+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: [],+ styles: {},+ };+}++export interface ITestBed {+ univer: Univer;+ get: Injector['get'];+ sheet: Workbook;+ univerAPI: FUniver;+}++export function createFormulaTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]): ITestBed {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override pluginName = 'test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const injector = this._injector;+ injector.add([SheetsSelectionsService]);+ injector.add([SheetInterceptorService]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([ISocketService, { useClass: WebSocketService }]);++ registerFormulaDependencies(injector);++ dependencies?.forEach((d) => injector.add(d));+ }+ }++ injector.get(LocaleService).load({ zhCN, enUS });++ univer.registerPlugin(TestPlugin);+ const sheet = univer.createUniverSheet(workbookData || getTestWorkbookDataDemo());++ const univerInstanceService = injector.get(IUniverInstanceService);+ univerInstanceService.focusUnit('test');+ const logService = injector.get(ILogService);++ logService.setLogLevel(LogLevel.SILENT); // change this to `LogLevel.VERBOSE` to debug tests via logs++ const univerAPI = FUniver.newAPI(injector);++ return {+ univer,+ get: injector.get.bind(injector),+ sheet,+ univerAPI,+ };+}++function registerFormulaDependencies(injector: Injector) {+ injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);+ injector.add([+ IDescriptionService,+ {+ useFactory: () => injector.createInstance(DescriptionService, undefined),+ },+ ]);++ injector.add([FormulaDataModel]);+ injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);++ injector.add([CalculateFormulaService]);+ injector.add([Lexer]);+ injector.add([LexerTreeBuilder]);++ injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);+ injector.add([IDependencyManagerService, { useClass: DependencyManagerService }]);+ injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);+ injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([ISuperTableService, { useClass: SuperTableService }]);+ injector.add([CalculateController]);++ injector.add([IFeatureCalculationManagerService, { useClass: FeatureCalculationManagerService }]);+ injector.add([FormulaDependencyGenerator]);+ injector.add([Interpreter]);+ injector.add([AstTreeBuilder]);++ injector.add([AstRootNodeFactory]);+ injector.add([FunctionNodeFactory]);+ injector.add([LambdaNodeFactory]);+ injector.add([LambdaParameterNodeFactory]);+ injector.add([OperatorNodeFactory]);+ injector.add([PrefixNodeFactory]);+ injector.add([ReferenceNodeFactory]);+ injector.add([SuffixNodeFactory]);+ injector.add([UnionNodeFactory]);+ injector.add([ValueNodeFactory]);+}diff --git a/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts b/packages/facade/src/apis/sheets/__tests__/create-test-bed.tsdeleted file mode 100644index 623ea5ba48..0000000000--- a/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts+++ /dev/null@@ -1,122 +0,0 @@-/**- * 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 { Dependency, IWorkbookData, Workbook } from '@univerjs/core';-import {- ILogService,- Inject,- Injector,- IUniverInstanceService,- LocaleService,- LocaleType,- LogLevel,- Plugin,- Univer,- UniverInstanceType,-} from '@univerjs/core';-import { FunctionService, IFunctionService, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';-import { ISocketService, WebSocketService } from '@univerjs/network';-import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';-import {- DescriptionService,- IDescriptionService,- IRegisterFunctionService,- RegisterFunctionService,-} from '@univerjs/sheets-formula';-import enUS from '@univerjs/sheets-formula/locale/en-US';-import zhCN from '@univerjs/sheets-formula/locale/zh-CN';--import { FUniver } from '../../facade';--function getTestWorkbookDataDemo(): IWorkbookData {- return {- id: 'test',- appVersion: '3.0.0-alpha',- sheets: {- sheet1: {- id: 'sheet1',- name: 'sheet1',- cellData: {},- },- },- locale: LocaleType.ZH_CN,- name: '',- sheetOrder: [],- styles: {},- };-}--export interface ITestBed {- univer: Univer;- get: Injector['get'];- sheet: Workbook;- univerAPI: FUniver;-}--export function createTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]): ITestBed {- const univer = new Univer();- const injector = univer.__getInjector();-- class TestPlugin extends Plugin {- static override pluginName = 'test-plugin';- static override type = UniverInstanceType.UNIVER_SHEET;-- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-- override onStarting(): void {- const injector = this._injector;- injector.add([SheetsSelectionsService]);- injector.add([SheetInterceptorService]);- injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);- injector.add([- IDescriptionService,- {- useFactory: () => this._injector.createInstance(DescriptionService, undefined),- },- ]);- injector.add([IFunctionService, { useClass: FunctionService }]);- injector.add([ISocketService, { useClass: WebSocketService }]);-- dependencies?.forEach((d) => injector.add(d));- }- }-- injector.get(LocaleService).load({ zhCN, enUS });-- univer.registerPlugin(TestPlugin);- univer.registerPlugin(UniverFormulaEnginePlugin);- const sheet = univer.createUniverSheet(workbookData || getTestWorkbookDataDemo());-- const univerInstanceService = injector.get(IUniverInstanceService);- univerInstanceService.focusUnit('test');- const logService = injector.get(ILogService);-- logService.setLogLevel(LogLevel.SILENT); // change this to `LogLevel.VERBOSE` to debug tests via logs-- const univerAPI = FUniver.newAPI(injector);-- return {- univer,- get: injector.get.bind(injector),- sheet,- univerAPI,- };-}diff --git a/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts b/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.tsnew file mode 100644index 0000000000..9ec209cedd--- /dev/null+++ b/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts@@ -0,0 +1,234 @@+/**+ * 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.+ */++/* eslint-disable max-lines-per-function */++import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';+import {+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ ThemeService,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { ActiveDirtyManagerService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';+import { ISocketService, WebSocketService } from '@univerjs/network';+import {+ RangeProtectionRuleModel,+ RefRangeService,+ SheetInterceptorService,+ SheetsSelectionsService,+ WorkbookPermissionService,+ WorksheetPermissionService,+ WorksheetProtectionPointModel,+ WorksheetProtectionRuleModel,+} from '@univerjs/sheets';+import {+ DescriptionService,+ IDescriptionService,+ IRegisterFunctionService,+ RegisterFunctionService,+ RegisterOtherFormulaService,+} from '@univerjs/sheets-formula';+import enUS from '@univerjs/sheets-formula/locale/en-US';+import zhCN from '@univerjs/sheets-formula/locale/zh-CN';++import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { ISheetSelectionRenderService, SheetRenderController, SheetSelectionRenderService, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';+import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';+import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';+import { UniverDataValidationPlugin } from '@univerjs/data-validation';+import { DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaService, DataValidationModel, SheetDataValidationManager, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';+import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';+import { FUniver } from '../../facade';++function getTestWorkbookDataDemo(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'sheet1',+ cellData: {+ 0: {+ 0: {+ v: 1,+ },+ },+ 1: {+ 0: {+ v: 2,+ },+ },+ 2: {+ 0: {+ v: 3,+ },+ },+ 3: {+ 0: {+ v: 4,+ },+ },+ },+ rowCount: 100,+ columnCount: 100,+ },+ },+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: [],+ styles: {},+ resources: [+ {+ name: 'SHEET_CONDITIONAL_FORMATTING_PLUGIN',+ data: '{"sheet-0011":[{"cfId":"AEGZdW8C","ranges":[{"startRow":2,"startColumn":1,"endRow":11,"endColumn":5,"startAbsoluteRefType":0,"endAbsoluteRefType":0,"rangeType":0}],"rule":{"type":"highlightCell","subType":"text","operator":"containsText","style":{"cl":{"rgb":"#2f56ef"},"bg":{"rgb":"#e8ecfc"}},"value":""},"stopIfTrue":false},{"cfId":"4ICEXdJj","ranges":[{"startRow":2,"startColumn":1,"endRow":11,"endColumn":5,"startAbsoluteRefType":0,"endAbsoluteRefType":0,"rangeType":0}],"rule":{"type":"highlightCell","subType":"text","operator":"containsText","style":{"cl":{"rgb":"#2f56ef"},"bg":{"rgb":"#e8ecfc"}},"value":""},"stopIfTrue":false},{"cfId":"geCv018z","ranges":[{"startRow":2,"startColumn":1,"endRow":11,"endColumn":5,"startAbsoluteRefType":0,"endAbsoluteRefType":0,"rangeType":0}],"rule":{"type":"highlightCell","subType":"text","operator":"containsText","style":{"cl":{"rgb":"#2f56ef"},"bg":{"rgb":"#e8ecfc"}},"value":""},"stopIfTrue":false}]}',+ },+ ],+ };+}++export interface ITestBed {+ univer: Univer;+ get: Injector['get'];+ sheet: UnitModel<IWorkbookData>;+ univerAPI: FUniver;+ injector: Injector;+}++export function createWorksheetTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]): ITestBed {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override pluginName = 'test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const injector = this._injector;+ injector.add([SheetsSelectionsService]);+ injector.add([SheetInterceptorService]);+ injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);+ injector.add([+ IDescriptionService,+ {+ useFactory: () => this._injector.createInstance(DescriptionService, undefined),+ },+ ]);++ injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([ISocketService, { useClass: WebSocketService }]);+ injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }]);+ injector.add([SheetsRenderService]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([SheetSkeletonManagerService]);+ injector.add([FormulaDataModel]);+ injector.add([LexerTreeBuilder]);+ injector.add([RefRangeService]);+ injector.add([WorksheetPermissionService]);+ injector.add([WorkbookPermissionService]);+ injector.add([WorksheetProtectionPointModel]);+ injector.add([RangeProtectionRuleModel]);+ injector.add([WorksheetProtectionRuleModel]);++ const renderManagerService = injector.get(IRenderManagerService);+ renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService] as Dependency);+ renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetRenderController] as Dependency);++ // register feature modules+ ([+ // conditional formatting+ [ConditionalFormattingService],+ [ConditionalFormattingFormulaService],+ [ConditionalFormattingRuleModel],+ [ConditionalFormattingViewModel],++ // data validation+ [DataValidationCacheService],+ [DataValidationFormulaService],+ [DataValidationCustomFormulaService],+ [RegisterOtherFormulaService],+ [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],+ [SheetsDataValidationValidatorService],++ // sheets filter+ ] as Dependency[]).forEach((d) => {+ injector.add(d);+ });++ dependencies?.forEach((d) => injector.add(d));+ }+ }++ // load i18n+ injector.get(LocaleService).load({ zhCN, enUS });++ // load theme service+ const themeService = injector.get(ThemeService);+ themeService.setTheme({ colorBlack: '#35322b' });++ // register builtin plugins+ // note that UI plugins are not registered here, because the unit test environment does not have a UI+ univer.registerPlugin(TestPlugin);+ univer.registerPlugin(UniverSheetsFilterPlugin);+ univer.registerPlugin(UniverDataValidationPlugin);++ const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());+ const univerInstanceService = injector.get(IUniverInstanceService);+ univerInstanceService.focusUnit('test');++ // set log level+ const logService = injector.get(ILogService);+ logService.setLogLevel(LogLevel.SILENT); // NOTE: change this to `LogLevel.VERBOSE` to debug tests via logs++ // init data validation+ const createSheetDataValidationManager = (unitId: string, subUnitId: string) => {+ return new SheetDataValidationManager(+ unitId,+ subUnitId,+ injector+ );+ };+ const dataValidationModel = injector.get(DataValidationModel);+ dataValidationModel.setManagerCreator(createSheetDataValidationManager);++ const univerAPI = FUniver.newAPI(injector);++ return {+ univer,+ get: injector.get.bind(injector),+ sheet,+ univerAPI,+ injector,+ };+}diff --git a/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-formula.spec.tsindex 8728abc00a..21a1de0569 100644--- a/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts+++ b/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts@@ -21,7 +21,7 @@ import { beforeEach, describe, expect, it } from 'vitest';import { SetArrayFormulaDataMutation, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';import type { FUniver } from '../../facade';-import { createFacadeTestBed } from '../../__tests__/create-test-bed';+import { createFormulaTestBed } from './create-formula-test-bed';describe('Test FFormula', () => {let get: Injector['get'];@@ -41,7 +41,7 @@ describe('Test FFormula', () => {) => Nullable<IStyleData>;beforeEach(() => {- const testBed = createFacadeTestBed();+ const testBed = createFormulaTestBed();get = testBed.get;univerAPI = testBed.univerAPI;diff --git a/packages/facade/src/apis/sheets/__tests__/f-worksheet.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-worksheet.spec.tsindex f227b63240..71a8d3f6e3 100644--- a/packages/facade/src/apis/sheets/__tests__/f-worksheet.spec.ts+++ b/packages/facade/src/apis/sheets/__tests__/f-worksheet.spec.ts@@ -14,13 +14,13 @@* limitations under the License.*/-import type { ICellData, Injector, IStyleData, Nullable } from '@univerjs/core';-import { ICommandService, IUniverInstanceService } from '@univerjs/core';-import { SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';+import type { ICellData, Injector, IStyleData, Nullable, Workbook } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';+import { InsertColCommand, InsertColMutation, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRowsCommand, MoveRowsMutation, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, SetColHiddenCommand, SetColHiddenMutation, SetColVisibleMutation, SetColWidthCommand, SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetRowHeightCommand, SetRowHiddenCommand, SetRowHiddenMutation, SetRowVisibleMutation, SetSelectionsOperation, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand, SetWorksheetColWidthMutation, SetWorksheetRowHeightMutation, SetWorksheetRowIsAutoHeightCommand, SetWorksheetRowIsAutoHeightMutation, SheetsSelectionsService } from '@univerjs/sheets';import { beforeEach, describe, expect, it } from 'vitest';import type { FUniver } from '../../facade';-import { createFacadeTestBed } from '../../__tests__/create-test-bed';+import { createWorksheetTestBed } from './create-worksheet-test-bed';describe('Test FWorksheet', () => {let get: Injector['get'];@@ -38,9 +38,10 @@ describe('Test FWorksheet', () => {endRow: number,endColumn: number) => Nullable<IStyleData>;+ let setSelection: (startRow: number, endRow: number, startColumn: number, endColumn: number) => void;beforeEach(() => {- const testBed = createFacadeTestBed();+ const testBed = createWorksheetTestBed();get = testBed.get;univerAPI = testBed.univerAPI;@@ -52,6 +53,37 @@ describe('Test FWorksheet', () => {commandService.registerCommand(SetHorizontalTextAlignCommand);commandService.registerCommand(SetTextWrapCommand);+ // row+ commandService.registerCommand(InsertRowCommand);+ commandService.registerCommand(InsertRowMutation);+ commandService.registerCommand(RemoveRowCommand);+ commandService.registerCommand(RemoveRowMutation);+ commandService.registerCommand(MoveRowsCommand);+ commandService.registerCommand(MoveRowsMutation);+ commandService.registerCommand(SetRowHiddenCommand);+ commandService.registerCommand(SetRowHiddenMutation);+ commandService.registerCommand(SetSelectionsOperation);+ commandService.registerCommand(SetSpecificRowsVisibleCommand);+ commandService.registerCommand(SetRowVisibleMutation);+ commandService.registerCommand(SetRowHeightCommand);+ commandService.registerCommand(SetWorksheetRowHeightMutation);+ commandService.registerCommand(SetWorksheetRowIsAutoHeightCommand);+ commandService.registerCommand(SetWorksheetRowIsAutoHeightMutation);++ // column+ commandService.registerCommand(InsertColCommand);+ commandService.registerCommand(InsertColMutation);+ commandService.registerCommand(RemoveColCommand);+ commandService.registerCommand(RemoveColMutation);+ commandService.registerCommand(MoveColsCommand);+ commandService.registerCommand(MoveColsMutation);+ commandService.registerCommand(SetColHiddenCommand);+ commandService.registerCommand(SetColHiddenMutation);+ commandService.registerCommand(SetSpecificColsVisibleCommand);+ commandService.registerCommand(SetColVisibleMutation);+ commandService.registerCommand(SetColWidthCommand);+ commandService.registerCommand(SetWorksheetColWidthMutation);+getValueByPosition = (startRow: number,startColumn: number,@@ -76,10 +108,378 @@ describe('Test FWorksheet', () => {return styles.getStyleByCell(value);}};++ setSelection = (startRow: number, endRow: number, startColumn: number, endColumn: number, rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL) => {+ const selectionManagerService = get(SheetsSelectionsService);+ selectionManagerService.addSelections([+ {+ range: { startRow, startColumn, endColumn, endRow, rangeType },+ primary: {+ startRow,+ endRow: startRow,+ startColumn,+ endColumn: startColumn,+ actualColumn: startColumn,+ actualRow: startRow,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ },+ ]);+ };+ });++ it('Worksheet getSheetId', () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');+ expect(activeSheet?.getSheetId()).toBe('sheet1');});it('Worksheet getSheetName', () => {const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');expect(activeSheet?.getSheetName()).toBe('sheet1');});++ it('Worksheet getSelection', () => {+ setSelection(0, 0, 0, 0);+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');+ const range = activeSheet?.getSelection()?.getActiveRange()?.getRange();+ expect(range).toEqual({ startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL });+ });++ it('Worksheet getRange', () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');+ const range = activeSheet?.getRange(0, 3, 1, 1);+ expect(range).toBeDefined();+ });++ it('Worksheet getMaxColumns', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');+ expect(activeSheet?.getMaxColumns()).toBe(100);+ });++ it('Worksheet getMaxRows', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');+ expect(activeSheet?.getMaxRows()).toBe(100);+ });++ // #region Data Validation++ it('Worksheet getDataValidations', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');+ expect(activeSheet?.getDataValidations()).toBeDefined();+ });++ it('Worksheet getValidatorStatus', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');+ expect(activeSheet?.getValidatorStatus()).toBeDefined();+ });++ // #endregion++ // #region Filter++ it('Worksheet getFilter', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');+ expect(activeSheet?.getFilter()).toBeDefined();+ });++ // #endregion++ // #region Row++ it('Worksheet insertRowAfter', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.insertRowAfter(0);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxRows()).toBe(101);+ });++ it('Worksheet insertRowBefore', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.insertRowBefore(0);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxRows()).toBe(101);+ });++ it('Worksheet insertRows', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.insertRows(0, 2);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxRows()).toBe(102);+ });++ it('Worksheet insertRowsAfter', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.insertRowsAfter(0, 2);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxRows()).toBe(102);+ });++ it('Worksheet insertRowsBefore', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.insertRowsBefore(0, 2);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxRows()).toBe(102);+ });++ it('Worksheet deleteRow', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.deleteRow(0);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxRows()).toBe(99);+ });++ it('Worksheet deleteRows', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.deleteRows(0, 2);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxRows()).toBe(98);+ });++ it('Worksheet moveRows', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const range = activeSheet?.getRange(0, 0, 1, 1);+ if (!range) return;++ const sheet = await activeSheet?.moveRows(range, 10);+ expect(sheet).toBeDefined();+ expect(sheet?.getRange(9, 0, 1, 1).getValue()).toBe(1);+ });++ it('Worksheet hideRow/unhideRow', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const range = activeSheet?.getRange(0, 0, 1, 1);+ if (!range) return;++ const sheet = await activeSheet?.hideRow(range);+ expect(sheet).toBeDefined();++ const currentWorksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();+ const hiddenRows = currentWorksheet?.getHiddenRows();+ expect(hiddenRows).toStrictEqual([{+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 99,+ rangeType: RANGE_TYPE.ROW,+ }]);++ const sheet2 = await activeSheet?.unhideRow(range);+ expect(sheet2).toBeDefined();++ const hiddenRows2 = currentWorksheet?.getHiddenRows();+ expect(hiddenRows2).toStrictEqual([]);+ });++ it('Worksheet hideRows/showRows', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.hideRows(0, 2);+ expect(sheet).toBeDefined();++ const currentWorksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();+ const hiddenRows = currentWorksheet?.getHiddenRows();+ expect(hiddenRows).toStrictEqual([{+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 99,+ rangeType: RANGE_TYPE.ROW,+ }]);++ const sheet2 = await activeSheet?.showRows(0, 2);+ expect(sheet2).toBeDefined();++ const hiddenRows2 = currentWorksheet?.getHiddenRows();+ expect(hiddenRows2).toStrictEqual([]);+ });++ it('Worksheet setRowHeight', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.setRowHeight(0, 100);+ expect(sheet).toBeDefined();++ const currentWorksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();+ const currentRowHeight = currentWorksheet?.getRowManager().getRowHeight(0);+ expect(currentRowHeight).toBe(100);+ });++ it('Worksheet setRowHeights', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.setRowHeights(0, 2, 100);+ expect(sheet).toBeDefined();++ const currentWorksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();+ const currentRowHeight = currentWorksheet?.getRowManager().getRowHeight(0, 2);+ expect(currentRowHeight).toBe(200);+ });++ it('Worksheet setRowHeightsForced', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.setRowHeightsForced(0, 2, 100);+ expect(sheet).toBeDefined();++ const currentWorksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();+ const currentRowHeight = currentWorksheet?.getRowManager().getRowHeight(0, 2);+ expect(currentRowHeight).toBe(200);+ });++ // #endregion++ // #region Column++ it('Worksheet insertColumnAfter', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.insertColumnAfter(0);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxColumns()).toBe(101);+ });++ it('Worksheet insertColumnBefore', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.insertColumnBefore(0);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxColumns()).toBe(101);+ });++ it('Worksheet insertColumns', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.insertColumns(0, 2);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxColumns()).toBe(102);+ });++ it('Worksheet insertColumnsAfter', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.insertColumnsAfter(0, 2);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxColumns()).toBe(102);+ });++ it('Worksheet insertColumnsBefore', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.insertColumnsBefore(0, 2);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxColumns()).toBe(102);+ });++ it('Worksheet deleteColumn', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.deleteColumn(0);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxColumns()).toBe(99);+ });++ it('Worksheet deleteColumns', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.deleteColumns(0, 2);+ expect(sheet).toBeDefined();+ expect(sheet?.getMaxColumns()).toBe(98);+ });++ it('Worksheet moveColumns', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const range = activeSheet?.getRange(0, 0, 1, 1);+ if (!range) return;++ const sheet = await activeSheet?.moveColumns(range, 10);+ expect(sheet).toBeDefined();+ expect(sheet?.getRange(0, 9, 1, 1).getValue()).toBe(1);+ });++ it('Worksheet hideColumn/unhideColumn', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const range = activeSheet?.getRange(0, 0, 1, 1);+ if (!range) return;++ const sheet = await activeSheet?.hideColumn(range);+ expect(sheet).toBeDefined();++ const currentWorksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();+ const hiddenCols = currentWorksheet?.getHiddenCols();+ expect(hiddenCols).toStrictEqual([{+ startRow: 0,+ endRow: 99,+ startColumn: 0,+ endColumn: 0,+ rangeType: RANGE_TYPE.COLUMN,+ }]);++ const sheet2 = await activeSheet?.unhideColumn(range);+ expect(sheet2).toBeDefined();++ const hiddenCols2 = currentWorksheet?.getHiddenCols();+ expect(hiddenCols2).toStrictEqual([]);+ });++ it('Worksheet hideColumns/showColumns', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.hideColumns(0, 2);+ expect(sheet).toBeDefined();++ const currentWorksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();+ const hiddenCols = currentWorksheet?.getHiddenCols();+ expect(hiddenCols).toStrictEqual([{+ startRow: 0,+ endRow: 99,+ startColumn: 0,+ endColumn: 1,+ rangeType: RANGE_TYPE.COLUMN,+ }]);++ const sheet2 = await activeSheet?.showColumns(0, 2);+ expect(sheet2).toBeDefined();++ const hiddenCols2 = currentWorksheet?.getHiddenCols();+ expect(hiddenCols2).toStrictEqual([]);+ });++ it('Worksheet setColWidth', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.setColumnWidth(0, 100);+ expect(sheet).toBeDefined();++ const currentWorksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();+ const currentColWidth = currentWorksheet?.getColumnManager().getColumnWidth(0);+ expect(currentColWidth).toBe(100);+ });++ it('Worksheet setColWidths', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');++ const sheet = await activeSheet?.setColumnWidths(0, 2, 100);+ expect(sheet).toBeDefined();++ const currentWorksheet = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();+ const currentColWidth = currentWorksheet?.getColumnManager().getColumnWidth(0);+ expect(currentColWidth).toBe(100);+ const currentColWidth2 = currentWorksheet?.getColumnManager().getColumnWidth(1);+ expect(currentColWidth2).toBe(100);+ });++ // #endregion});diff --git a/packages/facade/src/apis/sheets/f-worksheet.ts b/packages/facade/src/apis/sheets/f-worksheet.tsindex e6db90dbf6..283be0a558 100644--- a/packages/facade/src/apis/sheets/f-worksheet.ts+++ b/packages/facade/src/apis/sheets/f-worksheet.ts@@ -15,9 +15,8 @@*/import type { IRange, Nullable, ObjectMatrix, Workbook, Worksheet } from '@univerjs/core';-import type { ISetWorksheetColWidthMutationParams, ISetWorksheetRowHeightMutationParams } from '@univerjs/sheets';-import { SetWorksheetColWidthMutation, SetWorksheetRowHeightMutation, SheetsSelectionsService } from '@univerjs/sheets';-import { ICommandService, Inject, Injector } from '@univerjs/core';+import { copyRangeStyles, InsertColCommand, InsertRowCommand, MoveColsCommand, MoveRowsCommand, RemoveColCommand, RemoveRowCommand, SetColHiddenCommand, SetColWidthCommand, SetRowHeightCommand, SetRowHiddenCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetWorksheetRowIsAutoHeightCommand, SheetsSelectionsService } from '@univerjs/sheets';+import { Direction, ICommandService, Inject, Injector, RANGE_TYPE } from '@univerjs/core';import type { IDataValidationResCache } from '@univerjs/sheets-data-validation';import { DataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';@@ -27,6 +26,7 @@ import { FRange } from './f-range';import { FSelection } from './f-selection';import { FDataValidation } from './f-data-validation';import { FFilter } from './f-filter';+import { covertToColRange, covertToRowRange } from './utils';export class FWorksheet {constructor(@@ -75,38 +75,6 @@ export class FWorksheet {return this._injector.createInstance(FRange, this._workbook, this._worksheet, range);}- setRowHeights(startRow: number, numRows: number, height: number): void {- this._commandService.syncExecuteCommand(SetWorksheetRowHeightMutation.id, {- unitId: this._workbook.getUnitId(),- subUnitId: this._worksheet.getSheetId(),- ranges: [- {- startRow,- endRow: startRow + numRows - 1,- startColumn: 0,- endColumn: this._worksheet.getColumnCount() - 1,- },- ],- rowHeight: height,- } as ISetWorksheetRowHeightMutationParams);- }-- setColumnWidths(startColumn: number, numColumns: number, width: number): void {- this._commandService.syncExecuteCommand(SetWorksheetColWidthMutation.id, {- unitId: this._workbook.getUnitId(),- subUnitId: this._worksheet.getSheetId(),- ranges: [- {- startColumn,- endColumn: startColumn + numColumns - 1,- startRow: 0,- endRow: this._worksheet.getRowCount() - 1,- },- ],- colWidth: width,- } as ISetWorksheetColWidthMutationParams);- }-/*** Returns the current number of columns in the sheet, regardless of content.* @return The maximum columns count of the sheet@@ -161,4 +129,635 @@ export class FWorksheet {}// #endregion++ // #region Row++ /**+ * Inserts a row after the given row position.+ * @param afterPosition The row after which the new row should be added, starting at 0 for the first row.+ * @returns This sheet, for chaining.+ */+ async insertRowAfter(afterPosition: number): Promise<FWorksheet> {+ return this.insertRowsAfter(afterPosition, 1);+ }++ /**+ * Inserts a row before the given row position.+ * @param beforePosition The row before which the new row should be added, starting at 0 for the first row.+ * @returns This sheet, for chaining.+ */+ async insertRowBefore(beforePosition: number): Promise<FWorksheet> {+ return this.insertRowsBefore(beforePosition, 1);+ }++ /**+ * Inserts one or more consecutive blank rows in a sheet starting at the specified location.+ * @param rowIndex The index indicating where to insert a row, starting at 0 for the first row.+ * @param numRows The number of rows to insert.+ * @returns This sheet, for chaining.+ */+ async insertRows(rowIndex: number, numRows: number = 1): Promise<FWorksheet> {+ return this.insertRowsBefore(rowIndex, numRows);+ }++ /**+ * Inserts a number of rows after the given row position.+ * @param afterPosition The row after which the new rows should be added, starting at 0 for the first row.+ * @param howMany The number of rows to insert.+ * @returns This sheet, for chaining.+ */+ async insertRowsAfter(afterPosition: number, howMany: number): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const direction = Direction.DOWN;++ const startRow = afterPosition + 1;+ const endRow = afterPosition + howMany;+ const startColumn = 0;+ const endColumn = this._worksheet.getColumnCount() - 1;++ // copy styles of the row below+ const cellValue = copyRangeStyles(this._worksheet, startRow, endRow, startColumn, endColumn, true, afterPosition);++ await this._commandService.executeCommand(InsertRowCommand.id, {+ unitId,+ subUnitId,+ direction,+ range: {+ startRow,+ endRow,+ startColumn,+ endColumn,+ },+ cellValue,+ });++ return this;+ }++ /**+ * Inserts a number of rows before the given row position.+ * @param beforePosition The row before which the new rows should be added, starting at 0 for the first row.+ * @param howMany The number of rows to insert.+ * @returns This sheet, for chaining.+ */+ async insertRowsBefore(beforePosition: number, howMany: number): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const direction = Direction.UP;++ const startRow = beforePosition;+ const endRow = beforePosition + howMany - 1;+ const startColumn = 0;+ const endColumn = this._worksheet.getColumnCount() - 1;++ // copy styles of the row above+ const cellValue = copyRangeStyles(this._worksheet, startRow, endRow, startColumn, endColumn, true, beforePosition - 1);++ await this._commandService.executeCommand(InsertRowCommand.id, {+ unitId,+ subUnitId,+ direction,+ range: {+ startRow,+ endRow,+ startColumn,+ endColumn,+ },+ cellValue,+ });++ return this;+ }++ /**+ * Deletes the row at the given row position.+ * @param rowPosition The position of the row, starting at 0 for the first row.+ * @returns This sheet, for chaining.+ */+ async deleteRow(rowPosition: number): Promise<FWorksheet> {+ return this.deleteRows(rowPosition, 1);+ }++ /**+ * Deletes a number of rows starting at the given row position.+ * @param rowPosition The position of the first row to delete, starting at 0 for the first row.+ * @param howMany The number of rows to delete.+ * @returns This sheet, for chaining.+ */+ async deleteRows(rowPosition: number, howMany: number): Promise<FWorksheet> {+ const range = {+ startRow: rowPosition,+ endRow: rowPosition + howMany - 1,+ startColumn: 0,+ endColumn: this._worksheet.getColumnCount() - 1,+ };++ await this._commandService.executeCommand(RemoveRowCommand.id, {+ range,+ });++ return this;+ }++ /**+ * Moves the rows selected by the given range to the position indicated by the destinationIndex. The rowSpec itself does not have to exactly represent an entire row or group of rows to move—it selects all rows that the range spans.+ * @param rowSpec A range spanning the rows that should be moved.+ * @param destinationIndex The index that the rows should be moved to. Note that this index is based on the coordinates before the rows are moved. Existing data is shifted down to make room for the moved rows while the source rows are removed from the grid. Therefore, the data may end up at a different index than originally specified. Use 0-index for this method.+ * @returns This sheet, for chaining.+ */+ async moveRows(rowSpec: FRange, destinationIndex: number): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const range = covertToRowRange(rowSpec.getRange(), this._worksheet);+ const fromRange = range;+ const toRange = {+ startRow: destinationIndex,+ endRow: destinationIndex,+ startColumn: range.startColumn,+ endColumn: range.endColumn,+ };++ await this._commandService.executeCommand(MoveRowsCommand.id, {+ unitId,+ subUnitId,+ range,+ fromRange,+ toRange,+ });++ return this;+ }++ /**+ * Hides the rows in the given range.+ * @param row The row range to hide.+ * @returns This sheet, for chaining.+ */+ async hideRow(row: FRange): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const range = covertToRowRange(row.getRange(), this._worksheet);++ await this._commandService.executeCommand(SetRowHiddenCommand.id, {+ unitId,+ subUnitId,+ ranges: [range],+ });++ return this;+ }++ /**+ * Hides one or more consecutive rows starting at the given index. Use 0-index for this method.+ * @param rowIndex The starting index of the rows to hide.+ * @param numRows The number of rows to hide.+ * @returns This sheet, for chaining.+ */+ async hideRows(rowIndex: number, numRows: number = 1): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const range: IRange = {+ startRow: rowIndex,+ endRow: rowIndex + numRows - 1,+ startColumn: 0,+ endColumn: this._worksheet.getColumnCount() - 1,+ rangeType: RANGE_TYPE.ROW,+ };++ await this._commandService.executeCommand(SetRowHiddenCommand.id, {+ unitId,+ subUnitId,+ ranges: [range],+ });+ return this;+ }++ /**+ * Unhides the row in the given range.+ * @param row The range to unhide, if hidden.+ * @returns This sheet, for chaining.+ */+ async unhideRow(row: FRange): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const range = covertToRowRange(row.getRange(), this._worksheet);++ await this._commandService.executeCommand(SetSpecificRowsVisibleCommand.id, {+ unitId,+ subUnitId,+ ranges: [range],+ });++ return this;+ }++ /**+ * Unhides one or more consecutive rows starting at the given index. Use 0-index for this method.+ * @param rowIndex The starting index of the rows to unhide.+ * @param numRows The number of rows to unhide.+ * @returns This sheet, for chaining.+ */+ async showRows(rowIndex: number, numRows: number = 1): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const range: IRange = {+ startRow: rowIndex,+ endRow: rowIndex + numRows - 1,+ startColumn: 0,+ endColumn: this._worksheet.getColumnCount() - 1,+ rangeType: RANGE_TYPE.ROW,+ };++ await this._commandService.executeCommand(SetSpecificRowsVisibleCommand.id, {+ unitId,+ subUnitId,+ ranges: [range],+ });++ return this;+ }++ /**+ * Sets the row height of the given row in pixels. By default, rows grow to fit cell contents. If you want to force rows to a specified height, use setRowHeightsForced(startRow, numRows, height).+ * @param rowPosition The row position to change.+ * @param height The height in pixels to set it to.+ * @returns This sheet, for chaining.+ */+ async setRowHeight(rowPosition: number, height: number): Promise<FWorksheet> {+ return this.setRowHeights(rowPosition, 1, height);+ }++ /**+ * Sets the height of the given rows in pixels. By default, rows grow to fit cell contents. If you want to force rows to a specified height, use setRowHeightsForced(startRow, numRows, height).+ * @param startRow The starting row position to change.+ * @param numRows The number of rows to change.+ * @param height The height in pixels to set it to.+ * @returns This sheet, for chaining.+ */+ async setRowHeights(startRow: number, numRows: number, height: number): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const rowManager = this._worksheet.getRowManager();++ const autoHeightRanges: IRange[] = [];+ const rowHeightRanges: IRange[] = [];++ for (let i = startRow; i < startRow + numRows; i++) {+ const autoRowHeight = rowManager.getRow(i)?.ah || this._worksheet.getConfig().defaultRowHeight;+ const range = {+ startRow: i,+ endRow: i,+ startColumn: 0,+ endColumn: this._worksheet.getColumnCount() - 1,+ };++ // if the new height is less than the current height, set auto height+ if (height <= autoRowHeight) {+ autoHeightRanges.push(range);+ } else { // if the new height is greater than the current height, set the new height+ rowHeightRanges.push(range);+ }+ }++ if (rowHeightRanges.length > 0) {+ await this._commandService.executeCommand(SetRowHeightCommand.id, {+ unitId,+ subUnitId,+ ranges: rowHeightRanges,+ value: height,+ });+ }++ if (autoHeightRanges.length > 0) {+ await this._commandService.executeCommand(SetWorksheetRowIsAutoHeightCommand.id, {+ unitId,+ subUnitId,+ ranges: autoHeightRanges,+ });+ }++ return this;+ }++ /**+ * Sets the height of the given rows in pixels. By default, rows grow to fit cell contents. When you use setRowHeightsForced, rows are forced to the specified height even if the cell contents are taller than the row height.+ * @param startRow The starting row position to change.+ * @param numRows The number of rows to change.+ * @param height The height in pixels to set it to.+ * @returns This sheet, for chaining.+ */+ async setRowHeightsForced(startRow: number, numRows: number, height: number): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const ranges = [+ {+ startRow,+ endRow: startRow + numRows - 1,+ startColumn: 0,+ endColumn: this._worksheet.getColumnCount() - 1,+ },+ ];++ await this._commandService.executeCommand(SetRowHeightCommand.id, {+ unitId,+ subUnitId,+ ranges,+ value: height,+ });++ return this;+ }++ // #endregion++ // #region Column++ /**+ * Inserts a column after the given column position.+ * @param afterPosition The column after which the new column should be added, starting at 0 for the first column.+ * @returns This sheet, for chaining.+ */+ async insertColumnAfter(afterPosition: number): Promise<FWorksheet> {+ return this.insertColumnsAfter(afterPosition, 1);+ }++ /**+ * Inserts a column before the given column position.+ * @param beforePosition The column before which the new column should be added, starting at 0 for the first column.+ * @returns This sheet, for chaining.+ */+ async insertColumnBefore(beforePosition: number): Promise<FWorksheet> {+ return this.insertColumnsBefore(beforePosition, 1);+ }++ /**+ * Inserts one or more consecutive blank columns in a sheet starting at the specified location.+ * @param columnIndex The index indicating where to insert a column, starting at 0 for the first column.+ * @param numColumns The number of columns to insert.+ * @returns This sheet, for chaining.+ */+ async insertColumns(columnIndex: number, numColumns: number = 1): Promise<FWorksheet> {+ return this.insertColumnsBefore(columnIndex, numColumns);+ }++ /**+ * Inserts a given number of columns after the given column position.+ * @param afterPosition The column after which the new column should be added, starting at 0 for the first column.+ * @param howMany The number of columns to insert.+ * @returns This sheet, for chaining.+ */+ async insertColumnsAfter(afterPosition: number, howMany: number): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const direction = Direction.RIGHT;++ const startRow = 0;+ const endRow = this._worksheet.getRowCount() - 1;+ const startColumn = afterPosition + 1;+ const endColumn = afterPosition + howMany;++ // copy styles of the column to the right+ const cellValue = copyRangeStyles(this._worksheet, startRow, endRow, startColumn, endColumn, false, afterPosition);++ await this._commandService.executeCommand(InsertColCommand.id, {+ unitId,+ subUnitId,+ direction,+ range: {+ startRow,+ endRow,+ startColumn,+ endColumn,+ },+ cellValue,+ });++ return this;+ }++ /**+ * Inserts a number of columns before the given column position.+ * @param beforePosition The column before which the new column should be added, starting at 0 for the first column.+ * @param howMany The number of columns to insert.+ * @returns This sheet, for chaining.+ */+ async insertColumnsBefore(beforePosition: number, howMany: number): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const direction = Direction.LEFT;++ const startRow = 0;+ const endRow = this._worksheet.getRowCount() - 1;+ const startColumn = beforePosition;+ const endColumn = beforePosition + howMany - 1;++ // copy styles of the column to the left+ const cellValue = copyRangeStyles(this._worksheet, startRow, endRow, startColumn, endColumn, false, beforePosition - 1);++ await this._commandService.executeCommand(InsertColCommand.id, {+ unitId,+ subUnitId,+ direction,+ range: {+ startRow,+ endRow,+ startColumn,+ endColumn,+ },+ cellValue,+ });++ return this;+ }++ /**+ * Deletes the column at the given column position.+ * @param columnPosition The position of the column, starting at 0 for the first column.+ * @returns This sheet, for chaining.+ */+ async deleteColumn(columnPosition: number): Promise<FWorksheet> {+ return this.deleteColumns(columnPosition, 1);+ }++ /**+ * Deletes a number of columns starting at the given column position.+ * @param columnPosition The position of the first column to delete, starting at 0 for the first column.+ * @param howMany The number of columns to delete.+ * @returns This sheet, for chaining.+ */+ async deleteColumns(columnPosition: number, howMany: number): Promise<FWorksheet> {+ const range = {+ startRow: 0,+ endRow: this._worksheet.getRowCount() - 1,+ startColumn: columnPosition,+ endColumn: columnPosition + howMany - 1,+ };++ await this._commandService.executeCommand(RemoveColCommand.id, {+ range,+ });++ return this;+ }++ /**+ * Moves the columns selected by the given range to the position indicated by the destinationIndex. The columnSpec itself does not have to exactly represent an entire column or group of columns to move—it selects all columns that the range spans.+ * @param columnSpec A range spanning the columns that should be moved.+ * @param destinationIndex The index that the columns should be moved to. Note that this index is based on the coordinates before the columns are moved. Existing data is shifted right to make room for the moved columns while the source columns are removed from the grid. Therefore, the data may end up at a different index than originally specified. Use 0-index for this method.+ * @returns This sheet, for chaining.+ */+ async moveColumns(columnSpec: FRange, destinationIndex: number): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const range = covertToColRange(columnSpec.getRange(), this._worksheet);+ const fromRange = range;+ const toRange = {+ startRow: 0,+ endRow: this._worksheet.getRowCount() - 1,+ startColumn: destinationIndex,+ endColumn: destinationIndex,+ };++ await this._commandService.executeCommand(MoveColsCommand.id, {+ unitId,+ subUnitId,+ range,+ fromRange,+ toRange,+ });++ return this;+ }++ /**+ * Hides the column or columns in the given range.+ * @param column The column range to hide.+ * @returns This sheet, for chaining.+ */+ async hideColumn(column: FRange): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const range = covertToColRange(column.getRange(), this._worksheet);++ await this._commandService.executeCommand(SetColHiddenCommand.id, {+ unitId,+ subUnitId,+ ranges: [range],+ });++ return this;+ }++ /**+ * Hides one or more consecutive columns starting at the given index. Use 0-index for this method.+ * @param columnIndex The starting index of the columns to hide.+ * @param numColumns The number of columns to hide.+ * @returns This sheet, for chaining.+ */+ async hideColumns(columnIndex: number, numColumns: number = 1): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const range: IRange = {+ startRow: 0,+ endRow: this._worksheet.getRowCount() - 1,+ startColumn: columnIndex,+ endColumn: columnIndex + numColumns - 1,+ rangeType: RANGE_TYPE.COLUMN,+ };++ await this._commandService.executeCommand(SetColHiddenCommand.id, {+ unitId,+ subUnitId,+ ranges: [range],+ });++ return this;+ }++ /**+ * Unhides the column in the given range.+ * @param column The range to unhide, if hidden.+ * @returns This sheet, for chaining.+ */+ async unhideColumn(column: FRange): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const range = covertToColRange(column.getRange(), this._worksheet);++ await this._commandService.executeCommand(SetSpecificColsVisibleCommand.id, {+ unitId,+ subUnitId,+ ranges: [range],+ });++ return this;+ }++ /**+ * Unhides one or more consecutive columns starting at the given index. Use 0-index for this method.+ * @param columnIndex The starting index of the columns to unhide.+ * @param numColumns The number of columns to unhide.+ * @returns This sheet, for chaining.+ */+ async showColumns(columnIndex: number, numColumns: number = 1): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const range: IRange = {+ startRow: 0,+ endRow: this._worksheet.getRowCount() - 1,+ startColumn: columnIndex,+ endColumn: columnIndex + numColumns - 1,+ rangeType: RANGE_TYPE.COLUMN,+ };++ await this._commandService.executeCommand(SetSpecificColsVisibleCommand.id, {+ unitId,+ subUnitId,+ ranges: [range],+ });++ return this;+ }++ /**+ * Sets the width of the given column in pixels.+ * @param columnPosition The position of the given column to set.+ * @param width The width in pixels to set it to.+ * @returns This sheet, for chaining.+ */+ async setColumnWidth(columnPosition: number, width: number): Promise<FWorksheet> {+ return this.setColumnWidths(columnPosition, 1, width);+ }++ /**+ * Sets the width of the given columns in pixels.+ * @param startColumn The starting column position to change.+ * @param numColumns The number of columns to change.+ * @param width The width in pixels to set it to.+ * @returns This sheet, for chaining.+ */+ async setColumnWidths(startColumn: number, numColumns: number, width: number): Promise<FWorksheet> {+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const ranges = [+ {+ startColumn,+ endColumn: startColumn + numColumns - 1,+ startRow: 0,+ endRow: this._worksheet.getRowCount() - 1,+ },+ ];++ await this._commandService.executeCommand(SetColWidthCommand.id, {+ unitId,+ subUnitId,+ ranges,+ value: width,+ });++ return this;+ }++ // #endregion}diff --git a/packages/facade/src/apis/sheets/utils.ts b/packages/facade/src/apis/sheets/utils.tsindex 42cb22aace..46ff30b3fd 100644--- a/packages/facade/src/apis/sheets/utils.ts+++ b/packages/facade/src/apis/sheets/utils.ts@@ -14,13 +14,14 @@* limitations under the License.*/-import type { CellValue, ICellData, IObjectMatrixPrimitiveType, IRange, IRangeWithCoord, Nullable } from '@univerjs/core';+import type { CellValue, ICellData, IObjectMatrixPrimitiveType, IRange, IRangeWithCoord, Nullable, Worksheet } from '@univerjs/core';import {HorizontalAlign,isCellV,isFormulaString,isICellData,ObjectMatrix,+ RANGE_TYPE,Tools,VerticalAlign,} from '@univerjs/core';@@ -150,3 +151,23 @@ export function isSingleCell(mergeInfo: IRangeWithCoord, range: IRange): boolean&& mergeInfo.startRow === range.startRow&& mergeInfo.endRow === range.endRow;}++export function covertToRowRange(range: IRange, worksheet: Worksheet): IRange {+ return {+ startRow: range.startRow,+ endRow: range.endRow,+ startColumn: 0,+ endColumn: worksheet.getColumnCount() - 1,+ rangeType: RANGE_TYPE.ROW,+ };+}++export function covertToColRange(range: IRange, worksheet: Worksheet): IRange {+ return {+ startRow: 0,+ endRow: worksheet.getRowCount() - 1,+ startColumn: range.startColumn,+ endColumn: range.endColumn,+ rangeType: RANGE_TYPE.COLUMN,+ };+}diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.tsindex d244e49cb8..e787ecefd1 100644--- a/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts@@ -499,7 +499,7 @@ export class HeaderResizeRenderController extends Disposable implements IRenderMthis._commandService.executeCommand<ISetWorksheetRowIsAutoHeightCommandParams>(SetWorksheetRowIsAutoHeightCommand.id,{- anchorRow: this._currentRow,+ ranges: [{ startRow: this._currentRow, endRow: this._currentRow, startColumn: 0, endColumn: this._sheetSkeletonManagerService.getCurrent()?.skeleton.worksheet.getColumnCount() || 0 }],});diff --git a/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.tsindex c73d0a7800..91eb33a86a 100644--- a/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts@@ -193,8 +193,7 @@ describe('Test insert and remove rows cols commands', () => {// the merged cell should be moved downexpect(getMergedInfo(3, 2)).toEqual({ startRow: 3, endRow: 4, startColumn: 2, endColumn: 2 });// Insert row style- expect(getCellStyle(1, 1)).toBe('s2');- expect(getCellStyle(2, 1)).toBe('s2');+ expect(getCellStyle(1, 0)).toBe('s1');await commandService.executeCommand(UndoCommand.id);expect(getRowCount()).toBe(20);@@ -209,7 +208,7 @@ describe('Test insert and remove rows cols commands', () => {expect(getRowCount()).toBe(initRowCount);expect(getCellStyle(2, 1)).toBe('s4');expect(getMergedInfo(2, 2)).toEqual({ startRow: 2, endRow: 3, startColumn: 2, endColumn: 2 });- const result = await commandService.executeCommand(InsertRowBeforeCommand.id);+ const result = await commandService.executeCommand(InsertRowAfterCommand.id);// TODO: expect row heightexpect(result).toBeTruthy();expect(getRowCount()).toBe(21);@@ -222,6 +221,15 @@ describe('Test insert and remove rows cols commands', () => {await commandService.executeCommand(RedoCommand.id);expect(getRowCount()).toBe(21);});++ it("Should 'insert after' work, copy style", async () => {+ selectRow(0, 0);+ const result = await commandService.executeCommand(InsertRowAfterCommand.id);+ expect(result).toBeTruthy();++ // Insert row style+ expect(getCellStyle(1, 0)).toBe('s1');+ });});describe('Insert columns', () => {@@ -233,8 +241,7 @@ describe('Test insert and remove rows cols commands', () => {expect(result).toBeTruthy();expect(getColCount()).toBe(21);// Insert column style- expect(getCellStyle(1, 1)).toBe('s2');- expect(getCellStyle(1, 2)).toBe('s2');+ expect(getCellStyle(0, 1)).toBe('s1');const undoResult = await commandService.executeCommand(UndoCommand.id);expect(undoResult).toBeTruthy();@@ -254,6 +261,16 @@ describe('Test insert and remove rows cols commands', () => {expect(getMergedInfo(3, 3)).toEqual({ startRow: 2, endRow: 3, startColumn: 3, endColumn: 3 });expect(getMergedInfo(1, 4)).toEqual({ startRow: 1, endRow: 1, startColumn: 3, endColumn: 4 });});++ it("Should 'insert after' work, copy style", async () => {+ selectColumn(0, 0);++ const result = await commandService.executeCommand(InsertColAfterCommand.id);+ expect(result).toBeTruthy();++ // Insert column style+ expect(getCellStyle(0, 1)).toBe('s1');+ });});describe('Remove rows', () => {@@ -385,6 +402,7 @@ const TEST_ROW_COL_INSERTION_DEMO: IWorkbookData = {name: '',sheetOrder: [],styles: {+ s1: { bg: { rgb: '#ff0000' } },s2: { bl: 0 },s3: { bl: 1 },s4: { fs: 12 },diff --git a/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.tsindex 807826ef9c..20ed86b43b 100644--- a/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/move-rows-cols.command.spec.ts@@ -217,6 +217,30 @@ describe('Test move rows cols', () => {});});+ it('Should move forward works with range', async () => {+ selectRow(2, 2);++ const result = await commandService.executeCommand<IMoveRowsCommandParams>(MoveRowsCommand.id, {+ fromRange: { ...cellToRange(18, 1), endRow: 19 },+ toRange: { ...cellToRange(1, 1), endRow: 2 },+ range: { startRow: 18, startColumn: 0, endRow: 19, endColumn: 19, rangeType: RANGE_TYPE.ROW },+ });+ expect(result).toEqual(true);+ expect(getCellInfo(0, 0)?.v).toEqual('A1');+ expect(getCellInfo(3, 1)?.v).toEqual('B2');+ expect(getMergedInfo(3, 1)).toEqual({ startRow: 3, endRow: 3, startColumn: 1, endColumn: 2 });+ expect(getMergedInfo(4, 1)).toEqual({ startRow: 4, endRow: 5, startColumn: 1, endColumn: 1 });+ expect(getRowHeight(1)).toBe(24);+ expect(getRowHeight(3)).toBe(30);+ expect(getCurrentSelection()).toEqual({+ startRow: 2,+ endRow: 2,+ startColumn: 0,+ endColumn: 19,+ rangeType: RANGE_TYPE.ROW,+ });+ });+it('Should forbidding moving when parts of merged cells are selected', async () => {selectRow(2, 2);@@ -299,6 +323,30 @@ describe('Test move rows cols', () => {});});+ it('Should move forward works with range', async () => {+ selectColumn(2, 2);++ const result = await commandService.executeCommand<IMoveColsCommandParams>(MoveColsCommand.id, {+ fromRange: { ...cellToRange(1, 18), endColumn: 19 },+ toRange: { ...cellToRange(1, 1), endColumn: 2 },+ range: { startRow: 0, startColumn: 18, endRow: 19, endColumn: 19, rangeType: RANGE_TYPE.COLUMN },+ });+ expect(result).toEqual(true);+ expect(getCellInfo(0, 0)?.v).toEqual('A1');+ expect(getCellInfo(1, 3)?.v).toEqual('B2');+ expect(getMergedInfo(1, 3)).toEqual({ startRow: 1, endRow: 1, startColumn: 3, endColumn: 4 });+ expect(getMergedInfo(2, 3)).toEqual({ startRow: 2, endRow: 3, startColumn: 3, endColumn: 3 });+ expect(getColWidth(1)).toBe(88);+ expect(getColWidth(3)).toBe(30);+ expect(getCurrentSelection()).toEqual({+ startRow: 0,+ endRow: 19,+ startColumn: 2,+ endColumn: 2,+ rangeType: RANGE_TYPE.COLUMN,+ });+ });+it('Should forbidding moving when parts of merged cells are selected', async () => {selectColumn(2, 2);diff --git a/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.tsindex 73ae804cf6..0a03370e56 100644--- a/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts@@ -133,4 +133,12 @@ describe('Test set col width commands', () => {expect(getColumnWidth(2)).toBe(40);expect(getColumnWidth(5)).toBe(40);});++ it('Direct change col widths with ranges', async () => {+ await commandService.executeCommand<ISetColWidthCommandParams>(SetColWidthCommand.id, {+ value: 50,+ ranges: [{ startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 }],+ });+ expect(getColumnWidth(1)).toBe(50);+ });});diff --git a/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.tsindex 80d7b6c57c..849769126b 100644--- a/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/set-row-col-visible.command.spec.ts@@ -153,8 +153,12 @@ describe('Test row col hide/unhine commands', () => {await commandService.executeCommand(RedoCommand.id);expect(getRowRawVisible(0)).toBeFalsy();- selectRow(2, 2);- await commandService.executeCommand(SetRowHiddenCommand.id);+ // Specify the parameter ranges as the third row+ await commandService.executeCommand(SetRowHiddenCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ ranges: [{ startRow: 2, startColumn: 2, endRow: 2, endColumn: 2, rangeType: RANGE_TYPE.ROW }],+ });expect(getRowRawVisible(2)).toBeFalsy();// select a range and invoke unhide command will unhide all@@ -212,8 +216,12 @@ describe('Test row col hide/unhine commands', () => {await commandService.executeCommand(RedoCommand.id);expect(getColVisible(0)).toBeFalsy();- selectColumn(2, 2);- await commandService.executeCommand(SetColHiddenCommand.id);+ // Specify the parameter ranges as the third column+ await commandService.executeCommand(SetColHiddenCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ ranges: [{ startRow: 2, startColumn: 2, endRow: 2, endColumn: 2, rangeType: RANGE_TYPE.COLUMN }],+ });expect(getColVisible(2)).toBeFalsy();// select a range and invoke unhide command will unhide alldiff --git a/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.tsindex 95656c5ffd..9037efdace 100644--- a/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/set-row-height.command.spec.ts@@ -171,6 +171,15 @@ describe('Test set row height commands', () => {expect(getRowHeight(5)).toBe(77);});+ it('Direct change row heights with ranges', async () => {+ await commandService.executeCommand<ISetRowHeightCommandParams>(SetRowHeightCommand.id, {+ value: 88,+ ranges: [{ startRow: 2, endRow: 2, startColumn: 0, endColumn: 0 }],+ });+ expect(getRowHeight(2)).toBe(88);+ expect(getRowIsAutoHeight(2)).toBe(BooleanNumber.FALSE);+ });+describe('Set fit content in ranges', () => {it('Should change all rows ia to true in selections', async () => {await commandService.executeCommand(SetWorksheetRowIsAutoHeightCommand.id);diff --git a/packages/sheets/src/commands/commands/insert-row-col.command.ts b/packages/sheets/src/commands/commands/insert-row-col.command.tsindex 2f424182bf..0008ca964f 100644--- a/packages/sheets/src/commands/commands/insert-row-col.command.ts+++ b/packages/sheets/src/commands/commands/insert-row-col.command.ts@@ -22,7 +22,6 @@ import {ICommandService,IUndoRedoService,IUniverInstanceService,- Range,RANGE_TYPE,sequenceExecute,UniverInstanceType,@@ -44,7 +43,7 @@ import {} from '../mutations/insert-row-col.mutation';import { RemoveColMutation, RemoveRowMutation } from '../mutations/remove-row-col.mutation';import { SetRangeValuesMutation } from '../mutations/set-range-values.mutation';-import { followSelectionOperation } from './utils/selection-utils';+import { copyRangeStyles, followSelectionOperation } from './utils/selection-utils';export interface IInsertRowCommandParams {unitId: string;@@ -181,27 +180,23 @@ export const InsertRowBeforeCommand: ICommand = {const unitId = workbook.getUnitId();const subUnitId = worksheet.getSheetId();- const rowCount = range.endRow - range.startRow + 1;- const cellValue: IObjectMatrixPrimitiveType<ICellData> = {};- Range.foreach(range, (row, col) => {- const cell = worksheet.getCell(row, col);- if (!cell || !cell.s) {- return;- }- if (!cellValue[row]) {- cellValue[row] = {};- }- cellValue[row][col] = { s: cell.s };- });++ const { startRow, endRow } = range;+ const startColumn = 0;+ const endColumn = worksheet.getColumnCount() - 1;++ // copy styles from the row above+ const cellValue = copyRangeStyles(worksheet, startRow, endRow, startColumn, endColumn, true, startRow - 1);+const insertRowParams: IInsertRowCommandParams = {unitId,subUnitId,direction: Direction.UP,range: {- startRow: range.startRow,- endRow: range.startRow + rowCount - 1,- startColumn: 0,- endColumn: worksheet.getColumnCount() - 1,+ startRow,+ endRow,+ startColumn,+ endColumn,},cellValue,};@@ -241,17 +236,26 @@ export const InsertRowAfterCommand: ICommand = {const subUnitId = worksheet.getSheetId();const count = range.endRow - range.startRow + 1;+ const startRow = range.endRow + 1;+ const endRow = range.endRow + count;+ const startColumn = 0;+ const endColumn = worksheet.getColumnCount() - 1;++ // copy styles from the row below+ const cellValue = copyRangeStyles(worksheet, startRow, endRow, startColumn, endColumn, true, range.endRow);+const insertRowParams: IInsertRowCommandParams = {unitId,subUnitId,direction: Direction.DOWN,range: {- startRow: range.endRow + 1,- endRow: range.endRow + count,- startColumn: 0,- endColumn: worksheet.getColumnCount() - 1,+ startRow,+ endRow,+ startColumn,+ endColumn,rangeType: RANGE_TYPE.ROW,},+ cellValue,};return accessor.get(ICommandService).executeCommand(InsertRowCommand.id, insertRowParams);@@ -375,27 +379,23 @@ export const InsertColBeforeCommand: ICommand = {const unitId = workbook.getUnitId();const subUnitId = worksheet.getSheetId();- const count = range.endColumn - range.startColumn + 1;- const cellValue: IObjectMatrixPrimitiveType<ICellData> = {};- Range.foreach(range, (row, col) => {- const cell = worksheet.getCell(row, col);- if (!cell || !cell.s) {- return;- }- if (!cellValue[row]) {- cellValue[row] = {};- }- cellValue[row][col] = { s: cell.s };- });++ const { startColumn, endColumn } = range;+ const startRow = 0;+ const endRow = worksheet.getRowCount() - 1;++ // copy styles from the column before+ const cellValue = copyRangeStyles(worksheet, startRow, endRow, startColumn, endColumn, false, startColumn - 1);+const insertColParams: IInsertColCommandParams = {unitId,subUnitId,direction: Direction.LEFT,range: {- startColumn: range.startColumn,- endColumn: range.startColumn + count - 1,- startRow: 0,- endRow: worksheet.getRowCount() - 1,+ startColumn,+ endColumn,+ startRow,+ endRow,rangeType: RANGE_TYPE.COLUMN,},cellValue,@@ -434,16 +434,25 @@ export const InsertColAfterCommand: ICommand = {const subUnitId = worksheet.getSheetId();const count = range.endColumn - range.startColumn + 1;+ const startColumn = range.endColumn + 1;+ const endColumn = range.endColumn + count;+ const startRow = 0;+ const endRow = worksheet.getRowCount() - 1;++ // copy styles from the column after+ const cellValue = copyRangeStyles(worksheet, startRow, endRow, startColumn, endColumn, false, range.endColumn);+const insertColParams: IInsertColCommandParams = {unitId,subUnitId,direction: Direction.RIGHT,range: {- startColumn: range.endColumn + 1,- endColumn: range.endColumn + count,- startRow: 0,- endRow: worksheet.getRowCount() - 1,+ startColumn,+ endColumn,+ startRow,+ endRow,},+ cellValue,};return accessor.get(ICommandService).executeCommand(InsertColCommand.id, insertColParams);diff --git a/packages/sheets/src/commands/commands/move-rows-cols.command.ts b/packages/sheets/src/commands/commands/move-rows-cols.command.tsindex e732403c8c..4258e56b54 100644--- a/packages/sheets/src/commands/commands/move-rows-cols.command.ts+++ b/packages/sheets/src/commands/commands/move-rows-cols.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IAccessor, ICommand, IRange, Workbook } from '@univerjs/core';+import type { IAccessor, ICommand, IRange } from '@univerjs/core';import {CommandType,ErrorService,@@ -25,7 +25,6 @@ import {RANGE_TYPE,Rectangle,sequenceExecute,- UniverInstanceType,} from '@univerjs/core';import { SheetsSelectionsService } from '../../services/selections/selection-manager.service';@@ -39,10 +38,15 @@ import {} from '../mutations/move-rows-cols.mutation';import type { ISetSelectionsOperationParams } from '../operations/selection.operation';import { SetSelectionsOperation } from '../operations/selection.operation';+import type { ISelectionWithStyle } from '../../basics';import { columnAcrossMergedCell, rowAcrossMergedCell } from './utils/merged-cell-util';import { alignToMergedCellsBorders, getPrimaryForRange } from './utils/selection-utils';+import { getSheetCommandTarget } from './utils/target-util';export interface IMoveRowsCommandParams {+ unitId?: string;+ subUnitId?: string;+ range?: IRange; // for facade to use, accepting user parametersfromRange: IRange;toRange: IRange;}@@ -54,13 +58,18 @@ export const MoveRowsCommandId = 'sheet.command.move-rows' as const;export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {id: MoveRowsCommandId,type: CommandType.COMMAND,+ // eslint-disable-next-line max-lines-per-functionhandler: async (accessor: IAccessor, params: IMoveRowsCommandParams) => {const selectionManagerService = accessor.get(SheetsSelectionsService);- const selections = selectionManagerService.getCurrentSelections();const {fromRange: { startRow: fromRow },toRange: { startRow: toRow },+ range,} = params;++ // user can specify the range to move, or use the current selection+ const selections = range ? [covertRangeToSelection(range)] : selectionManagerService.getCurrentSelections();+const filteredSelections = selections?.filter((selection) =>selection.range.rangeType === RANGE_TYPE.ROW &&@@ -73,14 +82,11 @@ export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {const sheetInterceptorService = accessor.get(SheetInterceptorService);const univerInstanceService = accessor.get(IUniverInstanceService);- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);- if (!workbook) {- return false;- }- const worksheet = workbook.getActiveSheet();- if (!worksheet) {- return false;- }++ const target = getSheetCommandTarget(univerInstanceService, params);+ if (!target) return false;++ const { workbook, worksheet } = target;const unitId = workbook.getUnitId();const subUnitId = worksheet.getSheetId();@@ -114,33 +120,6 @@ export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {};const undoMoveRowsParams = MoveRowsMutationUndoFactory(accessor, moveRowsParams);- // we could just move the merged cells because other situations are not allowed- // we should only deal with merged cell that is between the range of the rows to move- const movedLength = toRow - fromRow;- const moveBackward = movedLength < 0;- const count = rangeToMove.endRow - rangeToMove.startRow + 1;-- // deal with selections- const destSelection: IRange = moveBackward- ? destinationRange- : {- ...destinationRange,- startRow: destinationRange.startRow - count,- endRow: destinationRange.endRow - count,- };- const setSelectionsParam: ISetSelectionsOperationParams = {- unitId,- subUnitId,-- selections: [{ range: destSelection, primary: getPrimaryForRange(destSelection, worksheet), style: null }],- };- const undoSetSelectionsParam: ISetSelectionsOperationParams = {- unitId,- subUnitId,-- selections: [{ range: rangeToMove, primary: beforePrimary, style: null }],- };-const commandService = accessor.get(ICommandService);const interceptorCommands = sheetInterceptorService.onCommandExecute({ id: MoveRowsCommand.id, params });@@ -148,17 +127,50 @@ export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {const redos = [...(interceptorCommands.preRedos ?? []),{ id: MoveRowsMutation.id, params: moveRowsParams },- { id: SetSelectionsOperation.id, params: setSelectionsParam },- ...interceptorCommands.redos,];const undos = [...(interceptorCommands.preUndos ?? []),{ id: MoveRowsMutation.id, params: undoMoveRowsParams },- { id: SetSelectionsOperation.id, params: undoSetSelectionsParam },- ...interceptorCommands.undos,];+ // Handle selection in user interaction, not when using the Facade API+ if (beforePrimary) {+ // we could just move the merged cells because other situations are not allowed+ // we should only deal with merged cell that is between the range of the rows to move+ const movedLength = toRow - fromRow;+ const moveBackward = movedLength < 0;+ const count = rangeToMove.endRow - rangeToMove.startRow + 1;++ // deal with selections+ const destSelection: IRange = moveBackward+ ? destinationRange+ : {+ ...destinationRange,+ startRow: destinationRange.startRow - count,+ endRow: destinationRange.endRow - count,+ };++ const setSelectionsParam: ISetSelectionsOperationParams = {+ unitId,+ subUnitId,++ selections: [{ range: destSelection, primary: getPrimaryForRange(destSelection, worksheet), style: null }],+ };+ const undoSetSelectionsParam: ISetSelectionsOperationParams = {+ unitId,+ subUnitId,++ selections: [{ range: rangeToMove, primary: beforePrimary, style: null }],+ };++ redos.push({ id: SetSelectionsOperation.id, params: setSelectionsParam });+ undos.push({ id: SetSelectionsOperation.id, params: undoSetSelectionsParam });+ }++ redos.push(...interceptorCommands.redos);+ undos.push(...interceptorCommands.undos);+const result = sequenceExecute(redos, commandService);if (result.result) {@@ -176,6 +188,9 @@ export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {};export interface IMoveColsCommandParams {+ unitId?: string;+ subUnitId?: string;+ range?: IRange; // for facade to use, accepting user parametersfromRange: IRange;toRange: IRange;}@@ -184,13 +199,18 @@ export const MoveColsCommandId = 'sheet.command.move-cols' as const;export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {id: MoveColsCommandId,type: CommandType.COMMAND,+ // eslint-disable-next-line max-lines-per-functionhandler: async (accessor: IAccessor, params: IMoveColsCommandParams) => {const selectionManagerService = accessor.get(SheetsSelectionsService);- const selections = selectionManagerService.getCurrentSelections();const {fromRange: { startColumn: fromCol },toRange: { startColumn: toCol },+ range,} = params;++ // user can specify the range to move, or use the current selection+ const selections = range ? [covertRangeToSelection(range)] : selectionManagerService.getCurrentSelections();+const filteredSelections = selections?.filter((selection) =>selection.range.rangeType === RANGE_TYPE.COLUMN &&@@ -203,14 +223,11 @@ export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {const sheetInterceptorService = accessor.get(SheetInterceptorService);const univerInstanceService = accessor.get(IUniverInstanceService);- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);- if (!workbook) {- return false;- }- const worksheet = workbook.getActiveSheet();- if (!worksheet) {- return false;- }++ const target = getSheetCommandTarget(univerInstanceService, params);+ if (!target) return false;++ const { workbook, worksheet } = target;const unitId = workbook.getUnitId();const subUnitId = worksheet.getSheetId();@@ -244,33 +261,6 @@ export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {};const undoMoveColsParams = MoveColsMutationUndoFactory(accessor, moveColsParams);- // we could just move the merged cells because other situations are not allowed- // we should only deal with merged cell that is between the range of the cols to move- const count = rangeToMove.endColumn - rangeToMove.startColumn + 1;- const movedLength = toCol - fromCol;- const moveBackward = movedLength < 0;-- // deal with selections- const destSelection: IRange = moveBackward- ? destinationRange- : {- ...destinationRange,- startColumn: destinationRange.startColumn - count,- endColumn: destinationRange.endColumn - count,- };- const setSelectionsParam: ISetSelectionsOperationParams = {- unitId,- subUnitId,-- selections: [{ range: destSelection, primary: getPrimaryForRange(destSelection, worksheet), style: null }],- };- const undoSetSelectionsParam: ISetSelectionsOperationParams = {- unitId,- subUnitId,-- selections: [{ range: rangeToMove, primary: beforePrimary, style: null }],- };-const commandService = accessor.get(ICommandService);const interceptorCommands = sheetInterceptorService.onCommandExecute({ id: MoveColsCommand.id, params });@@ -278,17 +268,49 @@ export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {const redos = [...(interceptorCommands.preRedos ?? []),{ id: MoveColsMutation.id, params: moveColsParams },- { id: SetSelectionsOperation.id, params: setSelectionsParam },- ...interceptorCommands.redos,];const undos = [...(interceptorCommands.preUndos ?? []),{ id: MoveColsMutation.id, params: undoMoveColsParams },- { id: SetSelectionsOperation.id, params: undoSetSelectionsParam },- ...interceptorCommands.undos,];+ // Handle selection in user interaction, not when using the Facade API+ if (beforePrimary) {+ // we could just move the merged cells because other situations are not allowed+ // we should only deal with merged cell that is between the range of the cols to move+ const count = rangeToMove.endColumn - rangeToMove.startColumn + 1;+ const movedLength = toCol - fromCol;+ const moveBackward = movedLength < 0;++ // deal with selections+ const destSelection: IRange = moveBackward+ ? destinationRange+ : {+ ...destinationRange,+ startColumn: destinationRange.startColumn - count,+ endColumn: destinationRange.endColumn - count,+ };+ const setSelectionsParam: ISetSelectionsOperationParams = {+ unitId,+ subUnitId,++ selections: [{ range: destSelection, primary: getPrimaryForRange(destSelection, worksheet), style: null }],+ };+ const undoSetSelectionsParam: ISetSelectionsOperationParams = {+ unitId,+ subUnitId,++ selections: [{ range: rangeToMove, primary: beforePrimary, style: null }],+ };++ redos.push({ id: SetSelectionsOperation.id, params: setSelectionsParam });+ undos.push({ id: SetSelectionsOperation.id, params: undoSetSelectionsParam });+ }++ redos.push(...interceptorCommands.redos);+ undos.push(...interceptorCommands.undos);+const result = sequenceExecute(redos, commandService);if (result.result) {@@ -304,3 +326,11 @@ export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {return true;},};++function covertRangeToSelection(range: IRange): ISelectionWithStyle {+ return {+ range,+ primary: null,+ style: null,+ };+}diff --git a/packages/sheets/src/commands/commands/set-col-visible.command.ts b/packages/sheets/src/commands/commands/set-col-visible.command.tsindex b6dd96c021..53723647d5 100644--- a/packages/sheets/src/commands/commands/set-col-visible.command.ts+++ b/packages/sheets/src/commands/commands/set-col-visible.command.ts@@ -142,19 +142,25 @@ export const SetSelectedColsVisibleCommand: ICommand = {},};+export interface ISetColHiddenCommandParams {+ unitId?: string;+ subUnitId?: string;+ ranges?: IRange[];+}+export const SetColHiddenCommand: ICommand = {type: CommandType.COMMAND,id: 'sheet.command.set-col-hidden',- handler: async (accessor: IAccessor) => {+ handler: async (accessor: IAccessor, params?: ISetColHiddenCommandParams) => {const selectionManagerService = accessor.get(SheetsSelectionsService);const sheetInterceptorService = accessor.get(SheetInterceptorService);const univerInstanceService = accessor.get(IUniverInstanceService);const commandService = accessor.get(ICommandService);- let ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);+ let ranges = params?.ranges?.length ? params.ranges : selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);if (!ranges?.length) return false;- const target = getSheetCommandTarget(univerInstanceService);+ const target = getSheetCommandTarget(univerInstanceService, params);if (!target) return false;const { worksheet, unitId, subUnitId } = target;diff --git a/packages/sheets/src/commands/commands/set-row-visible.command.ts b/packages/sheets/src/commands/commands/set-row-visible.command.tsindex 885f8f967e..7da6cde5e1 100644--- a/packages/sheets/src/commands/commands/set-row-visible.command.ts+++ b/packages/sheets/src/commands/commands/set-row-visible.command.ts@@ -141,10 +141,16 @@ export const SetSelectedRowsVisibleCommand: ICommand = {},};-export const SetRowHiddenCommand: ICommand = {+export interface ISetRowHiddenCommandParams {+ unitId?: string;+ subUnitId?: string;+ ranges?: IRange[];+}++export const SetRowHiddenCommand: ICommand<ISetRowHiddenCommandParams> = {type: CommandType.COMMAND,id: 'sheet.command.set-rows-hidden',- handler: async (accessor: IAccessor) => {+ handler: async (accessor: IAccessor, params?: ISetRowHiddenCommandParams) => {const selectionManagerService = accessor.get(SheetsSelectionsService);const commandService = accessor.get(ICommandService);const undoRedoService = accessor.get(IUndoRedoService);@@ -152,10 +158,10 @@ export const SetRowHiddenCommand: ICommand = {const sheetInterceptorService = accessor.get(SheetInterceptorService);// Ranges should be divided by already hidden rows.- let ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);+ let ranges = params?.ranges?.length ? params.ranges : selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);if (!ranges?.length) return false;- const target = getSheetCommandTarget(univerInstanceService);+ const target = getSheetCommandTarget(univerInstanceService, params);if (!target) return false;ranges = divideRangesByHiddenRows(target.worksheet, ranges);diff --git a/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts b/packages/sheets/src/commands/commands/set-worksheet-col-width.command.tsindex 40288a3396..51e69f909b 100644--- a/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts+++ b/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts@@ -146,6 +146,9 @@ export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> =};export interface ISetColWidthCommandParams {+ unitId?: string;+ subUnitId?: string;+ ranges?: IRange[];value: number;}@@ -158,10 +161,11 @@ export const SetColWidthCommand: ICommand = {const undoRedoService = accessor.get(IUndoRedoService);const sheetInterceptorService = accessor.get(SheetInterceptorService);- const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);+ // user can specify the ranges to set col width, if not, use current selections+ const selections = params?.ranges?.length ? params.ranges : selectionManagerService.getCurrentSelections()?.map((s) => s.range);if (!selections?.length) return false;- const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), params);if (!target) return false;const { subUnitId, unitId } = target;diff --git a/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts b/packages/sheets/src/commands/commands/set-worksheet-row-height.command.tsindex 57ae5ce03f..2b3fff832a 100644--- a/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts+++ b/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts@@ -189,8 +189,12 @@ export const DeltaRowHeightCommand: ICommand = {};export interface ISetRowHeightCommandParams {+ unitId?: string;+ subUnitId?: string;+ ranges?: IRange[]; // For Facade APIvalue: number;}+export const SetRowHeightCommand: ICommand = {type: CommandType.COMMAND,id: 'sheet.command.set-row-height',@@ -202,12 +206,13 @@ export const SetRowHeightCommand: ICommand = {const univerInstanceService = accessor.get(IUniverInstanceService);const sheetInterceptorService = accessor.get(SheetInterceptorService);- const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);+ // user can specify the ranges to set row height, if not, use the current selection+ const selections = params?.ranges?.length ? params.ranges : selectionManagerService.getCurrentSelections()?.map((s) => s.range);if (!selections?.length) {return false;}- const target = getSheetCommandTarget(univerInstanceService);+ const target = getSheetCommandTarget(univerInstanceService, params);if (!target) return false;const { unitId, subUnitId } = target;@@ -288,35 +293,25 @@ export const SetRowHeightCommand: ICommand = {};export interface ISetWorksheetRowIsAutoHeightCommandParams {- anchorRow?: number;+ unitId?: string;+ subUnitId?: string;+ ranges?: IRange[]; // For Facade API}export const SetWorksheetRowIsAutoHeightCommand: ICommand = {type: CommandType.COMMAND,id: 'sheet.command.set-row-is-auto-height',- handler: async (accessor: IAccessor, params: ISetWorksheetRowIsAutoHeightCommandParams) => {+ handler: async (accessor: IAccessor, params?: ISetWorksheetRowIsAutoHeightCommandParams) => {const commandService = accessor.get(ICommandService);const undoRedoService = accessor.get(IUndoRedoService);const selectionManagerService = accessor.get(SheetsSelectionsService);const univerInstanceService = accessor.get(IUniverInstanceService);- const target = getSheetCommandTarget(univerInstanceService);+ const target = getSheetCommandTarget(univerInstanceService, params);if (!target) return false;- const { unitId, subUnitId, worksheet } = target;- const { anchorRow } = params ?? {};-- const ranges =- anchorRow != null- ? [- {- startRow: anchorRow,- endRow: anchorRow,- startColumn: 0,- endColumn: worksheet.getMaxColumns() - 1,- },- ]- : selectionManagerService.getCurrentSelections()?.map((s) => s.range);+ const { unitId, subUnitId } = target;+ const ranges = params?.ranges?.length ? params.ranges : selectionManagerService.getCurrentSelections()?.map((s) => s.range);if (!ranges?.length) {return false;diff --git a/packages/sheets/src/commands/commands/utils/selection-utils.ts b/packages/sheets/src/commands/commands/utils/selection-utils.tsindex 418a98b688..acc9dcdade 100644--- a/packages/sheets/src/commands/commands/utils/selection-utils.ts+++ b/packages/sheets/src/commands/commands/utils/selection-utils.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IRange, ISelectionCell, Nullable, Workbook, Worksheet } from '@univerjs/core';+import type { ICellData, IObjectMatrixPrimitiveType, IRange, ISelectionCell, Nullable, Workbook, Worksheet } from '@univerjs/core';import { RANGE_TYPE, Rectangle, selectionToArray } from '@univerjs/core';import type { ISetSelectionsOperationParams } from '../../operations/selection.operation';@@ -233,3 +233,39 @@ export function createRangeIteratorWithSkipFilteredRows(sheet: Worksheet) {forOperableEach,};}++/**+ * Copy the styles of a range of cells to another range. Used for insert row and insert column.+ * @param worksheet+ * @param startRow+ * @param endRow+ * @param startColumn+ * @param endColumn+ * @param isRow+ * @param styleRowOrColumn+ * @returns+ */+export function copyRangeStyles(+ worksheet: Worksheet,+ startRow: number,+ endRow: number,+ startColumn: number,+ endColumn: number,+ isRow: boolean,+ styleRowOrColumn: number+): IObjectMatrixPrimitiveType<ICellData> {+ const cellValue: IObjectMatrixPrimitiveType<ICellData> = {};+ for (let row = startRow; row <= endRow; row++) {+ for (let column = startColumn; column <= endColumn; column++) {+ const cell = isRow ? worksheet.getCell(styleRowOrColumn, column) : worksheet.getCell(row, styleRowOrColumn);+ if (!cell || !cell.s) {+ continue;+ }+ if (!cellValue[row]) {+ cellValue[row] = {};+ }+ cellValue[row][column] = { s: cell.s };+ }+ }+ return cellValue;+}diff --git a/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts b/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.tsindex adc634f4aa..cfeadefc09 100644--- a/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts+++ b/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts@@ -159,7 +159,7 @@ export const SetWorksheetRowHeightMutation: IMutation<ISetWorksheetRowHeightMutaif (typeof rowHeight === 'number') {row.h = rowHeight;} else {- row.h = rowHeight[rowIndex] ?? defaultRowHeight;+ row.h = rowHeight[rowIndex] ?? defaultRowHeight; // Start from startRow}row.h = Math.min(MAXIMUM_ROW_HEIGHT, row.h);@@ -193,7 +193,7 @@ export const SetWorksheetRowIsAutoHeightMutation: IMutation<ISetWorksheetRowIsAuif (typeof autoHeightInfo === 'number') {row.ia = autoHeightInfo;} else {- row.ia = autoHeightInfo[rowIndex - startRow] ?? defaultRowIsAutoHeight;+ row.ia = autoHeightInfo[rowIndex] ?? defaultRowIsAutoHeight; // Start from startRow, same as SetWorksheetRowHeightMutation}}}diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex e4083b3845..33e1b3e950 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -168,6 +168,7 @@ export { RangeProtectionPermissionEditPoint } from './services/permission/permisexport { RangeProtectionPermissionViewPoint } from './services/permission/permission-point/range/view';export { generateNullCellValue, generateNullCell } from './basics/utils';+export { copyRangeStyles } from './commands/commands/utils/selection-utils';// #region - all commands