diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c844038..3cceffc 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,9 +1,31 @@ -name: Tests +name: CI on: pull_request: jobs: + lint: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install + + - name: Run linter + run: pnpm lint + test: runs-on: ubuntu-latest diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 0000000..acd310a --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,2 @@ +pnpm lint +pnpm test diff --git a/eslint.config.js b/eslint.config.js index a14c2bd..d7605c1 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -17,11 +17,20 @@ export default defineConfig( }, rules: { 'curly': ['error', 'all'], + '@typescript-eslint/no-unused-vars': ['error', { + argsIgnorePattern: '^_' + }], '@stylistic/semi': ['error', 'always'], '@stylistic/quotes': ['error', 'single', { avoidEscape: true }], '@stylistic/brace-style': ['error', '1tbs', { allowSingleLine: true }], '@stylistic/eol-last': ['error', 'always'], - '@stylistic/no-trailing-spaces': ['error'] + '@stylistic/no-trailing-spaces': ['error'], + '@stylistic/max-len': ['error', { + code: 80, + ignoreUrls: true, + ignoreStrings: true, + ignoreTemplateLiterals: true + }] }, }, { diff --git a/examples/grid-lite/components-react/index.html b/examples/grid-lite/components-react/index.html new file mode 100644 index 0000000..7f1e258 --- /dev/null +++ b/examples/grid-lite/components-react/index.html @@ -0,0 +1,13 @@ + + + + + + Highcharts Grid Lite - React Example + + +
+ + + + diff --git a/examples/grid-lite/components-react/package.json b/examples/grid-lite/components-react/package.json new file mode 100644 index 0000000..cd5b45a --- /dev/null +++ b/examples/grid-lite/components-react/package.json @@ -0,0 +1,26 @@ +{ + "name": "grid-lite-minimal-react", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview", + "clean": "rimraf dist node_modules" + }, + "dependencies": { + "@highcharts/grid-lite": ">=3.0.0", + "@highcharts/grid-lite-react": "workspace:*", + "react": ">=18", + "react-dom": ">=18" + }, + "devDependencies": { + "@types/react": ">=18", + "@types/react-dom": ">=18", + "@vitejs/plugin-react": "^4.2.0", + "typescript": "^5.0.0", + "vite": "^5.0.0" + } +} + diff --git a/examples/grid-lite/components-react/src/App.tsx b/examples/grid-lite/components-react/src/App.tsx new file mode 100644 index 0000000..f24838d --- /dev/null +++ b/examples/grid-lite/components-react/src/App.tsx @@ -0,0 +1,186 @@ +import { useState, useRef } from 'react'; +import { + type GridInstance, + type GridRefHandle, + type GridOptions, + Grid, + Caption, + Data, + DataTable, + ColumnDefaults, + Column, + Description, + Pagination, + Header +} from '@highcharts/grid-lite-react'; + +function App() { + 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 onGridCallback = (grid: GridInstance) => { + console.info('(callback) grid:', grid); + }; + + // Pagination + // const [paginationEnabled, setPaginationEnabled] = useState(false); + + // const onPaginationClick = () => { + // setPaginationEnabled(true); + // }; + + return ( + <> + + {/* */} + + + Grid Caption v2.1 +
+ + + + + + Grid Description + + +
+ + {/* */} +
+ + ); +} + +export default App; diff --git a/examples/grid-lite/components-react/src/index.css b/examples/grid-lite/components-react/src/index.css new file mode 100644 index 0000000..9a63579 --- /dev/null +++ b/examples/grid-lite/components-react/src/index.css @@ -0,0 +1,33 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +#root { + width: 100%; + min-height: 100vh; + padding: 20px; +} + +#controls { + margin-top: 20px; + display: flex; + gap: 10px; +} + +@media (prefers-color-scheme: dark) { + body { + background-color: #121212; + color: #ffffff; + } +} + diff --git a/examples/grid-lite/components-react/src/main.tsx b/examples/grid-lite/components-react/src/main.tsx new file mode 100644 index 0000000..0c657b5 --- /dev/null +++ b/examples/grid-lite/components-react/src/main.tsx @@ -0,0 +1,11 @@ +import React from 'react'; +import ReactDOM from 'react-dom/client'; +import App from './App'; +import './index.css'; + +ReactDOM.createRoot(document.getElementById('root')!).render( + + + +); + diff --git a/examples/grid-lite/components-react/tsconfig.json b/examples/grid-lite/components-react/tsconfig.json new file mode 100644 index 0000000..78a6daf --- /dev/null +++ b/examples/grid-lite/components-react/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "target": "ES2020", + "lib": [ + "DOM", + "ES2016", + "ES2017.Object" + ], + "jsx": "react-jsx", + "module": "ES6", + "moduleResolution": "node", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "noImplicitThis": true, + "noFallthroughCasesInSwitch": true, + "skipDefaultLibCheck": true, + "skipLibCheck": true, + "ignoreDeprecations": "5.0", + "allowSyntheticDefaultImports": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true + }, + "include": ["src"], + "references": [{ "path": "./tsconfig.node.json" }] +} + diff --git a/examples/grid-lite/components-react/tsconfig.node.json b/examples/grid-lite/components-react/tsconfig.node.json new file mode 100644 index 0000000..f7c2070 --- /dev/null +++ b/examples/grid-lite/components-react/tsconfig.node.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "composite": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true, + "types": ["node"] + }, + "include": ["vite.config.ts"] +} + diff --git a/examples/grid-lite/components-react/vite.config.ts b/examples/grid-lite/components-react/vite.config.ts new file mode 100644 index 0000000..2e3f28b --- /dev/null +++ b/examples/grid-lite/components-react/vite.config.ts @@ -0,0 +1,30 @@ +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; +import { resolve, dirname } from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +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') + } + ] + }, + server: { + port: 3000 + } +}); + diff --git a/package.json b/package.json index 5d1eb21..0aaabc9 100644 --- a/package.json +++ b/package.json @@ -1,36 +1,39 @@ { - "name": "highcharts-grid-react", - "description": "Monorepo for Highcharts Grid Pro & Lite React libraries.", - "private": true, - "type": "module", - "scripts": { - "test": "vitest run", - "test:watch": "vitest", - "pretest:e2e": "pnpm build", - "test:e2e": "vitest run --config vitest.e2e.config.ts", - "test:all": "pnpm test && pnpm test:e2e", - "check": "pnpm lint && pnpm test", - "build": "pnpm -r --filter './packages/*' run build", - "lint": "pnpm -r --filter './packages/*' run lint", - "clean": "pnpm -r --filter './{packages,examples}/*' run clean && rimraf node_modules", - "release:preflight": "pnpm check && pnpm build", - "release:prepare": "node scripts/release.js", - "release": "pnpm release:preflight && pnpm publish -r --access public" - }, - "packageManager": "pnpm@10.27.0", - "devDependencies": { - "@eslint/js": "^9.39.1", - "@stylistic/eslint-plugin": "^5.6.1", - "@testing-library/react": "^16.3.1", - "@types/node": "^20.0.0", - "@vitest/browser": "^4.0.16", - "@vitest/browser-playwright": "^4.0.16", - "eslint": "^9.39.1", - "globals": "^17.0.0", - "playwright": "^1.57.0", - "rimraf": "^6.1.2", - "typescript": "^5.9.3", - "typescript-eslint": "^8.48.0", - "vitest": "^4.0.16" - } + "name": "highcharts-grid-react", + "description": "Monorepo for Highcharts Grid Pro & Lite React libraries.", + "private": true, + "type": "module", + "scripts": { + "test": "vitest run", + "pretest": "pnpm build", + "test:watch": "vitest", + "pretest:e2e": "pnpm build", + "test:e2e": "vitest run --config vitest.e2e.config.ts", + "test:all": "pnpm test && pnpm test:e2e", + "check": "pnpm lint && pnpm test", + "build": "pnpm -r --filter './packages/*' run build", + "lint": "pnpm -r --filter './packages/*' run lint", + "clean": "pnpm -r --filter './{packages,examples}/*' run clean && rimraf node_modules", + "release:preflight": "pnpm check && pnpm build", + "release:prepare": "node scripts/release.js", + "release": "pnpm release:preflight && pnpm publish -r --access public", + "prepare": "husky" + }, + "packageManager": "pnpm@10.27.0", + "devDependencies": { + "@eslint/js": "^9.39.1", + "@stylistic/eslint-plugin": "^5.6.1", + "@testing-library/react": "^16.3.1", + "@types/node": "^20.0.0", + "@vitest/browser": "^4.0.16", + "@vitest/browser-playwright": "^4.0.16", + "eslint": "^9.39.1", + "globals": "^17.0.0", + "husky": "^9.1.7", + "playwright": "^1.57.0", + "rimraf": "^6.1.2", + "typescript": "^5.9.3", + "typescript-eslint": "^8.48.0", + "vitest": "^4.0.16" + } } diff --git a/packages/grid-lite-react/src/Grid.tsx b/packages/grid-lite-react/src/Grid.tsx index f4d21fb..44b5643 100644 --- a/packages/grid-lite-react/src/Grid.tsx +++ b/packages/grid-lite-react/src/Grid.tsx @@ -7,14 +7,38 @@ * */ +import { useMemo } from 'react'; import { BaseGrid, - GridProps + GridProps, + getChildProps } from '@highcharts/grid-shared-react'; +import { merge } from '@highcharts/grid-lite/es-modules/Shared/Utilities.js'; import Grid from '@highcharts/grid-lite/es-modules/masters/grid-lite.src'; import '@highcharts/grid-lite/css/grid-lite.css'; import type { Options } from '@highcharts/grid-lite/es-modules/Grid/Core/Options'; -export default function GridLite({ options, gridRef, callback }: GridProps) { - return ; +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(childOptions, options ?? {}) as Options, + [childOptions, options] + ); + + return ( + + ); } diff --git a/packages/grid-lite-react/src/index.ts b/packages/grid-lite-react/src/index.ts index 93cb0e5..79cbac6 100644 --- a/packages/grid-lite-react/src/index.ts +++ b/packages/grid-lite-react/src/index.ts @@ -11,6 +11,33 @@ import GridLite from '@highcharts/grid-lite'; export { default as Grid } from './Grid'; export { default as GridLite } from './Grid'; -export type { GridInstance } from '@highcharts/grid-shared-react'; -export type { GridRefHandle } from '@highcharts/grid-shared-react'; +export { + Caption, + Data, + ColumnDefaults, + Column, + Description, + Pagination, + Header +} 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, + PaginationProps, + HeaderProps, + GroupedHeaderOptions, + HeaderCellAccessibilityProps +} from '@highcharts/grid-shared-react'; export type GridOptions = GridLite.Options; diff --git a/packages/grid-lite-react/src/__tests__/Grid.test.tsx b/packages/grid-lite-react/tests/Grid.test.tsx similarity index 72% rename from packages/grid-lite-react/src/__tests__/Grid.test.tsx rename to packages/grid-lite-react/tests/Grid.test.tsx index 770322a..140e4eb 100644 --- a/packages/grid-lite-react/src/__tests__/Grid.test.tsx +++ b/packages/grid-lite-react/tests/Grid.test.tsx @@ -1,5 +1,5 @@ -import { createGridTests } from '@highcharts/grid-shared-react/src/test/createGridTests'; -import { Grid, GridOptions } from '../index'; +import { createGridTests } from '@highcharts/grid-shared-react/tests/createGridTests'; +import { Grid, GridOptions } from '../src/index'; createGridTests( 'Grid Lite', diff --git a/packages/grid-pro-react/src/Grid.tsx b/packages/grid-pro-react/src/Grid.tsx index 398edea..c9e596f 100644 --- a/packages/grid-pro-react/src/Grid.tsx +++ b/packages/grid-pro-react/src/Grid.tsx @@ -7,14 +7,38 @@ * */ +import { useMemo } from 'react'; import { BaseGrid, - GridProps + GridProps, + getChildProps } from '@highcharts/grid-shared-react'; +import { merge } from '@highcharts/grid-pro/es-modules/Shared/Utilities.js'; import Grid from '@highcharts/grid-pro/es-modules/masters/grid-pro.src'; import '@highcharts/grid-pro/css/grid-pro.css'; import type { Options } from '@highcharts/grid-pro/es-modules/Grid/Core/Options'; -export default function GridPro({ options, gridRef, callback }: GridProps) { - return ; +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(childOptions, options ?? {}) as Options, + [childOptions, options] + ); + + return ( + + ); } diff --git a/packages/grid-pro-react/src/index.ts b/packages/grid-pro-react/src/index.ts index a44be66..7ba334f 100644 --- a/packages/grid-pro-react/src/index.ts +++ b/packages/grid-pro-react/src/index.ts @@ -11,6 +11,33 @@ import GridPro from '@highcharts/grid-pro'; export { default as Grid } from './Grid'; export { default as GridPro } from './Grid'; -export type { GridInstance } from '@highcharts/grid-shared-react'; -export type { GridRefHandle } from '@highcharts/grid-shared-react'; +export { + Caption, + Data, + ColumnDefaults, + Column, + Description, + Pagination, + Header +} 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, + PaginationProps, + HeaderProps, + GroupedHeaderOptions, + HeaderCellAccessibilityProps +} from '@highcharts/grid-shared-react'; export type GridOptions = GridPro.Options; diff --git a/packages/grid-pro-react/src/__tests__/Grid.test.tsx b/packages/grid-pro-react/tests/Grid.test.tsx similarity index 72% rename from packages/grid-pro-react/src/__tests__/Grid.test.tsx rename to packages/grid-pro-react/tests/Grid.test.tsx index e44d6d9..65e49d7 100644 --- a/packages/grid-pro-react/src/__tests__/Grid.test.tsx +++ b/packages/grid-pro-react/tests/Grid.test.tsx @@ -1,5 +1,5 @@ -import { createGridTests } from '@highcharts/grid-shared-react/src/test/createGridTests'; -import { Grid, GridOptions } from '../index'; +import { createGridTests } from '@highcharts/grid-shared-react/tests/createGridTests'; +import { Grid, GridOptions } from '../src/index'; createGridTests( 'Grid Pro', diff --git a/packages/grid-shared-react/src/components/BaseGrid.tsx b/packages/grid-shared-react/src/components/BaseGrid.tsx index 437459e..4d51c20 100644 --- a/packages/grid-shared-react/src/components/BaseGrid.tsx +++ b/packages/grid-shared-react/src/components/BaseGrid.tsx @@ -7,7 +7,7 @@ * */ -import { useRef, useImperativeHandle, forwardRef, ForwardedRef } from 'react'; +import { useRef, useImperativeHandle, forwardRef, ForwardedRef, ReactNode } from 'react'; import { useGrid, GridType, @@ -31,7 +31,11 @@ export interface GridProps { /** * Grid configuration options */ - options: TOptions; + options?: TOptions; + /** + * Declarative option components (e.g. Caption) passed as children. + */ + children?: ReactNode; /** * Optional ref to access the grid instance */ @@ -45,11 +49,10 @@ export interface GridProps { /** * Props for BaseGrid component */ -export interface BaseGridProps extends GridProps { - /** - * Grid instance (from @highcharts/grid-lite or @highcharts/grid-pro) - */ +export interface BaseGridProps { + options?: TOptions; Grid: GridType; + callback?: (grid: GridInstance) => void; } export const BaseGrid = forwardRef(function BaseGrid( diff --git a/packages/grid-shared-react/src/components/BaseGridOptions.ts b/packages/grid-shared-react/src/components/BaseGridOptions.ts new file mode 100644 index 0000000..aabeb10 --- /dev/null +++ b/packages/grid-shared-react/src/components/BaseGridOptions.ts @@ -0,0 +1,34 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +/** + * Metadata attached to declarative option components + * rendered as BaseGrid children. + */ +export interface BaseGridOptions { + type: 'Grid_Option'; + /** + * Dot-notation path of the Grid option (e.g. `caption`). + */ + gridOption: string; + /** + * Sub-option that receives string children (e.g. `text`). + */ + childOption?: string; + defaultOptions?: Record; + isArrayType?: boolean; +} + +/** + * A React component that maps JSX props to a Grid options path + * via `_GridReact`. + */ +export interface BaseGridOptionsComponent { + _GridReact: BaseGridOptions; +} diff --git a/packages/grid-shared-react/src/components/options/caption/Caption.tsx b/packages/grid-shared-react/src/components/options/caption/Caption.tsx new file mode 100644 index 0000000..99c9199 --- /dev/null +++ b/packages/grid-shared-react/src/components/options/caption/Caption.tsx @@ -0,0 +1,33 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +import { ReactNode } from 'react'; + +export interface CaptionProps { + /** + * The custom CSS class name for the table caption. + */ + className?: string; + /** + * The HTML tag to use for the caption. + */ + htmlTag?: string; + children?: ReactNode; +} + +export function Caption(_props: CaptionProps) { + return null; +} + +Caption._GridReact = { + type: 'Grid_Option', + gridOption: 'caption', + childOption: 'text', + isArrayType: false +}; diff --git a/packages/grid-shared-react/src/components/options/caption/index.ts b/packages/grid-shared-react/src/components/options/caption/index.ts new file mode 100644 index 0000000..3e96b78 --- /dev/null +++ b/packages/grid-shared-react/src/components/options/caption/index.ts @@ -0,0 +1,11 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +export { Caption } from './Caption'; +export type { CaptionProps } from './Caption'; 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/description/Description.tsx b/packages/grid-shared-react/src/components/options/description/Description.tsx new file mode 100644 index 0000000..c6ee575 --- /dev/null +++ b/packages/grid-shared-react/src/components/options/description/Description.tsx @@ -0,0 +1,29 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +import { ReactNode } from 'react'; + +export interface DescriptionProps { + /** + * The custom CSS class name for the description. + */ + className?: string; + children?: ReactNode; +} + +export function Description(_props: DescriptionProps) { + return null; +} + +Description._GridReact = { + type: 'Grid_Option', + gridOption: 'description', + childOption: 'text', + isArrayType: false +}; diff --git a/packages/grid-shared-react/src/components/options/description/index.ts b/packages/grid-shared-react/src/components/options/description/index.ts new file mode 100644 index 0000000..65cb487 --- /dev/null +++ b/packages/grid-shared-react/src/components/options/description/index.ts @@ -0,0 +1,11 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +export { Description } from './Description'; +export type { DescriptionProps } from './Description'; diff --git a/packages/grid-shared-react/src/components/options/header/Header.tsx b/packages/grid-shared-react/src/components/options/header/Header.tsx new file mode 100644 index 0000000..b952ef3 --- /dev/null +++ b/packages/grid-shared-react/src/components/options/header/Header.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 { HeaderProps } from './headerProps'; + +export function Header(_props: HeaderProps) { + return null; +} + +Header._GridReact = { + type: 'Grid_Option', + gridOption: 'header' +}; diff --git a/packages/grid-shared-react/src/components/options/header/headerProps.ts b/packages/grid-shared-react/src/components/options/header/headerProps.ts new file mode 100644 index 0000000..86f57bb --- /dev/null +++ b/packages/grid-shared-react/src/components/options/header/headerProps.ts @@ -0,0 +1,36 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +/** + * Accessibility options for a header cell in the header tree. + */ +export interface HeaderCellAccessibilityProps { + description?: string; +} + +/** + * Header node in the `header` tree. A group (with `columns`) or a leaf + * (with `columnId`). Mirrors Grid Core `GroupedHeaderOptions`. + */ +export interface GroupedHeaderOptions { + accessibility?: HeaderCellAccessibilityProps; + format?: string; + className?: string; + columnId?: string; + columns?: Array; +} + +export interface HeaderProps { + /** + * Header tree: column order, inclusion, and grouping. + * Each entry is a column id (`string`) or a {@link GroupedHeaderOptions} + * object. Maps to Grid Core `options.header`. + */ + header?: Array; +} diff --git a/packages/grid-shared-react/src/components/options/header/index.ts b/packages/grid-shared-react/src/components/options/header/index.ts new file mode 100644 index 0000000..e25312d --- /dev/null +++ b/packages/grid-shared-react/src/components/options/header/index.ts @@ -0,0 +1,15 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +export { Header } from './Header'; +export type { + HeaderProps, + GroupedHeaderOptions, + HeaderCellAccessibilityProps +} from './headerProps'; diff --git a/packages/grid-shared-react/src/components/options/index.ts b/packages/grid-shared-react/src/components/options/index.ts new file mode 100644 index 0000000..36984b3 --- /dev/null +++ b/packages/grid-shared-react/src/components/options/index.ts @@ -0,0 +1,32 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +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'; +export { Pagination } from './pagination'; +export type { PaginationProps } from './pagination'; +export { Header } from './header'; +export type { + HeaderProps, + GroupedHeaderOptions, + HeaderCellAccessibilityProps +} from './header'; diff --git a/packages/grid-shared-react/src/components/options/pagination/Pagination.tsx b/packages/grid-shared-react/src/components/options/pagination/Pagination.tsx new file mode 100644 index 0000000..8a169d7 --- /dev/null +++ b/packages/grid-shared-react/src/components/options/pagination/Pagination.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 { PaginationProps } from './paginationProps'; + +export function Pagination(_props: PaginationProps) { + return null; +} + +Pagination._GridReact = { + type: 'Grid_Option', + gridOption: 'pagination' +}; diff --git a/packages/grid-shared-react/src/components/options/pagination/index.ts b/packages/grid-shared-react/src/components/options/pagination/index.ts new file mode 100644 index 0000000..d5d79cb --- /dev/null +++ b/packages/grid-shared-react/src/components/options/pagination/index.ts @@ -0,0 +1,11 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +export { Pagination } from './Pagination'; +export type { PaginationProps } from './paginationProps'; diff --git a/packages/grid-shared-react/src/components/options/pagination/paginationProps.ts b/packages/grid-shared-react/src/components/options/pagination/paginationProps.ts new file mode 100644 index 0000000..a5f9a93 --- /dev/null +++ b/packages/grid-shared-react/src/components/options/pagination/paginationProps.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 + * + */ + +export interface PaginationProps { + /** + * Whether pagination should be rendered. + * Defaults to `true` when the `` component is used. + * Pass `false` to disable pagination while keeping other options. + */ + enabled?: boolean; + /** + * The current page number. + */ + page?: number; + /** + * Number of rows per page. + */ + pageSize?: number; + /** + * Alignment of pagination elements within the wrapper. + */ + align?: 'left' | 'center' | 'right' | 'distributed'; + /** + * Whether to show the page information text. + */ + pageInfo?: boolean; + /** + * Whether to show the page size selector. + */ + pageSizeSelector?: boolean; + /** + * Available options for the page size selector dropdown. + */ + pageSizeOptions?: number[]; + /** + * Whether to show numbered page buttons. + */ + pageButtons?: boolean; + /** + * Maximum number of page number buttons to show before using ellipsis. + */ + pageButtonsCount?: number; + /** + * Whether to show the first and last page navigation buttons. + */ + firstLast?: boolean; + /** + * Whether to show the previous and next page navigation buttons. + */ + previousNext?: boolean; +} diff --git a/packages/grid-shared-react/src/hooks/useGrid.test.tsx b/packages/grid-shared-react/src/hooks/useGrid.test.tsx index 774a6a1..53e86d1 100644 --- a/packages/grid-shared-react/src/hooks/useGrid.test.tsx +++ b/packages/grid-shared-react/src/hooks/useGrid.test.tsx @@ -60,9 +60,10 @@ describe('useGrid', () => { expect(initQueue).toHaveLength(1); }); - const [firstInit] = initQueue; + const firstInit = initQueue[0]; - await firstInit.resolve(); + expect(firstInit).toBeDefined(); + await firstInit!.resolve(); await waitFor(() => { expect(container.querySelector('[data-grid-id="1"]')).not.toBeNull(); diff --git a/packages/grid-shared-react/src/hooks/useGrid.ts b/packages/grid-shared-react/src/hooks/useGrid.ts index 327e3fb..f5e1756 100644 --- a/packages/grid-shared-react/src/hooks/useGrid.ts +++ b/packages/grid-shared-react/src/hooks/useGrid.ts @@ -8,14 +8,13 @@ */ import { useEffect, RefObject, useRef } from 'react'; -import { BaseGridProps } from '../components/BaseGrid'; /** * Interface describing the shape of a Grid instance returned by Grid.grid() */ export interface GridInstance { destroy(): void; - update(options: TOptions, redraw?: boolean): void; + update(options: TOptions, redraw?: boolean, oneToOne?: boolean): void; } /** @@ -25,11 +24,18 @@ export interface GridInstance { * directly depending on their types. */ export interface GridType { - grid(container: HTMLDivElement, options: TOptions, async?: boolean): GridInstance | Promise>; + grid( + container: HTMLDivElement, + options?: TOptions, + async?: boolean + ): GridInstance | Promise>; } -export interface UseGridOptions extends BaseGridProps { +export interface UseGridOptions { containerRef: RefObject; + options?: TOptions; + Grid: GridType; + callback?: (grid: GridInstance) => void; } export function useGrid({ @@ -40,7 +46,7 @@ export function useGrid({ }: UseGridOptions) { const currGridRef = useRef | null>(null); const callbackRef = useRef(callback); - const pendingOptionsRef = useRef(null); + const pendingOptionsRef = useRef(void 0); const initStartedRef = useRef(false); // StrictMode runs effects twice: mount → cleanup → mount. @@ -60,7 +66,8 @@ export function useGrid({ return; } - // StrictMode cleanup runs before re-mount; allow init to complete if re-mounted. + // StrictMode cleanup runs before re-mount; + // allow init to complete if re-mounted. destroyOnInitRef.current = false; // Prevent double initialization @@ -71,24 +78,27 @@ export function useGrid({ const initGrid = async () => { try { - // Use pending options if available (from rapid updates during init) + // Use pending options if available + // (from rapid updates during init) const initOptions = pendingOptionsRef.current ?? options; - pendingOptionsRef.current = null; + pendingOptionsRef.current = void 0; const grid = await Grid.grid(container, initOptions, true); if (destroyOnInitRef.current) { - // Component unmounted while we were initializing - destroy immediately + // Component unmounted while initializing - + // destroy immediately grid.destroy(); return; } currGridRef.current = grid; - // Apply any pending options that came in while we were initializing - if (pendingOptionsRef.current) { - grid.update(pendingOptionsRef.current, true); - pendingOptionsRef.current = null; + // Apply pending options that came in + // while we were initializing + if (pendingOptionsRef.current !== void 0) { + grid.update(pendingOptionsRef.current, true, true); + pendingOptionsRef.current = void 0; } callbackRef.current?.(grid); @@ -115,9 +125,14 @@ export function useGrid({ // Effect for options updates - separate from init useEffect(() => { + if (options === void 0) { + return; + } + 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 6a47b1b..4cfc3ca 100644 --- a/packages/grid-shared-react/src/index.ts +++ b/packages/grid-shared-react/src/index.ts @@ -12,4 +12,30 @@ import { GridType, GridInstance } from './hooks/useGrid'; import type { GridProps, GridRefHandle } from './components/BaseGrid'; export { BaseGrid }; +export { + Caption, + Data, + ColumnDefaults, + Column, + Description, + Pagination, + Header +} from './components/options'; +export { getChildProps } from './utils/getChildProps'; +export type { + CaptionProps, + DescriptionProps, + DataProps, + DataColumns, + DataColumnValue, + ColumnProps, + ColumnOptionsProps, + ColumnDataType, + ColumnSortingOrder, + CellValueGetterContext, + PaginationProps, + HeaderProps, + GroupedHeaderOptions, + HeaderCellAccessibilityProps +} from './components/options'; export type { GridType, GridInstance, GridProps, GridRefHandle }; diff --git a/packages/grid-shared-react/src/utils/getChildProps.ts b/packages/grid-shared-react/src/utils/getChildProps.ts new file mode 100644 index 0000000..bc1c5a6 --- /dev/null +++ b/packages/grid-shared-react/src/utils/getChildProps.ts @@ -0,0 +1,349 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +import { Fragment, isValidElement, ReactElement, ReactNode } from 'react'; +import type { BaseGridOptionsComponent, BaseGridOptions } from '../components/BaseGridOptions'; +import { normalizeColumnOptions } from './mappers/column'; +import { normalizePaginationOptions } from './mappers/pagination'; + +function objInsert( + obj: Record, + path: string, + value: unknown +): Record { + const keys = path.split('.'); + let current = obj; + + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + + if (key === void 0) { + continue; + } + + if (!isObject(current[key])) { + current[key] = {}; + } + current = current[key] as Record; + } + + const lastKey = keys.at(-1); + + if (lastKey !== void 0) { + current[lastKey] = value; + } + return obj; +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function isReactElement(value: unknown): value is ReactElement { + return isValidElement(value); +} + +function getOptionComponent(type: unknown): BaseGridOptionsComponent | null { + if (typeof type !== 'function' && (typeof type !== 'object' || type === null)) { + return null; + } + + const component = type as Partial; + + return component._GridReact ? type as BaseGridOptionsComponent : null; +} + +function getChildPropsFromElement( + child: ReactElement +): Record { + return (child.props ?? {}) as Record; +} + +function renderChildren(children: ReactNode): string { + if (typeof children === 'string' || typeof children === 'number') { + return String(children); + } + + if (Array.isArray(children)) { + return children + .map((child) => renderChildren(child)) + .join(''); + } + + 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) { + const fragmentProps = childNodes.props as { children?: ReactNode }; + return flattenChildren(fragmentProps.children); + } + + return [childNodes]; +} + +function getEffectiveMeta( + component: BaseGridOptionsComponent, + parentMeta?: BaseGridOptions +): BaseGridOptions { + const meta = component._GridReact; + + if (!parentMeta) { + return meta; + } + + return { + ...meta, + childOption: parentMeta.childOption + ? `${parentMeta.childOption}.${meta.childOption ?? ''}` + : meta.childOption, + gridOption: parentMeta.gridOption + ? `${parentMeta.gridOption}.${meta.gridOption}` + : meta.gridOption + }; +} + +function parseColumnElement(child: ReactElement): Record { + const { + children, + id, + columnId, + ...props + } = getChildPropsFromElement(child); + void children; + void id; + + 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 = flattenChildren(children) + .map((child) => resolveOptionChild(child)) + .filter((child): child is ReactElement => child !== null); + + function handleChildren( + childNodes: ReactNode, + obj: Record, + meta: BaseGridOptions + ): void { + if (childNodes == null || childNodes === false) { + return; + } + + const nonOptionChildren: ReactNode[] = []; + + if (Array.isArray(childNodes)) { + for (const child of childNodes) { + if (isReactElement(child) && isOptionElement(child)) { + handleChild(child, meta); + continue; + } + + nonOptionChildren.push(child); + } + } else if (isReactElement(childNodes) && isOptionElement(childNodes)) { + handleChild(childNodes, meta); + } else { + nonOptionChildren.push(childNodes); + } + + if (meta.childOption) { + const childrenToRender = nonOptionChildren.length > 0 ? + nonOptionChildren : + [childNodes]; + + objInsert(obj, meta.childOption, renderChildren(childrenToRender)); + } + } + + function handleChild( + child: ReactElement, + parentMeta?: BaseGridOptions + ): void { + const component = getOptionComponent(child.type); + + if (!component) { + return; + } + + const meta = getEffectiveMeta(component, parentMeta); + + if (!meta.gridOption) { + 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; + } + + if (meta.gridOption === 'pagination') { + const pagination = normalizePaginationOptions(props); + pagination.position = isTopPaginationChild( + child, + resolvedChildren + ) ? 'top' : 'bottom'; + optionsFromChildren.pagination = pagination; + return; + } + + if (meta.gridOption === 'header') { + if (props.header !== void 0) { + optionsFromChildren.header = props.header; + } + return; + } + + const optionParent = optionsFromChildren[meta.gridOption] ?? ( + optionsFromChildren[meta.gridOption] = meta.isArrayType ? [] : {} + ); + const parentIsArray = Array.isArray(optionParent); + const insertInto = parentIsArray + ? {} + : optionParent as Record; + + if (meta.defaultOptions) { + Object.assign(insertInto, meta.defaultOptions); + } + + Object.assign(insertInto, props); + + if (typeof childChildren === 'string' || typeof childChildren === 'number') { + if (meta.childOption) { + objInsert(insertInto, meta.childOption, String(childChildren)); + } + } else if (childChildren != null) { + handleChildren(childChildren as ReactNode, insertInto, meta); + } + + if (parentIsArray) { + const optionItems = optionsFromChildren[ + meta.gridOption + ] as unknown[]; + optionItems.push(insertInto); + } + } + + for (const child of resolvedChildren) { + 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 isTopPaginationChild( + child: ReactElement, + children: ReactElement[] +): boolean { + const childIndex = children.indexOf(child); + + if (childIndex === -1) { + return false; + } + + return children + .slice(0, childIndex) + .every((candidate) => { + const gridOption = getOptionComponent(candidate.type) + ?._GridReact.gridOption; + return gridOption === 'pagination'; + }); +} + +function isOptionElement(child: ReactElement): boolean { + return getOptionComponent(child.type) !== null; +} + +function resolveOptionChild(child: ReactNode): ReactElement | null { + if (!isReactElement(child)) { + return null; + } + + const component = getOptionComponent(child.type); + + if (component) { + return child; + } + + if (typeof child.type !== 'function') { + return null; + } + + const renderChild = child.type as ( + props: Record + ) => ReactNode; + const rendered = renderChild(getChildPropsFromElement(child)); + + if (isReactElement(rendered) && getOptionComponent(rendered.type)) { + return rendered; + } + + return null; +} diff --git a/packages/grid-shared-react/src/utils/mappers/column/columnOptions.ts b/packages/grid-shared-react/src/utils/mappers/column/columnOptions.ts new file mode 100644 index 0000000..f1ae833 --- /dev/null +++ b/packages/grid-shared-react/src/utils/mappers/column/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/column/index.ts b/packages/grid-shared-react/src/utils/mappers/column/index.ts new file mode 100644 index 0000000..01a620a --- /dev/null +++ b/packages/grid-shared-react/src/utils/mappers/column/index.ts @@ -0,0 +1,10 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +export { normalizeColumnOptions } from './columnOptions'; 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..82418e3 --- /dev/null +++ b/packages/grid-shared-react/src/utils/mappers/mapPrefixedProps.ts @@ -0,0 +1,61 @@ +/** + * 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/src/utils/mappers/pagination/index.ts b/packages/grid-shared-react/src/utils/mappers/pagination/index.ts new file mode 100644 index 0000000..de3e9f4 --- /dev/null +++ b/packages/grid-shared-react/src/utils/mappers/pagination/index.ts @@ -0,0 +1,10 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +export { normalizePaginationOptions } from './paginationOptions'; diff --git a/packages/grid-shared-react/src/utils/mappers/pagination/paginationOptions.ts b/packages/grid-shared-react/src/utils/mappers/pagination/paginationOptions.ts new file mode 100644 index 0000000..0db2d55 --- /dev/null +++ b/packages/grid-shared-react/src/utils/mappers/pagination/paginationOptions.ts @@ -0,0 +1,84 @@ +/** + * Grid React integration. + * Copyright (c) 2025, Highsoft + * + * A valid license is required for using this software. + * See highcharts.com/license + * + */ + +import type { PaginationProps } from '../../../components/options/pagination/paginationProps'; + +export function normalizePaginationOptions( + props: Record +): Record { + const { + pageInfo, + pageSizeSelector, + pageSizeOptions, + pageButtons, + pageButtonsCount, + firstLast, + previousNext, + enabled, + page, + pageSize, + align + } = props as PaginationProps; + + const result: Record = { + enabled: enabled ?? true + }; + + if (page !== void 0) { + result.page = page; + } + if (pageSize !== void 0) { + result.pageSize = pageSize; + } + if (align !== void 0) { + result.align = align; + } + + const controls: Record = {}; + + if (pageInfo !== void 0) { + controls.pageInfo = pageInfo; + } + + if (pageSizeSelector === false) { + controls.pageSizeSelector = false; + } else if (pageSizeOptions !== void 0) { + controls.pageSizeSelector = { + enabled: true, + options: pageSizeOptions + }; + } else if (pageSizeSelector !== void 0) { + controls.pageSizeSelector = pageSizeSelector; + } + + if (pageButtons === false) { + controls.pageButtons = false; + } else if (pageButtonsCount !== void 0) { + controls.pageButtons = { + enabled: true, + count: pageButtonsCount + }; + } else if (pageButtons !== void 0) { + controls.pageButtons = pageButtons; + } + + if (firstLast !== void 0) { + controls.firstLastButtons = firstLast; + } + + if (previousNext !== void 0) { + controls.previousNextButtons = previousNext; + } + + if (Object.keys(controls).length > 0) { + result.controls = controls; + } + + return result; +} diff --git a/packages/grid-shared-react/src/test/createGridTests.tsx b/packages/grid-shared-react/tests/createGridTests.tsx similarity index 95% rename from packages/grid-shared-react/src/test/createGridTests.tsx rename to packages/grid-shared-react/tests/createGridTests.tsx index 1faed12..acf05db 100644 --- a/packages/grid-shared-react/src/test/createGridTests.tsx +++ b/packages/grid-shared-react/tests/createGridTests.tsx @@ -5,12 +5,13 @@ import { type ComponentType } from 'react'; import { describe, it, expect, vi } from 'vitest'; -import { GridProps, GridRefHandle } from '../components/BaseGrid'; -import { GridInstance } from '../hooks/useGrid'; +import { GridProps, GridRefHandle } from '../src/components/BaseGrid'; +import { GridInstance } from '../src/hooks/useGrid'; /** * Creates a standard test suite for a Grid component. - * Use this to avoid duplicating tests between grid-lite-react and grid-pro-react. + * Use this to avoid duplicating tests between + * grid-lite-react and grid-pro-react. */ export function createGridTests( name: string, diff --git a/packages/grid-shared-react/tests/options/Caption.test.tsx b/packages/grid-shared-react/tests/options/Caption.test.tsx new file mode 100644 index 0000000..832944e --- /dev/null +++ b/packages/grid-shared-react/tests/options/Caption.test.tsx @@ -0,0 +1,21 @@ +import { describe, it, expect } from 'vitest'; +import { Caption } from '../../src/components/options/caption/Caption'; +import { getChildProps } from '../../src/utils/getChildProps'; + +describe('Caption', () => { + it('maps caption props and children into options.caption', () => { + expect( + getChildProps( + + Sales table + + ) + ).toEqual({ + caption: { + className: 'grid-caption', + htmlTag: 'h2', + text: 'Sales table' + } + }); + }); +}); diff --git a/packages/grid-shared-react/tests/options/Column.test.tsx b/packages/grid-shared-react/tests/options/Column.test.tsx new file mode 100644 index 0000000..f52c073 --- /dev/null +++ b/packages/grid-shared-react/tests/options/Column.test.tsx @@ -0,0 +1,54 @@ +import { describe, it, expect } from 'vitest'; +import { Column } from '../../src/components/options/columns/Column'; +import { getChildProps } from '../../src/utils/getChildProps'; + +describe('Column', () => { + it('maps column props into options.columns', () => { + expect( + getChildProps( + + ) + ).toEqual({ + columns: [{ + width: 120, + sorting: { + enabled: true, + order: 'asc' + }, + header: { + format: '{value} USD' + }, + id: 'price' + }], + data: { + autogenerateColumns: false + } + }); + }); + + it('maps multiple columns into options.columns array', () => { + expect( + getChildProps( + <> + + + + ) + ).toEqual({ + columns: [ + { width: 200, id: 'product' }, + { width: 120, id: 'price' } + ], + data: { + autogenerateColumns: false + } + }); + }); +}); diff --git a/packages/grid-shared-react/tests/options/ColumnDefaults.test.tsx b/packages/grid-shared-react/tests/options/ColumnDefaults.test.tsx new file mode 100644 index 0000000..1a43555 --- /dev/null +++ b/packages/grid-shared-react/tests/options/ColumnDefaults.test.tsx @@ -0,0 +1,27 @@ +import { describe, it, expect } from 'vitest'; +import { ColumnDefaults } from '../../src/components/options/columns/ColumnDefaults'; +import { getChildProps } from '../../src/utils/getChildProps'; + +describe('ColumnDefaults', () => { + it('maps column defaults props into options.columnDefaults', () => { + expect( + getChildProps( + + ) + ).toEqual({ + columnDefaults: { + width: 160, + sorting: { + enabled: true + }, + cells: { + format: '{value}' + } + } + }); + }); +}); diff --git a/packages/grid-shared-react/tests/options/Data.test.tsx b/packages/grid-shared-react/tests/options/Data.test.tsx new file mode 100644 index 0000000..a6f165a --- /dev/null +++ b/packages/grid-shared-react/tests/options/Data.test.tsx @@ -0,0 +1,38 @@ +import { describe, it, expect } from 'vitest'; +import { Data } from '../../src/components/options/data/Data'; +import { getChildProps } from '../../src/utils/getChildProps'; + +describe('Data', () => { + it('maps columns to options.data.columns', () => { + const columns = { + product: ['Apples', 'Oranges'], + price: [1.2, 2.4] + }; + + expect( + getChildProps( + + ) + ).toEqual({ + data: { + columns, + providerType: 'local', + autogenerateColumns: true + } + }); + }); + + it('maps dataTable to options.data.dataTable', () => { + const dataTable = { id: 'table-1', rows: [] }; + + expect(getChildProps()).toEqual({ + data: { + dataTable + } + }); + }); +}); diff --git a/packages/grid-shared-react/tests/options/Description.test.tsx b/packages/grid-shared-react/tests/options/Description.test.tsx new file mode 100644 index 0000000..145a800 --- /dev/null +++ b/packages/grid-shared-react/tests/options/Description.test.tsx @@ -0,0 +1,20 @@ +import { describe, it, expect } from 'vitest'; +import { Description } from '../../src/components/options/description/Description'; +import { getChildProps } from '../../src/utils/getChildProps'; + +describe('Description', () => { + it('maps description props and children into options.description', () => { + expect( + getChildProps( + + Monthly sales overview + + ) + ).toEqual({ + description: { + className: 'grid-description', + text: 'Monthly sales overview' + } + }); + }); +}); diff --git a/packages/grid-shared-react/tests/options/Header.test.tsx b/packages/grid-shared-react/tests/options/Header.test.tsx new file mode 100644 index 0000000..58fa656 --- /dev/null +++ b/packages/grid-shared-react/tests/options/Header.test.tsx @@ -0,0 +1,13 @@ +import { describe, it, expect } from 'vitest'; +import { Header } from '../../src/components/options/header/Header'; +import { getChildProps } from '../../src/utils/getChildProps'; + +describe('Header', () => { + it('maps header prop to options.header', () => { + const header = ['product', { columnId: 'price', format: '{value} USD' }]; + + expect(getChildProps(
)).toEqual({ + header + }); + }); +}); diff --git a/packages/grid-shared-react/tests/options/Pagination.test.tsx b/packages/grid-shared-react/tests/options/Pagination.test.tsx new file mode 100644 index 0000000..1608d8d --- /dev/null +++ b/packages/grid-shared-react/tests/options/Pagination.test.tsx @@ -0,0 +1,63 @@ +import { describe, it, expect } from 'vitest'; +import { Data } from '../../src/components/options/data/Data'; +import { Pagination } from '../../src/components/options/pagination/Pagination'; +import { getChildProps } from '../../src/utils/getChildProps'; + +describe('Pagination', () => { + it('normalizes pagination props into options.pagination', () => { + expect( + getChildProps( + + ) + ).toEqual({ + pagination: { + enabled: false, + page: 2, + pageSize: 25, + align: 'center', + position: 'top', + controls: { + pageInfo: true, + pageSizeSelector: { + enabled: true, + options: [10, 25, 50] + }, + pageButtons: { + enabled: true, + count: 5 + }, + firstLastButtons: true, + previousNextButtons: false + } + } + }); + }); + + it('sets position to top for the first pagination and bottom after other options', () => { + const top = getChildProps( + <> + + + + ); + const bottom = getChildProps( + <> + + + + ); + + expect(top.pagination).toMatchObject({ position: 'top' }); + expect(bottom.pagination).toMatchObject({ position: 'bottom' }); + }); +}); 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"] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 05e60b9..648ccc3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -32,6 +32,9 @@ importers: globals: specifier: ^17.0.0 version: 17.0.0 + husky: + specifier: ^9.1.7 + version: 9.1.7 playwright: specifier: ^1.57.0 version: 1.57.0 @@ -48,6 +51,37 @@ importers: specifier: ^4.0.16 version: 4.0.16(@types/node@20.19.26)(@vitest/browser-playwright@4.0.16)(jsdom@27.4.0) + examples/grid-lite/components-react: + dependencies: + '@highcharts/grid-lite': + specifier: '>=3.0.0' + version: 3.0.0 + '@highcharts/grid-lite-react': + specifier: workspace:* + version: link:../../../packages/grid-lite-react + react: + specifier: '>=18' + version: 19.2.1 + react-dom: + specifier: '>=18' + version: 19.2.1(react@19.2.1) + devDependencies: + '@types/react': + specifier: '>=18' + version: 19.2.7 + '@types/react-dom': + specifier: '>=18' + version: 19.2.3(@types/react@19.2.7) + '@vitejs/plugin-react': + specifier: ^4.2.0 + version: 4.7.0(vite@5.4.21(@types/node@20.19.26)) + typescript: + specifier: ^5.0.0 + version: 5.9.3 + vite: + specifier: ^5.0.0 + version: 5.4.21(@types/node@20.19.26) + examples/grid-lite/minimal-nextjs: dependencies: '@highcharts/grid-lite': @@ -1501,6 +1535,11 @@ packages: resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} engines: {node: '>= 14'} + husky@9.1.7: + resolution: {integrity: sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==} + engines: {node: '>=18'} + hasBin: true + ignore@5.3.2: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} @@ -3251,6 +3290,8 @@ snapshots: - supports-color optional: true + husky@9.1.7: {} + ignore@5.3.2: {} ignore@7.0.5: {} diff --git a/vitest.config.ts b/vitest.config.ts index 8ad4fee..e23f4e9 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -3,7 +3,10 @@ import { playwright } from '@vitest/browser-playwright'; export default defineConfig({ test: { - include: ['packages/*/src/**/*.test.{ts,tsx}'], + include: [ + 'packages/*/src/**/*.test.{ts,tsx}', + 'packages/*/tests/**/*.test.{ts,tsx}' + ], globals: true, css: true, browser: {