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
fix(sheets-filter): some filter bugs (#3199)
YuHongec698319f27b
diff --git a/packages/sheets-filter/src/controllers/__tests__/sheets-filter.controller.spec.ts b/packages/sheets-filter/src/controllers/__tests__/sheets-filter.controller.spec.tsnew file mode 100644index 0000000000..554cc0c3e7--- /dev/null+++ b/packages/sheets-filter/src/controllers/__tests__/sheets-filter.controller.spec.ts@@ -0,0 +1,283 @@+/**+ * 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 { IWorkbookData, Workbook } from '@univerjs/core';+import { ICommandService, Inject, Injector, IUniverInstanceService, LocaleType, Plugin, RANGE_TYPE, UndoCommand, Univer, UniverInstanceType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';+import { MoveColsCommand, MoveColsMutation, MoveRowsCommand, MoveRowsMutation, RefRangeService, SetRangeValuesMutation, SetSelectionsOperation, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';+import { SHEET_FILTER_SNAPSHOT_ID, SheetsFilterService } from '../../services/sheet-filter.service';+import { SheetsFilterController } from '../sheets-filter.controller';++function testWorkbookDataWithFilterFactory(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ cellData: {+ 0: {+ 0: {+ v: 'A1',+ },+ 1: {+ v: 'B1',+ },+ 2: {+ v: 'C1',+ },+ 3: {+ v: 'D1',+ },+ },+ 1: {+ 0: {+ v: 'A2',+ },+ 1: {+ v: 'B2',+ },+ 2: {+ v: 'C2',+ },+ 3: {+ v: 'D2',+ },+ },+ 2: {+ 0: {+ v: 'A3',+ },+ 1: {+ v: 'B3',+ },+ 2: {+ v: 'C3',+ },+ 3: {+ v: 'D3',+ },+ },+ 3: {+ 0: {+ v: 'A',+ },+ 1: {+ v: 'B',+ },+ 2: {+ v: 'C',+ },+ 3: {+ v: 'D',+ },+ },+ },+ name: 'Sheet-001',+ },+ },+ resources: [+ {+ name: SHEET_FILTER_SNAPSHOT_ID,+ data: JSON.stringify({+ sheet1: {+ ref: { startRow: 3, startColumn: 0, endRow: 5, endColumn: 5 },+ },+ }),+ },+ ],+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: [],+ styles: {},+ };+}++function createFilterControllerTestBed(workbookData?: IWorkbookData) {+ const univer = new Univer();+ const injector = univer.__getInjector();+ const get = injector.get.bind(injector);++ class SheetsFilterTestPlugin extends Plugin {+ static override type = UniverInstanceType.UNIVER_SHEET;+ static override pluginName = 'SheetsFilterTestPlugin';++ constructor(_config: unknown, @Inject(Injector) protected readonly _injector: Injector) {+ super();+ }++ override onStarting(): void {+ this._injector.add([RefRangeService]);+ this._injector.add([SheetsFilterService]);+ this._injector.add([SheetsFilterController]);+ this._injector.add([SheetsSelectionsService]);+ this._injector.add([SheetInterceptorService]);+ }++ override onReady(): void {+ this._injector.get(SheetsFilterController);+ }+ }++ univer.registerPlugin(SheetsFilterTestPlugin);++ const sheet = univer.createUniverSheet(workbookData || testWorkbookDataWithFilterFactory());++ const sheetsFilterService = get(SheetsFilterService);+ const commandService = get(ICommandService);++ ([+ MoveRowsCommand,+ MoveRowsMutation,+ MoveColsCommand,+ MoveColsMutation,+ SetSelectionsOperation,+ SetRangeValuesMutation,+ ]+ ).forEach((command) => commandService.registerCommand(command));++ return {+ univer,+ get,+ sheet,+ sheetsFilterService,+ commandService,+ };+}++describe('test controller of sheets filter', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;+ let sheetsFilterService: SheetsFilterService;+ let instanceService: IUniverInstanceService;++ beforeEach(() => {+ const testBed = createFilterControllerTestBed();+ univer = testBed.univer;+ get = testBed.get;++ commandService = get(ICommandService);+ sheetsFilterService = get(SheetsFilterService);+ instanceService = get(IUniverInstanceService);+ instanceService.setCurrentUnitForType('test');+ instanceService.focusUnit('test');+ });++ afterEach(() => {+ univer.dispose();+ });++ describe('test interceptor of move-rows-command', () => {+ it('should be success when move row before filter header', async () => {+ await commandService.executeCommand(SetSelectionsOperation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ selections: [+ {+ range: {+ rangeType: RANGE_TYPE.ROW,+ startRow: 0,+ endRow: 0,+ },+ },+ ],+ });+ const result = await commandService.executeCommand(MoveRowsCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ fromRange: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 5 },+ toRange: { startRow: 2, startColumn: 0, endRow: 2, endColumn: 5 },+ });+ expect(result).toBeTruthy();+ expect((sheetsFilterService as SheetsFilterService).getFilterModel('test', 'sheet1')!.getRange())+ .toEqual({ startRow: 3, startColumn: 0, endRow: 5, endColumn: 5 });+ const workbook = instanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(0, 0)?.v).toBe('A2');+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(1, 0)?.v).toBe('A1');+ });+ });++ describe('test interceptor of move-cols-command', () => {+ it('should be restored when undo move cols command', async () => {+ await commandService.executeCommand(SetSelectionsOperation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ selections: [+ {+ range: {+ rangeType: RANGE_TYPE.COLUMN,+ startRow: 0,+ endRow: 10,+ startColumn: 0,+ endColumn: 5,+ },+ },+ ],+ });+ const result = await commandService.executeCommand(MoveColsCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ fromRange: { startRow: 0, startColumn: 0, endRow: 10, endColumn: 5 },+ toRange: { startRow: 0, startColumn: 10, endRow: 10, endColumn: 15 },+ });+ expect(result).toBeTruthy();+ expect((sheetsFilterService as SheetsFilterService).getFilterModel('test', 'sheet1')!.getRange())+ .toEqual({ startRow: 3, startColumn: 4, endRow: 5, endColumn: 9 });++ expect(await commandService.executeCommand(UndoCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ })).toBeTruthy();+ expect((sheetsFilterService as SheetsFilterService).getFilterModel('test', 'sheet1')!.getRange())+ .toEqual({ startRow: 3, startColumn: 0, endRow: 5, endColumn: 5 });+ });+ });++ describe('test extend range of filter', () => {+ it('should not be extended when edit null', async () => {+ expect(await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 6: {+ 0: {+ f: null,+ },+ },+ },+ } as ISetRangeValuesMutationParams)).toBeTruthy();+ expect((sheetsFilterService as SheetsFilterService).getFilterModel('test', 'sheet1')!.getRange())+ .toEqual({ startRow: 3, startColumn: 0, endRow: 5, endColumn: 5 });+ });+ it('should be extended when edit not null', async () => {+ expect(await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 6: {+ 0: {+ v: 'test',+ },+ },+ },+ } as ISetRangeValuesMutationParams)).toBeTruthy();+ expect((sheetsFilterService as SheetsFilterService).getFilterModel('test', 'sheet1')!.getRange())+ .toEqual({ startRow: 3, startColumn: 0, endRow: 6, endColumn: 5 });+ });+ });+});diff --git a/packages/sheets-filter/src/controllers/sheets-filter.controller.ts b/packages/sheets-filter/src/controllers/sheets-filter.controller.tsindex fd68828c5b..ff66f157be 100644--- a/packages/sheets-filter/src/controllers/sheets-filter.controller.ts+++ b/packages/sheets-filter/src/controllers/sheets-filter.controller.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICommandInfo, IMutationInfo, IObjectArrayPrimitiveType, IRange, Nullable, Workbook } from '@univerjs/core';+import type { ICellData, ICommandInfo, IMutationInfo, IObjectArrayPrimitiveType, IRange, Nullable, Workbook } from '@univerjs/core';import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInstanceService, moveMatrixArray, Rectangle } from '@univerjs/core';import type { EffectRefRangeParams, IAddWorksheetMergeMutationParams, IInsertColCommandParams, IInsertRowCommandParams, IInsertRowMutationParams, IMoveColsCommandParams, IMoveRangeCommandParams, IMoveRowsCommandParams, IRemoveColMutationParams, IRemoveRowsMutationParams, IRemoveSheetCommandParams, ISetRangeValuesMutationParams, ISetWorksheetActivateCommandParams, ISheetCommandSharedParams } from '@univerjs/sheets';import { EffectRefRangId, expandToContinuousRange, getSheetCommandTarget, InsertColCommand, InsertRowCommand, InsertRowMutation, INTERCEPTOR_POINT, MoveRangeCommand, MoveRowsCommand, RefRangeService, RemoveColCommand, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, SetRangeValuesMutation, SetWorksheetActivateCommand, SheetInterceptorService } from '@univerjs/sheets';@@ -26,6 +26,7 @@ import type { FilterColumn } from '../models/filter-model';import { mergeSetFilterCriteria } from '../utils';export class SheetsFilterController extends Disposable {+ private _disposableCollection: DisposableCollection = new DisposableCollection();constructor(@ICommandService private readonly _commandService: ICommandService,@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,@@ -51,64 +52,10 @@ export class SheetsFilterController extends Disposable {].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));}- // eslint-disable-next-line max-lines-per-functionprivate _initInterceptors(): void {this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations: (command) => this._getUpdateFilter(command),}));-- const disposableCollection = new DisposableCollection();- const registerRefRange = (unitId: string, subUnitId: string) => {- const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);- if (!workbook) return;-- const workSheet = workbook?.getSheetBySheetId(subUnitId);- if (!workSheet) return;-- disposableCollection.dispose();- const range = this._sheetsFilterService.getFilterModel(unitId, subUnitId)?.getRange();- const handler = (config: EffectRefRangeParams) => {- switch (config.id) {- case InsertRowCommand.id: {- const params = config.params as IInsertRowCommandParams;- const _unitId = params.unitId || unitId;- const _subUnitId = params.subUnitId || subUnitId;- return this._handleInsertRowCommand(params, _unitId, _subUnitId);- }- case InsertColCommand.id: {- const params = config.params as IInsertColCommandParams;- const _unitId = params.unitId || unitId;- const _subUnitId = params.subUnitId || subUnitId;- return this._handleInsertColCommand(params, _unitId, _subUnitId);- }- case RemoveColCommand.id: {- const params = config.params as IRemoveColMutationParams;- return this._handleRemoveColCommand(params, unitId, subUnitId);- }- case RemoveRowCommand.id: {- const params = config.params as IRemoveRowsMutationParams;- return this._handleRemoveRowCommand(params, unitId, subUnitId);- }- case EffectRefRangId.MoveColsCommandId: {- const params = config.params as IMoveColsCommandParams;- return this._handleMoveColsCommand(params, unitId, subUnitId);- }- case EffectRefRangId.MoveRowsCommandId: {- const params = config.params as IMoveRowsCommandParams;- return this._handleMoveRowsCommand(params, unitId, subUnitId);- }- case MoveRangeCommand.id: {- const params = config.params as IMoveRangeCommandParams;- return this._handleMoveRangeCommand(params, unitId, subUnitId);- }- }- return { redos: [], undos: [] };- };-- if (range) {- disposableCollection.add(this._refRangeService.registerRefRange(range, handler, unitId, subUnitId));- }- };this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id === SetWorksheetActivateCommand.id) {const params = commandInfo.params as ISetWorksheetActivateCommandParams;@@ -117,7 +64,7 @@ export class SheetsFilterController extends Disposable {if (!sheetId || !unitId) {return;}- registerRefRange(unitId, sheetId);+ this._registerRefRange(unitId, sheetId);}if (commandInfo.id === SetSheetsFilterRangeMutation.id) {const params = commandInfo.params as IAddWorksheetMergeMutationParams;@@ -126,7 +73,7 @@ export class SheetsFilterController extends Disposable {if (!sheetId || !unitId) {return;}- registerRefRange(params.unitId, params.subUnitId);+ this._registerRefRange(params.unitId, params.subUnitId);}}));@@ -135,12 +82,61 @@ export class SheetsFilterController extends Disposable {const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);const sheet = workbook?.getActiveSheet();if (sheet) {- registerRefRange(unitId, sheet.getSheetId());+ this._registerRefRange(unitId, sheet.getSheetId());}}}));}+ private _registerRefRange(unitId: string, subUnitId: string): void {+ this._disposableCollection.dispose();+ const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);+ const workSheet = workbook?.getSheetBySheetId(subUnitId);+ if (!workbook || !workSheet) return;+ const range = this._sheetsFilterService.getFilterModel(unitId, subUnitId)?.getRange();+ const handler = (config: EffectRefRangeParams) => {+ switch (config.id) {+ case InsertRowCommand.id: {+ const params = config.params as IInsertRowCommandParams;+ const _unitId = params.unitId || unitId;+ const _subUnitId = params.subUnitId || subUnitId;+ return this._handleInsertRowCommand(params, _unitId, _subUnitId);+ }+ case InsertColCommand.id: {+ const params = config.params as IInsertColCommandParams;+ const _unitId = params.unitId || unitId;+ const _subUnitId = params.subUnitId || subUnitId;+ return this._handleInsertColCommand(params, _unitId, _subUnitId);+ }+ case RemoveColCommand.id: {+ const params = config.params as IRemoveColMutationParams;+ return this._handleRemoveColCommand(params, unitId, subUnitId);+ }+ case RemoveRowCommand.id: {+ const params = config.params as IRemoveRowsMutationParams;+ return this._handleRemoveRowCommand(params, unitId, subUnitId);+ }+ case EffectRefRangId.MoveColsCommandId: {+ const params = config.params as IMoveColsCommandParams;+ return this._handleMoveColsCommand(params, unitId, subUnitId);+ }+ case EffectRefRangId.MoveRowsCommandId: {+ const params = config.params as IMoveRowsCommandParams;+ return this._handleMoveRowsCommand(params, unitId, subUnitId);+ }+ case MoveRangeCommand.id: {+ const params = config.params as IMoveRangeCommandParams;+ return this._handleMoveRangeCommand(params, unitId, subUnitId);+ }+ }+ return { redos: [], undos: [] };+ };++ if (range) {+ this._disposableCollection.add(this._refRangeService.registerRefRange(range, handler, unitId, subUnitId));+ }+ }+private _getUpdateFilter(command: ICommandInfo) {const { id } = command;switch (id) {@@ -449,8 +445,17 @@ export class SheetsFilterController extends Disposable {col: newColIndex,criteria: { ...filter.serialize(), colId: newColIndex },};++ const undoSetCriteriaMutationParams: ISetSheetsFilterCriteriaMutationParams = {+ unitId,+ subUnitId,+ col: newColIndex,+ criteria: filterModel.getFilterColumn(newColIndex) ?+ { ...filterModel.getFilterColumn(newColIndex)?.serialize(), colId: newColIndex }+ : null,+ };redos.push({ id: SetSheetsFilterCriteriaMutation.id, params: setCriteriaMutationParams });- undos.push({ id: RemoveSheetsFilterMutation.id, params: { unitId, subUnitId, col: newColIndex, criteria: { ...filterModel.getFilterColumn(newColIndex)?.serialize(), colId: newColIndex } } });+ undos.push({ id: SetSheetsFilterCriteriaMutation.id, params: undoSetCriteriaMutationParams });}if (!filterCol[oldColIndex]?.filter) {const setCriteriaMutationParams: ISetSheetsFilterCriteriaMutationParams = {@@ -476,7 +481,7 @@ export class SheetsFilterController extends Disposable {},};redos.unshift({ id: SetSheetsFilterRangeMutation.id, params: setFilterRangeMutationParams });- undos.push({ id: SetSheetsFilterRangeMutation.id, params: { range: filterRange, unitId, subUnitId } });+ undos.unshift({ id: SetSheetsFilterRangeMutation.id, params: { range: filterRange, unitId, subUnitId } });}return {@@ -533,8 +538,8 @@ export class SheetsFilterController extends Disposable {endRow: newEnd,},};- redos.unshift({ id: SetSheetsFilterRangeMutation.id, params: setFilterRangeMutationParams });- undos.push({ id: SetSheetsFilterRangeMutation.id, params: { range: filterRange, unitId, subUnitId } });+ redos.push({ id: SetSheetsFilterRangeMutation.id, params: setFilterRangeMutationParams }, { id: ReCalcSheetsFilterMutation.id, params: { unitId, subUnitId } });+ undos.push({ id: SetSheetsFilterRangeMutation.id, params: { range: filterRange, unitId, subUnitId } }, { id: ReCalcSheetsFilterMutation.id, params: { unitId, subUnitId } });}return {redos,@@ -743,7 +748,7 @@ export class SheetsFilterController extends Disposable {if (cellValue) {for (let col = extendRegion.startColumn; col <= extendRegion.endColumn; col++) {const cell = cellValue?.[extendRegion.startRow]?.[col];- if (cell && Object.keys(cell).length !== 0) {+ if (cell && this._cellHasValue(cell)) {const worksheet = (this._univerInstanceService.getUnit(unitId) as Workbook)?.getSheetBySheetId(subUnitId);if (worksheet) {const extendedRange = expandToContinuousRange(extendRegion, { down: true }, worksheet);@@ -753,6 +758,7 @@ export class SheetsFilterController extends Disposable {...filterRange,endRow: extendedRange.endRow,});+ this._registerRefRange(unitId, subUnitId);}}}@@ -800,11 +806,20 @@ export class SheetsFilterController extends Disposable {const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);if (!filterModel) return;const filterRange = filterModel.getRange();- if (command.id === MoveRowsCommand.id && params.fromRange.startRow <= filterRange.startRow && params.fromRange.endRow < filterRange.endRow) {+ if (command.id === MoveRowsCommand.id && params.fromRange.startRow <= filterRange.startRow && params.fromRange.endRow < filterRange.endRow && params.fromRange.endRow >= filterRange.startRow) {this._sheetsFilterService.setFilterErrorMsg('sheets-filter.msg.filter-header-forbidden');throw new Error('[SheetsFilterController]: Cannot move header row of filter');}}));}++ private _cellHasValue(cell: ICellData): boolean {+ const values = Object.values(cell);+ if (values.length === 0 || values.every((v) => v == null)) {+ return false;+ }++ return true;+ }}diff --git a/packages/sheets/src/services/permission/workbook-permission/util.ts b/packages/sheets/src/services/permission/workbook-permission/util.tsindex 6130364509..4563d6531a 100644--- a/packages/sheets/src/services/permission/workbook-permission/util.ts+++ b/packages/sheets/src/services/permission/workbook-permission/util.ts@@ -53,4 +53,6 @@ export const defaultWorkbookPermissionPoints = [UnitAction.Share,UnitAction.MoveSheet,UnitAction.CopySheet,+ UnitAction.RecoverHistory,+ UnitAction.ViewHistory,];