diff --git a/packages/devextreme/js/__internal/grids/data_grid/grouping/extenders/grouping_columns_controller.ts b/packages/devextreme/js/__internal/grids/data_grid/grouping/extenders/grouping_columns_controller.ts index 094b7377d61a..2b67c3676510 100644 --- a/packages/devextreme/js/__internal/grids/data_grid/grouping/extenders/grouping_columns_controller.ts +++ b/packages/devextreme/js/__internal/grids/data_grid/grouping/extenders/grouping_columns_controller.ts @@ -6,7 +6,7 @@ export const groupingColumnsControllerExtender = ( Base: ModuleType, ): ModuleType => 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(); diff --git a/packages/devextreme/js/__internal/grids/grid_core/columns_controller/__tests__/columns_controller.column_creation.test.ts b/packages/devextreme/js/__internal/grids/grid_core/columns_controller/__tests__/columns_controller.column_creation.test.ts new file mode 100644 index 000000000000..02900d17909e --- /dev/null +++ b/packages/devextreme/js/__internal/grids/grid_core/columns_controller/__tests__/columns_controller.column_creation.test.ts @@ -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 & ColumnsControllerOptions & { + columns?: (Column | string)[]; +}; + +const createGrid = async ({ columns, ...options }: GridOptions): Promise => { + 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 => { + 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; + 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([]); + }); +}); diff --git a/packages/devextreme/js/__internal/grids/grid_core/columns_controller/__tests__/columns_controller_utils.test.ts b/packages/devextreme/js/__internal/grids/grid_core/columns_controller/__tests__/columns_controller_utils.test.ts index 8dd188150f4d..f16b4494bab9 100644 --- a/packages/devextreme/js/__internal/grids/grid_core/columns_controller/__tests__/columns_controller_utils.test.ts +++ b/packages/devextreme/js/__internal/grids/grid_core/columns_controller/__tests__/columns_controller_utils.test.ts @@ -4,15 +4,10 @@ import { import type { Response as SendRequestResult } from '@js/common/ai-integration'; import config from '@js/core/config'; import type { Properties as DataGridProperties } from '@js/ui/data_grid'; -import errors from '@js/ui/widget/ui.errors'; import { AIIntegration } from '@ts/core/ai_integration/core/ai_integration'; -import { variableWrapper } from '@ts/core/utils/variable_wrapper'; import type { ColumnsController } from '@ts/grids/grid_core/columns_controller/columns_controller'; import { columnOptionCore, - createColumn, - createColumnsFromDataSourceAdapter, - createColumnsFromOptions, customizeTextForBooleanDataType, digitsCount, findColumn, @@ -336,342 +331,6 @@ describe('strictParseNumber', () => { }); }); -describe('createColumn', () => { - beforeEach(beforeTest); - afterEach(afterTest); - - it.each([ - ['undefined', undefined], - ['an empty string', ''], - ])('should return undefined for %s', async (_, columnOptions) => { - const columnsController = await getColumnsController(); - - expect(createColumn(columnsController, columnOptions)).toBeUndefined(); - }); - - it('should create a column from a data field string', async () => { - const columnsController = await getColumnsController(); - - const column = createColumn(columnsController, 'firstName'); - - expect(column).toMatchObject({ dataField: 'firstName', name: 'firstName', caption: 'First Name' }); - }); - - it('should set the name on the passed column options', async () => { - const columnsController = await getColumnsController(); - const columnOptions: Column = { dataField: 'age' }; - - createColumn(columnsController, columnOptions); - - expect(columnOptions.name).toBe('age'); - }); - - it('should give each column its own header id', async () => { - const columnsController = await getColumnsController(); - - const first = createColumn(columnsController, 'a'); - const second = createColumn(columnsController, '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 columnsController = await getColumnsController(); - - expect(createColumn(columnsController, { type: 'buttons' })?.headerId).toBeUndefined(); - }); - - it('should apply the default column options', async () => { - const columnsController = await getColumnsController(); - - expect(createColumn(columnsController, 'a')).toMatchObject({ visible: true, showInColumnChooser: true }); - }); - - it('should apply the grid-level column settings', async () => { - const columnsController = await getColumnsController({ columnMinWidth: 50 }); - - expect(createColumn(columnsController, 'a')?.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 columnsController = await getColumnsController({ columnMinWidth: 50 }); - - const column = createColumn(columnsController, { dataField: 'firstName', ...columnOptions }); - - expect(column).toHaveProperty(optionName, expected); - }); - - it('should reset the selector', async () => { - const columnsController = await getColumnsController(); - - const column = createColumn(columnsController, { dataField: 'a', selector: (): number => 1 }); - - expect(column?.selector).toBeNull(); - }); - - it('should disable fixing for a band child', async () => { - const columnsController = await getColumnsController({ columnFixing: { enabled: true } }); - const bandColumn: Column = { caption: 'Band' }; - - expect(createColumn(columnsController, 'a')?.allowFixing).toBe(true); - expect(createColumn(columnsController, 'a', undefined, bandColumn)?.allowFixing).toBe(false); - }); - - it('should copy a command column without the default and grid-level settings', async () => { - const columnsController = await getColumnsController({ columnMinWidth: 50 }); - const columnOptions: Column = { type: 'expand', command: 'expand' }; - - const column = createColumn(columnsController, columnOptions); - - expect(column).toEqual(columnOptions); - expect(column).not.toBe(columnOptions); - }); - - it('should take the data field from the user state of a named column', async () => { - const columnsController = await getColumnsController(); - const columnOptions: Column = { name: 'n', dataField: 'original' }; - - const column = createColumn(columnsController, columnOptions, { name: 'n', dataField: 'renamed' }); - - 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 columnsController = await getColumnsController(); - const columnOptions = Object.create({ width: 100 }) as Column; - columnOptions.name = 'n'; - columnOptions.dataField = 'original'; - - const column = createColumn(columnsController, columnOptions, { name: 'n', dataField: 'renamed' }); - - expect(column?.width).toBe(100); - }); - - it.each([ - ['has no name', { dataField: 'renamed' }], - ['has no data field', { name: 'n' }], - ])('should keep the data field when the user state %s', async (_, userState) => { - const columnsController = await getColumnsController(); - - const column = createColumn(columnsController, { name: 'n', dataField: 'original' }, userState); - - expect(column?.dataField).toBe('original'); - }); - - it('should link the filter operations to the default ones when the column options set neither', async () => { - const columnsController = await getColumnsController({ - commonColumnSettings: { defaultFilterOperations: ['=', '<>'] }, - }); - - const column = createColumn(columnsController, 'a'); - - expect(column?.filterOperations).toEqual(['=', '<>']); - expect(column?.filterOperations).toBe(column?.defaultFilterOperations); - }); - - it('should keep the filter operations the column options set', async () => { - const columnsController = await getColumnsController({ - commonColumnSettings: { defaultFilterOperations: ['=', '<>'] }, - }); - - const column = createColumn(columnsController, { dataField: 'a', filterOperations: ['contains'] }); - - expect(column?.filterOperations).toEqual(['contains']); - }); -}); - -describe('createColumnsFromOptions', () => { - beforeEach(beforeTest); - afterEach(afterTest); - - it('should return an empty array when there are no column options', async () => { - const columnsController = await getColumnsController(); - - expect(createColumnsFromOptions(columnsController, undefined)).toEqual([]); - }); - - it('should create a column from a data field string', async () => { - const columnsController = await getColumnsController(); - - const [column] = createColumnsFromOptions(columnsController, ['firstName']); - - expect(column.dataField).toBe('firstName'); - expect(column.caption).toBe('First Name'); - }); - - it('should keep the passed column options', async () => { - const columnsController = await getColumnsController(); - - const [column] = createColumnsFromOptions(columnsController, [{ dataField: 'age', width: 100 }]); - - expect(column.dataField).toBe('age'); - expect(column.width).toBe(100); - }); - - it('should skip empty column options', async () => { - const columnsController = await getColumnsController(); - - // @ts-expect-error JS users can leave empty items in the columns option - const columns = createColumnsFromOptions(columnsController, [null, 'a']); - - expect(columns.map((column) => column.dataField)).toEqual(['a']); - }); - - it('should put band children right after their band and link them to it', async () => { - const columnsController = await getColumnsController(); - - const columns = createColumnsFromOptions(columnsController, [ - { caption: 'Band', columns: ['a', { dataField: 'b' }] }, - 'c', - ]); - - expect(columns.map((column) => column.caption)).toEqual(['Band', 'A', 'B', 'C']); - expect(columns[1].ownerBand).toBe(columns[0]); - expect(columns[2].ownerBand).toBe(columns[0]); - expect(columns[0].ownerBand).toBeUndefined(); - expect(columns[3].ownerBand).toBeUndefined(); - }); - - it('should replace the band child options with the hasColumns flag', async () => { - const columnsController = await getColumnsController(); - - const [band] = createColumnsFromOptions(columnsController, [{ caption: 'Band', columns: ['a'] }]); - - expect(band.hasColumns).toBe(true); - expect(band).not.toHaveProperty('columns'); - }); - - it('should flatten nested bands depth-first', async () => { - const columnsController = await getColumnsController(); - - const columns = createColumnsFromOptions(columnsController, [ - { caption: 'Outer', columns: [{ caption: 'Inner', columns: ['x'] }, 'y'] }, - ]); - - expect(columns.map((column) => column.caption)).toEqual(['Outer', 'Inner', 'X', 'Y']); - expect(columns[1].ownerBand).toBe(columns[0]); - expect(columns[2].ownerBand).toBe(columns[1]); - expect(columns[3].ownerBand).toBe(columns[0]); - }); - - it('should look up the user state of a band child by its position in the flat list', async () => { - const columnsController = await getColumnsController(); - columnsController.setUserState([ - { name: 'band' }, - { name: 'child', dataField: 'renamed' }, - ]); - - const columns = createColumnsFromOptions(columnsController, [ - { name: 'band', caption: 'Band', columns: [{ name: 'child', dataField: 'original' }] }, - ]); - - expect(columns[1].dataField).toBe('renamed'); - }); - - it('should warn once about unsupported options in band children', async () => { - const log = jest.spyOn(errors, 'log').mockImplementation(jest.fn()); - const columnsController = await getColumnsController(); - const columnsOptions = [{ caption: 'Band', columns: [{ dataField: 'a', fixed: true }] }]; - - createColumnsFromOptions(columnsController, columnsOptions); - createColumnsFromOptions(columnsController, columnsOptions); - - expect(log).toHaveBeenCalledTimes(1); - expect(log).toHaveBeenCalledWith('W1028', 'fixed'); - }); -}); - -describe('createColumnsFromDataSourceAdapter', () => { - beforeEach(beforeTest); - afterEach(() => { - variableWrapper.resetInjection(); - afterTest(); - }); - - const getDataFields = async ( - dataSource: DataGridProperties['dataSource'], - ): Promise<(string | undefined)[]> => { - const { instance } = await createDataGrid({ dataSource, columns: [] }); - const dataSourceAdapter = instance.getController('dataSource').getAdapter(); - - if (!dataSourceAdapter) { - throw new Error('The grid has no data source adapter'); - } - - return createColumnsFromDataSourceAdapter(instance.getController('columns'), dataSourceAdapter) - .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([{ b: 1 }, { 1: 'x' }])).toEqual(['1', 'b']); - }); - - it('should include inherited fields', async () => { - const item = Object.create({ inherited: 1 }) as Record; - item.own = 2; - - expect(await getDataFields([item])).toEqual(['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 return no columns when there are no items', async () => { - expect(await getDataFields([])).toEqual([]); - }); -}); - describe('isColumnFixed', () => { beforeEach(beforeTest); afterEach(afterTest); diff --git a/packages/devextreme/js/__internal/grids/grid_core/columns_controller/columns_controller.ts b/packages/devextreme/js/__internal/grids/grid_core/columns_controller/columns_controller.ts index 0f50b32c3016..2a1d7c948d1d 100644 --- a/packages/devextreme/js/__internal/grids/grid_core/columns_controller/columns_controller.ts +++ b/packages/devextreme/js/__internal/grids/grid_core/columns_controller/columns_controller.ts @@ -12,7 +12,7 @@ import type { DeferredObj } from '@js/core/utils/deferred'; import { Deferred, when } from '@js/core/utils/deferred'; import { extend } from '@js/core/utils/extend'; import { each, map } from '@js/core/utils/iterator'; -import { orderEach } from '@js/core/utils/object'; +import { deepExtendArraySafe, orderEach } from '@js/core/utils/object'; import { isDefined, isFunction, isNumeric, isObject, isPlainObject, isString, } from '@js/core/utils/type'; @@ -58,13 +58,8 @@ import modules from '../modules/modules'; import { StickyPosition } from '../sticky_columns/const'; import gridCoreUtils from '../utils'; import { - addExpandColumn, - assignColumns, columnOptionCore, convertOwnerBandToColumnReference, - createColumn, - createColumnsFromDataSourceAdapter, - createColumnsFromOptions, defaultSetCellValue, digitsCount, findColumn, @@ -85,6 +80,7 @@ import { isColumnNameRequired, isFirstOrLastColumn, isSortOrderValid, + isUserStateColumn, mergeColumns, numberToString, processBandColumns, @@ -105,13 +101,17 @@ import { COLUMN_CHOOSER_LOCATION, COLUMN_OPTION_REGEXP, DATATYPE_OPERATIONS, + DEFAULT_COLUMN_OPTIONS, DETAIL_COMMAND_COLUMN_NAME, GROUP_COMMAND_COLUMN_NAME, GROUP_LOCATION, + UNSUPPORTED_PROPERTIES_FOR_CHILD_COLUMNS, USER_STATE_FIELD_NAMES, } from './const'; import { UserStateApplier } from './user_state_applier'; +let globalColumnId = 1; + export class ColumnsController extends modules.Controller { public _skipProcessingColumnsChange!: string | boolean; @@ -121,7 +121,7 @@ export class ColumnsController extends modules.Controller { private _isColumnsFromOptions!: boolean; - public _columnsUserState?: SavedColumnState[] | null; + private columnsUserState?: SavedColumnState[] | null; private dataSourceAdapterApplied?: boolean; @@ -141,7 +141,7 @@ export class ColumnsController extends modules.Controller { public _reinitAfterLookupChanges?: boolean; - public _previousColumns?: Column[]; + private previousColumns?: Column[]; public _hasUserState!: boolean; @@ -155,7 +155,7 @@ export class ColumnsController extends modules.Controller { public _columnChanges?: ColumnsChanges; - public _isWarnedAboutUnsupportedProperties?: boolean; + private isWarnedAboutUnsupportedProperties?: boolean; private getCommonColumnSettings(column?: Column): Partial | undefined { switch (true) { @@ -186,18 +186,17 @@ export class ColumnsController extends modules.Controller { this._isColumnsFromOptions = !!columns; if (this._isColumnsFromOptions) { - assignColumns(this, columns ? createColumnsFromOptions(this, columns) : []); + this.assignColumns(columns ? this.createColumnsFromOptions(columns) : []); this.applyUserState(); } else { - assignColumns( - this, - this._columnsUserState - ? createColumnsFromOptions(this, this._columnsUserState) + this.assignColumns( + this.columnsUserState + ? this.createColumnsFromOptions(this.columnsUserState) : this._columns, ); } - addExpandColumn(this); + this.addExpandColumn(); if (this.dataSourceAdapterApplied) { this.applyDataSourceAdapter(this.appliedDataSourceAdapter, true, isApplyingUserState); @@ -208,7 +207,7 @@ export class ColumnsController extends modules.Controller { this._checkColumns(); } - public _getExpandColumnOptions(): Column { + protected _getExpandColumnOptions(): Column { return { type: 'expand', command: 'expand', @@ -318,7 +317,7 @@ export class ColumnsController extends modules.Controller { if (!this._skipProcessingColumnsChange) { if (args.fullName === 'columns') { - this._columnsUserState = null; + this.columnsUserState = null; this._ignoreColumnOptionNames = null; this.init(); } else { @@ -436,12 +435,11 @@ export class ColumnsController extends modules.Controller { } if (!this._isColumnsFromOptions) { - const columnsFromDataSourceAdapter = createColumnsFromDataSourceAdapter( - this, + const columnsFromDataSourceAdapter = this.createColumnsFromDataSourceAdapter( dataSourceAdapter, ); if (columnsFromDataSourceAdapter.length) { - assignColumns(this, columnsFromDataSourceAdapter); + this.assignColumns(columnsFromDataSourceAdapter); this.generatedColumnsCount = this._columns.length; this.applyUserState(); } @@ -479,7 +477,7 @@ export class ColumnsController extends modules.Controller { } public reinit(ignoreColumnOptionNames?: string[] | false): void { - this._columnsUserState = this.getUserState(); + this.columnsUserState = this.getUserState(); // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- false clears list this._ignoreColumnOptionNames = ignoreColumnOptionNames || null; this.init(); @@ -1279,12 +1277,12 @@ export class ColumnsController extends modules.Controller { private _updateColumnOptions(column: WithCellValueCalculator, columnIndex: number): void { const defaultSelector = (data: RawItemData): unknown => column.calculateCellValue(data); const shouldTakeOriginalCallbackFromPrevious = this._reinitAfterLookupChanges - && this._previousColumns?.[columnIndex]; + && this.previousColumns?.[columnIndex]; column.selector = column.selector ?? defaultSelector; column.selector.columnIndex = columnIndex; column.selector.originalCallback = shouldTakeOriginalCallbackFromPrevious - ? this._previousColumns?.[columnIndex].selector?.originalCallback ?? column.selector + ? this.previousColumns?.[columnIndex].selector?.originalCallback ?? column.selector : column.selector; [ @@ -1453,7 +1451,7 @@ export class ColumnsController extends modules.Controller { } customizeColumns(columns); - assignColumns(this, createColumnsFromOptions(this, columns)); + this.assignColumns(this.createColumnsFromOptions(columns)); } } @@ -1619,7 +1617,7 @@ export class ColumnsController extends modules.Controller { columnsOptions.push(sort.selector); } }); - assignColumns(this, createColumnsFromOptions(this, columnsOptions)); + this.assignColumns(this.createColumnsFromOptions(columnsOptions)); } const shouldApplyGrouping = (Boolean(needToApplyGroupingFromDataSource) @@ -1788,14 +1786,166 @@ export class ColumnsController extends modules.Controller { return this.getVisibleIndex(index, rowIndex); } + private createColumn( + columnOptions: Column, + userStateColumnOptions?: ColumnUserState, + bandColumn?: Column, + ): WithCellValueCalculator; + + private createColumn( + columnOptions: Column | string | undefined, + userStateColumnOptions?: ColumnUserState, + bandColumn?: Column, + ): WithCellValueCalculator | undefined; + + private createColumn( + columnOptions: Column | string | undefined, + userStateColumnOptions?: ColumnUserState, + bandColumn?: Column, + ): WithCellValueCalculator | undefined { + if (!columnOptions) { + return undefined; + } + + const options: Column = isString(columnOptions) ? { dataField: columnOptions } : columnOptions; + let result: Column = {}; + + this.setName(options); + + if (options.command) { + result = deepExtendArraySafe({}, options); + } else { + const commonColumnOptions = this.getCommonSettings(options); + const userStateDataField = userStateColumnOptions?.name && userStateColumnOptions.dataField; + const optionsWithUserState: Column = userStateDataField + ? extend({}, options, { dataField: userStateDataField }) + : options; + const calculatedColumnOptions = this.createCalculatedColumnOptions( + optionsWithUserState, + bandColumn, + ); + + if (!optionsWithUserState.type) { + result = { headerId: `dx-col-${globalColumnId}` }; + globalColumnId += 1; + } + + deepExtendArraySafe(result, DEFAULT_COLUMN_OPTIONS, false, true); + deepExtendArraySafe(result, commonColumnOptions, false, true); + deepExtendArraySafe(result, calculatedColumnOptions, false, true); + deepExtendArraySafe(result, optionsWithUserState, false, true); + deepExtendArraySafe(result, { selector: null }, false, true); + } + + if (options.filterOperations === options.defaultFilterOperations) { + setFilterOperationsAsDefaultValues(result); + } + + // @ts-expect-error the calculated options set calculateCellValue; command options are internal + return result; + } + + private createColumnsFromOptions( + columnsOptions: (Column | string | undefined)[], + bandColumn?: Column, + createdColumnCount = 0, + ): WithCellValueCalculator[] { + const result: WithCellValueCalculator[] = []; + + columnsOptions.forEach((columnOptions) => { + const currentIndex = createdColumnCount + result.length; + const userStateColumnOptions = this.columnsUserState + && isUserStateColumn(columnOptions as ColumnUserState, this.columnsUserState[currentIndex]) + && this.columnsUserState[currentIndex]; + const column = this.createColumn( + columnOptions, + userStateColumnOptions || undefined, + bandColumn, + ); + + if (!column) { + return; + } + + if (bandColumn) { + // @ts-expect-error ownerBand holds the band column until updateColumnIndexes sets its index + column.ownerBand = bandColumn; + } + + result.push(column); + + if (!column.columns) { + return; + } + + this.warnFixedInChildColumnsOnce(column.columns); + const childColumns = this.createColumnsFromOptions(column.columns, column, result.length); + delete column.columns; + column.hasColumns = true; + result.push(...childColumns); + }); + + return result; + } + + private warnFixedInChildColumnsOnce(childColumns: (Column | string)[]): void { + if (this.isWarnedAboutUnsupportedProperties) { + return; + } + + for (const column of childColumns) { + const unsupportedProperty = isObject(column) + ? UNSUPPORTED_PROPERTIES_FOR_CHILD_COLUMNS.find((property) => property in column) + : undefined; + + if (unsupportedProperty) { + this.isWarnedAboutUnsupportedProperties = true; + errors.log('W1028', unsupportedProperty); + return; + } + } + } + + private createColumnsFromDataSourceAdapter( + dataSourceAdapter: DataSourceAdapter, + ): WithCellValueCalculator[] { + const fieldNames: Record = {}; + + this._getFirstItems(dataSourceAdapter).forEach((item) => { + if (!item) { + return; + } + + // eslint-disable-next-line guard-for-in -- inherited fields become columns too + for (const fieldName in item) { + const value = item[fieldName]; + + if (!isFunction(value) || variableWrapper.isWrapped(value)) { + fieldNames[fieldName] = true; + } + } + }); + + return Object.keys(fieldNames) + .filter((fieldName) => !fieldName.startsWith('__')) + .map((fieldName) => this.createColumn(fieldName) as WithCellValueCalculator); + } + + private assignColumns(columns: WithCellValueCalculator[]): void { + this.previousColumns = this._columns; + this._columns = columns; + this.resetColumnsCache(); + this.updateColumnDataTypes(); + } + private addColumn(options: Column | string): void { - let column = createColumn(this, options) as WithCellValueCalculator; + let column = this.createColumn(options) as WithCellValueCalculator; const index = this._columns.length; this._columns.push(column); if (column.isBand) { - this._columns = createColumnsFromOptions(this, this._columns); + this._columns = this.createColumnsFromOptions(this._columns); column = this._columns[index]; } @@ -1825,6 +1975,12 @@ export class ColumnsController extends modules.Controller { } } + private addExpandColumn(): void { + const options = this._getExpandColumnOptions(); + + this.addCommandColumn(options); + } + public addCommandColumn(options: Column): void { let commandColumn = this._commandColumns.find((column) => ( column.command === options.command @@ -1837,7 +1993,7 @@ export class ColumnsController extends modules.Controller { } private applyUserState(): void { - const columnsUserState = this._columnsUserState; + const { columnsUserState } = this; if (!columnsUserState) { return; @@ -1848,17 +2004,16 @@ export class ColumnsController extends modules.Controller { columnsUserState, ignoreColumnOptionNames: this._ignoreColumnOptionNames ?? [], hasUserState: this._hasUserState, - createColumn: (columnOptions): WithCellValueCalculator => createColumn( - this, + createColumn: (columnOptions): WithCellValueCalculator => this.createColumn( isString(columnOptions) ? { dataField: columnOptions } : columnOptions, ), }).apply(); if (hasAddedBands) { updateColumnIndexes(this); - assignColumns(this, createColumnsFromOptions(this, columns)); + this.assignColumns(this.createColumnsFromOptions(columns)); } else { - assignColumns(this, columns); + this.assignColumns(columns); } } @@ -1880,7 +2035,7 @@ export class ColumnsController extends modules.Controller { return result; } - public setName(column: Column): void { + private setName(column: Column): void { if (!isColumnNameRequired(column)) { // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- skip empty names column.name = column.name || column.dataField || column.type; @@ -1930,7 +2085,7 @@ export class ColumnsController extends modules.Controller { state?.forEach(this.setName); - this._columnsUserState = state; + this.columnsUserState = state; this._ignoreColumnOptionNames = this.getIgnoreColumnOptionNames(); this._hasUserState = !!state; @@ -1985,7 +2140,7 @@ export class ColumnsController extends modules.Controller { } } - public _createCalculatedColumnOptions( + private createCalculatedColumnOptions( columnOptions: Column, bandColumn?: Column, ): Column { diff --git a/packages/devextreme/js/__internal/grids/grid_core/columns_controller/columns_controller_utils.ts b/packages/devextreme/js/__internal/grids/grid_core/columns_controller/columns_controller_utils.ts index 760b3df5099f..d0215b2bfdea 100644 --- a/packages/devextreme/js/__internal/grids/grid_core/columns_controller/columns_controller_utils.ts +++ b/packages/devextreme/js/__internal/grids/grid_core/columns_controller/columns_controller_utils.ts @@ -7,19 +7,15 @@ import { equalByValue } from '@js/core/utils/common'; import { compileGetter, compileSetter } from '@js/core/utils/data'; import dateSerialization from '@js/core/utils/date_serialization'; import { extend } from '@js/core/utils/extend'; -import { deepExtendArraySafe } from '@js/core/utils/object'; import { getDefaultAlignment } from '@js/core/utils/position'; import { - isDefined, isFunction, isNumeric, isObject, isString, type, + isDefined, isNumeric, isObject, isString, type, } from '@js/core/utils/type'; -import variableWrapper from '@js/core/utils/variable_wrapper'; import type { DataGridCommandColumnType } from '@js/ui/data_grid'; -import errors from '@js/ui/widget/ui.errors'; import { getNumberFormatLocale } from '@ts/core/global_format_config'; import { CLASSES as COLUMN_HEADERS_CLASSES } from '@ts/grids/grid_core/column_headers/const'; import { AI_COLUMN_NAME } from '../ai_column/const'; -import type DataSourceAdapter from '../data_source_adapter/data_source_adapter'; import type { RawItemData } from '../data_source_adapter/types'; import { StickyPosition } from '../sticky_columns/const'; import { getColumnFixedPosition } from '../sticky_columns/utils'; @@ -29,11 +25,9 @@ import { COLUMN_CHOOSER_LOCATION, COLUMN_INDEX_OPTIONS, COMMAND_COLUMNS_WITH_REQUIRED_NAMES, - DEFAULT_COLUMN_OPTIONS, GROUP_COMMAND_COLUMN_NAME, GROUP_LOCATION, IGNORE_COLUMN_OPTION_NAMES, - UNSUPPORTED_PROPERTIES_FOR_CHILD_COLUMNS, USER_STATE_FIELD_NAMES, USER_STATE_FIELD_NAMES_15_1, VIRTUAL_COMMAND_COLUMN_NAME, @@ -44,27 +38,6 @@ import type { DropLocationNames, GroupColumn, ValueSerializers, WithCellValueCalculator, } from './types'; -const warnFixedInChildColumnsOnce = ( - controller: ColumnsController, - childColumns: (Column | string)[], -): void => { - if (controller._isWarnedAboutUnsupportedProperties) { - return; - } - - for (const column of childColumns) { - const unsupportedProperty = isObject(column) - ? UNSUPPORTED_PROPERTIES_FOR_CHILD_COLUMNS.find((property) => property in column) - : undefined; - - if (unsupportedProperty) { - controller._isWarnedAboutUnsupportedProperties = true; - errors.log('W1028', unsupportedProperty); - return; - } - } -}; - export const hasCellValueCalculator = ( item: T, ): item is WithCellValueCalculator => Boolean(item.calculateCellValue); @@ -73,68 +46,6 @@ export const setFilterOperationsAsDefaultValues = (column: Column): void => { column.filterOperations = column.defaultFilterOperations; }; -let globalColumnId = 1; - -export function createColumn( - that: ColumnsController, - columnOptions: Column, - userStateColumnOptions?: ColumnUserState, - bandColumn?: Column, -): WithCellValueCalculator; -export function createColumn( - that: ColumnsController, - columnOptions: Column | string | undefined, - userStateColumnOptions?: ColumnUserState, - bandColumn?: Column, -): WithCellValueCalculator | undefined; -export function createColumn( - that: ColumnsController, - columnOptions: Column | string | undefined, - userStateColumnOptions?: ColumnUserState, - bandColumn?: Column, -): WithCellValueCalculator | undefined { - if (!columnOptions) { - return undefined; - } - - const options: Column = isString(columnOptions) ? { dataField: columnOptions } : columnOptions; - let result: Column = {}; - - that.setName(options); - - if (options.command) { - result = deepExtendArraySafe({}, options); - } else { - const commonColumnOptions = that.getCommonSettings(options); - const userStateDataField = userStateColumnOptions?.name && userStateColumnOptions.dataField; - const optionsWithUserState: Column = userStateDataField - ? extend({}, options, { dataField: userStateDataField }) - : options; - const calculatedColumnOptions = that._createCalculatedColumnOptions( - optionsWithUserState, - bandColumn, - ); - - if (!optionsWithUserState.type) { - result = { headerId: `dx-col-${globalColumnId}` }; - globalColumnId += 1; - } - - deepExtendArraySafe(result, DEFAULT_COLUMN_OPTIONS, false, true); - deepExtendArraySafe(result, commonColumnOptions, false, true); - deepExtendArraySafe(result, calculatedColumnOptions, false, true); - deepExtendArraySafe(result, optionsWithUserState, false, true); - deepExtendArraySafe(result, { selector: null }, false, true); - } - - if (options.filterOperations === options.defaultFilterOperations) { - setFilterOperationsAsDefaultValues(result); - } - - // @ts-expect-error the calculated options set calculateCellValue; command options are internal - return result; -} - export function isUserStateColumn( column: ColumnUserState | undefined, userStateColumn: ColumnUserState | undefined, @@ -150,55 +61,6 @@ export function isUserStateColumn( return isNameMatched && (isDataFieldMatched || !!column.name); } -export const createColumnsFromOptions = ( - that: ColumnsController, - columnsOptions: (Column | string | undefined)[] | undefined, - bandColumn?: Column, - createdColumnCount = 0, -): WithCellValueCalculator[] => { - if (!columnsOptions) { - return []; - } - - const result: WithCellValueCalculator[] = []; - - columnsOptions.forEach((columnOptions) => { - const currentIndex = createdColumnCount + result.length; - const userStateColumnOptions = that._columnsUserState - && isUserStateColumn(columnOptions as ColumnUserState, that._columnsUserState[currentIndex]) - && that._columnsUserState[currentIndex]; - const column = createColumn( - that, - columnOptions, - userStateColumnOptions || undefined, - bandColumn, - ); - - if (!column) { - return; - } - - if (bandColumn) { - // @ts-expect-error ownerBand holds the band column until updateColumnIndexes sets its index - column.ownerBand = bandColumn; - } - - result.push(column); - - if (!column.columns) { - return; - } - - warnFixedInChildColumnsOnce(that, column.columns); - const childColumns = createColumnsFromOptions(that, column.columns, column, result.length); - delete column.columns; - column.hasColumns = true; - result.push(...childColumns); - }); - - return result; -}; - export const getParentBandColumns = ( columnIndex: number | undefined, columnParentByIndex: Record, @@ -462,32 +324,6 @@ export const getCustomizeTextByDataType = (dataType: string | undefined): Column return undefined; }; -export const createColumnsFromDataSourceAdapter = ( - that: ColumnsController, - dataSourceAdapter: DataSourceAdapter, -): WithCellValueCalculator[] => { - const fieldNames: Record = {}; - - that._getFirstItems(dataSourceAdapter).forEach((item) => { - if (!item) { - return; - } - - // eslint-disable-next-line guard-for-in -- inherited fields become columns too - for (const fieldName in item) { - const value = item[fieldName]; - - if (!isFunction(value) || variableWrapper.isWrapped(value)) { - fieldNames[fieldName] = true; - } - } - }); - - return Object.keys(fieldNames) - .filter((fieldName) => !fieldName.startsWith('__')) - .map((fieldName) => createColumn(that, fieldName) as WithCellValueCalculator); -}; - export const updateColumnIndexes = (that: ColumnsController): void => { that._columns.forEach((column, index) => { column.index = index; @@ -678,16 +514,6 @@ export const updateIndexes = (that: ColumnsController, column?: Column): void => updateColumnVisibleIndexes(that, column); }; -export function assignColumns( - that: ColumnsController, - columns: WithCellValueCalculator[], -): void { - that._previousColumns = that._columns; - that._columns = columns; - that.resetColumnsCache(); - that.updateColumnDataTypes(); -} - export function updateColumnChanges( that: ColumnsController, changeType: ColumnChangeType, @@ -897,12 +723,6 @@ export const columnOptionCore = function ( return undefined; }; -export const addExpandColumn = (that: ColumnsController): void => { - const options = that._getExpandColumnOptions(); - - that.addCommandColumn(options); -}; - export function defaultSetCellValue(this: Column, data: RawItemData, value: unknown): void { if (!this.dataField) { return;