diff --git a/examples/grid-lite/components-react/src/App.tsx b/examples/grid-lite/components-react/src/App.tsx index 5894db3..ac64cd3 100644 --- a/examples/grid-lite/components-react/src/App.tsx +++ b/examples/grid-lite/components-react/src/App.tsx @@ -5,46 +5,136 @@ import { type GridOptions, Grid, Caption, + Data, + DataTable, + ColumnDefaults, + Column, Description } from '@highcharts/grid-lite-react'; function App() { - // const grid = useRef | null>(null); - const [description, setDescription] = useState('Grid Description'); - const onSetDescriptionClick = () => { - setDescription('This is a new description'); + const grid = useRef | null>(null); + + // ==== OPTIONS ==== + // const [options] = useState({ + // dataTable: { + // columns: { + // name: ['1111Alice', 'Bob', 'Charlie', 'David', 'Eve'], + // age: [23, 34, 45, 56, 67], + // city: ['New York', 'Oslo', 'Paris', 'Tokyo', 'London'], + // salary: [50000, 60000, 70000, 80000, 90000] + // } + // } + // }); + + // ==== DATA ==== + // Data Columns + const [dataSource, setDataSource] = useState({ + name: ['COLUMNS', 'Bob', 'Charlie', 'David', 'Eve'], + age: [23, 34, 45, 56, 67], + city: ['New York', 'Oslo', 'Paris', 'Tokyo', 'London'], + salary: [50000, 60000, 70000, 80000, 90000] + }); + + // Data Table + // const dataTable = new DataTable({ + // columns: { + // name: ['DATATABLE', 'Bob', 'Charlie', 'David', 'Eve'], + // age: [23, 34, 45, 56, 67], + // city: ['New York', 'Oslo', 'Paris', 'Tokyo', 'London'], + // salary: [50000, 60000, 70000, 80000, 90000] + // } + // }); + + // ==== ACTIONS ==== + const onButtonClick = () => { // console.info('(ref) grid:', grid.current?.grid); + setDataSource({ + name: ['John', 'Jane', 'Jim', 'Jill', 'Jack'], + age: [30, 25, 35, 40, 45], + city: ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Miami'], + salary: [40000, 35000, 45000, 50000, 55000] + }); }; - const [options] = useState({ - dataTable: { - columns: { - name: ['Alice', 'Bob', 'Charlie', 'David', 'Eve'], - age: [23, 34, 45, 56, 67], - city: ['New York', 'Oslo', 'Paris', 'Tokyo', 'London'], - salary: [50000, 60000, 70000, 80000, 90000] - } - } - }); + const onGridCallback = (grid: GridInstance) => { + console.info('(callback) grid:', grid); + }; return ( <> console.info('(callback) grid:', grid)} + callback={onGridCallback} > - Grid Caption - {description} - { /* - -
Grid Header
- Grid Cell -
-
*/} + + + Grid Caption v2.1 + + + + + + Grid Description {/* Grid Pagination */}
- + ); } diff --git a/examples/grid-lite/components-react/vite.config.ts b/examples/grid-lite/components-react/vite.config.ts index adf42ba..2e3f28b 100644 --- a/examples/grid-lite/components-react/vite.config.ts +++ b/examples/grid-lite/components-react/vite.config.ts @@ -9,6 +9,14 @@ export default defineConfig({ plugins: [react()], resolve: { alias: [ + { + find: '@highcharts/grid-lite-react', + replacement: resolve(__dirname, '../../../packages/grid-lite-react/src/index.ts') + }, + { + find: '@highcharts/grid-shared-react', + replacement: resolve(__dirname, '../../../packages/grid-shared-react/src/index.ts') + }, { find: /^@highcharts\/grid-lite(\/.*)?$/, replacement: resolve(__dirname, 'node_modules/@highcharts/grid-lite$1') diff --git a/packages/grid-lite-react/src/Grid.tsx b/packages/grid-lite-react/src/Grid.tsx index f7851aa..aa47803 100644 --- a/packages/grid-lite-react/src/Grid.tsx +++ b/packages/grid-lite-react/src/Grid.tsx @@ -20,10 +20,24 @@ import type { Options } from '@highcharts/grid-lite/es-modules/Grid/Core/Options export default function GridLite(props: GridProps) { const { gridRef, children, options, ...gridProps } = props; + const childOptions = useMemo(() => getChildProps(children), [children]); + const columnKey = useMemo(() => { + const columns = childOptions.columns as Array<{ id?: string }> | undefined; + + return columns?.map((column) => column.id).join('\0') ?? ''; + }, [childOptions]); const gridOptions = useMemo( - () => merge(getChildProps(children), options ?? {}) as Options, - [children, options] + () => merge(childOptions, options ?? {}) as Options, + [childOptions, options] ); - return ; + return ( + + ); } diff --git a/packages/grid-lite-react/src/index.ts b/packages/grid-lite-react/src/index.ts index 695362c..4272e3d 100644 --- a/packages/grid-lite-react/src/index.ts +++ b/packages/grid-lite-react/src/index.ts @@ -11,6 +11,21 @@ import GridLite from '@highcharts/grid-lite'; export { default as Grid } from './Grid'; export { default as GridLite } from './Grid'; -export { Caption, Description } from '@highcharts/grid-shared-react'; -export type { GridInstance, GridRefHandle, CaptionProps, DescriptionProps } from '@highcharts/grid-shared-react'; +export { Caption, Data, ColumnDefaults, Column, Description } from '@highcharts/grid-shared-react'; +export { DataTable, DataConnector } from '@highcharts/grid-lite'; +export { merge } from '@highcharts/grid-lite/es-modules/Shared/Utilities.js'; +export type { + GridInstance, + GridRefHandle, + CaptionProps, + DescriptionProps, + DataProps, + DataColumns, + DataColumnValue, + ColumnProps, + ColumnOptionsProps, + ColumnDataType, + ColumnSortingOrder, + CellValueGetterContext +} from '@highcharts/grid-shared-react'; export type GridOptions = GridLite.Options; diff --git a/packages/grid-pro-react/src/Grid.tsx b/packages/grid-pro-react/src/Grid.tsx index fc7f2ba..c236cfd 100644 --- a/packages/grid-pro-react/src/Grid.tsx +++ b/packages/grid-pro-react/src/Grid.tsx @@ -20,10 +20,24 @@ import type { Options } from '@highcharts/grid-pro/es-modules/Grid/Core/Options' export default function GridPro(props: GridProps) { const { gridRef, children, options, ...gridProps } = props; + const childOptions = useMemo(() => getChildProps(children), [children]); + const columnKey = useMemo(() => { + const columns = childOptions.columns as Array<{ id?: string }> | undefined; + + return columns?.map((column) => column.id).join('\0') ?? ''; + }, [childOptions]); const gridOptions = useMemo( - () => merge(getChildProps(children), options ?? {}) as Options, - [children, options] + () => merge(childOptions, options ?? {}) as Options, + [childOptions, options] ); - return ; + return ( + + ); } diff --git a/packages/grid-pro-react/src/index.ts b/packages/grid-pro-react/src/index.ts index 84f1e66..a8a0200 100644 --- a/packages/grid-pro-react/src/index.ts +++ b/packages/grid-pro-react/src/index.ts @@ -11,6 +11,21 @@ import GridPro from '@highcharts/grid-pro'; export { default as Grid } from './Grid'; export { default as GridPro } from './Grid'; -export { Caption, Description } from '@highcharts/grid-shared-react'; -export type { GridInstance, GridRefHandle, CaptionProps, DescriptionProps } from '@highcharts/grid-shared-react'; +export { Caption, Data, ColumnDefaults, Column, Description } from '@highcharts/grid-shared-react'; +export { DataTable, DataConnector } from '@highcharts/grid-pro'; +export { merge } from '@highcharts/grid-pro/es-modules/Shared/Utilities.js'; +export type { + GridInstance, + GridRefHandle, + CaptionProps, + DescriptionProps, + DataProps, + DataColumns, + DataColumnValue, + ColumnProps, + ColumnOptionsProps, + ColumnDataType, + ColumnSortingOrder, + CellValueGetterContext +} from '@highcharts/grid-shared-react'; export type GridOptions = GridPro.Options; diff --git a/packages/grid-shared-react/src/components/options/columns/Column.tsx b/packages/grid-shared-react/src/components/options/columns/Column.tsx new file mode 100644 index 0000000..f5cd44a --- /dev/null +++ b/packages/grid-shared-react/src/components/options/columns/Column.tsx @@ -0,0 +1,20 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +import type { ColumnProps } from './columnProps'; + +export function Column(_props: ColumnProps) { + return null; +} + +Column._GridReact = { + type: 'Grid_Option', + gridOption: 'columns', + isArrayType: true +}; diff --git a/packages/grid-shared-react/src/components/options/columns/ColumnDefaults.tsx b/packages/grid-shared-react/src/components/options/columns/ColumnDefaults.tsx new file mode 100644 index 0000000..d8569ba --- /dev/null +++ b/packages/grid-shared-react/src/components/options/columns/ColumnDefaults.tsx @@ -0,0 +1,19 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +import type { ColumnOptionsProps } from './columnProps'; + +export function ColumnDefaults(_props: ColumnOptionsProps) { + return null; +} + +ColumnDefaults._GridReact = { + type: 'Grid_Option', + gridOption: 'columnDefaults' +}; diff --git a/packages/grid-shared-react/src/components/options/columns/columnProps.ts b/packages/grid-shared-react/src/components/options/columns/columnProps.ts new file mode 100644 index 0000000..1452f99 --- /dev/null +++ b/packages/grid-shared-react/src/components/options/columns/columnProps.ts @@ -0,0 +1,74 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +export type ColumnDataType = 'string' | 'number' | 'boolean' | 'datetime'; + +export type ColumnSortingOrder = 'asc' | 'desc' | null; + +/** + * `this` context passed to `cellValueGetter` by Grid Core. + */ +export interface CellValueGetterContext { + row: { + index: number; + }; +} + +/** + * Shared column options (`columnDefaults` and per-column overrides). + */ +export interface ColumnOptionsProps { + dataType?: ColumnDataType; + width?: number | string; + sortingEnabled?: boolean; + sortingOrder?: ColumnSortingOrder; + sortingPriority?: number; + sortingOrderSequence?: ColumnSortingOrder[]; + sortingCompare?: (a: unknown, b: unknown) => number; + filteringEnabled?: boolean; + filteringInline?: boolean; + filteringCondition?: string; + filteringValue?: string | number | boolean | null; + headerClassName?: string; + headerFormat?: string; + headerFormatter?: (this: unknown) => string; + headerStyle?: unknown; + cellRowHeader?: boolean; + cellClassName?: string; + cellFormat?: string; + cellFormatter?: (this: unknown) => string; + /** + * Custom cell value resolver. `this` is the Grid table cell (`row.index` + * is the row index in the presentation data). + */ + cellValueGetter?: (this: CellValueGetterContext) => unknown; + cellContextMenu?: { + enabled?: boolean; + items?: unknown[]; + }; + cellStyle?: unknown; + style?: unknown; + exportable?: boolean; +} + +export interface ColumnProps extends ColumnOptionsProps { + /** + * HTML `id` attribute for styling hooks. Not passed to Grid options. + */ + id?: string; + /** + * References the column to configure (data field id). Maps header, cells, + * sorting, filtering, etc. to Grid Core column options. + * + * Becomes `options.columns[].id` in Grid Core (same identifier). + */ + columnId?: string; + className?: string; + enabled?: boolean; +} diff --git a/packages/grid-shared-react/src/components/options/data/Data.tsx b/packages/grid-shared-react/src/components/options/data/Data.tsx new file mode 100644 index 0000000..7ec764a --- /dev/null +++ b/packages/grid-shared-react/src/components/options/data/Data.tsx @@ -0,0 +1,64 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +export type DataColumnValue = boolean | null | number | string | undefined; + +export type DataColumns = Record>; + +export interface DataProps { + /** + * The type of the data provider. + * + * @default 'local' + */ + providerType?: 'local' | string; + /** + * Whether columns should be generated automatically from data source + * column ids. + * + * Defaults to `true`. When declarative `` components are used, + * the React wrapper sets this to `false` unless you pass this prop + * explicitly. + * + * @default true + */ + autogenerateColumns?: boolean; + /** + * Columns data to initialize the Grid with. + */ + columns?: DataColumns; + /** + * Data table as a source of data for the grid. + */ + dataTable?: unknown; + /** + * Connector instance or options used to populate the data table. + */ + connector?: unknown; + /** + * Automatically update the grid when the data table changes. + * + * @default false + */ + updateOnChange?: boolean; + /** + * The column ID that contains the stable, unique row IDs. + */ + idColumn?: string; +} + +export function Data(_props: DataProps) { + return null; +} + +Data._GridReact = { + type: 'Grid_Option', + gridOption: 'data', + isArrayType: false +}; diff --git a/packages/grid-shared-react/src/components/options/index.ts b/packages/grid-shared-react/src/components/options/index.ts index 5cf87d4..dbbf7f4 100644 --- a/packages/grid-shared-react/src/components/options/index.ts +++ b/packages/grid-shared-react/src/components/options/index.ts @@ -9,5 +9,16 @@ export { Caption } from './caption'; export type { CaptionProps } from './caption'; +export { Data } from './data/Data'; +export type { DataProps, DataColumns, DataColumnValue } from './data/Data'; +export { ColumnDefaults } from './columns/ColumnDefaults'; +export { Column } from './columns/Column'; +export type { + ColumnProps, + ColumnOptionsProps, + ColumnDataType, + ColumnSortingOrder, + CellValueGetterContext +} from './columns/columnProps'; export { Description } from './description'; export type { DescriptionProps } from './description'; diff --git a/packages/grid-shared-react/src/hooks/useGrid.ts b/packages/grid-shared-react/src/hooks/useGrid.ts index adf07cf..c5b752f 100644 --- a/packages/grid-shared-react/src/hooks/useGrid.ts +++ b/packages/grid-shared-react/src/hooks/useGrid.ts @@ -14,7 +14,7 @@ import { useEffect, RefObject, useRef } from 'react'; */ export interface GridInstance { destroy(): void; - update(options: TOptions, redraw?: boolean): void; + update(options: TOptions, redraw?: boolean, oneToOne?: boolean): void; } /** @@ -89,7 +89,7 @@ export function useGrid({ // Apply any pending options that came in while we were initializing if (pendingOptionsRef.current !== void 0) { - grid.update(pendingOptionsRef.current, true); + grid.update(pendingOptionsRef.current, true, true); pendingOptionsRef.current = void 0; } @@ -122,8 +122,8 @@ export function useGrid({ } if (currGridRef.current) { - // Grid exists, update it directly - currGridRef.current.update(options, true); + // Declarative React options replace the previous snapshot (oneToOne). + currGridRef.current.update(options, true, true); } else { // Grid still initializing, queue the update pendingOptionsRef.current = options; diff --git a/packages/grid-shared-react/src/index.ts b/packages/grid-shared-react/src/index.ts index 3672450..3814da0 100644 --- a/packages/grid-shared-react/src/index.ts +++ b/packages/grid-shared-react/src/index.ts @@ -12,7 +12,18 @@ import { GridType, GridInstance } from './hooks/useGrid'; import type { GridProps, GridRefHandle } from './components/BaseGrid'; export { BaseGrid }; -export { Caption, Description } from './components/options'; +export { Caption, Data, ColumnDefaults, Column, Description } from './components/options'; export { getChildProps } from './utils/getChildProps'; -export type { CaptionProps, DescriptionProps } from './components/options'; +export type { + CaptionProps, + DescriptionProps, + DataProps, + DataColumns, + DataColumnValue, + ColumnProps, + ColumnOptionsProps, + ColumnDataType, + ColumnSortingOrder, + CellValueGetterContext +} from './components/options'; export type { GridType, GridInstance, GridProps, GridRefHandle }; diff --git a/packages/grid-shared-react/src/utils/getChildProps.test.tsx b/packages/grid-shared-react/src/utils/getChildProps.test.tsx new file mode 100644 index 0000000..1498a4e --- /dev/null +++ b/packages/grid-shared-react/src/utils/getChildProps.test.tsx @@ -0,0 +1,50 @@ +import { describe, it, expect } from 'vitest'; +import { Data } from '../components/options/data/Data'; +import { getChildProps } from './getChildProps'; + +describe('getChildProps', () => { + it('maps Data columns to options.data.columns', () => { + const columns = { + name: ['Alice', 'Bob'], + age: [23, 34] + }; + + expect(getChildProps()).toEqual({ + data: { + columns + } + }); + }); + + it('maps all Data props to options.data', () => { + const columns = { + name: ['Alice'] + }; + const connector = { id: 'csv' }; + const dataTable = { id: 'table-1' }; + + expect( + getChildProps( + + ) + ).toEqual({ + data: { + providerType: 'local', + autogenerateColumns: false, + columns, + connector, + dataTable, + updateOnChange: true, + idColumn: 'id' + } + }); + }); +}); diff --git a/packages/grid-shared-react/src/utils/getChildProps.ts b/packages/grid-shared-react/src/utils/getChildProps.ts index 3d11b1a..572376d 100644 --- a/packages/grid-shared-react/src/utils/getChildProps.ts +++ b/packages/grid-shared-react/src/utils/getChildProps.ts @@ -7,8 +7,9 @@ * */ -import { isValidElement, ReactElement, ReactNode } from 'react'; +import { Fragment, isValidElement, ReactElement, ReactNode } from 'react'; import type { BaseGridOptionsComponent, BaseGridOptions } from '../components/BaseGridOptions'; +import { normalizeColumnOptions } from './mappers/columnOptions'; function objInsert( obj: Record, @@ -75,6 +76,22 @@ function renderChildren(children: ReactNode): string { return ''; } +function flattenChildren(childNodes: ReactNode): ReactNode[] { + if (childNodes == null || childNodes === false) { + return []; + } + + if (Array.isArray(childNodes)) { + return childNodes.flatMap((child) => flattenChildren(child)); + } + + if (isReactElement(childNodes) && childNodes.type === Fragment) { + return flattenChildren((childNodes.props as { children?: ReactNode }).children); + } + + return [childNodes]; +} + function getEffectiveMeta( component: BaseGridOptionsComponent, parentMeta?: BaseGridOptions @@ -96,9 +113,32 @@ function getEffectiveMeta( }; } +function parseColumnElement(child: ReactElement): Record { + const { children: _ignored, columnId, id: _cssId, ...props } = getChildPropsFromElement(child); + const options = normalizeColumnOptions(props); + + // columnId selects the column; Core expects the same value as `id`. + if (columnId !== void 0) { + options.id = columnId; + } + + return options; +} + +function pushColumn( + optionsFromChildren: Record, + child: ReactElement +): void { + const columns = (optionsFromChildren.columns ?? ( + optionsFromChildren.columns = [] + )) as Record[]; + + columns.push(parseColumnElement(child)); +} + export function getChildProps(children: ReactNode): Record { const optionsFromChildren: Record = {}; - const resolvedChildren = (Array.isArray(children) ? children.flat() : [children]) + const resolvedChildren = flattenChildren(children) .map((child) => resolveOptionChild(child)) .filter((child): child is ReactElement => child !== null); @@ -150,13 +190,24 @@ export function getChildProps(children: ReactNode): Record { return; } + const childProps = getChildPropsFromElement(child); + const { children: childChildren, ...props } = childProps; + + if (meta.gridOption === 'columnDefaults') { + optionsFromChildren.columnDefaults = normalizeColumnOptions(props); + return; + } + + if (meta.gridOption === 'columns') { + pushColumn(optionsFromChildren, child); + return; + } + const optionParent = optionsFromChildren[meta.gridOption] ?? ( optionsFromChildren[meta.gridOption] = meta.isArrayType ? [] : {} ); const parentIsArray = Array.isArray(optionParent); const insertInto = parentIsArray ? {} : optionParent as Record; - const childProps = getChildPropsFromElement(child); - const { children: childChildren, ...props } = childProps; if (meta.defaultOptions) { Object.assign(insertInto, meta.defaultOptions); @@ -181,9 +232,34 @@ export function getChildProps(children: ReactNode): Record { handleChild(child); } + applyDeclarativeColumnDefaults(optionsFromChildren); + return optionsFromChildren; } +/** + * When declarative `` components are present, only those columns + * should render unless `data.autogenerateColumns` is set explicitly on ``. + */ +function applyDeclarativeColumnDefaults( + optionsFromChildren: Record +): void { + const columns = optionsFromChildren.columns; + + if (!Array.isArray(columns) || columns.length === 0) { + return; + } + + const data = isObject(optionsFromChildren.data) ? + { ...optionsFromChildren.data } : + {}; + + if (!('autogenerateColumns' in data)) { + data.autogenerateColumns = false; + optionsFromChildren.data = data; + } +} + function isOptionElement(child: ReactElement): boolean { return getOptionComponent(child.type) !== null; } diff --git a/packages/grid-shared-react/src/utils/mappers/columnOptions.ts b/packages/grid-shared-react/src/utils/mappers/columnOptions.ts new file mode 100644 index 0000000..300c39c --- /dev/null +++ b/packages/grid-shared-react/src/utils/mappers/columnOptions.ts @@ -0,0 +1,24 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +import { mapPrefixedProps } from './mapPrefixedProps'; + +/** Flat prop prefix → nested Grid option key for columns. */ +const COLUMN_PROP_PREFIXES = { + sorting: 'sorting', + filtering: 'filtering', + header: 'header', + cell: 'cells' +} as const; + +export function normalizeColumnOptions( + props: Record +): Record { + return mapPrefixedProps(props, COLUMN_PROP_PREFIXES); +} diff --git a/packages/grid-shared-react/src/utils/mappers/mapPrefixedProps.ts b/packages/grid-shared-react/src/utils/mappers/mapPrefixedProps.ts new file mode 100644 index 0000000..9fdd271 --- /dev/null +++ b/packages/grid-shared-react/src/utils/mappers/mapPrefixedProps.ts @@ -0,0 +1,57 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +/** + * Maps flat props with a shared prefix into nested Grid option objects. + * + * Convention: `{prefix}{OptionKey}` → `{groupKey}.{optionKey}` + * + * @example + * mapPrefixedProps( + * { sortingEnabled: true, sortingOrder: 'asc', width: 120 }, + * { sorting: 'sorting' } + * ); + * // => { width: 120, sorting: { enabled: true, order: 'asc' } } + */ +export type PrefixedPropMap = Record; + +export function mapPrefixedProps( + props: Record, + prefixToGroup: PrefixedPropMap +): Record { + const result = { ...props }; + const groups: Record> = {}; + const prefixes = Object.keys(prefixToGroup).sort((a, b) => b.length - a.length); + + for (const flatKey of Object.keys(result)) { + const prefix = prefixes.find( + (candidate) => flatKey.startsWith(candidate) && flatKey.length > candidate.length + ); + + if (!prefix) { + continue; + } + + const groupKey = prefixToGroup[prefix]; + const nestedKey = toNestedKey(flatKey.slice(prefix.length)); + + (groups[groupKey] ??= {})[nestedKey] = result[flatKey]; + delete result[flatKey]; + } + + for (const [groupKey, nested] of Object.entries(groups)) { + result[groupKey] = nested; + } + + return result; +} + +function toNestedKey(segment: string): string { + return segment.charAt(0).toLowerCase() + segment.slice(1); +} diff --git a/packages/grid-shared-react/tsconfig.json b/packages/grid-shared-react/tsconfig.json index b1b3107..f1d16c9 100644 --- a/packages/grid-shared-react/tsconfig.json +++ b/packages/grid-shared-react/tsconfig.json @@ -1,4 +1,4 @@ { "extends": "../../tsconfig.base.json", - "include": ["src", "tests"] + "include": ["src"] }