Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const groupingColumnsControllerExtender = (
Base: ModuleType<ColumnsController>,
): ModuleType<ColumnsController> => class GroupingColumnsExtender extends Base {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
public _getExpandColumnOptions() {
protected _getExpandColumnOptions() {
const options = super._getExpandColumnOptions();

options.cellTemplate = gridCore.getExpandCellTemplate();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,358 @@
import {
afterEach, beforeEach, describe, expect, it, jest,
} from '@jest/globals';
import type { Properties as DataGridProperties } from '@js/ui/data_grid';
import errors from '@js/ui/widget/ui.errors';
import { variableWrapper } from '@ts/core/utils/variable_wrapper';
import type { ColumnsController } from '@ts/grids/grid_core/columns_controller/columns_controller';
import type { Column, ColumnsControllerOptions } from '@ts/grids/grid_core/columns_controller/types';

import type { DataGridInstance } from '../../__tests__/__mock__/helpers/utils';
import {
afterTest,
beforeTest,
createDataGrid,
} from '../../__tests__/__mock__/helpers/utils';

interface Grid {
instance: DataGridInstance;
columnsController: ColumnsController;
}

type GridOptions = Omit<DataGridProperties, 'columns'> & ColumnsControllerOptions & {
columns?: (Column | string)[];
};

const createGrid = async ({ columns, ...options }: GridOptions): Promise<Grid> => {
const { instance } = await createDataGrid({
dataSource: [],
...options,
columns: columns as DataGridProperties['columns'],
});

return { instance, columnsController: instance.getController('columns') };
};

const getColumns = async (
columns: (Column | string)[],
options: GridOptions = {},
): Promise<Column[]> => {
const { columnsController } = await createGrid({ ...options, columns });

return columnsController.getColumns();
};

describe('column creation', () => {
beforeEach(beforeTest);
afterEach(afterTest);

describe('from the columns option', () => {
it('should create a column from a data field string', async () => {
const [column] = await getColumns(['firstName']);

expect(column).toMatchObject({ dataField: 'firstName', name: 'firstName', caption: 'First Name' });
});

it('should keep the passed column options', async () => {
const [column] = await getColumns([{ dataField: 'age', width: 100 }]);

expect(column.dataField).toBe('age');
expect(column.width).toBe(100);
});

it('should skip empty column options', async () => {
// @ts-expect-error JS users can leave empty items in the columns option
const columns = await getColumns([null, '', undefined, 'a']);

expect(columns.map((column) => column.dataField)).toEqual(['a']);
});

it('should set the name on the passed column options', async () => {
const columnOptions: Column = { dataField: 'age' };

await getColumns([columnOptions]);

expect(columnOptions.name).toBe('age');
});

it('should give each column its own header id', async () => {
const [first, second] = await getColumns(['a', 'b']);

expect(first.headerId).toMatch(/^dx-col-\d+$/);
expect(second.headerId).toMatch(/^dx-col-\d+$/);
expect(first.headerId).not.toBe(second.headerId);
});

it('should not give a header id to a column with a type', async () => {
const [column] = await getColumns([{ type: 'buttons' }]);

expect(column.headerId).toBeUndefined();
});

it('should apply the default column options', async () => {
const [column] = await getColumns(['a']);

expect(column).toMatchObject({ visible: true, showInColumnChooser: true });
});

it('should apply the grid-level column settings', async () => {
const [column] = await getColumns(['a'], { columnMinWidth: 50 });

expect(column.minWidth).toBe(50);
});

it.each([
['the default options', { visible: false }, 'visible', false],
['the grid-level settings', { minWidth: 10 }, 'minWidth', 10],
['the calculated options', { caption: 'Name' }, 'caption', 'Name'],
])('should let the column options override %s', async (_, columnOptions, optionName, expected) => {
const [column] = await getColumns([{ dataField: 'firstName', ...columnOptions }], { columnMinWidth: 50 });

expect(column).toHaveProperty(optionName, expected);
});

it('should not take the selector from the column options', async () => {
const selector = (): number => 1;

const [column] = await getColumns([{ dataField: 'a', selector }]);

expect(column.selector).not.toBe(selector);
});

it('should copy a command column without the default and grid-level settings', async () => {
const columnOptions: Column = { type: 'expand', command: 'expand' };

const [column] = await getColumns([columnOptions], { columnMinWidth: 50 });

expect(column).not.toBe(columnOptions);
expect(column).toMatchObject({ type: 'expand', command: 'expand' });
expect(column.visible).toBeUndefined();
expect(column.minWidth).toBeUndefined();
expect(column.headerId).toBeUndefined();
});

it('should link the filter operations to the default ones when the column options set neither', async () => {
const [column] = await getColumns(['a'], {
commonColumnSettings: { defaultFilterOperations: ['=', '<>'] },
});

expect(column.filterOperations).toEqual(['=', '<>']);
expect(column.filterOperations).toBe(column.defaultFilterOperations);
});

it('should keep the filter operations the column options set', async () => {
const [column] = await getColumns([{ dataField: 'a', filterOperations: ['contains'] }], {
commonColumnSettings: { defaultFilterOperations: ['=', '<>'] },
});

expect(column.filterOperations).toEqual(['contains']);
});
});

describe('for band columns', () => {
it('should put band children right after their band and link them to it', async () => {
const columns = await getColumns([
{ caption: 'Band', columns: ['a', { dataField: 'b' }] },
'c',
]);

expect(columns.map((column) => column.caption)).toEqual(['Band', 'A', 'B', 'C']);
expect(columns[1].ownerBand).toBe(0);
expect(columns[2].ownerBand).toBe(0);
expect(columns[0].ownerBand).toBeUndefined();
expect(columns[3].ownerBand).toBeUndefined();
});

it('should replace the band child options with the hasColumns flag', async () => {
const [band] = await getColumns([{ caption: 'Band', columns: ['a'] }]);

expect(band.hasColumns).toBe(true);
expect(band).not.toHaveProperty('columns');
});

it('should flatten nested bands depth-first', async () => {
const columns = await getColumns([
{ caption: 'Outer', columns: [{ caption: 'Inner', columns: ['x'] }, 'y'] },
]);

expect(columns.map((column) => column.caption)).toEqual(['Outer', 'Inner', 'X', 'Y']);
expect(columns[1].ownerBand).toBe(0);
expect(columns[2].ownerBand).toBe(1);
expect(columns[3].ownerBand).toBe(0);
});

it('should disable fixing for a band child', async () => {
const [column, , child] = await getColumns(
['a', { caption: 'Band', columns: ['b'] }],
{ columnFixing: { enabled: true } },
);

expect(column.allowFixing).toBe(true);
expect(child.allowFixing).toBe(false);
});

it('should warn once about unsupported options in band children', async () => {
const log = jest.spyOn(errors, 'log').mockImplementation(jest.fn());
const columns = [{ caption: 'Band', columns: [{ dataField: 'a', fixed: true }] }];
const { instance } = await createGrid({ columns });

instance.option('columns', columns);

const warnings = log.mock.calls.filter(([id]) => id === 'W1028');
log.mockRestore();
expect(warnings).toEqual([['W1028', 'fixed']]);
});
});

describe('with a user state', () => {
it('should take the data field from the user state of a named column', async () => {
const columnOptions: Column = { name: 'n', dataField: 'original' };
const { columnsController } = await createGrid({ columns: ['a', columnOptions] });

columnsController.setUserState([{ name: 'a', dataField: 'a' }, { name: 'n', dataField: 'renamed' }]);

const [, column] = columnsController.getColumns();
expect(column.dataField).toBe('renamed');
expect(column.caption).toBe('Renamed');
expect(columnOptions.dataField).toBe('original');
});

it('should keep inherited column options when the user state changes the data field', async () => {
const columnOptions = Object.create({ width: 100 }) as Column;
columnOptions.name = 'n';
columnOptions.dataField = 'original';
const { columnsController } = await createGrid({ columns: [columnOptions] });

columnsController.setUserState([{ name: 'n', dataField: 'renamed' }]);

const [column] = columnsController.getColumns();
expect(column.caption).toBe('Renamed');
expect(column.width).toBe(100);
});

it.each([
['has no name', { dataField: 'renamed' }],
['has no data field', { name: 'n' }],
])('should calculate the column from its own data field when the user state %s', async (_, userState) => {
const { columnsController } = await createGrid({ columns: [{ name: 'n', dataField: 'original' }] });

columnsController.setUserState([userState]);

expect(columnsController.getColumns()[0].caption).toBe('Original');
});

it('should look up the user state of a band child by its position in the flat list', async () => {
const { columnsController } = await createGrid({
columns: [{ name: 'band', caption: 'Band', columns: [{ name: 'child', dataField: 'original' }] }],
});

columnsController.setUserState([{ name: 'band' }, { name: 'child', dataField: 'renamed' }]);

const [, child] = columnsController.getColumns();
expect(child.dataField).toBe('renamed');
expect(child.caption).toBe('Renamed');
});
});

describe('when a column is added', () => {
it('should create the added column', async () => {
const { instance, columnsController } = await createGrid({ columns: ['a'] });

instance.addColumn('firstName');

const [first, added] = columnsController.getColumns();
expect(added).toMatchObject({ dataField: 'firstName', caption: 'First Name', visible: true });
expect(added.headerId).toMatch(/^dx-col-\d+$/);
expect(added.headerId).not.toBe(first.headerId);
});

it('should create the children of an added band', async () => {
const { instance, columnsController } = await createGrid({ columns: ['a'] });

instance.addColumn({ caption: 'Band', columns: ['b', 'c'] });

const columns = columnsController.getColumns();
expect(columns.map((column) => column.caption)).toEqual(['A', 'Band', 'B', 'C']);
expect(columns[2].ownerBand).toBe(1);
expect(columns[3].ownerBand).toBe(1);
});
});
});

describe('column generation from the data source', () => {
beforeEach(beforeTest);
afterEach(() => {
variableWrapper.resetInjection();
afterTest();
});

const getDataFields = async (
dataSource: DataGridProperties['dataSource'],
): Promise<(string | undefined)[]> => {
const { columnsController } = await createGrid({ dataSource });

return columnsController.getColumns().map((column) => column.dataField);
};

it('should create a column for each field of the loaded items', async () => {
expect(await getDataFields([{ id: 1, name: 'Alex' }])).toEqual(['id', 'name']);
});

it('should take each field once, in the order it first appears', async () => {
const dataFields = await getDataFields([{ id: 1, name: 'Alex' }, { id: 2, age: 30 }]);

expect(dataFields).toEqual(['id', 'name', 'age']);
});

it('should put integer-like field names first, as object keys do', async () => {
expect(await getDataFields([{ id: 1, b: 1 }, { id: 2, 1: 'x' }])).toEqual(['1', 'id', 'b']);
});

it('should include inherited fields', async () => {
const item = Object.create({ inherited: 1 }) as Record<string, unknown>;
item.id = 1;
item.own = 2;

expect(await getDataFields([item])).toEqual(['id', 'own', 'inherited']);
});

it('should skip function fields', async () => {
expect(await getDataFields([{ id: 1, getName: (): string => 'Alex' }])).toEqual(['id']);
});

it('should keep wrapped function fields', async () => {
const observable = (): string => 'Alex';
variableWrapper.inject({ isWrapped: (value) => value === observable });

expect(await getDataFields([{ id: 1, name: observable }])).toEqual(['id', 'name']);
});

it('should skip service fields that start with a double underscore', async () => {
expect(await getDataFields([{ __KEY__: 1, id: 1, a__b: 2 }])).toEqual(['id', 'a__b']);
});

it('should skip empty items', async () => {
expect(await getDataFields([null, { id: 1 }])).toEqual(['id']);
});

it('should skip falsy primitive items even when their prototype has enumerable fields', async () => {
// eslint-disable-next-line no-extend-native -- the test needs a polluted prototype
Object.defineProperty(Number.prototype, 'polluted', { value: 'x', enumerable: true, configurable: true });

try {
expect(await getDataFields([0, { id: 1 }])).toEqual(['id']);
} finally {
Reflect.deleteProperty(Number.prototype, 'polluted');
}
});

it('should take the fields of the items in the first group', async () => {
const dataFields = await getDataFields({ store: [{ city: 'Rome', id: 1 }], group: 'city' });

expect(dataFields).toEqual(['city', 'id']);
});

it('should create no columns when there are no items', async () => {
expect(await getDataFields([])).toEqual([]);
});
});
Loading
Loading