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(sheets-table): move tables with cell ranges (#7832)
wpxp1234565316a89231a6
diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.tsindex 0ff08b3097..d9315a6c22 100644--- a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.ts+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.ts@@ -14,9 +14,85 @@* limitations under the License.*/-import { SetSelectionsOperation } from '@univerjs/sheets';-import { SelectAllCommand } from '@univerjs/sheets-ui';-import { describe, expect, it, vi } from 'vitest';+import type { IWorkbookData, Workbook } from '@univerjs/core';+import {+ ICommandService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ RANGE_TYPE,+ RedoCommand,+ Tools,+ UndoCommand,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ ActiveDirtyManagerService,+ CalculateFormulaService,+ DefinedNamesService,+ FormulaCurrentConfigService,+ FormulaDataModel,+ FormulaRuntimeService,+ HyperlinkEngineFormulaService,+ IActiveDirtyManagerService,+ ICalculateFormulaService,+ IDefinedNamesService,+ IFormulaCurrentConfigService,+ IFormulaRuntimeService,+ IHyperlinkEngineFormulaService,+ ISheetRowFilteredService,+ ISuperTableService,+ LexerTreeBuilder,+ RemoveSuperTableMutation,+ SetSuperTableMutation,+ SheetRowFilteredService,+ SuperTableService,+} from '@univerjs/engine-formula';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import {+ AddWorksheetMergeMutation,+ ExclusiveRangeService,+ IExclusiveRangeService,+ MoveRangeMutation,+ RangeProtectionRuleModel,+ RefRangeService,+ RemoveWorksheetMergeMutation,+ SetRangeValuesMutation,+ SetSelectionsOperation,+ SetWorksheetActiveOperation,+ SetWorksheetColWidthMutation,+ SetWorksheetRowAutoHeightMutation,+ SetWorksheetRowHeightMutation,+ SheetInterceptorService,+ SheetRangeThemeModel,+ SheetRangeThemeService,+ SheetSkeletonService,+ SheetsSelectionsService,+ WorkbookPermissionService,+ WorksheetPermissionService,+ WorksheetProtectionPointModel,+ WorksheetProtectionRuleModel,+ ZebraCrossingCacheController,+} from '@univerjs/sheets';+import { TableManager, UniverSheetsTablePlugin } from '@univerjs/sheets-table';+import enUS from '@univerjs/sheets-table/locale/en-US';+import {+ IMarkSelectionService,+ ISheetClipboardService,+ MarkSelectionService,+ SelectAllCommand,+ SheetClipboardController,+ SheetClipboardService,+} from '@univerjs/sheets-ui';+import {+ IClipboardInterfaceService,+ IMessageService,+ INotificationService,+ IPlatformService,+ PlatformService,+} from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { SheetTableSelectionController } from '../sheet-table-selection.controller';describe('SheetTableSelectionController', () => {@@ -91,3 +167,196 @@ describe('SheetTableSelectionController', () => {controller.dispose();});});++const TABLE_RANGE = { startRow: 2, endRow: 5, startColumn: 1, endColumn: 3 };++function createClipboardTestBed() {+ const data: IWorkbookData = {+ id: 'test',+ name: 'Tables',+ appVersion: '1.0.3',+ locale: LocaleType.EN_US,+ styles: {},+ sheetOrder: ['sheet1', 'sheet2'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Source',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 2: { 1: { v: 'Name' }, 2: { v: 'Amount' }, 3: { v: 'Tax' } },+ 3: { 1: { v: 'A' }, 2: { v: 10 }, 3: { v: 1 } },+ 4: { 1: { v: 'B' }, 2: { v: 20 }, 3: { v: 2 } },+ 5: { 1: { v: 'C' }, 2: { v: 30 }, 3: { v: 3 } },+ },+ },+ sheet2: { id: 'sheet2', name: 'Target', rowCount: 20, columnCount: 20, cellData: {} },+ },+ };+ const clipboard: IClipboardInterfaceService = {+ supportClipboard: true,+ write: async () => {},+ writeText: async () => {},+ read: async () => [],+ readText: async () => '',+ };+ const univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([SheetsSelectionsService]);+ injector.add([SheetInterceptorService]);+ injector.add([RangeProtectionRuleModel]);+ injector.add([WorksheetProtectionRuleModel]);+ injector.add([WorksheetProtectionPointModel]);+ injector.add([WorkbookPermissionService]);+ injector.add([WorksheetPermissionService]);+ injector.add([RefRangeService]);+ injector.add([SheetTableSelectionController]);+ injector.add([IExclusiveRangeService, { useClass: ExclusiveRangeService }]);+ injector.add([SheetRangeThemeModel]);+ injector.add([SheetRangeThemeService]);+ injector.add([ZebraCrossingCacheController]);+ injector.add([ISheetRowFilteredService, { useClass: SheetRowFilteredService }]);+ injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);+ injector.add([ISuperTableService, { useClass: SuperTableService }]);+ injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);+ injector.add([FormulaDataModel]);+ injector.add([LexerTreeBuilder]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);+ injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);+ injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([SheetSkeletonService]);+ injector.add([IMarkSelectionService, { useClass: MarkSelectionService }]);+ injector.add([ISheetClipboardService, { useClass: SheetClipboardService }]);+ injector.add([SheetClipboardController]);+ injector.add([IClipboardInterfaceService, { useValue: clipboard }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([INotificationService, { useValue: { show: () => ({ dispose() {} }) } }]);+ injector.add([IMessageService, { useValue: {+ show: () => ({ dispose() {} }),+ remove() {},+ removeAll() {},+ } }]);+ const plugin = injector.createInstance(UniverSheetsTablePlugin, {});+ plugin.onStarting();+ injector.get(SheetInterceptorService);+ const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, data);+ injector.get(IUniverInstanceService).focusUnit('test');+ const commands = injector.get(ICommandService);+ commands.registerCommand(SetSuperTableMutation);+ commands.registerCommand(RemoveSuperTableMutation);+ plugin.onReady();+ injector.get(SheetClipboardController);+ return { univer, sheet, get: injector.get.bind(injector) };+}++function expandTableSelection(bed: ReturnType<typeof createClipboardTestBed>) {+ const range = bed.get(SheetsSelectionsService).getCurrentLastSelection()!.range;+ const mutations = bed.get(SheetInterceptorService).onCommandExecute({ id: SelectAllCommand.id, params: { range } });+ for (const mutation of mutations.redos) {+ bed.get(ICommandService).syncExecuteCommand(mutation.id, mutation.params);+ }+}++describe('Table selection and clipboard interaction', () => {+ let bed: ReturnType<typeof createClipboardTestBed>;++ beforeEach(() => {+ bed = createClipboardTestBed();+ const { get } = bed;+ const locale = get(LocaleService);+ locale.load({ enUS });+ locale.setLocale(LocaleType.EN_US);+ locale.setDirection('ltr');+ get(WorkbookPermissionService);+ get(WorksheetPermissionService);+ get(SheetTableSelectionController);+ const commands = get(ICommandService);+ [+ MoveRangeMutation,+ SetSelectionsOperation,+ SetRangeValuesMutation,+ SetWorksheetActiveOperation,+ SetWorksheetColWidthMutation,+ SetWorksheetRowAutoHeightMutation,+ SetWorksheetRowHeightMutation,+ AddWorksheetMergeMutation,+ RemoveWorksheetMergeMutation,+ ].forEach((command) => commands.registerCommand(command));+ get(TableManager).addTable('test', 'sheet1', 'Orders', TABLE_RANGE, ['Name', 'Amount', 'Tax'], 'orders');+ get(SheetsSelectionsService).setSelections('test', 'sheet1', [{+ range: { startRow: 3, endRow: 3, startColumn: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ }]);+ });++ afterEach(() => bed.univer.dispose());++ it('selects the table body first, then includes the header', () => {+ const selections = bed.get(SheetsSelectionsService);+ expandTableSelection(bed);+ expect(selections.getCurrentLastSelection()!.range).toEqual({ ...TABLE_RANGE, startRow: 3 });+ expandTableSelection(bed);+ expect(selections.getCurrentLastSelection()!.range).toEqual(TABLE_RANGE);+ });++ it.each(['sheet1', 'sheet2'])('cuts a fully selected table to %s with one undo step', async (sheetId) => {+ const commands = bed.get(ICommandService);+ expandTableSelection(bed);+ expandTableSelection(bed);+ const manager = bed.get(TableManager);+ const table = manager.getTableById('test', 'orders')!;+ const before = Tools.deepClone(table.toJSON());+ const source = bed.sheet.getSheetBySheetId('sheet1')!;+ const values = source.getRange(2, 1, 5, 3).getValues();+ const clipboard = bed.get(ISheetClipboardService);+ expect(await clipboard.cut()).toBe(true);+ const copyId = clipboard.copyContentCache().getLastCopyId()!;+ const range = { startRow: 10, endRow: 13, startColumn: 5, endColumn: 7 };+ expect(await clipboard.pasteByCopyId(copyId, undefined, {+ unitId: 'test',+ subUnitId: sheetId,+ range,+ })).toBe(true);+ expect(manager.getTableById('test', 'orders')).toBe(table);+ expect(table.toJSON()).toEqual({ ...before, range });+ expect(table.getSubunitId()).toBe(sheetId);+ expect(bed.sheet.getSheetBySheetId(sheetId)!.getRange(10, 5, 13, 7).getValues()).toEqual(values);+ expect(source.getCellRaw(3, 1)).toBeUndefined();+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(table.getSubunitId()).toBe('sheet1');+ expect(table.toJSON()).toEqual(before);+ expect(source.getRange(2, 1, 5, 3).getValues()).toEqual(values);+ expect(await commands.executeCommand(RedoCommand.id)).toBe(true);+ expect(table.toJSON()).toEqual({ ...before, range });+ expect(table.getSubunitId()).toBe(sheetId);+ });++ it('cuts the table body across sheets as ordinary cells and keeps the table definition in place', async () => {+ expandTableSelection(bed);+ const before = Tools.deepClone(bed.sheet.getSnapshot());+ const table = bed.get(TableManager).getTableById('test', 'orders')!;+ const tableBefore = Tools.deepClone(table.toJSON());+ const source = bed.sheet.getSheetBySheetId('sheet1')!;+ const values = source.getRange(3, 1, 5, 3).getValues();+ const clipboard = bed.get(ISheetClipboardService);+ expect(await clipboard.cut()).toBe(true);+ const copyId = clipboard.copyContentCache().getLastCopyId()!;+ expect(await clipboard.pasteByCopyId(copyId, undefined, {+ unitId: 'test',+ subUnitId: 'sheet2',+ range: { startRow: 10, endRow: 12, startColumn: 5, endColumn: 7 },+ })).toBe(true);+ expect(bed.sheet.getSheetBySheetId('sheet2')!.getRange(10, 5, 12, 7).getValues()).toEqual(values);+ expect(source.getCellRaw(3, 1)).toBeUndefined();+ expect(source.getCellRaw(2, 1)?.v).toBe('Name');+ expect(table.toJSON()).toEqual(tableBefore);+ expect(table.getSubunitId()).toBe('sheet1');+ expect(await bed.get(ICommandService).executeCommand(UndoCommand.id)).toBe(true);+ expect(bed.sheet.getSnapshot()).toEqual(before);+ expect(table.toJSON()).toEqual(tableBefore);+ });+});diff --git a/packages/sheets-table/src/commands/mutations/move-sheet-table.mutation.ts b/packages/sheets-table/src/commands/mutations/move-sheet-table.mutation.tsnew file mode 100644index 0000000000..e6b8faa7ab--- /dev/null+++ b/packages/sheets-table/src/commands/mutations/move-sheet-table.mutation.ts@@ -0,0 +1,72 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IMutation, Workbook } from '@univerjs/core';+import type { ITableCalculatedColumnConfig, ITableRange } from '../../types/type';+import { CommandType, IUniverInstanceService } from '@univerjs/core';+import { TableManager } from '../../models/table-manager';++export interface IMoveSheetTableMutationParams {+ unitId: string;+ tableId: string;+ subUnitId: string;+ range: ITableRange;+ calculatedColumns?: ITableCalculatedColumnConfig[];+}++export const MoveSheetTableMutation: IMutation<IMoveSheetTableMutationParams> = {+ id: 'sheet.mutation.move-table',+ type: CommandType.MUTATION,+ handler: (accessor, params) => {+ if (!params) {+ return false;+ }++ const { unitId, tableId, subUnitId, range, calculatedColumns } = params;+ const manager = accessor.get(TableManager);+ const table = manager.getTableById(unitId, tableId);+ const workbook = accessor.get(IUniverInstanceService).getUnit<Workbook>(unitId);+ const worksheet = workbook?.getSheetBySheetId(subUnitId);+ if (!table || !worksheet) {+ return false;+ }++ // Cell and formula mutations run first, so the new anchor contains the cut-adjusted formula.+ const columns = calculatedColumns ?? table.getTableInfo().columns.map((column, columnIndex) => {+ const row = range.startRow + (table.isShowHeader() ? 1 : 0);+ const endRow = range.endRow - (table.isShowFooter() ? 1 : 0);+ const formula = column.formula && row <= endRow+ ? worksheet.getCellRaw(row, range.startColumn + columnIndex)?.f+ : undefined;+ return {+ columnId: column.id,+ formula: formula || column.formula,+ formulaIsArray: column.formulaIsArray,+ };+ }).filter((column) => column.formula);++ for (const config of columns) {+ const column = table.getColumn(config.columnId);+ if (column) {+ column.formula = config.formula;+ column.formulaIsArray = config.formulaIsArray;+ }+ }++ manager.moveTable(unitId, tableId, subUnitId, range);+ return true;+ },+};diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.tsindex 0da48b86fe..fe66c04cf7 100644--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts@@ -89,20 +89,49 @@ import {ValueNodeFactory,} from '@univerjs/engine-formula';import { Engine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';-import { InsertColMutation, InsertRowMutation, MoveRangeCommand, MoveRangeMutation, RangeProtectionRuleModel, RefRangeService, RemoveColByRangeCommand, RemoveColCommand, RemoveColMutation, RemoveRowByRangeCommand, RemoveRowCommand, RemoveRowMutation, SetRangeValuesCommand, SetRangeValuesMutation, SheetInterceptorService, SheetSkeletonService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';+import {+ InsertColMutation,+ InsertRowMutation,+ MoveRangeCommand,+ MoveRangeMutation,+ RangeProtectionRuleModel,+ RefRangeService,+ RemoveColByRangeCommand,+ RemoveColCommand,+ RemoveColMutation,+ RemoveRowByRangeCommand,+ RemoveRowCommand,+ RemoveRowMutation,+ SetRangeValuesCommand,+ SetRangeValuesMutation,+ SetSelectionsOperation,+ SheetInterceptorService,+ SheetSkeletonService,+ SheetsSelectionsService,+ WorkbookPermissionService,+ WorksheetPermissionService,+ WorksheetProtectionPointModel,+ WorksheetProtectionRuleModel,+} from '@univerjs/sheets';import { UpdateFormulaController } from '@univerjs/sheets-formula';import enUS from '@univerjs/sheets/locale/en-US';import zhCN from '@univerjs/sheets/locale/zh-CN';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DeleteSheetTableCommand } from '../../commands/commands/delete-sheet-table.command';import { SetSheetTableCommand } from '../../commands/commands/set-sheet-table.command';-import { SheetTableInsertColumnAtCommand, SheetTableRemoveColumnAtCommand } from '../../commands/commands/sheet-table-row-col.command';+import {+ SheetTableInsertColumnAtCommand,+ SheetTableRemoveColumnAtCommand,+} from '../../commands/commands/sheet-table-row-col.command';import { AddSheetTableMutation } from '../../commands/mutations/add-sheet-table.mutation';import { DeleteSheetTableMutation } from '../../commands/mutations/delete-sheet-table.mutation';+import { MoveSheetTableMutation } from '../../commands/mutations/move-sheet-table.mutation';import { SetSheetTableMutation } from '../../commands/mutations/set-sheet-table.mutation';+import { getCalculatedColumnFillMutation } from '../../commands/utils/calculated-column';import { TableManager } from '../../models/table-manager';import { SheetTableService } from '../../services/table.service';import { SheetTableFormulaController } from '../sheet-table-formula.controller';+import { SheetTableMoveController } from '../sheet-table-move.controller';import { SheetTableRefRangeController } from '../sheet-table-ref-range.controller';interface ITestBed {@@ -278,6 +307,7 @@ function createControllerTestBed() {[TableManager],[SheetTableService],[SheetTableFormulaController],+ [SheetTableMoveController],[SheetTableRefRangeController],[UpdateFormulaController],];@@ -341,6 +371,8 @@ describe('Sheet table formula integration', () => {commandService.registerCommand(RemoveColCommand);commandService.registerCommand(MoveRangeCommand);commandService.registerCommand(MoveRangeMutation);+ commandService.registerCommand(MoveSheetTableMutation);+ commandService.registerCommand(SetSelectionsOperation);commandService.registerCommand(RemoveRowByRangeCommand);commandService.registerCommand(RemoveColByRangeCommand);commandService.registerCommand(RemoveRowMutation);@@ -362,6 +394,7 @@ describe('Sheet table formula integration', () => {commandService.registerCommand(SetArrayFormulaDataMutation);testBed.injector.get(SheetTableFormulaController);+ testBed.injector.get(SheetTableMoveController);testBed.injector.get(SheetTableRefRangeController);testBed.injector.get(UpdateFormulaController);@@ -428,6 +461,54 @@ describe('Sheet table formula integration', () => {testBed?.univer.dispose();});+ it.each(['sheet1', 'sheet2'])('preserves structured references and calculated column anchors when moving to %s', async (sheetId) => {+ const manager = testBed.injector.get(TableManager);+ const table = manager.getTableById('test', 'orders-table')!;+ expect(await commandService.executeCommand(SetSheetTableCommand.id, {+ unitId: 'test',+ tableId: table.getId(),+ calculatedColumn: { columnId: 'tax-column', formula: '=SUM(B2,B2)' },+ })).toBe(true);+ const before = table.toJSON();+ const range = { startRow: 10, endRow: 13, startColumn: 5, endColumn: 7 };+ expect(await commandService.executeCommand(MoveRangeCommand.id, {+ fromUnitId: 'test',+ fromSubUnitId: 'sheet1',+ fromRange: table.getRange(),+ toUnitId: 'test',+ toSubUnitId: sheetId,+ toRange: range,+ })).toBe(true);+ expect(table.getSubunitId()).toBe(sheetId);+ expect(table.getRange()).toEqual(range);+ expect(table.getTableInfo().columns.map((column) => column.id)).toEqual(before.columns.map((column) => column.id));+ expect(getCellFormula(sheetId, 11, 7)).toBe('=SUM(G12,G12)');+ expect(table.getColumn('tax-column')!.formula).toBe('=SUM(G12,G12)');+ expect(calculate('=SUM(Orders[amount])', 5, 4, 'sheet1')).toBe(60);+ expect(calculateCellFormula('test', sheetId, 11, 7)).toBe(20);+ expect(calculateCellFormula('test', sheetId, 12, 7)).toBe(40);+ expect(calculateCellFormula('test', sheetId, 13, 7)).toBe(60);+ expect(getCellFormula('sheet1', 5, 4)).toBe('=SUM(Orders[amount])');+ const moved = table.toJSON();+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(table.toJSON()).toEqual(before);+ expect(table.getSubunitId()).toBe('sheet1');+ expect(calculateCellFormula('test', 'sheet1', 1, 2)).toBe(20);+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(table.toJSON()).toEqual(moved);+ expect(calculateCellFormula('test', sheetId, 11, 7)).toBe(20);+ const fill = getCalculatedColumnFillMutation(table, 'test', sheetId, 14, 14, () => testBed.injector.get(LexerTreeBuilder));+ expect(fill).toBeDefined();+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: sheetId,+ cellValue: { 14: { 6: { v: 40 } } },+ });+ commandService.syncExecuteCommand(fill!.id, fill!.params);+ expect(getCellFormula(sheetId, 14, 7)).toBe('=SUM(G15,G15)');+ expect(calculateCellFormula('test', sheetId, 14, 7)).toBe(80);+ });+it('should sync table formulas when a table is renamed, undone, and redone', async () => {expect(await commandService.executeCommand(SetSheetTableCommand.id, {unitId: 'test',diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-move.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-move.controller.spec.tsnew file mode 100644index 0000000000..e0335ca5a8--- /dev/null+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-move.controller.spec.ts@@ -0,0 +1,348 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IMutationInfo, IWorkbookData, Workbook } from '@univerjs/core';+import {+ CommandType,+ ICommandService,+ IPermissionService,+ IUndoRedoService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ RedoCommand,+ Tools,+ UndoCommand,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { ISheetRowFilteredService, SheetRowFilteredService } from '@univerjs/engine-formula';+import {+ ExclusiveRangeService,+ IExclusiveRangeService,+ MoveRangeCommand,+ MoveRangeMutation,+ RangeProtectionRuleModel,+ SetSelectionsOperation,+ SheetInterceptorService,+ SheetRangeThemeModel,+ SheetRangeThemeService,+ SheetsSelectionsService,+ WorkbookPermissionService,+ WorksheetEditPermission,+ WorksheetPermissionService,+ WorksheetProtectionPointModel,+ WorksheetProtectionRuleModel,+ ZebraCrossingCacheController,+} from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { MoveSheetTableMutation } from '../../commands/mutations/move-sheet-table.mutation';+import { FEATURE_TABLE_ID } from '../../const';+import enUS from '../../locale/en-US';+import { TableManager } from '../../models/table-manager';+import { TableColumnFilterTypeEnum } from '../../types/enum';+import { SheetTableMoveController } from '../sheet-table-move.controller';+import { SheetTableRangeController } from '../sheet-table-range.controller';+import { SheetsTableThemeController } from '../sheet-table-theme.controller';+import { SheetsTableController } from '../sheets-table.controller';+import { TableFilterController } from '../table-filter.controller';++const SOURCE_RANGE = { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 };++describe('SheetTableMoveController', () => {+ let univer: Univer;+ let workbook: Workbook;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([TableManager]);+ injector.add([SheetInterceptorService]);+ injector.add([SheetsSelectionsService]);+ injector.add([RangeProtectionRuleModel]);+ injector.add([WorksheetProtectionRuleModel]);+ injector.add([WorksheetProtectionPointModel]);+ injector.add([WorkbookPermissionService]);+ injector.add([WorksheetPermissionService]);+ injector.add([SheetTableMoveController]);+ injector.add([SheetTableRangeController]);+ injector.add([IExclusiveRangeService, { useClass: ExclusiveRangeService }]);+ injector.add([SheetRangeThemeModel]);+ injector.add([SheetRangeThemeService]);+ injector.add([SheetsTableThemeController]);+ injector.add([SheetsTableController]);+ injector.add([TableFilterController]);+ injector.add([ZebraCrossingCacheController]);+ injector.add([ISheetRowFilteredService, { useClass: SheetRowFilteredService }]);+ const locale = injector.get(LocaleService);+ locale.load({ enUS });+ locale.setLocale(LocaleType.EN_US);+ locale.setDirection('ltr');+ injector.get(WorkbookPermissionService);+ injector.get(WorksheetPermissionService);+ injector.get(SheetInterceptorService);+ workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'test',+ appVersion: '1.0.3',+ locale: LocaleType.EN_US,+ name: 'Tables',+ styles: {},+ sheetOrder: ['sheet1', 'sheet2'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Source',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: { 0: { v: 'Name' }, 1: { v: 'Amount' } },+ 1: { 0: { v: 'A' }, 1: { v: 10 } },+ 2: { 0: { v: 'B' }, 1: { v: 20 } },+ 3: { 0: { v: 'C' }, 1: { v: 30 } },+ },+ },+ sheet2: { id: 'sheet2', name: 'Target', rowCount: 20, columnCount: 20, cellData: {} },+ },+ });+ injector.get(IUniverInstanceService).focusUnit('test');+ const commands = injector.get(ICommandService);+ commands.registerCommand(MoveRangeCommand);+ commands.registerCommand(MoveRangeMutation);+ commands.registerCommand(MoveSheetTableMutation);+ commands.registerCommand(SetSelectionsOperation);+ });++ afterEach(() => univer.dispose());++ it.each([+ { sheetId: 'sheet1', range: { startRow: 5, endRow: 8, startColumn: 6, endColumn: 7 } },+ { sheetId: 'sheet1', range: { startRow: 1, endRow: 4, startColumn: 1, endColumn: 2 } },+ { sheetId: 'sheet2', range: { startRow: 5, endRow: 8, startColumn: 6, endColumn: 7 } },+ ])('moves cells and table identity together to $sheetId at $range', async ({ sheetId, range }) => {+ const injector = univer.__getInjector();+ injector.get(SheetTableMoveController);+ injector.get(SheetTableRangeController);+ injector.get(SheetsTableThemeController);+ injector.get(SheetsTableController);+ const manager = injector.get(TableManager);+ const tableId = manager.addTable('test', 'sheet1', 'Orders', SOURCE_RANGE, ['Name', 'Amount']);+ const table = manager.getTableById('test', tableId)!;+ table.setTableMeta({ source: 'invoices' });+ table.getTableColumnByIndex(0)!.setMeta({ custom: true });+ table.getTableColumnByIndex(0)!.showFilterButton = false;+ const before = Tools.deepClone(table.toJSON());+ const values = workbook.getSheetBySheetId('sheet1')!.getRange(0, 0, 3, 1).getValues();+ const commands = injector.get(ICommandService);+ expect(await commands.executeCommand(MoveRangeCommand.id, {+ fromUnitId: 'test',+ fromSubUnitId: 'sheet1',+ fromRange: SOURCE_RANGE,+ toUnitId: 'test',+ toSubUnitId: sheetId,+ toRange: range,+ })).toBe(true);+ expect(manager.getTableById('test', tableId)).toBe(table);+ expect(table.toJSON()).toEqual({ ...before, range });+ expect(table.getSubunitId()).toBe(sheetId);+ expect(workbook.getSheetBySheetId(sheetId)!.getRange(range.startRow, range.startColumn, range.endRow, range.endColumn).getValues()).toEqual(values);+ expect(injector.get(IExclusiveRangeService).getExclusiveRanges('test', sheetId, FEATURE_TABLE_ID))+ .toEqual([{ groupId: tableId, range }]);+ expect(injector.get(SheetsTableController).getContainerTableWithRange('test', sheetId, range)).toBe(table);+ expect(injector.get(SheetRangeThemeService).getAppliedRangeThemeStyle({ unitId: 'test', subUnitId: sheetId, range }))+ .toBe(before.options.tableStyleId);+ if (sheetId !== 'sheet1') {+ expect(injector.get(IExclusiveRangeService).getExclusiveRanges('test', 'sheet1', FEATURE_TABLE_ID)).toEqual([]);+ expect(injector.get(SheetsTableController).getContainerTableWithRange('test', 'sheet1', SOURCE_RANGE)).toBeUndefined();+ expect(injector.get(SheetRangeThemeService).getAppliedRangeThemeStyle({ unitId: 'test', subUnitId: 'sheet1', range: SOURCE_RANGE }))+ .toBeUndefined();+ }+ const persisted = Tools.deepClone(manager.toJSON('test'));+ expect(persisted[sheetId].tables[0]).toEqual({ ...before, range });+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(table.toJSON()).toEqual(before);+ expect(table.getSubunitId()).toBe('sheet1');+ expect(workbook.getSheetBySheetId('sheet1')!.getRange(0, 0, 3, 1).getValues()).toEqual(values);+ expect(await commands.executeCommand(RedoCommand.id)).toBe(true);+ expect(manager.toJSON('test')).toEqual(persisted);+ manager.deleteUnitId('test');+ manager.fromJSON('test', persisted);+ expect(manager.getTableById('test', tableId)!.toJSON()).toEqual({ ...before, range });+ expect(manager.getTableById('test', tableId)!.getSubunitId()).toBe(sheetId);+ });++ it('moves multiple complete tables with their surrounding cells', async () => {+ const injector = univer.__getInjector();+ injector.get(SheetTableMoveController);+ const manager = injector.get(TableManager);+ const first = manager.addTable('test', 'sheet1', 'First', SOURCE_RANGE, ['Name', 'Amount']);+ const second = manager.addTable('test', 'sheet1', 'Second', { ...SOURCE_RANGE, startColumn: 3, endColumn: 4 }, ['Name', 'Amount']);+ const commands = injector.get(ICommandService);+ expect(await commands.executeCommand(MoveRangeCommand.id, {+ fromRange: { ...SOURCE_RANGE, endColumn: 4 },+ toRange: { startRow: 6, endRow: 9, startColumn: 5, endColumn: 9 },+ })).toBe(true);+ expect(manager.getTableById('test', first)!.getRange()).toEqual({ startRow: 6, endRow: 9, startColumn: 5, endColumn: 6 });+ expect(manager.getTableById('test', second)!.getRange()).toEqual({ startRow: 6, endRow: 9, startColumn: 8, endColumn: 9 });+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(manager.getTableById('test', first)!.getRange()).toEqual(SOURCE_RANGE);+ expect(manager.getTableById('test', second)!.getRange()).toEqual({ ...SOURCE_RANGE, startColumn: 3, endColumn: 4 });+ });++ it('preserves the calculated-column template when only a header and footer remain', async () => {+ const injector = univer.__getInjector();+ injector.get(SheetTableMoveController);+ const manager = injector.get(TableManager);+ const range = { ...SOURCE_RANGE, endRow: 1 };+ const id = manager.addTable('test', 'sheet1', 'Empty', range, ['Name', 'Amount'], undefined, { showFooter: true });+ const column = manager.getTableById('test', id)!.getTableColumnByIndex(1)!;+ column.formula = '=A2';+ workbook.getSheetBySheetId('sheet1')!.getCellMatrix().setValue(1, 1, { f: '=SUM(A1:A1)' });+ expect(await injector.get(ICommandService).executeCommand(MoveRangeCommand.id, {+ fromRange: range,+ toRange: { startRow: 5, endRow: 6, startColumn: 4, endColumn: 5 },+ })).toBe(true);+ expect(column.formula).toBe('=A2');+ });++ it('replays a cross-sheet movement changeset with the same persisted table identity', async () => {+ const injector = univer.__getInjector();+ injector.get(SheetTableMoveController);+ const manager = injector.get(TableManager);+ manager.addTable('test', 'sheet1', 'Orders', SOURCE_RANGE, ['Name', 'Amount'], 'orders');+ const originalCells = Tools.deepClone(workbook.getSnapshot());+ const originalTables = Tools.deepClone(manager.toJSON('test'));+ const mutations: IMutationInfo[] = [];+ const commands = injector.get(ICommandService);+ const listener = commands.onCommandExecuted((command) => {+ if (command.type === CommandType.MUTATION && command.params) {+ mutations.push({ id: command.id, type: CommandType.MUTATION, params: Tools.deepClone(command.params) });+ }+ });+ expect(await commands.executeCommand(MoveRangeCommand.id, {+ fromRange: SOURCE_RANGE,+ toSubUnitId: 'sheet2',+ toRange: { startRow: 5, endRow: 8, startColumn: 4, endColumn: 5 },+ })).toBe(true);+ listener.dispose();+ const instances = injector.get(IUniverInstanceService);+ const peer = instances.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ ...originalCells,+ id: 'peer',+ }, { makeCurrent: false });+ manager.fromJSON('peer', originalTables);+ for (const mutation of mutations) {+ expect(commands.syncExecuteCommand(mutation.id, {+ ...mutation.params,+ unitId: 'peer',+ }, { fromChangeset: true })).toBe(true);+ }+ expect(manager.toJSON('peer')).toEqual(manager.toJSON('test'));+ expect(peer.getSheetBySheetId('sheet1')!.getCellMatrix().getMatrix())+ .toEqual(workbook.getSheetBySheetId('sheet1')!.getCellMatrix().getMatrix());+ expect(peer.getSheetBySheetId('sheet2')!.getCellMatrix().getMatrix())+ .toEqual(workbook.getSheetBySheetId('sheet2')!.getCellMatrix().getMatrix());+ });++ it('moves filtered rows to the destination and clears the old worksheet cache on undo and redo', async () => {+ const injector = univer.__getInjector();+ injector.get(SheetTableMoveController);+ injector.get(TableFilterController);+ const manager = injector.get(TableManager);+ const id = manager.addTable('test', 'sheet1', 'Orders', SOURCE_RANGE, ['Name', 'Amount']);+ manager.addFilter('test', id, 0, { filterType: TableColumnFilterTypeEnum.manual, values: ['A'] });+ const source = workbook.getSheetBySheetId('sheet1')!;+ const target = workbook.getSheetBySheetId('sheet2')!;+ expect(source.getRowFiltered(2)).toBe(true);+ expect(source.getRowFiltered(3)).toBe(true);+ const commands = injector.get(ICommandService);+ expect(await commands.executeCommand(MoveRangeCommand.id, {+ fromRange: SOURCE_RANGE,+ toSubUnitId: 'sheet2',+ toRange: { startRow: 5, endRow: 8, startColumn: 4, endColumn: 5 },+ })).toBe(true);+ expect(source.getRowFiltered(2)).toBe(false);+ expect(source.getRowFiltered(3)).toBe(false);+ expect(target.getRowFiltered(6)).toBe(false);+ expect(target.getRowFiltered(7)).toBe(true);+ expect(target.getRowFiltered(8)).toBe(true);+ expect(manager.toJSON('test').sheet2.tableFilteredOutRows).toEqual([7, 8]);+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(source.getRowFiltered(2)).toBe(true);+ expect(target.getRowFiltered(7)).toBe(false);+ expect(await commands.executeCommand(RedoCommand.id)).toBe(true);+ expect(source.getRowFiltered(2)).toBe(false);+ expect(target.getRowFiltered(7)).toBe(true);+ });++ it.each([+ { name: 'partial table outside its range', sheetId: 'sheet1', fromRange: { ...SOURCE_RANGE, startRow: 1 }, toRange: { startRow: 6, endRow: 8, startColumn: 5, endColumn: 6 } },+ { name: 'partial table across sheets', sheetId: 'sheet2', fromRange: { ...SOURCE_RANGE, startRow: 1 }, toRange: { startRow: 6, endRow: 8, startColumn: 5, endColumn: 6 } },+ { name: 'partial header', sheetId: 'sheet1', fromRange: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, toRange: { startRow: 1, endRow: 1, startColumn: 0, endColumn: 0 } },+ { name: 'cells into a table header', sheetId: 'sheet1', fromRange: { startRow: 1, endRow: 1, startColumn: 0, endColumn: 0 }, toRange: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } },+ ])('moves $name as ordinary cells without relocating the table', async ({ sheetId, fromRange, toRange }) => {+ const injector = univer.__getInjector();+ injector.get(SheetTableMoveController);+ const manager = injector.get(TableManager);+ manager.addTable('test', 'sheet1', 'Orders', SOURCE_RANGE, ['Name', 'Amount']);+ const before = Tools.deepClone(workbook.getSnapshot());+ const tables = Tools.deepClone(manager.toJSON('test'));+ const source = workbook.getSheetBySheetId('sheet1')!;+ const values = source.getRange(fromRange.startRow, fromRange.startColumn, fromRange.endRow, fromRange.endColumn).getValues();+ const commands = injector.get(ICommandService);+ expect(await commands.executeCommand(MoveRangeCommand.id, { fromRange, toRange, toSubUnitId: sheetId })).toBe(true);+ expect(workbook.getSheetBySheetId(sheetId)!.getRange(toRange.startRow, toRange.startColumn, toRange.endRow, toRange.endColumn).getValues()).toEqual(values);+ expect(manager.toJSON('test')).toEqual(tables);+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(workbook.getSnapshot()).toEqual(before);+ expect(manager.toJSON('test')).toEqual(tables);+ });++ it('rejects a complete table overlapping another table without moving cells or creating history', async () => {+ const injector = univer.__getInjector();+ injector.get(SheetTableMoveController);+ const manager = injector.get(TableManager);+ manager.addTable('test', 'sheet1', 'Orders', SOURCE_RANGE, ['Name', 'Amount']);+ const toRange = { startRow: 6, endRow: 9, startColumn: 5, endColumn: 6 };+ manager.addTable('test', 'sheet1', 'Other', toRange, ['Name', 'Amount']);+ const before = Tools.deepClone(workbook.getSnapshot());+ const tables = Tools.deepClone(manager.toJSON('test'));+ const history = injector.get(IUndoRedoService).getUndoRedoStatus('test');+ expect(await injector.get(ICommandService).executeCommand(MoveRangeCommand.id, { fromRange: SOURCE_RANGE, toRange })).toBe(false);+ expect(workbook.getSnapshot()).toEqual(before);+ expect(manager.toJSON('test')).toEqual(tables);+ expect(injector.get(IUndoRedoService).getUndoRedoStatus('test')).toEqual(history);+ });++ it('allows body edits and rejects migration to a protected worksheet', async () => {+ const injector = univer.__getInjector();+ injector.get(SheetTableMoveController);+ const manager = injector.get(TableManager);+ const id = manager.addTable('test', 'sheet1', 'Orders', SOURCE_RANGE, ['Name', 'Amount']);+ const commands = injector.get(ICommandService);+ expect(await commands.executeCommand(MoveRangeCommand.id, {+ fromRange: { startRow: 1, endRow: 1, startColumn: 0, endColumn: 0 },+ toRange: { startRow: 2, endRow: 2, startColumn: 0, endColumn: 0 },+ })).toBe(true);+ expect(manager.getTableById('test', id)!.getRange()).toEqual(SOURCE_RANGE);+ injector.get(IPermissionService).updatePermissionPoint(new WorksheetEditPermission('test', 'sheet2').id, false);+ expect(await commands.executeCommand(MoveRangeCommand.id, {+ fromRange: SOURCE_RANGE,+ toSubUnitId: 'sheet2',+ toRange: SOURCE_RANGE,+ })).toBe(false);+ expect(manager.getTableById('test', id)!.getSubunitId()).toBe('sheet1');+ });+});diff --git a/packages/sheets-table/src/controllers/sheet-table-move.controller.ts b/packages/sheets-table/src/controllers/sheet-table-move.controller.tsnew file mode 100644index 0000000000..0e5ec9cf5c--- /dev/null+++ b/packages/sheets-table/src/controllers/sheet-table-move.controller.ts@@ -0,0 +1,169 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IMutationInfo, Worksheet } from '@univerjs/core';+import type { IMoveRangeCommandParams } from '@univerjs/sheets';+import type { LocaleKey } from '../locale/types';+import {+ Disposable,+ ErrorService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ Rectangle,+} from '@univerjs/core';+import {+ checkRangesEditablePermission,+ getSheetCommandTarget,+ MoveRangeCommand,+ SheetInterceptorService,+} from '@univerjs/sheets';+import { MoveSheetTableMutation } from '../commands/mutations/move-sheet-table.mutation';+import { TableManager } from '../models/table-manager';++export class SheetTableMoveController extends Disposable {+ constructor(+ @Inject(TableManager) private readonly _tableManager: TableManager,+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(Injector) private readonly _injector: Injector,+ @Inject(LocaleService) private readonly _localeService: LocaleService,+ @Inject(ErrorService) private readonly _errorService: ErrorService+ ) {+ super();++ this.disposeWithMe(+ this._sheetInterceptorService.interceptBeforeCommand({+ performCheck: async (command) => command.id !== MoveRangeCommand.id || this._checkMove(command.params as IMoveRangeCommandParams),+ })+ );+ this.disposeWithMe(+ this._sheetInterceptorService.interceptAfterCommand({+ getMutations: (command) => command.id === MoveRangeCommand.id+ ? this._getMoveMutations(command.params as IMoveRangeCommandParams)+ : { redos: [], undos: [] },+ })+ );+ }++ private _getTargets(params: IMoveRangeCommandParams) {+ const source = getSheetCommandTarget(this._univerInstanceService, {+ unitId: params.fromUnitId ?? params.toUnitId,+ subUnitId: params.fromSubUnitId,+ });+ const target = getSheetCommandTarget(this._univerInstanceService, {+ unitId: params.toUnitId ?? source?.unitId,+ subUnitId: params.toSubUnitId ?? source?.subUnitId,+ });+ return { source, target };+ }++ private _checkMove(params: IMoveRangeCommandParams): boolean {+ const { source, target } = this._getTargets(params);+ if (!source || !target || source.unitId !== target.unitId) {+ return false;+ }++ const sourceTables = this._tableManager.getTablesBySubunitId(source.unitId, source.subUnitId);+ const movingTables = sourceTables.filter((table) => Rectangle.contains(params.fromRange, table.getRange()));++ if (!movingTables.length) {+ return true;+ }++ const targetTables = this._tableManager.getTablesBySubunitId(target.unitId, target.subUnitId);++ for (const table of targetTables) {+ if (movingTables.includes(table) || !Rectangle.intersects(params.toRange, table.getRange())) {+ continue;+ }+ this._errorService.emit(this._localeService.t<LocaleKey>('sheets-table.moveTableOverlapError'));+ return false;+ }++ const { fromRange, toRange } = params;+ if (!this._isValidMoveRange(params, target.worksheet)) {+ return false;+ }++ return checkRangesEditablePermission(this._injector, source.unitId, source.subUnitId, [fromRange])+ && checkRangesEditablePermission(this._injector, target.unitId, target.subUnitId, [toRange]);+ }++ private _isValidMoveRange(params: IMoveRangeCommandParams, worksheet: Worksheet): boolean {+ const { fromRange, toRange } = params;+ if (fromRange.endRow - fromRange.startRow !== toRange.endRow - toRange.startRow+ || fromRange.endColumn - fromRange.startColumn !== toRange.endColumn - toRange.startColumn+ || toRange.startRow < 0 || toRange.startColumn < 0+ || toRange.endRow >= worksheet.getRowCount()+ || toRange.endColumn >= worksheet.getColumnCount()) {+ return false;+ }+ return true;+ }++ private _getMoveMutations(params: IMoveRangeCommandParams) {+ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];++ const { source, target } = this._getTargets(params);+ if (!source || !target || source.unitId !== target.unitId) {+ return { redos, undos };+ }++ const rowOffset = params.toRange.startRow - params.fromRange.startRow;+ const columnOffset = params.toRange.startColumn - params.fromRange.startColumn;+ const tables = this._tableManager.getTablesBySubunitId(source.unitId, source.subUnitId);++ for (const table of tables) {+ const range = table.getRange();+ if (!Rectangle.contains(params.fromRange, range)) {+ continue;+ }+ redos.push({+ id: MoveSheetTableMutation.id,+ params: {+ unitId: source.unitId,+ tableId: table.getId(),+ subUnitId: target.subUnitId,+ range: {+ startRow: range.startRow + rowOffset,+ endRow: range.endRow + rowOffset,+ startColumn: range.startColumn + columnOffset,+ endColumn: range.endColumn + columnOffset,+ },+ },+ });+ undos.push({+ id: MoveSheetTableMutation.id,+ params: {+ unitId: source.unitId,+ tableId: table.getId(),+ subUnitId: source.subUnitId,+ range,+ calculatedColumns: table.getTableInfo().columns.filter((column) => column.formula).map((column) => ({+ columnId: column.id,+ formula: column.formula,+ formulaIsArray: column.formulaIsArray,+ })),+ },+ });+ }++ return { redos, undos };+ }+}diff --git a/packages/sheets-table/src/controllers/sheet-table-range.controller.ts b/packages/sheets-table/src/controllers/sheet-table-range.controller.tsindex 65c51045b9..97fd0b50fe 100644--- a/packages/sheets-table/src/controllers/sheet-table-range.controller.ts+++ b/packages/sheets-table/src/controllers/sheet-table-range.controller.ts@@ -31,8 +31,8 @@ export class SheetTableRangeController extends Disposable {private _initRangeListener() {this.disposeWithMe(this._tableManager.tableRangeChanged$.subscribe((event) => {- const { range, tableId, unitId, subUnitId } = event;- this._exclusiveRangeService.clearExclusiveRangesByGroupId(unitId, subUnitId, FEATURE_TABLE_ID, tableId);+ const { range, tableId, unitId, subUnitId, oldSubUnitId = subUnitId } = event;+ this._exclusiveRangeService.clearExclusiveRangesByGroupId(unitId, oldSubUnitId, FEATURE_TABLE_ID, tableId);this._exclusiveRangeService.addExclusiveRange(unitId, subUnitId, FEATURE_TABLE_ID, [{range: { ...range },groupId: tableId,diff --git a/packages/sheets-table/src/controllers/sheet-table-theme.controller.ts b/packages/sheets-table/src/controllers/sheet-table-theme.controller.tsindex 6efa48e9af..c2657dfc1c 100644--- a/packages/sheets-table/src/controllers/sheet-table-theme.controller.ts+++ b/packages/sheets-table/src/controllers/sheet-table-theme.controller.ts@@ -55,7 +55,7 @@ export class SheetsTableThemeController extends Disposable {this.disposeWithMe(this._tableManager.tableRangeChanged$.subscribe((event) => {- const { range, oldRange, tableId, unitId, subUnitId } = event;+ const { range, oldRange, tableId, unitId, subUnitId, oldSubUnitId = subUnitId } = event;const table = this._tableManager.getTable(unitId, tableId)!;let tableStyleId = table.getTableStyleId();if (!tableStyleId) {@@ -64,7 +64,7 @@ export class SheetsTableThemeController extends Disposable {}this._sheetRangeThemeService.removeRangeThemeRule(tableStyleId, {unitId,- subUnitId,+ subUnitId: oldSubUnitId,range: { ...oldRange },});this._sheetRangeThemeService.registerRangeThemeStyle(tableStyleId, {diff --git a/packages/sheets-table/src/controllers/sheets-table.controller.ts b/packages/sheets-table/src/controllers/sheets-table.controller.tsindex 7f610a992c..9759b5d377 100644--- a/packages/sheets-table/src/controllers/sheets-table.controller.ts+++ b/packages/sheets-table/src/controllers/sheets-table.controller.ts@@ -17,7 +17,17 @@import type { IMutationInfo, IRange, Workbook } from '@univerjs/core';import type { ICopySheetCommandParams, IRemoveSheetCommandParams } from '@univerjs/sheets';import type { ITableResource } from '../types/type';-import { Disposable, generateRandomId, Inject, InterceptorEffectEnum, IResourceManagerService, IUniverInstanceService, Rectangle, RTree, UniverInstanceType } from '@univerjs/core';+import {+ Disposable,+ generateRandomId,+ Inject,+ InterceptorEffectEnum,+ IResourceManagerService,+ IUniverInstanceService,+ Rectangle,+ RTree,+ UniverInstanceType,+} from '@univerjs/core';import { CopySheetCommand, INTERCEPTOR_POINT, RemoveSheetCommand, SheetInterceptorService } from '@univerjs/sheets';import { AddSheetTableMutation } from '../commands/mutations/add-sheet-table.mutation';import { DeleteSheetTableMutation } from '../commands/mutations/delete-sheet-table.mutation';@@ -78,11 +88,11 @@ export class SheetsTableController extends Disposable {this.disposeWithMe(this._tableManager.tableRangeChanged$.subscribe((event) => {- const { range, tableId, unitId, subUnitId, oldRange } = event;+ const { range, tableId, unitId, subUnitId, oldRange, oldSubUnitId = subUnitId } = event;const rTree = this._ensureTableRangeRTree(unitId);rTree.remove({unitId,- sheetId: subUnitId,+ sheetId: oldSubUnitId,id: tableId,range: { ...oldRange },});diff --git a/packages/sheets-table/src/controllers/table-filter.controller.ts b/packages/sheets-table/src/controllers/table-filter.controller.tsindex e9f2b13c3d..063b6af89f 100644--- a/packages/sheets-table/src/controllers/table-filter.controller.ts+++ b/packages/sheets-table/src/controllers/table-filter.controller.ts@@ -15,17 +15,20 @@*/import type { Workbook } from '@univerjs/core';-import type { Subscription } from 'rxjs';import { Disposable, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { ISheetRowFilteredService } from '@univerjs/engine-formula';-import { getSheetCommandTarget, INTERCEPTOR_POINT, SheetInterceptorService, ZebraCrossingCacheController } from '@univerjs/sheets';+import {+ getSheetCommandTarget,+ INTERCEPTOR_POINT,+ SheetInterceptorService,+ ZebraCrossingCacheController,+} from '@univerjs/sheets';import { filter, switchMap } from 'rxjs';import { TableManager } from '../models/table-manager';export class TableFilterController extends Disposable {private readonly _tableFilteredOutRows = new Map<string, Set<number>>();- private _subscription: Subscription | null = null;constructor(@Inject(TableManager) private _tableManager: TableManager,@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,@@ -59,7 +62,7 @@ export class TableFilterController extends Disposable {}private _initFilteredOutRows() {- this._tableManager.tableInitStatus$.pipe(+ this.disposeWithMe(this._tableManager.tableInitStatus$.pipe(filter((initialized) => initialized),switchMap(() => {return this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET);@@ -74,13 +77,13 @@ export class TableFilterController extends Disposable {}const { unitId, subUnitId } = target;this._refreshTableFilteredOutRows(unitId, subUnitId);- });+ }));}registerFilterChangeEvent() {this.disposeWithMe(this._tableManager.tableFilterChanged$.subscribe((event) => {- const { unitId, subUnitId, tableId } = event;+ const { unitId, subUnitId, tableId, oldSubUnitId } = event;const workbook = this._univerInstanceService.getUnit<Workbook>(unitId);const worksheet = workbook?.getSheetBySheetId(subUnitId);const table = this._tableManager.getTable(unitId, tableId);@@ -94,6 +97,10 @@ export class TableFilterController extends Disposable {this._refreshTableFilteredOutRows(unitId, subUnitId);this._zebraCrossingCacheController.updateZebraCrossingCache(unitId, subUnitId);+ if (oldSubUnitId && oldSubUnitId !== subUnitId) {+ this._refreshTableFilteredOutRows(unitId, oldSubUnitId);+ this._zebraCrossingCacheController.updateZebraCrossingCache(unitId, oldSubUnitId);+ }}));}@@ -128,6 +135,6 @@ export class TableFilterController extends Disposable {override dispose(): void {super.dispose();- this._subscription?.unsubscribe();+ this._tableFilteredOutRows.clear();}}diff --git a/packages/sheets-table/src/locale/ar-SA.ts b/packages/sheets-table/src/locale/ar-SA.tsindex 0251055192..28b886cb41 100644--- a/packages/sheets-table/src/locale/ar-SA.ts+++ b/packages/sheets-table/src/locale/ar-SA.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'عمود',tablePrefix: 'جدول',+ moveTableOverlapError: 'يتداخل نطاق الوجهة مع جدول آخر.',tableNameError: 'لا يمكن أن يحتوي اسم الجدول على مسافات، ولا يمكن أن يبدأ برقم، ولا يمكن أن يكون مطابقًا لاسم جدول موجود',},};diff --git a/packages/sheets-table/src/locale/ca-ES.ts b/packages/sheets-table/src/locale/ca-ES.tsindex 0240f96ad2..a2ab577d55 100644--- a/packages/sheets-table/src/locale/ca-ES.ts+++ b/packages/sheets-table/src/locale/ca-ES.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Columna',tablePrefix: 'Taula',+ moveTableOverlapError: 'La destinació se superposa amb una altra taula.',tableNameError: 'El nom de la taula no pot contenir espais, no pot començar amb un número i no pot ser idèntic a un nom de taula existent',},};diff --git a/packages/sheets-table/src/locale/de-DE.ts b/packages/sheets-table/src/locale/de-DE.tsindex 953e51087a..b372029114 100644--- a/packages/sheets-table/src/locale/de-DE.ts+++ b/packages/sheets-table/src/locale/de-DE.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Spalte',tablePrefix: 'Tabelle',+ moveTableOverlapError: 'Der Zielbereich überschneidet sich mit einer anderen Tabelle.',tableNameError: 'Tabellenname darf keine Leerzeichen enthalten, darf nicht mit einer Zahl beginnen und darf nicht mit einem vorhandenen Tabellennamen identisch sein',},};diff --git a/packages/sheets-table/src/locale/en-US.ts b/packages/sheets-table/src/locale/en-US.tsindex d6a7adf559..5f98b26ddb 100644--- a/packages/sheets-table/src/locale/en-US.ts+++ b/packages/sheets-table/src/locale/en-US.ts@@ -18,6 +18,7 @@ const locale = {'sheets-table': {columnPrefix: 'Column',tablePrefix: 'Table',+ moveTableOverlapError: 'The destination overlaps another table.',tableNameError: 'Table name cannot contain spaces, cannot start with a number, and cannot be identical to an existing table name',},};diff --git a/packages/sheets-table/src/locale/es-ES.ts b/packages/sheets-table/src/locale/es-ES.tsindex b5496c1ef4..17759f615e 100644--- a/packages/sheets-table/src/locale/es-ES.ts+++ b/packages/sheets-table/src/locale/es-ES.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Columna',tablePrefix: 'Tabla',+ moveTableOverlapError: 'El destino se superpone con otra tabla.',tableNameError: 'El nombre de la tabla no puede contener espacios, no puede comenzar con un número y no puede ser idéntico a un nombre de tabla existente',},};diff --git a/packages/sheets-table/src/locale/fa-IR.ts b/packages/sheets-table/src/locale/fa-IR.tsindex aaa04bc234..58ab6d9ffe 100644--- a/packages/sheets-table/src/locale/fa-IR.ts+++ b/packages/sheets-table/src/locale/fa-IR.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'ستون',tablePrefix: 'جدول',+ moveTableOverlapError: 'محدودهٔ مقصد با جدول دیگری همپوشانی دارد.',tableNameError: 'نام جدول نمیتواند شامل فاصله باشد، نمیتواند با عدد شروع شود و نمیتواند با نام جدولهای موجود تکراری باشد',},};diff --git a/packages/sheets-table/src/locale/fr-FR.ts b/packages/sheets-table/src/locale/fr-FR.tsindex d9d78c8ebb..2610695059 100644--- a/packages/sheets-table/src/locale/fr-FR.ts+++ b/packages/sheets-table/src/locale/fr-FR.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Colonne',tablePrefix: 'Tableau',+ moveTableOverlapError: 'La destination chevauche un autre tableau.',tableNameError: 'Le nom du tableau ne peut pas contenir d\'espaces, ne peut pas commencer par un chiffre et ne peut pas être identique à un nom de tableau existant',},};diff --git a/packages/sheets-table/src/locale/id-ID.ts b/packages/sheets-table/src/locale/id-ID.tsindex 276a10e0e3..23ef91d63f 100644--- a/packages/sheets-table/src/locale/id-ID.ts+++ b/packages/sheets-table/src/locale/id-ID.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Kolom',tablePrefix: 'Tabel',+ moveTableOverlapError: 'Rentang tujuan tumpang tindih dengan tabel lain.',tableNameError: 'Nama tabel tidak boleh mengandung spasi, tidak boleh diawali dengan angka, dan tidak boleh sama dengan nama tabel yang sudah ada',},};diff --git a/packages/sheets-table/src/locale/it-IT.ts b/packages/sheets-table/src/locale/it-IT.tsindex 3ba12296c5..e293d9509f 100644--- a/packages/sheets-table/src/locale/it-IT.ts+++ b/packages/sheets-table/src/locale/it-IT.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Colonna',tablePrefix: 'Tabella',+ moveTableOverlapError: 'La destinazione si sovrappone a un’altra tabella.',tableNameError: 'Il nome della tabella non può contenere spazi, non può iniziare con un numero e non può essere identico a un nome di tabella esistente',},};diff --git a/packages/sheets-table/src/locale/ja-JP.ts b/packages/sheets-table/src/locale/ja-JP.tsindex 3448d16899..3a53f98b1a 100644--- a/packages/sheets-table/src/locale/ja-JP.ts+++ b/packages/sheets-table/src/locale/ja-JP.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: '列',tablePrefix: '表',+ moveTableOverlapError: '移動先が他のテーブルと重なっています。',tableNameError: '表の名前は空白を含めることはできず、数字で始めることはできず、既存の表名と重複できません',},};diff --git a/packages/sheets-table/src/locale/ko-KR.ts b/packages/sheets-table/src/locale/ko-KR.tsindex 3796055f28..b1a175c9b2 100644--- a/packages/sheets-table/src/locale/ko-KR.ts+++ b/packages/sheets-table/src/locale/ko-KR.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: '열',tablePrefix: '표',+ moveTableOverlapError: '대상 범위가 다른 표와 겹칩니다.',tableNameError: '표 이름은 공백을 포함할 수 없으며 숫자로 시작할 수 없고 기존 표 이름과 중복될 수 없습니다',},};diff --git a/packages/sheets-table/src/locale/pl-PL.ts b/packages/sheets-table/src/locale/pl-PL.tsindex 337e878dd3..5075d0c7e7 100644--- a/packages/sheets-table/src/locale/pl-PL.ts+++ b/packages/sheets-table/src/locale/pl-PL.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Kolumna',tablePrefix: 'Tabela',+ moveTableOverlapError: 'Zakres docelowy nakłada się na inną tabelę.',tableNameError: 'Nazwa tabeli nie może zawierać spacji, nie może zaczynać się od cyfry i nie może być identyczna z istniejącą nazwą tabeli',},};diff --git a/packages/sheets-table/src/locale/pt-BR.ts b/packages/sheets-table/src/locale/pt-BR.tsindex 8e69cfbdaa..72dca9b725 100644--- a/packages/sheets-table/src/locale/pt-BR.ts+++ b/packages/sheets-table/src/locale/pt-BR.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Coluna',tablePrefix: 'Tabela',+ moveTableOverlapError: 'O destino se sobrepõe a outra tabela.',tableNameError: 'O nome da tabela não pode conter espaços, não pode começar com um número e não pode ser idêntico a um nome de tabela existente',},};diff --git a/packages/sheets-table/src/locale/ru-RU.ts b/packages/sheets-table/src/locale/ru-RU.tsindex a14c6c0748..0c509c88ca 100644--- a/packages/sheets-table/src/locale/ru-RU.ts+++ b/packages/sheets-table/src/locale/ru-RU.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Столбец',tablePrefix: 'Таблица',+ moveTableOverlapError: 'Диапазон назначения пересекается с другой таблицей.',tableNameError: 'Имя таблицы не может содержать пробелы, не может начинаться с цифры и не может совпадать с именем существующей таблицы',},};diff --git a/packages/sheets-table/src/locale/sk-SK.ts b/packages/sheets-table/src/locale/sk-SK.tsindex 82a983667b..08670f1f23 100644--- a/packages/sheets-table/src/locale/sk-SK.ts+++ b/packages/sheets-table/src/locale/sk-SK.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Stĺpec',tablePrefix: 'Tabuľka',+ moveTableOverlapError: 'Cieľový rozsah sa prekrýva s inou tabuľkou.',tableNameError: 'Názov tabuľky nesmie obsahovať medzery, nesmie začínať číslom a nesmie byť zhodný s existujúcim názvom tabuľky',},};diff --git a/packages/sheets-table/src/locale/vi-VN.ts b/packages/sheets-table/src/locale/vi-VN.tsindex ff7b85c0e4..2198fbf598 100644--- a/packages/sheets-table/src/locale/vi-VN.ts+++ b/packages/sheets-table/src/locale/vi-VN.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: 'Cột',tablePrefix: 'Bảng',+ moveTableOverlapError: 'Vùng đích chồng lấp với một bảng khác.',tableNameError: 'Tên bảng không thể chứa khoảng trắng, không được bắt đầu bằng số và không được trùng với tên bảng đã có',},};diff --git a/packages/sheets-table/src/locale/zh-CN.ts b/packages/sheets-table/src/locale/zh-CN.tsindex e8982cf160..d8922cc709 100644--- a/packages/sheets-table/src/locale/zh-CN.ts+++ b/packages/sheets-table/src/locale/zh-CN.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: '列',tablePrefix: '表格',+ moveTableOverlapError: '目标区域与其他表格重叠。',tableNameError: '表格名称不能包含空格, 不能以数字开头,不能和已有表格名称重复',},};diff --git a/packages/sheets-table/src/locale/zh-HK.ts b/packages/sheets-table/src/locale/zh-HK.tsindex f54b8cde69..a554edf369 100644--- a/packages/sheets-table/src/locale/zh-HK.ts+++ b/packages/sheets-table/src/locale/zh-HK.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: '列',tablePrefix: '表格',+ moveTableOverlapError: '目標區域與其他表格重疊。',tableNameError: '表格名稱不能包含空格, 不能以數字開頭,不能和已有表格名稱重複',},};diff --git a/packages/sheets-table/src/locale/zh-TW.ts b/packages/sheets-table/src/locale/zh-TW.tsindex f54b8cde69..a554edf369 100644--- a/packages/sheets-table/src/locale/zh-TW.ts+++ b/packages/sheets-table/src/locale/zh-TW.ts@@ -20,6 +20,7 @@ const locale: typeof enUS = {'sheets-table': {columnPrefix: '列',tablePrefix: '表格',+ moveTableOverlapError: '目標區域與其他表格重疊。',tableNameError: '表格名稱不能包含空格, 不能以數字開頭,不能和已有表格名稱重複',},};diff --git a/packages/sheets-table/src/models/table-manager.ts b/packages/sheets-table/src/models/table-manager.tsindex ffa33e53c3..40c8b527d6 100644--- a/packages/sheets-table/src/models/table-manager.ts+++ b/packages/sheets-table/src/models/table-manager.ts@@ -364,6 +364,26 @@ export class TableManager extends Disposable {});}+ moveTable(unitId: string, tableId: string, subUnitId: string, range: ITableRange) {+ const table = this.getTableById(unitId, tableId);+ if (!table) {+ return;+ }+ const oldRange = table.getRange();+ const oldSubUnitId = table.getSubunitId();+ table.setSubunitId(subUnitId);+ table.setRange({ ...range });+ this._tableRangeChanged$.next({+ unitId,+ subUnitId,+ oldSubUnitId,+ tableId,+ range: { ...range },+ oldRange,+ });+ this._tableFilterChanged$.next({ unitId, subUnitId, oldSubUnitId, tableId });+ }+setTableByConfig(unitId: string, tableId: string, config: ITableSetConfig) {const unitMap = this._tableMap.get(unitId);const table = unitMap?.get(tableId);diff --git a/packages/sheets-table/src/plugin.ts b/packages/sheets-table/src/plugin.tsindex 7ef34a9086..0523daeb18 100644--- a/packages/sheets-table/src/plugin.ts+++ b/packages/sheets-table/src/plugin.ts@@ -15,7 +15,18 @@*/import type { IUniverSheetsTableConfig } from './config/config';-import { DependentOn, ICommandService, IConfigService, Inject, Injector, merge, Plugin, registerDependencies, touchDependencies, UniverInstanceType } from '@univerjs/core';+import {+ DependentOn,+ ICommandService,+ IConfigService,+ Inject,+ Injector,+ merge,+ Plugin,+ registerDependencies,+ touchDependencies,+ UniverInstanceType,+} from '@univerjs/core';import { UniverSheetsPlugin } from '@univerjs/sheets';import pkg from '../package.json';import { AddSheetTableCommand } from './commands/commands/add-sheet-table.command';@@ -25,14 +36,24 @@ import { RemoveTableThemeCommand } from './commands/commands/remove-table-theme.import { SetSheetTableCommand } from './commands/commands/set-sheet-table.command';import { SetSheetTableFilterCommand } from './commands/commands/set-table-filter.command';import { SetSheetTableSortStateCommand } from './commands/commands/set-table-sort-state.command';-import { SheetTableInsertColCommand, SheetTableInsertColumnAtCommand, SheetTableInsertRowAtCommand, SheetTableInsertRowCommand, SheetTableRemoveColCommand, SheetTableRemoveColumnAtCommand, SheetTableRemoveRowCommand } from './commands/commands/sheet-table-row-col.command';+import {+ SheetTableInsertColCommand,+ SheetTableInsertColumnAtCommand,+ SheetTableInsertRowAtCommand,+ SheetTableInsertRowCommand,+ SheetTableRemoveColCommand,+ SheetTableRemoveColumnAtCommand,+ SheetTableRemoveRowCommand,+} from './commands/commands/sheet-table-row-col.command';import { AddSheetTableMutation } from './commands/mutations/add-sheet-table.mutation';import { DeleteSheetTableMutation } from './commands/mutations/delete-sheet-table.mutation';+import { MoveSheetTableMutation } from './commands/mutations/move-sheet-table.mutation';import { SetSheetTableMutation } from './commands/mutations/set-sheet-table.mutation';import { SetSheetTableFilterMutation } from './commands/mutations/set-table-filter.mutation';import { defaultPluginConfig, SHEETS_TABLE_PLUGIN_CONFIG_KEY } from './config/config';import { PLUGIN_NAME } from './const';import { SheetTableFormulaController } from './controllers/sheet-table-formula.controller';+import { SheetTableMoveController } from './controllers/sheet-table-move.controller';import { SheetTableRangeController } from './controllers/sheet-table-range.controller';import { SheetTableRefRangeController } from './controllers/sheet-table-ref-range.controller';import { SheetsTableThemeController } from './controllers/sheet-table-theme.controller';@@ -75,6 +96,7 @@ export class UniverSheetsTablePlugin extends Plugin {[TableFilterController],[SheetTableRangeController],[SheetTableRefRangeController],+ [SheetTableMoveController],[SheetTableFormulaController],]);}@@ -84,6 +106,7 @@ export class UniverSheetsTablePlugin extends Plugin {[SheetTableFormulaController],[SheetTableRangeController],[SheetTableRefRangeController],+ [SheetTableMoveController],[SheetsTableThemeController],[SheetsTableController],[SheetTableService],@@ -101,6 +124,7 @@ export class UniverSheetsTablePlugin extends Plugin {AddSheetTableMutation,DeleteSheetTableCommand,DeleteSheetTableMutation,+ MoveSheetTableMutation,SetSheetTableFilterMutation,SetSheetTableFilterCommand,SetSheetTableSortStateCommand,diff --git a/packages/sheets-table/src/types/type.ts b/packages/sheets-table/src/types/type.tsindex afbd791f63..04a3633a85 100644--- a/packages/sheets-table/src/types/type.ts+++ b/packages/sheets-table/src/types/type.ts@@ -221,6 +221,7 @@ export interface ITableNameChangedEvent extends ITableBaseEvent {export interface ITableRangeChangedEvent extends ITableBaseEvent {range: ITableRange;oldRange: ITableRange;+ oldSubUnitId?: string;}export interface ITableThemeChangedEvent extends ITableBaseEvent {@@ -232,18 +233,11 @@ export type ITableDeletedEvent = ITableAddedEvent & {tableStyleId?: string;};-export interface ITableRangeChangedEvent {- unitId: string;- subUnitId: string;- tableId: string;- range: ITableRange;- oldRange: ITableRange;-}-export interface ITableFilterChangedEvent {unitId: string;subUnitId: string;tableId: string;+ oldSubUnitId?: string;}export interface ITableColumnJson {dataType: TableColumnDataTypeEnum;diff --git a/packages/sheets-ui/src/commands/commands/__tests__/move-range-confirm.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/move-range-confirm.command.spec.tsindex 6bee81ee55..00f098f116 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/move-range-confirm.command.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/move-range-confirm.command.spec.ts@@ -18,6 +18,7 @@ import type { Injector, IWorkbookData, Univer, Workbook } from '@univerjs/core';import {ICommandService,IConfirmService,+ IUndoRedoService,LocaleService,LocaleType,TestConfirmService,@@ -26,6 +27,7 @@ import {MoveRangeCommand,MoveRangeMutation,SetSelectionsOperation,+ SheetInterceptorService,} from '@univerjs/sheets';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { MoveRangeConfirmCommand } from '../move-range-confirm.command';@@ -50,7 +52,9 @@ describe('MoveRangeConfirmCommand', () => {workbook = testBed.sheet;commandService = get(ICommandService);confirmService = get(IConfirmService) as TestConfirmService<unknown>;- get(LocaleService).setLocale(LocaleType.EN_US);+ const localeService = get(LocaleService);+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');[MoveRangeCommand, MoveRangeConfirmCommand, MoveRangeMutation, SetSelectionsOperation].forEach((command) => {commandService.registerCommand(command);@@ -61,6 +65,44 @@ describe('MoveRangeConfirmCommand', () => {univer.dispose();});+ it('rejects an invalid move before asking to overwrite target content', async () => {+ const confirm = vi.spyOn(confirmService, 'confirm').mockResolvedValue(true);+ const history = get(IUndoRedoService).getUndoRedoStatus('test');+ get(SheetInterceptorService).interceptBeforeCommand({+ performCheck: async (command) => command.id !== MoveRangeCommand.id,+ });++ expect(await commandService.executeCommand(MoveRangeConfirmCommand.id, {+ fromRange: FROM_RANGE,+ toRange: TO_RANGE,+ })).toBe(false);+ expect(confirm).not.toHaveBeenCalled();+ expect(getCellValue(0, 0)).toBe('source');+ expect(getCellValue(0, 1)).toBe('target');+ expect(get(IUndoRedoService).getUndoRedoStatus('test')).toEqual(history);+ });++ it('revalidates the move if the target becomes unavailable while confirming', async () => {+ let canMove = true;+ get(SheetInterceptorService).interceptBeforeCommand({+ performCheck: async (command) => command.id !== MoveRangeCommand.id || canMove,+ });+ const confirm = vi.spyOn(confirmService, 'confirm').mockImplementation(async () => {+ canMove = false;+ return true;+ });+ const history = get(IUndoRedoService).getUndoRedoStatus('test');++ expect(await commandService.executeCommand(MoveRangeConfirmCommand.id, {+ fromRange: FROM_RANGE,+ toRange: TO_RANGE,+ })).toBe(false);+ expect(confirm).toHaveBeenCalledTimes(1);+ expect(getCellValue(0, 0)).toBe('source');+ expect(getCellValue(0, 1)).toBe('target');+ expect(get(IUndoRedoService).getUndoRedoStatus('test')).toEqual(history);+ });+it('does not overwrite target content when confirmation is canceled', async () => {const confirm = vi.spyOn(confirmService, 'confirm').mockResolvedValue(false);diff --git a/packages/sheets-ui/src/commands/commands/move-range-confirm.command.ts b/packages/sheets-ui/src/commands/commands/move-range-confirm.command.tsindex bf2a522ce5..5722e7d49d 100644--- a/packages/sheets-ui/src/commands/commands/move-range-confirm.command.ts+++ b/packages/sheets-ui/src/commands/commands/move-range-confirm.command.ts@@ -25,7 +25,12 @@ import {LocaleService,Rectangle,} from '@univerjs/core';-import { findFirstNonEmptyCell, getSheetCommandTarget, MoveRangeCommand } from '@univerjs/sheets';+import {+ findFirstNonEmptyCell,+ getSheetCommandTarget,+ MoveRangeCommand,+ SheetInterceptorService,+} from '@univerjs/sheets';export const MoveRangeConfirmCommand: ICommand<IMoveRangeCommandParams> = {type: CommandType.COMMAND,@@ -35,6 +40,14 @@ export const MoveRangeConfirmCommand: ICommand<IMoveRangeCommandParams> = {return false;}+ const canMove = await accessor.get(SheetInterceptorService).beforeCommandExecute({+ id: MoveRangeCommand.id,+ params,+ });+ if (!canMove) {+ return false;+ }+const commandService = accessor.get(ICommandService);const univerInstanceService = accessor.get(IUniverInstanceService);const sourceTarget = getSheetCommandTarget(univerInstanceService, {diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.tsindex bfa6681323..f6a75febfd 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts@@ -36,6 +36,7 @@ import {AddWorksheetMergeMutation,discreteRangeToRange,MergeCellController,+ MoveRangeCommand,MoveRangeMutation,RefRangeService,RemoveWorksheetMergeMutation,@@ -45,6 +46,7 @@ import {SetWorksheetColWidthMutation,SetWorksheetRowAutoHeightMutation,SetWorksheetRowHeightMutation,+ SheetInterceptorService,SheetsSelectionsService,WorkbookEditablePermission,} from '@univerjs/sheets';@@ -949,6 +951,65 @@ describe('Test clipboard', () => {});describe('Test cut command in single selection', () => {+ it('checks range movement before resource hooks and keeps a rejected cut available for retry', async () => {+ const workbook = get(IUniverInstanceService).getUnit<Workbook>('test')!;+ const snapshot = Tools.deepClone(workbook.getSnapshot());+ const history = get(IUndoRedoService).getUndoRedoStatus('test');+ const matrix = new ObjectMatrix<ICellData>();+ matrix.setValue(0, 0, { v: 'A25' });+ const copyId = 'rejected-cut';+ sheetClipboardService.copyContentCache().set(copyId, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { rows: [24], cols: [0] },+ matrix,+ copyType: COPY_TYPE.CUT,+ });+ let allowed = false;+ const checks: unknown[] = [];+ const validation = get(SheetInterceptorService).interceptBeforeCommand({+ performCheck: async (command) => {+ checks.push(command);+ return allowed;+ },+ });+ let hooksCalled = 0;+ const hook = sheetClipboardService.addClipboardHook({+ id: 'movement-preflight-resource',+ onBeforePaste: () => {+ hooksCalled++;+ return true;+ },+ });+ const target = {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 24, endRow: 24, startColumn: 1, endColumn: 1 },+ };+ expect(await sheetClipboardService.pasteByCopyId(copyId, undefined, target)).toBe(false);+ expect(checks).toEqual([{+ id: MoveRangeCommand.id,+ params: {+ fromUnitId: 'test',+ fromSubUnitId: 'sheet1',+ fromRange: { startRow: 24, endRow: 24, startColumn: 0, endColumn: 0 },+ toUnitId: 'test',+ toSubUnitId: 'sheet1',+ toRange: target.range,+ },+ }]);+ expect(hooksCalled).toBe(0);+ expect(workbook.getSnapshot()).toEqual(snapshot);+ expect(get(IUndoRedoService).getUndoRedoStatus('test')).toEqual(history);+ expect(sheetClipboardService.copyContentCache().get(copyId)?.matrix).toBe(matrix);+ allowed = true;+ expect(await sheetClipboardService.pasteByCopyId(copyId, undefined, target)).toBe(true);+ expect(getValues(24, 0, 24, 1)?.[0].map((cell) => cell?.v ?? null)).toEqual([null, 'A25']);+ expect(hooksCalled).toBe(1);+ validation.dispose();+ hook.dispose();+ });+it('rejects cross-workbook cuts before running resource hooks and retains the cut for a valid retry', async () => {const instances = get(IUniverInstanceService);const source = instances.getUnit<Workbook>('test', UniverInstanceType.UNIVER_SHEET)!;diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.tsindex 35806d75c8..703dcd50cd 100644--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts@@ -76,12 +76,15 @@ import {} from '@univerjs/core';import { IRenderManagerService, withCurrentTypeOfRenderer } from '@univerjs/engine-render';import {+ discreteRangeToRange,getPrimaryForRange,+ MoveRangeCommand,rangeToDiscreteRange,SetSelectionsOperation,SetWorksheetActiveOperation,SetWorksheetRowAutoHeightMutation,SetWorksheetRowAutoHeightMutationFactory,+ SheetInterceptorService,SheetsSelectionsService,} from '@univerjs/sheets';import {@@ -1023,6 +1026,22 @@ export class SheetClipboardService extends Disposable implements ISheetClipboardconst start = pasteTarget.pastedRange.rows[0];const end = range.rows[range.rows.length - 1] - range.rows[0] + start;pasteTarget.pastedRange.rows = Array.from(new Array(end + 1).keys()).slice(start);+ if (!skipCellCopy) {+ const canMove = await this._injector.get(SheetInterceptorService).beforeCommandExecute({+ id: MoveRangeCommand.id,+ params: {+ fromUnitId: copyUnitId,+ fromSubUnitId: copySubUnitId,+ fromRange: discreteRangeToRange(range),+ toUnitId: target.unitId,+ toSubUnitId: target.subUnitId,+ toRange: discreteRangeToRange(pasteTarget.pastedRange),+ },+ });+ if (!canMove) {+ return false;+ }+ }}const pasteRes = this._pasteUSM(diff --git a/packages/sheets/src/commands/mutations/__tests__/move-range.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/move-range.mutation.spec.tsnew file mode 100644index 0000000000..d3e5dc07db--- /dev/null+++ b/packages/sheets/src/commands/mutations/__tests__/move-range.mutation.spec.ts@@ -0,0 +1,59 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IWorkbookData, Workbook } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, LocaleType, Tools, Univer, UniverInstanceType } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { MoveRangeMutation } from '../move-range.mutation';++describe('MoveRangeMutation', () => {+ it('applies a changeset to its explicit workbook while another workbook is active', () => {+ const univer = new Univer();+ try {+ const injector = univer.__getInjector();+ const data: IWorkbookData = {+ id: 'active',+ appVersion: '1.0.3',+ locale: LocaleType.EN_US,+ name: 'Active',+ styles: {},+ sheetOrder: ['sheet1'],+ sheets: { sheet1: { id: 'sheet1', name: 'Sheet1', rowCount: 10, columnCount: 10, cellData: { 0: { 0: { v: 'source' } } } } },+ };+ const active = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, data);+ const instances = injector.get(IUniverInstanceService);+ const peer = instances.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ ...Tools.deepClone(data),+ id: 'peer',+ }, { makeCurrent: false });+ const commands = injector.get(ICommandService);+ commands.registerCommand(MoveRangeMutation);+ expect(commands.syncExecuteCommand(MoveRangeMutation.id, {+ unitId: 'peer',+ fromRange: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ toRange: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },+ from: { subUnitId: 'sheet1', value: { 0: { 0: null } } },+ to: { subUnitId: 'sheet1', value: { 1: { 1: { v: 'source' } } } },+ }, { fromChangeset: true })).toBe(true);+ expect(peer.getSheetBySheetId('sheet1')!.getCellRaw(0, 0)).toBeUndefined();+ expect(peer.getSheetBySheetId('sheet1')!.getCellRaw(1, 1)?.v).toBe('source');+ expect(active.getSheetBySheetId('sheet1')!.getCellRaw(0, 0)?.v).toBe('source');+ expect(active.getSheetBySheetId('sheet1')!.getCellRaw(1, 1)).toBeUndefined();+ } finally {+ univer.dispose();+ }+ });+});diff --git a/packages/sheets/src/commands/mutations/move-range.mutation.ts b/packages/sheets/src/commands/mutations/move-range.mutation.tsindex 3755b75477..0c84b8d849 100644--- a/packages/sheets/src/commands/mutations/move-range.mutation.ts+++ b/packages/sheets/src/commands/mutations/move-range.mutation.ts@@ -14,7 +14,14 @@* limitations under the License.*/-import type { ICellData, IMutation, IObjectMatrixPrimitiveType, IRange, Nullable, Workbook } from '@univerjs/core';+import type {+ ICellData,+ IMutation,+ IObjectMatrixPrimitiveType,+ IRange,+ Nullable,+ Workbook,+} from '@univerjs/core';import { CommandType, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';export interface IMoveRangeMutationParams {@@ -42,7 +49,7 @@ export const MoveRangeMutation: IMutation<IMoveRangeMutationParams, boolean> = {}const univerInstanceService = accessor.get(IUniverInstanceService);- const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ const workbook = univerInstanceService.getUnit<Workbook>(params.unitId, UniverInstanceType.UNIVER_SHEET);if (!workbook) {return false;}