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-table): preserve column identities during replay (#7915)
白熱203585ee03d4
diff --git a/packages/sheets-table/src/commands/commands/__tests__/add-sheet-table.command.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/add-sheet-table.command.spec.tsnew file mode 100644index 0000000000..10d1c5ae64--- /dev/null+++ b/packages/sheets-table/src/commands/commands/__tests__/add-sheet-table.command.spec.ts@@ -0,0 +1,144 @@+/**+ * 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.+ */++/**+ * 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 } from '@univerjs/core';+import {+ ICommandService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ RedoCommand,+ Tools,+ UndoCommand,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { afterEach, describe, expect, it } from 'vitest';+import type { ITableOptions } from '../../../types/type';+import enUS from '../../../locale/en-US';+import { TableColumn } from '../../../models/table-column';+import { TableManager } from '../../../models/table-manager';+import { UniverSheetsTablePlugin } from '../../../plugin';+import { AddSheetTableMutation } from '../../mutations/add-sheet-table.mutation';+import { AddSheetTableCommand } from '../add-sheet-table.command';++const universes: Univer[] = [];++function createUniver() {+ const univer = new Univer();+ universes.push(univer);+ const injector = univer.__getInjector();+ const locale = injector.get(LocaleService);+ locale.load({ [LocaleType.EN_US]: enUS });+ locale.setLocale(LocaleType.EN_US);+ locale.setDirection('ltr');+ univer.registerPlugin(UniverSheetsTablePlugin);+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, {+ id: 'unit',+ sheetOrder: ['sheet'],+ sheets: {+ sheet: {+ id: 'sheet',+ name: 'Source',+ rowCount: 20,+ columnCount: 10,+ cellData: {+ 0: { 2: { v: 'Region' }, 3: { v: 'Amount' } },+ 1: { 2: { v: 'North' }, 3: { v: 10 } },+ 2: { 2: { v: 'South' }, 3: { v: 20 } },+ },+ },+ },+ });+ injector.get(IUniverInstanceService).focusUnit('unit');+ return injector;+}++afterEach(() => universes.splice(0).forEach((univer) => univer.dispose()));++describe('AddSheetTableCommand', () => {+ it.each([false, true])('preserves column identities during replay and undo/redo with partial definitions: %s', (partial) => {+ const main = createUniver();+ const replica = createUniver();+ const commands = main.get(ICommandService);+ const manager = main.get(TableManager);+ const replicaManager = replica.get(TableManager);+ const mutations: IMutationInfo[] = [];+ const subscription = commands.onCommandExecuted((command) => {+ if (command.id === AddSheetTableMutation.id && command.params) {+ mutations.push({ id: command.id, params: Tools.deepClone(command.params) });+ }+ });+ const options: ITableOptions = partial+ ? { columns: [new TableColumn('authored-region', 'Authored region').toJSON()] }+ : {};+ const originalOptions = Tools.deepClone(options);+ expect(commands.syncExecuteCommand(AddSheetTableCommand.id, {+ unitId: 'unit',+ subUnitId: 'sheet',+ id: 'table',+ name: 'Sales',+ range: { startRow: 0, endRow: 2, startColumn: 2, endColumn: 3 },+ options,+ })).toBe(true);+ subscription.dispose();+ const columns = manager.getTable('unit', 'table')!.toJSON().columns;+ const mutation = mutations[0];+ expect(replica.get(ICommandService).syncExecuteCommand(mutation.id, mutation.params)).toBe(true);+ expect(replicaManager.getTable('unit', 'table')!.toJSON().columns).toEqual(columns);+ expect(options).toEqual(originalOptions);+ if (partial) {+ expect(columns[0]).toMatchObject({ id: 'authored-region', displayName: 'Authored region' });+ options.columns![0].id = 'caller-changed';+ }+ expect(commands.syncExecuteCommand(UndoCommand.id)).toBe(true);+ expect(manager.getTable('unit', 'table')).toBeUndefined();+ expect(commands.syncExecuteCommand(RedoCommand.id)).toBe(true);+ expect(manager.getTable('unit', 'table')!.toJSON().columns).toEqual(columns);+ });++ it('generates a unique name for a conflicting name and leaves no table for missing parameters', () => {+ const injector = createUniver();+ const commands = injector.get(ICommandService);+ const manager = injector.get(TableManager);+ expect(commands.syncExecuteCommand(AddSheetTableCommand.id)).toBe(false);+ expect(manager.getTableList('unit')).toHaveLength(0);+ expect(commands.syncExecuteCommand(AddSheetTableCommand.id, {+ unitId: 'unit',+ subUnitId: 'sheet',+ id: 'table',+ name: 'Source',+ range: { startRow: 0, endRow: 2, startColumn: 2, endColumn: 3 },+ })).toBe(true);+ expect(manager.getTable('unit', 'table')!.getDisplayName()).toBe('Table1');+ });+});diff --git a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.tsindex 4163090a14..1917dafb91 100644--- a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts+++ b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts@@ -14,7 +14,6 @@* limitations under the License.*/-import type { ITableManualFilterItem } from '../../../types/type';import { ICommandService, ILogService, IUndoRedoService, IUniverInstanceService, LocaleService } from '@univerjs/core';import { IDefinedNamesService } from '@univerjs/engine-formula';import {@@ -24,6 +23,7 @@ import {SheetRangeThemeModel,} from '@univerjs/sheets';import { describe, expect, it, vi } from 'vitest';+import type { ITableManualFilterItem } from '../../../types/type';import { TableManager } from '../../../models/table-manager';import { TableColumnFilterTypeEnum } from '../../../types/enum';import { IRangeOperationTypeEnum, IRowColTypeEnum } from '../../../types/type';@@ -31,7 +31,6 @@ import { AddSheetTableMutation } from '../../mutations/add-sheet-table.mutation'import { DeleteSheetTableMutation } from '../../mutations/delete-sheet-table.mutation';import { SetSheetTableMutation } from '../../mutations/set-sheet-table.mutation';import { SetSheetTableFilterMutation } from '../../mutations/set-table-filter.mutation';-import { AddSheetTableCommand } from '../add-sheet-table.command';import { AddTableThemeCommand } from '../add-table-theme.command';import { DeleteSheetTableCommand } from '../delete-sheet-table.command';import { RemoveTableThemeCommand } from '../remove-table-theme.command';@@ -51,58 +50,6 @@ function createAccessor(pairs: Array<[unknown, unknown]>) {}describe('sheets-table commands', () => {- it('AddSheetTableCommand should auto-generate table name and push undo/redo', () => {- const syncExecuteCommand = vi.fn(() => true);- const pushUndoRedo = vi.fn();- const tableManager = {- getTableList: vi.fn(() => [{ name: 'table9' }]),- getColumnHeader: vi.fn(() => ['Name']),- };-- const accessor = createAccessor([- [ICommandService, { syncExecuteCommand }],- [IUndoRedoService, { pushUndoRedo }],- [LocaleService, { t: (key: string) => (key === 'sheets-table.tablePrefix' ? 'Table' : 'Column') }],- [TableManager, tableManager],- [IUniverInstanceService, {- getUnit: () => ({ getSheets: () => [{ getName: () => 'SheetA' }] }),- }],- [IDefinedNamesService, {- getDefinedNameMap: () => ({ d1: { name: 'DefinedA' } }),- }],- ]);-- const result = AddSheetTableCommand.handler(accessor, {- unitId: 'u1',- subUnitId: 's1',- range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },- name: 'SheetA',- });-- expect(result).toBe(true);- expect(tableManager.getColumnHeader).toHaveBeenCalledWith(- 'u1',- 's1',- { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },- 'Column'- );- expect(syncExecuteCommand).toHaveBeenCalledWith(- AddSheetTableMutation.id,- expect.objectContaining({- unitId: 'u1',- subUnitId: 's1',- name: 'Table10',- header: ['Name'],- }),- undefined- );- expect(pushUndoRedo).toHaveBeenCalledTimes(1);- });-- it('AddSheetTableCommand should return false when params are missing', () => {- expect(AddSheetTableCommand.handler(createAccessor([]), undefined as any)).toBe(false);- });-it('DeleteSheetTableCommand should build undo mutations from table snapshot', () => {const syncExecuteCommand = vi.fn(() => true);const pushUndoRedo = vi.fn();diff --git a/packages/sheets-table/src/commands/commands/add-sheet-table.command.ts b/packages/sheets-table/src/commands/commands/add-sheet-table.command.tsindex 6c04ddc586..4d9ef106de 100644--- a/packages/sheets-table/src/commands/commands/add-sheet-table.command.ts+++ b/packages/sheets-table/src/commands/commands/add-sheet-table.command.ts@@ -15,8 +15,6 @@*/import type { ICommand, IMutationInfo, IRange } from '@univerjs/core';-import type { LocaleKey } from '../../locale/types';-import type { ITableOptions } from '../../types/type';import {CommandType,customNameCharacterCheck,@@ -26,8 +24,12 @@ import {IUniverInstanceService,LocaleService,sequenceExecute,+ Tools,} from '@univerjs/core';import { IDefinedNamesService } from '@univerjs/engine-formula';+import type { LocaleKey } from '../../locale/types';+import type { ITableOptions } from '../../types/type';+import { TableColumn } from '../../models/table-column';import { TableManager } from '../../models/table-manager';import { getExistingNamesSet } from '../../util';import { AddSheetTableMutation } from '../mutations/add-sheet-table.mutation';@@ -83,8 +85,11 @@ export const AddSheetTableCommand: ICommand<IAddSheetTableCommandParams> = {const { unitId, subUnitId, range } = params;const header = tableManager.getColumnHeader(unitId, subUnitId, range, localeService.t<LocaleKey>('sheets-table.columnPrefix'));+ const options = Tools.deepClone(params.options ?? {});+ options.columns = header.map((name, index) =>+ options.columns?.[index] ?? new TableColumn(generateRandomId(), name).toJSON());- redos.push({ id: AddSheetTableMutation.id, params: { ...params, tableId, name: tableName, header } });+ redos.push({ id: AddSheetTableMutation.id, params: { ...params, tableId, name: tableName, header, options } });undos.push({ id: DeleteSheetTableMutation.id, params: { tableId, unitId: params.unitId } });const res = sequenceExecute(redos, commandService);diff --git a/packages/sheets-ui/src/menu/__tests__/mobile-schema.spec.ts b/packages/sheets-ui/src/menu/__tests__/mobile-schema.spec.tsdeleted file mode 100644index 72003472ec..0000000000--- a/packages/sheets-ui/src/menu/__tests__/mobile-schema.spec.ts+++ /dev/null@@ -1,41 +0,0 @@-/**- * 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 { MenuSchemaType } from '@univerjs/ui';-import { ContextMenuGroup, ContextMenuPosition } from '@univerjs/ui';-import { describe, expect, it } from 'vitest';-import { mobileMenuSchema } from '../mobile-schema';-import { menuSchema } from '../schema';--interface IContextMenuGroupSchema {- mobileLayout?: 'grid' | 'list';- quickLayout?: 'icon' | 'tile';-}--function getQuickGroup(schema: MenuSchemaType): IContextMenuGroupSchema {- const contextMenu = schema as Record<string, MenuSchemaType>;- const mainArea = contextMenu[ContextMenuPosition.MAIN_AREA] as Record<string, MenuSchemaType>;- return mainArea[ContextMenuGroup.QUICK] as IContextMenuGroupSchema;-}--describe('mobile menu schema', () => {- it('keeps the mobile clipboard group in a list without changing the desktop tile layout', () => {- expect(getQuickGroup(mobileMenuSchema)).toMatchObject({ mobileLayout: 'list' });- expect(getQuickGroup(mobileMenuSchema).quickLayout).toBeUndefined();- expect(getQuickGroup(menuSchema)).toMatchObject({ quickLayout: 'tile' });- expect(getQuickGroup(menuSchema).mobileLayout).toBeUndefined();- });-});