Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(sheets-table): preserve imported table differential formats (#8087)

wpxp1234562b3d7f253aab
diff --git a/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts b/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts
index e0516cc6aa..929c6dcb89 100644
--- a/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts
+++ b/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts
@@ -34,6 +34,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import {
+ InterceptCellContentPriority,
INTERCEPTOR_POINT,
INumfmtService,
NumfmtService,
@@ -83,6 +84,7 @@ function createWorkbookData(
3: { v: '20%', t: CellValueType.STRING, s: 'textStyle' },
4: { v: 0, t: CellValueType.NUMBER },
5: { v: 0.009999999999999787, t: CellValueType.NUMBER, s: 'textStyle' },
+ 6: { v: 12.345, t: CellValueType.NUMBER, s: { n: null } },
},
},
},
@@ -183,6 +185,39 @@ describe('SheetsNumfmtCellContentController', () => {
univer.dispose();
});
+ it('formats runtime table number formats without persisting cell styles and respects direct formats', () => {
+ get(SheetsNumfmtCellContentController);
+ get(SheetInterceptorService).intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
+ priority: InterceptCellContentPriority.TABLE_STYLE,
+ effect: InterceptorEffectEnum.Style | InterceptorEffectEnum.Value,
+ handler: (cell, location, next) => {
+ return next({ ...cell, themeStyle: { n: { pattern: '0.000' } } });
+ },
+ });
+ const worksheet = workbook.getSheetBySheetId('sheet1')!;
+ expect(getInterceptedCell(worksheet, workbook, 1, 1, get)?.v).toBe('1234.500');
+ expect(get(SheetInterceptorService).fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT, InterceptorEffectEnum.Value)(
+ worksheet.getCellRaw(1, 1),
+ { rawData: worksheet.getCellRaw(1, 1), workbook, worksheet, unitId: 'test', subUnitId: 'sheet1', row: 1, col: 1 }
+ )?.v).toBe('1234.500');
+ expect(worksheet.getCellRaw(1, 1)).toEqual({ v: '1234.5', t: CellValueType.STRING });
+ expect(getInterceptedCell(worksheet, workbook, 1, 6, get)?.v).toBe(12.345);
+ expect(worksheet.getCellRaw(1, 6)?.s).toEqual({ n: null });
+ numfmtService.setValues('test', 'sheet1', [{ pattern: '0.0', ranges: [cellToRange(1, 1)] }]);
+ expect(getInterceptedCell(worksheet, workbook, 1, 1, get)?.v).toBe('1234.5');
+ expect(getInterceptedCell(worksheet, workbook, 1, 0, get)?.v).toBe('123');
+ });
+
+ it('keeps legacy number-format lookup when no table dxf is present', () => {
+ get(SheetsNumfmtCellContentController);
+ const worksheet = workbook.getSheetBySheetId('sheet1')!;
+ expect(getInterceptedCell(worksheet, workbook, 1, 1, get)?.v).toBe('1234.5');
+ numfmtService.setValues('test', 'sheet1', [{ pattern: '0.00', ranges: [cellToRange(1, 1), cellToRange(1, 6)] }]);
+ expect(getInterceptedCell(worksheet, workbook, 1, 1, get)?.v).toBe('1234.50');
+ expect(getInterceptedCell(worksheet, workbook, 1, 6, get)?.v).toBe('12.35');
+ expect(workbook.getStyles().getStyleByCell(worksheet.getCellRaw(1, 6))?.n?.pattern).toBe('0.00');
+ });
+
it('skips unsupported cells and handles text format markers', () => {
get(SheetsNumfmtCellContentController);
const worksheet = workbook.getSheetBySheetId('sheet1')!;
diff --git a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
index 7269ecdaee..e261442f11 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
@@ -121,6 +121,18 @@ export class SheetsNumfmtCellContentController extends Disposable {
);
}
+ private _getNumfmtValue(cell: ICellDataForSheetInterceptor, location: ISheetLocation) {
+ const { unitId, subUnitId: sheetId, row, col, workbook } = location;
+ const tableDxfNumfmt = cell.themeStyle?.n;
+ if (tableDxfNumfmt === undefined) {
+ return workbook.getStyles().get(cell.s)?.n ?? this._numfmtService.getValue(unitId, sheetId, row, col);
+ }
+ const directNumfmt = workbook.getStyles().getStyleByCell(cell)?.n;
+ return directNumfmt !== undefined
+ ? directNumfmt
+ : this._numfmtService.getValue(unitId, sheetId, row, col) ?? tableDxfNumfmt;
+ }
+
private _formatCell(
cell: Nullable<ICellDataForSheetInterceptor>,
location: ISheetLocation & { rawData: Nullable<ICellData> }
@@ -132,7 +144,7 @@ export class SheetsNumfmtCellContentController extends Disposable {
const { unitId, subUnitId: sheetId, row, col, workbook } = location;
const locale = this.getLocale(workbook);
const dateSystem = workbook.getDateSystem();
- const numfmtValue = workbook.getStyles().get(cell.s)?.n ?? this._numfmtService.getValue(unitId, sheetId, row, col);
+ const numfmtValue = this._getNumfmtValue(cell, location);
const pattern = numfmtValue?.pattern;
// General must preserve numeric strings such as '001'.
if (isDefaultFormat(pattern)) {
diff --git a/packages/sheets-table/README.md b/packages/sheets-table/README.md
index 92360efb9b..d3bde42faf 100644
--- a/packages/sheets-table/README.md
+++ b/packages/sheets-table/README.md
@@ -48,3 +48,26 @@ Use this package with `@univerjs/sheets-table-ui` when users need table controls
- [Documentation](https://docs.univer.ai)
- [NPM package](https://npmjs.com/package/@univerjs/sheets-table)
- [GitHub repository](https://github.com/dream-num/univer)
+
+## Table differential formats
+
+Imported XLSX table themes and direct differential formats are separate. Table themes remain in the existing range-theme resource; direct formats remain in Table and TableColumn metadata. This support requires the matching Sheets and Sheets Numfmt implementations and a matching Office native importer/exporter. No new resource version field, column `style` mapping, Facade method or style editor is introduced.
+
+| Location | Format keys |
+| --- | --- |
+| `table.meta._xlsx.options` | `dataDxfStyle`, `headerRowDxfStyle`, `totalsRowDxfStyle`, `tableBorderDxfStyle`, `headerRowBorderDxfStyle`, `totalsRowBorderDxfStyle` |
+| `column.meta._xlsx` | `dataDxfStyle`, `headerRowDxfStyle`, `totalsRowDxfStyle` |
+
+Each format contains supported `IStyleData` properties. Fields beginning with an underscore preserve exchange information and are not rendered. The runtime applies the matching table region, then the matching column region by property, on top of the table theme. Explicit cell formats retain precedence; existing conditional-format processing remains separate. Border attributes are projected onto the current region boundary. Inside-horizontal and inside-vertical OOXML borders are not represented by the current frontend border model.
+
+The Sheets package exports its existing `RangeThemeInterceptorId`; table direct formats use the same identifier so reads that explicitly exclude inherited range formatting also exclude these formats. `InterceptCellContentPriority.TABLE_STYLE` places the metadata resolver before number formatting.
+
+Sheets Table writes matching direct formats to the existing runtime `themeStyle`; the theme and number-format interceptors consume that value according to their existing interceptor order without adding JSON or snapshot fields. Without a matching dxf, theme assignment and number-format lookup retain their previous behavior. The dxf number-format fallback is enabled only when the current high-priority Table interceptor has supplied `themeStyle.n`.
+
+Formats follow the current table range and column identities, including inserted rows and table moves. For tables with dxf metadata, table and column metadata are retained when copying worksheets and undoing table deletion, and column shifts preserve column objects. Tables without dxf continue to use their original structural and restoration paths. An imported table that has direct formats but originally no theme does not receive the default table theme. Ordinary default-theme behavior for other tables is unchanged. Direct formats are import-only: no UI, Facade setter or dedicated editing command is provided.
+
+For internal creation and restoration, `AddSheetTableMutation` accepts optional `meta`; `TableManager.addTable` and `SheetTableService.addTable` accept the same metadata as an optional final argument. Metadata is installed before the table-added event. Existing calls remain valid and do not add empty table metadata when the argument is omitted. The manager restores supplied column metadata only for tables with dxf; ordinary column initialization retains its previous behavior.
+
+The matching exporter treats an existing metadata container as authoritative: deleting a dxf key clears that direct format instead of reviving a stale native field or raw XML attribute. If the container is absent, legacy native fields remain readable. Raw dxf XML matching the current supported properties is retained; edits use the supported encoder and may lose unsupported extensions. These export consistency rules do not expose frontend dxf editing; mutating a metadata object directly is not a supported undoable formatting operation.
+
+New importers no longer materialize direct table formats into cell styles or use the old empty `rust-direct-dxf-*` theme. Older runtimes do not dynamically consume the new import result even if they save its metadata. Older bindings do not guarantee the new metadata edit/clear semantics. Upgrade the runtime and native exchange components together. Historical materialized snapshots are not automatically rewritten; re-import the original XLSX when possible. Published package combinations and Excel rendering require separate consumer validation.
diff --git a/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts b/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts
index de5478b237..26998a47da 100644
--- a/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts
+++ b/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts
@@ -15,9 +15,10 @@
*/
import type { ICommand, IMutationInfo } from '@univerjs/core';
-import type { IDeleteSheetTableParams } from '../mutations/delete-sheet-table.mutation';
-import { CommandType, ICommandService, ILogService, IUndoRedoService, sequenceExecute } from '@univerjs/core';
+import { CommandType, ICommandService, ILogService, IUndoRedoService, sequenceExecute, Tools } from '@univerjs/core';
import { SheetInterceptorService } from '@univerjs/sheets';
+import type { IDeleteSheetTableParams } from '../mutations/delete-sheet-table.mutation';
+import { hasTableDxfStyles } from '../../models/table-dxf';
import { TableManager } from '../../models/table-manager';
import { AddSheetTableMutation } from '../mutations/add-sheet-table.mutation';
import { DeleteSheetTableMutation } from '../mutations/delete-sheet-table.mutation';
@@ -67,7 +68,10 @@ export const DeleteSheetTableCommand: ICommand<IDeleteSheetTableParams> = {
tableId: params.tableId,
name: tableConfig.name,
range: tableConfig.range,
- options: tableConfig.options,
+ ...(hasTableDxfStyles(tableConfig) ? { meta: Tools.deepClone(tableConfig.meta) } : {}),
+ options: hasTableDxfStyles(tableConfig)
+ ? { ...tableConfig.options, columns: Tools.deepClone(tableConfig.columns) }
+ : tableConfig.options,
},
});
tableConfig.filters.tableColumnFilterList?.forEach((tableFilter, column) => {
diff --git a/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.ts b/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.ts
index 77d9bd553d..4d1a9d1ef2 100644
--- a/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.ts
+++ b/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import type { IWorkbookData, Workbook } from '@univerjs/core';
+import { LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import { TableManager } from '../../../models/table-manager';
import { SheetTableService } from '../../../services/table.service';
@@ -45,31 +47,36 @@ function accessorForTableManager(tableManager: TableManager) {
}
describe('sheets-table mutations', () => {
- it('AddSheetTableMutation should delegate to SheetTableService.addTable', () => {
- const service = {
- addTable: vi.fn(),
- } as unknown as SheetTableService;
-
- const result = AddSheetTableMutation.handler(accessorForService(service), {
- unitId: 'u1',
- subUnitId: 's1',
- tableId: 't1',
- name: 'Table',
- header: ['A'],
- range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
- options: { showHeader: true },
- });
-
- expect(result).toBe(true);
- expect(service.addTable).toHaveBeenCalledWith(
- 'u1',
- 's1',
- 'Table',
- { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
- ['A'],
- 't1',
- { showHeader: true }
- );
+ it('AddSheetTableMutation preserves table metadata through the real service and model', () => {
+ const univer = new Univer();
+ try {
+ const injector = univer.__getInjector();
+ injector.add([TableManager]);
+ injector.add([SheetTableService]);
+ univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {
+ id: 'u1',
+ name: 'Tables',
+ appVersion: '1.0.0',
+ locale: LocaleType.EN_US,
+ sheetOrder: ['s1'],
+ styles: {},
+ sheets: { s1: { id: 's1', name: 'Sheet', rowCount: 10, columnCount: 4, cellData: {} } },
+ });
+ const meta = { _xlsx: { options: { dataDxfStyle: { n: { pattern: '0.00' } } } } };
+ expect(AddSheetTableMutation.handler(injector, {
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ name: 'Table',
+ header: ['A', 'B'],
+ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },
+ options: { showHeader: true },
+ meta,
+ })).toBe(true);
+ expect(injector.get(TableManager).getTable('u1', 't1')!.toJSON().meta).toEqual(meta);
+ } finally {
+ univer.dispose();
+ }
});
it('DeleteSheetTableMutation should delegate to SheetTableService.deleteTable', () => {
diff --git a/packages/sheets-table/src/commands/mutations/add-sheet-table.mutation.ts b/packages/sheets-table/src/commands/mutations/add-sheet-table.mutation.ts
index 9f8ef269d3..414d8abf71 100644
--- a/packages/sheets-table/src/commands/mutations/add-sheet-table.mutation.ts
+++ b/packages/sheets-table/src/commands/mutations/add-sheet-table.mutation.ts
@@ -15,8 +15,8 @@
*/
import type { IMutation } from '@univerjs/core';
-import type { ITableOptions, ITableRange } from '../../types/type';
import { CommandType } from '@univerjs/core';
+import type { ITableOptions, ITableRange, TableMetaType } from '../../types/type';
import { SheetTableService } from '../../services/table.service';
export interface IAddSheetTableParams {
@@ -28,15 +28,16 @@ export interface IAddSheetTableParams {
options?: ITableOptions;
tableId?: string;
header?: string[];
+ meta?: TableMetaType;
}
export const AddSheetTableMutation: IMutation<IAddSheetTableParams & { tableId: string }> = {
id: 'sheet.mutation.add-table',
type: CommandType.MUTATION,
handler: (accessor, params) => {
- const { tableId, unitId, subUnitId, name, range, header, options } = params;
+ const { tableId, unitId, subUnitId, name, range, header, options, meta } = params;
const sheetTableService = accessor.get(SheetTableService);
- sheetTableService.addTable(unitId, subUnitId, name, range, header, tableId, options);
+ sheetTableService.addTable(unitId, subUnitId, name, range, header, tableId, options, meta);
return true;
},
};
diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-theme.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-theme.controller.spec.ts
index 85918955df..5c72cd9da1 100644
--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-theme.controller.spec.ts
+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-theme.controller.spec.ts
@@ -14,119 +14,173 @@
* limitations under the License.
*/
-import { Subject } from 'rxjs';
-import { describe, expect, it, vi } from 'vitest';
+import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
+import { BooleanNumber, ICommandService, IUniverInstanceService, LocaleService, LocaleType, UndoCommand, Univer, UniverInstanceType } from '@univerjs/core';
+import { FUniver } from '@univerjs/core/facade';
+import { RangeThemeInterceptorId, RangeThemeStyle, SheetInterceptorService, SheetRangeThemeModel, SheetRangeThemeService, UniverSheetsPlugin } from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DeleteSheetTableCommand } from '../../commands/commands/delete-sheet-table.command';
+import { AddSheetTableMutation } from '../../commands/mutations/add-sheet-table.mutation';
+import { DeleteSheetTableMutation } from '../../commands/mutations/delete-sheet-table.mutation';
+import { PLUGIN_NAME } from '../../const';
+import enUS from '../../locale/en-US';
+import { Table } from '../../models/table';
+import { TableManager } from '../../models/table-manager';
+import { UniverSheetsTablePlugin } from '../../plugin';
+import { SheetTableService } from '../../services/table.service';
import { SheetsTableThemeController } from '../sheet-table-theme.controller';
+import { SheetsTableController } from '../sheets-table.controller';
+import '@univerjs/sheets/facade';
describe('SheetsTableThemeController', () => {
- it('should initialize themes and react to table theme lifecycle events', () => {
- const tableAdd$ = new Subject<any>();
- const tableRangeChanged$ = new Subject<any>();
- const tableThemeChanged$ = new Subject<any>();
- const tableDelete$ = new Subject<any>();
-
- const table = {
- getTableStyleId: vi.fn(() => undefined),
- setTableStyleId: vi.fn(),
- getRange: vi.fn(() => ({ startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 })),
- };
-
- const tableManager = {
- tableAdd$,
- tableRangeChanged$,
- tableThemeChanged$,
- tableDelete$,
- getTable: vi.fn(() => table),
- };
-
- const sheetRangeThemeService = {
- registerRangeThemeStyle: vi.fn(),
- removeRangeThemeRule: vi.fn(),
- };
- const sheetRangeThemeModel = {
- registerDefaultRangeTheme: vi.fn(),
- };
- const configService = {
- getConfig: vi.fn(() => ({
- defaultThemeIndex: 1,
- userThemes: [{ name: 'user-theme', style: {} }],
- })),
- };
-
- const controller = new SheetsTableThemeController(
- tableManager as any,
- sheetRangeThemeService as any,
- sheetRangeThemeModel as any,
- configService as any
- );
-
- expect(sheetRangeThemeModel.registerDefaultRangeTheme).toHaveBeenCalledTimes(7);
-
- tableAdd$.next({
- unitId: 'u1',
- subUnitId: 's1',
- tableId: 't1',
- tableStyleId: '',
- range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },
- });
-
- expect(table.setTableStyleId).toHaveBeenCalledWith('table-default-0');
- expect(sheetRangeThemeService.registerRangeThemeStyle).toHaveBeenCalledWith('table-default-0', {
- unitId: 'u1',
- subUnitId: 's1',
- range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },
- });
-
- tableRangeChanged$.next({
- unitId: 'u1',
- subUnitId: 's1',
- tableId: 't1',
- oldRange: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },
- range: { startRow: 1, endRow: 5, startColumn: 1, endColumn: 2 },
- });
-
- expect(sheetRangeThemeService.removeRangeThemeRule).toHaveBeenCalledWith('table-default-0', {
- unitId: 'u1',
- subUnitId: 's1',
- range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },
- });
- expect(sheetRangeThemeService.registerRangeThemeStyle).toHaveBeenCalledWith('table-default-0', {
- unitId: 'u1',
- subUnitId: 's1',
- range: { startRow: 1, endRow: 5, startColumn: 1, endColumn: 2 },
- });
-
- tableThemeChanged$.next({
- unitId: 'u1',
- subUnitId: 's1',
- tableId: 't1',
- oldTheme: 'table-default-0',
- theme: 'table-default-1',
- });
-
- expect(sheetRangeThemeService.removeRangeThemeRule).toHaveBeenCalledWith('table-default-0', {
- unitId: 'u1',
- subUnitId: 's1',
- range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },
- });
- expect(sheetRangeThemeService.registerRangeThemeStyle).toHaveBeenCalledWith('table-default-1', {
- unitId: 'u1',
- subUnitId: 's1',
- range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },
+ let univer: Univer;
+ let workbook: Workbook;
+ let manager: TableManager;
+ beforeEach(() => {
+ univer = new Univer();
+ const injector = univer.__getInjector();
+ const dependencies: Dependency[] = [
+ [SheetTableService],
+ [TableManager],
+ [SheetInterceptorService],
+ [SheetRangeThemeModel],
+ [SheetRangeThemeService],
+ [SheetsTableThemeController],
+ [SheetsTableController],
+ ];
+ dependencies.forEach((dependency) => injector.add(dependency));
+ const locale = injector.get(LocaleService);
+ locale.load({ enUS });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
+ injector.get(SheetInterceptorService);
+ injector.get(SheetRangeThemeModel);
+ injector.get(SheetsTableThemeController);
+ injector.get(SheetsTableController);
+ workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {
+ id: 'book',
+ appVersion: '1.0.0',
+ locale: LocaleType.EN_US,
+ name: 'Tables',
+ styles: {},
+ sheetOrder: ['sheet'],
+ sheets: { sheet: { id: 'sheet', name: 'Sheet', rowCount: 20, columnCount: 10, cellData: { 1: { 1: { v: 12 } }, 2: { 1: { v: 20, s: { bg: { rgb: '#abcdef' } } } } } } },
});
+ injector.get(IUniverInstanceService).focusUnit('book');
+ manager = injector.get(TableManager);
+ });
+ afterEach(() => univer.dispose());
+
+ it('keeps default themes and updates the registered range after moves and theme changes', () => {
+ const id = manager.addTable('book', 'sheet', 'Orders', { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }, ['Name', 'Amount']);
+ const table = manager.getTable('book', id)!;
+ const service = univer.__getInjector().get(SheetRangeThemeService);
+ expect(table.getTableStyleId()).toBe('table-default-0');
+ manager.setTableByConfig('book', id, { theme: 'table-default-1' });
+ const range = { startRow: 5, endRow: 8, startColumn: 2, endColumn: 3 };
+ manager.moveTable('book', id, 'sheet', range);
+ expect(service.getAppliedRangeThemeStyle({ unitId: 'book', subUnitId: 'sheet', range })).toBe('table-default-1');
+ });
- tableDelete$.next({
- unitId: 'u1',
- subUnitId: 's1',
- range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },
- });
+ it('keeps unformatted tables and nonmatching regions on the ordinary theme path', () => {
+ const id = manager.addTable('book', 'sheet', 'Orders', { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }, ['Name', 'Amount']);
+ const table = manager.getTable('book', id)!;
+ const sheet = workbook.getActiveSheet();
+ const model = univer.__getInjector().get(SheetRangeThemeModel);
+ expect(table.toJSON().meta).toBeUndefined();
+ expect(sheet.getCell(1, 1)?.themeStyle).toBe(model.getCellStyle('book', 'sheet', 1, 1));
+ expect(sheet.getComposedCellStyle(2, 1).bg?.rgb).toBe('#abcdef');
+ table.setTableMeta({ _xlsx: { options: { headerRowDxfStyle: { cl: { rgb: '#123456' } } } } });
+ expect(sheet.getCell(1, 1)?.themeStyle).toBe(model.getCellStyle('book', 'sheet', 1, 1));
+ expect(sheet.getCell(0, 1)?.themeStyle?.cl?.rgb).toBe('#123456');
+ expect(sheet.getCellRaw(1, 1)).toEqual({ v: 12 });
+ });
- expect(sheetRangeThemeService.removeRangeThemeRule).toHaveBeenCalledWith('table-default-0', {
- unitId: 'u1',
- subUnitId: 's1',
- range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },
- });
+ it('composes themes and table/column dxf metadata while leaving raw cells unchanged', () => {
+ univer.__getInjector().get(SheetRangeThemeModel).registerDefaultRangeTheme(new RangeThemeStyle('imported-theme', {
+ wholeStyle: { bg: { rgb: '#eeeeee' }, bl: BooleanNumber.TRUE },
+ headerRowStyle: { bg: { rgb: '#111111' } },
+ }));
+ const id = manager.addTable('book', 'sheet', 'Orders', { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }, ['Name', 'Amount'], undefined, { tableStyleId: 'imported-theme' }, { _xlsx: { options: { dataDxfStyle: { cl: { rgb: '#123456' } } } } });
+ const table = manager.getTable('book', id)!;
+ table.getTableColumnByIndex(1)!.setMeta({ _xlsx: { dataDxfStyle: { n: { pattern: '0.00' }, bl: BooleanNumber.FALSE } } });
+ const sheet = workbook.getActiveSheet();
+ expect(sheet.getComposedCellStyle(1, 1)).toMatchObject({ bg: { rgb: '#eeeeee' }, cl: { rgb: '#123456' }, bl: BooleanNumber.FALSE, n: { pattern: '0.00' } });
+ expect(sheet.getComposedCellStyle(2, 1).bg?.rgb).toBe('#abcdef');
+ expect(sheet.getCellRaw(1, 1)).toEqual({ v: 12 });
+ expect(sheet.getCellWithFilteredInterceptors(1, 1, RangeThemeInterceptorId, (interceptor) => interceptor.id !== RangeThemeInterceptorId)?.themeStyle).toBeUndefined();
+ expect(sheet.getCellStyleOnly(1, 1)?.themeStyle?.n?.pattern).toBe('0.00');
+ expect(manager.toJSON('book').sheet.tables[0].columns[1].meta._xlsx.dataDxfStyle.n.pattern).toBe('0.00');
+ const range = { startRow: 5, endRow: 8, startColumn: 2, endColumn: 3 };
+ manager.moveTable('book', id, 'sheet', range);
+ expect(sheet.getComposedCellStyle(6, 3).n?.pattern).toBe('0.00');
+ expect(sheet.getComposedCellStyle(1, 1).n).toBeUndefined();
+ });
- controller.dispose();
+ it('does not add a default theme to an imported unstyled table with direct formats', () => {
+ const id = manager.addTable('book', 'sheet', 'Orders', { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }, ['Name', 'Amount'], undefined, {}, { _xlsx: { rawTableXml: '<table/>', options: { dataDxfStyle: { n: { pattern: '0.00' } } } } });
+ expect(manager.getTable('book', id)!.getTableStyleId()).toBe('');
+ manager.moveTable('book', id, 'sheet', { startRow: 5, endRow: 8, startColumn: 2, endColumn: 3 });
+ expect(manager.getTable('book', id)!.getTableStyleId()).toBe('');
+ expect(workbook.getActiveSheet().getComposedCellStyle(6, 3).n?.pattern).toBe('0.00');
+ });
+ it('preserves table and column dxf metadata through deletion and undo', async () => {
+ const injector = univer.__getInjector();
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(DeleteSheetTableCommand);
+ commands.registerCommand(DeleteSheetTableMutation);
+ commands.registerCommand(AddSheetTableMutation);
+ const id = manager.addTable('book', 'sheet', 'Orders', { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }, ['Name', 'Amount'], undefined, {}, { _xlsx: { options: { dataDxfStyle: { n: { pattern: '0.00' } } } } });
+ manager.getTable('book', id)!.getTableColumnByIndex(1)!.setMeta({ _xlsx: { headerRowDxfStyle: { bl: BooleanNumber.FALSE } } });
+ const before = JSON.parse(JSON.stringify(manager.getTable('book', id)!.toJSON()));
+ expect(await commands.executeCommand(DeleteSheetTableCommand.id, { unitId: 'book', subUnitId: 'sheet', tableId: id })).toBe(true);
+ expect(manager.getTable('book', id)).toBeUndefined();
+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);
+ expect(manager.getTable('book', id)!.toJSON()).toMatchObject(before);
+ });
+ it('keeps theme identity and all region metadata through actual Facade structural edits and save', async () => {
+ const headless = new Univer();
+ try {
+ const locale = headless.__getInjector().get(LocaleService);
+ locale.load({ enUS });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
+ headless.registerPlugin(UniverSheetsPlugin);
+ headless.registerPlugin(UniverSheetsTablePlugin);
+ const table = new Table('orders', 'Orders', { startRow: 0, endRow: 4, startColumn: 0, endColumn: 1 }, ['Name', 'Amount'], { tableStyleId: 'table-default-0', showFooter: true });
+ table.setTableMeta({ _xlsx: { options: {
+ dataDxfStyle: { n: { pattern: '0.00' } },
+ headerRowDxfStyle: { bl: BooleanNumber.FALSE },
+ totalsRowDxfStyle: { n: { pattern: '0.000' } },
+ } } });
+ table.getTableColumnByIndex(1)!.setMeta({ _xlsx: {
+ dataDxfStyle: { n: { pattern: '0.0000' } },
+ headerRowDxfStyle: { cl: { rgb: '#123456' } },
+ totalsRowDxfStyle: { bl: BooleanNumber.TRUE },
+ } });
+ const before = JSON.parse(JSON.stringify(table.toJSON()));
+ const api = FUniver.newAPI(headless);
+ const book = api.createWorkbook({ id: 'facade-book', name: 'Facade', appVersion: '1.0.0', locale: LocaleType.EN_US, styles: {}, sheetOrder: ['data'], sheets: { data: { id: 'data', name: 'Data', rowCount: 20, columnCount: 10, cellData: { 0: { 0: { v: 'Name' }, 1: { v: 'Amount' } }, 1: { 0: { v: 'A' }, 1: { v: 10 } }, 2: { 0: { v: 'B' }, 1: { v: 20 } } } } }, resources: [{ name: PLUGIN_NAME, data: JSON.stringify({ data: { tables: [before], tableFilteredOutRows: [] } }) }] });
+ headless.__getInjector().get(IUniverInstanceService).focusUnit('facade-book');
+ book.getActiveSheet().insertRows(0, 1);
+ book.getActiveSheet().deleteRows(2, 1);
+ book.getActiveSheet().insertColumns(0, 1);
+ book.getActiveSheet().deleteColumns(0, 1);
+ book.getActiveSheet().deleteColumns(1, 1);
+ expect(await headless.__getInjector().get(ICommandService).executeCommand(UndoCommand.id)).toBe(true);
+ const saved = book.save();
+ const resource = saved.resources!.find((item) => item.name === PLUGIN_NAME)!;
+ const after = JSON.parse(resource.data).data.tables[0];
+ expect(after.options.tableStyleId).toBe(before.options.tableStyleId);
+ expect(after.meta).toEqual(before.meta);
+ expect(after.columns.map((column: { meta: unknown }) => column.meta)).toEqual(before.columns.map((column: { meta: unknown }) => column.meta));
+ expect(after.range).toMatchObject({ startRow: 1, endRow: 4, startColumn: 0, endColumn: 1 });
+ const unit = headless.__getInjector().get(IUniverInstanceService).getUnit<Workbook>('facade-book')!;
+ expect(unit.getActiveSheet().getComposedCellStyle(2, 1).n?.pattern).toBe('0.0000');
+ expect(saved.sheets.data.cellData?.[2]?.[1]).toMatchObject({ v: 20 });
+ expect(saved.sheets.data.cellData?.[2]?.[1]?.s).toBeUndefined();
+ } finally {
+ headless.dispose();
+ }
});
});
diff --git a/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts b/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts
index 5cbe62338e..5e508289a4 100644
--- a/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts
+++ b/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts
@@ -21,8 +21,6 @@ import type {
IInsertRowMutationParams,
IRemoveRowColCommandParams,
} from '@univerjs/sheets';
-import type { LocaleKey } from '../locale/types';
-import type { ITableColumnJson, ITableJson } from '../types/type';
import {
Disposable,
ICommandService,
@@ -31,6 +29,7 @@ import {
IUniverInstanceService,
LocaleService,
Rectangle,
+ Tools,
} from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
import {
@@ -46,10 +45,13 @@ import {
RemoveRowMutation,
SheetInterceptorService,
} from '@univerjs/sheets';
+import type { LocaleKey } from '../locale/types';
+import type { ITableColumnJson, ITableJson } from '../types/type';
import { AddSheetTableMutation } from '../commands/mutations/add-sheet-table.mutation';
import { DeleteSheetTableMutation } from '../commands/mutations/delete-sheet-table.mutation';
import { SetSheetTableMutation } from '../commands/mutations/set-sheet-table.mutation';
import { getCalculatedColumnFillMutation } from '../commands/utils/calculated-column';
+import { hasTableDxfStyles } from '../models/table-dxf';
import { TableManager } from '../models/table-manager';
import { IRangeOperationTypeEnum, IRowColTypeEnum } from '../types/type';
import { convertCellDataToString, getColumnName } from '../util';
@@ -74,21 +76,20 @@ export class SheetTableRefRangeController extends Disposable {
}
private _initCommandInterceptor() {
- const self = this;
this._sheetInterceptorService.interceptCommand({
priority: -1,
- getMutations(commandInfo) {
+ getMutations: (commandInfo) => {
const defaultReturn = { redos: [], undos: [] };
const { id, params } = commandInfo;
switch (id) {
case InsertRowCommand.id:
- return self._generateTableMutationWithInsertRow(params as IInsertRowCommandParams);
+ return this._generateTableMutationWithInsertRow(params as IInsertRowCommandParams);
case InsertColCommand.id:
- return self._generateTableMutationWithInsertCol(params as IInsertColCommandParams);
+ return this._generateTableMutationWithInsertCol(params as IInsertColCommandParams);
case RemoveRowCommand.id:
- return self._generateTableMutationWithRemoveRow(params as IRemoveRowColCommandParams);
+ return this._generateTableMutationWithRemoveRow(params as IRemoveRowColCommandParams);
case RemoveColCommand.id:
- return self._generateTableMutationWithRemoveCol(params as IRemoveRowColCommandParams);
+ return this._generateTableMutationWithRemoveCol(params as IRemoveRowColCommandParams);
}
return defaultReturn;
@@ -262,7 +263,10 @@ export class SheetTableRefRangeController extends Disposable {
tableId: tableJson.id,
name: tableJson.name,
range: tableJson.range,
- options: tableJson.options,
+ ...(hasTableDxfStyles(tableJson) ? { meta: Tools.deepClone(tableJson.meta) } : {}),
+ options: hasTableDxfStyles(tableJson)
+ ? { ...tableJson.options, columns: Tools.deepClone(tableJson.columns) }
+ : tableJson.options,
},
});
} else if (range.startRow > tableRange.startRow && range.startRow <= tableRange.endRow) {
@@ -398,7 +402,10 @@ export class SheetTableRefRangeController extends Disposable {
name: tableJson.name,
header,
range: tableJson.range,
- options: tableJson.options,
+ ...(hasTableDxfStyles(tableJson) ? { meta: Tools.deepClone(tableJson.meta) } : {}),
+ options: hasTableDxfStyles(tableJson)
+ ? { ...tableJson.options, columns: Tools.deepClone(tableJson.columns) }
+ : tableJson.options,
},
});
undos.push(...(formulaMutations.preUndos ?? []), ...formulaMutations.undos);
@@ -543,9 +550,10 @@ export class SheetTableRefRangeController extends Disposable {
name: tableJson.name,
header,
range: tableJson.range,
+ ...(hasTableDxfStyles(tableJson) ? { meta: Tools.deepClone(tableJson.meta) } : {}),
options: {
...tableJson.options,
- columns: tableJson.columns,
+ columns: hasTableDxfStyles(tableJson) ? Tools.deepClone(tableJson.columns) : tableJson.columns,
filters: tableJson.filters.tableColumnFilterList,
},
},
@@ -612,13 +620,16 @@ export class SheetTableRefRangeController extends Disposable {
allTables.forEach((table) => {
const tableRange = table.getRange();
if (range.startColumn <= tableRange.startColumn) {
- this._tableManager.updateTableRange(unitId, table.getId(), {
- newRange: {
- ...tableRange,
- startColumn: tableRange.startColumn + insertCount,
- endColumn: tableRange.endColumn + insertCount,
- },
- });
+ const newRange = {
+ ...tableRange,
+ startColumn: tableRange.startColumn + insertCount,
+ endColumn: tableRange.endColumn + insertCount,
+ };
+ if (hasTableDxfStyles(table.toJSON())) {
+ this._tableManager.moveTable(unitId, table.getId(), subUnitId, newRange);
+ } else {
+ this._tableManager.updateTableRange(unitId, table.getId(), { newRange });
+ }
}
});
} else if (commandInfo.id === RemoveRowMutation.id) {
@@ -646,13 +657,16 @@ export class SheetTableRefRangeController extends Disposable {
allTables.forEach((table) => {
const tableRange = table.getRange();
if (range.startColumn < tableRange.startColumn) {
- this._tableManager.updateTableRange(unitId, table.getId(), {
- newRange: {
- ...tableRange,
- startColumn: tableRange.startColumn - removeCount,
- endColumn: tableRange.endColumn - removeCount,
- },
- });
+ const newRange = {
+ ...tableRange,
+ startColumn: tableRange.startColumn - removeCount,
+ endColumn: tableRange.endColumn - removeCount,
+ };
+ if (hasTableDxfStyles(table.toJSON())) {
+ this._tableManager.moveTable(unitId, table.getId(), subUnitId, newRange);
+ } else {
+ this._tableManager.updateTableRange(unitId, table.getId(), { newRange });
+ }
}
});
}
diff --git a/packages/sheets-table/src/controllers/sheet-table-theme.controller.ts b/packages/sheets-table/src/controllers/sheet-table-theme.controller.ts
index c2657dfc1c..ee9dd39f71 100644
--- a/packages/sheets-table/src/controllers/sheet-table-theme.controller.ts
+++ b/packages/sheets-table/src/controllers/sheet-table-theme.controller.ts
@@ -14,10 +14,11 @@
* limitations under the License.
*/
-import type { ITableDefaultThemeStyle, IUniverSheetsTableConfig } from '../config/config';
import { Disposable, IConfigService, Inject } from '@univerjs/core';
import { RangeThemeStyle, SheetRangeThemeModel, SheetRangeThemeService } from '@univerjs/sheets';
+import type { ITableDefaultThemeStyle, IUniverSheetsTableConfig } from '../config/config';
import { SHEETS_TABLE_PLUGIN_CONFIG_KEY } from '../config/config';
+import { isImportedTableWithoutTheme } from '../models/table-dxf';
import { TableManager } from '../models/table-manager';
import { tableThemeConfig } from './table-theme.factory';
@@ -42,6 +43,10 @@ export class SheetsTableThemeController extends Disposable {
this._tableManager.tableAdd$.subscribe((event) => {
const { range, tableId, unitId, subUnitId, tableStyleId } = event;
const table = this._tableManager.getTable(unitId, tableId)!;
+ if (!tableStyleId && isImportedTableWithoutTheme(table)) {
+ table.setTableStyleId('');
+ return;
+ }
// If the tableStyleId is not set or is empty string, use the default theme
const _tableStyleId = tableStyleId || this._allThemes[this._defaultThemeIndex].name;
table.setTableStyleId(_tableStyleId);
@@ -58,6 +63,9 @@ export class SheetsTableThemeController extends Disposable {
const { range, oldRange, tableId, unitId, subUnitId, oldSubUnitId = subUnitId } = event;
const table = this._tableManager.getTable(unitId, tableId)!;
let tableStyleId = table.getTableStyleId();
+ if (!tableStyleId && isImportedTableWithoutTheme(table)) {
+ return;
+ }
if (!tableStyleId) {
tableStyleId = this._allThemes[this._defaultThemeIndex].name;
table.setTableStyleId(tableStyleId);
diff --git a/packages/sheets-table/src/controllers/sheets-table.controller.ts b/packages/sheets-table/src/controllers/sheets-table.controller.ts
index 9759b5d377..a840305089 100644
--- a/packages/sheets-table/src/controllers/sheets-table.controller.ts
+++ b/packages/sheets-table/src/controllers/sheets-table.controller.ts
@@ -16,8 +16,8 @@
import type { IMutationInfo, IRange, Workbook } from '@univerjs/core';
import type { ICopySheetCommandParams, IRemoveSheetCommandParams } from '@univerjs/sheets';
-import type { ITableResource } from '../types/type';
import {
+ composeStyles,
Disposable,
generateRandomId,
Inject,
@@ -26,12 +26,15 @@ import {
IUniverInstanceService,
Rectangle,
RTree,
+ Tools,
UniverInstanceType,
} from '@univerjs/core';
-import { CopySheetCommand, INTERCEPTOR_POINT, RemoveSheetCommand, SheetInterceptorService } from '@univerjs/sheets';
+import { CopySheetCommand, InterceptCellContentPriority, INTERCEPTOR_POINT, RangeThemeInterceptorId, RemoveSheetCommand, SheetInterceptorService } from '@univerjs/sheets';
+import type { ITableResource } from '../types/type';
import { AddSheetTableMutation } from '../commands/mutations/add-sheet-table.mutation';
import { DeleteSheetTableMutation } from '../commands/mutations/delete-sheet-table.mutation';
import { PLUGIN_NAME } from '../const';
+import { getTableDxfStyle, hasTableDxfStyles } from '../models/table-dxf';
import { TableManager } from '../models/table-manager';
export class SheetsTableController extends Disposable {
@@ -46,6 +49,7 @@ export class SheetsTableController extends Disposable {
this.registerTableChangeEvent();
this._initSnapshot();
this._initSheetChange();
+ this.registerTableStyleInterceptor();
this.registerTableHeaderInterceptor();
}
@@ -119,6 +123,30 @@ export class SheetsTableController extends Disposable {
);
}
+ registerTableStyleInterceptor() {
+ this.disposeWithMe(this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
+ id: RangeThemeInterceptorId,
+ effect: InterceptorEffectEnum.Style | InterceptorEffectEnum.Value,
+ priority: InterceptCellContentPriority.TABLE_STYLE,
+ handler: (cell, context, next) => {
+ const { row, col, unitId, subUnitId } = context;
+ const table = this.getContainerTableWithRange(unitId, subUnitId, {
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ });
+ const style = table && getTableDxfStyle(table, row, col);
+ if (!style) {
+ return next(cell);
+ }
+ const result = (!cell || cell === context.rawData) ? { ...context.rawData } : cell;
+ result.themeStyle = composeStyles(result.themeStyle, style);
+ return next(result);
+ },
+ }));
+ }
+
registerTableHeaderInterceptor() {
this.disposeWithMe(
this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
@@ -137,12 +165,9 @@ export class SheetsTableController extends Disposable {
const tableStartRow = tableRange.startRow;
if (tableStartRow === row) {
const columnName = table.getColumnNameByIndex(index);
- if (!cell || cell === context.rawData) {
- cell = { ...context.rawData };
- }
-
- cell.v = columnName;
- return next(cell);
+ const result = (!cell || cell === context.rawData) ? { ...context.rawData } : cell;
+ result.v = columnName;
+ return next(result);
}
}
}
@@ -235,9 +260,10 @@ export class SheetsTableController extends Disposable {
name: tableJson.name,
range: tableJson.range,
tableId: tableJson.id,
+ ...(hasTableDxfStyles(tableJson) ? { meta: Tools.deepClone(tableJson.meta) } : {}),
options: {
...tableJson.options,
- columns: tableJson.columns,
+ columns: hasTableDxfStyles(tableJson) ? Tools.deepClone(tableJson.columns) : tableJson.columns,
filters: tableJson.filters.tableColumnFilterList,
},
},
@@ -277,9 +303,10 @@ export class SheetsTableController extends Disposable {
sheetId: targetSubUnitId,
},
tableId,
+ ...(hasTableDxfStyles(tableJson) ? { meta: Tools.deepClone(tableJson.meta) } : {}),
options: {
...tableJson.options,
- columns: tableJson.columns,
+ columns: hasTableDxfStyles(tableJson) ? Tools.deepClone(tableJson.columns) : tableJson.columns,
filters: tableJson.filters.tableColumnFilterList,
},
},
diff --git a/packages/sheets-table/src/models/__tests__/table-dxf.spec.ts b/packages/sheets-table/src/models/__tests__/table-dxf.spec.ts
new file mode 100644
index 0000000000..5bfbfabed2
--- /dev/null
+++ b/packages/sheets-table/src/models/__tests__/table-dxf.spec.ts
@@ -0,0 +1,94 @@
+/**
+ * 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 { BooleanNumber, BorderStyleTypes } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { Table } from '../table';
+import { getTableDxfStyle, hasTableDxfStyles, isImportedTableWithoutTheme } from '../table-dxf';
+
+function fixture() {
+ const table = new Table('t', 'Orders', { startRow: 2, endRow: 6, startColumn: 1, endColumn: 3 }, ['A', 'B', 'C'], { showFooter: true });
+ table.setTableMeta({ _xlsx: { options: {
+ dataDxfStyle: { bg: { rgb: '#eeeeee' }, bl: BooleanNumber.TRUE },
+ headerRowDxfStyle: { bg: { rgb: '#111111' }, bl: BooleanNumber.TRUE },
+ totalsRowDxfStyle: { bg: { rgb: '#dddddd' } },
+ tableBorderDxfStyle: { bd: { t: { s: BorderStyleTypes.THIN }, b: { s: BorderStyleTypes.THIN }, l: { s: BorderStyleTypes.THIN }, r: { s: BorderStyleTypes.THIN } } },
+ headerRowBorderDxfStyle: { bd: { b: { s: BorderStyleTypes.DOUBLE } } },
+ totalsRowBorderDxfStyle: { bd: { t: { s: BorderStyleTypes.MEDIUM } } },
+ } } });
+ table.getTableColumnByIndex(1)!.setMeta({ _xlsx: {
+ dataDxfStyle: { n: { pattern: '0.00' }, bl: BooleanNumber.FALSE, _rawDxfId: 4 },
+ headerRowDxfStyle: { cl: { rgb: '#ffffff' } },
+ totalsRowDxfStyle: { n: { pattern: '0.000' } },
+ } });
+ return table;
+}
+
+describe('table differential formats', () => {
+ it('combines all nine table/column regions without leaking raw metadata or mutating the model', () => {
+ const table = fixture();
+ const before = JSON.stringify(table.toJSON());
+ expect(getTableDxfStyle(table, 2, 2)).toMatchObject({ bg: { rgb: '#111111' }, cl: { rgb: '#ffffff' }, bd: { b: { s: BorderStyleTypes.DOUBLE } } });
+ expect(getTableDxfStyle(table, 3, 2)).toEqual({ bg: { rgb: '#eeeeee' }, n: { pattern: '0.00' }, bl: BooleanNumber.FALSE });
+ expect(getTableDxfStyle(table, 6, 2)).toMatchObject({ bg: { rgb: '#dddddd' }, n: { pattern: '0.000' }, bd: { t: { s: BorderStyleTypes.MEDIUM }, b: { s: BorderStyleTypes.THIN } } });
+ expect(getTableDxfStyle(table, 3, 1)).toMatchObject({ bd: { l: { s: BorderStyleTypes.THIN } } });
+ expect(getTableDxfStyle(table, 3, 3)).toMatchObject({ bd: { r: { s: BorderStyleTypes.THIN } } });
+ expect(getTableDxfStyle(table, 0, 2)).toBeUndefined();
+ expect(JSON.stringify(table.toJSON())).toBe(before);
+ });
+
+ it('leaves tables without dxf and cells without a matching dxf unchanged', () => {
+ const table = new Table('plain', 'Plain', { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 }, ['A', 'B', 'C']);
+ table.setTableMeta({ custom: 'table' });
+ table.getTableColumnByIndex(1)!.setMeta({ custom: 'column' });
+ const before = JSON.stringify(table.toJSON());
+ expect(hasTableDxfStyles(table.toJSON())).toBe(false);
+ expect(getTableDxfStyle(table, 1, 1)).toBeUndefined();
+ expect(isImportedTableWithoutTheme(table)).toBe(false);
+ expect(JSON.stringify(table.toJSON())).toBe(before);
+ table.setTableMeta({ _xlsx: { options: { tableBorderDxfStyle: { bd: { l: { s: BorderStyleTypes.THIN } } } } } });
+ expect(hasTableDxfStyles(table.toJSON())).toBe(true);
+ expect(getTableDxfStyle(table, 1, 1)).toBeUndefined();
+ expect(getTableDxfStyle(table, 1, 0)?.bd?.l?.s).toBe(BorderStyleTypes.THIN);
+ });
+
+ it('follows range/header/footer changes and metadata removal', () => {
+ const table = fixture();
+ table.setRange({ startRow: 5, endRow: 10, startColumn: 4, endColumn: 6 });
+ expect(getTableDxfStyle(table, 6, 5)?.n?.pattern).toBe('0.00');
+ expect(getTableDxfStyle(table, 3, 2)).toBeUndefined();
+ table.setShowHeader(false);
+ table.fromJSON({ ...table.toJSON(), options: { ...table.toJSON().options, showFooter: false } });
+ expect(getTableDxfStyle(table, 5, 5)?.n?.pattern).toBe('0.00');
+ expect(getTableDxfStyle(table, 10, 5)?.n?.pattern).toBe('0.00');
+ table.getTableColumnByIndex(1)!.setMeta({ _xlsx: {} });
+ expect(getTableDxfStyle(table, 6, 5)?.n).toBeUndefined();
+ expect(getTableDxfStyle(table, 6, 5)?.bg?.rgb).toBe('#eeeeee');
+ });
+
+ it('recognizes imported direct formats without inventing a table theme', () => {
+ const table = fixture();
+ const meta = table.getTableMeta();
+ meta._xlsx.rawTableXml = '<table dataDxfId="0"/>';
+ expect(isImportedTableWithoutTheme(table)).toBe(true);
+ expect(table.getTableStyleId()).toBe('');
+ meta._xlsx.options = {};
+ table.getTableColumnByIndex(1)!.setMeta({ _xlsx: {} });
+ expect(table.getTableStyleId()).toBe('');
+ table.setTableStyleId('selected-theme');
+ expect(table.getTableStyleId()).toBe('selected-theme');
+ });
+});
diff --git a/packages/sheets-table/src/models/table-dxf.ts b/packages/sheets-table/src/models/table-dxf.ts
new file mode 100644
index 0000000000..54b93ae508
--- /dev/null
+++ b/packages/sheets-table/src/models/table-dxf.ts
@@ -0,0 +1,129 @@
+/**
+ * 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 { IBorderData, IStyleData } from '@univerjs/core';
+import { composeStyles } from '@univerjs/core';
+import type { ITableColumnJson, TableMetaType } from '../types/type';
+import type { Table } from './table';
+
+const TABLE_DXF_STYLE_KEYS = ['dataDxfStyle', 'headerRowDxfStyle', 'totalsRowDxfStyle', 'tableBorderDxfStyle', 'headerRowBorderDxfStyle', 'totalsRowBorderDxfStyle'] as const;
+
+type DxfStyleKey = typeof TABLE_DXF_STYLE_KEYS[number];
+
+type ITableDxfStyles = Partial<Record<DxfStyleKey, IStyleData>>;
+
+function tableDxfStyles(meta: TableMetaType | undefined): ITableDxfStyles | undefined {
+ return meta?._xlsx?.options;
+}
+
+function hasColumnDxfStyles(meta: TableMetaType | undefined): boolean {
+ return TABLE_DXF_STYLE_KEYS.slice(0, 3).some((key) => !!meta?._xlsx?.[key]);
+}
+
+export function hasTableDxfStyles(table: { meta?: TableMetaType; columns?: ITableColumnJson[] }): boolean {
+ const styles = tableDxfStyles(table.meta);
+ return TABLE_DXF_STYLE_KEYS.some((key) => !!styles?.[key])
+ || !!table.columns?.some((column) => hasColumnDxfStyles(column.meta));
+}
+
+export function isImportedTableWithoutTheme(table: Table): boolean {
+ const xlsx = table.getTableMeta()?._xlsx;
+ if (!xlsx?.rawTableXml || xlsx.options?.tableStyleId) {
+ return false;
+ }
+ if (/\b(?:dataDxfId|headerRowDxfId|totalsRowDxfId|tableBorderDxfId|headerRowBorderDxfId|totalsRowBorderDxfId)\s*=/.test(xlsx.rawTableXml)) {
+ return true;
+ }
+ const hasDxf = (styles: ITableDxfStyles | undefined) => styles && Object.keys(styles).some((key) => key.endsWith('DxfStyle'));
+ if (hasDxf(tableDxfStyles(table.getTableMeta()))) {
+ return true;
+ }
+ for (let index = 0; index < table.getColumnsCount(); index++) {
+ if (hasDxf(table.getTableColumnByIndex(index)?.getMeta()?._xlsx)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+function renderableStyle(style: IStyleData | undefined): IStyleData | undefined {
+ if (!style) {
+ return undefined;
+ }
+ return Object.fromEntries(Object.entries(style).filter(([key]) => !key.startsWith('_')));
+}
+
+function regionBorder(style: IStyleData | undefined, row: number, col: number, startRow: number, endRow: number, startColumn: number, endColumn: number): IStyleData | undefined {
+ if (!style?.bd || startRow > endRow) {
+ return undefined;
+ }
+ const bd: IBorderData = {};
+ if (row === startRow && style.bd.t !== undefined) {
+ bd.t = style.bd.t;
+ }
+ if (row === endRow && style.bd.b !== undefined) {
+ bd.b = style.bd.b;
+ }
+ if (col === startColumn && style.bd.l !== undefined) {
+ bd.l = style.bd.l;
+ }
+ if (col === endColumn && style.bd.r !== undefined) {
+ bd.r = style.bd.r;
+ }
+ return Object.keys(bd).length ? { bd } : undefined;
+}
+
+function composeDxfStyles(layers: Array<IStyleData | undefined>): IStyleData | undefined {
+ const style = composeStyles(...layers);
+ let border: IStyleData['bd'];
+ for (const layer of layers) {
+ if (layer?.bd === null) {
+ border = null;
+ } else if (layer?.bd) {
+ border = { ...border, ...Object.fromEntries(Object.entries(layer.bd).filter(([, value]) => value !== undefined)) };
+ }
+ }
+ if (border !== undefined) {
+ style.bd = border;
+ }
+ return Object.keys(style).length ? style : undefined;
+}
+
+/** Resolve table-owned formats without assigning a direct style to the cell. */
+export function getTableDxfStyle(table: Table, row: number, col: number): IStyleData | undefined {
+ const { startRow, endRow, startColumn, endColumn } = table.getRange();
+ if (row < startRow || row > endRow || col < startColumn || col > endColumn) {
+ return undefined;
+ }
+ const source = tableDxfStyles(table.getTableMeta());
+ const column = table.getTableColumnByIndex(col - startColumn)?.getMeta()?._xlsx as ITableDxfStyles | undefined;
+ const header = table.isShowHeader() && row === startRow;
+ const totals = table.isShowFooter() && row === endRow;
+ let key: DxfStyleKey = 'dataDxfStyle';
+ if (header) {
+ key = 'headerRowDxfStyle';
+ } else if (totals) {
+ key = 'totalsRowDxfStyle';
+ }
+ const layers = [
+ renderableStyle(source?.[key]),
+ renderableStyle(column?.[key]),
+ regionBorder(source?.tableBorderDxfStyle, row, col, startRow, endRow, startColumn, endColumn),
+ header ? regionBorder(source?.headerRowBorderDxfStyle, row, col, startRow, startRow, startColumn, endColumn) : undefined,
+ totals ? regionBorder(source?.totalsRowBorderDxfStyle, row, col, endRow, endRow, startColumn, endColumn) : undefined,
+ ];
+ return composeDxfStyles(layers);
+}
diff --git a/packages/sheets-table/src/models/table-manager.ts b/packages/sheets-table/src/models/table-manager.ts
index 40c8b527d6..66f154ea85 100644
--- a/packages/sheets-table/src/models/table-manager.ts
+++ b/packages/sheets-table/src/models/table-manager.ts
@@ -15,6 +15,9 @@
*/
import type { IRange, Workbook } from '@univerjs/core';
+import { Disposable, generateRandomId, Inject, IUniverInstanceService, LocaleService } from '@univerjs/core';
+import { getSheetCommandTarget } from '@univerjs/sheets';
+import { BehaviorSubject, Subject } from 'rxjs';
import type { LocaleKey } from '../locale/types';
import type {
ITableAddedEvent,
@@ -33,16 +36,15 @@ import type {
ITableResource,
ITableSetConfig,
ITableThemeChangedEvent,
+ TableMetaType,
} from '../types/type';
-import { Disposable, generateRandomId, Inject, IUniverInstanceService, LocaleService } from '@univerjs/core';
-import { getSheetCommandTarget } from '@univerjs/sheets';
-import { BehaviorSubject, Subject } from 'rxjs';
import {
IRangeOperationTypeEnum,
} from '../types/type';
import { convertCellDataToString, getColumnName } from '../util';
import { Table } from './table';
import { TableColumn } from './table-column';
+import { hasTableDxfStyles } from './table-dxf';
export class TableManager extends Disposable {
private _tableMap: Map<string, Map<string, Table>>;
@@ -106,10 +108,16 @@ export class TableManager extends Disposable {
* @param {ITableOptions} [options] Other options of the table.
* @returns {string} The table id.
*/
- addTable(unitId: string, subUnitId: string, name: string, range: ITableRange, header?: string[], initId?: string, options?: ITableOptions): string {
+ addTable(unitId: string, subUnitId: string, name: string, range: ITableRange, header?: string[], initId?: string, options?: ITableOptions, meta?: TableMetaType): string {
const id = initId ?? generateRandomId();
const tableHeader = header || this.getColumnHeader(unitId, subUnitId, range);
const table = new Table(id, name, range, tableHeader, options);
+ if (meta !== undefined) {
+ table.setTableMeta(meta);
+ }
+ if (options?.columns && hasTableDxfStyles({ meta, columns: options.columns })) {
+ options.columns.forEach((column, index) => table.getTableColumnByIndex(index)?.setMeta(column.meta));
+ }
// set subunit id to table
table.setSubunitId(subUnitId);
const unitMap = this._ensureUnit(unitId);
@@ -494,7 +502,7 @@ export class TableManager extends Disposable {
tables = data[subUnitId].tables;
} else if (Array.isArray(data[subUnitId])) {
// for older versions, where tables were not nested under subUnitId
- tables = data[subUnitId] as any as ITableJson[];
+ tables = data[subUnitId] as unknown as ITableJson[];
}
if (!tables) {
return;
diff --git a/packages/sheets-table/src/models/table.ts b/packages/sheets-table/src/models/table.ts
index 4906625a31..ef9b215ba6 100644
--- a/packages/sheets-table/src/models/table.ts
+++ b/packages/sheets-table/src/models/table.ts
@@ -14,10 +14,11 @@
* limitations under the License.
*/
-import type { ITableColumnJson, ITableFilterItem, ITableInfo, ITableJson, ITableOptions, ITableRange } from '../types/type';
import { generateRandomId } from '@univerjs/core';
+import type { ITableColumnJson, ITableFilterItem, ITableInfo, ITableJson, ITableOptions, ITableRange, TableMetaType } from '../types/type';
import { tableThemeConfig } from '../controllers/table-theme.factory';
import { TableColumn } from './table-column';
+import { isImportedTableWithoutTheme } from './table-dxf';
import { TableFilters } from './table-filter';
export class Table {
@@ -33,7 +34,7 @@ export class Table {
private _range: ITableRange;
private _columns: Map<string, TableColumn> = new Map();
private _columnOrder: string[] = [];
- tableMeta: Record<string, any>;
+ tableMeta: TableMetaType;
private _tableFilters: TableFilters;
private _subUnitId: string;
@@ -141,7 +142,7 @@ export class Table {
this._columnOrder.splice(index, 1);
}
- setTableMeta(meta: Record<string, any>) {
+ setTableMeta(meta: TableMetaType) {
this.tableMeta = meta;
}
@@ -198,6 +199,9 @@ export class Table {
}
getTableStyleId() {
+ if (!this._tableStyleId && isImportedTableWithoutTheme(this)) {
+ return '';
+ }
return this._tableStyleId ?? tableThemeConfig[0].name;
}
diff --git a/packages/sheets-table/src/services/table.service.ts b/packages/sheets-table/src/services/table.service.ts
index 3866bd26b5..7226d1a660 100644
--- a/packages/sheets-table/src/services/table.service.ts
+++ b/packages/sheets-table/src/services/table.service.ts
@@ -15,8 +15,8 @@
*/
import type { Worksheet } from '@univerjs/core';
-import type { ITableFilterItem, ITableInfoWithUnitId, ITableOptions, ITableRange, TableMetaType } from '../types/type';
import { Disposable, Inject } from '@univerjs/core';
+import type { ITableFilterItem, ITableInfoWithUnitId, ITableOptions, ITableRange, TableMetaType } from '../types/type';
import { getCellValueWithConditionType } from '../models/filter-util/condition';
import { TableManager } from '../models/table-manager';
import { TableConditionTypeEnum } from '../types/enum';
@@ -43,8 +43,8 @@ export class SheetTableService extends Disposable {
return this._tableManager.getTableList(unitId);
}
- addTable(unitId: string, subUnitId: string, tableName: string, rangeInfo: ITableRange, tableHeader?: string[], tableId?: string, options?: ITableOptions): string {
- return this._tableManager.addTable(unitId, subUnitId, tableName, rangeInfo, tableHeader, tableId, options);
+ addTable(unitId: string, subUnitId: string, tableName: string, rangeInfo: ITableRange, tableHeader?: string[], tableId?: string, options?: ITableOptions, meta?: TableMetaType): string {
+ return this._tableManager.addTable(unitId, subUnitId, tableName, rangeInfo, tableHeader, tableId, options, meta);
}
deleteTable(unitId: string, subUnitId: string, tableId: string) {
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index f06e593cad..45bbba9a5e 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -645,7 +645,7 @@ export {
export type { MutationsAffectRange } from './services/ref-range/util';
export * from './services/selections';
export { getNextPrimaryCell } from './services/selections/move-active-cell-util';
-export { InterceptCellContentPriority, INTERCEPTOR_POINT } from './services/sheet-interceptor/interceptor-const';
+export { InterceptCellContentPriority, INTERCEPTOR_POINT, RangeThemeInterceptorId } from './services/sheet-interceptor/interceptor-const';
export {
AFTER_CELL_EDIT,
BEFORE_CELL_EDIT,
diff --git a/packages/sheets/src/models/range-theme-model.ts b/packages/sheets/src/models/range-theme-model.ts
index a97859d806..a985a90488 100644
--- a/packages/sheets/src/models/range-theme-model.ts
+++ b/packages/sheets/src/models/range-theme-model.ts
@@ -16,6 +16,7 @@
import type { ICellDataForSheetInterceptor, IRange, Nullable, Workbook } from '@univerjs/core';
import {
+ composeStyles,
Disposable,
generateRandomId,
Inject,
@@ -351,7 +352,15 @@ export class SheetRangeThemeModel extends Disposable {
if (style) {
const newCell: ICellDataForSheetInterceptor = (!cell || cell === context.rawData) ? { ...context.rawData } : cell;
- newCell.themeStyle = style;
+ const inheritedStyle = newCell.themeStyle;
+ if (!inheritedStyle) {
+ newCell.themeStyle = style;
+ return next(newCell);
+ }
+ newCell.themeStyle = composeStyles(style, inheritedStyle);
+ if (style.bd && inheritedStyle?.bd) {
+ newCell.themeStyle.bd = { ...style.bd, ...inheritedStyle.bd };
+ }
return next(newCell);
}
diff --git a/packages/sheets/src/services/sheet-interceptor/interceptor-const.ts b/packages/sheets/src/services/sheet-interceptor/interceptor-const.ts
index 2bc107dd88..67910c0c9c 100644
--- a/packages/sheets/src/services/sheet-interceptor/interceptor-const.ts
+++ b/packages/sheets/src/services/sheet-interceptor/interceptor-const.ts
@@ -15,8 +15,8 @@
*/
import type { ICellData, ICellDataForSheetInterceptor, ICellInterceptor, Nullable } from '@univerjs/core';
-import type { ISheetLocation, ISheetRowLocation } from './utils/interceptor';
import { createInterceptorKey } from '@univerjs/core';
+import type { ISheetLocation, ISheetRowLocation } from './utils/interceptor';
const CELL_CONTENT = createInterceptorKey<ICellDataForSheetInterceptor, ISheetLocation & { rawData: Nullable<ICellData> }>('CELL_CONTENT') as ICellInterceptor<ICellDataForSheetInterceptor, ISheetLocation & { rawData: Nullable<ICellData> }>;
const ROW_FILTERED = createInterceptorKey<boolean, ISheetRowLocation>('ROW_FILTERED');
@@ -30,6 +30,7 @@ export enum InterceptCellContentPriority {
DATA_VALIDATION = 9,
NUMFMT = 10,
CELL_IMAGE = 11,
+ TABLE_STYLE = 12,
}
// used for define the range theme interceptor, it will also use to ignore the range theme interceptor
export const RangeThemeInterceptorId = 'sheet.interceptor.range-theme-id';