From acef00ff89bba3dc77885255c9aca3ecb970bc38 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 09:59:41 -0500 Subject: [PATCH 01/22] Generate the README API reference from JSDoc Make the JSDoc comments the single source of the API documentation: the README's API reference is generated from them, so the docs no longer have to be kept in sync by hand. - Move the API reference text of the README into the JSDoc comments of the exports, keeping the README's wording - Add `vp run docs`, which generates the API reference with TypeDoc and typedoc-plugin-markdown between the `api:start` and `api:end` markers of the README - `vp run ci` fails if the generated README is out of date - TypeDoc does not support TypeScript 7 yet, so it runs with `@typescript/typescript6` while the `typescript` package stays on TypeScript 7 Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 5 + AGENTS.md | 7 +- README.md | 4558 ++++++++++++++++++----- package-lock.json | 257 ++ package.json | 7 + scripts/generateApiDocs.ts | 277 ++ src/Cell.tsx | 5 + src/Columns.tsx | 41 + src/DataGrid.tsx | 600 ++- src/DataGridRenderersContext.ts | 35 + src/Row.tsx | 5 + src/TreeDataGrid.tsx | 131 + src/cellRenderers/SelectCheckbox.tsx | 7 + src/cellRenderers/renderCheckbox.tsx | 16 + src/cellRenderers/renderToggleGroup.tsx | 23 + src/cellRenderers/renderValue.tsx | 18 + src/editors/renderTextEditor.tsx | 18 + src/hooks/useRowSelection.ts | 69 + src/hooks/useScrollToPosition.tsx | 5 + src/index.ts | 5 + src/renderHeaderCell.tsx | 19 + src/sortStatus.tsx | 10 + src/types.ts | 609 ++- tsconfig.node.json | 7 +- typedoc.json | 37 + vite.config.ts | 13 +- 26 files changed, 5817 insertions(+), 967 deletions(-) create mode 100644 scripts/generateApiDocs.ts create mode 100644 typedoc.json diff --git a/.github/dependabot.yml b/.github/dependabot.yml index c6fa222447..11019201ea 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -24,6 +24,11 @@ updates: - 'react-dom' - '@types/react' - '@types/react-dom' + typedoc: + patterns: + - 'typedoc' + - 'typedoc-*' + - '@typescript/typescript6' # everything else: single PR for minor/patch bumps, # majors still land individually dependencies: diff --git a/AGENTS.md b/AGENTS.md index 39253499f5..a77b89ddb7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,8 @@ src/ style/ # build-time CSS via ecij tagged templates; layers.css declares @layer order cellRenderers/ # default cell renderers (e.g., checkbox, toggleGroup, value) editors/ # default editors (renderTextEditor) +scripts/ + generateApiDocs.ts # generates the API reference of README.md from JSDoc (`vp run docs`) test/ browser/ # vitest browser-mode tests (Playwright: Chromium, Firefox, WebKit) node/ # vitest SSR tests (Node.js) @@ -25,6 +27,7 @@ website/ # demo site (Vite + TanStack Router) ## Conventions - **Public API** — all exports flow through `src/index.ts`. Keep `README.md` in sync with user-facing changes. +- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. Every export from `src/index.ts` needs a `@group` tag with one of the sections in `groupOrder` of `typedoc.json` (Components, Hooks, Render Functions, Context, Other, Types). Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. - **Docs** — keep `AGENTS.md` in sync with tooling, conventions, or architectural changes. - **Default renderers** — `DataGridRenderersContext` allows overriding default renderers (`renderCheckbox`, `renderSortStatus`, `renderRow`, `renderCell`, `noRowsFallback`) without prop-drilling. - **TypeScript strict** with `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, `erasableSyntaxOnly`. Distinguish missing properties from `undefined` values. @@ -50,8 +53,9 @@ website/ # demo site (Vite + TanStack Router) The project uses [Vite+](https://viteplus.dev/guide/), whose global `vp` CLI wraps Vite, Rolldown, Vitest, tsdown, Oxlint, Oxfmt, and Vite Task. Run `vp` directly, not through `npx`. Its docs are in `node_modules/vite-plus/docs`. - `vp ` runs a built-in command, e.g., `vp dev`, `vp check`, `vp test`, `vp pack`, `vp build`. -- `vp run ` runs a task from `vite.config.ts`, e.g., `vp run typecheck`, `vp run eslint`, `vp run ci`. +- `vp run ` runs a task from `vite.config.ts`, e.g., `vp run typecheck`, `vp run eslint`, `vp run docs`, `vp run ci`. - Run `vp install` after pulling changes. +- `vp run docs` runs TypeDoc with `typedoc-plugin-markdown` (config in `typedoc.json`). TypeDoc does not support TypeScript 7 yet, so `scripts/generateApiDocs.ts` resolves TypeDoc's `typescript` imports to `@typescript/typescript6`; the `typescript` package stays on TypeScript 7. ## Validation @@ -62,4 +66,5 @@ While iterating, run individual checks instead. The static checks take seconds, - `vp run typecheck` type checks with `tsc --build`; `vp check` does not type check. - `vp check --fix` formats and lints, fixing what it can. Without `--fix`, a formatting error stops it before linting. - `vp run eslint` lints Markdown files. +- `vp run docs` regenerates the README's API reference; CI fails if it changes `README.md`. - `vp test ` runs specific test files, e.g., `vp test test/browser/sorting.test.tsx`. Add `--project "browser (chromium)"` to test in a single browser, or `--project node` to run the SSR test. The full suite takes about a minute. diff --git a/README.md b/README.md index 2046b9eaa3..cc0cc2c2c3 100644 --- a/README.md +++ b/README.md @@ -198,7 +198,7 @@ Example of customizing colors: ### Standard Props -The DataGrid accepts standard [`className`](#classname-string--undefined) and [`style`](#style-cssproperties--undefined) props: +The DataGrid accepts standard [`className`](#classname) and [`style`](#style) props: ```tsx + +## Components + +### Cell + +```ts +const Cell: (props: RenderCellProps) => Element; +``` + +The default cell component. Can be wrapped via the `renderers.renderCell` prop. + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `R` | +| `SR` | + +#### Parameters + +| Parameter | Type | +| --------- | -------------------------------------------------- | +| `props` | [`RenderCellProps`](#rendercellprops)\<`R`, `SR`\> | + +#### Returns + +`Element` + +--- + +### DataGrid() + +```ts +function DataGrid(props: DataGridProps): Element; +``` + +Main API component to render a data grid of rows and columns + +#### Type Parameters + +| Type Parameter | Default type | Description | +| ------------------- | ------------ | ---------------- | +| `R` | - | Row type | +| `SR` | `unknown` | Summary row type | +| `K` _extends_ `Key` | `Key` | Row key type | + +#### Parameters + +| Parameter | Type | +| --------- | --------------------------------------------------- | +| `props` | [`DataGridProps`](#datagridprops)\<`R`, `SR`, `K`\> | + +#### Returns + +`Element` + +#### Example -#### `` +```tsx + +``` + +--- + +### DataGridProps + +#### Type Parameters + +| Type Parameter | Default type | Description | +| ------------------- | ------------ | ---------------- | +| `R` | - | Row type | +| `SR` | `unknown` | Summary row type | +| `K` _extends_ `Key` | `Key` | Row key type | + +#### Properties + +##### ref? -##### DataGridProps +```ts +ref?: Maybe>; +``` + +Optional ref for imperative APIs like scrolling to or focusing a cell. See [`DataGridHandle`](#datagridhandle). -###### `columns: readonly ColumnOrColumnGroup[]` +##### columns -An array of column definitions and/or column groups. See the [`ColumnOrColumnGroup`](#columnorcolumngrouptrow-tsummaryrow) type for all available options. +```ts +columns: readonly ColumnOrColumnGroup[]; +``` + +An array of column definitions and/or column groups. See the [`ColumnOrColumnGroup`](#columnorcolumngroup) type for all available options. :warning: **Performance:** Passing a new `columns` array will trigger a re-render and recalculation for the entire grid. Always memoize this prop using `useMemo` or define it outside the component to avoid unnecessary re-renders. -###### `rows: readonly R[]` +##### rows + +```ts +rows: readonly R[]; +``` An array of rows. The row data can be of any type. @@ -264,23 +357,31 @@ An array of rows. The row data can be of any type. setRows(rows.map((row) => ({ ...row }))); ``` -###### `ref?: Maybe>` - -Optional ref for imperative APIs like scrolling to or focusing a cell. See [`DataGridHandle`](#datagridhandle). +##### topSummaryRows? -###### `topSummaryRows?: Maybe` +```ts +topSummaryRows?: Maybe; +``` Rows pinned at the top of the grid for summary purposes. :warning: **Performance:** Memoize this array to prevent internal memoization invalidation. -###### `bottomSummaryRows?: Maybe` +##### bottomSummaryRows? + +```ts +bottomSummaryRows?: Maybe; +``` Rows pinned at the bottom of the grid for summary purposes. :warning: **Performance:** Memoize this array to prevent internal memoization invalidation. -###### `rowKeyGetter?: Maybe<(row: R) => K>` +##### rowKeyGetter? + +```ts +rowKeyGetter?: Maybe<(row: R) => K>; +``` Function to return a unique key/identifier for each row. `rowKeyGetter` is required for row selection to work. @@ -305,12 +406,16 @@ function MyGrid() { :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. -###### `onRowsChange?: Maybe<(rows: R[], data: RowsChangeData) => void>` +##### onRowsChange? + +```ts +onRowsChange?: Maybe<(rows: R[], data: RowsChangeData) => void>; +``` Callback triggered when rows are changed. The first parameter is a new rows array with both the updated rows and the other untouched rows. -The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. See the [`RowsChangeData`](#rowschangedatatrow-tsummaryrow) type. +The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. See the [`RowsChangeData`](#rowschangedata) type. ```tsx import { useState } from 'react'; @@ -323,9 +428,11 @@ function MyGrid() { } ``` -###### `rowHeight?: Maybe number)>` +##### rowHeight? -**Default:** `35` pixels +```ts +rowHeight?: Maybe number)>; +``` Height of each row in pixels. A function can be used to set different row heights. @@ -343,15 +450,27 @@ function getRowHeight(row) { :warning: **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. -###### `headerRowHeight?: Maybe` +###### Default Value + +`35` pixels -**Default:** `rowHeight` when it is a number, otherwise `35` pixels +##### headerRowHeight? + +```ts +headerRowHeight?: Maybe; +``` Height of the header row in pixels. -###### `summaryRowHeight?: Maybe` +###### Default Value + +`rowHeight` when it is a number, otherwise `35` pixels -**Default:** `rowHeight` when it is a number, otherwise `35` pixels +##### summaryRowHeight? + +```ts +summaryRowHeight?: Maybe; +``` Height of each summary row in pixels. @@ -366,9 +485,17 @@ Height of each summary row in pixels. /> ``` -###### `columnWidths?: Maybe` +###### Default Value + +`rowHeight` when it is a number, otherwise `35` pixels + +##### columnWidths? + +```ts +columnWidths?: Maybe; +``` -A map of column widths containing both measured and resized widths. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths) type. +A map of column widths containing both measured and resized widths. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths-1) type. ```tsx const [columnWidths, setColumnWidths] = useState((): ColumnWidths => new Map()); @@ -382,19 +509,35 @@ function addNewRow() { return ``` -###### `onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>` +##### onColumnWidthsChange? + +```ts +onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; +``` + +Callback triggered when column widths change. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths-1) type. -Callback triggered when column widths change. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths) type. +##### selectedRows? -###### `selectedRows?: Maybe>` +```ts +selectedRows?: Maybe>; +``` A set of selected row keys. `rowKeyGetter` is required for row selection to work. -###### `isRowSelectionDisabled?: Maybe<(row: R) => boolean>` +##### isRowSelectionDisabled? + +```ts +isRowSelectionDisabled?: Maybe<(row: R) => boolean>; +``` Function to determine if row selection is disabled for a specific row. -###### `onSelectedRowsChange?: Maybe<(selectedRows: Set) => void>` +##### onSelectedRowsChange? + +```ts +onSelectedRowsChange?: Maybe<(selectedRows: Set) => void>; +``` Callback triggered when the selection changes. @@ -433,13 +576,21 @@ function MyGrid() { } ``` -###### `sortColumns?: Maybe` +##### sortColumns? + +```ts +sortColumns?: Maybe; +``` An array of sorted columns. See the [`SortColumn`](#sortcolumn) type. Sorting is controlled: the grid does not reorder `rows` for you. Apply the sorting to your `rows` state (or derived rows) based on `sortColumns`. -###### `onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>` +##### onSortColumnsChange? + +```ts +onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>; +``` Callback triggered when sorting changes. @@ -480,9 +631,13 @@ function onSortColumnsChange(sortColumns: SortColumn[]) { } ``` -###### `defaultColumnOptions?: Maybe>` +##### defaultColumnOptions? -Default options applied to all columns. See the [`DefaultColumnOptions`](#defaultcolumnoptionstrow-tsummaryrow) type. +```ts +defaultColumnOptions?: Maybe>; +``` + +Default options applied to all columns. See the [`DefaultColumnOptions`](#defaultcolumnoptions-1) type. ```tsx function MyGrid() { @@ -501,9 +656,13 @@ function MyGrid() { } ``` -###### `onCellMouseDown?: CellMouseEventHandler` +##### onCellMouseDown? + +```ts +onCellMouseDown?: CellMouseEventHandler; +``` -Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargstrow-tsummaryrow) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. ```tsx function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { @@ -515,9 +674,13 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellClick?: CellMouseEventHandler` +##### onCellClick? + +```ts +onCellClick?: CellMouseEventHandler; +``` -Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargstrow-tsummaryrow) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. This event can be used to open the cell editor on a single click: @@ -531,9 +694,13 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellDoubleClick?: CellMouseEventHandler` +##### onCellDoubleClick? + +```ts +onCellDoubleClick?: CellMouseEventHandler; +``` -Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargstrow-tsummaryrow) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. ```tsx function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { @@ -545,9 +712,13 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellContextMenu?: CellMouseEventHandler` +##### onCellContextMenu? -Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargstrow-tsummaryrow) and [`CellMouseEvent`](#cellmouseevent) types. +```ts +onCellContextMenu?: CellMouseEventHandler; +``` + +Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. ```tsx function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { @@ -560,9 +731,13 @@ function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellKeyDown?: Maybe<(args: CellKeyDownArgs, event: CellKeyboardEvent) => void>` +##### onCellKeyDown? + +```ts +onCellKeyDown?: Maybe<(args: CellKeyDownArgs, event: CellKeyboardEvent) => void>; +``` -Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. See the [`CellKeyDownArgs`](#cellkeydownargstrow-tsummaryrow) and [`CellKeyboardEvent`](#cellkeyboardevent) types. +Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. See the [`CellKeyDownArgs`](#cellkeydownargs) and [`CellKeyboardEvent`](#cellkeyboardevent) types. **Examples** @@ -586,27 +761,59 @@ function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { } ``` -See [more examples](website/routes/CellNavigation.tsx). +See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website/routes/CellNavigation.tsx). + +##### onCellCopy? + +```ts +onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => void>; +``` -###### `onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => void>` +Callback triggered when a cell's content is copied. See the [`CellCopyArgs`](#cellcopyargs) type. -Callback triggered when a cell's content is copied. See the [`CellCopyArgs`](#cellcopyargstrow-tsummaryrow) type. +##### onCellPaste? -###### `onCellPaste?: Maybe<(args: CellPasteArgs, event: CellClipboardEvent) => R>` +```ts +onCellPaste?: Maybe<(args: CellPasteArgs, event: CellClipboardEvent) => R>; +``` -Callback triggered when content is pasted into a cell. See the [`CellPasteArgs`](#cellpasteargstrow-tsummaryrow) type. +Callback triggered when content is pasted into a cell. See the [`CellPasteArgs`](#cellpasteargs) type. Return the updated row; the grid will call `onRowsChange` with it. -###### `onActivePositionChange?: Maybe<(args: PositionChangeArgs) => void>` +##### onActivePositionChange? + +```ts +onActivePositionChange?: Maybe<(args: PositionChangeArgs) => void>; +``` + +Callback triggered when the active position changes. See the [`PositionChangeArgs`](#positionchangeargs) type. + +##### onColumnResize? + +```ts +onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void>; +``` + +Callback triggered when a column is resized. The `column` parameter is the full [`CalculatedColumn`](#calculatedcolumn) object, and `width` is the new width in pixels. + +##### onColumnsReorder? + +```ts +onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>; +``` + +Callback triggered when columns are reordered. The parameters are the `key` values of the source and target columns. -Callback triggered when the active position changes. See the [`PositionChangeArgs`](#positionchangeargstrow-tsummaryrow) type. +##### onFill? -###### `onFill?: Maybe<(event: FillEvent) => R>` +```ts +onFill?: Maybe<(event: FillEvent) => R>; +``` Callback triggered when the value of the active cell is dragged to fill other cells. When this prop is set, a drag handle is shown on the active cell if it is editable. Drag the handle up or down to fill the cells it passes over, or double-click it to fill all the cells below. -The grid calls `onFill` for each editable target cell. Return the updated target row; the grid will call `onRowsChange` with the updated rows. See the [`FillEvent`](#filleventtrow) type. +The grid calls `onFill` for each editable target cell. Return the updated target row; the grid will call `onRowsChange` with the updated rows. See the [`FillEvent`](#fillevent) type. ```tsx function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { @@ -616,29 +823,35 @@ function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { ; ``` -###### `onScroll?: React.UIEventHandler | undefined` +##### onScroll? -Native DOM `onScroll` prop. +```ts +onScroll?: UIEventHandler; +``` -###### `onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void>` +Native DOM `onScroll` prop. -Callback triggered when a column is resized. The `column` parameter is the full [`CalculatedColumn`](#calculatedcolumntrow-tsummaryrow) object, and `width` is the new width in pixels. +##### enableVirtualization? -###### `onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>` +```ts +enableVirtualization?: Maybe; +``` -Callback triggered when columns are reordered. The parameters are the `key` values of the source and target columns. +This prop can be used to disable virtualization. -###### `enableVirtualization?: Maybe` +###### Default Value -**Default:** `true` +`true` -This prop can be used to disable virtualization. +##### renderers? -###### `renderers?: Maybe>` +```ts +renderers?: Maybe>; +``` Custom renderers for cells, rows, and other components. -See the [`Renderers`](#rendererstrow-tsummaryrow) type for the full shape. +See the [`Renderers`](#renderers-1) type for the full shape. Example of replacing default components: @@ -695,7 +908,11 @@ function MyGrid() { } ``` -###### `rowClass?: Maybe<(row: R, rowIdx: number) => Maybe>` +##### rowClass? + +```ts +rowClass?: Maybe<(row: R, rowIdx: number) => Maybe>; +``` Function to apply custom class names to rows. @@ -713,7 +930,11 @@ function MyGrid() { :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. -###### `headerRowClass?: Maybe` +##### headerRowClass? + +```ts +headerRowClass?: Maybe; +``` Custom class name for the header row. @@ -721,9 +942,13 @@ Custom class name for the header row. ``` -###### `direction?: Maybe<'ltr' | 'rtl'>` +##### direction? + +```ts +direction?: Maybe; +``` -This property sets the text direction of the grid. It defaults to `'ltr'` (left-to-right). See the [`Direction`](#direction) type. +This property sets the text direction of the grid. It defaults to `'ltr'` (left-to-right). See the [`Direction`](#direction-1) type. Setting `direction` to `'rtl'` has the following effects: @@ -732,39 +957,79 @@ Setting `direction` to `'rtl'` has the following effects: - Column resize cursor is shown on the left edge of the column - Scrollbar is moved to the left -###### `className?: string | undefined` +###### Default Value + +`'ltr'` + +##### className? + +```ts +className?: string; +``` Custom class name for the grid. -###### `style?: CSSProperties | undefined` +##### style? + +```ts +style?: CSSProperties; +``` Custom styles for the grid. -###### `role?: string | undefined` +##### role? + +```ts +role?: AriaRole; +``` ARIA role for the grid container. Defaults to `grid`. -###### `'aria-label'?: string | undefined` +##### aria-label? + +```ts +"aria-label"?: string; +``` The label of the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. -###### `'aria-labelledby'?: string | undefined` +##### aria-labelledby? + +```ts +"aria-labelledby"?: string; +``` The id of the element containing a label for the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. -###### `'aria-rowcount'?: number | undefined` +##### aria-rowcount? + +```ts +"aria-rowcount"?: number; +``` Total number of rows for assistive technologies. -###### `'aria-description'?: string | undefined` +##### aria-description? + +```ts +"aria-description"?: string; +``` A human-readable description of the grid. -###### `'aria-describedby'?: string | undefined` +##### aria-describedby? + +```ts +"aria-describedby"?: string; +``` If the grid has a caption or description, `aria-describedby` can be set on the grid element with a value referring to the element containing the description. -###### `'data-testid'?: Maybe` +##### data-testid? + +```ts +"data-testid"?: Maybe; +``` This prop can be used to add a test ID for testing. We recommend querying the grid by its `role` and `name`. @@ -779,11 +1044,99 @@ test('grid', async () => { }); ``` -###### `'data-cy'?: Maybe` +##### data-cy? + +```ts +"data-cy"?: Maybe; +``` Optional attribute to help with Cypress (or similar) selectors. -#### `` +--- + +### Row + +```ts +const Row: (props: RenderRowProps) => Element; +``` + +The default row component. Can be wrapped via the `renderers.renderRow` prop. + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `R` | +| `SR` | + +#### Parameters + +| Parameter | Type | +| --------- | ------------------------------------------------ | +| `props` | [`RenderRowProps`](#renderrowprops)\<`R`, `SR`\> | + +#### Returns + +`Element` + +--- + +### SelectCheckbox() + +```ts +function SelectCheckbox(__namedParameters: SelectCheckboxProps): ReactNode; +``` + +A component for rendering row selection checkboxes. + +The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. + +#### Parameters + +| Parameter | Type | +| ------------------- | --------------------------------------------- | +| `__namedParameters` | [`SelectCheckboxProps`](#selectcheckboxprops) | + +#### Returns + +`ReactNode` + +--- + +### ToggleGroup() + +```ts +function ToggleGroup(__namedParameters: RenderGroupCellContentProps): Element; +``` + +Low-level component used by `renderToggleGroup` to render the expand/collapse control. Useful if you build a custom group cell renderer. + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `R` | +| `SR` | + +#### Parameters + +| Parameter | Type | +| ------------------- | -------------------------------------------------------------------------- | +| `__namedParameters` | [`RenderGroupCellContentProps`](#rendergroupcellcontentprops)\<`R`, `SR`\> | + +#### Returns + +`Element` + +--- + +### TreeDataGrid() + +```ts +function TreeDataGrid( + __namedParameters: TreeDataGridProps +): Element; +``` `TreeDataGrid` is a component built on top of `DataGrid` to add hierarchical row grouping. This implements the [Treegrid pattern](https://www.w3.org/WAI/ARIA/apg/patterns/treegrid/). @@ -816,43 +1169,118 @@ The following `DataGrid` props are not supported in `TreeDataGrid`: - Cell copy/paste does not work on group rows - Column groups are not supported; `columns` must be `Column[]` -##### TreeDataGridProps +#### Type Parameters -All [`DataGridProps`](#datagridprops) are supported except those listed above. The `columns` prop only supports `Column[]` (no column groups). When `rowHeight` is a function, it receives [`RowHeightArgs`](#rowheightargstrow) instead of just the row. Additional props are listed below: +| Type Parameter | Default type | Description | +| ------------------- | ------------ | ---------------- | +| `R` | - | Row type | +| `SR` | `unknown` | Summary row type | +| `K` _extends_ `Key` | `Key` | Row key type | -###### `groupBy: readonly string[]` +#### Parameters -**Required.** An array of column keys to group by. The order determines the grouping hierarchy (first key is the top level, second key is nested under the first, etc.). +| Parameter | Type | +| ------------------- | ----------------------------------------------------------- | +| `__namedParameters` | [`TreeDataGridProps`](#treedatagridprops)\<`R`, `SR`, `K`\> | -```tsx -import { TreeDataGrid, type Column } from 'react-data-grid'; +#### Returns -interface Row { - id: number; - country: string; - city: string; - name: string; -} +`Element` -const columns: readonly Column[] = [ - { key: 'country', name: 'Country' }, - { key: 'city', name: 'City' }, - { key: 'name', name: 'Name' } -]; +--- -function MyGrid() { - return ( - - ); -} +### TreeDataGridProps + +All [`DataGridProps`](#datagridprops) are supported except those listed above. The `columns` prop only supports `Column[]` (no column groups). When `rowHeight` is a function, it receives [`RowHeightArgs`](#rowheightargs) instead of just the row. Additional props are listed below: + +#### Extends + +- [`Omit`](#omit)\<[`DataGridProps`](#datagridprops)\<`R`, `SR`, `K`\>, + \| `"columns"` + \| `"role"` + \| `"aria-rowcount"` + \| `"rowHeight"` + \| `"onFill"` + \| `"isRowSelectionDisabled"`\> + +#### Type Parameters + +| Type Parameter | Default type | Description | +| ------------------- | ------------ | ---------------- | +| `R` | - | Row type | +| `SR` | `unknown` | Summary row type | +| `K` _extends_ `Key` | `Key` | Row key type | + +#### Properties + +##### columns + +```ts +columns: readonly Column[]; +``` + +##### rowHeight? + +```ts +rowHeight?: Maybe< + | number +| ((args: RowHeightArgs) => number)>; +``` + +**Note:** Unlike `DataGrid`, the `rowHeight` function receives [`RowHeightArgs`](#rowheightargs), which includes a `type` property to distinguish between regular rows and group rows: + +```tsx +function getRowHeight(args: RowHeightArgs): number { + if (args.type === 'GROUP') { + return 50; // Custom height for group rows + } + return 35; // Height for regular rows +} + + +``` + +##### groupBy + +```ts +groupBy: readonly string[]; +``` + +**Required.** An array of column keys to group by. The order determines the grouping hierarchy (first key is the top level, second key is nested under the first, etc.). + +```tsx +import { TreeDataGrid, type Column } from 'react-data-grid'; + +interface Row { + id: number; + country: string; + city: string; + name: string; +} + +const columns: readonly Column[] = [ + { key: 'country', name: 'Country' }, + { key: 'city', name: 'City' }, + { key: 'name', name: 'Name' } +]; + +function MyGrid() { + return ( + + ); +} ``` -###### `rowGrouper: (rows: readonly R[], columnKey: string) => Record` +##### rowGrouper + +```ts +rowGrouper: (rows: readonly R[], columnKey: string) => Record; +``` **Required.** A function that groups rows by the specified column key. Returns an object where keys are the group values and values are arrays of rows belonging to that group. @@ -864,7 +1292,22 @@ function rowGrouper(rows: readonly Row[], columnKey: string): Record` +###### Parameters + +| Parameter | Type | +| ----------- | -------------- | +| `rows` | readonly `R`[] | +| `columnKey` | `string` | + +###### Returns + +`Record`\<`string`, readonly `R`[]\> + +##### expandedGroupIds + +```ts +expandedGroupIds: ReadonlySet; +``` **Required.** A set of group IDs that are currently expanded. Group IDs are generated by `groupIdGetter`. @@ -885,76 +1328,81 @@ function MyGrid() { } ``` -###### `onExpandedGroupIdsChange: (expandedGroupIds: Set) => void` +##### onExpandedGroupIdsChange -**Required.** Callback triggered when groups are expanded or collapsed. +```ts +onExpandedGroupIdsChange: (expandedGroupIds: Set) => void; +``` -###### `groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>` +**Required.** Callback triggered when groups are expanded or collapsed. -Function to generate unique IDs for group rows. If not provided, a default implementation is used that concatenates parent and group keys with `__`. +###### Parameters -:warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. +| Parameter | Type | +| ------------------ | ------------------ | +| `expandedGroupIds` | `Set`\<`unknown`\> | -###### `rowHeight?: Maybe) => number)>` +###### Returns -**Note:** Unlike `DataGrid`, the `rowHeight` function receives [`RowHeightArgs`](#rowheightargstrow), which includes a `type` property to distinguish between regular rows and group rows: +`void` -```tsx -function getRowHeight(args: RowHeightArgs): number { - if (args.type === 'GROUP') { - return 50; // Custom height for group rows - } - return 35; // Height for regular rows -} +##### groupIdGetter? - +```ts +groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>; ``` -#### `` - -The default row component. Can be wrapped via the `renderers.renderRow` prop. - -##### Props +Function to generate unique IDs for group rows. If not provided, a default implementation is used that concatenates parent and group keys with `__`. -[`RenderRowProps`](#renderrowpropstrow-tsummaryrow) +:warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. -#### `` +## Hooks -The default cell component. Can be wrapped via the `renderers.renderCell` prop. +### useHeaderRowSelection() -##### Props +```ts +function useHeaderRowSelection(): object; +``` -[`RenderCellProps`](#rendercellpropstrow-tsummaryrow) +Hook for managing header row selection state. Used within custom header cell renderers to implement custom "select all" functionality. -#### `` +#### Returns -A component for rendering row selection checkboxes. +`object` -##### Props +- `isIndeterminate: boolean` - Whether some (but not all) rows are selected +- `isRowSelected: boolean` - Whether all rows are selected +- `onRowSelectionChange: (event: SelectHeaderRowEvent) => void` - Callback to change selection state -The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. +##### isIndeterminate -#### `` +```ts +isIndeterminate: boolean; +``` -Low-level component used by `renderToggleGroup` to render the expand/collapse control. Useful if you build a custom group cell renderer. +##### isRowSelected -##### Props +```ts +isRowSelected: boolean; +``` -[`RenderGroupCellContentProps`](#rendergroupcellcontentpropstrow-tsummaryrow) +##### onRowSelectionChange -### Hooks +```ts +onRowSelectionChange: (selectRowEvent: SelectHeaderRowEvent) => void; +``` -#### `useHeaderRowSelection()` +###### Parameters -Hook for managing header row selection state. Used within custom header cell renderers to implement custom "select all" functionality. +| Parameter | Type | +| ---------------- | ----------------------------------------------- | +| `selectRowEvent` | [`SelectHeaderRowEvent`](#selectheaderrowevent) | -**Returns:** +###### Returns -- `isIndeterminate: boolean` - Whether some (but not all) rows are selected -- `isRowSelected: boolean` - Whether all rows are selected -- `onRowSelectionChange: (event: SelectHeaderRowEvent) => void` - Callback to change selection state +`void` -**Example:** +#### Example ```tsx import { useLayoutEffect, useRef } from 'react'; @@ -980,17 +1428,53 @@ function CustomHeaderCell() { } ``` -#### `useRowSelection()` +--- + +### useRowSelection() + +```ts +function useRowSelection(): object; +``` Hook for managing row selection state. Used within custom cell renderers to implement custom row selection. -**Returns:** +#### Returns + +`object` - `isRowSelectionDisabled: boolean` - Whether selection is disabled for this row - `isRowSelected: boolean` - Whether this row is selected - `onRowSelectionChange: (event: SelectRowEvent) => void` - Callback to change selection state -**Example:** +##### isRowSelectionDisabled + +```ts +isRowSelectionDisabled: boolean; +``` + +##### isRowSelected + +```ts +isRowSelected: boolean; +``` + +##### onRowSelectionChange + +```ts +onRowSelectionChange: (selectRowEvent: SelectRowEvent) => void; +``` + +###### Parameters + +| Parameter | Type | +| ---------------- | -------------------------------------------- | +| `selectRowEvent` | [`SelectRowEvent`](#selectrowevent)\<`any`\> | + +###### Returns + +`void` + +#### Example ```tsx function CustomSelectCell({ row }: RenderCellContentProps) { @@ -1013,15 +1497,68 @@ function CustomSelectCell({ row }: RenderCellContentProps) { } ``` -### Render Functions +## Render Functions + +### renderCheckbox() + +```ts +function renderCheckbox(__namedParameters: RenderCheckboxProps): Element; +``` + +Renders a checkbox input with proper styling and accessibility. + +#### Parameters + +| Parameter | Type | +| ------------------- | --------------------------------------------- | +| `__namedParameters` | [`RenderCheckboxProps`](#rendercheckboxprops) | + +#### Returns + +`Element` + +#### Example + +```tsx +import { DataGrid, renderCheckbox } from 'react-data-grid'; + + renderCheckbox({ ...props, 'aria-label': 'Select row' }) + }} +/>; +``` + +--- -#### `renderHeaderCell(props: RenderHeaderCellContentProps)` +### renderHeaderCell() + +```ts +function renderHeaderCell( + __namedParameters: RenderHeaderCellContentProps +): string | Element; +``` The default header cell content renderer. Renders sortable columns with sort indicators. -**Props:** [`RenderHeaderCellContentProps`](#renderheadercellcontentpropstrow-tsummaryrow) +#### Type Parameters + +| Type Parameter | +| -------------- | +| `R` | +| `SR` | + +#### Parameters + +| Parameter | Type | +| ------------------- | ---------------------------------------------------------------------------- | +| `__namedParameters` | [`RenderHeaderCellContentProps`](#renderheadercellcontentprops)\<`R`, `SR`\> | + +#### Returns + +`string` \| `Element` -**Example:** +#### Example ```tsx import { renderHeaderCell, type Column } from 'react-data-grid'; @@ -1036,13 +1573,76 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderTextEditor(props: RenderEditCellContentProps)` +--- + +### renderSortIcon() + +```ts +function renderSortIcon(__namedParameters: RenderSortIconProps): Element | null; +``` + +Renders the sort direction arrow icon. + +#### Parameters + +| Parameter | Type | +| ------------------- | --------------------------------------------- | +| `__namedParameters` | [`RenderSortIconProps`](#rendersorticonprops) | + +#### Returns + +`Element` \| `null` + +--- + +### renderSortPriority() + +```ts +function renderSortPriority(__namedParameters: RenderSortPriorityProps): number | undefined; +``` + +Renders the sort priority number for multi-column sorting. + +#### Parameters + +| Parameter | Type | +| ------------------- | ----------------------------------------------------- | +| `__namedParameters` | [`RenderSortPriorityProps`](#rendersortpriorityprops) | + +#### Returns + +`number` \| `undefined` + +--- + +### renderTextEditor() + +```ts +function renderTextEditor( + __namedParameters: RenderEditCellContentProps +): Element; +``` A basic text editor provided for convenience. -**Props:** [`RenderEditCellContentProps`](#rendereditcellcontentpropstrow-tsummaryrow) +#### Type Parameters + +| Type Parameter | +| -------------- | +| `TRow` | +| `TSummaryRow` | + +#### Parameters -**Example:** +| Parameter | Type | +| ------------------- | ------------------------------------------------------------------------------------ | +| `__namedParameters` | [`RenderEditCellContentProps`](#rendereditcellcontentprops)\<`TRow`, `TSummaryRow`\> | + +#### Returns + +`Element` + +#### Example ```tsx import { renderTextEditor, type Column } from 'react-data-grid'; @@ -1056,43 +1656,34 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderSortIcon(props: RenderSortIconProps)` - -Renders the sort direction arrow icon. - -**Props:** [`RenderSortIconProps`](#rendersorticonprops) - -#### `renderSortPriority(props: RenderSortPriorityProps)` - -Renders the sort priority number for multi-column sorting. - -**Props:** [`RenderSortPriorityProps`](#rendersortpriorityprops) +--- -#### `renderCheckbox(props: RenderCheckboxProps)` +### renderToggleGroup() -Renders a checkbox input with proper styling and accessibility. +```ts +function renderToggleGroup(props: RenderGroupCellContentProps): Element; +``` -**Props:** [`RenderCheckboxProps`](#rendercheckboxprops) +The default group cell content renderer for the columns used for grouping (`groupBy` prop). This renders the expand/collapse toggle. -**Example:** +#### Type Parameters -```tsx -import { DataGrid, renderCheckbox } from 'react-data-grid'; +| Type Parameter | +| -------------- | +| `R` | +| `SR` | - renderCheckbox({ ...props, 'aria-label': 'Select row' }) - }} -/>; -``` +#### Parameters -#### `renderToggleGroup(props: RenderGroupCellContentProps)` +| Parameter | Type | +| --------- | -------------------------------------------------------------------------- | +| `props` | [`RenderGroupCellContentProps`](#rendergroupcellcontentprops)\<`R`, `SR`\> | -The default group cell content renderer for the columns used for grouping (`groupBy` prop). This renders the expand/collapse toggle. +#### Returns -**Props:** [`RenderGroupCellContentProps`](#rendergroupcellcontentpropstrow-tsummaryrow) +`Element` -**Example:** +#### Example ```tsx import { renderToggleGroup, type Column } from 'react-data-grid'; @@ -1106,13 +1697,34 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderValue(props: RenderCellContentProps)` +--- + +### renderValue() + +```ts +function renderValue(props: RenderCellContentProps): ReactNode; +``` The default cell content renderer that renders the value of `row[column.key]`. -**Props:** [`RenderCellContentProps`](#rendercellcontentpropstrow-tsummaryrow) +#### Type Parameters + +| Type Parameter | +| -------------- | +| `R` | +| `SR` | -**Example:** +#### Parameters + +| Parameter | Type | +| --------- | ---------------------------------------------------------------- | +| `props` | [`RenderCellContentProps`](#rendercellcontentprops)\<`R`, `SR`\> | + +#### Returns + +`ReactNode` + +#### Example ```tsx import { renderValue, type Column } from 'react-data-grid'; @@ -1126,13 +1738,17 @@ const columns: readonly Column[] = [ ]; ``` -### Context +## Context -#### `DataGridRenderersContext` +### DataGridRenderersContext + +```ts +const DataGridRenderersContext: Context>>; +``` Context for providing default renderers to DataGrids in your app. -**Example:** +#### Example ```tsx import { @@ -1163,14 +1779,36 @@ function AppProvider({ children }) { } ``` -### Other +## Other + +### SELECT\_COLUMN\_KEY + +```ts +const SELECT_COLUMN_KEY: 'rdg-select-column' = 'rdg-select-column'; +``` + +The key used for the `SelectColumn`. Useful for identifying or filtering the select column. + +#### Example + +```tsx +import { SELECT_COLUMN_KEY } from 'react-data-grid'; + +const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN_KEY); +``` + +--- + +### SelectColumn -#### `SelectColumn: Column` +```ts +const SelectColumn: Column; +``` A pre-configured column for row selection. Includes checkbox renderers for the header row, regular rows, and group rows. -**Example:** +#### Example ```tsx import { DataGrid, SelectColumn, type Column } from 'react-data-grid'; @@ -1194,42 +1832,65 @@ function MyGrid() { } ``` -#### `SELECT_COLUMN_KEY = 'rdg-select-column'` +## Types -The key used for the `SelectColumn`. Useful for identifying or filtering the select column. +### CalculatedColumn -**Example:** +Extends `Column` with additional computed properties used internally by the grid. This is the type passed to render functions. The `Column` properties it redeclares, like `width` and `renderCell`, are resolved to their default values when not set. -```tsx -import { SELECT_COLUMN_KEY } from 'react-data-grid'; +#### See -const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN_KEY); -``` +[`Column`](#column-1), [`onColumnResize`](#oncolumnresize) prop on `` -### Types +#### Extends -#### `Column` +- [`Column`](#column-1)\<`TRow`, `TSummaryRow`\> -Defines the configuration for a column in the grid. +#### Type Parameters -**See also:** [`columns`](#columns-readonly-columnorcolumngroupr-sr) prop on `` +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | -##### `name: string | ReactElement` +#### Properties -The name of the column. Displayed in the header cell by default. +##### parent -##### `key: string` +```ts +readonly parent: + | CalculatedColumnParent + | undefined; +``` -A unique key to distinguish each column. +The column group that contains the column, or `undefined` if the column is not in a group -##### `width?: Maybe` +##### idx -**Default:** `auto` +```ts +readonly idx: number; +``` -Width can be any valid CSS grid column value. If not specified, it will be determined automatically based on grid width and specified widths of other columns. +The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` -```tsx -const columns: Column[] = [ +##### level + +```ts +readonly level: number; +``` + +Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups + +##### width + +```ts +readonly width: string | number; +``` + +Width can be any valid CSS grid column value. If not specified, it will be determined automatically based on grid width and specified widths of other columns. + +```tsx +const columns: Column[] = [ { key: 'id', name: 'ID', @@ -1262,108 +1923,95 @@ width: 'minmax(100px, max-content)', `max-content` can be used to expand the column to show all the content. Note that the grid is only able to calculate column width for visible rows. -##### `minWidth?: Maybe` +###### Default Value + +`auto` + +###### Overrides + +[`Column`](#column-1).[`width`](#width-1) -**Default:** `50` pixels +##### minWidth + +```ts +readonly minWidth: number; +``` Minimum column width in pixels. -##### `maxWidth?: Maybe` +###### Default Value -Maximum column width in pixels. +`50` pixels -##### `cellClass?: Maybe Maybe)>` +###### Overrides -Class name(s) for cells. Can be a string or a function that returns a class name based on the row. +[`Column`](#column-1).[`minWidth`](#minwidth-1) -```tsx -const columns: Column[] = [ - { - key: 'status', - name: 'Status', - cellClass: (row) => `status-${row.status}` - }, - { - key: 'price', - name: 'Price', - cellClass: 'text-right' // Static class - } -]; +##### maxWidth + +```ts +readonly maxWidth: number | undefined; ``` -```css -.status-active { - color: green; - font-weight: bold; -} +Maximum column width in pixels. -.status-inactive { - color: gray; -} +###### Overrides -.text-right { - text-align: right; -} -``` +[`Column`](#column-1).[`maxWidth`](#maxwidth-1) -##### `headerCellClass?: Maybe` +##### resizable -Class name(s) for the header cell. +```ts +readonly resizable: boolean; +``` -##### `summaryCellClass?: Maybe Maybe)>` +Enable resizing of the column. -Class name(s) for summary cells. Can be a string or a function that returns a class name based on the summary row. +###### Default Value -##### `renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>` +`false` -Render function to render the content of cells. +###### Overrides -##### `renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) => ReactNode>` +[`Column`](#column-1).[`resizable`](#resizable-1) -Render function to render the content of the header cell. +##### sortable -##### `renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>` +```ts +readonly sortable: boolean; +``` -Render function to render the content of summary cells. +Enable sorting of the column. -##### `renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>` +###### Default Value -Render function to render the content of group cells when using `TreeDataGrid`. +`false` -##### `renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>` +###### Overrides -Render function to render the content of edit cells. When set, the column is automatically set to be editable. +[`Column`](#column-1).[`sortable`](#sortable-1) -##### `editable?: Maybe boolean)>` +##### draggable -Control whether cells can be edited with `renderEditCell`. +```ts +readonly draggable: boolean; +``` -##### `colSpan?: Maybe<(args: ColSpanArgs) => Maybe>` +Enable dragging of the column. -Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. See the [`ColSpanArgs`](#colspanargstrow-tsummaryrow) type. +###### Default Value -**Example:** +`false` -```tsx -import type { Column } from 'react-data-grid'; +###### Overrides -const columns: readonly Column[] = [ - { - key: 'title', - name: 'Title', - colSpan(args) { - if (args.type === 'ROW' && args.row.isFullWidth) { - return 5; // Span 5 columns for full-width rows - } - return undefined; - } - } -]; -``` +[`Column`](#column-1).[`draggable`](#draggable-1) -##### `frozen?: Maybe` +##### frozen -**Default:** `false` +```ts +readonly frozen: ColumnFrozen; +``` Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. See the [`ColumnFrozen`](#columnfrozen) type. @@ -1379,871 +2027,3043 @@ const columns: readonly Column[] = [ ]; ``` -##### `resizable?: Maybe` - -**Default:** `false` +###### Default Value -Enable resizing of the column. +`false` -##### `sortable?: Maybe` +###### Overrides -**Default:** `false` +[`Column`](#column-1).[`frozen`](#frozen-1) -Enable sorting of the column. +##### renderCell -##### `draggable?: Maybe` +```ts +readonly renderCell: (props: RenderCellContentProps) => ReactNode; +``` -**Default:** `false` +Render function to render the content of cells. -Enable dragging of the column. +###### Parameters -##### `sortDescendingFirst?: Maybe` +| Parameter | Type | +| --------- | ---------------------------------------------------------------------------- | +| `props` | [`RenderCellContentProps`](#rendercellcontentprops)\<`TRow`, `TSummaryRow`\> | -**Default:** `false` +###### Returns -Sets the column sort order to be descending instead of ascending the first time the column is sorted. +`ReactNode` -##### `editorOptions` +###### Overrides -Options for cell editing. +[`Column`](#column-1).[`renderCell`](#rendercell-1) -###### `displayCellContent?: Maybe` +##### renderHeaderCell -**Default:** `false` +```ts +readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; +``` -Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. +Render function to render the content of the header cell. -###### `commitOnOutsideClick?: Maybe` +###### Parameters -**Default:** `true` +| Parameter | Type | +| --------- | ---------------------------------------------------------------------------------------- | +| `props` | [`RenderHeaderCellContentProps`](#renderheadercellcontentprops)\<`TRow`, `TSummaryRow`\> | -Commit changes when clicking outside the cell. +###### Returns -###### `closeOnExternalRowChange?: Maybe` +`ReactNode` -**Default:** `true` +###### Overrides -Close the editor when the row value changes externally. +[`Column`](#column-1).[`renderHeaderCell`](#renderheadercell-2) -#### `ColumnGroup` +--- -Defines a group of columns that share a common header. +### CalculatedColumnOrColumnGroup -```tsx -interface ColumnGroup { - /** The name of the column group. It will be displayed in the header cell */ - readonly name: string | ReactElement; - readonly headerCellClass?: Maybe; - readonly children: readonly ColumnOrColumnGroup[]; -} +```ts +type CalculatedColumnOrColumnGroup = CalculatedColumnParent | CalculatedColumn; ``` -**Example:** +Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. -```tsx -import type { ColumnOrColumnGroup } from 'react-data-grid'; +#### Type Parameters -const columns: readonly ColumnOrColumnGroup[] = [ - { - name: 'Personal Info', - children: [ - { key: 'firstName', name: 'First Name' }, - { key: 'lastName', name: 'Last Name' } - ] - } -]; -``` +| Type Parameter | +| -------------- | +| `R` | +| `SR` | -**See also:** [`ColumnOrColumnGroup`](#columnorcolumngrouptrow-tsummaryrow) +#### See -#### `ColumnOrColumnGroup` +[`CalculatedColumn`](#calculatedcolumn), [`CalculatedColumnParent`](#calculatedcolumnparent) -Union type representing either a `Column` or a `ColumnGroup`. +--- -**See also:** [`columns`](#columns-readonly-columnorcolumngroupr-sr) prop on `` +### CalculatedColumnParent -#### `CalculatedColumn` +Represents a parent column group in the calculated column structure. -Extends `Column` with additional computed properties used internally by the grid. This is the type passed to render functions. The `Column` properties it redeclares, like `width` and `renderCell`, are resolved to their default values when not set. +#### See -```tsx -interface CalculatedColumn extends Column { - /** The column group that contains the column, or `undefined` if the column is not in a group */ - readonly parent: CalculatedColumnParent | undefined; - /** The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` */ - readonly idx: number; - /** Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups */ - readonly level: number; - readonly width: number | string; - readonly minWidth: number; - readonly maxWidth: number | undefined; - readonly resizable: boolean; - readonly sortable: boolean; - readonly draggable: boolean; - readonly frozen: ColumnFrozen; - readonly renderCell: (props: RenderCellContentProps) => ReactNode; - readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; -} -``` +[`CalculatedColumn`](#calculatedcolumn) -**See also:** [`Column`](#columntrow-tsummaryrow), [`onColumnResize`](#oncolumnresize-maybecolumn-calculatedcolumnr-sr-width-number--void) prop on `` +#### Type Parameters -#### `CalculatedColumnParent` +| Type Parameter | +| -------------- | +| `R` | +| `SR` | -Represents a parent column group in the calculated column structure. +#### Properties -```tsx -interface CalculatedColumnParent { - readonly name: string | ReactElement; - readonly parent: CalculatedColumnParent | undefined; - readonly idx: number; - readonly colSpan: number; - readonly level: number; - readonly headerCellClass?: Maybe; -} +##### name + +```ts +readonly name: + | string +| ReactElement>; ``` -**See also:** [`CalculatedColumn`](#calculatedcolumntrow-tsummaryrow) +##### parent -#### `CalculatedColumnOrColumnGroup` +```ts +readonly parent: + | CalculatedColumnParent + | undefined; +``` -Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. +##### idx -```tsx -type CalculatedColumnOrColumnGroup = CalculatedColumnParent | CalculatedColumn; +```ts +readonly idx: number; ``` -**See also:** [`CalculatedColumn`](#calculatedcolumntrow-tsummaryrow), [`CalculatedColumnParent`](#calculatedcolumnparenttrow-tsummaryrow) +##### colSpan -#### `DefaultColumnOptions` +```ts +readonly colSpan: number; +``` -Default options applied to all columns. +##### level -```tsx -type DefaultColumnOptions = Pick< - Column, - | 'renderCell' - | 'renderHeaderCell' - | 'width' - | 'minWidth' - | 'maxWidth' - | 'resizable' - | 'sortable' - | 'draggable' ->; +```ts +readonly level: number; ``` -**See also:** [`defaultColumnOptions`](#defaultcolumnoptions-maybedefaultcolumnoptionsr-sr) prop on `` +##### headerCellClass? -#### `ColumnFrozen` +```ts +readonly headerCellClass?: Maybe; +``` -Whether a column is frozen, and on which edge. +--- -```tsx -type ColumnFrozen = boolean | 'start' | 'end'; +### CellCopyArgs + +```ts +type CellCopyArgs = CellCopyPasteArgs; ``` -**See also:** [`column.frozen`](#frozen-maybeboolean--start--end) +Arguments passed to `onCellCopy`. -#### `RenderCellContentProps` +#### Type Parameters -Props passed to custom cell content renderers (`column.renderCell`). +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | -```tsx -interface RenderCellContentProps { - column: CalculatedColumn; - row: TRow; - rowIdx: number; - isCellEditable: boolean; - tabIndex: number; - onRowChange: (row: TRow) => void; -} -``` +#### See -**Example:** +[`onCellCopy`](#oncellcopy) prop on `` -```tsx -import type { RenderCellContentProps } from 'react-data-grid'; +--- -function renderCell({ row, column, onRowChange }: RenderCellContentProps) { - return ( -
- {row[column.key]} - -
- ); -} +### CellKeyboardEvent + +```ts +type CellKeyboardEvent = CellEvent>; ``` -**See also:** [`column.renderCell`](#rendercell-maybeprops-rendercellcontentpropstrow-tsummaryrow--reactnode), [`renderValue`](#rendervaluer-srprops-rendercellcontentpropsr-sr) function +Extends `React.KeyboardEvent` with grid-specific methods. -#### `RenderHeaderCellContentProps` +#### See -Props passed to custom header cell content renderers (`column.renderHeaderCell`). +[`onCellKeyDown`](#oncellkeydown) prop on `` -```tsx -interface RenderHeaderCellContentProps { - column: CalculatedColumn; - sortDirection: SortDirection | undefined; - priority: number | undefined; - tabIndex: number; -} +--- + +### CellKeyDownArgs + +```ts +type CellKeyDownArgs = + | ActiveCellKeyDownArgs + | EditCellKeyDownArgs; ``` -**See also:** [`column.renderHeaderCell`](#renderheadercell-maybeprops-renderheadercellcontentpropstrow-tsummaryrow--reactnode), [`renderHeaderCell`](#renderheadercellr-srprops-renderheadercellcontentpropsr-sr) function +Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. + +#### Type Parameters -#### `RenderEditCellContentProps` +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | -Props passed to custom editors (`column.renderEditCell`). +#### Example ```tsx -interface RenderEditCellContentProps { - column: CalculatedColumn; - row: TRow; - rowIdx: number; - onRowChange: (row: TRow, commitChanges?: boolean) => void; - onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; +import type { CellKeyboardEvent, CellKeyDownArgs } from 'react-data-grid'; + +function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { + if (args.mode === 'EDIT' && event.key === 'Escape') { + args.onClose(false); // Close without committing + event.preventGridDefault(); + } } ``` -**Example:** +#### See -```tsx -import type { RenderEditCellContentProps } from 'react-data-grid'; +[`onCellKeyDown`](#oncellkeydown) prop on `` -function renderEditor({ row, column, onRowChange, onClose }: RenderEditCellContentProps) { - return ( - onRowChange({ ...row, [column.key]: event.target.value })} - onBlur={() => onClose(true)} - /> - ); -} -``` +--- -**See also:** [`column.renderEditCell`](#rendereditcell-maybeprops-rendereditcellcontentpropstrow-tsummaryrow--reactnode), [`renderTextEditor`](#rendertexteditortrow-tsummaryrowprops-rendereditcellcontentpropstrow-tsummaryrow) function +### CellMouseArgs -#### `RenderSummaryCellContentProps` +Arguments passed to cell mouse event handlers. -Props passed to summary cell content renderers (`column.renderSummaryCell`). +#### Example ```tsx -interface RenderSummaryCellContentProps { - column: CalculatedColumn; - row: TSummaryRow; - tabIndex: number; +import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; + +function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { + console.log('Clicked cell at row', args.rowIdx, 'column', args.column.key); + args.setActivePosition(true); // Focus and start editing } ``` -**See also:** [`column.renderSummaryCell`](#rendersummarycell-maybeprops-rendersummarycellcontentpropstsummaryrow-trow--reactnode) - -#### `RenderGroupCellContentProps` +#### See -Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. +[`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` -```tsx -interface RenderGroupCellContentProps { - groupKey: unknown; - column: CalculatedColumn; - row: GroupRow; - childRows: readonly TRow[]; - isExpanded: boolean; - tabIndex: number; - toggleGroup: () => void; -} -``` +#### Type Parameters -**See also:** [`column.renderGroupCell`](#rendergroupcell-maybeprops-rendergroupcellcontentpropstrow-tsummaryrow--reactnode), [`renderToggleGroup`](#rendertogglegroupr-srprops-rendergroupcellcontentpropsr-sr) function, [``](#togglegroup-) +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | -#### `RenderRowProps` +#### Properties -Props passed to custom row renderers. +##### column -```tsx -interface RenderRowProps { - row: TRow; - iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; - rowIdx: number; - activeCellIdx: number | undefined; - isRowSelectionDisabled: boolean; - isRowSelected: boolean; - gridRowStart: number; - draggedOverCellIdx: number | undefined; - activeCellEditor: ReactElement> | undefined; - onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: TRow) => void; - rowClass: Maybe<(row: TRow, rowIdx: number) => Maybe>; - isTreeGrid: boolean; - setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; - // ... and DOM props, cell event handlers (onCellMouseDown, onCellClick, onCellDoubleClick, onCellContextMenu) -} +```ts +column: CalculatedColumn; ``` -**See also:** [`renderers.renderRow`](#renderers-mayberenderersr-sr), [``](#row-) +The column object of the cell. -#### `RenderCellProps` - -Props passed to the cell renderer when using `renderers.renderCell`. +##### row -```tsx -interface RenderCellProps { - column: CalculatedColumn; - row: TRow; - rowIdx: number; - colSpan: number | undefined; - isDraggedOver: boolean; - isCellActive: boolean; - onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: TRow) => void; - setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; - // ... and DOM props, cell event handlers (onCellMouseDown, onCellClick, onCellDoubleClick, onCellContextMenu) -} +```ts +row: TRow; ``` -**See also:** [`renderers.renderCell`](#renderers-mayberenderersr-sr), [``](#cell-) - -#### `RenderCheckboxProps` +The row object of the cell. -Props for custom checkbox renderers. +##### rowIdx -```tsx -interface RenderCheckboxProps { - /** Whether the checkbox is checked */ - checked?: boolean | undefined; - /** Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected */ - indeterminate?: boolean | undefined; - /** Whether the checkbox is disabled */ - disabled?: boolean | undefined; - /** Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows */ - onChange: (checked: boolean, shift: boolean) => void; - /** `0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox */ - tabIndex?: number | undefined; - /** Accessible label for the checkbox */ - 'aria-label'?: string | undefined; - /** ID of the element that labels the checkbox */ - 'aria-labelledby'?: string | undefined; -} +```ts +rowIdx: number; ``` -**See also:** [`renderCheckbox`](#rendercheckboxprops-rendercheckboxprops) function, [`renderers.renderCheckbox`](#renderers-mayberenderersr-sr), [``](#selectcheckbox-) +The row index of the cell. -#### `RenderSortStatusProps` +##### setActivePosition -Props for custom sort status renderers. - -```tsx -interface RenderSortStatusProps extends RenderSortIconProps, RenderSortPriorityProps {} +```ts +setActivePosition: (enableEditor?: boolean) => void; ``` -**See also:** [`renderers.renderSortStatus`](#renderers-mayberenderersr-sr) +Function to manually focus the cell. Pass `true` to immediately start editing. -#### `RenderSortIconProps` +###### Parameters -Props for custom sort icon renderers. +| Parameter | Type | +| --------------- | --------- | +| `enableEditor?` | `boolean` | -```tsx -interface RenderSortIconProps { - /** The sort direction of the column, or `undefined` if it is not sorted */ - sortDirection: SortDirection | undefined; -} -``` +###### Returns -**See also:** [`renderSortIcon`](#rendersorticonprops-rendersorticonprops) function +`void` -#### `RenderSortPriorityProps` +--- -Props for custom sort priority renderers. +### CellMouseEvent -```tsx -interface RenderSortPriorityProps { - /** The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise */ - priority: number | undefined; -} +```ts +type CellMouseEvent = CellEvent>; ``` -**See also:** [`renderSortPriority`](#rendersortpriorityprops-rendersortpriorityprops) function - -#### `Renderers` +Extends `React.MouseEvent` with grid-specific methods. -Custom renderer configuration for the grid. +#### Example ```tsx -interface Renderers { - renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; - renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>; - renderRow?: Maybe<(key: Key, props: RenderRowProps) => ReactNode>; - renderSortStatus?: Maybe<(props: RenderSortStatusProps) => ReactNode>; - noRowsFallback?: Maybe; +import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; + +function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'actions') { + event.preventGridDefault(); // Prevent cell focus + } } ``` -**See also:** [`renderers`](#renderers-mayberenderersr-sr) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) +#### See -#### `CellMouseArgs` +[`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` -Arguments passed to cell mouse event handlers. +--- -```tsx -interface CellMouseArgs { - /** The column object of the cell. */ - column: CalculatedColumn; - /** The row object of the cell. */ - row: TRow; - /** The row index of the cell. */ - rowIdx: number; - /** Function to manually focus the cell. Pass `true` to immediately start editing. */ - setActivePosition: (enableEditor?: boolean) => void; -} +### CellPasteArgs + +```ts +type CellPasteArgs = CellCopyPasteArgs; ``` -**Example:** +Arguments passed to `onCellPaste`. + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### See + +[`onCellPaste`](#oncellpaste) prop on `` + +--- + +### ColSpanArgs + +```ts +type ColSpanArgs = + | { + type: 'HEADER'; + } + | { + type: 'ROW'; + row: TRow; + } + | { + type: 'SUMMARY'; + row: TSummaryRow; + }; +``` + +Arguments passed to the `colSpan` function. + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `TRow` | +| `TSummaryRow` | + +#### Example + +```tsx +import type { Column } from 'react-data-grid'; + +const columns: readonly Column[] = [ + { + key: 'title', + name: 'Title', + colSpan(args) { + if (args.type === 'ROW' && args.row.isFullWidth) { + return 3; // Span 3 columns + } + return undefined; + } + } +]; +``` + +#### See + +[`column.colSpan`](#colspan-1) + +--- + +### Column + +Defines the configuration for a column in the grid. + +#### See + +[`columns`](#columns) prop on `` + +#### Extended by + +- [`CalculatedColumn`](#calculatedcolumn) + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### name + +```ts +readonly name: + | string +| ReactElement>; +``` + +The name of the column. Displayed in the header cell by default. + +##### key + +```ts +readonly key: string; +``` + +A unique key to distinguish each column. + +##### width? + +```ts +readonly width?: Maybe; +``` + +Width can be any valid CSS grid column value. If not specified, it will be determined automatically based on grid width and specified widths of other columns. + +```tsx +const columns: Column[] = [ + { + key: 'id', + name: 'ID', + width: 80, // Fixed width in pixels + resizable: false + }, + { + key: 'name', + name: 'Name', + width: '30%', // Percentage width + minWidth: 100, + maxWidth: 400 + }, + { + key: 'description', + name: 'Description' + // No width specified - automatically sized + } +]; +``` + +Other examples: + +```tsx +width: 80, // pixels +width: '25%', +width: 'max-content', +width: 'minmax(100px, max-content)', +``` + +`max-content` can be used to expand the column to show all the content. Note that the grid is only able to calculate column width for visible rows. + +###### Default Value + +`auto` + +##### minWidth? + +```ts +readonly minWidth?: Maybe; +``` + +Minimum column width in pixels. + +###### Default Value + +`50` pixels + +##### maxWidth? + +```ts +readonly maxWidth?: Maybe; +``` + +Maximum column width in pixels. + +##### cellClass? + +```ts +readonly cellClass?: Maybe Maybe)>; +``` + +Class name(s) for cells. Can be a string or a function that returns a class name based on the row. + +```tsx +const columns: Column[] = [ + { + key: 'status', + name: 'Status', + cellClass: (row) => `status-${row.status}` + }, + { + key: 'price', + name: 'Price', + cellClass: 'text-right' // Static class + } +]; +``` + +```css +.status-active { + color: green; + font-weight: bold; +} + +.status-inactive { + color: gray; +} + +.text-right { + text-align: right; +} +``` + +##### headerCellClass? + +```ts +readonly headerCellClass?: Maybe; +``` + +Class name(s) for the header cell. + +##### summaryCellClass? + +```ts +readonly summaryCellClass?: Maybe Maybe)>; +``` + +Class name(s) for summary cells. Can be a string or a function that returns a class name based on the summary row. + +##### renderCell? + +```ts +readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; +``` + +Render function to render the content of cells. + +##### renderHeaderCell? + +```ts +readonly renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) => ReactNode>; +``` + +Render function to render the content of the header cell. + +##### renderSummaryCell? + +```ts +readonly renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>; +``` + +Render function to render the content of summary cells. + +##### renderGroupCell? + +```ts +readonly renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>; +``` + +Render function to render the content of group cells when using `TreeDataGrid`. + +##### renderEditCell? + +```ts +readonly renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>; +``` + +Render function to render the content of edit cells. When set, the column is automatically set to be editable. + +##### editable? + +```ts +readonly editable?: Maybe boolean)>; +``` + +Control whether cells can be edited with `renderEditCell`. + +##### colSpan? + +```ts +readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; +``` + +Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. See the [`ColSpanArgs`](#colspanargs) type. + +###### Example + +```tsx +import type { Column } from 'react-data-grid'; + +const columns: readonly Column[] = [ + { + key: 'title', + name: 'Title', + colSpan(args) { + if (args.type === 'ROW' && args.row.isFullWidth) { + return 5; // Span 5 columns for full-width rows + } + return undefined; + } + } +]; +``` + +##### frozen? + +```ts +readonly frozen?: Maybe; +``` + +Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. See the [`ColumnFrozen`](#columnfrozen) type. + +- `'start'` (or `true` for backward compatibility) — pins the column to the start edge (left in LTR, right in RTL). +- `'end'` — pins the column to the end edge (right in LTR, left in RTL). +- `false` (default) — the column scrolls with the rest of the grid. + +```tsx +const columns: readonly Column[] = [ + { key: 'id', name: 'ID', frozen: 'start' }, + { key: 'name', name: 'Name' }, + { key: 'actions', name: 'Actions', frozen: 'end' } +]; +``` + +###### Default Value + +`false` + +##### resizable? + +```ts +readonly resizable?: Maybe; +``` + +Enable resizing of the column. + +###### Default Value + +`false` + +##### sortable? + +```ts +readonly sortable?: Maybe; +``` + +Enable sorting of the column. + +###### Default Value + +`false` + +##### draggable? + +```ts +readonly draggable?: Maybe; +``` + +Enable dragging of the column. + +###### Default Value + +`false` + +##### sortDescendingFirst? + +```ts +readonly sortDescendingFirst?: Maybe; +``` + +Sets the column sort order to be descending instead of ascending the first time the column is sorted. + +###### Default Value + +`false` + +##### editorOptions? + +```ts +readonly editorOptions?: Maybe; +``` + +Options for cell editing. + +--- + +### ColumnFrozen + +```ts +type ColumnFrozen = boolean | 'start' | 'end'; +``` + +Whether a column is frozen, and on which edge. + +#### See + +[`column.frozen`](#frozen-1) + +--- + +### ColumnGroup + +Defines a group of columns that share a common header. + +#### Example + +```tsx +import type { ColumnOrColumnGroup } from 'react-data-grid'; + +const columns: readonly ColumnOrColumnGroup[] = [ + { + name: 'Personal Info', + children: [ + { key: 'firstName', name: 'First Name' }, + { key: 'lastName', name: 'Last Name' } + ] + } +]; +``` + +#### See + +[`ColumnOrColumnGroup`](#columnorcolumngroup) + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `R` | - | +| `SR` | `unknown` | + +#### Properties + +##### name + +```ts +readonly name: + | string +| ReactElement>; +``` + +The name of the column group. It will be displayed in the header cell + +##### headerCellClass? + +```ts +readonly headerCellClass?: Maybe; +``` + +##### children + +```ts +readonly children: readonly ColumnOrColumnGroup[]; +``` + +--- + +### ColumnOrColumnGroup + +```ts +type ColumnOrColumnGroup = Column | ColumnGroup; +``` + +Union type representing either a `Column` or a `ColumnGroup`. + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `R` | - | +| `SR` | `unknown` | + +#### See + +[`columns`](#columns) prop on `` + +--- + +### ColumnWidth + +Represents a single column's width. + +#### See + +[`ColumnWidths`](#columnwidths-1) + +#### Properties + +##### type + +```ts +readonly type: "resized" | "measured"; +``` + +`'resized'` if the user resized the column, or `'measured'` if the grid measured it + +##### width + +```ts +readonly width: number; +``` + +The width in pixels + +--- + +### ColumnWidths + +```ts +type ColumnWidths = ReadonlyMap; +``` + +A map of column widths. + +#### See + +[`columnWidths`](#columnwidths) and [`onColumnWidthsChange`](#oncolumnwidthschange) props on `` + +--- + +### DataGridHandle + +Handle type assigned to a grid's `ref` for programmatic grid control. + +#### Example + +```tsx +import { useRef } from 'react'; +import { DataGrid, type DataGridHandle } from 'react-data-grid'; + +function MyGrid() { + const gridRef = useRef(null); + + function scrollToTop() { + gridRef.current?.scrollToCell({ rowIdx: 0 }); + } + + return ; +} +``` + +#### See + +[`ref`](#ref) prop on `` + +#### Properties + +##### element + +```ts +element: HTMLDivElement | null; +``` + +##### scrollToCell + +```ts +scrollToCell: (position: PartialPosition) => void; +``` + +###### Parameters + +| Parameter | Type | +| ---------- | ------------------------------------- | +| `position` | [`PartialPosition`](#partialposition) | + +###### Returns + +`void` + +##### setActivePosition + +```ts +setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +``` + +###### Parameters + +| Parameter | Type | +| ---------- | ------------------------------------------------------- | +| `position` | [`Position`](#position) | +| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | + +###### Returns + +`void` + +--- + +### DefaultColumnOptions + +```ts +type DefaultColumnOptions = Pick< + Column, + | 'renderCell' + | 'renderHeaderCell' + | 'width' + | 'minWidth' + | 'maxWidth' + | 'resizable' + | 'sortable' + | 'draggable' +>; +``` + +Default options applied to all columns. + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `R` | +| `SR` | + +#### See + +[`defaultColumnOptions`](#defaultcolumnoptions) prop on `` + +--- + +### Direction + +```ts +type Direction = 'ltr' | 'rtl'; +``` + +Text direction of the grid. + +#### See + +[`direction`](#direction) prop on `` + +--- + +### FillEvent + +Event object for drag-fill operations. + +#### See + +[`onFill`](#onfill) prop on `` + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `TRow` | + +#### Properties + +##### columnKey + +```ts +columnKey: string; +``` + +##### sourceRow + +```ts +sourceRow: TRow; +``` + +##### targetRow + +```ts +targetRow: TRow; +``` + +--- + +### PositionChangeArgs + +Arguments passed to `onActivePositionChange`. + +#### See + +[`onActivePositionChange`](#onactivepositionchange) prop on `` + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### rowIdx + +```ts +rowIdx: number; +``` + +row index of the active position + +##### row + +```ts +row: TRow | undefined; +``` + +row object of the active position, +undefined if the active position is on a header or summary row + +##### column + +```ts +column: + | CalculatedColumn + | undefined; +``` + +column object of the active position, +undefined if the active position is a row instead of a cell + +--- + +### RenderCellContentProps + +Props passed to custom cell content renderers (`column.renderCell`). + +#### Example + +```tsx +import type { RenderCellContentProps } from 'react-data-grid'; + +function renderCell({ row, column, onRowChange }: RenderCellContentProps) { + return ( +
+ {row[column.key]} + +
+ ); +} +``` + +#### See + +[`column.renderCell`](#rendercell-1), [`renderValue`](#rendervalue) function + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### column + +```ts +column: CalculatedColumn; +``` + +##### row + +```ts +row: TRow; +``` + +##### rowIdx + +```ts +rowIdx: number; +``` + +##### isCellEditable + +```ts +isCellEditable: boolean; +``` + +##### tabIndex + +```ts +tabIndex: number; +``` + +##### onRowChange + +```ts +onRowChange: (row: TRow) => void; +``` + +###### Parameters + +| Parameter | Type | +| --------- | ------ | +| `row` | `TRow` | + +###### Returns + +`void` + +--- + +### RenderCellProps + +Props passed to the cell renderer when using `renderers.renderCell`. + +#### See + +[`renderers.renderCell`](#renderers), [``](#cell) + +#### Extends + +- [`BaseRenderCellProps`](#baserendercellprops)\<`TRow`, `TSummaryRow`\> + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `TRow` | +| `TSummaryRow` | + +#### Properties + +##### onCellMouseDown? + +```ts +onCellMouseDown?: CellMouseEventHandler; +``` + +Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +```tsx +function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + event.preventGridDefault(); + } +} + +; +``` + +###### Inherited from + +`BaseRenderCellProps.onCellMouseDown` + +##### onCellClick? + +```ts +onCellClick?: CellMouseEventHandler; +``` + +Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +This event can be used to open the cell editor on a single click: + +```tsx +function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + args.setActivePosition(true); + } +} + +; +``` + +###### Inherited from + +`BaseRenderCellProps.onCellClick` + +##### onCellDoubleClick? + +```ts +onCellDoubleClick?: CellMouseEventHandler; +``` + +Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +```tsx +function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + event.preventGridDefault(); + } +} + +; +``` + +###### Inherited from + +`BaseRenderCellProps.onCellDoubleClick` + +##### onCellContextMenu? + +```ts +onCellContextMenu?: CellMouseEventHandler; +``` + +Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +```tsx +function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + event.preventDefault(); + // open custom context menu + } +} + +; +``` + +###### Inherited from + +`BaseRenderCellProps.onCellContextMenu` + +##### rowIdx + +```ts +rowIdx: number; +``` + +###### Inherited from + +[`BaseRenderCellProps`](#baserendercellprops).[`rowIdx`](#rowidx-7) + +##### setActivePosition + +```ts +setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +``` + +###### Parameters + +| Parameter | Type | +| ---------- | ------------------------------------------------------- | +| `position` | [`Position`](#position) | +| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | + +###### Returns + +`void` + +###### Inherited from + +[`BaseRenderCellProps`](#baserendercellprops).[`setActivePosition`](#setactiveposition-5) + +##### column + +```ts +column: CalculatedColumn; +``` + +##### row + +```ts +row: TRow; +``` + +##### colSpan + +```ts +colSpan: number | undefined; +``` + +##### isDraggedOver + +```ts +isDraggedOver: boolean; +``` + +##### isCellActive + +```ts +isCellActive: boolean; +``` + +##### onRowChange + +```ts +onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: TRow) => void; +``` + +###### Parameters + +| Parameter | Type | +| --------- | ---------------------------------------------------------------- | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | +| `rowIdx` | `number` | +| `newRow` | `TRow` | + +###### Returns + +`void` + +--- + +### RenderCheckboxProps + +Props for custom checkbox renderers. + +#### See + +[`renderCheckbox`](#rendercheckbox) function, [`renderers.renderCheckbox`](#renderers), [``](#selectcheckbox) + +#### Properties + +##### checked? + +```ts +checked?: boolean; +``` + +Whether the checkbox is checked + +##### indeterminate? + +```ts +indeterminate?: boolean; +``` + +Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected + +##### disabled? + +```ts +disabled?: boolean; +``` + +Whether the checkbox is disabled + +##### onChange + +```ts +onChange: (checked: boolean, shift: boolean) => void; +``` + +Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows + +###### Parameters + +| Parameter | Type | +| --------- | --------- | +| `checked` | `boolean` | +| `shift` | `boolean` | + +###### Returns + +`void` + +##### tabIndex? + +```ts +tabIndex?: number; +``` + +`0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox + +##### aria-label? + +```ts +"aria-label"?: string; +``` + +Accessible label for the checkbox + +##### aria-labelledby? + +```ts +"aria-labelledby"?: string; +``` + +ID of the element that labels the checkbox + +--- + +### RenderEditCellContentProps + +Props passed to custom editors (`column.renderEditCell`). + +#### Example + +```tsx +import type { RenderEditCellContentProps } from 'react-data-grid'; + +function renderEditor({ row, column, onRowChange, onClose }: RenderEditCellContentProps) { + return ( + onRowChange({ ...row, [column.key]: event.target.value })} + onBlur={() => onClose(true)} + /> + ); +} +``` + +#### See + +[`column.renderEditCell`](#rendereditcell), [`renderTextEditor`](#rendertexteditor) function + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### column + +```ts +column: CalculatedColumn; +``` + +##### row + +```ts +row: TRow; +``` + +##### rowIdx + +```ts +rowIdx: number; +``` + +##### onRowChange + +```ts +onRowChange: (row: TRow, commitChanges?: boolean) => void; +``` + +###### Parameters + +| Parameter | Type | +| ---------------- | --------- | +| `row` | `TRow` | +| `commitChanges?` | `boolean` | + +###### Returns + +`void` + +##### onClose + +```ts +onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; +``` + +###### Parameters + +| Parameter | Type | +| ---------------- | --------- | +| `commitChanges?` | `boolean` | +| `shouldFocus?` | `boolean` | + +###### Returns + +`void` + +--- + +### Renderers + +Custom renderer configuration for the grid. + +#### See + +[`renderers`](#renderers) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `TRow` | +| `TSummaryRow` | + +#### Properties + +##### renderCell? + +```ts +readonly renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; +``` + +##### renderCheckbox? + +```ts +readonly renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>; +``` + +##### renderRow? + +```ts +readonly renderRow?: Maybe<(key: Key, props: RenderRowProps) => ReactNode>; +``` + +##### renderSortStatus? + +```ts +readonly renderSortStatus?: Maybe<(props: RenderSortStatusProps) => ReactNode>; +``` + +##### noRowsFallback? + +```ts +readonly noRowsFallback?: ReactNode; +``` + +--- + +### RenderGroupCellContentProps + +Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. + +#### See + +[`column.renderGroupCell`](#rendergroupcell), [`renderToggleGroup`](#rendertogglegroup) function, [``](#togglegroup) + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### groupKey + +```ts +groupKey: unknown; +``` + +##### column + +```ts +column: CalculatedColumn; +``` + +##### row + +```ts +row: GroupRow; +``` + +##### childRows + +```ts +childRows: readonly TRow[]; +``` + +##### isExpanded + +```ts +isExpanded: boolean; +``` + +##### tabIndex + +```ts +tabIndex: number; +``` + +##### toggleGroup + +```ts +toggleGroup: () => void; +``` + +###### Returns + +`void` + +--- + +### RenderHeaderCellContentProps + +Props passed to custom header cell content renderers (`column.renderHeaderCell`). + +#### See + +[`column.renderHeaderCell`](#renderheadercell-2), [`renderHeaderCell`](#renderheadercell) function + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### column + +```ts +column: CalculatedColumn; +``` + +##### sortDirection + +```ts +sortDirection: SortDirection | undefined; +``` + +##### priority + +```ts +priority: number | undefined; +``` + +##### tabIndex + +```ts +tabIndex: number; +``` + +--- + +### RenderRowProps + +Props passed to custom row renderers. + +#### See + +[`renderers.renderRow`](#renderers), [``](#row) + +#### Extends + +- [`BaseRenderRowProps`](#baserenderrowprops)\<`TRow`, `TSummaryRow`\> + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### onCellMouseDown? + +```ts +onCellMouseDown?: CellMouseEventHandler; +``` + +Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +```tsx +function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + event.preventGridDefault(); + } +} + +; +``` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`onCellMouseDown`](#oncellmousedown-3) + +##### onCellClick? + +```ts +onCellClick?: CellMouseEventHandler; +``` + +Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +This event can be used to open the cell editor on a single click: + +```tsx +function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + args.setActivePosition(true); + } +} + +; +``` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`onCellClick`](#oncellclick-3) + +##### onCellDoubleClick? + +```ts +onCellDoubleClick?: CellMouseEventHandler; +``` + +Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +```tsx +function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + event.preventGridDefault(); + } +} + +; +``` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`onCellDoubleClick`](#oncelldoubleclick-3) + +##### onCellContextMenu? + +```ts +onCellContextMenu?: CellMouseEventHandler; +``` + +Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +```tsx +function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + event.preventDefault(); + // open custom context menu + } +} + +; +``` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`onCellContextMenu`](#oncellcontextmenu-3) + +##### setActivePosition + +```ts +setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +``` + +###### Parameters + +| Parameter | Type | +| ---------- | ------------------------------------------------------- | +| `position` | [`Position`](#position) | +| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | + +###### Returns + +`void` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`setActivePosition`](#setactiveposition-6) + +##### iterateOverViewportColumnsForRow + +```ts +iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; +``` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`iterateOverViewportColumnsForRow`](#iterateoverviewportcolumnsforrow-1) + +##### rowIdx + +```ts +rowIdx: number; +``` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`rowIdx`](#rowidx-8) + +##### activeCellIdx + +```ts +activeCellIdx: number | undefined; +``` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`activeCellIdx`](#activecellidx-1) + +##### isRowSelectionDisabled + +```ts +isRowSelectionDisabled: boolean; +``` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`isRowSelectionDisabled`](#isrowselectiondisabled-3) + +##### isRowSelected + +```ts +isRowSelected: boolean; +``` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`isRowSelected`](#isrowselected-3) + +##### gridRowStart + +```ts +gridRowStart: number; +``` + +###### Inherited from + +[`BaseRenderRowProps`](#baserenderrowprops).[`gridRowStart`](#gridrowstart-1) + +##### row + +```ts +row: TRow; +``` + +##### draggedOverCellIdx + +```ts +draggedOverCellIdx: number | undefined; +``` + +##### activeCellEditor + +```ts +activeCellEditor: + | ReactElement, string | JSXElementConstructor> + | undefined; +``` + +##### onRowChange + +```ts +onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: TRow) => void; +``` + +###### Parameters + +| Parameter | Type | +| --------- | ---------------------------------------------------------------- | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | +| `rowIdx` | `number` | +| `newRow` | `TRow` | + +###### Returns + +`void` + +##### rowClass + +```ts +rowClass: Maybe<(row: TRow, rowIdx: number) => Maybe>; +``` + +##### isTreeGrid + +```ts +isTreeGrid: boolean; +``` + +--- + +### RenderSortIconProps + +Props for custom sort icon renderers. + +#### See + +[`renderSortIcon`](#rendersorticon) function + +#### Extended by + +- [`RenderSortStatusProps`](#rendersortstatusprops) + +#### Properties + +##### sortDirection + +```ts +sortDirection: SortDirection | undefined; +``` + +The sort direction of the column, or `undefined` if it is not sorted + +--- + +### RenderSortPriorityProps + +Props for custom sort priority renderers. + +#### See + +[`renderSortPriority`](#rendersortpriority) function + +#### Extended by + +- [`RenderSortStatusProps`](#rendersortstatusprops) + +#### Properties + +##### priority + +```ts +priority: number | undefined; +``` + +The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise + +--- + +### RenderSortStatusProps + +Props for custom sort status renderers. + +#### See + +[`renderers.renderSortStatus`](#renderers) + +#### Extends + +- [`RenderSortIconProps`](#rendersorticonprops) +- [`RenderSortPriorityProps`](#rendersortpriorityprops) + +#### Properties + +--- + +### RenderSummaryCellContentProps + +Props passed to summary cell content renderers (`column.renderSummaryCell`). + +#### See + +[`column.renderSummaryCell`](#rendersummarycell) + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TSummaryRow` | - | +| `TRow` | `unknown` | + +#### Properties + +##### column + +```ts +column: CalculatedColumn; +``` + +##### row + +```ts +row: TSummaryRow; +``` + +##### tabIndex + +```ts +tabIndex: number; +``` + +--- + +### RowHeightArgs + +```ts +type RowHeightArgs = + | { + type: 'ROW'; + row: TRow; + } + | { + type: 'GROUP'; + row: GroupRow; + }; +``` + +Arguments passed to `TreeDataGrid`'s `rowHeight` prop when it is a function. + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `TRow` | + +#### Example + +```tsx +function getRowHeight(args: RowHeightArgs): number { + if (args.type === 'GROUP') { + return 40; + } + return args.row.isLarge ? 60 : 35; +} + + +``` + +#### See + +[`rowHeight`](#rowheight-1) prop on `` + +--- + +### RowsChangeData + +Data provided to the `onRowsChange` callback. + +#### See + +[`onRowsChange`](#onrowschange) prop on `` + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `R` | - | +| `SR` | `unknown` | + +#### Properties + +##### indexes + +```ts +indexes: number[]; +``` + +Indexes of the rows that changed + +##### column + +```ts +column: CalculatedColumn; +``` + +The column of the cells that changed + +--- + +### SelectHeaderRowEvent + +Event object for header row selection changes. + +#### See + +[`useHeaderRowSelection`](#useheaderrowselection) hook + +#### Properties + +##### checked + +```ts +checked: boolean; +``` + +--- + +### SelectRowEvent + +Event object for row selection changes. + +#### See + +[`useRowSelection`](#userowselection) hook + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `TRow` | + +#### Properties + +##### row + +```ts +row: TRow; +``` + +##### checked + +```ts +checked: boolean; +``` + +##### isShiftClick + +```ts +isShiftClick: boolean; +``` + +--- + +### SetActivePositionOptions + +Options for programmatically updating the grid's active position. + +#### See + +[`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) + +#### Properties + +##### enableEditor? + +```ts +enableEditor?: Maybe; +``` + +##### shouldFocus? + +```ts +shouldFocus?: Maybe; +``` + +--- + +### SortColumn + +Describes a sorted column. + +#### See + +[`sortColumns`](#sortcolumns) and [`onSortColumnsChange`](#onsortcolumnschange) props on `` + +#### Properties + +##### columnKey + +```ts +readonly columnKey: string; +``` + +##### direction + +```ts +readonly direction: SortDirection; +``` + +--- + +### SortDirection + +```ts +type SortDirection = 'ASC' | 'DESC'; +``` + +#### See + +[`SortColumn`](#sortcolumn) + +## Internal Types + +### ActiveCellKeyDownArgs + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### mode + +```ts +mode: 'ACTIVE'; +``` + +##### column + +```ts +column: + | CalculatedColumn + | undefined; +``` + +column object of the active position, +undefined if the active position is a row instead of a cell + +##### row + +```ts +row: TRow; +``` + +##### rowIdx + +```ts +rowIdx: number; +``` + +##### setActivePosition + +```ts +setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +``` + +###### Parameters + +| Parameter | Type | +| ---------- | ------------------------------------------------------- | +| `position` | [`Position`](#position) | +| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | + +###### Returns + +`void` + +--- + +### BaseRenderCellProps + +#### Extends + +- [`Omit`](#omit)\<`React.ComponentProps`\<`"div"`\>, `"children"`\> +- `Pick`\<[`DataGridProps`](#datagridprops)\<`TRow`, `TSummaryRow`\>, + \| `"onCellMouseDown"` + \| `"onCellClick"` + \| `"onCellDoubleClick"` + \| `"onCellContextMenu"`\> + +#### Extended by + +- [`RenderCellProps`](#rendercellprops) +- [`BaseRenderRowProps`](#baserenderrowprops) + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### rowIdx + +```ts +rowIdx: number; +``` + +##### setActivePosition + +```ts +setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +``` + +###### Parameters + +| Parameter | Type | +| ---------- | ------------------------------------------------------- | +| `position` | [`Position`](#position) | +| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | + +###### Returns + +`void` + +--- + +### BaseRenderRowProps + +#### Extends + +- [`BaseRenderCellProps`](#baserendercellprops)\<`TRow`, `TSummaryRow`\> + +#### Extended by + +- [`RenderRowProps`](#renderrowprops) + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### onCellMouseDown? + +```ts +onCellMouseDown?: CellMouseEventHandler; +``` + +Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. ```tsx -import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; +function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + event.preventGridDefault(); + } +} + +; +``` + +###### Inherited from + +`BaseRenderCellProps.onCellMouseDown` + +##### onCellClick? + +```ts +onCellClick?: CellMouseEventHandler; +``` + +Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +This event can be used to open the cell editor on a single click: + +```tsx +function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + args.setActivePosition(true); + } +} + +; +``` + +###### Inherited from + +`BaseRenderCellProps.onCellClick` + +##### onCellDoubleClick? + +```ts +onCellDoubleClick?: CellMouseEventHandler; +``` + +Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +```tsx +function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + event.preventGridDefault(); + } +} + +; +``` + +###### Inherited from + +`BaseRenderCellProps.onCellDoubleClick` + +##### onCellContextMenu? + +```ts +onCellContextMenu?: CellMouseEventHandler; +``` + +Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. + +```tsx +function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + event.preventDefault(); + // open custom context menu + } +} + +; +``` + +###### Inherited from + +`BaseRenderCellProps.onCellContextMenu` + +##### setActivePosition + +```ts +setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +``` + +###### Parameters + +| Parameter | Type | +| ---------- | ------------------------------------------------------- | +| `position` | [`Position`](#position) | +| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | + +###### Returns + +`void` + +###### Inherited from + +[`BaseRenderCellProps`](#baserendercellprops).[`setActivePosition`](#setactiveposition-5) + +##### iterateOverViewportColumnsForRow + +```ts +iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; +``` + +##### rowIdx + +```ts +rowIdx: number; +``` + +###### Overrides + +[`BaseRenderCellProps`](#baserendercellprops).[`rowIdx`](#rowidx-7) + +##### activeCellIdx + +```ts +activeCellIdx: number | undefined; +``` + +##### isRowSelectionDisabled + +```ts +isRowSelectionDisabled: boolean; +``` + +##### isRowSelected + +```ts +isRowSelected: boolean; +``` + +##### gridRowStart + +```ts +gridRowStart: number; +``` + +--- + +### CellClipboardEvent + +```ts +type CellClipboardEvent = React.ClipboardEvent; +``` + +Type alias for `React.ClipboardEvent`. Used for copy and paste events. This helper type is not exported; the shape is shown for reference. + +#### See + +[`onCellCopy`](#oncellcopy) and [`onCellPaste`](#oncellpaste) props on `` + +--- + +### CellCopyPasteArgs + +#### Type Parameters + +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | + +#### Properties + +##### column + +```ts +column: CalculatedColumn; +``` + +##### row + +```ts +row: TRow; +``` + +--- + +### CellEvent + +```ts +type CellEvent> = E & object; +``` + +Adds grid-specific methods to a React event. This helper type is not exported; the shape is shown for reference. + +#### Type Parameters + +| Type Parameter | +| -------------------------------------------------------- | +| `E` _extends_ `React.SyntheticEvent`\<`HTMLDivElement`\> | + +#### Type Declaration + +##### preventGridDefault + +```ts +preventGridDefault: () => void; +``` + +Prevents the default grid behavior for this event + +###### Returns + +`void` + +##### isGridDefaultPrevented + +```ts +isGridDefaultPrevented: () => boolean; +``` + +Returns whether `preventGridDefault` was called + +###### Returns + +`boolean` + +#### See + +[`CellMouseEvent`](#cellmouseevent), [`CellKeyboardEvent`](#cellkeyboardevent) + +--- + +### CellMouseEventHandler + +```ts +type CellMouseEventHandler = Maybe< + (args: CellMouseArgs, event: CellMouseEvent) => void +>; +``` + +Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `R` | +| `SR` | + +--- + +### ColumnEditorOptions + +Options for cell editing. -function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { - console.log('Clicked cell at row', args.rowIdx, 'column', args.column.key); - args.setActivePosition(true); // Focus and start editing -} +#### Properties + +##### displayCellContent? + +```ts +readonly displayCellContent?: Maybe; ``` -**See also:** [`onCellMouseDown`](#oncellmousedown-cellmouseeventhandlerr-sr), [`onCellClick`](#oncellclick-cellmouseeventhandlerr-sr), [`onCellDoubleClick`](#oncelldoubleclick-cellmouseeventhandlerr-sr), and [`onCellContextMenu`](#oncellcontextmenu-cellmouseeventhandlerr-sr) props on `` +Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. +By default, the cell content is not rendered when the edit cell is open. + +###### Default Value -#### `CellMouseEventHandler` (internal) +`false` -Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. +##### commitOnOutsideClick? -```tsx -type CellMouseEventHandler = Maybe< - (args: CellMouseArgs, event: CellMouseEvent) => void ->; +```ts +readonly commitOnOutsideClick?: Maybe; ``` -#### `CellEvent` (internal) +Commit changes when clicking outside the cell. -Adds grid-specific methods to a React event. This helper type is not exported; the shape is shown for reference. +###### Default Value -```tsx -type CellEvent> = E & { - /** Prevents the default grid behavior for this event */ - preventGridDefault: () => void; - /** Returns whether `preventGridDefault` was called */ - isGridDefaultPrevented: () => boolean; -}; +`true` + +##### closeOnExternalRowChange? + +```ts +readonly closeOnExternalRowChange?: Maybe; ``` -**See also:** [`CellMouseEvent`](#cellmouseevent), [`CellKeyboardEvent`](#cellkeyboardevent) +Close the editor when the row value changes externally. -#### `CellMouseEvent` +###### Default Value -Extends `React.MouseEvent` with grid-specific methods. +`true` -```tsx -type CellMouseEvent = CellEvent>; -``` +--- -**Example:** +### EditCellKeyDownArgs -```tsx -import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; +#### Type Parameters -function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'actions') { - event.preventGridDefault(); // Prevent cell focus - } -} -``` +| Type Parameter | Default type | +| -------------- | ------------ | +| `TRow` | - | +| `TSummaryRow` | `unknown` | -**See also:** [`onCellMouseDown`](#oncellmousedown-cellmouseeventhandlerr-sr), [`onCellClick`](#oncellclick-cellmouseeventhandlerr-sr), [`onCellDoubleClick`](#oncelldoubleclick-cellmouseeventhandlerr-sr), and [`onCellContextMenu`](#oncellcontextmenu-cellmouseeventhandlerr-sr) props on `` +#### Properties -#### `CellKeyDownArgs` +##### mode -Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. +```ts +mode: 'EDIT'; +``` -**ACTIVE mode:** +##### column -```tsx -interface ActiveCellKeyDownArgs { - mode: 'ACTIVE'; - /** - * column object of the active position, - * undefined if the active position is a row instead of a cell - */ - column: CalculatedColumn | undefined; - row: TRow; - rowIdx: number; - setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -} +```ts +column: CalculatedColumn; ``` -**EDIT mode:** +##### row -```tsx -interface EditCellKeyDownArgs { - mode: 'EDIT'; - column: CalculatedColumn; - row: TRow; - rowIdx: number; - navigate: () => void; - onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; -} +```ts +row: TRow; ``` -**Example:** +##### rowIdx -```tsx -import type { CellKeyboardEvent, CellKeyDownArgs } from 'react-data-grid'; +```ts +rowIdx: number; +``` -function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { - if (args.mode === 'EDIT' && event.key === 'Escape') { - args.onClose(false); // Close without committing - event.preventGridDefault(); - } -} +##### navigate + +```ts +navigate: () => void; ``` -**See also:** [`onCellKeyDown`](#oncellkeydown-maybeargs-cellkeydownargsr-sr-event-cellkeyboardevent--void) prop on `` +###### Returns -#### `CellKeyboardEvent` +`void` -Extends `React.KeyboardEvent` with grid-specific methods. +##### onClose -```tsx -type CellKeyboardEvent = CellEvent>; +```ts +onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; ``` -**See also:** [`onCellKeyDown`](#oncellkeydown-maybeargs-cellkeydownargsr-sr-event-cellkeyboardevent--void) prop on `` +###### Parameters -#### `CellClipboardEvent` (internal) +| Parameter | Type | +| ---------------- | --------- | +| `commitChanges?` | `boolean` | +| `shouldFocus?` | `boolean` | -Type alias for `React.ClipboardEvent`. Used for copy and paste events. This helper type is not exported; the shape is shown for reference. +###### Returns -```tsx -type CellClipboardEvent = React.ClipboardEvent; -``` +`void` -**See also:** [`onCellCopy`](#oncellcopy-maybeargs-cellcopyargsr-sr-event-cellclipboardevent--void) and [`onCellPaste`](#oncellpaste-maybeargs-cellpasteargsr-sr-event-cellclipboardevent--r) props on `` +--- -#### `CellCopyArgs` +### EditCellProps -Arguments passed to `onCellCopy`. +#### Extends -```tsx -interface CellCopyArgs { - column: CalculatedColumn; - row: TRow; -} -``` +- `Pick`\<[`RenderCellProps`](#rendercellprops)\<`R`, `SR`\>, `"column"` \| `"colSpan"` \| `"row"` \| `"rowIdx"`\> -**See also:** [`onCellCopy`](#oncellcopy-maybeargs-cellcopyargsr-sr-event-cellclipboardevent--void) prop on `` +#### Type Parameters -#### `CellPasteArgs` +| Type Parameter | +| -------------- | +| `R` | +| `SR` | -Arguments passed to `onCellPaste`. +#### Properties -```tsx -interface CellPasteArgs { - column: CalculatedColumn; - row: TRow; -} +##### onRowChange + +```ts +onRowChange: (row: R, commitChanges: boolean, shouldFocus: boolean) => void; ``` -**See also:** [`onCellPaste`](#oncellpaste-maybeargs-cellpasteargsr-sr-event-cellclipboardevent--r) prop on `` +###### Parameters -#### `PositionChangeArgs` +| Parameter | Type | +| --------------- | --------- | +| `row` | `R` | +| `commitChanges` | `boolean` | +| `shouldFocus` | `boolean` | -Arguments passed to `onActivePositionChange`. +###### Returns -```tsx -interface PositionChangeArgs { - /** row index of the active position */ - rowIdx: number; - /** - * row object of the active position, - * undefined if the active position is on a header or summary row - */ - row: TRow | undefined; - /** - * column object of the active position, - * undefined if the active position is a row instead of a cell - */ - column: CalculatedColumn | undefined; -} +`void` + +##### closeEditor + +```ts +closeEditor: (shouldFocus: boolean) => void; ``` -**See also:** [`onActivePositionChange`](#onactivepositionchange-maybeargs-positionchangeargsr-sr--void) prop on `` +###### Parameters -#### `ColSpanArgs` +| Parameter | Type | +| ------------- | --------- | +| `shouldFocus` | `boolean` | -Arguments passed to the `colSpan` function. +###### Returns -```tsx -type ColSpanArgs = - | { readonly type: 'HEADER' } - | { readonly type: 'ROW'; readonly row: TRow } - | { readonly type: 'SUMMARY'; readonly row: TSummaryRow }; +`void` + +##### navigate + +```ts +navigate: (event: KeyboardEvent) => void; ``` -**Example:** +###### Parameters -```tsx -import type { Column } from 'react-data-grid'; +| Parameter | Type | +| --------- | ----------------------------------- | +| `event` | `KeyboardEvent`\<`HTMLDivElement`\> | -const columns: readonly Column[] = [ - { - key: 'title', - name: 'Title', - colSpan(args) { - if (args.type === 'ROW' && args.row.isFullWidth) { - return 3; // Span 3 columns - } - return undefined; - } - } -]; +###### Returns + +`void` + +##### onKeyDown + +```ts +onKeyDown: Maybe<(args: EditCellKeyDownArgs, event: CellKeyboardEvent) => void>; ``` -**See also:** [`column.colSpan`](#colspan-maybeargs-colspanargstrow-tsummaryrow--maybenumber) +--- -#### `RowHeightArgs` +### GroupRow -Arguments passed to `TreeDataGrid`'s `rowHeight` prop when it is a function. +Represents a group row in `TreeDataGrid`. This helper type is not exported; the shape is shown for reference. -```tsx -type RowHeightArgs = { type: 'ROW'; row: TRow } | { type: 'GROUP'; row: GroupRow }; -``` +#### See -**Example:** +[`RenderGroupCellContentProps`](#rendergroupcellcontentprops), [`RowHeightArgs`](#rowheightargs), [``](#treedatagrid) -```tsx -function getRowHeight(args: RowHeightArgs): number { - if (args.type === 'GROUP') { - return 40; - } - return args.row.isLarge ? 60 : 35; -} +#### Type Parameters - -``` +| Type Parameter | +| -------------- | +| `TRow` | -**See also:** [`rowHeight`](#rowheight-maybenumber--args-rowheightargsr--number) prop on `` +#### Properties -#### `SortColumn` +##### childRows -Describes a sorted column. +```ts +readonly childRows: readonly TRow[]; +``` -```tsx -interface SortColumn { - readonly columnKey: string; - readonly direction: SortDirection; -} +##### id + +```ts +readonly id: string; ``` -**See also:** [`sortColumns`](#sortcolumns-maybereadonly-sortcolumn) and [`onSortColumnsChange`](#onsortcolumnschange-maybesortcolumns-sortcolumn--void) props on `` +##### parentId -#### `SortDirection` +```ts +readonly parentId: unknown; +``` -```tsx -type SortDirection = 'ASC' | 'DESC'; +##### groupKey + +```ts +readonly groupKey: unknown; ``` -**See also:** [`SortColumn`](#sortcolumn) +##### isExpanded -#### `RowsChangeData` +```ts +readonly isExpanded: boolean; +``` -Data provided to the `onRowsChange` callback. +##### level -```tsx -interface RowsChangeData { - /** Indexes of the rows that changed */ - indexes: number[]; - /** The column of the cells that changed */ - column: CalculatedColumn; -} +```ts +readonly level: number; ``` -**See also:** [`onRowsChange`](#onrowschange-mayberows-r-data-rowschangedatar-sr--void) prop on `` +##### posInSet -#### `SelectRowEvent` +```ts +readonly posInSet: number; +``` -Event object for row selection changes. +##### setSize -```tsx -interface SelectRowEvent { - row: TRow; - checked: boolean; - isShiftClick: boolean; -} +```ts +readonly setSize: number; ``` -**See also:** [`useRowSelection`](#userowselection) hook +##### startRowIndex -#### `SelectHeaderRowEvent` +```ts +readonly startRowIndex: number; +``` -Event object for header row selection changes. +--- -```tsx -interface SelectHeaderRowEvent { - checked: boolean; -} +### IterateOverViewportColumnsForRow + +```ts +type IterateOverViewportColumnsForRow = ( + activeIdx: number | undefined, + args?: ColSpanArgs +) => IteratorObject>; ``` -**See also:** [`useHeaderRowSelection`](#useheaderrowselection) hook +#### Type Parameters -#### `FillEvent` +| Type Parameter | +| -------------- | +| `TRow` | +| `TSummaryRow` | -Event object for drag-fill operations. +#### Parameters -```tsx -interface FillEvent { - columnKey: string; - sourceRow: TRow; - targetRow: TRow; -} +| Parameter | Type | +| ----------- | ------------------------------------------------------ | +| `activeIdx` | `number` \| `undefined` | +| `args?` | [`ColSpanArgs`](#colspanargs)\<`TRow`, `TSummaryRow`\> | + +#### Returns + +`IteratorObject`\<[`ViewportColumnWithColSpan`](#viewportcolumnwithcolspan)\<`TRow`, `TSummaryRow`\>\> + +--- + +### Maybe + +```ts +type Maybe = T | undefined | null; ``` -**See also:** [`onFill`](#onfill-maybeevent-filleventr--r) prop on `` +Utility type for optional values. This helper type is not exported; the shape is shown for reference. -#### `DataGridHandle` +#### Type Parameters -Handle type assigned to a grid's `ref` for programmatic grid control. +| Type Parameter | +| -------------- | +| `T` | -```tsx -interface DataGridHandle { - element: HTMLDivElement | null; - scrollToCell: (position: PartialPosition) => void; - setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -} +--- + +### Omit + +```ts +type Omit = Pick>; ``` -**Example:** +#### Type Parameters -```tsx -import { useRef } from 'react'; -import { DataGrid, type DataGridHandle } from 'react-data-grid'; +| Type Parameter | +| ----------------------- | +| `T` | +| `K` _extends_ keyof `T` | -function MyGrid() { - const gridRef = useRef(null); +--- - function scrollToTop() { - gridRef.current?.scrollToCell({ rowIdx: 0 }); - } +### PartialPosition - return ; -} +Position for scrolling to a cell. Both fields are optional: omit `idx` to scroll to a row, or omit `rowIdx` to scroll to a column. This helper type is not exported; the shape is shown for reference. + +#### See + +[`DataGridHandle`](#datagridhandle) + +#### Properties + +##### idx? + +```ts +readonly idx?: Maybe; +``` + +##### rowIdx? + +```ts +readonly rowIdx?: Maybe; ``` -**See also:** [`ref`](#ref-maybereactrefdatagridhandle) prop on `` +--- -#### `Position` (internal) +### Position Represents a cell position in the grid. This helper type is not exported; the shape is shown for reference. -```tsx -interface Position { - /** Column index, or `-1` for the whole row in `TreeDataGrid` */ - readonly idx: number; - /** Row index: `0` is the first row, header rows and top summary rows have negative indexes, and bottom summary rows come after the last row */ - readonly rowIdx: number; -} +#### See + +[`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) + +#### Properties + +##### idx + +```ts +readonly idx: number; ``` -**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargstrow-tsummaryrow) +Column index, or `-1` for the whole row in `TreeDataGrid` -#### `PartialPosition` (internal) +##### rowIdx -Position for scrolling to a cell. Both fields are optional: omit `idx` to scroll to a row, or omit `rowIdx` to scroll to a column. This helper type is not exported; the shape is shown for reference. +```ts +readonly rowIdx: number; +``` -```tsx -interface PartialPosition { - readonly idx?: Maybe; - readonly rowIdx?: Maybe; -} +Row index: `0` is the first row, header rows and top summary rows have negative indexes, and bottom summary rows come after the last row + +--- + +### SelectCheckboxProps + +#### Extends + +- [`SharedInputProps`](#sharedinputprops) + +#### Properties + +##### value + +```ts +value: boolean; ``` -**See also:** [`DataGridHandle`](#datagridhandle) +Whether the checkbox is checked -#### `SetActivePositionOptions` +##### indeterminate? -Options for programmatically updating the grid's active position. +```ts +indeterminate?: boolean; +``` -```tsx -interface SetActivePositionOptions { - enableEditor?: Maybe; - shouldFocus?: Maybe; -} +Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected + +###### Inherited from + +[`RenderCheckboxProps`](#rendercheckboxprops).[`indeterminate`](#indeterminate) + +##### disabled? + +```ts +disabled?: boolean; ``` -**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargstrow-tsummaryrow) +Whether the checkbox is disabled -#### `ColumnWidths` +###### Inherited from -A map of column widths. +[`RenderCheckboxProps`](#rendercheckboxprops).[`disabled`](#disabled) -```tsx -type ColumnWidths = ReadonlyMap; +##### onChange + +```ts +onChange: (checked: boolean, shift: boolean) => void; ``` -**See also:** [`columnWidths`](#columnwidths-maybecolumnwidths) and [`onColumnWidthsChange`](#oncolumnwidthschange-maybecolumnwidths-columnwidths--void) props on `` +Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows -#### `ColumnWidth` +###### Parameters -Represents a single column's width. +| Parameter | Type | +| --------- | --------- | +| `checked` | `boolean` | +| `shift` | `boolean` | -```tsx -interface ColumnWidth { - /** `'resized'` if the user resized the column, or `'measured'` if the grid measured it */ - readonly type: 'resized' | 'measured'; - /** The width in pixels */ - readonly width: number; -} +###### Returns + +`void` + +###### Inherited from + +[`RenderCheckboxProps`](#rendercheckboxprops).[`onChange`](#onchange) + +##### tabIndex? + +```ts +tabIndex?: number; ``` -**See also:** [`ColumnWidths`](#columnwidths) +`0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox -#### `Direction` +###### Inherited from -Text direction of the grid. +[`RenderCheckboxProps`](#rendercheckboxprops).[`tabIndex`](#tabindex-1) -```tsx -type Direction = 'ltr' | 'rtl'; +##### aria-label? + +```ts +"aria-label"?: string; ``` -**See also:** [`direction`](#direction-maybeltr--rtl) prop on `` +Accessible label for the checkbox -#### `GroupRow` (internal) +###### Inherited from -Represents a group row in `TreeDataGrid`. This helper type is not exported; the shape is shown for reference. +[`RenderCheckboxProps`](#rendercheckboxprops).[`aria-label`](#aria-label-1) -```tsx -interface GroupRow { - readonly childRows: readonly TRow[]; - readonly id: string; - readonly parentId: unknown; - readonly groupKey: unknown; - readonly isExpanded: boolean; - readonly level: number; - readonly posInSet: number; - readonly setSize: number; - readonly startRowIndex: number; -} +##### aria-labelledby? + +```ts +"aria-labelledby"?: string; ``` -**See also:** [`RenderGroupCellContentProps`](#rendergroupcellcontentpropstrow-tsummaryrow), [`RowHeightArgs`](#rowheightargstrow), [``](#treedatagrid-) +ID of the element that labels the checkbox -#### `Maybe` (internal) +###### Inherited from -Utility type for optional values. This helper type is not exported; the shape is shown for reference. +[`RenderCheckboxProps`](#rendercheckboxprops).[`aria-labelledby`](#aria-labelledby-1) -```tsx -type Maybe = T | undefined | null; +--- + +### SharedInputProps + +```ts +type SharedInputProps = Pick< + RenderCheckboxProps, + 'disabled' | 'tabIndex' | 'aria-label' | 'aria-labelledby' | 'indeterminate' | 'onChange' +>; ``` -### Generics +--- -- `R`, `TRow`: Row type -- `SR`, `TSummaryRow`: Summary row type -- `K`: Row key type +### ViewportColumnWithColSpan + +```ts +type ViewportColumnWithColSpan = [ + column: CalculatedColumn, + isCellActive: boolean, + colSpan: number | undefined +]; +``` + +#### Type Parameters + +| Type Parameter | +| -------------- | +| `TRow` | +| `TSummaryRow` | + + [ci-badge]: https://github.com/Comcast/react-data-grid/actions/workflows/ci.yml/badge.svg [ci-url]: https://github.com/Comcast/react-data-grid/actions/workflows/ci.yml diff --git a/package-lock.json b/package-lock.json index 9caa3b90e0..48ebfb0a75 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "@types/node": "^26.0.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", + "@typescript/typescript6": "^6.0.2", "@vitejs/plugin-react": "^6.1.1", "@vitest/browser-playwright": "5.0.5", "@vitest/coverage-istanbul": "5.0.5", @@ -29,6 +30,9 @@ "publint": "^0.3.25", "react": "^19.3.0", "react-dom": "^19.3.0", + "typedoc": "^0.28.20", + "typedoc-plugin-markdown": "^4.14.1", + "typedoc-plugin-missing-exports": "^4.1.4", "typescript": "beta", "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0", "vite-plus": "1.3.0", @@ -471,6 +475,20 @@ "npm": ">=10" } }, + "node_modules/@gerrit0/mini-shiki": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@gerrit0/mini-shiki/-/mini-shiki-3.23.0.tgz", + "integrity": "sha512-bEMORlG0cqdjVyCEuU0cDQbORWX+kYCeo0kV1lbxF5bt4r7SID2l9bqsxJEM0zndaxpOUT7riCyIVEuqq/Ynxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/engine-oniguruma": "^3.23.0", + "@shikijs/langs": "^3.23.0", + "@shikijs/themes": "^3.23.0", + "@shikijs/types": "^3.23.0", + "@shikijs/vscode-textmate": "^10.0.2" + } + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", @@ -2097,6 +2115,55 @@ "dev": true, "license": "MIT" }, + "node_modules/@shikijs/engine-oniguruma": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.23.0.tgz", + "integrity": "sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.23.0", + "@shikijs/vscode-textmate": "^10.0.2" + } + }, + "node_modules/@shikijs/langs": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.23.0.tgz", + "integrity": "sha512-2Ep4W3Re5aB1/62RSYQInK9mM3HsLeB91cHqznAJMuylqjzNVAVCMnNWRHFtcNHXsoNRayP9z1qj4Sq3nMqYXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.23.0" + } + }, + "node_modules/@shikijs/themes": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.23.0.tgz", + "integrity": "sha512-5qySYa1ZgAT18HR/ypENL9cUSGOeI2x+4IvYJu4JgVJdizn6kG4ia5Q1jDEOi7gTbN4RbuYtmHh0W3eccOrjMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.23.0" + } + }, + "node_modules/@shikijs/types": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.23.0.tgz", + "integrity": "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, + "node_modules/@shikijs/vscode-textmate": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.1.0.tgz", + "integrity": "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@tanstack/history": { "version": "1.162.5", "resolved": "https://registry.npmjs.org/@tanstack/history/-/history-1.162.5.tgz", @@ -2494,6 +2561,21 @@ "dev": true, "license": "MIT" }, + "node_modules/@typescript/old": { + "name": "typescript", + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.1.0-beta", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.1.0-beta.tgz", @@ -2851,6 +2933,19 @@ "node": ">=16.20.0" } }, + "node_modules/@typescript/typescript6": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript6/-/typescript6-6.0.2.tgz", + "integrity": "sha512-mbCddXd+jm7hfx7w2YU64/Av4/NqqeG3GoRZgxPcgoTxYjhrcfJRw9ULch71SS4G+Q3bOXFhRvPqjguN0Hyp5w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@typescript/old": "npm:typescript@^6" + }, + "bin": { + "tsc6": "bin/tsc6" + } + }, "node_modules/@vitejs/plugin-react": { "version": "6.1.2", "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz", @@ -3814,6 +3909,13 @@ "node": ">=14" } }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, "node_modules/aria-query": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", @@ -4249,6 +4351,19 @@ "node": ">=14" } }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-module-lexer": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", @@ -5148,6 +5263,26 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/linkify-it": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.2.tgz", + "integrity": "sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^2.0.0" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -5185,6 +5320,13 @@ "yallist": "^3.0.2" } }, + "node_modules/lunr": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz", + "integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==", + "dev": true, + "license": "MIT" + }, "node_modules/lz-string": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", @@ -5217,6 +5359,34 @@ "source-map-js": "^1.2.1" } }, + "node_modules/markdown-it": { + "version": "14.3.3", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.3.3.tgz", + "integrity": "sha512-L//tDAkjTjJCU6pBUSBTgs3Kg4InVaZuUZog/b6V12UKhcDQ7S78877ibbCanRExwPuYP1CZD7Gd2dxSy1GXRg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1", + "entities": "^4.5.0", + "linkify-it": "^5.0.2", + "mdurl": "^2.0.0", + "punycode.js": "^2.3.1", + "uc.micro": "^2.1.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, "node_modules/markdown-table": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz", @@ -5495,6 +5665,13 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/mdurl": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", + "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", + "dev": true, + "license": "MIT" + }, "node_modules/micromark": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", @@ -6665,6 +6842,16 @@ "node": ">=6" } }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/qified": { "version": "0.10.1", "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz", @@ -7015,6 +7202,53 @@ "node": ">= 0.8.0" } }, + "node_modules/typedoc": { + "version": "0.28.20", + "resolved": "https://registry.npmjs.org/typedoc/-/typedoc-0.28.20.tgz", + "integrity": "sha512-uSKqkh8Cr48vllnEy+jdaAgOeR6Y+QCBW7usgUsKj7gJEfR7stw9U/fE49LBnj2tPRKPY0c0EBJSWe9Appmplg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@gerrit0/mini-shiki": "^3.23.0", + "lunr": "^2.3.9", + "markdown-it": "^14.3.0", + "minimatch": "^10.2.5", + "yaml": "^2.9.0" + }, + "bin": { + "typedoc": "bin/typedoc" + }, + "engines": { + "node": ">= 18", + "pnpm": ">= 10" + }, + "peerDependencies": { + "typescript": "5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x || 5.7.x || 5.8.x || 5.9.x || 6.0.x" + } + }, + "node_modules/typedoc-plugin-markdown": { + "version": "4.14.1", + "resolved": "https://registry.npmjs.org/typedoc-plugin-markdown/-/typedoc-plugin-markdown-4.14.1.tgz", + "integrity": "sha512-24XX0oqyBsjBIBNoSH4wbgQkouci/CmgmO1ZBSaVkrcflqXFL2PQ5zFOpkz+Ewow5xQ3q2You+wrcmilNepRKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "typedoc": "0.28.x" + } + }, + "node_modules/typedoc-plugin-missing-exports": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/typedoc-plugin-missing-exports/-/typedoc-plugin-missing-exports-4.1.4.tgz", + "integrity": "sha512-tIay6z6MRb/4+mfWgKNPR6qEM5rz9S8rTiz0JWmSb/66A6AlZIl9q+1lAFygj4n8GHH1fsqKYQNt9JbNcuE0Uw==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "typedoc": "^0.28.1" + } + }, "node_modules/typescript": { "version": "7.1.0-beta", "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.1.0-beta.tgz", @@ -7051,6 +7285,13 @@ "@typescript/typescript-win32-x64": "7.1.0-beta" } }, + "node_modules/uc.micro": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", + "dev": true, + "license": "MIT" + }, "node_modules/undici-types": { "version": "8.9.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", @@ -7632,6 +7873,22 @@ "dev": true, "license": "ISC" }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index 2dfad52fb6..5e713c8123 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "@types/node": "^26.0.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", + "@typescript/typescript6": "^6.0.2", "@vitejs/plugin-react": "^6.1.1", "@vitest/browser-playwright": "5.0.5", "@vitest/coverage-istanbul": "5.0.5", @@ -50,6 +51,9 @@ "publint": "^0.3.25", "react": "^19.3.0", "react-dom": "^19.3.0", + "typedoc": "^0.28.20", + "typedoc-plugin-markdown": "^4.14.1", + "typedoc-plugin-missing-exports": "^4.1.4", "typescript": "beta", "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0", "vite-plus": "1.3.0", @@ -62,6 +66,9 @@ }, "overrides": { "oxc-transform-react": "$oxc-transform-react", + "typedoc": { + "typescript": "$typescript" + }, "typescript": "$typescript", "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0", "vitest": "5.0.5" diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts new file mode 100644 index 0000000000..398c283d5f --- /dev/null +++ b/scripts/generateApiDocs.ts @@ -0,0 +1,277 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import { registerHooks } from 'node:module'; +import type { SomeType } from 'typedoc'; + +// TODO: remove when TypeDoc supports TypeScript 7 +// TypeDoc relies on the TypeScript API, which TypeScript 7 does not provide yet, +// so TypeDoc's `typescript` imports resolve to TypeScript 6 instead +registerHooks({ + resolve(specifier, context, nextResolve) { + return nextResolve(specifier === 'typescript' ? '@typescript/typescript6' : specifier, context); + } +}); + +const { + Application, + Context, + Converter, + DeclarationReflection, + ParameterReflection, + ReferenceType, + ReflectionGroup, + ReflectionKind, + SignatureReflection, + TSConfigReader, + Type, + TypeDocReader, + TypeParameterReflection +} = await import('typedoc'); + +const readmePath = 'README.md'; +const startMarker = ''; +const endMarker = ''; + +const app = await Application.bootstrapWithPlugins({}, [new TypeDocReader(), new TSConfigReader()]); + +// TODO: remove when TypeDoc supports TypeScript 7 +// TypeDoc identifies TypeScript's lib types, like `NoInfer`, by their package name, +// which it derives from the path of TypeScript 6: `node_modules/@typescript/old` +const { createSymbolReference } = Context.prototype; +Context.prototype.createSymbolReference = function (...args) { + const reference = createSymbolReference.apply(this, args); + if (reference.package === '@typescript/old') { + reference.package = 'typescript'; + } + return reference; +}; + +// collect the public exports before typedoc-plugin-missing-exports adds the internal types, +// its listener has a priority of 1e9 +const publicNames = new Set(); +app.converter.on( + Converter.EVENT_RESOLVE_BEGIN, + ({ project }) => { + for (const child of project.children ?? []) { + publicNames.add(child.name); + } + }, + Number.POSITIVE_INFINITY +); + +// `NoInfer` only affects type inference, show the type it wraps instead +app.converter.on(Converter.EVENT_RESOLVE_END, ({ project }) => { + for (const reflection of Object.values(project.reflections)) { + if ( + (reflection instanceof DeclarationReflection || + reflection instanceof ParameterReflection || + reflection instanceof SignatureReflection || + reflection instanceof TypeParameterReflection) && + reflection.type !== undefined + ) { + reflection.type = unwrapNoInfer(reflection.type); + } + + if (reflection instanceof TypeParameterReflection && reflection.default !== undefined) { + reflection.default = unwrapNoInfer(reflection.default); + } + + // the default values of inferred object types, like the return types of the hooks, + // are implementation details + if ( + reflection instanceof DeclarationReflection && + reflection.parent?.kindOf(ReflectionKind.TypeLiteral) === true + ) { + delete reflection.defaultValue; + } + } +}); + +const project = await app.convert(); + +if (project === undefined) { + throw new Error('TypeDoc failed to convert the project'); +} + +app.validate(project); + +if (app.logger.hasErrors() || app.logger.hasWarnings()) { + throw new Error('TypeDoc reported errors or warnings'); +} + +// public exports must be in one of the sections of `groupOrder`, set with a `@group` tag, +// the remaining groups only contain the types that are referenced by the public API but not exported +const sections = new Set(app.options.getValue('groupOrder').filter((title) => title !== '*')); +const internalGroup = new ReflectionGroup('Internal Types', project); +const publicGroups = (project.groups ?? []).filter((group) => { + if (sections.has(group.title)) return true; + + for (const child of group.children) { + if (publicNames.has(child.name)) { + throw new Error( + `${child.name} must have a @group tag with one of: ${[...sections].join(', ')}` + ); + } + } + + internalGroup.children.push(...group.children); + return false; +}); +internalGroup.children.sort((a, b) => a.name.localeCompare(b.name)); +project.groups = [...publicGroups, internalGroup]; + +// only list the members that are inherited from internal types, +// the members inherited from public types are listed in their own section +for (const reflection of project.getReflectionsByKind(ReflectionKind.Interface)) { + if (!(reflection instanceof DeclarationReflection)) continue; + + // e.g. `extends Column` or `extends Omit` + const publicBaseTypes = new Set(); + for (const type of reflection.extendedTypes ?? []) { + if (!(type instanceof ReferenceType)) continue; + const [typeArgument] = type.typeArguments ?? []; + if ( + publicNames.has(type.name) || + ((type.name === 'Omit' || type.name === 'Pick') && + typeArgument instanceof ReferenceType && + publicNames.has(typeArgument.name)) + ) { + publicBaseTypes.add(type.name); + } + } + + const membersInheritedFromPublicTypes = + reflection.children?.filter((child) => { + const baseType = child.inheritedFrom?.name.split('.')[0]; + return baseType !== undefined && publicBaseTypes.has(baseType); + }) ?? []; + + for (const child of membersInheritedFromPublicTypes) { + project.removeReflection(child); + } + + // `removeReflection` doesn't remove the members from the groups that are rendered + const remainingMembers = new Set(reflection.children); + for (const group of reflection.groups ?? []) { + group.children = group.children.filter((child) => remainingMembers.has(child)); + } +} + +const outputDirectory = app.options.getValue('out'); +await app.generateOutputs(project); + +const api = await readFile(`${outputDirectory}/README.md`, 'utf8'); +const readme = await readFile(readmePath, 'utf8'); + +const startIndex = readme.indexOf(startMarker); +const endIndex = readme.indexOf(endMarker); + +if (startIndex === -1 || endIndex < startIndex) { + throw new Error(`${readmePath} must contain ${startMarker} followed by ${endMarker}`); +} + +const before = readme.slice(0, startIndex + startMarker.length); +const after = readme.slice(endIndex); + +await writeFile(readmePath, `${before}\n\n${replaceAnchors(api.trim(), before)}\n\n${after}`); + +// typedoc-plugin-markdown adds an HTML anchor before each heading and links to it, +// replace them with the anchors GitHub generates for the headings, +// which are numbered across the whole README, starting with the headings before the API reference +function replaceAnchors(api: string, precedingMarkdown: string) { + const slugCounts = new Map(); + function slug(heading: string) { + const base = heading + .replaceAll(/\[([^\]]*)\]\([^)]*\)/g, '$1') + .replaceAll(/\\(.)/g, '$1') + .replaceAll('`', '') + .toLowerCase() + .replaceAll(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, '') + .replaceAll(' ', '-'); + const count = slugCounts.get(base) ?? 0; + slugCounts.set(base, count + 1); + return count === 0 ? base : `${base}-${count}`; + } + + forEachLine(precedingMarkdown, (line, isInCodeBlock) => { + const heading = isInCodeBlock ? null : /^#{1,6} (.+)$/.exec(line); + if (heading !== null) slug(heading[1]); + }); + + const anchors = new Map(); + const lines: string[] = []; + let pendingAnchor: string | undefined; + forEachLine(api, (line, isInCodeBlock) => { + if (!isInCodeBlock) { + const anchor = /^<\/a>$/.exec(line); + if (anchor !== null) { + pendingAnchor = anchor[1]; + return; + } + + const heading = /^#{1,6} (.+)$/.exec(line); + if (heading !== null) { + const headingSlug = slug(heading[1]); + if (pendingAnchor !== undefined) { + anchors.set(pendingAnchor, headingSlug); + pendingAnchor = undefined; + } + } else if (pendingAnchor !== undefined && line === '') { + // the empty line between the anchor and its heading + return; + } + } + + lines.push(line); + }); + + // the anchors of the rows of the type parameter tables have no heading + const removedAnchors = new Set(); + const markdown = lines.join('\n').replaceAll(/<\/a> /g, (_, id: string) => { + removedAnchors.add(id); + return ''; + }); + + return markdown.replaceAll(/\]\(#([^)]+)\)/g, (link, id: string) => { + if (removedAnchors.has(id)) { + throw new Error(`The link to #${id} has no heading to link to`); + } + const anchor = anchors.get(id); + return anchor === undefined ? link : `](#${anchor})`; + }); +} + +function forEachLine(markdown: string, callback: (line: string, isInCodeBlock: boolean) => void) { + let isInCodeBlock = false; + for (const line of markdown.split('\n')) { + const isFence = line.trimStart().startsWith('```'); + callback(line, isInCodeBlock || isFence); + if (isFence) isInCodeBlock = !isInCodeBlock; + } +} + +function unwrapNoInfer(type: SomeType): SomeType { + if ( + type instanceof ReferenceType && + type.name === 'NoInfer' && + type.typeArguments?.length === 1 + ) { + return unwrapNoInfer(type.typeArguments[0]); + } + + // `Type` is the base class of all the `SomeType` types + for (const [key, value] of Object.entries(type)) { + if (value instanceof Type) { + Reflect.set(type, key, unwrapNoInfer(value as SomeType)); + } else if (Array.isArray(value)) { + Reflect.set( + type, + key, + value.map((item: unknown) => + item instanceof Type ? unwrapNoInfer(item as SomeType) : item + ) + ); + } + } + + return type; +} diff --git a/src/Cell.tsx b/src/Cell.tsx index 6ec113ed2e..d247e44c52 100644 --- a/src/Cell.tsx +++ b/src/Cell.tsx @@ -124,6 +124,11 @@ function Cell({ ); } +/** + * The default cell component. Can be wrapped via the `renderers.renderCell` prop. + * + * @group Components + */ const MemoCell = memo(Cell) as (props: RenderCellProps) => React.JSX.Element; export { MemoCell as Cell }; diff --git a/src/Columns.tsx b/src/Columns.tsx index c2d8219fef..4ffb6abe15 100644 --- a/src/Columns.tsx +++ b/src/Columns.tsx @@ -7,6 +7,18 @@ import type { } from './types'; import { SelectCheckbox } from './cellRenderers'; +/** + * The key used for the `SelectColumn`. Useful for identifying or filtering the select column. + * + * @example + * ```tsx + * import { SELECT_COLUMN_KEY } from 'react-data-grid'; + * + * const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN_KEY); + * ``` + * + * @group Other + */ export const SELECT_COLUMN_KEY = 'rdg-select-column'; function SelectAllCell({ tabIndex }: RenderHeaderCellContentProps) { @@ -56,6 +68,35 @@ function GroupSelectCell({ row, tabIndex }: RenderGroupCellContentProps ); } +/** + * A pre-configured column for row selection. + * Includes checkbox renderers for the header row, regular rows, and group rows. + * + * @example + * ```tsx + * import { DataGrid, SelectColumn, type Column } from 'react-data-grid'; + * + * const columns: readonly Column[] = [SelectColumn, ...otherColumns]; + * + * function rowKeyGetter(row: Row) { + * return row.id; + * } + * + * function MyGrid() { + * return ( + * + * ); + * } + * ``` + * + * @group Other + */ // oxlint-disable-next-line typescript/no-explicit-any export const SelectColumn: Column = { key: SELECT_COLUMN_KEY, diff --git a/src/DataGrid.tsx b/src/DataGrid.tsx index 3d2a5bf9e6..3a7d986016 100644 --- a/src/DataGrid.tsx +++ b/src/DataGrid.tsx @@ -80,6 +80,13 @@ import { } from './style/core'; import SummaryRow from './SummaryRow'; +/** + * Default options applied to all columns. + * + * @see {@linkcode DataGridProps.defaultColumnOptions | defaultColumnOptions} prop on `` + * + * @group Types + */ export type DefaultColumnOptions = Pick< Column, | 'renderCell' @@ -92,135 +99,619 @@ export type DefaultColumnOptions = Pick< | 'draggable' >; +/** + * Handle type assigned to a grid's `ref` for programmatic grid control. + * + * @example + * ```tsx + * import { useRef } from 'react'; + * import { DataGrid, type DataGridHandle } from 'react-data-grid'; + * + * function MyGrid() { + * const gridRef = useRef(null); + * + * function scrollToTop() { + * gridRef.current?.scrollToCell({ rowIdx: 0 }); + * } + * + * return ; + * } + * ``` + * + * @see {@linkcode DataGridProps.ref | ref} prop on `` + * + * @group Types + */ export interface DataGridHandle { element: HTMLDivElement | null; scrollToCell: (position: PartialPosition) => void; setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; } -type SharedDivProps = Pick< - React.ComponentProps<'div'>, - | 'role' - | 'aria-label' - | 'aria-labelledby' - | 'aria-description' - | 'aria-describedby' - | 'aria-rowcount' - | 'className' - | 'style' - | 'onScroll' ->; +type DivProps = React.ComponentProps<'div'>; -export interface DataGridProps extends SharedDivProps { +/** + * @typeParam R - Row type + * @typeParam SR - Summary row type + * @typeParam K - Row key type + * + * @group Components + */ +export interface DataGridProps { + /** + * Optional ref for imperative APIs like scrolling to or focusing a cell. See {@linkcode DataGridHandle}. + */ ref?: Maybe>; /** * Grid and data props */ - /** An array of column definitions */ + /** + * An array of column definitions and/or column groups. See the {@linkcode ColumnOrColumnGroup} type for all available options. + * + * :warning: **Performance:** Passing a new `columns` array will trigger a re-render and recalculation for the entire grid. Always memoize this prop using `useMemo` or define it outside the component to avoid unnecessary re-renders. + */ columns: readonly ColumnOrColumnGroup, NoInfer>[]; - /** An array of rows, which can be of any type */ + /** + * An array of rows. The row data can be of any type. + * + * :bulb: **Performance:** The grid is optimized for efficient rendering: + * + * - **Virtualization**: Only visible rows are rendered in the DOM + * - **Individual row updates**: Row components are memoized, so updating a single row object will only re-render that specific row, not all rows + * - **Array reference matters**: Changing the array reference itself (e.g., `setRows([...rows])`) triggers viewport and layout recalculations, even if the row objects are unchanged + * - **Best practice**: When updating rows, create a new array but reuse unchanged row objects. For example: + * + * ```tsx + * // ✅ Good: Only the changed row is re-rendered + * setRows(rows.map((row, idx) => (idx === targetIdx ? { ...row, updated: true } : row))); + * + * // ❌ Avoid: Creates new references for all rows, causing all visible rows to re-render + * setRows(rows.map((row) => ({ ...row }))); + * ``` + */ rows: readonly R[]; - /** Rows pinned at the top of the grid for summary purposes */ + /** + * Rows pinned at the top of the grid for summary purposes. + * + * :warning: **Performance:** Memoize this array to prevent internal memoization invalidation. + */ topSummaryRows?: Maybe; - /** Rows pinned at the bottom of the grid for summary purposes */ + /** + * Rows pinned at the bottom of the grid for summary purposes. + * + * :warning: **Performance:** Memoize this array to prevent internal memoization invalidation. + */ bottomSummaryRows?: Maybe; - /** Function to return a unique key/identifier for each row */ + /** + * Function to return a unique key/identifier for each row. `rowKeyGetter` is required for row selection to work. + * + * ```tsx + * import { DataGrid } from 'react-data-grid'; + * + * interface Row { + * id: number; + * name: string; + * } + * + * function rowKeyGetter(row: Row) { + * return row.id; + * } + * + * function MyGrid() { + * return ; + * } + * ``` + * + * :bulb: While optional, setting this prop is recommended for optimal performance, as the returned value is used to set the `key` prop on the row elements. + * + * :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. + */ rowKeyGetter?: Maybe<(row: NoInfer) => K>; - /** Callback triggered when rows are changed */ + /** + * Callback triggered when rows are changed. + * + * The first parameter is a new rows array with both the updated rows and the other untouched rows. + * The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. See the {@linkcode RowsChangeData} type. + * + * ```tsx + * import { useState } from 'react'; + * import { DataGrid } from 'react-data-grid'; + * + * function MyGrid() { + * const [rows, setRows] = useState(initialRows); + * + * return ; + * } + * ``` + */ onRowsChange?: Maybe<(rows: NoInfer[], data: RowsChangeData, NoInfer>) => void>; /** * Dimensions props */ /** - * Height of each row in pixels - * @default 35 + * Height of each row in pixels. A function can be used to set different row heights. + * + * ```tsx + * // Fixed height for all rows + * ; + * + * // Dynamic height per row + * function getRowHeight(row) { + * return row.isExpanded ? 100 : 35; + * } + * + * ; + * ``` + * + * :warning: **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. + * + * @defaultValue `35` pixels */ rowHeight?: Maybe) => number)>; /** - * Height of the header row in pixels - * @default `rowHeight` when it is a number, otherwise 35 + * Height of the header row in pixels. + * + * @defaultValue `rowHeight` when it is a number, otherwise `35` pixels */ headerRowHeight?: Maybe; /** - * Height of each summary row in pixels - * @default `rowHeight` when it is a number, otherwise 35 + * Height of each summary row in pixels. + * + * ```tsx + * + * ``` + * + * @defaultValue `rowHeight` when it is a number, otherwise `35` pixels */ summaryRowHeight?: Maybe; - /** A map of column widths */ + /** + * A map of column widths containing both measured and resized widths. If not provided, an internal state is used. See the {@linkcode ColumnWidths} type. + * + * ```tsx + * const [columnWidths, setColumnWidths] = useState((): ColumnWidths => new Map()); + * + * function addNewRow() { + * setRows(...); + * // reset column widths after adding a new row + * setColumnWidths(new Map()); + * } + * + * return + * ``` + */ columnWidths?: Maybe; - /** Callback triggered when column widths change */ + /** + * Callback triggered when column widths change. If not provided, an internal state is used. See the {@linkcode ColumnWidths} type. + */ onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; /** * Feature props */ - /** A set of selected row keys */ + /** + * A set of selected row keys. `rowKeyGetter` is required for row selection to work. + */ selectedRows?: Maybe>; - /** Function to determine if row selection is disabled for a specific row */ + /** + * Function to determine if row selection is disabled for a specific row. + */ isRowSelectionDisabled?: Maybe<(row: NoInfer) => boolean>; - /** Callback triggered when the selection changes */ + /** + * Callback triggered when the selection changes. + * + * ```tsx + * import { useState } from 'react'; + * import { DataGrid, SelectColumn, type Column } from 'react-data-grid'; + * + * const rows: readonly Row[] = [...]; + * + * const columns: readonly Column[] = [ + * SelectColumn, + * // other columns + * ]; + * + * function rowKeyGetter(row: Row) { + * return row.id; + * } + * + * function isRowSelectionDisabled(row: Row) { + * return !row.isActive; + * } + * + * function MyGrid() { + * const [selectedRows, setSelectedRows] = useState((): ReadonlySet => new Set()); + * + * return ( + * + * ); + * } + * ``` + */ onSelectedRowsChange?: Maybe<(selectedRows: Set>) => void>; - /** An array of sorted columns */ + /** + * An array of sorted columns. See the {@linkcode SortColumn} type. + * + * Sorting is controlled: the grid does not reorder `rows` for you. Apply the sorting to your `rows` state (or derived rows) based on `sortColumns`. + */ sortColumns?: Maybe; - /** Callback triggered when sorting changes */ + /** + * Callback triggered when sorting changes. + * + * ```tsx + * import { useState } from 'react'; + * import { DataGrid, type Column, type SortColumn } from 'react-data-grid'; + * + * const rows: readonly Row[] = [...]; + * + * const columns: readonly Column[] = [ + * { + * key: 'name', + * name: 'Name', + * sortable: true + * }, + * // other columns + * ]; + * + * function MyGrid() { + * const [sortColumns, setSortColumns] = useState([]); + * + * return ( + * + * ); + * } + * ``` + * + * More than one column can be sorted via Ctrl+Click (Cmd+Click on macOS). To disable multi-column sorting, change the `onSortColumnsChange` function to: + * + * ```tsx + * function onSortColumnsChange(sortColumns: SortColumn[]) { + * setSortColumns(sortColumns.slice(-1)); + * } + * ``` + */ onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>; - /** Default options applied to all columns */ + /** + * Default options applied to all columns. See the {@linkcode DefaultColumnOptions} type. + * + * ```tsx + * function MyGrid() { + * return ( + * + * ); + * } + * ``` + */ defaultColumnOptions?: Maybe, NoInfer>>; /** * Event props */ - /** Callback triggered when a pointer becomes active in a cell */ + /** + * Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the {@linkcode CellMouseArgs} and {@linkcode CellMouseEvent} types. + * + * ```tsx + * function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { + * if (args.column.key === 'id') { + * event.preventGridDefault(); + * } + * } + * + * ; + * ``` + */ onCellMouseDown?: CellMouseEventHandler; - /** Callback triggered when a cell is clicked */ + /** + * Callback triggered when a cell is clicked. See the {@linkcode CellMouseArgs} and {@linkcode CellMouseEvent} types. + * + * This event can be used to open the cell editor on a single click: + * + * ```tsx + * function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { + * if (args.column.key === 'id') { + * args.setActivePosition(true); + * } + * } + * + * ; + * ``` + */ onCellClick?: CellMouseEventHandler; - /** Callback triggered when a cell is double-clicked */ + /** + * Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the {@linkcode CellMouseArgs} and {@linkcode CellMouseEvent} types. + * + * ```tsx + * function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { + * if (args.column.key === 'id') { + * event.preventGridDefault(); + * } + * } + * + * ; + * ``` + */ onCellDoubleClick?: CellMouseEventHandler; - /** Callback triggered when a cell is right-clicked */ + /** + * Callback triggered when a cell is right-clicked. See the {@linkcode CellMouseArgs} and {@linkcode CellMouseEvent} types. + * + * ```tsx + * function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { + * if (args.column.key === 'id') { + * event.preventDefault(); + * // open custom context menu + * } + * } + * + * ; + * ``` + */ onCellContextMenu?: CellMouseEventHandler; - /** Callback triggered when a key is pressed in a cell */ + /** + * Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. See the {@linkcode CellKeyDownArgs} and {@linkcode CellKeyboardEvent} types. + * + * **Examples** + * + * - Prevent editing on `Enter` + * + * ```tsx + * function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { + * if (args.mode === 'ACTIVE' && event.key === 'Enter') { + * event.preventGridDefault(); + * } + * } + * ``` + * + * - Prevent navigation on `Tab` + * + * ```tsx + * function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { + * if (args.mode === 'ACTIVE' && event.key === 'Tab') { + * event.preventGridDefault(); + * } + * } + * ``` + * + * See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website/routes/CellNavigation.tsx). + */ onCellKeyDown?: Maybe< (args: CellKeyDownArgs, NoInfer>, event: CellKeyboardEvent) => void >; - /** Callback triggered when a cell's content is copied */ + /** + * Callback triggered when a cell's content is copied. See the {@linkcode CellCopyArgs} type. + */ onCellCopy?: Maybe< (args: CellCopyArgs, NoInfer>, event: CellClipboardEvent) => void >; - /** Callback triggered when content is pasted into a cell */ + /** + * Callback triggered when content is pasted into a cell. See the {@linkcode CellPasteArgs} type. + * + * Return the updated row; the grid will call `onRowsChange` with it. + */ onCellPaste?: Maybe< (args: CellPasteArgs, NoInfer>, event: CellClipboardEvent) => NoInfer >; - /** Function called whenever the active position is changed */ + /** + * Callback triggered when the active position changes. See the {@linkcode PositionChangeArgs} type. + */ onActivePositionChange?: Maybe<(args: PositionChangeArgs, NoInfer>) => void>; - /** Callback triggered when a column is resized */ + /** + * Callback triggered when a column is resized. The `column` parameter is the full {@linkcode CalculatedColumn} object, and `width` is the new width in pixels. + */ onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void>; - /** Callback triggered when columns are reordered */ + /** + * Callback triggered when columns are reordered. The parameters are the `key` values of the source and target columns. + */ onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>; - /** Callback triggered when the value of the active cell is dragged to fill other cells */ + /** + * Callback triggered when the value of the active cell is dragged to fill other cells. When this prop is set, a drag handle is shown on the active cell if it is editable. Drag the handle up or down to fill the cells it passes over, or double-click it to fill all the cells below. + * + * The grid calls `onFill` for each editable target cell. Return the updated target row; the grid will call `onRowsChange` with the updated rows. See the {@linkcode FillEvent} type. + * + * ```tsx + * function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { + * return { ...targetRow, [columnKey]: sourceRow[columnKey as keyof Row] }; + * } + * + * ; + * ``` + */ onFill?: Maybe<(event: FillEvent>) => NoInfer>; + /** + * Native DOM `onScroll` prop. + */ + onScroll?: DivProps['onScroll']; /** * Toggles and modes */ - /** @default true */ + /** + * This prop can be used to disable virtualization. + * + * @defaultValue `true` + */ enableVirtualization?: Maybe; /** * Miscellaneous */ - /** Custom renderers for cells, rows, and other components */ + /** + * Custom renderers for cells, rows, and other components. + * + * See the {@linkcode Renderers} type for the full shape. + * + * Example of replacing default components: + * + * ```tsx + * import { DataGrid, type Renderers } from 'react-data-grid'; + * + * const customRenderers: Renderers = { + * // Custom row render function + * renderRow(key, props) { + * return ; + * }, + * + * // Custom cell render function + * renderCell(key, props) { + * return ; + * }, + * + * // Custom checkbox render function + * renderCheckbox(props) { + * return ; + * }, + * + * // Custom sort status indicator + * renderSortStatus(props) { + * return ; + * }, + * + * // Custom empty state + * noRowsFallback:
No data available
+ * }; + * + * ; + * ``` + * + * The default `` component can be wrapped via `renderers.renderRow` to add contexts or tweak props: + * + * ```tsx + * import { DataGrid, Row, type RenderRowProps } from 'react-data-grid'; + * + * interface MyRow { + * id: number; + * } + * + * function myRowRenderer(key: React.Key, props: RenderRowProps) { + * return ( + * + * + * + * ); + * } + * + * function MyGrid() { + * return ; + * } + * ``` + */ renderers?: Maybe, NoInfer>>; - /** Function to apply custom class names to rows */ + /** + * Function to apply custom class names to rows. + * + * ```tsx + * import { DataGrid } from 'react-data-grid'; + * + * function rowClass(row: Row, rowIdx: number) { + * return rowIdx % 2 === 0 ? 'even' : 'odd'; + * } + * + * function MyGrid() { + * return ; + * } + * ``` + * + * :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. + */ rowClass?: Maybe<(row: NoInfer, rowIdx: number) => Maybe>; - /** Custom class name for the header row */ + /** + * Custom class name for the header row. + * + * ```tsx + * + * ``` + */ headerRowClass?: Maybe; /** - * Text direction of the grid ('ltr' or 'rtl') - * @default 'ltr' + * This property sets the text direction of the grid. It defaults to `'ltr'` (left-to-right). See the {@linkcode Direction} type. + * + * Setting `direction` to `'rtl'` has the following effects: + * + * - Columns flow from right to left + * - Start-frozen columns are pinned on the right, and end-frozen columns are pinned on the left + * - Column resize cursor is shown on the left edge of the column + * - Scrollbar is moved to the left + * + * @defaultValue `'ltr'` */ direction?: Maybe; + /** + * Custom class name for the grid. + */ + className?: DivProps['className']; + /** + * Custom styles for the grid. + */ + style?: DivProps['style']; + /** + * ARIA role for the grid container. Defaults to `grid`. + */ + role?: DivProps['role']; + /** + * The label of the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. + */ + 'aria-label'?: DivProps['aria-label']; + /** + * The id of the element containing a label for the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. + */ + 'aria-labelledby'?: DivProps['aria-labelledby']; + /** + * Total number of rows for assistive technologies. + */ + 'aria-rowcount'?: DivProps['aria-rowcount']; + /** + * A human-readable description of the grid. + */ + 'aria-description'?: DivProps['aria-description']; + /** + * If the grid has a caption or description, `aria-describedby` can be set on the grid element with a value referring to the element containing the description. + */ + 'aria-describedby'?: DivProps['aria-describedby']; + /** + * This prop can be used to add a test ID for testing. We recommend querying the grid by its `role` and `name`. + * + * ```tsx + * function MyGrid() { + * return ; + * } + * + * test('grid', async () => { + * await page.render(); + * const grid = page.getByRole('grid', { name: 'my-grid' }); + * }); + * ``` + */ 'data-testid'?: Maybe; + /** + * Optional attribute to help with Cypress (or similar) selectors. + */ 'data-cy'?: Maybe; } @@ -228,8 +719,15 @@ export interface DataGridProps extends Sha * Main API component to render a data grid of rows and columns * * @example - * + * ```tsx * + * ``` + * + * @typeParam R - Row type + * @typeParam SR - Summary row type + * @typeParam K - Row key type + * + * @group Components */ export function DataGrid(props: DataGridProps) { const { diff --git a/src/DataGridRenderersContext.ts b/src/DataGridRenderersContext.ts index 32f1aa00c4..4984bd05e9 100644 --- a/src/DataGridRenderersContext.ts +++ b/src/DataGridRenderersContext.ts @@ -2,6 +2,41 @@ import { createContext, use } from 'react'; import type { Maybe, Renderers } from './types'; +/** + * Context for providing default renderers to DataGrids in your app. + * + * @example + * ```tsx + * import { + * DataGridRenderersContext, + * renderCheckbox, + * renderSortIcon, + * renderSortPriority, + * type Renderers + * } from 'react-data-grid'; + * + * // custom implementations of renderers + * const defaultGridRenderers: Renderers = { + * renderCheckbox, + * renderSortStatus(props) { + * return ( + * <> + * {renderSortIcon(props)} + * {renderSortPriority(props)} + * + * ); + * } + * }; + * + * function AppProvider({ children }) { + * return ( + * {children} + * ); + * } + * ``` + * + * @group Context + */ // oxlint-disable-next-line typescript/no-explicit-any export const DataGridRenderersContext = createContext>>(undefined); DataGridRenderersContext.displayName = 'DataGridRenderersContext'; diff --git a/src/Row.tsx b/src/Row.tsx index a8b55bc21b..40fb96412b 100644 --- a/src/Row.tsx +++ b/src/Row.tsx @@ -86,6 +86,11 @@ function Row({ ); } +/** + * The default row component. Can be wrapped via the `renderers.renderRow` prop. + * + * @group Components + */ const MemoRow = memo(Row) as (props: RenderRowProps) => React.JSX.Element; export { MemoRow as Row }; diff --git a/src/TreeDataGrid.tsx b/src/TreeDataGrid.tsx index 05f50d2945..5516d70429 100644 --- a/src/TreeDataGrid.tsx +++ b/src/TreeDataGrid.tsx @@ -25,19 +25,112 @@ import { useRenderers } from './DataGridRenderersContext'; import GroupedRow from './GroupedRow'; import { defaultRenderRow } from './Row'; +/** + * All {@linkcode DataGridProps} are supported except those listed above. The `columns` prop only supports `Column[]` (no column groups). When `rowHeight` is a function, it receives {@linkcode RowHeightArgs} instead of just the row. Additional props are listed below: + * + * @typeParam R - Row type + * @typeParam SR - Summary row type + * @typeParam K - Row key type + * + * @group Components + */ export interface TreeDataGridProps extends Omit< DataGridProps, 'columns' | 'role' | 'aria-rowcount' | 'rowHeight' | 'onFill' | 'isRowSelectionDisabled' > { columns: readonly Column, NoInfer>[]; + /** + * **Note:** Unlike `DataGrid`, the `rowHeight` function receives {@linkcode RowHeightArgs | RowHeightArgs}, which includes a `type` property to distinguish between regular rows and group rows: + * + * ```tsx + * function getRowHeight(args: RowHeightArgs): number { + * if (args.type === 'GROUP') { + * return 50; // Custom height for group rows + * } + * return 35; // Height for regular rows + * } + * + * + * ``` + */ rowHeight?: Maybe>) => number)>; + /** + * **Required.** An array of column keys to group by. The order determines the grouping hierarchy (first key is the top level, second key is nested under the first, etc.). + * + * ```tsx + * import { TreeDataGrid, type Column } from 'react-data-grid'; + * + * interface Row { + * id: number; + * country: string; + * city: string; + * name: string; + * } + * + * const columns: readonly Column[] = [ + * { key: 'country', name: 'Country' }, + * { key: 'city', name: 'City' }, + * { key: 'name', name: 'Name' } + * ]; + * + * function MyGrid() { + * return ( + * + * ); + * } + * ``` + */ groupBy: readonly string[]; + /** + * **Required.** A function that groups rows by the specified column key. Returns an object where keys are the group values and values are arrays of rows belonging to that group. + * + * ```tsx + * function rowGrouper(rows: readonly Row[], columnKey: string): Record { + * return Object.groupBy(rows, (row) => row[columnKey]); + * } + * ``` + * + * :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. + */ rowGrouper: ( rows: readonly NoInfer[], columnKey: string ) => Record[]>; + /** + * **Required.** A set of group IDs that are currently expanded. Group IDs are generated by `groupIdGetter`. + * + * ```tsx + * import { useState } from 'react'; + * import { TreeDataGrid } from 'react-data-grid'; + * + * function MyGrid() { + * const [expandedGroupIds, setExpandedGroupIds] = useState((): ReadonlySet => new Set()); + * + * return ( + * + * ); + * } + * ``` + */ expandedGroupIds: ReadonlySet; + /** + * **Required.** Callback triggered when groups are expanded or collapsed. + */ onExpandedGroupIdsChange: (expandedGroupIds: Set) => void; + /** + * Function to generate unique IDs for group rows. If not provided, a default implementation is used that concatenates parent and group keys with `__`. + * + * :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. + */ groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>; } @@ -50,6 +143,44 @@ interface GroupBy { type GroupByMap = Map>; type ReadonlyGroupByMap = ReadonlyMap>; +/** + * `TreeDataGrid` is a component built on top of `DataGrid` to add hierarchical row grouping. This implements the [Treegrid pattern](https://www.w3.org/WAI/ARIA/apg/patterns/treegrid/). + * + * **How it works:** + * + * 1. The `groupBy` prop specifies which columns should be used for grouping + * 2. The `rowGrouper` function groups rows by the specified column keys + * 3. Group rows are rendered with expand/collapse toggles + * 4. Child rows are nested under their parent groups + * 5. Groups can be expanded/collapsed by clicking the toggle or using keyboard navigation (←, →) + * + * **Keyboard Navigation:** + * + * - → (Right Arrow): Expand a collapsed group row when focused + * - ← (Left Arrow): Collapse an expanded group row when focused, or navigate to the parent group + * + * **Unsupported Props:** + * + * The following `DataGrid` props are not supported in `TreeDataGrid`: + * + * - `onFill` - Drag-fill is disabled for tree grids + * - `isRowSelectionDisabled` - Row selection disabling is not available + * - `role` - `TreeDataGrid` manages the ARIA role + * - `aria-rowcount` - `TreeDataGrid` manages the ARIA row count + * + * **Caveats:** + * + * - Group columns cannot be rendered under one column + * - Group columns are automatically frozen and cannot be unfrozen + * - Cell copy/paste does not work on group rows + * - Column groups are not supported; `columns` must be `Column[]` + * + * @typeParam R - Row type + * @typeParam SR - Summary row type + * @typeParam K - Row key type + * + * @group Components + */ export function TreeDataGrid({ columns: rawColumns, rows: rawRows, diff --git a/src/cellRenderers/SelectCheckbox.tsx b/src/cellRenderers/SelectCheckbox.tsx index f721c518b4..21b1908dc2 100644 --- a/src/cellRenderers/SelectCheckbox.tsx +++ b/src/cellRenderers/SelectCheckbox.tsx @@ -11,6 +11,13 @@ interface SelectCheckboxProps extends SharedInputProps { value: boolean; } +/** + * A component for rendering row selection checkboxes. + * + * The same props as {@linkcode RenderCheckboxProps}, with `value: boolean` in place of `checked`. + * + * @group Components + */ export function SelectCheckbox({ value, tabIndex, diff --git a/src/cellRenderers/renderCheckbox.tsx b/src/cellRenderers/renderCheckbox.tsx index 9920c08157..a3ac92824c 100644 --- a/src/cellRenderers/renderCheckbox.tsx +++ b/src/cellRenderers/renderCheckbox.tsx @@ -22,6 +22,22 @@ const checkbox = css` const checkboxClassname = `rdg-checkbox-input ${checkbox}`; +/** + * Renders a checkbox input with proper styling and accessibility. + * + * @example + * ```tsx + * import { DataGrid, renderCheckbox } from 'react-data-grid'; + * + * renderCheckbox({ ...props, 'aria-label': 'Select row' }) + * }} + * />; + * ``` + * + * @group Render Functions + */ export function renderCheckbox({ onChange, indeterminate, ...props }: RenderCheckboxProps) { function handleChange(e: React.ChangeEvent) { onChange(e.target.checked, (e.nativeEvent as MouseEvent).shiftKey); diff --git a/src/cellRenderers/renderToggleGroup.tsx b/src/cellRenderers/renderToggleGroup.tsx index aacf370344..1ff6e6e12f 100644 --- a/src/cellRenderers/renderToggleGroup.tsx +++ b/src/cellRenderers/renderToggleGroup.tsx @@ -26,10 +26,33 @@ const caret = css` const caretClassname = `rdg-caret ${caret}`; +/** + * The default group cell content renderer for the columns used for grouping (`groupBy` prop). This renders the expand/collapse toggle. + * + * @example + * ```tsx + * import { renderToggleGroup, type Column } from 'react-data-grid'; + * + * const columns: readonly Column[] = [ + * { + * key: 'group', + * name: 'Group', + * renderGroupCell: renderToggleGroup + * } + * ]; + * ``` + * + * @group Render Functions + */ export function renderToggleGroup(props: RenderGroupCellContentProps) { return ; } +/** + * Low-level component used by `renderToggleGroup` to render the expand/collapse control. Useful if you build a custom group cell renderer. + * + * @group Components + */ export function ToggleGroup({ groupKey, isExpanded, diff --git a/src/cellRenderers/renderValue.tsx b/src/cellRenderers/renderValue.tsx index 070be7f904..908cf44b55 100644 --- a/src/cellRenderers/renderValue.tsx +++ b/src/cellRenderers/renderValue.tsx @@ -1,5 +1,23 @@ import type { RenderCellContentProps } from '../types'; +/** + * The default cell content renderer that renders the value of `row[column.key]`. + * + * @example + * ```tsx + * import { renderValue, type Column } from 'react-data-grid'; + * + * const columns: readonly Column[] = [ + * { + * key: 'title', + * name: 'Title', + * renderCell: renderValue + * } + * ]; + * ``` + * + * @group Render Functions + */ export function renderValue(props: RenderCellContentProps) { return props.row?.[props.column.key as keyof R] as React.ReactNode; } diff --git a/src/editors/renderTextEditor.tsx b/src/editors/renderTextEditor.tsx index a53e9a4eca..1decd85b6a 100644 --- a/src/editors/renderTextEditor.tsx +++ b/src/editors/renderTextEditor.tsx @@ -38,6 +38,24 @@ function autoFocusAndSelect(input: HTMLInputElement | null) { input?.select(); } +/** + * A basic text editor provided for convenience. + * + * @example + * ```tsx + * import { renderTextEditor, type Column } from 'react-data-grid'; + * + * const columns: readonly Column[] = [ + * { + * key: 'title', + * name: 'Title', + * renderEditCell: renderTextEditor + * } + * ]; + * ``` + * + * @group Render Functions + */ export function renderTextEditor({ row, column, diff --git a/src/hooks/useRowSelection.ts b/src/hooks/useRowSelection.ts index 64f02778bc..407a1ecd1b 100644 --- a/src/hooks/useRowSelection.ts +++ b/src/hooks/useRowSelection.ts @@ -16,6 +16,39 @@ export const RowSelectionChangeContext = createContext< >(undefined); RowSelectionChangeContext.displayName = 'RowSelectionChangeContext'; +/** + * Hook for managing row selection state. Used within custom cell renderers to implement custom row selection. + * + * @returns + * + * - `isRowSelectionDisabled: boolean` - Whether selection is disabled for this row + * - `isRowSelected: boolean` - Whether this row is selected + * - `onRowSelectionChange: (event: SelectRowEvent) => void` - Callback to change selection state + * + * @example + * ```tsx + * function CustomSelectCell({ row }: RenderCellContentProps) { + * const { isRowSelectionDisabled, isRowSelected, onRowSelectionChange } = useRowSelection(); + * + * return ( + * + * onRowSelectionChange({ + * row, + * checked: event.currentTarget.checked, + * isShiftClick: event.nativeEvent.shiftKey + * }) + * } + * /> + * ); + * } + * ``` + * + * @group Hooks + */ export function useRowSelection() { const rowSelectionContext = use(RowSelectionContext); const rowSelectionChangeContext = use(RowSelectionChangeContext); @@ -46,6 +79,42 @@ export const HeaderRowSelectionChangeContext = createContext< >(undefined); HeaderRowSelectionChangeContext.displayName = 'HeaderRowSelectionChangeContext'; +/** + * Hook for managing header row selection state. Used within custom header cell renderers to implement custom "select all" functionality. + * + * @returns + * + * - `isIndeterminate: boolean` - Whether some (but not all) rows are selected + * - `isRowSelected: boolean` - Whether all rows are selected + * - `onRowSelectionChange: (event: SelectHeaderRowEvent) => void` - Callback to change selection state + * + * @example + * ```tsx + * import { useLayoutEffect, useRef } from 'react'; + * + * function CustomHeaderCell() { + * const { isIndeterminate, isRowSelected, onRowSelectionChange } = useHeaderRowSelection(); + * const checkboxRef = useRef(null); + * + * useLayoutEffect(() => { + * if (checkboxRef.current) { + * checkboxRef.current.indeterminate = isIndeterminate && !isRowSelected; + * } + * }, [isIndeterminate, isRowSelected]); + * + * return ( + * onRowSelectionChange({ checked: event.target.checked })} + * /> + * ); + * } + * ``` + * + * @group Hooks + */ export function useHeaderRowSelection() { const headerRowSelectionContext = use(HeaderRowSelectionContext); const headerRowSelectionChangeContext = use(HeaderRowSelectionChangeContext); diff --git a/src/hooks/useScrollToPosition.tsx b/src/hooks/useScrollToPosition.tsx index b34758a0f3..e38c2faaf5 100644 --- a/src/hooks/useScrollToPosition.tsx +++ b/src/hooks/useScrollToPosition.tsx @@ -3,6 +3,11 @@ import { useState } from 'react'; import { scrollIntoView } from '../utils'; import type { Maybe } from '../types'; +/** + * Position for scrolling to a cell. Both fields are optional: omit `idx` to scroll to a row, or omit `rowIdx` to scroll to a column. This helper type is not exported; the shape is shown for reference. + * + * @see {@linkcode DataGridHandle} + */ export interface PartialPosition { readonly idx?: Maybe; readonly rowIdx?: Maybe; diff --git a/src/index.ts b/src/index.ts index 6b999c11b0..eab00a06fa 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,8 @@ +/** + * @module + * @sortStrategy alphabetical + */ + import './style/layers.css'; export { diff --git a/src/renderHeaderCell.tsx b/src/renderHeaderCell.tsx index 7132838812..5cae692330 100644 --- a/src/renderHeaderCell.tsx +++ b/src/renderHeaderCell.tsx @@ -19,6 +19,25 @@ const headerSortName = css` const headerSortNameClassname = `rdg-header-sort-name ${headerSortName}`; +/** + * The default header cell content renderer. Renders sortable columns with sort indicators. + * + * @example + * ```tsx + * import { renderHeaderCell, type Column } from 'react-data-grid'; + * + * const columns: readonly Column[] = [ + * { + * key: 'name', + * name: 'Name', + * sortable: true, + * renderHeaderCell + * } + * ]; + * ``` + * + * @group Render Functions + */ export function renderHeaderCell({ column, sortDirection, diff --git a/src/sortStatus.tsx b/src/sortStatus.tsx index 752f22f576..c9bf5a4ab0 100644 --- a/src/sortStatus.tsx +++ b/src/sortStatus.tsx @@ -23,6 +23,11 @@ export default function renderSortStatus({ sortDirection, priority }: RenderSort ); } +/** + * Renders the sort direction arrow icon. + * + * @group Render Functions + */ export function renderSortIcon({ sortDirection }: RenderSortIconProps) { if (sortDirection === undefined) return null; @@ -33,6 +38,11 @@ export function renderSortIcon({ sortDirection }: RenderSortIconProps) { ); } +/** + * Renders the sort priority number for multi-column sorting. + * + * @group Render Functions + */ export function renderSortPriority({ priority }: RenderSortPriorityProps) { return priority; } diff --git a/src/types.ts b/src/types.ts index b8acbd1496..0e14721a24 100644 --- a/src/types.ts +++ b/src/types.ts @@ -4,87 +4,231 @@ import type { DataGridProps } from './DataGrid'; export type Omit = Pick>; +/** + * Utility type for optional values. This helper type is not exported; the shape is shown for reference. + */ export type Maybe = T | undefined | null; export type StateSetter = React.Dispatch>; +/** + * Defines the configuration for a column in the grid. + * + * @see {@linkcode DataGridProps.columns | columns} prop on `` + * + * @group Types + */ export interface Column { - /** The name of the column. Displayed in the header cell by default */ + /** The name of the column. Displayed in the header cell by default. */ readonly name: string | ReactElement; - /** A unique key to distinguish each column */ + /** A unique key to distinguish each column. */ readonly key: string; /** - * Column width. If not specified, it will be determined automatically based on grid width and specified widths of other columns - * @default 'auto' + * Width can be any valid CSS grid column value. If not specified, it will be determined automatically based on grid width and specified widths of other columns. + * + * ```tsx + * const columns: Column[] = [ + * { + * key: 'id', + * name: 'ID', + * width: 80, // Fixed width in pixels + * resizable: false + * }, + * { + * key: 'name', + * name: 'Name', + * width: '30%', // Percentage width + * minWidth: 100, + * maxWidth: 400 + * }, + * { + * key: 'description', + * name: 'Description' + * // No width specified - automatically sized + * } + * ]; + * ``` + * + * Other examples: + * + * ```tsx + * width: 80, // pixels + * width: '25%', + * width: 'max-content', + * width: 'minmax(100px, max-content)', + * ``` + * + * `max-content` can be used to expand the column to show all the content. Note that the grid is only able to calculate column width for visible rows. + * + * @defaultValue `auto` */ readonly width?: Maybe; /** - * Minimum column width in pixels - * @default 50 + * Minimum column width in pixels. + * + * @defaultValue `50` pixels */ readonly minWidth?: Maybe; - /** Maximum column width in pixels */ + /** Maximum column width in pixels. */ readonly maxWidth?: Maybe; - /** Class name(s) for cells */ + /** + * Class name(s) for cells. Can be a string or a function that returns a class name based on the row. + * + * ```tsx + * const columns: Column[] = [ + * { + * key: 'status', + * name: 'Status', + * cellClass: (row) => `status-${row.status}` + * }, + * { + * key: 'price', + * name: 'Price', + * cellClass: 'text-right' // Static class + * } + * ]; + * ``` + * + * ```css + * .status-active { + * color: green; + * font-weight: bold; + * } + * + * .status-inactive { + * color: gray; + * } + * + * .text-right { + * text-align: right; + * } + * ``` + */ readonly cellClass?: Maybe Maybe)>; - /** Class name(s) for the header cell */ + /** Class name(s) for the header cell. */ readonly headerCellClass?: Maybe; - /** Class name(s) for summary cells */ + /** Class name(s) for summary cells. Can be a string or a function that returns a class name based on the summary row. */ readonly summaryCellClass?: Maybe Maybe)>; - /** Render function to render the content of cells */ + /** Render function to render the content of cells. */ readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; - /** Render function to render the content of the header cell */ + /** Render function to render the content of the header cell. */ readonly renderHeaderCell?: Maybe< (props: RenderHeaderCellContentProps) => ReactNode >; - /** Render function to render the content of summary cells */ + /** Render function to render the content of summary cells. */ readonly renderSummaryCell?: Maybe< (props: RenderSummaryCellContentProps) => ReactNode >; - /** Render function to render the content of group cells */ + /** Render function to render the content of group cells when using `TreeDataGrid`. */ readonly renderGroupCell?: Maybe< (props: RenderGroupCellContentProps) => ReactNode >; - /** Render function to render the content of edit cells. When set, the column is automatically set to be editable */ + /** Render function to render the content of edit cells. When set, the column is automatically set to be editable. */ readonly renderEditCell?: Maybe< (props: RenderEditCellContentProps) => ReactNode >; - /** Control whether cells can be edited with `renderEditCell` */ + /** Control whether cells can be edited with `renderEditCell`. */ readonly editable?: Maybe boolean)>; + /** + * Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. See the {@linkcode ColSpanArgs} type. + * + * @example + * ```tsx + * import type { Column } from 'react-data-grid'; + * + * const columns: readonly Column[] = [ + * { + * key: 'title', + * name: 'Title', + * colSpan(args) { + * if (args.type === 'ROW' && args.row.isFullWidth) { + * return 5; // Span 5 columns for full-width rows + * } + * return undefined; + * } + * } + * ]; + * ``` + */ readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; - /** Determines whether the column is frozen, and on which edge. - * `true` is an alias for `'start'` for backward compatibility. */ + /** + * Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. See the {@linkcode ColumnFrozen} type. + * + * - `'start'` (or `true` for backward compatibility) — pins the column to the start edge (left in LTR, right in RTL). + * - `'end'` — pins the column to the end edge (right in LTR, left in RTL). + * - `false` (default) — the column scrolls with the rest of the grid. + * + * ```tsx + * const columns: readonly Column[] = [ + * { key: 'id', name: 'ID', frozen: 'start' }, + * { key: 'name', name: 'Name' }, + * { key: 'actions', name: 'Actions', frozen: 'end' } + * ]; + * ``` + * + * @defaultValue `false` + */ readonly frozen?: Maybe; - /** Enable resizing of the column */ + /** + * Enable resizing of the column. + * + * @defaultValue `false` + */ readonly resizable?: Maybe; - /** Enable sorting of the column */ + /** + * Enable sorting of the column. + * + * @defaultValue `false` + */ readonly sortable?: Maybe; - /** Enable dragging of the column */ + /** + * Enable dragging of the column. + * + * @defaultValue `false` + */ readonly draggable?: Maybe; - /** Sets the column sort order to be descending instead of ascending the first time the column is sorted */ + /** + * Sets the column sort order to be descending instead of ascending the first time the column is sorted. + * + * @defaultValue `false` + */ readonly sortDescendingFirst?: Maybe; - /** Options for cell editing */ - readonly editorOptions?: Maybe<{ - /** - * Render the cell content in addition to the edit cell content. - * Enable this option when the editor is rendered outside the grid, like a modal for example. - * By default, the cell content is not rendered when the edit cell is open. - * @default false - */ - readonly displayCellContent?: Maybe; - /** - * Commit changes when clicking outside the cell - * @default true - */ - readonly commitOnOutsideClick?: Maybe; - /** - * Close the editor when the row value changes externally - * @default true - */ - readonly closeOnExternalRowChange?: Maybe; - }>; + /** Options for cell editing. */ + readonly editorOptions?: Maybe; +} + +/** + * Options for cell editing. + */ +interface ColumnEditorOptions { + /** + * Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. + * By default, the cell content is not rendered when the edit cell is open. + * + * @defaultValue `false` + */ + readonly displayCellContent?: Maybe; + /** + * Commit changes when clicking outside the cell. + * + * @defaultValue `true` + */ + readonly commitOnOutsideClick?: Maybe; + /** + * Close the editor when the row value changes externally. + * + * @defaultValue `true` + */ + readonly closeOnExternalRowChange?: Maybe; } +/** + * Extends `Column` with additional computed properties used internally by the grid. This is the type passed to render functions. The `Column` properties it redeclares, like `width` and `renderCell`, are resolved to their default values when not set. + * + * @see {@linkcode Column}, {@linkcode DataGridProps.onColumnResize | onColumnResize} prop on `` + * + * @group Types + */ export interface CalculatedColumn extends Column { /** The column group that contains the column, or `undefined` if the column is not in a group */ readonly parent: CalculatedColumnParent | undefined; @@ -103,6 +247,28 @@ export interface CalculatedColumn extends Column) => ReactNode; } +/** + * Defines a group of columns that share a common header. + * + * @example + * ```tsx + * import type { ColumnOrColumnGroup } from 'react-data-grid'; + * + * const columns: readonly ColumnOrColumnGroup[] = [ + * { + * name: 'Personal Info', + * children: [ + * { key: 'firstName', name: 'First Name' }, + * { key: 'lastName', name: 'Last Name' } + * ] + * } + * ]; + * ``` + * + * @see {@linkcode ColumnOrColumnGroup} + * + * @group Types + */ export interface ColumnGroup { /** The name of the column group. It will be displayed in the header cell */ readonly name: string | ReactElement; @@ -110,6 +276,13 @@ export interface ColumnGroup { readonly children: readonly ColumnOrColumnGroup[]; } +/** + * Represents a parent column group in the calculated column structure. + * + * @see {@linkcode CalculatedColumn} + * + * @group Types + */ export interface CalculatedColumnParent { readonly name: string | ReactElement; readonly parent: CalculatedColumnParent | undefined; @@ -119,12 +292,31 @@ export interface CalculatedColumnParent { readonly headerCellClass?: Maybe; } +/** + * Union type representing either a `Column` or a `ColumnGroup`. + * + * @see {@linkcode DataGridProps.columns | columns} prop on `` + * + * @group Types + */ export type ColumnOrColumnGroup = Column | ColumnGroup; +/** + * Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. + * + * @see {@linkcode CalculatedColumn}, {@linkcode CalculatedColumnParent} + * + * @group Types + */ export type CalculatedColumnOrColumnGroup = | CalculatedColumnParent | CalculatedColumn; +/** + * Represents a cell position in the grid. This helper type is not exported; the shape is shown for reference. + * + * @see {@linkcode DataGridHandle}, {@linkcode CellKeyDownArgs} + */ export interface Position { /** Column index, or `-1` for the whole row in `TreeDataGrid` */ readonly idx: number; @@ -132,6 +324,27 @@ export interface Position { readonly rowIdx: number; } +/** + * Props passed to custom cell content renderers (`column.renderCell`). + * + * @example + * ```tsx + * import type { RenderCellContentProps } from 'react-data-grid'; + * + * function renderCell({ row, column, onRowChange }: RenderCellContentProps) { + * return ( + *
+ * {row[column.key]} + * + *
+ * ); + * } + * ``` + * + * @see {@linkcode Column.renderCell | column.renderCell}, {@linkcode renderValue} function + * + * @group Types + */ export interface RenderCellContentProps { column: CalculatedColumn; row: TRow; @@ -141,12 +354,26 @@ export interface RenderCellContentProps { onRowChange: (row: TRow) => void; } +/** + * Props passed to summary cell content renderers (`column.renderSummaryCell`). + * + * @see {@linkcode Column.renderSummaryCell | column.renderSummaryCell} + * + * @group Types + */ export interface RenderSummaryCellContentProps { column: CalculatedColumn; row: TSummaryRow; tabIndex: number; } +/** + * Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. + * + * @see {@linkcode Column.renderGroupCell | column.renderGroupCell}, {@linkcode renderToggleGroup} function, {@linkcode ToggleGroup | } + * + * @group Types + */ export interface RenderGroupCellContentProps { groupKey: unknown; column: CalculatedColumn; @@ -157,6 +384,29 @@ export interface RenderGroupCellContentProps { toggleGroup: () => void; } +/** + * Props passed to custom editors (`column.renderEditCell`). + * + * @example + * ```tsx + * import type { RenderEditCellContentProps } from 'react-data-grid'; + * + * function renderEditor({ row, column, onRowChange, onClose }: RenderEditCellContentProps) { + * return ( + * onRowChange({ ...row, [column.key]: event.target.value })} + * onBlur={() => onClose(true)} + * /> + * ); + * } + * ``` + * + * @see {@linkcode Column.renderEditCell | column.renderEditCell}, {@linkcode renderTextEditor} function + * + * @group Types + */ export interface RenderEditCellContentProps { column: CalculatedColumn; row: TRow; @@ -165,6 +415,13 @@ export interface RenderEditCellContentProps { onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; } +/** + * Props passed to custom header cell content renderers (`column.renderHeaderCell`). + * + * @see {@linkcode Column.renderHeaderCell | column.renderHeaderCell}, {@linkcode renderHeaderCell} function + * + * @group Types + */ export interface RenderHeaderCellContentProps { column: CalculatedColumn; sortDirection: SortDirection | undefined; @@ -183,6 +440,13 @@ interface BaseRenderCellProps setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; } +/** + * Props passed to the cell renderer when using `renderers.renderCell`. + * + * @see {@linkcode DataGridProps.renderers | renderers.renderCell}, {@linkcode Cell | } + * + * @group Types + */ export interface RenderCellProps extends BaseRenderCellProps { column: CalculatedColumn; row: TRow; @@ -202,6 +466,11 @@ export interface EditCellProps extends Pick< onKeyDown: Maybe<(args: EditCellKeyDownArgs, event: CellKeyboardEvent) => void>; } +/** + * Adds grid-specific methods to a React event. This helper type is not exported; the shape is shown for reference. + * + * @see {@linkcode CellMouseEvent}, {@linkcode CellKeyboardEvent} + */ export type CellEvent> = E & { /** Prevents the default grid behavior for this event */ preventGridDefault: () => void; @@ -209,12 +478,59 @@ export type CellEvent> = E & { isGridDefaultPrevented: () => boolean; }; +/** + * Extends `React.MouseEvent` with grid-specific methods. + * + * @example + * ```tsx + * import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; + * + * function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { + * if (args.column.key === 'actions') { + * event.preventGridDefault(); // Prevent cell focus + * } + * } + * ``` + * + * @see {@linkcode DataGridProps.onCellMouseDown | onCellMouseDown}, {@linkcode DataGridProps.onCellClick | onCellClick}, {@linkcode DataGridProps.onCellDoubleClick | onCellDoubleClick}, and {@linkcode DataGridProps.onCellContextMenu | onCellContextMenu} props on `` + * + * @group Types + */ export type CellMouseEvent = CellEvent>; +/** + * Extends `React.KeyboardEvent` with grid-specific methods. + * + * @see {@linkcode DataGridProps.onCellKeyDown | onCellKeyDown} prop on `` + * + * @group Types + */ export type CellKeyboardEvent = CellEvent>; +/** + * Type alias for `React.ClipboardEvent`. Used for copy and paste events. This helper type is not exported; the shape is shown for reference. + * + * @see {@linkcode DataGridProps.onCellCopy | onCellCopy} and {@linkcode DataGridProps.onCellPaste | onCellPaste} props on `` + */ export type CellClipboardEvent = React.ClipboardEvent; +/** + * Arguments passed to cell mouse event handlers. + * + * @example + * ```tsx + * import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; + * + * function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { + * console.log('Clicked cell at row', args.rowIdx, 'column', args.column.key); + * args.setActivePosition(true); // Focus and start editing + * } + * ``` + * + * @see {@linkcode DataGridProps.onCellMouseDown | onCellMouseDown}, {@linkcode DataGridProps.onCellClick | onCellClick}, {@linkcode DataGridProps.onCellDoubleClick | onCellDoubleClick}, and {@linkcode DataGridProps.onCellContextMenu | onCellContextMenu} props on `` + * + * @group Types + */ export interface CellMouseArgs { /** The column object of the cell. */ column: CalculatedColumn; @@ -247,10 +563,36 @@ export interface EditCellKeyDownArgs { onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; } +/** + * Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. + * + * @example + * ```tsx + * import type { CellKeyboardEvent, CellKeyDownArgs } from 'react-data-grid'; + * + * function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { + * if (args.mode === 'EDIT' && event.key === 'Escape') { + * args.onClose(false); // Close without committing + * event.preventGridDefault(); + * } + * } + * ``` + * + * @see {@linkcode DataGridProps.onCellKeyDown | onCellKeyDown} prop on `` + * + * @group Types + */ export type CellKeyDownArgs = | ActiveCellKeyDownArgs | EditCellKeyDownArgs; +/** + * Arguments passed to `onActivePositionChange`. + * + * @see {@linkcode DataGridProps.onActivePositionChange | onActivePositionChange} prop on `` + * + * @group Types + */ export interface PositionChangeArgs { /** row index of the active position */ rowIdx: number; @@ -266,6 +608,9 @@ export interface PositionChangeArgs { column: CalculatedColumn | undefined; } +/** + * Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. + */ export type CellMouseEventHandler = Maybe< (args: CellMouseArgs, NoInfer>, event: CellMouseEvent) => void >; @@ -297,6 +642,13 @@ export interface BaseRenderRowProps extends BaseRen gridRowStart: number; } +/** + * Props passed to custom row renderers. + * + * @see {@linkcode DataGridProps.renderers | renderers.renderRow}, {@linkcode Row | } + * + * @group Types + */ export interface RenderRowProps extends BaseRenderRowProps< TRow, TSummaryRow @@ -309,6 +661,13 @@ export interface RenderRowProps extends BaseRenderR isTreeGrid: boolean; } +/** + * Data provided to the `onRowsChange` callback. + * + * @see {@linkcode DataGridProps.onRowsChange | onRowsChange} prop on `` + * + * @group Types + */ export interface RowsChangeData { /** Indexes of the rows that changed */ indexes: number[]; @@ -316,16 +675,37 @@ export interface RowsChangeData { column: CalculatedColumn; } +/** + * Event object for row selection changes. + * + * @see {@linkcode useRowSelection} hook + * + * @group Types + */ export interface SelectRowEvent { row: TRow; checked: boolean; isShiftClick: boolean; } +/** + * Event object for header row selection changes. + * + * @see {@linkcode useHeaderRowSelection} hook + * + * @group Types + */ export interface SelectHeaderRowEvent { checked: boolean; } +/** + * Event object for drag-fill operations. + * + * @see {@linkcode DataGridProps.onFill | onFill} prop on `` + * + * @group Types + */ export interface FillEvent { columnKey: string; sourceRow: TRow; @@ -337,9 +717,28 @@ interface CellCopyPasteArgs { row: TRow; } +/** + * Arguments passed to `onCellCopy`. + * + * @see {@linkcode DataGridProps.onCellCopy | onCellCopy} prop on `` + * + * @group Types + */ export type CellCopyArgs = CellCopyPasteArgs; +/** + * Arguments passed to `onCellPaste`. + * + * @see {@linkcode DataGridProps.onCellPaste | onCellPaste} prop on `` + * + * @group Types + */ export type CellPasteArgs = CellCopyPasteArgs; +/** + * Represents a group row in `TreeDataGrid`. This helper type is not exported; the shape is shown for reference. + * + * @see {@linkcode RenderGroupCellContentProps}, {@linkcode RowHeightArgs}, {@linkcode TreeDataGrid | } + */ export interface GroupRow { readonly childRows: readonly TRow[]; readonly id: string; @@ -352,36 +751,127 @@ export interface GroupRow { readonly startRowIndex: number; } +/** + * Describes a sorted column. + * + * @see {@linkcode DataGridProps.sortColumns | sortColumns} and {@linkcode DataGridProps.onSortColumnsChange | onSortColumnsChange} props on `` + * + * @group Types + */ export interface SortColumn { readonly columnKey: string; readonly direction: SortDirection; } export type CellNavigationMode = 'NONE' | 'CHANGE_ROW'; +/** + * Whether a column is frozen, and on which edge. + * + * @see {@linkcode Column.frozen | column.frozen} + * + * @group Types + */ export type ColumnFrozen = boolean | 'start' | 'end'; +/** + * @see {@linkcode SortColumn} + * + * @group Types + */ export type SortDirection = 'ASC' | 'DESC'; +/** + * Arguments passed to the `colSpan` function. + * + * @example + * ```tsx + * import type { Column } from 'react-data-grid'; + * + * const columns: readonly Column[] = [ + * { + * key: 'title', + * name: 'Title', + * colSpan(args) { + * if (args.type === 'ROW' && args.row.isFullWidth) { + * return 3; // Span 3 columns + * } + * return undefined; + * } + * } + * ]; + * ``` + * + * @see {@linkcode Column.colSpan | column.colSpan} + * + * @group Types + */ export type ColSpanArgs = | { readonly type: 'HEADER' } | { readonly type: 'ROW'; readonly row: TRow } | { readonly type: 'SUMMARY'; readonly row: TSummaryRow }; +/** + * Arguments passed to `TreeDataGrid`'s `rowHeight` prop when it is a function. + * + * @example + * ```tsx + * function getRowHeight(args: RowHeightArgs): number { + * if (args.type === 'GROUP') { + * return 40; + * } + * return args.row.isLarge ? 60 : 35; + * } + * + * + * ``` + * + * @see {@linkcode TreeDataGridProps.rowHeight | rowHeight} prop on `` + * + * @group Types + */ export type RowHeightArgs = | { type: 'ROW'; row: TRow } | { type: 'GROUP'; row: GroupRow }; +/** + * Props for custom sort icon renderers. + * + * @see {@linkcode renderSortIcon} function + * + * @group Types + */ export interface RenderSortIconProps { /** The sort direction of the column, or `undefined` if it is not sorted */ sortDirection: SortDirection | undefined; } +/** + * Props for custom sort priority renderers. + * + * @see {@linkcode renderSortPriority} function + * + * @group Types + */ export interface RenderSortPriorityProps { /** The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise */ priority: number | undefined; } +/** + * Props for custom sort status renderers. + * + * @see {@linkcode DataGridProps.renderers | renderers.renderSortStatus} + * + * @group Types + */ export interface RenderSortStatusProps extends RenderSortIconProps, RenderSortPriorityProps {} +/** + * Props for custom checkbox renderers. + * + * @see {@linkcode renderCheckbox} function, {@linkcode DataGridProps.renderers | renderers.renderCheckbox}, {@linkcode SelectCheckbox | } + * + * @group Types + */ export interface RenderCheckboxProps { /** Whether the checkbox is checked */ checked?: boolean | undefined; @@ -399,6 +889,13 @@ export interface RenderCheckboxProps { 'aria-labelledby'?: string | undefined; } +/** + * Custom renderer configuration for the grid. + * + * @see {@linkcode DataGridProps.renderers | renderers} prop on ``, {@linkcode DataGridRenderersContext} + * + * @group Types + */ export interface Renderers { readonly renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; readonly renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>; @@ -407,11 +904,25 @@ export interface Renderers { readonly noRowsFallback?: Maybe; } +/** + * Options for programmatically updating the grid's active position. + * + * @see {@linkcode DataGridHandle}, {@linkcode CellKeyDownArgs} + * + * @group Types + */ export interface SetActivePositionOptions { enableEditor?: Maybe; shouldFocus?: Maybe; } +/** + * Represents a single column's width. + * + * @see {@linkcode ColumnWidths} + * + * @group Types + */ export interface ColumnWidth { /** `'resized'` if the user resized the column, or `'measured'` if the grid measured it */ readonly type: 'resized' | 'measured'; @@ -419,8 +930,22 @@ export interface ColumnWidth { readonly width: number; } +/** + * A map of column widths. + * + * @see {@linkcode DataGridProps.columnWidths | columnWidths} and {@linkcode DataGridProps.onColumnWidthsChange | onColumnWidthsChange} props on `` + * + * @group Types + */ export type ColumnWidths = ReadonlyMap; +/** + * Text direction of the grid. + * + * @see {@linkcode DataGridProps.direction | direction} prop on `` + * + * @group Types + */ export type Direction = 'ltr' | 'rtl'; export type ResizedWidth = number | 'max-content'; diff --git a/tsconfig.node.json b/tsconfig.node.json index 10fc8a24ca..6523361c29 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -3,7 +3,10 @@ "compilerOptions": { "lib": ["ESNext"], "module": "NodeNext", - "types": ["node"] + "types": ["node"], + // TODO: remove when TypeDoc supports TypeScript 7 + // TypeDoc's types import the TypeScript 6 API, which TypeScript 7 does not provide + "skipLibCheck": true }, - "include": ["eslint.config.ts"] + "include": ["eslint.config.ts", "scripts/**/*"] } diff --git a/typedoc.json b/typedoc.json new file mode 100644 index 0000000000..a0330141f4 --- /dev/null +++ b/typedoc.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://typedoc-plugin-markdown.org/schema.json", + "entryPoints": ["src/index.ts"], + "tsconfig": "tsconfig.src.json", + "plugin": ["typedoc-plugin-markdown", "typedoc-plugin-missing-exports"], + "placeInternalsInOwningModule": true, + "out": "node_modules/.cache/typedoc", + "router": "module", + "readme": "none", + "excludeExternals": true, + "disableSources": true, + "groupOrder": ["Components", "Hooks", "Render Functions", "Context", "Other", "Types", "*"], + "sort": ["source-order"], + "notRenderedTags": [ + "@showCategories", + "@showGroups", + "@hideCategories", + "@hideGroups", + "@disableGroups", + "@expand", + "@preventExpand", + "@expandType", + "@summary", + "@group", + "@groupDescription", + "@category", + "@categoryDescription", + "@sortStrategy" + ], + "hidePageHeader": true, + "hidePageTitle": true, + "hideBreadcrumbs": true, + "useCodeBlocks": true, + "expandParameters": true, + "parametersFormat": "table", + "useHTMLAnchors": true +} diff --git a/vite.config.ts b/vite.config.ts index 4fe6cec15b..797bf3e4bb 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -82,6 +82,12 @@ export default defineConfig({ command: 'tsc --build', cache: false }, + // generates the API reference of the README from the JSDoc comments + docs: { + command: ['node scripts/generateApiDocs.ts', 'vp fmt README.md'], + // the README is both an input and the output + cache: false + }, 'install-browsers': { command: isCI ? [ @@ -108,6 +114,8 @@ export default defineConfig({ // type check runs first, as type issues are often // the root cause of errors reported by later checks 'vp run typecheck', + 'vp run docs', + 'git diff --exit-code README.md', 'vp check', 'vp run eslint', 'vp pack', @@ -116,8 +124,9 @@ export default defineConfig({ 'vp run test' ], cache: { - // `vp pack` cleans `lib/` before writing to it - input: [{ auto: true }, '!lib/**'] + // `vp pack` cleans `lib/` before writing to it, + // and `vp run docs` writes its intermediate output to `node_modules/.cache/typedoc/` + input: [{ auto: true }, '!lib/**', '!node_modules/.cache/typedoc/**'] } }, // the first step of a release, see the header of `.github/workflows/publish.yml`: From 461e73851131bdacf0babd1f7e7a7727e0b64dc1 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 10:17:54 -0500 Subject: [PATCH 02/22] Lint JSDoc comments with oxlint Enable oxlint's `jsdoc` plugin, now that JSDoc comments are the source of the README's API reference. TypeDoc's tags are allowed by `jsdoc/check-tag-names`, and `@defaultValue` is preferred over `@default`. The rules that require types in comments are disabled, as TypeScript provides them. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- vite.config.ts | 53 ++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a77b89ddb7..9872f7ba32 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ website/ # demo site (Vite + TanStack Router) ## Conventions - **Public API** — all exports flow through `src/index.ts`. Keep `README.md` in sync with user-facing changes. -- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. Every export from `src/index.ts` needs a `@group` tag with one of the sections in `groupOrder` of `typedoc.json` (Components, Hooks, Render Functions, Context, Other, Types). Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. +- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. Every export from `src/index.ts` needs a `@group` tag with one of the sections in `groupOrder` of `typedoc.json` (Components, Hooks, Render Functions, Context, Other, Types). Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tags; add new TypeDoc tags to `definedTags` of `jsdoc/check-tag-names` in `vite.config.ts`. - **Docs** — keep `AGENTS.md` in sync with tooling, conventions, or architectural changes. - **Default renderers** — `DataGridRenderersContext` allows overriding default renderers (`renderCheckbox`, `renderSortStatus`, `renderRow`, `renderCell`, `noRowsFallback`) without prop-drilling. - **TypeScript strict** with `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, `erasableSyntaxOnly`. Distinguish missing properties from `undefined` values. diff --git a/vite.config.ts b/vite.config.ts index 797bf3e4bb..ef7ef91100 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -339,7 +339,7 @@ export default defineConfig({ lint: { ignorePatterns: ['/website/routeTree.gen.ts'], - plugins: ['eslint', 'oxc', 'react', 'typescript', 'unicorn', 'vitest'], + plugins: ['eslint', 'jsdoc', 'oxc', 'react', 'typescript', 'unicorn', 'vitest'], options: { denyWarnings: true, @@ -352,10 +352,18 @@ export default defineConfig({ builtin: true }, + settings: { + jsdoc: { + tagNamePreference: { + default: 'defaultValue' + } + } + }, + // https://oxc.rs/docs/guide/usage/linter/rules.html /* // copy all the rules from the rules table for easy pasting -const groups = new Set(['eslint', 'oxc', 'react', 'typescript', 'unicorn', 'vitest']); +const groups = new Set(['eslint', 'jsdoc', 'oxc', 'react', 'typescript', 'unicorn', 'vitest']); copy( Iterator.from(document.querySelectorAll('tbody tr')) .map((row) => [ @@ -560,6 +568,47 @@ copy( 'eslint/valid-typeof': ['warn', { requireStringLiterals: true }], 'eslint/vars-on-top': 'off', 'eslint/yoda': 'off', + 'jsdoc/check-access': 'warn', + 'jsdoc/check-property-names': 'warn', + 'jsdoc/check-tag-names': [ + 'warn', + { + // TypeDoc tags: https://typedoc.org/documents/Tags.html + definedTags: [ + 'category', + 'categoryDescription', + 'defaultValue', + 'group', + 'groupDescription', + 'inline', + 'inlineType', + 'internal', + 'module', + 'sortStrategy', + 'typeParam' + ] + } + ], + 'jsdoc/empty-tags': 'warn', + 'jsdoc/implements-on-classes': 'warn', + 'jsdoc/no-blank-blocks': 'warn', + 'jsdoc/no-defaults': 'warn', + 'jsdoc/require-param': 'off', + 'jsdoc/require-param-description': 'warn', + 'jsdoc/require-param-name': 'warn', + 'jsdoc/require-param-type': 'off', + 'jsdoc/require-property': 'warn', + 'jsdoc/require-property-description': 'warn', + 'jsdoc/require-property-name': 'warn', + 'jsdoc/require-property-type': 'off', + 'jsdoc/require-returns': 'off', + 'jsdoc/require-returns-description': 'warn', + 'jsdoc/require-returns-type': 'off', + 'jsdoc/require-throws-description': 'warn', + 'jsdoc/require-throws-type': 'off', + 'jsdoc/require-yields': 'warn', + 'jsdoc/require-yields-description': 'warn', + 'jsdoc/require-yields-type': 'off', 'oxc/approx-constant': 'warn', 'oxc/bad-array-method-on-arguments': 'warn', 'oxc/bad-bitwise-operator': 'warn', From 5529a785076380459b7edebc0a18176ddd36f8bd Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 10:45:56 -0500 Subject: [PATCH 03/22] Simplify the generated API reference Reduce the repetition of the generated API reference: - Remove the type parameter and parameter sections, which repeat the signatures and the "Generics" section - List the properties of interfaces in a table, unless a property has more than a short description - Only show the return type of functions with a `@returns` description - Remove the "Inherited from" and "Overrides" sections - Don't copy the comments of the members that `CalculatedColumn` redeclares Make the generator stricter: - Links from the hand-written README sections use the member they link to as link title, e.g. "Column.width", to keep their anchor up to date - Fail on links and anchors that don't match a heading - Use `github-slugger` for the heading anchors - Detect code fences by their character and length Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- README.md | 2309 +++++------------------------------- package-lock.json | 1 + package.json | 1 + scripts/generateApiDocs.ts | 194 ++- typedoc.json | 3 +- 6 files changed, 475 insertions(+), 2035 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9872f7ba32..6a0e9f7db6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ website/ # demo site (Vite + TanStack Router) ## Conventions - **Public API** — all exports flow through `src/index.ts`. Keep `README.md` in sync with user-facing changes. -- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. Every export from `src/index.ts` needs a `@group` tag with one of the sections in `groupOrder` of `typedoc.json` (Components, Hooks, Render Functions, Context, Other, Types). Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tags; add new TypeDoc tags to `definedTags` of `jsdoc/check-tag-names` in `vite.config.ts`. +- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. Every export from `src/index.ts` needs a `@group` tag with one of the sections in `groupOrder` of `typedoc.json` (Components, Hooks, Render Functions, Context, Other, Types). Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tags; add new TypeDoc tags to `definedTags` of `jsdoc/check-tag-names` in `vite.config.ts`. In the hand-written sections of the README, give links to API members the member as title, e.g., ``[`width`](#width "Column.width")``, so `vp run docs` keeps their anchor up to date. - **Docs** — keep `AGENTS.md` in sync with tooling, conventions, or architectural changes. - **Default renderers** — `DataGridRenderersContext` allows overriding default renderers (`renderCheckbox`, `renderSortStatus`, `renderRow`, `renderCell`, `noRowsFallback`) without prop-drilling. - **TypeScript strict** with `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, `erasableSyntaxOnly`. Distinguish missing properties from `undefined` values. diff --git a/README.md b/README.md index cc0cc2c2c3..2eacde3ce0 100644 --- a/README.md +++ b/README.md @@ -198,7 +198,7 @@ Example of customizing colors: ### Standard Props -The DataGrid accepts standard [`className`](#classname) and [`style`](#style) props: +The DataGrid accepts standard [`className`](#classname 'DataGridProps.className') and [`style`](#style 'DataGridProps.style') props: ```tsx (props: RenderCellProps) => Element; The default cell component. Can be wrapped via the `renderers.renderCell` prop. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `R` | -| `SR` | - -#### Parameters - -| Parameter | Type | -| --------- | -------------------------------------------------- | -| `props` | [`RenderCellProps`](#rendercellprops)\<`R`, `SR`\> | - -#### Returns - -`Element` - --- ### DataGrid() @@ -278,24 +261,6 @@ function DataGrid(props: DataGridProps | - -#### Returns - -`Element` - #### Example ```tsx @@ -306,14 +271,6 @@ Main API component to render a data grid of rows and columns ### DataGridProps -#### Type Parameters - -| Type Parameter | Default type | Description | -| ------------------- | ------------ | ---------------- | -| `R` | - | Row type | -| `SR` | `unknown` | Summary row type | -| `K` _extends_ `Key` | `Key` | Row key type | - #### Properties ##### ref? @@ -1062,23 +1019,6 @@ const Row: (props: RenderRowProps) => Element; The default row component. Can be wrapped via the `renderers.renderRow` prop. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `R` | -| `SR` | - -#### Parameters - -| Parameter | Type | -| --------- | ------------------------------------------------ | -| `props` | [`RenderRowProps`](#renderrowprops)\<`R`, `SR`\> | - -#### Returns - -`Element` - --- ### SelectCheckbox() @@ -1091,16 +1031,6 @@ A component for rendering row selection checkboxes. The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. -#### Parameters - -| Parameter | Type | -| ------------------- | --------------------------------------------- | -| `__namedParameters` | [`SelectCheckboxProps`](#selectcheckboxprops) | - -#### Returns - -`ReactNode` - --- ### ToggleGroup() @@ -1111,23 +1041,6 @@ function ToggleGroup(__namedParameters: RenderGroupCellContentProps | - -#### Returns - -`Element` - --- ### TreeDataGrid() @@ -1169,24 +1082,6 @@ The following `DataGrid` props are not supported in `TreeDataGrid`: - Cell copy/paste does not work on group rows - Column groups are not supported; `columns` must be `Column[]` -#### Type Parameters - -| Type Parameter | Default type | Description | -| ------------------- | ------------ | ---------------- | -| `R` | - | Row type | -| `SR` | `unknown` | Summary row type | -| `K` _extends_ `Key` | `Key` | Row key type | - -#### Parameters - -| Parameter | Type | -| ------------------- | ----------------------------------------------------------- | -| `__namedParameters` | [`TreeDataGridProps`](#treedatagridprops)\<`R`, `SR`, `K`\> | - -#### Returns - -`Element` - --- ### TreeDataGridProps @@ -1203,14 +1098,6 @@ All [`DataGridProps`](#datagridprops) are supported except those listed above. T \| `"onFill"` \| `"isRowSelectionDisabled"`\> -#### Type Parameters - -| Type Parameter | Default type | Description | -| ------------------- | ------------ | ---------------- | -| `R` | - | Row type | -| `SR` | `unknown` | Summary row type | -| `K` _extends_ `Key` | `Key` | Row key type | - #### Properties ##### columns @@ -1292,17 +1179,6 @@ function rowGrouper(rows: readonly Row[], columnKey: string): Record - ##### expandedGroupIds ```ts @@ -1336,16 +1212,6 @@ onExpandedGroupIdsChange: (expandedGroupIds: Set) => void; **Required.** Callback triggered when groups are expanded or collapsed. -###### Parameters - -| Parameter | Type | -| ------------------ | ------------------ | -| `expandedGroupIds` | `Set`\<`unknown`\> | - -###### Returns - -`void` - ##### groupIdGetter? ```ts @@ -1368,40 +1234,10 @@ Hook for managing header row selection state. Used within custom header cell ren #### Returns -`object` - - `isIndeterminate: boolean` - Whether some (but not all) rows are selected - `isRowSelected: boolean` - Whether all rows are selected - `onRowSelectionChange: (event: SelectHeaderRowEvent) => void` - Callback to change selection state -##### isIndeterminate - -```ts -isIndeterminate: boolean; -``` - -##### isRowSelected - -```ts -isRowSelected: boolean; -``` - -##### onRowSelectionChange - -```ts -onRowSelectionChange: (selectRowEvent: SelectHeaderRowEvent) => void; -``` - -###### Parameters - -| Parameter | Type | -| ---------------- | ----------------------------------------------- | -| `selectRowEvent` | [`SelectHeaderRowEvent`](#selectheaderrowevent) | - -###### Returns - -`void` - #### Example ```tsx @@ -1440,40 +1276,10 @@ Hook for managing row selection state. Used within custom cell renderers to impl #### Returns -`object` - - `isRowSelectionDisabled: boolean` - Whether selection is disabled for this row - `isRowSelected: boolean` - Whether this row is selected - `onRowSelectionChange: (event: SelectRowEvent) => void` - Callback to change selection state -##### isRowSelectionDisabled - -```ts -isRowSelectionDisabled: boolean; -``` - -##### isRowSelected - -```ts -isRowSelected: boolean; -``` - -##### onRowSelectionChange - -```ts -onRowSelectionChange: (selectRowEvent: SelectRowEvent) => void; -``` - -###### Parameters - -| Parameter | Type | -| ---------------- | -------------------------------------------- | -| `selectRowEvent` | [`SelectRowEvent`](#selectrowevent)\<`any`\> | - -###### Returns - -`void` - #### Example ```tsx @@ -1507,16 +1313,6 @@ function renderCheckbox(__namedParameters: RenderCheckboxProps): Element; Renders a checkbox input with proper styling and accessibility. -#### Parameters - -| Parameter | Type | -| ------------------- | --------------------------------------------- | -| `__namedParameters` | [`RenderCheckboxProps`](#rendercheckboxprops) | - -#### Returns - -`Element` - #### Example ```tsx @@ -1541,23 +1337,6 @@ function renderHeaderCell( The default header cell content renderer. Renders sortable columns with sort indicators. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `R` | -| `SR` | - -#### Parameters - -| Parameter | Type | -| ------------------- | ---------------------------------------------------------------------------- | -| `__namedParameters` | [`RenderHeaderCellContentProps`](#renderheadercellcontentprops)\<`R`, `SR`\> | - -#### Returns - -`string` \| `Element` - #### Example ```tsx @@ -1583,16 +1362,6 @@ function renderSortIcon(__namedParameters: RenderSortIconProps): Element | null; Renders the sort direction arrow icon. -#### Parameters - -| Parameter | Type | -| ------------------- | --------------------------------------------- | -| `__namedParameters` | [`RenderSortIconProps`](#rendersorticonprops) | - -#### Returns - -`Element` \| `null` - --- ### renderSortPriority() @@ -1603,16 +1372,6 @@ function renderSortPriority(__namedParameters: RenderSortPriorityProps): number Renders the sort priority number for multi-column sorting. -#### Parameters - -| Parameter | Type | -| ------------------- | ----------------------------------------------------- | -| `__namedParameters` | [`RenderSortPriorityProps`](#rendersortpriorityprops) | - -#### Returns - -`number` \| `undefined` - --- ### renderTextEditor() @@ -1625,23 +1384,6 @@ function renderTextEditor( A basic text editor provided for convenience. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `TRow` | -| `TSummaryRow` | - -#### Parameters - -| Parameter | Type | -| ------------------- | ------------------------------------------------------------------------------------ | -| `__namedParameters` | [`RenderEditCellContentProps`](#rendereditcellcontentprops)\<`TRow`, `TSummaryRow`\> | - -#### Returns - -`Element` - #### Example ```tsx @@ -1666,23 +1408,6 @@ function renderToggleGroup(props: RenderGroupCellContentProps): El The default group cell content renderer for the columns used for grouping (`groupBy` prop). This renders the expand/collapse toggle. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `R` | -| `SR` | - -#### Parameters - -| Parameter | Type | -| --------- | -------------------------------------------------------------------------- | -| `props` | [`RenderGroupCellContentProps`](#rendergroupcellcontentprops)\<`R`, `SR`\> | - -#### Returns - -`Element` - #### Example ```tsx @@ -1707,23 +1432,6 @@ function renderValue(props: RenderCellContentProps): ReactNode; The default cell content renderer that renders the value of `row[column.key]`. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `R` | -| `SR` | - -#### Parameters - -| Parameter | Type | -| --------- | ---------------------------------------------------------------- | -| `props` | [`RenderCellContentProps`](#rendercellcontentprops)\<`R`, `SR`\> | - -#### Returns - -`ReactNode` - #### Example ```tsx @@ -1840,479 +1548,162 @@ Extends `Column` with additional computed properties used internally by the grid #### See -[`Column`](#column-1), [`onColumnResize`](#oncolumnresize) prop on `` +[`Column`](#column), [`onColumnResize`](#oncolumnresize) prop on `` #### Extends -- [`Column`](#column-1)\<`TRow`, `TSummaryRow`\> +- [`Column`](#column)\<`TRow`, `TSummaryRow`\> -#### Type Parameters +#### Properties -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | +| Property | Modifier | Type | Description | Overrides | +| ------------------ | ---------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | +| `parent` | `readonly` | \| [`CalculatedColumnParent`](#calculatedcolumnparent)\<`TRow`, `TSummaryRow`\> \| `undefined` | The column group that contains the column, or `undefined` if the column is not in a group | - | +| `idx` | `readonly` | `number` | The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` | - | +| `level` | `readonly` | `number` | Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups | - | +| `width` | `readonly` | `string` \| `number` | - | | +| `minWidth` | `readonly` | `number` | - | | +| `maxWidth` | `readonly` | `number` \| `undefined` | - | | +| `resizable` | `readonly` | `boolean` | - | | +| `sortable` | `readonly` | `boolean` | - | | +| `draggable` | `readonly` | `boolean` | - | | +| `frozen` | `readonly` | [`ColumnFrozen`](#columnfrozen) | - | | +| `renderCell` | `readonly` | (`props`: [`RenderCellContentProps`](#rendercellcontentprops)\<`TRow`, `TSummaryRow`\>) => `ReactNode` | - | | +| `renderHeaderCell` | `readonly` | (`props`: [`RenderHeaderCellContentProps`](#renderheadercellcontentprops)\<`TRow`, `TSummaryRow`\>) => `ReactNode` | - | | -#### Properties +--- -##### parent +### CalculatedColumnOrColumnGroup ```ts -readonly parent: - | CalculatedColumnParent - | undefined; +type CalculatedColumnOrColumnGroup = CalculatedColumnParent | CalculatedColumn; ``` -The column group that contains the column, or `undefined` if the column is not in a group +Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. -##### idx +#### See -```ts -readonly idx: number; -``` +[`CalculatedColumn`](#calculatedcolumn), [`CalculatedColumnParent`](#calculatedcolumnparent) -The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` +--- -##### level +### CalculatedColumnParent -```ts -readonly level: number; -``` +Represents a parent column group in the calculated column structure. -Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups +#### See -##### width +[`CalculatedColumn`](#calculatedcolumn) -```ts -readonly width: string | number; -``` +#### Properties -Width can be any valid CSS grid column value. If not specified, it will be determined automatically based on grid width and specified widths of other columns. +| Property | Modifier | Type | +| ------------------ | ---------- | ---------------------------------------------------------------------------------------- | +| `name` | `readonly` | \| `string` \| `ReactElement`\<`unknown`, `string` \| `JSXElementConstructor`\<`any`\>\> | +| `parent` | `readonly` | \| [`CalculatedColumnParent`](#calculatedcolumnparent)\<`R`, `SR`\> \| `undefined` | +| `idx` | `readonly` | `number` | +| `colSpan` | `readonly` | `number` | +| `level` | `readonly` | `number` | +| `headerCellClass?` | `readonly` | [`Maybe`](#maybe)\<`string`\> | -```tsx -const columns: Column[] = [ - { - key: 'id', - name: 'ID', - width: 80, // Fixed width in pixels - resizable: false - }, - { - key: 'name', - name: 'Name', - width: '30%', // Percentage width - minWidth: 100, - maxWidth: 400 - }, - { - key: 'description', - name: 'Description' - // No width specified - automatically sized - } -]; -``` +--- -Other examples: +### CellCopyArgs -```tsx -width: 80, // pixels -width: '25%', -width: 'max-content', -width: 'minmax(100px, max-content)', +```ts +type CellCopyArgs = CellCopyPasteArgs; ``` -`max-content` can be used to expand the column to show all the content. Note that the grid is only able to calculate column width for visible rows. - -###### Default Value +Arguments passed to `onCellCopy`. -`auto` +#### See -###### Overrides +[`onCellCopy`](#oncellcopy) prop on `` -[`Column`](#column-1).[`width`](#width-1) +--- -##### minWidth +### CellKeyboardEvent ```ts -readonly minWidth: number; +type CellKeyboardEvent = CellEvent>; ``` -Minimum column width in pixels. - -###### Default Value +Extends `React.KeyboardEvent` with grid-specific methods. -`50` pixels +#### See -###### Overrides +[`onCellKeyDown`](#oncellkeydown) prop on `` -[`Column`](#column-1).[`minWidth`](#minwidth-1) +--- -##### maxWidth +### CellKeyDownArgs ```ts -readonly maxWidth: number | undefined; +type CellKeyDownArgs = + | ActiveCellKeyDownArgs + | EditCellKeyDownArgs; ``` -Maximum column width in pixels. - -###### Overrides +Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. -[`Column`](#column-1).[`maxWidth`](#maxwidth-1) +#### Example -##### resizable +```tsx +import type { CellKeyboardEvent, CellKeyDownArgs } from 'react-data-grid'; -```ts -readonly resizable: boolean; +function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { + if (args.mode === 'EDIT' && event.key === 'Escape') { + args.onClose(false); // Close without committing + event.preventGridDefault(); + } +} ``` -Enable resizing of the column. +#### See -###### Default Value +[`onCellKeyDown`](#oncellkeydown) prop on `` -`false` +--- + +### CellMouseArgs -###### Overrides +Arguments passed to cell mouse event handlers. -[`Column`](#column-1).[`resizable`](#resizable-1) +#### Example -##### sortable +```tsx +import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; -```ts -readonly sortable: boolean; +function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { + console.log('Clicked cell at row', args.rowIdx, 'column', args.column.key); + args.setActivePosition(true); // Focus and start editing +} ``` -Enable sorting of the column. +#### See -###### Default Value +[`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` -`false` +#### Properties -###### Overrides +| Property | Type | Description | +| ------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------ | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | The column object of the cell. | +| `row` | `TRow` | The row object of the cell. | +| `rowIdx` | `number` | The row index of the cell. | +| `setActivePosition` | (`enableEditor?`: `boolean`) => `void` | Function to manually focus the cell. Pass `true` to immediately start editing. | -[`Column`](#column-1).[`sortable`](#sortable-1) +--- -##### draggable +### CellMouseEvent ```ts -readonly draggable: boolean; +type CellMouseEvent = CellEvent>; ``` -Enable dragging of the column. - -###### Default Value +Extends `React.MouseEvent` with grid-specific methods. -`false` - -###### Overrides - -[`Column`](#column-1).[`draggable`](#draggable-1) - -##### frozen - -```ts -readonly frozen: ColumnFrozen; -``` - -Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. See the [`ColumnFrozen`](#columnfrozen) type. - -- `'start'` (or `true` for backward compatibility) — pins the column to the start edge (left in LTR, right in RTL). -- `'end'` — pins the column to the end edge (right in LTR, left in RTL). -- `false` (default) — the column scrolls with the rest of the grid. - -```tsx -const columns: readonly Column[] = [ - { key: 'id', name: 'ID', frozen: 'start' }, - { key: 'name', name: 'Name' }, - { key: 'actions', name: 'Actions', frozen: 'end' } -]; -``` - -###### Default Value - -`false` - -###### Overrides - -[`Column`](#column-1).[`frozen`](#frozen-1) - -##### renderCell - -```ts -readonly renderCell: (props: RenderCellContentProps) => ReactNode; -``` - -Render function to render the content of cells. - -###### Parameters - -| Parameter | Type | -| --------- | ---------------------------------------------------------------------------- | -| `props` | [`RenderCellContentProps`](#rendercellcontentprops)\<`TRow`, `TSummaryRow`\> | - -###### Returns - -`ReactNode` - -###### Overrides - -[`Column`](#column-1).[`renderCell`](#rendercell-1) - -##### renderHeaderCell - -```ts -readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; -``` - -Render function to render the content of the header cell. - -###### Parameters - -| Parameter | Type | -| --------- | ---------------------------------------------------------------------------------------- | -| `props` | [`RenderHeaderCellContentProps`](#renderheadercellcontentprops)\<`TRow`, `TSummaryRow`\> | - -###### Returns - -`ReactNode` - -###### Overrides - -[`Column`](#column-1).[`renderHeaderCell`](#renderheadercell-2) - ---- - -### CalculatedColumnOrColumnGroup - -```ts -type CalculatedColumnOrColumnGroup = CalculatedColumnParent | CalculatedColumn; -``` - -Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. - -#### Type Parameters - -| Type Parameter | -| -------------- | -| `R` | -| `SR` | - -#### See - -[`CalculatedColumn`](#calculatedcolumn), [`CalculatedColumnParent`](#calculatedcolumnparent) - ---- - -### CalculatedColumnParent - -Represents a parent column group in the calculated column structure. - -#### See - -[`CalculatedColumn`](#calculatedcolumn) - -#### Type Parameters - -| Type Parameter | -| -------------- | -| `R` | -| `SR` | - -#### Properties - -##### name - -```ts -readonly name: - | string -| ReactElement>; -``` - -##### parent - -```ts -readonly parent: - | CalculatedColumnParent - | undefined; -``` - -##### idx - -```ts -readonly idx: number; -``` - -##### colSpan - -```ts -readonly colSpan: number; -``` - -##### level - -```ts -readonly level: number; -``` - -##### headerCellClass? - -```ts -readonly headerCellClass?: Maybe; -``` - ---- - -### CellCopyArgs - -```ts -type CellCopyArgs = CellCopyPasteArgs; -``` - -Arguments passed to `onCellCopy`. - -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - -#### See - -[`onCellCopy`](#oncellcopy) prop on `` - ---- - -### CellKeyboardEvent - -```ts -type CellKeyboardEvent = CellEvent>; -``` - -Extends `React.KeyboardEvent` with grid-specific methods. - -#### See - -[`onCellKeyDown`](#oncellkeydown) prop on `` - ---- - -### CellKeyDownArgs - -```ts -type CellKeyDownArgs = - | ActiveCellKeyDownArgs - | EditCellKeyDownArgs; -``` - -Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. - -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - -#### Example - -```tsx -import type { CellKeyboardEvent, CellKeyDownArgs } from 'react-data-grid'; - -function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { - if (args.mode === 'EDIT' && event.key === 'Escape') { - args.onClose(false); // Close without committing - event.preventGridDefault(); - } -} -``` - -#### See - -[`onCellKeyDown`](#oncellkeydown) prop on `` - ---- - -### CellMouseArgs - -Arguments passed to cell mouse event handlers. - -#### Example - -```tsx -import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; - -function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { - console.log('Clicked cell at row', args.rowIdx, 'column', args.column.key); - args.setActivePosition(true); // Focus and start editing -} -``` - -#### See - -[`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` - -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - -#### Properties - -##### column - -```ts -column: CalculatedColumn; -``` - -The column object of the cell. - -##### row - -```ts -row: TRow; -``` - -The row object of the cell. - -##### rowIdx - -```ts -rowIdx: number; -``` - -The row index of the cell. - -##### setActivePosition - -```ts -setActivePosition: (enableEditor?: boolean) => void; -``` - -Function to manually focus the cell. Pass `true` to immediately start editing. - -###### Parameters - -| Parameter | Type | -| --------------- | --------- | -| `enableEditor?` | `boolean` | - -###### Returns - -`void` - ---- - -### CellMouseEvent - -```ts -type CellMouseEvent = CellEvent>; -``` - -Extends `React.MouseEvent` with grid-specific methods. - -#### Example +#### Example ```tsx import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; @@ -2338,13 +1729,6 @@ type CellPasteArgs = CellCopyPasteArgs` @@ -2370,13 +1754,6 @@ type ColSpanArgs = Arguments passed to the `colSpan` function. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `TRow` | -| `TSummaryRow` | - #### Example ```tsx @@ -2398,7 +1775,7 @@ const columns: readonly Column[] = [ #### See -[`column.colSpan`](#colspan-1) +[`column.colSpan`](#colspan) --- @@ -2414,13 +1791,6 @@ Defines the configuration for a column in the grid. - [`CalculatedColumn`](#calculatedcolumn) -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - #### Properties ##### name @@ -2728,7 +2098,7 @@ Whether a column is frozen, and on which edge. #### See -[`column.frozen`](#frozen-1) +[`column.frozen`](#frozen) --- @@ -2756,54 +2126,24 @@ const columns: readonly ColumnOrColumnGroup[] = [ [`ColumnOrColumnGroup`](#columnorcolumngroup) -#### Type Parameters +#### Properties -| Type Parameter | Default type | -| -------------- | ------------ | -| `R` | - | -| `SR` | `unknown` | +| Property | Modifier | Type | Description | +| ------------------ | ---------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | +| `name` | `readonly` | \| `string` \| `ReactElement`\<`unknown`, `string` \| `JSXElementConstructor`\<`any`\>\> | The name of the column group. It will be displayed in the header cell | +| `headerCellClass?` | `readonly` | [`Maybe`](#maybe)\<`string`\> | - | +| `children` | `readonly` | readonly [`ColumnOrColumnGroup`](#columnorcolumngroup)\<`R`, `SR`\>[] | - | -#### Properties +--- -##### name +### ColumnOrColumnGroup ```ts -readonly name: - | string -| ReactElement>; -``` - -The name of the column group. It will be displayed in the header cell - -##### headerCellClass? - -```ts -readonly headerCellClass?: Maybe; -``` - -##### children - -```ts -readonly children: readonly ColumnOrColumnGroup[]; -``` - ---- - -### ColumnOrColumnGroup - -```ts -type ColumnOrColumnGroup = Column | ColumnGroup; +type ColumnOrColumnGroup = Column | ColumnGroup; ``` Union type representing either a `Column` or a `ColumnGroup`. -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `R` | - | -| `SR` | `unknown` | - #### See [`columns`](#columns) prop on `` @@ -2820,21 +2160,10 @@ Represents a single column's width. #### Properties -##### type - -```ts -readonly type: "resized" | "measured"; -``` - -`'resized'` if the user resized the column, or `'measured'` if the grid measured it - -##### width - -```ts -readonly width: number; -``` - -The width in pixels +| Property | Modifier | Type | Description | +| -------- | ---------- | --------------------------- | ----------------------------------------------------------------------------------- | +| `type` | `readonly` | `"resized"` \| `"measured"` | `'resized'` if the user resized the column, or `'measured'` if the grid measured it | +| `width` | `readonly` | `number` | The width in pixels | --- @@ -2879,44 +2208,11 @@ function MyGrid() { #### Properties -##### element - -```ts -element: HTMLDivElement | null; -``` - -##### scrollToCell - -```ts -scrollToCell: (position: PartialPosition) => void; -``` - -###### Parameters - -| Parameter | Type | -| ---------- | ------------------------------------- | -| `position` | [`PartialPosition`](#partialposition) | - -###### Returns - -`void` - -##### setActivePosition - -```ts -setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -``` - -###### Parameters - -| Parameter | Type | -| ---------- | ------------------------------------------------------- | -| `position` | [`Position`](#position) | -| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | - -###### Returns - -`void` +| Property | Type | +| ------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `element` | `HTMLDivElement` \| `null` | +| `scrollToCell` | (`position`: [`PartialPosition`](#partialposition)) => `void` | +| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | --- @@ -2938,13 +2234,6 @@ type DefaultColumnOptions = Pick< Default options applied to all columns. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `R` | -| `SR` | - #### See [`defaultColumnOptions`](#defaultcolumnoptions) prop on `` @@ -2973,31 +2262,13 @@ Event object for drag-fill operations. [`onFill`](#onfill) prop on `` -#### Type Parameters - -| Type Parameter | -| -------------- | -| `TRow` | - #### Properties -##### columnKey - -```ts -columnKey: string; -``` - -##### sourceRow - -```ts -sourceRow: TRow; -``` - -##### targetRow - -```ts -targetRow: TRow; -``` +| Property | Type | +| ----------- | -------- | +| `columnKey` | `string` | +| `sourceRow` | `TRow` | +| `targetRow` | `TRow` | --- @@ -3009,42 +2280,13 @@ Arguments passed to `onActivePositionChange`. [`onActivePositionChange`](#onactivepositionchange) prop on `` -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - #### Properties -##### rowIdx - -```ts -rowIdx: number; -``` - -row index of the active position - -##### row - -```ts -row: TRow | undefined; -``` - -row object of the active position, -undefined if the active position is on a header or summary row - -##### column - -```ts -column: - | CalculatedColumn - | undefined; -``` - -column object of the active position, -undefined if the active position is a row instead of a cell +| Property | Type | Description | +| -------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `rowIdx` | `number` | row index of the active position | +| `row` | `TRow` \| `undefined` | row object of the active position, undefined if the active position is on a header or summary row | +| `column` | \| [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> \| `undefined` | column object of the active position, undefined if the active position is a row instead of a cell | --- @@ -3069,62 +2311,18 @@ function renderCell({ row, column, onRowChange }: RenderCellContentProps) #### See -[`column.renderCell`](#rendercell-1), [`renderValue`](#rendervalue) function - -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | +[`column.renderCell`](#rendercell), [`renderValue`](#rendervalue) function #### Properties -##### column - -```ts -column: CalculatedColumn; -``` - -##### row - -```ts -row: TRow; -``` - -##### rowIdx - -```ts -rowIdx: number; -``` - -##### isCellEditable - -```ts -isCellEditable: boolean; -``` - -##### tabIndex - -```ts -tabIndex: number; -``` - -##### onRowChange - -```ts -onRowChange: (row: TRow) => void; -``` - -###### Parameters - -| Parameter | Type | -| --------- | ------ | -| `row` | `TRow` | - -###### Returns - -`void` +| Property | Type | +| ---------------- | ---------------------------------------------------------------- | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | +| `row` | `TRow` | +| `rowIdx` | `number` | +| `isCellEditable` | `boolean` | +| `tabIndex` | `number` | +| `onRowChange` | (`row`: `TRow`) => `void` | --- @@ -3140,13 +2338,6 @@ Props passed to the cell renderer when using `renderers.renderCell`. - [`BaseRenderCellProps`](#baserendercellprops)\<`TRow`, `TSummaryRow`\> -#### Type Parameters - -| Type Parameter | -| -------------- | -| `TRow` | -| `TSummaryRow` | - #### Properties ##### onCellMouseDown? @@ -3167,10 +2358,6 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -`BaseRenderCellProps.onCellMouseDown` - ##### onCellClick? ```ts @@ -3191,10 +2378,6 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -`BaseRenderCellProps.onCellClick` - ##### onCellDoubleClick? ```ts @@ -3213,10 +2396,6 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -`BaseRenderCellProps.onCellDoubleClick` - ##### onCellContextMenu? ```ts @@ -3236,41 +2415,18 @@ function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -`BaseRenderCellProps.onCellContextMenu` - ##### rowIdx ```ts rowIdx: number; ``` -###### Inherited from - -[`BaseRenderCellProps`](#baserendercellprops).[`rowIdx`](#rowidx-7) - ##### setActivePosition ```ts setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; ``` -###### Parameters - -| Parameter | Type | -| ---------- | ------------------------------------------------------- | -| `position` | [`Position`](#position) | -| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | - -###### Returns - -`void` - -###### Inherited from - -[`BaseRenderCellProps`](#baserendercellprops).[`setActivePosition`](#setactiveposition-5) - ##### column ```ts @@ -3307,18 +2463,6 @@ isCellActive: boolean; onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: TRow) => void; ``` -###### Parameters - -| Parameter | Type | -| --------- | ---------------------------------------------------------------- | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | -| `rowIdx` | `number` | -| `newRow` | `TRow` | - -###### Returns - -`void` - --- ### RenderCheckboxProps @@ -3331,72 +2475,15 @@ Props for custom checkbox renderers. #### Properties -##### checked? - -```ts -checked?: boolean; -``` - -Whether the checkbox is checked - -##### indeterminate? - -```ts -indeterminate?: boolean; -``` - -Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected - -##### disabled? - -```ts -disabled?: boolean; -``` - -Whether the checkbox is disabled - -##### onChange - -```ts -onChange: (checked: boolean, shift: boolean) => void; -``` - -Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows - -###### Parameters - -| Parameter | Type | -| --------- | --------- | -| `checked` | `boolean` | -| `shift` | `boolean` | - -###### Returns - -`void` - -##### tabIndex? - -```ts -tabIndex?: number; -``` - -`0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox - -##### aria-label? - -```ts -"aria-label"?: string; -``` - -Accessible label for the checkbox - -##### aria-labelledby? - -```ts -"aria-labelledby"?: string; -``` - -ID of the element that labels the checkbox +| Property | Type | Description | +| ------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | +| `checked?` | `boolean` | Whether the checkbox is checked | +| `indeterminate?` | `boolean` | Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected | +| `disabled?` | `boolean` | Whether the checkbox is disabled | +| `onChange` | (`checked`: `boolean`, `shift`: `boolean`) => `void` | Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows | +| `tabIndex?` | `number` | `0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox | +| `aria-label?` | `string` | Accessible label for the checkbox | +| `aria-labelledby?` | `string` | ID of the element that labels the checkbox | --- @@ -3425,278 +2512,120 @@ function renderEditor({ row, column, onRowChange, onClose }: RenderEditCellConte [`column.renderEditCell`](#rendereditcell), [`renderTextEditor`](#rendertexteditor) function -#### Type Parameters +#### Properties -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | +| Property | Type | +| ------------- | ------------------------------------------------------------------ | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | +| `row` | `TRow` | +| `rowIdx` | `number` | +| `onRowChange` | (`row`: `TRow`, `commitChanges?`: `boolean`) => `void` | +| `onClose` | (`commitChanges?`: `boolean`, `shouldFocus?`: `boolean`) => `void` | -#### Properties +--- -##### column +### Renderers -```ts -column: CalculatedColumn; -``` +Custom renderer configuration for the grid. -##### row +#### See -```ts -row: TRow; -``` +[`renderers`](#renderers) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) -##### rowIdx +#### Properties -```ts -rowIdx: number; -``` +| Property | Modifier | Type | +| ------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------- | +| `renderCell?` | `readonly` | [`Maybe`](#maybe)\<(`key`: `Key`, `props`: [`RenderCellProps`](#rendercellprops)\<`TRow`, `TSummaryRow`\>) => `ReactNode`\> | +| `renderCheckbox?` | `readonly` | [`Maybe`](#maybe)\<(`props`: [`RenderCheckboxProps`](#rendercheckboxprops)) => `ReactNode`\> | +| `renderRow?` | `readonly` | [`Maybe`](#maybe)\<(`key`: `Key`, `props`: [`RenderRowProps`](#renderrowprops)\<`TRow`, `TSummaryRow`\>) => `ReactNode`\> | +| `renderSortStatus?` | `readonly` | [`Maybe`](#maybe)\<(`props`: [`RenderSortStatusProps`](#rendersortstatusprops)) => `ReactNode`\> | +| `noRowsFallback?` | `readonly` | `ReactNode` | -##### onRowChange +--- -```ts -onRowChange: (row: TRow, commitChanges?: boolean) => void; -``` +### RenderGroupCellContentProps + +Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. -###### Parameters +#### See + +[`column.renderGroupCell`](#rendergroupcell), [`renderToggleGroup`](#rendertogglegroup) function, [``](#togglegroup) -| Parameter | Type | -| ---------------- | --------- | -| `row` | `TRow` | -| `commitChanges?` | `boolean` | +#### Properties -###### Returns +| Property | Type | +| ------------- | ---------------------------------------------------------------- | +| `groupKey` | `unknown` | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | +| `row` | [`GroupRow`](#grouprow)\<`TRow`\> | +| `childRows` | readonly `TRow`[] | +| `isExpanded` | `boolean` | +| `tabIndex` | `number` | +| `toggleGroup` | () => `void` | -`void` +--- -##### onClose +### RenderHeaderCellContentProps -```ts -onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; -``` +Props passed to custom header cell content renderers (`column.renderHeaderCell`). -###### Parameters +#### See -| Parameter | Type | -| ---------------- | --------- | -| `commitChanges?` | `boolean` | -| `shouldFocus?` | `boolean` | +[`column.renderHeaderCell`](#renderheadercell-1), [`renderHeaderCell`](#renderheadercell) function -###### Returns +#### Properties -`void` +| Property | Type | +| --------------- | ---------------------------------------------------------------- | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | +| `sortDirection` | [`SortDirection`](#sortdirection) \| `undefined` | +| `priority` | `number` \| `undefined` | +| `tabIndex` | `number` | --- -### Renderers +### RenderRowProps -Custom renderer configuration for the grid. +Props passed to custom row renderers. #### See -[`renderers`](#renderers) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) +[`renderers.renderRow`](#renderers), [``](#row) -#### Type Parameters +#### Extends -| Type Parameter | -| -------------- | -| `TRow` | -| `TSummaryRow` | +- [`BaseRenderRowProps`](#baserenderrowprops)\<`TRow`, `TSummaryRow`\> #### Properties -##### renderCell? +##### onCellMouseDown? ```ts -readonly renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; +onCellMouseDown?: CellMouseEventHandler; ``` -##### renderCheckbox? - -```ts -readonly renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>; -``` +Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. -##### renderRow? +```tsx +function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'id') { + event.preventGridDefault(); + } +} -```ts -readonly renderRow?: Maybe<(key: Key, props: RenderRowProps) => ReactNode>; +; ``` -##### renderSortStatus? +##### onCellClick? ```ts -readonly renderSortStatus?: Maybe<(props: RenderSortStatusProps) => ReactNode>; +onCellClick?: CellMouseEventHandler; ``` -##### noRowsFallback? +Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. -```ts -readonly noRowsFallback?: ReactNode; -``` - ---- - -### RenderGroupCellContentProps - -Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. - -#### See - -[`column.renderGroupCell`](#rendergroupcell), [`renderToggleGroup`](#rendertogglegroup) function, [``](#togglegroup) - -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - -#### Properties - -##### groupKey - -```ts -groupKey: unknown; -``` - -##### column - -```ts -column: CalculatedColumn; -``` - -##### row - -```ts -row: GroupRow; -``` - -##### childRows - -```ts -childRows: readonly TRow[]; -``` - -##### isExpanded - -```ts -isExpanded: boolean; -``` - -##### tabIndex - -```ts -tabIndex: number; -``` - -##### toggleGroup - -```ts -toggleGroup: () => void; -``` - -###### Returns - -`void` - ---- - -### RenderHeaderCellContentProps - -Props passed to custom header cell content renderers (`column.renderHeaderCell`). - -#### See - -[`column.renderHeaderCell`](#renderheadercell-2), [`renderHeaderCell`](#renderheadercell) function - -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - -#### Properties - -##### column - -```ts -column: CalculatedColumn; -``` - -##### sortDirection - -```ts -sortDirection: SortDirection | undefined; -``` - -##### priority - -```ts -priority: number | undefined; -``` - -##### tabIndex - -```ts -tabIndex: number; -``` - ---- - -### RenderRowProps - -Props passed to custom row renderers. - -#### See - -[`renderers.renderRow`](#renderers), [``](#row) - -#### Extends - -- [`BaseRenderRowProps`](#baserenderrowprops)\<`TRow`, `TSummaryRow`\> - -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - -#### Properties - -##### onCellMouseDown? - -```ts -onCellMouseDown?: CellMouseEventHandler; -``` - -Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -```tsx -function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - event.preventGridDefault(); - } -} - -; -``` - -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`onCellMouseDown`](#oncellmousedown-3) - -##### onCellClick? - -```ts -onCellClick?: CellMouseEventHandler; -``` - -Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -This event can be used to open the cell editor on a single click: +This event can be used to open the cell editor on a single click: ```tsx function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { @@ -3708,10 +2637,6 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`onCellClick`](#oncellclick-3) - ##### onCellDoubleClick? ```ts @@ -3730,10 +2655,6 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`onCellDoubleClick`](#oncelldoubleclick-3) - ##### onCellContextMenu? ```ts @@ -3753,91 +2674,48 @@ function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`onCellContextMenu`](#oncellcontextmenu-3) - ##### setActivePosition ```ts setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; ``` -###### Parameters - -| Parameter | Type | -| ---------- | ------------------------------------------------------- | -| `position` | [`Position`](#position) | -| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | - -###### Returns - -`void` - -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`setActivePosition`](#setactiveposition-6) - ##### iterateOverViewportColumnsForRow ```ts iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; ``` -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`iterateOverViewportColumnsForRow`](#iterateoverviewportcolumnsforrow-1) - ##### rowIdx ```ts rowIdx: number; ``` -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`rowIdx`](#rowidx-8) - ##### activeCellIdx ```ts activeCellIdx: number | undefined; ``` -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`activeCellIdx`](#activecellidx-1) - ##### isRowSelectionDisabled ```ts isRowSelectionDisabled: boolean; ``` -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`isRowSelectionDisabled`](#isrowselectiondisabled-3) - ##### isRowSelected ```ts isRowSelected: boolean; ``` -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`isRowSelected`](#isrowselected-3) - ##### gridRowStart ```ts gridRowStart: number; ``` -###### Inherited from - -[`BaseRenderRowProps`](#baserenderrowprops).[`gridRowStart`](#gridrowstart-1) - ##### row ```ts @@ -3864,18 +2742,6 @@ activeCellEditor: onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: TRow) => void; ``` -###### Parameters - -| Parameter | Type | -| --------- | ---------------------------------------------------------------- | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | -| `rowIdx` | `number` | -| `newRow` | `TRow` | - -###### Returns - -`void` - ##### rowClass ```ts @@ -3904,13 +2770,9 @@ Props for custom sort icon renderers. #### Properties -##### sortDirection - -```ts -sortDirection: SortDirection | undefined; -``` - -The sort direction of the column, or `undefined` if it is not sorted +| Property | Type | Description | +| --------------- | ------------------------------------------------ | -------------------------------------------------------------------- | +| `sortDirection` | [`SortDirection`](#sortdirection) \| `undefined` | The sort direction of the column, or `undefined` if it is not sorted | --- @@ -3928,13 +2790,9 @@ Props for custom sort priority renderers. #### Properties -##### priority - -```ts -priority: number | undefined; -``` - -The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise +| Property | Type | Description | +| ---------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `priority` | `number` \| `undefined` | The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise | --- @@ -3963,32 +2821,13 @@ Props passed to summary cell content renderers (`column.renderSummaryCell`). [`column.renderSummaryCell`](#rendersummarycell) -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TSummaryRow` | - | -| `TRow` | `unknown` | - #### Properties -##### column - -```ts -column: CalculatedColumn; -``` - -##### row - -```ts -row: TSummaryRow; -``` - -##### tabIndex - -```ts -tabIndex: number; -``` +| Property | Type | +| ---------- | ---------------------------------------------------------------- | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | +| `row` | `TSummaryRow` | +| `tabIndex` | `number` | --- @@ -4008,12 +2847,6 @@ type RowHeightArgs = Arguments passed to `TreeDataGrid`'s `rowHeight` prop when it is a function. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `TRow` | - #### Example ```tsx @@ -4041,30 +2874,12 @@ Data provided to the `onRowsChange` callback. [`onRowsChange`](#onrowschange) prop on `` -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `R` | - | -| `SR` | `unknown` | - #### Properties -##### indexes - -```ts -indexes: number[]; -``` - -Indexes of the rows that changed - -##### column - -```ts -column: CalculatedColumn; -``` - -The column of the cells that changed +| Property | Type | Description | +| --------- | ---------------------------------------------------- | ------------------------------------ | +| `indexes` | `number`[] | Indexes of the rows that changed | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | The column of the cells that changed | --- @@ -4078,11 +2893,9 @@ Event object for header row selection changes. #### Properties -##### checked - -```ts -checked: boolean; -``` +| Property | Type | +| --------- | --------- | +| `checked` | `boolean` | --- @@ -4094,31 +2907,13 @@ Event object for row selection changes. [`useRowSelection`](#userowselection) hook -#### Type Parameters - -| Type Parameter | -| -------------- | -| `TRow` | - #### Properties -##### row - -```ts -row: TRow; -``` - -##### checked - -```ts -checked: boolean; -``` - -##### isShiftClick - -```ts -isShiftClick: boolean; -``` +| Property | Type | +| -------------- | --------- | +| `row` | `TRow` | +| `checked` | `boolean` | +| `isShiftClick` | `boolean` | --- @@ -4132,17 +2927,10 @@ Options for programmatically updating the grid's active position. #### Properties -##### enableEditor? - -```ts -enableEditor?: Maybe; -``` - -##### shouldFocus? - -```ts -shouldFocus?: Maybe; -``` +| Property | Type | +| --------------- | ------------------------------ | +| `enableEditor?` | [`Maybe`](#maybe)\<`boolean`\> | +| `shouldFocus?` | [`Maybe`](#maybe)\<`boolean`\> | --- @@ -4156,17 +2944,10 @@ Describes a sorted column. #### Properties -##### columnKey - -```ts -readonly columnKey: string; -``` - -##### direction - -```ts -readonly direction: SortDirection; -``` +| Property | Modifier | Type | +| ----------- | ---------- | --------------------------------- | +| `columnKey` | `readonly` | `string` | +| `direction` | `readonly` | [`SortDirection`](#sortdirection) | --- @@ -4184,60 +2965,15 @@ type SortDirection = 'ASC' | 'DESC'; ### ActiveCellKeyDownArgs -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - #### Properties -##### mode - -```ts -mode: 'ACTIVE'; -``` - -##### column - -```ts -column: - | CalculatedColumn - | undefined; -``` - -column object of the active position, -undefined if the active position is a row instead of a cell - -##### row - -```ts -row: TRow; -``` - -##### rowIdx - -```ts -rowIdx: number; -``` - -##### setActivePosition - -```ts -setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -``` - -###### Parameters - -| Parameter | Type | -| ---------- | ------------------------------------------------------- | -| `position` | [`Position`](#position) | -| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | - -###### Returns - -`void` +| Property | Type | Description | +| ------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `mode` | `"ACTIVE"` | - | +| `column` | \| [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> \| `undefined` | column object of the active position, undefined if the active position is a row instead of a cell | +| `row` | `TRow` | - | +| `rowIdx` | `number` | - | +| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | - | --- @@ -4257,37 +2993,12 @@ setActivePosition: (position: Position, options?: SetActivePositionOptions) => v - [`RenderCellProps`](#rendercellprops) - [`BaseRenderRowProps`](#baserenderrowprops) -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - -#### Properties - -##### rowIdx - -```ts -rowIdx: number; -``` - -##### setActivePosition - -```ts -setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -``` - -###### Parameters - -| Parameter | Type | -| ---------- | ------------------------------------------------------- | -| `position` | [`Position`](#position) | -| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | - -###### Returns +#### Properties -`void` +| Property | Type | +| ------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `rowIdx` | `number` | +| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | --- @@ -4301,13 +3012,6 @@ setActivePosition: (position: Position, options?: SetActivePositionOptions) => v - [`RenderRowProps`](#renderrowprops) -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - #### Properties ##### onCellMouseDown? @@ -4328,10 +3032,6 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -`BaseRenderCellProps.onCellMouseDown` - ##### onCellClick? ```ts @@ -4352,10 +3052,6 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -`BaseRenderCellProps.onCellClick` - ##### onCellDoubleClick? ```ts @@ -4374,10 +3070,6 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -`BaseRenderCellProps.onCellDoubleClick` - ##### onCellContextMenu? ```ts @@ -4397,31 +3089,12 @@ function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### Inherited from - -`BaseRenderCellProps.onCellContextMenu` - ##### setActivePosition ```ts setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; ``` -###### Parameters - -| Parameter | Type | -| ---------- | ------------------------------------------------------- | -| `position` | [`Position`](#position) | -| `options?` | [`SetActivePositionOptions`](#setactivepositionoptions) | - -###### Returns - -`void` - -###### Inherited from - -[`BaseRenderCellProps`](#baserendercellprops).[`setActivePosition`](#setactiveposition-5) - ##### iterateOverViewportColumnsForRow ```ts @@ -4434,10 +3107,6 @@ iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow`. Used for copy and paste e ### CellCopyPasteArgs -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - #### Properties -##### column - -```ts -column: CalculatedColumn; -``` - -##### row - -```ts -row: TRow; -``` +| Property | Type | +| -------- | ---------------------------------------------------------------- | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | +| `row` | `TRow` | --- @@ -4511,38 +3166,24 @@ type CellEvent> = E & object; Adds grid-specific methods to a React event. This helper type is not exported; the shape is shown for reference. -#### Type Parameters - -| Type Parameter | -| -------------------------------------------------------- | -| `E` _extends_ `React.SyntheticEvent`\<`HTMLDivElement`\> | - #### Type Declaration ##### preventGridDefault ```ts -preventGridDefault: () => void; +() => void ``` Prevents the default grid behavior for this event -###### Returns - -`void` - ##### isGridDefaultPrevented ```ts -isGridDefaultPrevented: () => boolean; +() => boolean; ``` Returns whether `preventGridDefault` was called -###### Returns - -`boolean` - #### See [`CellMouseEvent`](#cellmouseevent), [`CellKeyboardEvent`](#cellkeyboardevent) @@ -4559,13 +3200,6 @@ type CellMouseEventHandler = Maybe< Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `R` | -| `SR` | - --- ### ColumnEditorOptions @@ -4574,106 +3208,26 @@ Options for cell editing. #### Properties -##### displayCellContent? - -```ts -readonly displayCellContent?: Maybe; -``` - -Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. -By default, the cell content is not rendered when the edit cell is open. - -###### Default Value - -`false` - -##### commitOnOutsideClick? - -```ts -readonly commitOnOutsideClick?: Maybe; -``` - -Commit changes when clicking outside the cell. - -###### Default Value - -`true` - -##### closeOnExternalRowChange? - -```ts -readonly closeOnExternalRowChange?: Maybe; -``` - -Close the editor when the row value changes externally. - -###### Default Value - -`true` +| Property | Modifier | Type | Default value | Description | +| --------------------------- | ---------- | ------------------------------ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `displayCellContent?` | `readonly` | [`Maybe`](#maybe)\<`boolean`\> | `false` | Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. By default, the cell content is not rendered when the edit cell is open. | +| `commitOnOutsideClick?` | `readonly` | [`Maybe`](#maybe)\<`boolean`\> | `true` | Commit changes when clicking outside the cell. | +| `closeOnExternalRowChange?` | `readonly` | [`Maybe`](#maybe)\<`boolean`\> | `true` | Close the editor when the row value changes externally. | --- ### EditCellKeyDownArgs -#### Type Parameters - -| Type Parameter | Default type | -| -------------- | ------------ | -| `TRow` | - | -| `TSummaryRow` | `unknown` | - #### Properties -##### mode - -```ts -mode: 'EDIT'; -``` - -##### column - -```ts -column: CalculatedColumn; -``` - -##### row - -```ts -row: TRow; -``` - -##### rowIdx - -```ts -rowIdx: number; -``` - -##### navigate - -```ts -navigate: () => void; -``` - -###### Returns - -`void` - -##### onClose - -```ts -onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; -``` - -###### Parameters - -| Parameter | Type | -| ---------------- | --------- | -| `commitChanges?` | `boolean` | -| `shouldFocus?` | `boolean` | - -###### Returns - -`void` +| Property | Type | +| ---------- | ------------------------------------------------------------------ | +| `mode` | `"EDIT"` | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | +| `row` | `TRow` | +| `rowIdx` | `number` | +| `navigate` | () => `void` | +| `onClose` | (`commitChanges?`: `boolean`, `shouldFocus?`: `boolean`) => `void` | --- @@ -4683,70 +3237,14 @@ onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; - `Pick`\<[`RenderCellProps`](#rendercellprops)\<`R`, `SR`\>, `"column"` \| `"colSpan"` \| `"row"` \| `"rowIdx"`\> -#### Type Parameters - -| Type Parameter | -| -------------- | -| `R` | -| `SR` | - #### Properties -##### onRowChange - -```ts -onRowChange: (row: R, commitChanges: boolean, shouldFocus: boolean) => void; -``` - -###### Parameters - -| Parameter | Type | -| --------------- | --------- | -| `row` | `R` | -| `commitChanges` | `boolean` | -| `shouldFocus` | `boolean` | - -###### Returns - -`void` - -##### closeEditor - -```ts -closeEditor: (shouldFocus: boolean) => void; -``` - -###### Parameters - -| Parameter | Type | -| ------------- | --------- | -| `shouldFocus` | `boolean` | - -###### Returns - -`void` - -##### navigate - -```ts -navigate: (event: KeyboardEvent) => void; -``` - -###### Parameters - -| Parameter | Type | -| --------- | ----------------------------------- | -| `event` | `KeyboardEvent`\<`HTMLDivElement`\> | - -###### Returns - -`void` - -##### onKeyDown - -```ts -onKeyDown: Maybe<(args: EditCellKeyDownArgs, event: CellKeyboardEvent) => void>; -``` +| Property | Type | +| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `onRowChange` | (`row`: `R`, `commitChanges`: `boolean`, `shouldFocus`: `boolean`) => `void` | +| `closeEditor` | (`shouldFocus`: `boolean`) => `void` | +| `navigate` | (`event`: `KeyboardEvent`\<`HTMLDivElement`\>) => `void` | +| `onKeyDown` | [`Maybe`](#maybe)\<(`args`: [`EditCellKeyDownArgs`](#editcellkeydownargs)\<`R`, `SR`\>, `event`: [`CellKeyboardEvent`](#cellkeyboardevent)) => `void`\> | --- @@ -4758,67 +3256,19 @@ Represents a group row in `TreeDataGrid`. This helper type is not exported; the [`RenderGroupCellContentProps`](#rendergroupcellcontentprops), [`RowHeightArgs`](#rowheightargs), [``](#treedatagrid) -#### Type Parameters - -| Type Parameter | -| -------------- | -| `TRow` | - #### Properties -##### childRows - -```ts -readonly childRows: readonly TRow[]; -``` - -##### id - -```ts -readonly id: string; -``` - -##### parentId - -```ts -readonly parentId: unknown; -``` - -##### groupKey - -```ts -readonly groupKey: unknown; -``` - -##### isExpanded - -```ts -readonly isExpanded: boolean; -``` - -##### level - -```ts -readonly level: number; -``` - -##### posInSet - -```ts -readonly posInSet: number; -``` - -##### setSize - -```ts -readonly setSize: number; -``` - -##### startRowIndex - -```ts -readonly startRowIndex: number; -``` +| Property | Modifier | Type | +| --------------- | ---------- | ----------------- | +| `childRows` | `readonly` | readonly `TRow`[] | +| `id` | `readonly` | `string` | +| `parentId` | `readonly` | `unknown` | +| `groupKey` | `readonly` | `unknown` | +| `isExpanded` | `readonly` | `boolean` | +| `level` | `readonly` | `number` | +| `posInSet` | `readonly` | `number` | +| `setSize` | `readonly` | `number` | +| `startRowIndex` | `readonly` | `number` | --- @@ -4831,24 +3281,6 @@ type IterateOverViewportColumnsForRow = ( ) => IteratorObject>; ``` -#### Type Parameters - -| Type Parameter | -| -------------- | -| `TRow` | -| `TSummaryRow` | - -#### Parameters - -| Parameter | Type | -| ----------- | ------------------------------------------------------ | -| `activeIdx` | `number` \| `undefined` | -| `args?` | [`ColSpanArgs`](#colspanargs)\<`TRow`, `TSummaryRow`\> | - -#### Returns - -`IteratorObject`\<[`ViewportColumnWithColSpan`](#viewportcolumnwithcolspan)\<`TRow`, `TSummaryRow`\>\> - --- ### Maybe @@ -4859,12 +3291,6 @@ type Maybe = T | undefined | null; Utility type for optional values. This helper type is not exported; the shape is shown for reference. -#### Type Parameters - -| Type Parameter | -| -------------- | -| `T` | - --- ### Omit @@ -4873,13 +3299,6 @@ Utility type for optional values. This helper type is not exported; the shape is type Omit = Pick>; ``` -#### Type Parameters - -| Type Parameter | -| ----------------------- | -| `T` | -| `K` _extends_ keyof `T` | - --- ### PartialPosition @@ -4892,17 +3311,10 @@ Position for scrolling to a cell. Both fields are optional: omit `idx` to scroll #### Properties -##### idx? - -```ts -readonly idx?: Maybe; -``` - -##### rowIdx? - -```ts -readonly rowIdx?: Maybe; -``` +| Property | Modifier | Type | +| --------- | ---------- | ----------------------------- | +| `idx?` | `readonly` | [`Maybe`](#maybe)\<`number`\> | +| `rowIdx?` | `readonly` | [`Maybe`](#maybe)\<`number`\> | --- @@ -4916,21 +3328,10 @@ Represents a cell position in the grid. This helper type is not exported; the sh #### Properties -##### idx - -```ts -readonly idx: number; -``` - -Column index, or `-1` for the whole row in `TreeDataGrid` - -##### rowIdx - -```ts -readonly rowIdx: number; -``` - -Row index: `0` is the first row, header rows and top summary rows have negative indexes, and bottom summary rows come after the last row +| Property | Modifier | Type | Description | +| -------- | ---------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `idx` | `readonly` | `number` | Column index, or `-1` for the whole row in `TreeDataGrid` | +| `rowIdx` | `readonly` | `number` | Row index: `0` is the first row, header rows and top summary rows have negative indexes, and bottom summary rows come after the last row | --- @@ -4942,96 +3343,15 @@ Row index: `0` is the first row, header rows and top summary rows have negative #### Properties -##### value - -```ts -value: boolean; -``` - -Whether the checkbox is checked - -##### indeterminate? - -```ts -indeterminate?: boolean; -``` - -Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected - -###### Inherited from - -[`RenderCheckboxProps`](#rendercheckboxprops).[`indeterminate`](#indeterminate) - -##### disabled? - -```ts -disabled?: boolean; -``` - -Whether the checkbox is disabled - -###### Inherited from - -[`RenderCheckboxProps`](#rendercheckboxprops).[`disabled`](#disabled) - -##### onChange - -```ts -onChange: (checked: boolean, shift: boolean) => void; -``` - -Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows - -###### Parameters - -| Parameter | Type | -| --------- | --------- | -| `checked` | `boolean` | -| `shift` | `boolean` | - -###### Returns - -`void` - -###### Inherited from - -[`RenderCheckboxProps`](#rendercheckboxprops).[`onChange`](#onchange) - -##### tabIndex? - -```ts -tabIndex?: number; -``` - -`0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox - -###### Inherited from - -[`RenderCheckboxProps`](#rendercheckboxprops).[`tabIndex`](#tabindex-1) - -##### aria-label? - -```ts -"aria-label"?: string; -``` - -Accessible label for the checkbox - -###### Inherited from - -[`RenderCheckboxProps`](#rendercheckboxprops).[`aria-label`](#aria-label-1) - -##### aria-labelledby? - -```ts -"aria-labelledby"?: string; -``` - -ID of the element that labels the checkbox - -###### Inherited from - -[`RenderCheckboxProps`](#rendercheckboxprops).[`aria-labelledby`](#aria-labelledby-1) +| Property | Type | Description | Inherited from | +| ------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -------------- | +| `value` | `boolean` | Whether the checkbox is checked | - | +| `indeterminate?` | `boolean` | Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected | | +| `disabled?` | `boolean` | Whether the checkbox is disabled | | +| `onChange` | (`checked`: `boolean`, `shift`: `boolean`) => `void` | Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows | | +| `tabIndex?` | `number` | `0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox | | +| `aria-label?` | `string` | Accessible label for the checkbox | | +| `aria-labelledby?` | `string` | ID of the element that labels the checkbox | | --- @@ -5056,13 +3376,6 @@ type ViewportColumnWithColSpan = [ ]; ``` -#### Type Parameters - -| Type Parameter | -| -------------- | -| `TRow` | -| `TSummaryRow` | - [ci-badge]: https://github.com/Comcast/react-data-grid/actions/workflows/ci.yml/badge.svg diff --git a/package-lock.json b/package-lock.json index 48ebfb0a75..7c6faea918 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,6 +23,7 @@ "clsx": "^2.1.1", "ecij": "^0.6.0", "eslint": "^10.2.1", + "github-slugger": "^2.0.0", "jspdf": "^4.2.0", "jspdf-autotable": "^5.0.7", "oxc-transform-react": "^0.154.0", diff --git a/package.json b/package.json index 5e713c8123..4a962c26d1 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "clsx": "^2.1.1", "ecij": "^0.6.0", "eslint": "^10.2.1", + "github-slugger": "^2.0.0", "jspdf": "^4.2.0", "jspdf-autotable": "^5.0.7", "oxc-transform-react": "^0.154.0", diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index 398c283d5f..cfc2d2e625 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -1,6 +1,7 @@ import { readFile, writeFile } from 'node:fs/promises'; import { registerHooks } from 'node:module'; -import type { SomeType } from 'typedoc'; +import GithubSlugger from 'github-slugger'; +import type { ContainerReflection, SignatureReflection as SignatureModel, SomeType } from 'typedoc'; // TODO: remove when TypeDoc supports TypeScript 7 // TypeDoc relies on the TypeScript API, which TypeScript 7 does not provide yet, @@ -13,9 +14,11 @@ registerHooks({ const { Application, + Comment, Context, Converter, DeclarationReflection, + i18n, ParameterReflection, ReferenceType, ReflectionGroup, @@ -26,6 +29,7 @@ const { TypeDocReader, TypeParameterReflection } = await import('typedoc'); +const { MarkdownTheme, MarkdownThemeContext } = await import('typedoc-plugin-markdown'); const readmePath = 'README.md'; const startMarker = ''; @@ -45,6 +49,53 @@ Context.prototype.createSymbolReference = function (...args) { return reference; }; +class ReadmeThemeContext extends MarkdownThemeContext { + constructor(...args: ConstructorParameters) { + super(...args); + + const { groups } = this.partials; + const { useTableFormat: isDefaultTableFormat } = this.helpers; + let isTableInterface = false; + + this.partials = { + ...this.partials, + // list the properties of an interface in a table, unless a property has more than a short description + groups(model: ContainerReflection, options: Parameters[1]) { + isTableInterface = + model.kindOf(ReflectionKind.Interface) && model.children?.every(hasShortComment) === true; + return groups(model, options); + }, + // the signatures already show the return types + signatureReturns: (model: SignatureModel, options: { headingLevel: number }) => { + const returnsTag = model.comment?.getTag('@returns'); + if (returnsTag === undefined) return ''; + return `${'#'.repeat(options.headingLevel)} ${i18n.theme_returns()}\n\n${this.helpers.getCommentParts(returnsTag.content)}`; + }, + // the "Extends" sections already link to the base types + inheritance: () => '' + }; + + this.helpers = { + ...this.helpers, + useTableFormat: (key, reflectionKind) => + key === 'properties' && reflectionKind === ReflectionKind.Interface + ? isTableInterface + : isDefaultTableFormat(key, reflectionKind) + }; + } +} + +class ReadmeTheme extends MarkdownTheme { + override getRenderContext( + page: Parameters['getRenderContext']>[0] + ) { + return new ReadmeThemeContext(this, page, this.application.options); + } +} + +app.renderer.defineTheme('readme', ReadmeTheme); +app.options.setValue('theme', 'readme'); + // collect the public exports before typedoc-plugin-missing-exports adds the internal types, // its listener has a priority of 1e9 const publicNames = new Set(); @@ -119,11 +170,11 @@ const publicGroups = (project.groups ?? []).filter((group) => { internalGroup.children.sort((a, b) => a.name.localeCompare(b.name)); project.groups = [...publicGroups, internalGroup]; -// only list the members that are inherited from internal types, -// the members inherited from public types are listed in their own section for (const reflection of project.getReflectionsByKind(ReflectionKind.Interface)) { if (!(reflection instanceof DeclarationReflection)) continue; + // only list the members that are inherited from internal types, + // the members inherited from public types are listed in their own section, // e.g. `extends Column` or `extends Omit` const publicBaseTypes = new Set(); for (const type of reflection.extendedTypes ?? []) { @@ -154,6 +205,21 @@ for (const reflection of project.getReflectionsByKind(ReflectionKind.Interface)) for (const group of reflection.groups ?? []) { group.children = group.children.filter((child) => remainingMembers.has(child)); } + + // TypeDoc copies the comments of the members a member redeclares, + // like `CalculatedColumn` redeclaring the properties of `Column` with their resolved types, + // but their descriptions and defaults don't apply to the redeclared members + for (const child of reflection.children ?? []) { + const overwrittenComment = child.overwrites?.reflection?.comment; + if ( + child.comment !== undefined && + overwrittenComment !== undefined && + Comment.combineDisplayParts(child.comment.summary) === + Comment.combineDisplayParts(overwrittenComment.summary) + ) { + delete child.comment; + } + } } const outputDirectory = app.options.getValue('out'); @@ -169,27 +235,37 @@ if (startIndex === -1 || endIndex < startIndex) { throw new Error(`${readmePath} must contain ${startMarker} followed by ${endMarker}`); } -const before = readme.slice(0, startIndex + startMarker.length); -const after = readme.slice(endIndex); +await writeFile( + readmePath, + replaceAnchors( + readme.slice(0, startIndex + startMarker.length), + api.trim(), + readme.slice(endIndex) + ) +); -await writeFile(readmePath, `${before}\n\n${replaceAnchors(api.trim(), before)}\n\n${after}`); +// a property can be listed in a table if its comment is a single paragraph +function hasShortComment(reflection: InstanceType) { + const { comment } = reflection; + if (comment === undefined) return true; + const summary = Comment.combineDisplayParts(comment.summary); + return ( + comment.blockTags.every((tag) => tag.tag === '@defaultValue') && + !summary.includes('\n\n') && + !summary.includes('```') && + !/^\s*(?:[-*+]|\d+\.) /m.test(summary) + ); +} // typedoc-plugin-markdown adds an HTML anchor before each heading and links to it, // replace them with the anchors GitHub generates for the headings, -// which are numbered across the whole README, starting with the headings before the API reference -function replaceAnchors(api: string, precedingMarkdown: string) { - const slugCounts = new Map(); +// which are numbered across the whole README, starting with the headings before the API reference. +// Links outside of the API reference can link to a member with its name as the link title, +// e.g. `[width](#width "Column.width")`, to update the anchor when the numbering changes. +function replaceAnchors(precedingMarkdown: string, api: string, followingMarkdown: string) { + const slugger = new GithubSlugger(); function slug(heading: string) { - const base = heading - .replaceAll(/\[([^\]]*)\]\([^)]*\)/g, '$1') - .replaceAll(/\\(.)/g, '$1') - .replaceAll('`', '') - .toLowerCase() - .replaceAll(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, '') - .replaceAll(' ', '-'); - const count = slugCounts.get(base) ?? 0; - slugCounts.set(base, count + 1); - return count === 0 ? base : `${base}-${count}`; + return slugger.slug(getHeadingText(heading)); } forEachLine(precedingMarkdown, (line, isInCodeBlock) => { @@ -197,9 +273,12 @@ function replaceAnchors(api: string, precedingMarkdown: string) { if (heading !== null) slug(heading[1]); }); + // anchors of the plugin, and of the API reference members, e.g. `Column.width` const anchors = new Map(); + const memberAnchors = new Map(); const lines: string[] = []; let pendingAnchor: string | undefined; + let item: string | undefined; forEachLine(api, (line, isInCodeBlock) => { if (!isInCodeBlock) { const anchor = /^
<\/a>$/.exec(line); @@ -208,44 +287,89 @@ function replaceAnchors(api: string, precedingMarkdown: string) { return; } - const heading = /^#{1,6} (.+)$/.exec(line); + const heading = /^(#{1,6}) (.+)$/.exec(line); if (heading !== null) { - const headingSlug = slug(heading[1]); + const headingSlug = slug(heading[2]); + const name = getHeadingText(heading[2]).replace(/(?:\(\)|\?)$/, ''); + if (heading[1].length === 3) { + item = name; + memberAnchors.set(name, headingSlug); + } else if (pendingAnchor !== undefined && item !== undefined) { + memberAnchors.set(`${item}.${name}`, headingSlug); + } if (pendingAnchor !== undefined) { anchors.set(pendingAnchor, headingSlug); pendingAnchor = undefined; } - } else if (pendingAnchor !== undefined && line === '') { + } else if (pendingAnchor !== undefined) { // the empty line between the anchor and its heading - return; + if (line === '') return; + throw new Error(`The anchor #${pendingAnchor} is not followed by a heading: ${line}`); } } lines.push(line); }); - // the anchors of the rows of the type parameter tables have no heading - const removedAnchors = new Set(); + // the anchors of table rows have no heading to link to + const tableAnchors = new Set(); const markdown = lines.join('\n').replaceAll(/<\/a> /g, (_, id: string) => { - removedAnchors.add(id); + tableAnchors.add(id); return ''; }); - return markdown.replaceAll(/\]\(#([^)]+)\)/g, (link, id: string) => { - if (removedAnchors.has(id)) { - throw new Error(`The link to #${id} has no heading to link to`); - } + const apiMarkdown = markdown.replaceAll(/\]\(#([^)]+)\)/g, (_, id: string) => { const anchor = anchors.get(id); - return anchor === undefined ? link : `](#${anchor})`; + if (anchor === undefined) { + throw new Error( + tableAnchors.has(id) + ? `The link to #${id} links to a table row, which has no heading to link to` + : `The link to #${id} does not match any heading` + ); + } + return `](#${anchor})`; }); + + const linkedPrecedingMarkdown = precedingMarkdown.replaceAll( + /\]\(#[^ )]+ "([^"]+)"\)/g, + (_, member: string) => { + const anchor = memberAnchors.get(member); + if (anchor === undefined) { + throw new Error(`The link to "${member}" does not match any API reference heading`); + } + return `](#${anchor} "${member}")`; + } + ); + + return `${linkedPrecedingMarkdown}\n\n${apiMarkdown}\n\n${followingMarkdown}`; +} + +function getHeadingText(heading: string) { + return heading + .replaceAll(/\[([^\]]*)\]\([^)]*\)/g, '$1') + .replaceAll(/\\(.)/g, '$1') + .replaceAll('`', ''); } function forEachLine(markdown: string, callback: (line: string, isInCodeBlock: boolean) => void) { - let isInCodeBlock = false; + let fence: string | undefined; for (const line of markdown.split('\n')) { - const isFence = line.trimStart().startsWith('```'); - callback(line, isInCodeBlock || isFence); - if (isFence) isInCodeBlock = !isInCodeBlock; + const fenceMatch = /^ {0,3}(`{3,}|~{3,})/.exec(line); + if (fence === undefined) { + if (fenceMatch !== null) fence = fenceMatch[1]; + callback(line, fence !== undefined); + } else { + callback(line, true); + // a closing fence uses the same character, at least as many times, and has no info string + if ( + fenceMatch !== null && + fenceMatch[1].startsWith(fence[0]) && + fenceMatch[1].length >= fence.length && + line.trim() === fenceMatch[1] + ) { + fence = undefined; + } + } } } diff --git a/typedoc.json b/typedoc.json index a0330141f4..6e3a8ba392 100644 --- a/typedoc.json +++ b/typedoc.json @@ -32,6 +32,7 @@ "hideBreadcrumbs": true, "useCodeBlocks": true, "expandParameters": true, - "parametersFormat": "table", + "parametersFormat": "none", + "typeDeclarationVisibility": "compact", "useHTMLAnchors": true } From e7384dcec266beeee6477d2758edf8e6880190bd Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 10:51:18 -0500 Subject: [PATCH 04/22] Rename the `TRow` and `TSummaryRow` type parameters to `R` and `SR` Use the same type parameter names as the other types, which simplifies the "Generics" section of the README. Type parameter names are not part of the public API. Co-Authored-By: Claude Opus 5.5 --- README.md | 278 +++++++++++++++---------------- src/TreeDataGrid.tsx | 10 +- src/editors/renderTextEditor.tsx | 6 +- src/types.ts | 186 ++++++++++----------- 4 files changed, 230 insertions(+), 250 deletions(-) diff --git a/README.md b/README.md index 2eacde3ce0..1dbef71dc0 100644 --- a/README.md +++ b/README.md @@ -235,8 +235,8 @@ Replace default components with custom implementations using the [`renderers`](# ### Generics -- `R`, `TRow`: Row type -- `SR`, `TSummaryRow`: Summary row type +- `R`: Row type +- `SR`: Summary row type - `K`: Row key type @@ -1377,9 +1377,7 @@ Renders the sort priority number for multi-column sorting. ### renderTextEditor() ```ts -function renderTextEditor( - __namedParameters: RenderEditCellContentProps -): Element; +function renderTextEditor(__namedParameters: RenderEditCellContentProps): Element; ``` A basic text editor provided for convenience. @@ -1552,24 +1550,24 @@ Extends `Column` with additional computed properties used internally by the grid #### Extends -- [`Column`](#column)\<`TRow`, `TSummaryRow`\> +- [`Column`](#column)\<`R`, `SR`\> #### Properties -| Property | Modifier | Type | Description | Overrides | -| ------------------ | ---------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | -| `parent` | `readonly` | \| [`CalculatedColumnParent`](#calculatedcolumnparent)\<`TRow`, `TSummaryRow`\> \| `undefined` | The column group that contains the column, or `undefined` if the column is not in a group | - | -| `idx` | `readonly` | `number` | The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` | - | -| `level` | `readonly` | `number` | Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups | - | -| `width` | `readonly` | `string` \| `number` | - | | -| `minWidth` | `readonly` | `number` | - | | -| `maxWidth` | `readonly` | `number` \| `undefined` | - | | -| `resizable` | `readonly` | `boolean` | - | | -| `sortable` | `readonly` | `boolean` | - | | -| `draggable` | `readonly` | `boolean` | - | | -| `frozen` | `readonly` | [`ColumnFrozen`](#columnfrozen) | - | | -| `renderCell` | `readonly` | (`props`: [`RenderCellContentProps`](#rendercellcontentprops)\<`TRow`, `TSummaryRow`\>) => `ReactNode` | - | | -| `renderHeaderCell` | `readonly` | (`props`: [`RenderHeaderCellContentProps`](#renderheadercellcontentprops)\<`TRow`, `TSummaryRow`\>) => `ReactNode` | - | | +| Property | Modifier | Type | Description | Overrides | +| ------------------ | ---------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | +| `parent` | `readonly` | \| [`CalculatedColumnParent`](#calculatedcolumnparent)\<`R`, `SR`\> \| `undefined` | The column group that contains the column, or `undefined` if the column is not in a group | - | +| `idx` | `readonly` | `number` | The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` | - | +| `level` | `readonly` | `number` | Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups | - | +| `width` | `readonly` | `string` \| `number` | - | | +| `minWidth` | `readonly` | `number` | - | | +| `maxWidth` | `readonly` | `number` \| `undefined` | - | | +| `resizable` | `readonly` | `boolean` | - | | +| `sortable` | `readonly` | `boolean` | - | | +| `draggable` | `readonly` | `boolean` | - | | +| `frozen` | `readonly` | [`ColumnFrozen`](#columnfrozen) | - | | +| `renderCell` | `readonly` | (`props`: [`RenderCellContentProps`](#rendercellcontentprops)\<`R`, `SR`\>) => `ReactNode` | - | | +| `renderHeaderCell` | `readonly` | (`props`: [`RenderHeaderCellContentProps`](#renderheadercellcontentprops)\<`R`, `SR`\>) => `ReactNode` | - | | --- @@ -1611,7 +1609,7 @@ Represents a parent column group in the calculated column structure. ### CellCopyArgs ```ts -type CellCopyArgs = CellCopyPasteArgs; +type CellCopyArgs = CellCopyPasteArgs; ``` Arguments passed to `onCellCopy`. @@ -1639,9 +1637,7 @@ Extends `React.KeyboardEvent` with grid-specific methods. ### CellKeyDownArgs ```ts -type CellKeyDownArgs = - | ActiveCellKeyDownArgs - | EditCellKeyDownArgs; +type CellKeyDownArgs = ActiveCellKeyDownArgs | EditCellKeyDownArgs; ``` Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. @@ -1686,12 +1682,12 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { #### Properties -| Property | Type | Description | -| ------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------ | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | The column object of the cell. | -| `row` | `TRow` | The row object of the cell. | -| `rowIdx` | `number` | The row index of the cell. | -| `setActivePosition` | (`enableEditor?`: `boolean`) => `void` | Function to manually focus the cell. Pass `true` to immediately start editing. | +| Property | Type | Description | +| ------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------ | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | The column object of the cell. | +| `row` | `R` | The row object of the cell. | +| `rowIdx` | `number` | The row index of the cell. | +| `setActivePosition` | (`enableEditor?`: `boolean`) => `void` | Function to manually focus the cell. Pass `true` to immediately start editing. | --- @@ -1724,7 +1720,7 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ### CellPasteArgs ```ts -type CellPasteArgs = CellCopyPasteArgs; +type CellPasteArgs = CellCopyPasteArgs; ``` Arguments passed to `onCellPaste`. @@ -1738,17 +1734,17 @@ Arguments passed to `onCellPaste`. ### ColSpanArgs ```ts -type ColSpanArgs = +type ColSpanArgs = | { type: 'HEADER'; } | { type: 'ROW'; - row: TRow; + row: R; } | { type: 'SUMMARY'; - row: TSummaryRow; + row: SR; }; ``` @@ -1880,7 +1876,7 @@ Maximum column width in pixels. ##### cellClass? ```ts -readonly cellClass?: Maybe Maybe)>; +readonly cellClass?: Maybe Maybe)>; ``` Class name(s) for cells. Can be a string or a function that returns a class name based on the row. @@ -1926,7 +1922,7 @@ Class name(s) for the header cell. ##### summaryCellClass? ```ts -readonly summaryCellClass?: Maybe Maybe)>; +readonly summaryCellClass?: Maybe Maybe)>; ``` Class name(s) for summary cells. Can be a string or a function that returns a class name based on the summary row. @@ -1934,7 +1930,7 @@ Class name(s) for summary cells. Can be a string or a function that returns a cl ##### renderCell? ```ts -readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; +readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; ``` Render function to render the content of cells. @@ -1942,7 +1938,7 @@ Render function to render the content of cells. ##### renderHeaderCell? ```ts -readonly renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) => ReactNode>; +readonly renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) => ReactNode>; ``` Render function to render the content of the header cell. @@ -1950,7 +1946,7 @@ Render function to render the content of the header cell. ##### renderSummaryCell? ```ts -readonly renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>; +readonly renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>; ``` Render function to render the content of summary cells. @@ -1958,7 +1954,7 @@ Render function to render the content of summary cells. ##### renderGroupCell? ```ts -readonly renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>; +readonly renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>; ``` Render function to render the content of group cells when using `TreeDataGrid`. @@ -1966,7 +1962,7 @@ Render function to render the content of group cells when using `TreeDataGrid`. ##### renderEditCell? ```ts -readonly renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>; +readonly renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>; ``` Render function to render the content of edit cells. When set, the column is automatically set to be editable. @@ -1974,7 +1970,7 @@ Render function to render the content of edit cells. When set, the column is aut ##### editable? ```ts -readonly editable?: Maybe boolean)>; +readonly editable?: Maybe boolean)>; ``` Control whether cells can be edited with `renderEditCell`. @@ -1982,7 +1978,7 @@ Control whether cells can be edited with `renderEditCell`. ##### colSpan? ```ts -readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; +readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; ``` Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. See the [`ColSpanArgs`](#colspanargs) type. @@ -2267,8 +2263,8 @@ Event object for drag-fill operations. | Property | Type | | ----------- | -------- | | `columnKey` | `string` | -| `sourceRow` | `TRow` | -| `targetRow` | `TRow` | +| `sourceRow` | `R` | +| `targetRow` | `R` | --- @@ -2282,11 +2278,11 @@ Arguments passed to `onActivePositionChange`. #### Properties -| Property | Type | Description | -| -------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `rowIdx` | `number` | row index of the active position | -| `row` | `TRow` \| `undefined` | row object of the active position, undefined if the active position is on a header or summary row | -| `column` | \| [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> \| `undefined` | column object of the active position, undefined if the active position is a row instead of a cell | +| Property | Type | Description | +| -------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `rowIdx` | `number` | row index of the active position | +| `row` | `R` \| `undefined` | row object of the active position, undefined if the active position is on a header or summary row | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> \| `undefined` | column object of the active position, undefined if the active position is a row instead of a cell | --- @@ -2315,14 +2311,14 @@ function renderCell({ row, column, onRowChange }: RenderCellContentProps) #### Properties -| Property | Type | -| ---------------- | ---------------------------------------------------------------- | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | -| `row` | `TRow` | -| `rowIdx` | `number` | -| `isCellEditable` | `boolean` | -| `tabIndex` | `number` | -| `onRowChange` | (`row`: `TRow`) => `void` | +| Property | Type | +| ---------------- | ---------------------------------------------------- | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | +| `row` | `R` | +| `rowIdx` | `number` | +| `isCellEditable` | `boolean` | +| `tabIndex` | `number` | +| `onRowChange` | (`row`: `R`) => `void` | --- @@ -2336,14 +2332,14 @@ Props passed to the cell renderer when using `renderers.renderCell`. #### Extends -- [`BaseRenderCellProps`](#baserendercellprops)\<`TRow`, `TSummaryRow`\> +- [`BaseRenderCellProps`](#baserendercellprops)\<`R`, `SR`\> #### Properties ##### onCellMouseDown? ```ts -onCellMouseDown?: CellMouseEventHandler; +onCellMouseDown?: CellMouseEventHandler; ``` Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -2361,7 +2357,7 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ##### onCellClick? ```ts -onCellClick?: CellMouseEventHandler; +onCellClick?: CellMouseEventHandler; ``` Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -2381,7 +2377,7 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ##### onCellDoubleClick? ```ts -onCellDoubleClick?: CellMouseEventHandler; +onCellDoubleClick?: CellMouseEventHandler; ``` Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -2399,7 +2395,7 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ##### onCellContextMenu? ```ts -onCellContextMenu?: CellMouseEventHandler; +onCellContextMenu?: CellMouseEventHandler; ``` Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -2430,13 +2426,13 @@ setActivePosition: (position: Position, options?: SetActivePositionOptions) => v ##### column ```ts -column: CalculatedColumn; +column: CalculatedColumn; ``` ##### row ```ts -row: TRow; +row: R; ``` ##### colSpan @@ -2460,7 +2456,7 @@ isCellActive: boolean; ##### onRowChange ```ts -onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: TRow) => void; +onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; ``` --- @@ -2516,10 +2512,10 @@ function renderEditor({ row, column, onRowChange, onClose }: RenderEditCellConte | Property | Type | | ------------- | ------------------------------------------------------------------ | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | -| `row` | `TRow` | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | +| `row` | `R` | | `rowIdx` | `number` | -| `onRowChange` | (`row`: `TRow`, `commitChanges?`: `boolean`) => `void` | +| `onRowChange` | (`row`: `R`, `commitChanges?`: `boolean`) => `void` | | `onClose` | (`commitChanges?`: `boolean`, `shouldFocus?`: `boolean`) => `void` | --- @@ -2534,13 +2530,13 @@ Custom renderer configuration for the grid. #### Properties -| Property | Modifier | Type | -| ------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------- | -| `renderCell?` | `readonly` | [`Maybe`](#maybe)\<(`key`: `Key`, `props`: [`RenderCellProps`](#rendercellprops)\<`TRow`, `TSummaryRow`\>) => `ReactNode`\> | -| `renderCheckbox?` | `readonly` | [`Maybe`](#maybe)\<(`props`: [`RenderCheckboxProps`](#rendercheckboxprops)) => `ReactNode`\> | -| `renderRow?` | `readonly` | [`Maybe`](#maybe)\<(`key`: `Key`, `props`: [`RenderRowProps`](#renderrowprops)\<`TRow`, `TSummaryRow`\>) => `ReactNode`\> | -| `renderSortStatus?` | `readonly` | [`Maybe`](#maybe)\<(`props`: [`RenderSortStatusProps`](#rendersortstatusprops)) => `ReactNode`\> | -| `noRowsFallback?` | `readonly` | `ReactNode` | +| Property | Modifier | Type | +| ------------------- | ---------- | --------------------------------------------------------------------------------------------------------------- | +| `renderCell?` | `readonly` | [`Maybe`](#maybe)\<(`key`: `Key`, `props`: [`RenderCellProps`](#rendercellprops)\<`R`, `SR`\>) => `ReactNode`\> | +| `renderCheckbox?` | `readonly` | [`Maybe`](#maybe)\<(`props`: [`RenderCheckboxProps`](#rendercheckboxprops)) => `ReactNode`\> | +| `renderRow?` | `readonly` | [`Maybe`](#maybe)\<(`key`: `Key`, `props`: [`RenderRowProps`](#renderrowprops)\<`R`, `SR`\>) => `ReactNode`\> | +| `renderSortStatus?` | `readonly` | [`Maybe`](#maybe)\<(`props`: [`RenderSortStatusProps`](#rendersortstatusprops)) => `ReactNode`\> | +| `noRowsFallback?` | `readonly` | `ReactNode` | --- @@ -2554,15 +2550,15 @@ Props passed to group cell content renderers (`column.renderGroupCell`) when usi #### Properties -| Property | Type | -| ------------- | ---------------------------------------------------------------- | -| `groupKey` | `unknown` | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | -| `row` | [`GroupRow`](#grouprow)\<`TRow`\> | -| `childRows` | readonly `TRow`[] | -| `isExpanded` | `boolean` | -| `tabIndex` | `number` | -| `toggleGroup` | () => `void` | +| Property | Type | +| ------------- | ---------------------------------------------------- | +| `groupKey` | `unknown` | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | +| `row` | [`GroupRow`](#grouprow)\<`R`\> | +| `childRows` | readonly `R`[] | +| `isExpanded` | `boolean` | +| `tabIndex` | `number` | +| `toggleGroup` | () => `void` | --- @@ -2576,12 +2572,12 @@ Props passed to custom header cell content renderers (`column.renderHeaderCell`) #### Properties -| Property | Type | -| --------------- | ---------------------------------------------------------------- | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | -| `sortDirection` | [`SortDirection`](#sortdirection) \| `undefined` | -| `priority` | `number` \| `undefined` | -| `tabIndex` | `number` | +| Property | Type | +| --------------- | ---------------------------------------------------- | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | +| `sortDirection` | [`SortDirection`](#sortdirection) \| `undefined` | +| `priority` | `number` \| `undefined` | +| `tabIndex` | `number` | --- @@ -2595,14 +2591,14 @@ Props passed to custom row renderers. #### Extends -- [`BaseRenderRowProps`](#baserenderrowprops)\<`TRow`, `TSummaryRow`\> +- [`BaseRenderRowProps`](#baserenderrowprops)\<`R`, `SR`\> #### Properties ##### onCellMouseDown? ```ts -onCellMouseDown?: CellMouseEventHandler; +onCellMouseDown?: CellMouseEventHandler; ``` Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -2620,7 +2616,7 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ##### onCellClick? ```ts -onCellClick?: CellMouseEventHandler; +onCellClick?: CellMouseEventHandler; ``` Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -2640,7 +2636,7 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ##### onCellDoubleClick? ```ts -onCellDoubleClick?: CellMouseEventHandler; +onCellDoubleClick?: CellMouseEventHandler; ``` Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -2658,7 +2654,7 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ##### onCellContextMenu? ```ts -onCellContextMenu?: CellMouseEventHandler; +onCellContextMenu?: CellMouseEventHandler; ``` Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -2683,7 +2679,7 @@ setActivePosition: (position: Position, options?: SetActivePositionOptions) => v ##### iterateOverViewportColumnsForRow ```ts -iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; +iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; ``` ##### rowIdx @@ -2719,7 +2715,7 @@ gridRowStart: number; ##### row ```ts -row: TRow; +row: R; ``` ##### draggedOverCellIdx @@ -2732,20 +2728,20 @@ draggedOverCellIdx: number | undefined; ```ts activeCellEditor: - | ReactElement, string | JSXElementConstructor> + | ReactElement, string | JSXElementConstructor> | undefined; ``` ##### onRowChange ```ts -onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: TRow) => void; +onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; ``` ##### rowClass ```ts -rowClass: Maybe<(row: TRow, rowIdx: number) => Maybe>; +rowClass: Maybe<(row: R, rowIdx: number) => Maybe>; ``` ##### isTreeGrid @@ -2823,25 +2819,25 @@ Props passed to summary cell content renderers (`column.renderSummaryCell`). #### Properties -| Property | Type | -| ---------- | ---------------------------------------------------------------- | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | -| `row` | `TSummaryRow` | -| `tabIndex` | `number` | +| Property | Type | +| ---------- | ---------------------------------------------------- | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | +| `row` | `SR` | +| `tabIndex` | `number` | --- ### RowHeightArgs ```ts -type RowHeightArgs = +type RowHeightArgs = | { type: 'ROW'; - row: TRow; + row: R; } | { type: 'GROUP'; - row: GroupRow; + row: GroupRow; }; ``` @@ -2911,7 +2907,7 @@ Event object for row selection changes. | Property | Type | | -------------- | --------- | -| `row` | `TRow` | +| `row` | `R` | | `checked` | `boolean` | | `isShiftClick` | `boolean` | @@ -2970,8 +2966,8 @@ type SortDirection = 'ASC' | 'DESC'; | Property | Type | Description | | ------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `mode` | `"ACTIVE"` | - | -| `column` | \| [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> \| `undefined` | column object of the active position, undefined if the active position is a row instead of a cell | -| `row` | `TRow` | - | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> \| `undefined` | column object of the active position, undefined if the active position is a row instead of a cell | +| `row` | `R` | - | | `rowIdx` | `number` | - | | `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | - | @@ -2982,7 +2978,7 @@ type SortDirection = 'ASC' | 'DESC'; #### Extends - [`Omit`](#omit)\<`React.ComponentProps`\<`"div"`\>, `"children"`\> -- `Pick`\<[`DataGridProps`](#datagridprops)\<`TRow`, `TSummaryRow`\>, +- `Pick`\<[`DataGridProps`](#datagridprops)\<`R`, `SR`\>, \| `"onCellMouseDown"` \| `"onCellClick"` \| `"onCellDoubleClick"` @@ -3006,7 +3002,7 @@ type SortDirection = 'ASC' | 'DESC'; #### Extends -- [`BaseRenderCellProps`](#baserendercellprops)\<`TRow`, `TSummaryRow`\> +- [`BaseRenderCellProps`](#baserendercellprops)\<`R`, `SR`\> #### Extended by @@ -3017,7 +3013,7 @@ type SortDirection = 'ASC' | 'DESC'; ##### onCellMouseDown? ```ts -onCellMouseDown?: CellMouseEventHandler; +onCellMouseDown?: CellMouseEventHandler; ``` Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -3035,7 +3031,7 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ##### onCellClick? ```ts -onCellClick?: CellMouseEventHandler; +onCellClick?: CellMouseEventHandler; ``` Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -3055,7 +3051,7 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ##### onCellDoubleClick? ```ts -onCellDoubleClick?: CellMouseEventHandler; +onCellDoubleClick?: CellMouseEventHandler; ``` Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -3073,7 +3069,7 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ##### onCellContextMenu? ```ts -onCellContextMenu?: CellMouseEventHandler; +onCellContextMenu?: CellMouseEventHandler; ``` Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. @@ -3098,7 +3094,7 @@ setActivePosition: (position: Position, options?: SetActivePositionOptions) => v ##### iterateOverViewportColumnsForRow ```ts -iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; +iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; ``` ##### rowIdx @@ -3151,10 +3147,10 @@ Type alias for `React.ClipboardEvent`. Used for copy and paste e #### Properties -| Property | Type | -| -------- | ---------------------------------------------------------------- | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | -| `row` | `TRow` | +| Property | Type | +| -------- | ---------------------------------------------------- | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | +| `row` | `R` | --- @@ -3223,8 +3219,8 @@ Options for cell editing. | Property | Type | | ---------- | ------------------------------------------------------------------ | | `mode` | `"EDIT"` | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`TRow`, `TSummaryRow`\> | -| `row` | `TRow` | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | +| `row` | `R` | | `rowIdx` | `number` | | `navigate` | () => `void` | | `onClose` | (`commitChanges?`: `boolean`, `shouldFocus?`: `boolean`) => `void` | @@ -3258,27 +3254,27 @@ Represents a group row in `TreeDataGrid`. This helper type is not exported; the #### Properties -| Property | Modifier | Type | -| --------------- | ---------- | ----------------- | -| `childRows` | `readonly` | readonly `TRow`[] | -| `id` | `readonly` | `string` | -| `parentId` | `readonly` | `unknown` | -| `groupKey` | `readonly` | `unknown` | -| `isExpanded` | `readonly` | `boolean` | -| `level` | `readonly` | `number` | -| `posInSet` | `readonly` | `number` | -| `setSize` | `readonly` | `number` | -| `startRowIndex` | `readonly` | `number` | +| Property | Modifier | Type | +| --------------- | ---------- | -------------- | +| `childRows` | `readonly` | readonly `R`[] | +| `id` | `readonly` | `string` | +| `parentId` | `readonly` | `unknown` | +| `groupKey` | `readonly` | `unknown` | +| `isExpanded` | `readonly` | `boolean` | +| `level` | `readonly` | `number` | +| `posInSet` | `readonly` | `number` | +| `setSize` | `readonly` | `number` | +| `startRowIndex` | `readonly` | `number` | --- ### IterateOverViewportColumnsForRow ```ts -type IterateOverViewportColumnsForRow = ( +type IterateOverViewportColumnsForRow = ( activeIdx: number | undefined, - args?: ColSpanArgs -) => IteratorObject>; + args?: ColSpanArgs +) => IteratorObject>; ``` --- @@ -3369,8 +3365,8 @@ type SharedInputProps = Pick< ### ViewportColumnWithColSpan ```ts -type ViewportColumnWithColSpan = [ - column: CalculatedColumn, +type ViewportColumnWithColSpan = [ + column: CalculatedColumn, isCellActive: boolean, colSpan: number | undefined ]; diff --git a/src/TreeDataGrid.tsx b/src/TreeDataGrid.tsx index 5516d70429..0e52ff6732 100644 --- a/src/TreeDataGrid.tsx +++ b/src/TreeDataGrid.tsx @@ -134,14 +134,14 @@ export interface TreeDataGridProps extends groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>; } -interface GroupBy { - readonly childRows: readonly TRow[]; - readonly childGroups: readonly TRow[] | ReadonlyGroupByMap; +interface GroupBy { + readonly childRows: readonly R[]; + readonly childGroups: readonly R[] | ReadonlyGroupByMap; readonly startRowIndex: number; } -type GroupByMap = Map>; -type ReadonlyGroupByMap = ReadonlyMap>; +type GroupByMap = Map>; +type ReadonlyGroupByMap = ReadonlyMap>; /** * `TreeDataGrid` is a component built on top of `DataGrid` to add hierarchical row grouping. This implements the [Treegrid pattern](https://www.w3.org/WAI/ARIA/apg/patterns/treegrid/). diff --git a/src/editors/renderTextEditor.tsx b/src/editors/renderTextEditor.tsx index 1decd85b6a..527c224bfe 100644 --- a/src/editors/renderTextEditor.tsx +++ b/src/editors/renderTextEditor.tsx @@ -56,17 +56,17 @@ function autoFocusAndSelect(input: HTMLInputElement | null) { * * @group Render Functions */ -export function renderTextEditor({ +export function renderTextEditor({ row, column, onRowChange, onClose -}: RenderEditCellContentProps) { +}: RenderEditCellContentProps) { return ( onRowChange({ ...row, [column.key]: event.target.value })} onBlur={() => onClose(true, false)} /> diff --git a/src/types.ts b/src/types.ts index 0e14721a24..0c3b950a80 100644 --- a/src/types.ts +++ b/src/types.ts @@ -18,7 +18,7 @@ export type StateSetter = React.Dispatch>; * * @group Types */ -export interface Column { +export interface Column { /** The name of the column. Displayed in the header cell by default. */ readonly name: string | ReactElement; /** A unique key to distinguish each column. */ @@ -104,31 +104,23 @@ export interface Column { * } * ``` */ - readonly cellClass?: Maybe Maybe)>; + readonly cellClass?: Maybe Maybe)>; /** Class name(s) for the header cell. */ readonly headerCellClass?: Maybe; /** Class name(s) for summary cells. Can be a string or a function that returns a class name based on the summary row. */ - readonly summaryCellClass?: Maybe Maybe)>; + readonly summaryCellClass?: Maybe Maybe)>; /** Render function to render the content of cells. */ - readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; + readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; /** Render function to render the content of the header cell. */ - readonly renderHeaderCell?: Maybe< - (props: RenderHeaderCellContentProps) => ReactNode - >; + readonly renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) => ReactNode>; /** Render function to render the content of summary cells. */ - readonly renderSummaryCell?: Maybe< - (props: RenderSummaryCellContentProps) => ReactNode - >; + readonly renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>; /** Render function to render the content of group cells when using `TreeDataGrid`. */ - readonly renderGroupCell?: Maybe< - (props: RenderGroupCellContentProps) => ReactNode - >; + readonly renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>; /** Render function to render the content of edit cells. When set, the column is automatically set to be editable. */ - readonly renderEditCell?: Maybe< - (props: RenderEditCellContentProps) => ReactNode - >; + readonly renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>; /** Control whether cells can be edited with `renderEditCell`. */ - readonly editable?: Maybe boolean)>; + readonly editable?: Maybe boolean)>; /** * Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. See the {@linkcode ColSpanArgs} type. * @@ -150,7 +142,7 @@ export interface Column { * ]; * ``` */ - readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; + readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; /** * Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. See the {@linkcode ColumnFrozen} type. * @@ -229,9 +221,9 @@ interface ColumnEditorOptions { * * @group Types */ -export interface CalculatedColumn extends Column { +export interface CalculatedColumn extends Column { /** The column group that contains the column, or `undefined` if the column is not in a group */ - readonly parent: CalculatedColumnParent | undefined; + readonly parent: CalculatedColumnParent | undefined; /** The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` */ readonly idx: number; /** Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups */ @@ -243,8 +235,8 @@ export interface CalculatedColumn extends Column) => ReactNode; - readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; + readonly renderCell: (props: RenderCellContentProps) => ReactNode; + readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; } /** @@ -345,13 +337,13 @@ export interface Position { * * @group Types */ -export interface RenderCellContentProps { - column: CalculatedColumn; - row: TRow; +export interface RenderCellContentProps { + column: CalculatedColumn; + row: R; rowIdx: number; isCellEditable: boolean; tabIndex: number; - onRowChange: (row: TRow) => void; + onRowChange: (row: R) => void; } /** @@ -361,9 +353,9 @@ export interface RenderCellContentProps { * * @group Types */ -export interface RenderSummaryCellContentProps { - column: CalculatedColumn; - row: TSummaryRow; +export interface RenderSummaryCellContentProps { + column: CalculatedColumn; + row: SR; tabIndex: number; } @@ -374,11 +366,11 @@ export interface RenderSummaryCellContentProps { * * @group Types */ -export interface RenderGroupCellContentProps { +export interface RenderGroupCellContentProps { groupKey: unknown; - column: CalculatedColumn; - row: GroupRow; - childRows: readonly TRow[]; + column: CalculatedColumn; + row: GroupRow; + childRows: readonly R[]; isExpanded: boolean; tabIndex: number; toggleGroup: () => void; @@ -407,11 +399,11 @@ export interface RenderGroupCellContentProps { * * @group Types */ -export interface RenderEditCellContentProps { - column: CalculatedColumn; - row: TRow; +export interface RenderEditCellContentProps { + column: CalculatedColumn; + row: R; rowIdx: number; - onRowChange: (row: TRow, commitChanges?: boolean) => void; + onRowChange: (row: R, commitChanges?: boolean) => void; onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; } @@ -422,18 +414,18 @@ export interface RenderEditCellContentProps { * * @group Types */ -export interface RenderHeaderCellContentProps { - column: CalculatedColumn; +export interface RenderHeaderCellContentProps { + column: CalculatedColumn; sortDirection: SortDirection | undefined; priority: number | undefined; tabIndex: number; } -interface BaseRenderCellProps +interface BaseRenderCellProps extends Omit, 'children'>, Pick< - DataGridProps, + DataGridProps, 'onCellMouseDown' | 'onCellClick' | 'onCellDoubleClick' | 'onCellContextMenu' > { rowIdx: number; @@ -447,13 +439,13 @@ interface BaseRenderCellProps * * @group Types */ -export interface RenderCellProps extends BaseRenderCellProps { - column: CalculatedColumn; - row: TRow; +export interface RenderCellProps extends BaseRenderCellProps { + column: CalculatedColumn; + row: R; colSpan: number | undefined; isDraggedOver: boolean; isCellActive: boolean; - onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: TRow) => void; + onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; } export interface EditCellProps extends Pick< @@ -531,33 +523,33 @@ export type CellClipboardEvent = React.ClipboardEvent; * * @group Types */ -export interface CellMouseArgs { +export interface CellMouseArgs { /** The column object of the cell. */ - column: CalculatedColumn; + column: CalculatedColumn; /** The row object of the cell. */ - row: TRow; + row: R; /** The row index of the cell. */ rowIdx: number; /** Function to manually focus the cell. Pass `true` to immediately start editing. */ setActivePosition: (enableEditor?: boolean) => void; } -interface ActiveCellKeyDownArgs { +interface ActiveCellKeyDownArgs { mode: 'ACTIVE'; /** * column object of the active position, * undefined if the active position is a row instead of a cell */ - column: CalculatedColumn | undefined; - row: TRow; + column: CalculatedColumn | undefined; + row: R; rowIdx: number; setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; } -export interface EditCellKeyDownArgs { +export interface EditCellKeyDownArgs { mode: 'EDIT'; - column: CalculatedColumn; - row: TRow; + column: CalculatedColumn; + row: R; rowIdx: number; navigate: () => void; onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; @@ -582,9 +574,9 @@ export interface EditCellKeyDownArgs { * * @group Types */ -export type CellKeyDownArgs = - | ActiveCellKeyDownArgs - | EditCellKeyDownArgs; +export type CellKeyDownArgs = + | ActiveCellKeyDownArgs + | EditCellKeyDownArgs; /** * Arguments passed to `onActivePositionChange`. @@ -593,19 +585,19 @@ export type CellKeyDownArgs = * * @group Types */ -export interface PositionChangeArgs { +export interface PositionChangeArgs { /** row index of the active position */ rowIdx: number; /** * row object of the active position, * undefined if the active position is on a header or summary row */ - row: TRow | undefined; + row: R | undefined; /** * column object of the active position, * undefined if the active position is a row instead of a cell */ - column: CalculatedColumn | undefined; + column: CalculatedColumn | undefined; } /** @@ -615,26 +607,23 @@ export type CellMouseEventHandler = Maybe< (args: CellMouseArgs, NoInfer>, event: CellMouseEvent) => void >; -export type IterateOverViewportColumns = ( +export type IterateOverViewportColumns = ( activeColumnIdx: number -) => IteratorObject>; +) => IteratorObject>; -export type ViewportColumnWithColSpan = [ - column: CalculatedColumn, +export type ViewportColumnWithColSpan = [ + column: CalculatedColumn, isCellActive: boolean, colSpan: number | undefined ]; -export type IterateOverViewportColumnsForRow = ( +export type IterateOverViewportColumnsForRow = ( activeIdx: number | undefined, - args?: ColSpanArgs -) => IteratorObject>; + args?: ColSpanArgs +) => IteratorObject>; -export interface BaseRenderRowProps extends BaseRenderCellProps< - TRow, - TSummaryRow -> { - iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; +export interface BaseRenderRowProps extends BaseRenderCellProps { + iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; rowIdx: number; activeCellIdx: number | undefined; isRowSelectionDisabled: boolean; @@ -649,15 +638,12 @@ export interface BaseRenderRowProps extends BaseRen * * @group Types */ -export interface RenderRowProps extends BaseRenderRowProps< - TRow, - TSummaryRow -> { - row: TRow; +export interface RenderRowProps extends BaseRenderRowProps { + row: R; draggedOverCellIdx: number | undefined; - activeCellEditor: ReactElement> | undefined; - onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: TRow) => void; - rowClass: Maybe<(row: TRow, rowIdx: number) => Maybe>; + activeCellEditor: ReactElement> | undefined; + onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; + rowClass: Maybe<(row: R, rowIdx: number) => Maybe>; isTreeGrid: boolean; } @@ -682,8 +668,8 @@ export interface RowsChangeData { * * @group Types */ -export interface SelectRowEvent { - row: TRow; +export interface SelectRowEvent { + row: R; checked: boolean; isShiftClick: boolean; } @@ -706,15 +692,15 @@ export interface SelectHeaderRowEvent { * * @group Types */ -export interface FillEvent { +export interface FillEvent { columnKey: string; - sourceRow: TRow; - targetRow: TRow; + sourceRow: R; + targetRow: R; } -interface CellCopyPasteArgs { - column: CalculatedColumn; - row: TRow; +interface CellCopyPasteArgs { + column: CalculatedColumn; + row: R; } /** @@ -724,7 +710,7 @@ interface CellCopyPasteArgs { * * @group Types */ -export type CellCopyArgs = CellCopyPasteArgs; +export type CellCopyArgs = CellCopyPasteArgs; /** * Arguments passed to `onCellPaste`. * @@ -732,15 +718,15 @@ export type CellCopyArgs = CellCopyPasteArgs = CellCopyPasteArgs; +export type CellPasteArgs = CellCopyPasteArgs; /** * Represents a group row in `TreeDataGrid`. This helper type is not exported; the shape is shown for reference. * * @see {@linkcode RenderGroupCellContentProps}, {@linkcode RowHeightArgs}, {@linkcode TreeDataGrid | } */ -export interface GroupRow { - readonly childRows: readonly TRow[]; +export interface GroupRow { + readonly childRows: readonly R[]; readonly id: string; readonly parentId: unknown; readonly groupKey: unknown; @@ -804,10 +790,10 @@ export type SortDirection = 'ASC' | 'DESC'; * * @group Types */ -export type ColSpanArgs = +export type ColSpanArgs = | { readonly type: 'HEADER' } - | { readonly type: 'ROW'; readonly row: TRow } - | { readonly type: 'SUMMARY'; readonly row: TSummaryRow }; + | { readonly type: 'ROW'; readonly row: R } + | { readonly type: 'SUMMARY'; readonly row: SR }; /** * Arguments passed to `TreeDataGrid`'s `rowHeight` prop when it is a function. @@ -828,9 +814,7 @@ export type ColSpanArgs = * * @group Types */ -export type RowHeightArgs = - | { type: 'ROW'; row: TRow } - | { type: 'GROUP'; row: GroupRow }; +export type RowHeightArgs = { type: 'ROW'; row: R } | { type: 'GROUP'; row: GroupRow }; /** * Props for custom sort icon renderers. @@ -896,10 +880,10 @@ export interface RenderCheckboxProps { * * @group Types */ -export interface Renderers { - readonly renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; +export interface Renderers { + readonly renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; readonly renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>; - readonly renderRow?: Maybe<(key: Key, props: RenderRowProps) => ReactNode>; + readonly renderRow?: Maybe<(key: Key, props: RenderRowProps) => ReactNode>; readonly renderSortStatus?: Maybe<(props: RenderSortStatusProps) => ReactNode>; readonly noRowsFallback?: Maybe; } From 64cc55348c559a5268ae710f2394131aacd7d730 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 10:53:30 -0500 Subject: [PATCH 05/22] Don't repeat members inherited through internal types Members that come from a public type through an internal type, like the cell event handlers that `RenderCellProps` inherits from `BaseRenderCellProps`, which picks them from `DataGridProps`, repeated the docs of the public type. Remove them like the members inherited directly from public types, and remove the properties sections left empty, like the one of `RenderSortStatusProps`. Co-Authored-By: Claude Opus 5.5 --- README.md | 428 +++---------------------------------- scripts/generateApiDocs.ts | 85 +++++--- 2 files changed, 89 insertions(+), 424 deletions(-) diff --git a/README.md b/README.md index 1dbef71dc0..3379012b5e 100644 --- a/README.md +++ b/README.md @@ -2336,128 +2336,16 @@ Props passed to the cell renderer when using `renderers.renderCell`. #### Properties -##### onCellMouseDown? - -```ts -onCellMouseDown?: CellMouseEventHandler; -``` - -Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -```tsx -function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - event.preventGridDefault(); - } -} - -; -``` - -##### onCellClick? - -```ts -onCellClick?: CellMouseEventHandler; -``` - -Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -This event can be used to open the cell editor on a single click: - -```tsx -function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - args.setActivePosition(true); - } -} - -; -``` - -##### onCellDoubleClick? - -```ts -onCellDoubleClick?: CellMouseEventHandler; -``` - -Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -```tsx -function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - event.preventGridDefault(); - } -} - -; -``` - -##### onCellContextMenu? - -```ts -onCellContextMenu?: CellMouseEventHandler; -``` - -Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -```tsx -function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - event.preventDefault(); - // open custom context menu - } -} - -; -``` - -##### rowIdx - -```ts -rowIdx: number; -``` - -##### setActivePosition - -```ts -setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -``` - -##### column - -```ts -column: CalculatedColumn; -``` - -##### row - -```ts -row: R; -``` - -##### colSpan - -```ts -colSpan: number | undefined; -``` - -##### isDraggedOver - -```ts -isDraggedOver: boolean; -``` - -##### isCellActive - -```ts -isCellActive: boolean; -``` - -##### onRowChange - -```ts -onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; -``` +| Property | Type | Inherited from | +| ------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------- | +| `rowIdx` | `number` | | +| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | | +| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | - | +| `row` | `R` | - | +| `colSpan` | `number` \| `undefined` | - | +| `isDraggedOver` | `boolean` | - | +| `isCellActive` | `boolean` | - | +| `onRowChange` | (`column`: [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\>, `rowIdx`: `number`, `newRow`: `R`) => `void` | - | --- @@ -2595,160 +2483,21 @@ Props passed to custom row renderers. #### Properties -##### onCellMouseDown? - -```ts -onCellMouseDown?: CellMouseEventHandler; -``` - -Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -```tsx -function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - event.preventGridDefault(); - } -} - -; -``` - -##### onCellClick? - -```ts -onCellClick?: CellMouseEventHandler; -``` - -Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -This event can be used to open the cell editor on a single click: - -```tsx -function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - args.setActivePosition(true); - } -} - -; -``` - -##### onCellDoubleClick? - -```ts -onCellDoubleClick?: CellMouseEventHandler; -``` - -Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -```tsx -function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - event.preventGridDefault(); - } -} - -; -``` - -##### onCellContextMenu? - -```ts -onCellContextMenu?: CellMouseEventHandler; -``` - -Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -```tsx -function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - event.preventDefault(); - // open custom context menu - } -} - -; -``` - -##### setActivePosition - -```ts -setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -``` - -##### iterateOverViewportColumnsForRow - -```ts -iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; -``` - -##### rowIdx - -```ts -rowIdx: number; -``` - -##### activeCellIdx - -```ts -activeCellIdx: number | undefined; -``` - -##### isRowSelectionDisabled - -```ts -isRowSelectionDisabled: boolean; -``` - -##### isRowSelected - -```ts -isRowSelected: boolean; -``` - -##### gridRowStart - -```ts -gridRowStart: number; -``` - -##### row - -```ts -row: R; -``` - -##### draggedOverCellIdx - -```ts -draggedOverCellIdx: number | undefined; -``` - -##### activeCellEditor - -```ts -activeCellEditor: - | ReactElement, string | JSXElementConstructor> - | undefined; -``` - -##### onRowChange - -```ts -onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; -``` - -##### rowClass - -```ts -rowClass: Maybe<(row: R, rowIdx: number) => Maybe>; -``` - -##### isTreeGrid - -```ts -isTreeGrid: boolean; -``` +| Property | Type | Inherited from | +| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------- | +| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | | +| `iterateOverViewportColumnsForRow` | [`IterateOverViewportColumnsForRow`](#iterateoverviewportcolumnsforrow)\<`R`, `SR`\> | | +| `rowIdx` | `number` | | +| `activeCellIdx` | `number` \| `undefined` | | +| `isRowSelectionDisabled` | `boolean` | | +| `isRowSelected` | `boolean` | | +| `gridRowStart` | `number` | | +| `row` | `R` | - | +| `draggedOverCellIdx` | `number` \| `undefined` | - | +| `activeCellEditor` | \| `ReactElement`\<[`EditCellProps`](#editcellprops)\<`R`, `SR`\>, `string` \| `JSXElementConstructor`\<`any`\>\> \| `undefined` | - | +| `onRowChange` | (`column`: [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\>, `rowIdx`: `number`, `newRow`: `R`) => `void` | - | +| `rowClass` | [`Maybe`](#maybe)\<(`row`: `R`, `rowIdx`: `number`) => [`Maybe`](#maybe)\<`string`\>\> | - | +| `isTreeGrid` | `boolean` | - | --- @@ -2805,8 +2554,6 @@ Props for custom sort status renderers. - [`RenderSortIconProps`](#rendersorticonprops) - [`RenderSortPriorityProps`](#rendersortpriorityprops) -#### Properties - --- ### RenderSummaryCellContentProps @@ -3010,122 +2757,15 @@ type SortDirection = 'ASC' | 'DESC'; #### Properties -##### onCellMouseDown? - -```ts -onCellMouseDown?: CellMouseEventHandler; -``` - -Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -```tsx -function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - event.preventGridDefault(); - } -} - -; -``` - -##### onCellClick? - -```ts -onCellClick?: CellMouseEventHandler; -``` - -Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -This event can be used to open the cell editor on a single click: - -```tsx -function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - args.setActivePosition(true); - } -} - -; -``` - -##### onCellDoubleClick? - -```ts -onCellDoubleClick?: CellMouseEventHandler; -``` - -Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -```tsx -function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - event.preventGridDefault(); - } -} - -; -``` - -##### onCellContextMenu? - -```ts -onCellContextMenu?: CellMouseEventHandler; -``` - -Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. - -```tsx -function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'id') { - event.preventDefault(); - // open custom context menu - } -} - -; -``` - -##### setActivePosition - -```ts -setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -``` - -##### iterateOverViewportColumnsForRow - -```ts -iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; -``` - -##### rowIdx - -```ts -rowIdx: number; -``` - -##### activeCellIdx - -```ts -activeCellIdx: number | undefined; -``` - -##### isRowSelectionDisabled - -```ts -isRowSelectionDisabled: boolean; -``` - -##### isRowSelected - -```ts -isRowSelected: boolean; -``` - -##### gridRowStart - -```ts -gridRowStart: number; -``` +| Property | Type | Overrides | Inherited from | +| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- | --------- | -------------- | +| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | - | | +| `iterateOverViewportColumnsForRow` | [`IterateOverViewportColumnsForRow`](#iterateoverviewportcolumnsforrow)\<`R`, `SR`\> | - | - | +| `rowIdx` | `number` | | - | +| `activeCellIdx` | `number` \| `undefined` | - | - | +| `isRowSelectionDisabled` | `boolean` | - | - | +| `isRowSelected` | `boolean` | - | - | +| `gridRowStart` | `number` | - | - | --- diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index cfc2d2e625..f79eb7e6bb 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -170,40 +170,28 @@ const publicGroups = (project.groups ?? []).filter((group) => { internalGroup.children.sort((a, b) => a.name.localeCompare(b.name)); project.groups = [...publicGroups, internalGroup]; -for (const reflection of project.getReflectionsByKind(ReflectionKind.Interface)) { - if (!(reflection instanceof DeclarationReflection)) continue; - - // only list the members that are inherited from internal types, - // the members inherited from public types are listed in their own section, - // e.g. `extends Column` or `extends Omit` - const publicBaseTypes = new Set(); - for (const type of reflection.extendedTypes ?? []) { - if (!(type instanceof ReferenceType)) continue; - const [typeArgument] = type.typeArguments ?? []; - if ( - publicNames.has(type.name) || - ((type.name === 'Omit' || type.name === 'Pick') && - typeArgument instanceof ReferenceType && - publicNames.has(typeArgument.name)) - ) { - publicBaseTypes.add(type.name); - } - } - - const membersInheritedFromPublicTypes = - reflection.children?.filter((child) => { - const baseType = child.inheritedFrom?.name.split('.')[0]; - return baseType !== undefined && publicBaseTypes.has(baseType); - }) ?? []; +const interfaces = project + .getReflectionsByKind(ReflectionKind.Interface) + .filter((reflection) => reflection instanceof DeclarationReflection); + +// only list the members that are inherited from internal types, +// the members inherited from public types are listed in their own section +const membersInheritedFromPublicTypes = interfaces.flatMap( + (reflection) => reflection.children?.filter(isInheritedFromPublicType) ?? [] +); - for (const child of membersInheritedFromPublicTypes) { - project.removeReflection(child); - } +for (const member of membersInheritedFromPublicTypes) { + project.removeReflection(member); +} +for (const reflection of interfaces) { // `removeReflection` doesn't remove the members from the groups that are rendered const remainingMembers = new Set(reflection.children); - for (const group of reflection.groups ?? []) { - group.children = group.children.filter((child) => remainingMembers.has(child)); + if (reflection.groups !== undefined) { + for (const group of reflection.groups) { + group.children = group.children.filter((child) => remainingMembers.has(child)); + } + reflection.groups = reflection.groups.filter((group) => group.children.length > 0); } // TypeDoc copies the comments of the members a member redeclares, @@ -244,6 +232,43 @@ await writeFile( ) ); +// e.g. `extends Column` or `extends Omit` +function getPublicBaseTypes(reflection: InstanceType) { + const publicBaseTypes = new Set(); + for (const type of reflection.extendedTypes ?? []) { + if (!(type instanceof ReferenceType)) continue; + const [typeArgument] = type.typeArguments ?? []; + if ( + publicNames.has(type.name) || + ((type.name === 'Omit' || type.name === 'Pick') && + typeArgument instanceof ReferenceType && + publicNames.has(typeArgument.name)) + ) { + publicBaseTypes.add(type.name); + } + } + return publicBaseTypes; +} + +// a member is inherited from a public type directly, or through internal types, +// e.g. `RenderCellProps` inherits `onCellClick` from `BaseRenderCellProps`, which picks it from `DataGridProps` +function isInheritedFromPublicType(member: InstanceType): boolean { + const { inheritedFrom, parent } = member; + if (inheritedFrom === undefined) return false; + + if ( + parent instanceof DeclarationReflection && + getPublicBaseTypes(parent).has(inheritedFrom.name.split('.')[0]) + ) { + return true; + } + + const inheritedMember = inheritedFrom.reflection; + return ( + inheritedMember instanceof DeclarationReflection && isInheritedFromPublicType(inheritedMember) + ); +} + // a property can be listed in a table if its comment is a single paragraph function hasShortComment(reflection: InstanceType) { const { comment } = reflection; From 1b861ead0e44eeca3105d8dff5da83926d288eb7 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 10:56:06 -0500 Subject: [PATCH 06/22] Name destructured parameters `props` in the API reference TypeDoc names destructured parameters `__namedParameters`, which showed in the signatures of the components and render functions that destructure their props, e.g. `SelectCheckbox`. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++++++++---------- scripts/generateApiDocs.ts | 5 +++++ 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 3379012b5e..0b1e66a19b 100644 --- a/README.md +++ b/README.md @@ -1024,7 +1024,7 @@ The default row component. Can be wrapped via the `renderers.renderRow` prop. ### SelectCheckbox() ```ts -function SelectCheckbox(__namedParameters: SelectCheckboxProps): ReactNode; +function SelectCheckbox(props: SelectCheckboxProps): ReactNode; ``` A component for rendering row selection checkboxes. @@ -1036,7 +1036,7 @@ The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: bo ### ToggleGroup() ```ts -function ToggleGroup(__namedParameters: RenderGroupCellContentProps): Element; +function ToggleGroup(props: RenderGroupCellContentProps): Element; ``` Low-level component used by `renderToggleGroup` to render the expand/collapse control. Useful if you build a custom group cell renderer. @@ -1047,7 +1047,7 @@ Low-level component used by `renderToggleGroup` to render the expand/collapse co ```ts function TreeDataGrid( - __namedParameters: TreeDataGridProps + props: TreeDataGridProps ): Element; ``` @@ -1308,7 +1308,7 @@ function CustomSelectCell({ row }: RenderCellContentProps) { ### renderCheckbox() ```ts -function renderCheckbox(__namedParameters: RenderCheckboxProps): Element; +function renderCheckbox(props: RenderCheckboxProps): Element; ``` Renders a checkbox input with proper styling and accessibility. @@ -1330,9 +1330,7 @@ import { DataGrid, renderCheckbox } from 'react-data-grid'; ### renderHeaderCell() ```ts -function renderHeaderCell( - __namedParameters: RenderHeaderCellContentProps -): string | Element; +function renderHeaderCell(props: RenderHeaderCellContentProps): string | Element; ``` The default header cell content renderer. Renders sortable columns with sort indicators. @@ -1357,7 +1355,7 @@ const columns: readonly Column[] = [ ### renderSortIcon() ```ts -function renderSortIcon(__namedParameters: RenderSortIconProps): Element | null; +function renderSortIcon(props: RenderSortIconProps): Element | null; ``` Renders the sort direction arrow icon. @@ -1367,7 +1365,7 @@ Renders the sort direction arrow icon. ### renderSortPriority() ```ts -function renderSortPriority(__namedParameters: RenderSortPriorityProps): number | undefined; +function renderSortPriority(props: RenderSortPriorityProps): number | undefined; ``` Renders the sort priority number for multi-column sorting. @@ -1377,7 +1375,7 @@ Renders the sort priority number for multi-column sorting. ### renderTextEditor() ```ts -function renderTextEditor(__namedParameters: RenderEditCellContentProps): Element; +function renderTextEditor(props: RenderEditCellContentProps): Element; ``` A basic text editor provided for convenience. diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index f79eb7e6bb..9be78d06a9 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -134,6 +134,11 @@ app.converter.on(Converter.EVENT_RESOLVE_END, ({ project }) => { ) { delete reflection.defaultValue; } + + // TypeDoc names destructured parameters `__namedParameters` + if (reflection instanceof ParameterReflection && reflection.name === '__namedParameters') { + reflection.name = 'props'; + } } }); From 17dbe0d9fab3de7195c6323d6a620ca15cb58cc3 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 11:07:57 -0500 Subject: [PATCH 07/22] Show components as JSX elements in the API reference - Title components like the previous README, e.g. `` instead of `DataGrid()`, and show their props instead of a function signature - List the components with a props interface first, each followed by its props interface, then the other components Co-Authored-By: Claude Opus 5.5 --- README.md | 100 ++++++++++++++++--------------------- scripts/generateApiDocs.ts | 41 ++++++++++++++- 2 files changed, 82 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 0b1e66a19b..3734325662 100644 --- a/README.md +++ b/README.md @@ -243,21 +243,9 @@ Replace default components with custom implementations using the [`renderers`](# ## Components -### Cell +### `` -```ts -const Cell: (props: RenderCellProps) => Element; -``` - -The default cell component. Can be wrapped via the `renderers.renderCell` prop. - ---- - -### DataGrid() - -```ts -function DataGrid(props: DataGridProps): Element; -``` +**Props:** [`DataGridProps`](#datagridprops)\<`R`, `SR`, `K`\> Main API component to render a data grid of rows and columns @@ -1011,45 +999,9 @@ Optional attribute to help with Cypress (or similar) selectors. --- -### Row - -```ts -const Row: (props: RenderRowProps) => Element; -``` - -The default row component. Can be wrapped via the `renderers.renderRow` prop. - ---- - -### SelectCheckbox() - -```ts -function SelectCheckbox(props: SelectCheckboxProps): ReactNode; -``` - -A component for rendering row selection checkboxes. - -The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. - ---- - -### ToggleGroup() - -```ts -function ToggleGroup(props: RenderGroupCellContentProps): Element; -``` - -Low-level component used by `renderToggleGroup` to render the expand/collapse control. Useful if you build a custom group cell renderer. - ---- - -### TreeDataGrid() +### `` -```ts -function TreeDataGrid( - props: TreeDataGridProps -): Element; -``` +**Props:** [`TreeDataGridProps`](#treedatagridprops)\<`R`, `SR`, `K`\> `TreeDataGrid` is a component built on top of `DataGrid` to add hierarchical row grouping. This implements the [Treegrid pattern](https://www.w3.org/WAI/ARIA/apg/patterns/treegrid/). @@ -1222,6 +1174,40 @@ Function to generate unique IDs for group rows. If not provided, a default imple :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. +--- + +### `` + +**Props:** [`RenderCellProps`](#rendercellprops)\<`R`, `SR`\> + +The default cell component. Can be wrapped via the `renderers.renderCell` prop. + +--- + +### `` + +**Props:** [`RenderRowProps`](#renderrowprops)\<`R`, `SR`\> + +The default row component. Can be wrapped via the `renderers.renderRow` prop. + +--- + +### `` + +**Props:** [`SelectCheckboxProps`](#selectcheckboxprops) + +A component for rendering row selection checkboxes. + +The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. + +--- + +### `` + +**Props:** [`RenderGroupCellContentProps`](#rendergroupcellcontentprops)\<`R`, `SR`\> + +Low-level component used by `renderToggleGroup` to render the expand/collapse control. Useful if you build a custom group cell renderer. + ## Hooks ### useHeaderRowSelection() @@ -2326,7 +2312,7 @@ Props passed to the cell renderer when using `renderers.renderCell`. #### See -[`renderers.renderCell`](#renderers), [``](#cell) +[`renderers.renderCell`](#renderers), [``](#cell-) #### Extends @@ -2353,7 +2339,7 @@ Props for custom checkbox renderers. #### See -[`renderCheckbox`](#rendercheckbox) function, [`renderers.renderCheckbox`](#renderers), [``](#selectcheckbox) +[`renderCheckbox`](#rendercheckbox) function, [`renderers.renderCheckbox`](#renderers), [``](#selectcheckbox-) #### Properties @@ -2432,7 +2418,7 @@ Props passed to group cell content renderers (`column.renderGroupCell`) when usi #### See -[`column.renderGroupCell`](#rendergroupcell), [`renderToggleGroup`](#rendertogglegroup) function, [``](#togglegroup) +[`column.renderGroupCell`](#rendergroupcell), [`renderToggleGroup`](#rendertogglegroup) function, [``](#togglegroup-) #### Properties @@ -2473,7 +2459,7 @@ Props passed to custom row renderers. #### See -[`renderers.renderRow`](#renderers), [``](#row) +[`renderers.renderRow`](#renderers), [``](#row-) #### Extends @@ -2888,7 +2874,7 @@ Represents a group row in `TreeDataGrid`. This helper type is not exported; the #### See -[`RenderGroupCellContentProps`](#rendergroupcellcontentprops), [`RowHeightArgs`](#rowheightargs), [``](#treedatagrid) +[`RenderGroupCellContentProps`](#rendergroupcellcontentprops), [`RowHeightArgs`](#rowheightargs), [``](#treedatagrid-) #### Properties diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index 9be78d06a9..1d6e2d7f3e 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -23,6 +23,7 @@ const { ReferenceType, ReflectionGroup, ReflectionKind, + ReflectionType, SignatureReflection, TSConfigReader, Type, @@ -32,6 +33,8 @@ const { const { MarkdownTheme, MarkdownThemeContext } = await import('typedoc-plugin-markdown'); const readmePath = 'README.md'; +// the components of the "Components" section, without their props interfaces +const components = new Set(); const startMarker = ''; const endMarker = ''; @@ -53,12 +56,27 @@ class ReadmeThemeContext extends MarkdownThemeContext { constructor(...args: ConstructorParameters) { super(...args); - const { groups } = this.partials; + const { declarationTitle, groups, memberTitle, signatureTitle } = this.partials; const { useTableFormat: isDefaultTableFormat } = this.helpers; let isTableInterface = false; + // components are used as JSX elements, so show their props instead of a function signature + const getComponentProps = (signature: SignatureModel | undefined) => { + const propsType = signature?.parameters?.[0]?.type; + return propsType === undefined ? '' : `**Props:** ${this.partials.someType(propsType)}`; + }; + this.partials = { ...this.partials, + memberTitle: (model) => + components.has(model) ? `\`<${model.name} />\`` : memberTitle(model), + signatureTitle: (model, options) => + components.has(model.parent) ? getComponentProps(model) : signatureTitle(model, options), + // e.g. `Row`, a memoized component + declarationTitle: (model) => + components.has(model) && model.type instanceof ReflectionType + ? getComponentProps(model.type.declaration.signatures?.[0]) + : declarationTitle(model), // list the properties of an interface in a table, unless a property has more than a short description groups(model: ContainerReflection, options: Parameters[1]) { isTableInterface = @@ -175,6 +193,22 @@ const publicGroups = (project.groups ?? []).filter((group) => { internalGroup.children.sort((a, b) => a.name.localeCompare(b.name)); project.groups = [...publicGroups, internalGroup]; +// list the components with a props interface first, each followed by its props interface, +// e.g. `DataGrid` and `DataGridProps`, then the other components +const componentsGroup = publicGroups.find((group) => group.title === 'Components'); +if (componentsGroup !== undefined) { + const names = new Set(componentsGroup.children.map((child) => child.name)); + const getSortKey = ({ name }: { name: string }) => { + const component = name.endsWith('Props') ? name.slice(0, -'Props'.length) : name; + return names.has(`${component}Props`) ? `0 ${component} ${name}` : `1 ${name}`; + }; + componentsGroup.children.sort((a, b) => getSortKey(a).localeCompare(getSortKey(b))); + + for (const child of componentsGroup.children) { + if (!child.kindOf(ReflectionKind.Interface)) components.add(child); + } +} + const interfaces = project .getReflectionsByKind(ReflectionKind.Interface) .filter((reflection) => reflection instanceof DeclarationReflection); @@ -320,7 +354,10 @@ function replaceAnchors(precedingMarkdown: string, api: string, followingMarkdow const heading = /^(#{1,6}) (.+)$/.exec(line); if (heading !== null) { const headingSlug = slug(heading[2]); - const name = getHeadingText(heading[2]).replace(/(?:\(\)|\?)$/, ''); + // e.g. `DataGrid` for ``, `renderCheckbox` for `renderCheckbox()` + const name = getHeadingText(heading[2]) + .replace(/^<(.+) \/>$/, '$1') + .replace(/(?:\(\)|\?)$/, ''); if (heading[1].length === 3) { item = name; memberAnchors.set(name, headingSlug); From 4baada5f299e68e9a93e79f8262560c8c167af93 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 11:59:12 -0500 Subject: [PATCH 08/22] Use TypeScript 6 for TypeDoc as recommended by the TypeScript team Install TypeScript 6 as `typescript` and TypeScript 7 as `@typescript/native`, the setup recommended for tools that need the TypeScript API, which TypeScript 7 doesn't provide yet. TypeScript 6's package also provides a `tsc` binary, which npm linked instead of TypeScript 7's, so `vp run typecheck` used TypeScript 6. With this setup, `tsc` is TypeScript 7, and TypeDoc no longer needs a resolve hook, a peer dependency override, or `skipLibCheck`. Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 2 +- .vscode/settings.json | 2 +- AGENTS.md | 3 +- package-lock.json | 92 +++++++++++++++++++------------------- package.json | 7 +-- scripts/generateApiDocs.ts | 32 +++++-------- tsconfig.node.json | 8 ++-- vite.config.ts | 3 +- 8 files changed, 69 insertions(+), 80 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 11019201ea..dc3ccbc2d1 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -18,6 +18,7 @@ updates: typescript: patterns: - 'typescript' + - '@typescript/native' react: patterns: - 'react' @@ -28,7 +29,6 @@ updates: patterns: - 'typedoc' - 'typedoc-*' - - '@typescript/typescript6' # everything else: single PR for minor/patch bumps, # majors still land individually dependencies: diff --git a/.vscode/settings.json b/.vscode/settings.json index 0e546f4539..858660d493 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -9,7 +9,7 @@ "editor.formatOnSave": true, "editor.formatOnSaveMode": "file", "js/ts.experimental.useTsgo": true, - "js/ts.tsdk.path": "./node_modules/typescript", + "js/ts.tsdk.path": "./node_modules/@typescript/native", // ESLint is only used for Markdown; JS/TS is linted by the Oxc extension "eslint.validate": ["markdown"], "eslint.problems.shortenToSingleLine": true, diff --git a/AGENTS.md b/AGENTS.md index 6a0e9f7db6..a9be9a5ef0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,7 +55,8 @@ The project uses [Vite+](https://viteplus.dev/guide/), whose global `vp` CLI wra - `vp ` runs a built-in command, e.g., `vp dev`, `vp check`, `vp test`, `vp pack`, `vp build`. - `vp run ` runs a task from `vite.config.ts`, e.g., `vp run typecheck`, `vp run eslint`, `vp run docs`, `vp run ci`. - Run `vp install` after pulling changes. -- `vp run docs` runs TypeDoc with `typedoc-plugin-markdown` (config in `typedoc.json`). TypeDoc does not support TypeScript 7 yet, so `scripts/generateApiDocs.ts` resolves TypeDoc's `typescript` imports to `@typescript/typescript6`; the `typescript` package stays on TypeScript 7. +- `vp run docs` runs TypeDoc with `typedoc-plugin-markdown` (config in `typedoc.json`). +- Two TypeScript versions are installed: TypeScript 7 as `@typescript/native`, which provides `tsc` and is used by the editor and `vp pack`, and TypeScript 6 as `typescript` (`@typescript/typescript6`), for TypeDoc, which needs the TypeScript API that TypeScript 7 does not provide yet. ## Validation diff --git a/package-lock.json b/package-lock.json index 7c6faea918..ba98ef5ef7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,7 @@ "@types/node": "^26.0.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", - "@typescript/typescript6": "^6.0.2", + "@typescript/native": "npm:typescript@beta", "@vitejs/plugin-react": "^6.1.1", "@vitest/browser-playwright": "5.0.5", "@vitest/coverage-istanbul": "5.0.5", @@ -34,7 +34,7 @@ "typedoc": "^0.28.20", "typedoc-plugin-markdown": "^4.14.1", "typedoc-plugin-missing-exports": "^4.1.4", - "typescript": "beta", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0", "vite-plus": "1.3.0", "vitest": "5.0.5", @@ -2562,6 +2562,43 @@ "dev": true, "license": "MIT" }, + "node_modules/@typescript/native": { + "name": "typescript", + "version": "7.1.0-beta", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.1.0-beta.tgz", + "integrity": "sha512-cjWjZAJDsmZzsNC5GwHNlW0YPM65jZa5oR0KyQcYX3KSVIfTvtBq//vewISyatKk4OLi5grZjHhIVE9fdrw1UQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.1.0-beta", + "@typescript/typescript-android-arm64": "7.1.0-beta", + "@typescript/typescript-darwin-arm64": "7.1.0-beta", + "@typescript/typescript-darwin-x64": "7.1.0-beta", + "@typescript/typescript-freebsd-arm64": "7.1.0-beta", + "@typescript/typescript-freebsd-x64": "7.1.0-beta", + "@typescript/typescript-linux-arm": "7.1.0-beta", + "@typescript/typescript-linux-arm64": "7.1.0-beta", + "@typescript/typescript-linux-loong64": "7.1.0-beta", + "@typescript/typescript-linux-mips64el": "7.1.0-beta", + "@typescript/typescript-linux-ppc64": "7.1.0-beta", + "@typescript/typescript-linux-riscv64": "7.1.0-beta", + "@typescript/typescript-linux-s390x": "7.1.0-beta", + "@typescript/typescript-linux-x64": "7.1.0-beta", + "@typescript/typescript-netbsd-arm64": "7.1.0-beta", + "@typescript/typescript-netbsd-x64": "7.1.0-beta", + "@typescript/typescript-openbsd-arm64": "7.1.0-beta", + "@typescript/typescript-openbsd-x64": "7.1.0-beta", + "@typescript/typescript-sunos-x64": "7.1.0-beta", + "@typescript/typescript-win32-arm64": "7.1.0-beta", + "@typescript/typescript-win32-x64": "7.1.0-beta" + } + }, "node_modules/@typescript/old": { "name": "typescript", "version": "6.0.3", @@ -2934,19 +2971,6 @@ "node": ">=16.20.0" } }, - "node_modules/@typescript/typescript6": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript6/-/typescript6-6.0.2.tgz", - "integrity": "sha512-mbCddXd+jm7hfx7w2YU64/Av4/NqqeG3GoRZgxPcgoTxYjhrcfJRw9ULch71SS4G+Q3bOXFhRvPqjguN0Hyp5w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@typescript/old": "npm:typescript@^6" - }, - "bin": { - "tsc6": "bin/tsc6" - } - }, "node_modules/@vitejs/plugin-react": { "version": "6.1.2", "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz", @@ -7251,39 +7275,17 @@ } }, "node_modules/typescript": { - "version": "7.1.0-beta", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.1.0-beta.tgz", - "integrity": "sha512-cjWjZAJDsmZzsNC5GwHNlW0YPM65jZa5oR0KyQcYX3KSVIfTvtBq//vewISyatKk4OLi5grZjHhIVE9fdrw1UQ==", + "name": "@typescript/typescript6", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript6/-/typescript6-6.0.2.tgz", + "integrity": "sha512-mbCddXd+jm7hfx7w2YU64/Av4/NqqeG3GoRZgxPcgoTxYjhrcfJRw9ULch71SS4G+Q3bOXFhRvPqjguN0Hyp5w==", "dev": true, "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc" - }, - "engines": { - "node": ">=16.20.0" + "dependencies": { + "@typescript/old": "npm:typescript@^6" }, - "optionalDependencies": { - "@typescript/typescript-aix-ppc64": "7.1.0-beta", - "@typescript/typescript-android-arm64": "7.1.0-beta", - "@typescript/typescript-darwin-arm64": "7.1.0-beta", - "@typescript/typescript-darwin-x64": "7.1.0-beta", - "@typescript/typescript-freebsd-arm64": "7.1.0-beta", - "@typescript/typescript-freebsd-x64": "7.1.0-beta", - "@typescript/typescript-linux-arm": "7.1.0-beta", - "@typescript/typescript-linux-arm64": "7.1.0-beta", - "@typescript/typescript-linux-loong64": "7.1.0-beta", - "@typescript/typescript-linux-mips64el": "7.1.0-beta", - "@typescript/typescript-linux-ppc64": "7.1.0-beta", - "@typescript/typescript-linux-riscv64": "7.1.0-beta", - "@typescript/typescript-linux-s390x": "7.1.0-beta", - "@typescript/typescript-linux-x64": "7.1.0-beta", - "@typescript/typescript-netbsd-arm64": "7.1.0-beta", - "@typescript/typescript-netbsd-x64": "7.1.0-beta", - "@typescript/typescript-openbsd-arm64": "7.1.0-beta", - "@typescript/typescript-openbsd-x64": "7.1.0-beta", - "@typescript/typescript-sunos-x64": "7.1.0-beta", - "@typescript/typescript-win32-arm64": "7.1.0-beta", - "@typescript/typescript-win32-x64": "7.1.0-beta" + "bin": { + "tsc6": "bin/tsc6" } }, "node_modules/uc.micro": { diff --git a/package.json b/package.json index 4a962c26d1..65660369b3 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,7 @@ "@types/node": "^26.0.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", - "@typescript/typescript6": "^6.0.2", + "@typescript/native": "npm:typescript@beta", "@vitejs/plugin-react": "^6.1.1", "@vitest/browser-playwright": "5.0.5", "@vitest/coverage-istanbul": "5.0.5", @@ -55,7 +55,7 @@ "typedoc": "^0.28.20", "typedoc-plugin-markdown": "^4.14.1", "typedoc-plugin-missing-exports": "^4.1.4", - "typescript": "beta", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0", "vite-plus": "1.3.0", "vitest": "5.0.5", @@ -67,9 +67,6 @@ }, "overrides": { "oxc-transform-react": "$oxc-transform-react", - "typedoc": { - "typescript": "$typescript" - }, "typescript": "$typescript", "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0", "vitest": "5.0.5" diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index 1d6e2d7f3e..f3bf854e04 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -1,18 +1,6 @@ import { readFile, writeFile } from 'node:fs/promises'; -import { registerHooks } from 'node:module'; import GithubSlugger from 'github-slugger'; -import type { ContainerReflection, SignatureReflection as SignatureModel, SomeType } from 'typedoc'; - -// TODO: remove when TypeDoc supports TypeScript 7 -// TypeDoc relies on the TypeScript API, which TypeScript 7 does not provide yet, -// so TypeDoc's `typescript` imports resolve to TypeScript 6 instead -registerHooks({ - resolve(specifier, context, nextResolve) { - return nextResolve(specifier === 'typescript' ? '@typescript/typescript6' : specifier, context); - } -}); - -const { +import { Application, Comment, Context, @@ -28,9 +16,11 @@ const { TSConfigReader, Type, TypeDocReader, - TypeParameterReflection -} = await import('typedoc'); -const { MarkdownTheme, MarkdownThemeContext } = await import('typedoc-plugin-markdown'); + TypeParameterReflection, + type ContainerReflection, + type SomeType +} from 'typedoc'; +import { MarkdownTheme, MarkdownThemeContext } from 'typedoc-plugin-markdown'; const readmePath = 'README.md'; // the components of the "Components" section, without their props interfaces @@ -61,7 +51,7 @@ class ReadmeThemeContext extends MarkdownThemeContext { let isTableInterface = false; // components are used as JSX elements, so show their props instead of a function signature - const getComponentProps = (signature: SignatureModel | undefined) => { + const getComponentProps = (signature: SignatureReflection | undefined) => { const propsType = signature?.parameters?.[0]?.type; return propsType === undefined ? '' : `**Props:** ${this.partials.someType(propsType)}`; }; @@ -84,7 +74,7 @@ class ReadmeThemeContext extends MarkdownThemeContext { return groups(model, options); }, // the signatures already show the return types - signatureReturns: (model: SignatureModel, options: { headingLevel: number }) => { + signatureReturns: (model: SignatureReflection, options: { headingLevel: number }) => { const returnsTag = model.comment?.getTag('@returns'); if (returnsTag === undefined) return ''; return `${'#'.repeat(options.headingLevel)} ${i18n.theme_returns()}\n\n${this.helpers.getCommentParts(returnsTag.content)}`; @@ -272,7 +262,7 @@ await writeFile( ); // e.g. `extends Column` or `extends Omit` -function getPublicBaseTypes(reflection: InstanceType) { +function getPublicBaseTypes(reflection: DeclarationReflection) { const publicBaseTypes = new Set(); for (const type of reflection.extendedTypes ?? []) { if (!(type instanceof ReferenceType)) continue; @@ -291,7 +281,7 @@ function getPublicBaseTypes(reflection: InstanceType): boolean { +function isInheritedFromPublicType(member: DeclarationReflection): boolean { const { inheritedFrom, parent } = member; if (inheritedFrom === undefined) return false; @@ -309,7 +299,7 @@ function isInheritedFromPublicType(member: InstanceType) { +function hasShortComment(reflection: DeclarationReflection) { const { comment } = reflection; if (comment === undefined) return true; const summary = Comment.combineDisplayParts(comment.summary); diff --git a/tsconfig.node.json b/tsconfig.node.json index 6523361c29..30a83edc1c 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -1,12 +1,10 @@ { "extends": "./tsconfig.base.json", "compilerOptions": { - "lib": ["ESNext"], + // `DOM` for the `WebAssembly` types of `@shikijs/types`, a dependency of TypeDoc + "lib": ["ESNext", "DOM"], "module": "NodeNext", - "types": ["node"], - // TODO: remove when TypeDoc supports TypeScript 7 - // TypeDoc's types import the TypeScript 6 API, which TypeScript 7 does not provide - "skipLibCheck": true + "types": ["node"] }, "include": ["eslint.config.ts", "scripts/**/*"] } diff --git a/vite.config.ts b/vite.config.ts index ef7ef91100..658b0aea87 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -54,7 +54,8 @@ async function dragFill( // TODO: remove when vite-plus detects TypeScript 7.1 as TypeScript 7 async function getTscPath(): Promise { - const { default: getExePath } = await import('./node_modules/typescript/lib/getExePath.js'); + const { default: getExePath } = + await import('./node_modules/@typescript/native/lib/getExePath.js'); return getExePath(); } From ff508405f68ab597ba95a371366834887dce973d Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 16:23:33 -0500 Subject: [PATCH 09/22] Generate the API reference from `lib/index.d.ts` instead of TypeDoc Replace TypeDoc and `typedoc-plugin-markdown` with a smaller generator that parses the declarations and JSDoc comments of `lib/index.d.ts`, which `vp pack` bundles with TypeScript 7, using `oxc-parser`: - Only TypeScript 7 is needed again, as the generator doesn't rely on the TypeScript API - Types are shown as copyable declarations with their comments, like the previous README, instead of tables - The layout and labels follow the previous README Also replace the `:warning:` and `:bulb:` emoji shortcodes with emoji, as editors don't render shortcodes in hovers. Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 5 - .vscode/settings.json | 2 +- AGENTS.md | 5 +- README.md | 1653 +++++++++++++++--------------------- package-lock.json | 712 +++++++++------- package.json | 7 +- scripts/generateApiDocs.ts | 626 ++++++-------- src/DataGrid.tsx | 16 +- src/TreeDataGrid.tsx | 4 +- src/index.ts | 5 - src/types.ts | 47 +- tsconfig.node.json | 3 +- typedoc.json | 38 - vite.config.ts | 28 +- 14 files changed, 1417 insertions(+), 1734 deletions(-) delete mode 100644 typedoc.json diff --git a/.github/dependabot.yml b/.github/dependabot.yml index dc3ccbc2d1..c6fa222447 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -18,17 +18,12 @@ updates: typescript: patterns: - 'typescript' - - '@typescript/native' react: patterns: - 'react' - 'react-dom' - '@types/react' - '@types/react-dom' - typedoc: - patterns: - - 'typedoc' - - 'typedoc-*' # everything else: single PR for minor/patch bumps, # majors still land individually dependencies: diff --git a/.vscode/settings.json b/.vscode/settings.json index 858660d493..0e546f4539 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -9,7 +9,7 @@ "editor.formatOnSave": true, "editor.formatOnSaveMode": "file", "js/ts.experimental.useTsgo": true, - "js/ts.tsdk.path": "./node_modules/@typescript/native", + "js/ts.tsdk.path": "./node_modules/typescript", // ESLint is only used for Markdown; JS/TS is linted by the Oxc extension "eslint.validate": ["markdown"], "eslint.problems.shortenToSingleLine": true, diff --git a/AGENTS.md b/AGENTS.md index a9be9a5ef0..818a388810 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ website/ # demo site (Vite + TanStack Router) ## Conventions - **Public API** — all exports flow through `src/index.ts`. Keep `README.md` in sync with user-facing changes. -- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. Every export from `src/index.ts` needs a `@group` tag with one of the sections in `groupOrder` of `typedoc.json` (Components, Hooks, Render Functions, Context, Other, Types). Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tags; add new TypeDoc tags to `definedTags` of `jsdoc/check-tag-names` in `vite.config.ts`. In the hand-written sections of the README, give links to API members the member as title, e.g., ``[`width`](#width "Column.width")``, so `vp run docs` keeps their anchor up to date. +- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. Every export from `src/index.ts` needs a `@group` tag with one of the sections in `scripts/generateApiDocs.ts` (Components, Hooks, Render Functions, Context, Other, Types). Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tags; add new tags to `definedTags` of `jsdoc/check-tag-names` in `vite.config.ts`. In the hand-written sections of the README, give links to API members the member as title, e.g., ``[`width`](#width "Column.width")``, so `vp run docs` keeps their anchor up to date. - **Docs** — keep `AGENTS.md` in sync with tooling, conventions, or architectural changes. - **Default renderers** — `DataGridRenderersContext` allows overriding default renderers (`renderCheckbox`, `renderSortStatus`, `renderRow`, `renderCell`, `noRowsFallback`) without prop-drilling. - **TypeScript strict** with `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, `erasableSyntaxOnly`. Distinguish missing properties from `undefined` values. @@ -55,8 +55,7 @@ The project uses [Vite+](https://viteplus.dev/guide/), whose global `vp` CLI wra - `vp ` runs a built-in command, e.g., `vp dev`, `vp check`, `vp test`, `vp pack`, `vp build`. - `vp run ` runs a task from `vite.config.ts`, e.g., `vp run typecheck`, `vp run eslint`, `vp run docs`, `vp run ci`. - Run `vp install` after pulling changes. -- `vp run docs` runs TypeDoc with `typedoc-plugin-markdown` (config in `typedoc.json`). -- Two TypeScript versions are installed: TypeScript 7 as `@typescript/native`, which provides `tsc` and is used by the editor and `vp pack`, and TypeScript 6 as `typescript` (`@typescript/typescript6`), for TypeDoc, which needs the TypeScript API that TypeScript 7 does not provide yet. +- `vp run docs` runs `vp pack`, then `scripts/generateApiDocs.ts`, which parses the declarations and JSDoc comments of `lib/index.d.ts` with `oxc-parser`. ## Validation diff --git a/README.md b/README.md index 3734325662..1f0f250bc1 100644 --- a/README.md +++ b/README.md @@ -241,35 +241,35 @@ Replace default components with custom implementations using the [`renderers`](# -## Components +### Components -### `` - -**Props:** [`DataGridProps`](#datagridprops)\<`R`, `SR`, `K`\> +#### `` Main API component to render a data grid of rows and columns -#### Example +**Props:** [`DataGridProps`](#datagridprops) + +**Example:** ```tsx ``` ---- - -### DataGridProps +#### `DataGridProps` -#### Properties +```ts +interface DataGridProps { … } +``` -##### ref? +##### `ref?` ```ts -ref?: Maybe>; +ref?: Maybe>; ``` Optional ref for imperative APIs like scrolling to or focusing a cell. See [`DataGridHandle`](#datagridhandle). -##### columns +##### `columns` ```ts columns: readonly ColumnOrColumnGroup[]; @@ -277,9 +277,9 @@ columns: readonly ColumnOrColumnGroup[]; An array of column definitions and/or column groups. See the [`ColumnOrColumnGroup`](#columnorcolumngroup) type for all available options. -:warning: **Performance:** Passing a new `columns` array will trigger a re-render and recalculation for the entire grid. Always memoize this prop using `useMemo` or define it outside the component to avoid unnecessary re-renders. +⚠️ **Performance:** Passing a new `columns` array will trigger a re-render and recalculation for the entire grid. Always memoize this prop using `useMemo` or define it outside the component to avoid unnecessary re-renders. -##### rows +##### `rows` ```ts rows: readonly R[]; @@ -287,7 +287,7 @@ rows: readonly R[]; An array of rows. The row data can be of any type. -:bulb: **Performance:** The grid is optimized for efficient rendering: +💡 **Performance:** The grid is optimized for efficient rendering: - **Virtualization**: Only visible rows are rendered in the DOM - **Individual row updates**: Row components are memoized, so updating a single row object will only re-render that specific row, not all rows @@ -302,7 +302,7 @@ An array of rows. The row data can be of any type. setRows(rows.map((row) => ({ ...row }))); ``` -##### topSummaryRows? +##### `topSummaryRows?` ```ts topSummaryRows?: Maybe; @@ -310,9 +310,9 @@ topSummaryRows?: Maybe; Rows pinned at the top of the grid for summary purposes. -:warning: **Performance:** Memoize this array to prevent internal memoization invalidation. +⚠️ **Performance:** Memoize this array to prevent internal memoization invalidation. -##### bottomSummaryRows? +##### `bottomSummaryRows?` ```ts bottomSummaryRows?: Maybe; @@ -320,9 +320,9 @@ bottomSummaryRows?: Maybe; Rows pinned at the bottom of the grid for summary purposes. -:warning: **Performance:** Memoize this array to prevent internal memoization invalidation. +⚠️ **Performance:** Memoize this array to prevent internal memoization invalidation. -##### rowKeyGetter? +##### `rowKeyGetter?` ```ts rowKeyGetter?: Maybe<(row: R) => K>; @@ -347,11 +347,11 @@ function MyGrid() { } ``` -:bulb: While optional, setting this prop is recommended for optimal performance, as the returned value is used to set the `key` prop on the row elements. +💡 While optional, setting this prop is recommended for optimal performance, as the returned value is used to set the `key` prop on the row elements. -:warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. +⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. -##### onRowsChange? +##### `onRowsChange?` ```ts onRowsChange?: Maybe<(rows: R[], data: RowsChangeData) => void>; @@ -373,7 +373,7 @@ function MyGrid() { } ``` -##### rowHeight? +##### `rowHeight?` ```ts rowHeight?: Maybe number)>; @@ -393,13 +393,11 @@ function getRowHeight(row) { ; ``` -:warning: **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. - -###### Default Value +⚠️ **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. -`35` pixels +**Default:** `35` pixels -##### headerRowHeight? +##### `headerRowHeight?` ```ts headerRowHeight?: Maybe; @@ -407,11 +405,9 @@ headerRowHeight?: Maybe; Height of the header row in pixels. -###### Default Value +**Default:** `rowHeight` when it is a number, otherwise `35` pixels -`rowHeight` when it is a number, otherwise `35` pixels - -##### summaryRowHeight? +##### `summaryRowHeight?` ```ts summaryRowHeight?: Maybe; @@ -430,11 +426,9 @@ Height of each summary row in pixels. /> ``` -###### Default Value - -`rowHeight` when it is a number, otherwise `35` pixels +**Default:** `rowHeight` when it is a number, otherwise `35` pixels -##### columnWidths? +##### `columnWidths?` ```ts columnWidths?: Maybe; @@ -454,7 +448,7 @@ function addNewRow() { return ``` -##### onColumnWidthsChange? +##### `onColumnWidthsChange?` ```ts onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; @@ -462,7 +456,7 @@ onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; Callback triggered when column widths change. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths-1) type. -##### selectedRows? +##### `selectedRows?` ```ts selectedRows?: Maybe>; @@ -470,7 +464,7 @@ selectedRows?: Maybe>; A set of selected row keys. `rowKeyGetter` is required for row selection to work. -##### isRowSelectionDisabled? +##### `isRowSelectionDisabled?` ```ts isRowSelectionDisabled?: Maybe<(row: R) => boolean>; @@ -478,7 +472,7 @@ isRowSelectionDisabled?: Maybe<(row: R) => boolean>; Function to determine if row selection is disabled for a specific row. -##### onSelectedRowsChange? +##### `onSelectedRowsChange?` ```ts onSelectedRowsChange?: Maybe<(selectedRows: Set) => void>; @@ -521,7 +515,7 @@ function MyGrid() { } ``` -##### sortColumns? +##### `sortColumns?` ```ts sortColumns?: Maybe; @@ -531,7 +525,7 @@ An array of sorted columns. See the [`SortColumn`](#sortcolumn) type. Sorting is controlled: the grid does not reorder `rows` for you. Apply the sorting to your `rows` state (or derived rows) based on `sortColumns`. -##### onSortColumnsChange? +##### `onSortColumnsChange?` ```ts onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>; @@ -576,7 +570,7 @@ function onSortColumnsChange(sortColumns: SortColumn[]) { } ``` -##### defaultColumnOptions? +##### `defaultColumnOptions?` ```ts defaultColumnOptions?: Maybe>; @@ -601,7 +595,7 @@ function MyGrid() { } ``` -##### onCellMouseDown? +##### `onCellMouseDown?` ```ts onCellMouseDown?: CellMouseEventHandler; @@ -619,7 +613,7 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -##### onCellClick? +##### `onCellClick?` ```ts onCellClick?: CellMouseEventHandler; @@ -639,7 +633,7 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -##### onCellDoubleClick? +##### `onCellDoubleClick?` ```ts onCellDoubleClick?: CellMouseEventHandler; @@ -657,7 +651,7 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -##### onCellContextMenu? +##### `onCellContextMenu?` ```ts onCellContextMenu?: CellMouseEventHandler; @@ -676,7 +670,7 @@ function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -##### onCellKeyDown? +##### `onCellKeyDown?` ```ts onCellKeyDown?: Maybe<(args: CellKeyDownArgs, event: CellKeyboardEvent) => void>; @@ -708,7 +702,7 @@ function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website/routes/CellNavigation.tsx). -##### onCellCopy? +##### `onCellCopy?` ```ts onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => void>; @@ -716,7 +710,7 @@ onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => voi Callback triggered when a cell's content is copied. See the [`CellCopyArgs`](#cellcopyargs) type. -##### onCellPaste? +##### `onCellPaste?` ```ts onCellPaste?: Maybe<(args: CellPasteArgs, event: CellClipboardEvent) => R>; @@ -726,7 +720,7 @@ Callback triggered when content is pasted into a cell. See the [`CellPasteArgs`] Return the updated row; the grid will call `onRowsChange` with it. -##### onActivePositionChange? +##### `onActivePositionChange?` ```ts onActivePositionChange?: Maybe<(args: PositionChangeArgs) => void>; @@ -734,7 +728,7 @@ onActivePositionChange?: Maybe<(args: PositionChangeArgs) => void>; Callback triggered when the active position changes. See the [`PositionChangeArgs`](#positionchangeargs) type. -##### onColumnResize? +##### `onColumnResize?` ```ts onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void>; @@ -742,7 +736,7 @@ onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void> Callback triggered when a column is resized. The `column` parameter is the full [`CalculatedColumn`](#calculatedcolumn) object, and `width` is the new width in pixels. -##### onColumnsReorder? +##### `onColumnsReorder?` ```ts onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>; @@ -750,7 +744,7 @@ onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => v Callback triggered when columns are reordered. The parameters are the `key` values of the source and target columns. -##### onFill? +##### `onFill?` ```ts onFill?: Maybe<(event: FillEvent) => R>; @@ -768,15 +762,15 @@ function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { ; ``` -##### onScroll? +##### `onScroll?` ```ts -onScroll?: UIEventHandler; +onScroll?: DivProps['onScroll']; ``` Native DOM `onScroll` prop. -##### enableVirtualization? +##### `enableVirtualization?` ```ts enableVirtualization?: Maybe; @@ -784,11 +778,9 @@ enableVirtualization?: Maybe; This prop can be used to disable virtualization. -###### Default Value - -`true` +**Default:** `true` -##### renderers? +##### `renderers?` ```ts renderers?: Maybe>; @@ -853,7 +845,7 @@ function MyGrid() { } ``` -##### rowClass? +##### `rowClass?` ```ts rowClass?: Maybe<(row: R, rowIdx: number) => Maybe>; @@ -873,9 +865,9 @@ function MyGrid() { } ``` -:warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. +⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. -##### headerRowClass? +##### `headerRowClass?` ```ts headerRowClass?: Maybe; @@ -887,7 +879,7 @@ Custom class name for the header row. ``` -##### direction? +##### `direction?` ```ts direction?: Maybe; @@ -902,78 +894,76 @@ Setting `direction` to `'rtl'` has the following effects: - Column resize cursor is shown on the left edge of the column - Scrollbar is moved to the left -###### Default Value +**Default:** `'ltr'` -`'ltr'` - -##### className? +##### `className?` ```ts -className?: string; +className?: DivProps['className']; ``` Custom class name for the grid. -##### style? +##### `style?` ```ts -style?: CSSProperties; +style?: DivProps['style']; ``` Custom styles for the grid. -##### role? +##### `role?` ```ts -role?: AriaRole; +role?: DivProps['role']; ``` ARIA role for the grid container. Defaults to `grid`. -##### aria-label? +##### `aria-label?` ```ts -"aria-label"?: string; +'aria-label'?: DivProps['aria-label']; ``` The label of the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. -##### aria-labelledby? +##### `aria-labelledby?` ```ts -"aria-labelledby"?: string; +'aria-labelledby'?: DivProps['aria-labelledby']; ``` The id of the element containing a label for the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. -##### aria-rowcount? +##### `aria-rowcount?` ```ts -"aria-rowcount"?: number; +'aria-rowcount'?: DivProps['aria-rowcount']; ``` Total number of rows for assistive technologies. -##### aria-description? +##### `aria-description?` ```ts -"aria-description"?: string; +'aria-description'?: DivProps['aria-description']; ``` A human-readable description of the grid. -##### aria-describedby? +##### `aria-describedby?` ```ts -"aria-describedby"?: string; +'aria-describedby'?: DivProps['aria-describedby']; ``` If the grid has a caption or description, `aria-describedby` can be set on the grid element with a value referring to the element containing the description. -##### data-testid? +##### `data-testid?` ```ts -"data-testid"?: Maybe; +'data-testid'?: Maybe; ``` This prop can be used to add a test ID for testing. We recommend querying the grid by its `role` and `name`. @@ -989,19 +979,15 @@ test('grid', async () => { }); ``` -##### data-cy? +##### `data-cy?` ```ts -"data-cy"?: Maybe; +'data-cy'?: Maybe; ``` Optional attribute to help with Cypress (or similar) selectors. ---- - -### `` - -**Props:** [`TreeDataGridProps`](#treedatagridprops)\<`R`, `SR`, `K`\> +#### `` `TreeDataGrid` is a component built on top of `DataGrid` to add hierarchical row grouping. This implements the [Treegrid pattern](https://www.w3.org/WAI/ARIA/apg/patterns/treegrid/). @@ -1034,36 +1020,26 @@ The following `DataGrid` props are not supported in `TreeDataGrid`: - Cell copy/paste does not work on group rows - Column groups are not supported; `columns` must be `Column[]` ---- +**Props:** [`TreeDataGridProps`](#treedatagridprops) -### TreeDataGridProps +#### `TreeDataGridProps` All [`DataGridProps`](#datagridprops) are supported except those listed above. The `columns` prop only supports `Column[]` (no column groups). When `rowHeight` is a function, it receives [`RowHeightArgs`](#rowheightargs) instead of just the row. Additional props are listed below: -#### Extends - -- [`Omit`](#omit)\<[`DataGridProps`](#datagridprops)\<`R`, `SR`, `K`\>, - \| `"columns"` - \| `"role"` - \| `"aria-rowcount"` - \| `"rowHeight"` - \| `"onFill"` - \| `"isRowSelectionDisabled"`\> - -#### Properties +```ts +interface TreeDataGridProps extends Omit, 'columns' | 'role' | 'aria-rowcount' | 'rowHeight' | 'onFill' | 'isRowSelectionDisabled'> { … } +``` -##### columns +##### `columns` ```ts columns: readonly Column[]; ``` -##### rowHeight? +##### `rowHeight?` ```ts -rowHeight?: Maybe< - | number -| ((args: RowHeightArgs) => number)>; +rowHeight?: Maybe) => number)>; ``` **Note:** Unlike `DataGrid`, the `rowHeight` function receives [`RowHeightArgs`](#rowheightargs), which includes a `type` property to distinguish between regular rows and group rows: @@ -1079,7 +1055,7 @@ function getRowHeight(args: RowHeightArgs): number { ``` -##### groupBy +##### `groupBy` ```ts groupBy: readonly string[]; @@ -1115,7 +1091,7 @@ function MyGrid() { } ``` -##### rowGrouper +##### `rowGrouper` ```ts rowGrouper: (rows: readonly R[], columnKey: string) => Record; @@ -1129,9 +1105,9 @@ function rowGrouper(rows: readonly Row[], columnKey: string): Record; @@ -1156,7 +1132,7 @@ function MyGrid() { } ``` -##### onExpandedGroupIdsChange +##### `onExpandedGroupIdsChange` ```ts onExpandedGroupIdsChange: (expandedGroupIds: Set) => void; @@ -1164,7 +1140,7 @@ onExpandedGroupIdsChange: (expandedGroupIds: Set) => void; **Required.** Callback triggered when groups are expanded or collapsed. -##### groupIdGetter? +##### `groupIdGetter?` ```ts groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>; @@ -1172,59 +1148,55 @@ groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>; Function to generate unique IDs for group rows. If not provided, a default implementation is used that concatenates parent and group keys with `__`. -:warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. - ---- - -### `` +⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. -**Props:** [`RenderCellProps`](#rendercellprops)\<`R`, `SR`\> +#### `` The default cell component. Can be wrapped via the `renderers.renderCell` prop. ---- +**Props:** [`RenderCellProps`](#rendercellprops) -### `` - -**Props:** [`RenderRowProps`](#renderrowprops)\<`R`, `SR`\> +#### `` The default row component. Can be wrapped via the `renderers.renderRow` prop. ---- - -### `` +**Props:** [`RenderRowProps`](#renderrowprops) -**Props:** [`SelectCheckboxProps`](#selectcheckboxprops) +#### `` A component for rendering row selection checkboxes. The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. ---- - -### `` +**Props:** [`SelectCheckboxProps`](#selectcheckboxprops) -**Props:** [`RenderGroupCellContentProps`](#rendergroupcellcontentprops)\<`R`, `SR`\> +#### `` Low-level component used by `renderToggleGroup` to render the expand/collapse control. Useful if you build a custom group cell renderer. -## Hooks +**Props:** [`RenderGroupCellContentProps`](#rendergroupcellcontentprops) -### useHeaderRowSelection() +### Hooks + +#### `useHeaderRowSelection()` ```ts -function useHeaderRowSelection(): object; +function useHeaderRowSelection(): { + isIndeterminate: boolean; + isRowSelected: boolean; + onRowSelectionChange: (selectRowEvent: SelectHeaderRowEvent) => void; +}; ``` Hook for managing header row selection state. Used within custom header cell renderers to implement custom "select all" functionality. -#### Returns +**Returns:** - `isIndeterminate: boolean` - Whether some (but not all) rows are selected - `isRowSelected: boolean` - Whether all rows are selected - `onRowSelectionChange: (event: SelectHeaderRowEvent) => void` - Callback to change selection state -#### Example +**Example:** ```tsx import { useLayoutEffect, useRef } from 'react'; @@ -1250,23 +1222,25 @@ function CustomHeaderCell() { } ``` ---- - -### useRowSelection() +#### `useRowSelection()` ```ts -function useRowSelection(): object; +function useRowSelection(): { + isRowSelectionDisabled: boolean; + isRowSelected: boolean; + onRowSelectionChange: (selectRowEvent: SelectRowEvent) => void; +}; ``` Hook for managing row selection state. Used within custom cell renderers to implement custom row selection. -#### Returns +**Returns:** - `isRowSelectionDisabled: boolean` - Whether selection is disabled for this row - `isRowSelected: boolean` - Whether this row is selected - `onRowSelectionChange: (event: SelectRowEvent) => void` - Callback to change selection state -#### Example +**Example:** ```tsx function CustomSelectCell({ row }: RenderCellContentProps) { @@ -1289,17 +1263,21 @@ function CustomSelectCell({ row }: RenderCellContentProps) { } ``` -## Render Functions +### Render Functions -### renderCheckbox() +#### `renderCheckbox()` ```ts -function renderCheckbox(props: RenderCheckboxProps): Element; +function renderCheckbox({ + onChange, + indeterminate, + ...props +}: RenderCheckboxProps): import('react').JSX.Element; ``` Renders a checkbox input with proper styling and accessibility. -#### Example +**Example:** ```tsx import { DataGrid, renderCheckbox } from 'react-data-grid'; @@ -1311,17 +1289,19 @@ import { DataGrid, renderCheckbox } from 'react-data-grid'; />; ``` ---- - -### renderHeaderCell() +#### `renderHeaderCell()` ```ts -function renderHeaderCell(props: RenderHeaderCellContentProps): string | Element; +function renderHeaderCell({ + column, + sortDirection, + priority +}: RenderHeaderCellContentProps): string | import('react').JSX.Element; ``` The default header cell content renderer. Renders sortable columns with sort indicators. -#### Example +**Example:** ```tsx import { renderHeaderCell, type Column } from 'react-data-grid'; @@ -1336,37 +1316,36 @@ const columns: readonly Column[] = [ ]; ``` ---- - -### renderSortIcon() +#### `renderSortIcon()` ```ts -function renderSortIcon(props: RenderSortIconProps): Element | null; +function renderSortIcon({ sortDirection }: RenderSortIconProps): import('react').JSX.Element | null; ``` Renders the sort direction arrow icon. ---- - -### renderSortPriority() +#### `renderSortPriority()` ```ts -function renderSortPriority(props: RenderSortPriorityProps): number | undefined; +function renderSortPriority({ priority }: RenderSortPriorityProps): number | undefined; ``` Renders the sort priority number for multi-column sorting. ---- - -### renderTextEditor() +#### `renderTextEditor()` ```ts -function renderTextEditor(props: RenderEditCellContentProps): Element; +function renderTextEditor({ + row, + column, + onRowChange, + onClose +}: RenderEditCellContentProps): import('react').JSX.Element; ``` A basic text editor provided for convenience. -#### Example +**Example:** ```tsx import { renderTextEditor, type Column } from 'react-data-grid'; @@ -1380,17 +1359,17 @@ const columns: readonly Column[] = [ ]; ``` ---- - -### renderToggleGroup() +#### `renderToggleGroup()` ```ts -function renderToggleGroup(props: RenderGroupCellContentProps): Element; +function renderToggleGroup( + props: RenderGroupCellContentProps +): import('react').JSX.Element; ``` The default group cell content renderer for the columns used for grouping (`groupBy` prop). This renders the expand/collapse toggle. -#### Example +**Example:** ```tsx import { renderToggleGroup, type Column } from 'react-data-grid'; @@ -1404,17 +1383,15 @@ const columns: readonly Column[] = [ ]; ``` ---- - -### renderValue() +#### `renderValue()` ```ts -function renderValue(props: RenderCellContentProps): ReactNode; +function renderValue(props: RenderCellContentProps): React.ReactNode; ``` The default cell content renderer that renders the value of `row[column.key]`. -#### Example +**Example:** ```tsx import { renderValue, type Column } from 'react-data-grid'; @@ -1428,17 +1405,17 @@ const columns: readonly Column[] = [ ]; ``` -## Context +### Context -### DataGridRenderersContext +#### `DataGridRenderersContext` ```ts -const DataGridRenderersContext: Context>>; +const DataGridRenderersContext: import("react").Context>>; ``` Context for providing default renderers to DataGrids in your app. -#### Example +**Example:** ```tsx import { @@ -1469,17 +1446,17 @@ function AppProvider({ children }) { } ``` -## Other +### Other -### SELECT\_COLUMN\_KEY +#### `SELECT_COLUMN_KEY` ```ts -const SELECT_COLUMN_KEY: 'rdg-select-column' = 'rdg-select-column'; +const SELECT_COLUMN_KEY = 'rdg-select-column'; ``` The key used for the `SelectColumn`. Useful for identifying or filtering the select column. -#### Example +**Example:** ```tsx import { SELECT_COLUMN_KEY } from 'react-data-grid'; @@ -1487,9 +1464,7 @@ import { SELECT_COLUMN_KEY } from 'react-data-grid'; const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN_KEY); ``` ---- - -### SelectColumn +#### `SelectColumn` ```ts const SelectColumn: Column; @@ -1498,7 +1473,7 @@ const SelectColumn: Column; A pre-configured column for row selection. Includes checkbox renderers for the header row, regular rows, and group rows. -#### Example +**Example:** ```tsx import { DataGrid, SelectColumn, type Column } from 'react-data-grid'; @@ -1522,111 +1497,90 @@ function MyGrid() { } ``` -## Types +### Types -### CalculatedColumn +#### `CalculatedColumn` Extends `Column` with additional computed properties used internally by the grid. This is the type passed to render functions. The `Column` properties it redeclares, like `width` and `renderCell`, are resolved to their default values when not set. -#### See - -[`Column`](#column), [`onColumnResize`](#oncolumnresize) prop on `` - -#### Extends - -- [`Column`](#column)\<`R`, `SR`\> - -#### Properties +```ts +interface CalculatedColumn extends Column { + /** The column group that contains the column, or `undefined` if the column is not in a group */ + readonly parent: CalculatedColumnParent | undefined; + /** The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` */ + readonly idx: number; + /** Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups */ + readonly level: number; + readonly width: number | string; + readonly minWidth: number; + readonly maxWidth: number | undefined; + readonly resizable: boolean; + readonly sortable: boolean; + readonly draggable: boolean; + readonly frozen: ColumnFrozen; + readonly renderCell: (props: RenderCellContentProps) => ReactNode; + readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; +} +``` -| Property | Modifier | Type | Description | Overrides | -| ------------------ | ---------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | -| `parent` | `readonly` | \| [`CalculatedColumnParent`](#calculatedcolumnparent)\<`R`, `SR`\> \| `undefined` | The column group that contains the column, or `undefined` if the column is not in a group | - | -| `idx` | `readonly` | `number` | The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` | - | -| `level` | `readonly` | `number` | Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups | - | -| `width` | `readonly` | `string` \| `number` | - | | -| `minWidth` | `readonly` | `number` | - | | -| `maxWidth` | `readonly` | `number` \| `undefined` | - | | -| `resizable` | `readonly` | `boolean` | - | | -| `sortable` | `readonly` | `boolean` | - | | -| `draggable` | `readonly` | `boolean` | - | | -| `frozen` | `readonly` | [`ColumnFrozen`](#columnfrozen) | - | | -| `renderCell` | `readonly` | (`props`: [`RenderCellContentProps`](#rendercellcontentprops)\<`R`, `SR`\>) => `ReactNode` | - | | -| `renderHeaderCell` | `readonly` | (`props`: [`RenderHeaderCellContentProps`](#renderheadercellcontentprops)\<`R`, `SR`\>) => `ReactNode` | - | | +**See also:** [`Column`](#column), [`onColumnResize`](#oncolumnresize) prop on `` ---- +#### `CalculatedColumnOrColumnGroup` -### CalculatedColumnOrColumnGroup +Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. ```ts type CalculatedColumnOrColumnGroup = CalculatedColumnParent | CalculatedColumn; ``` -Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. - -#### See - -[`CalculatedColumn`](#calculatedcolumn), [`CalculatedColumnParent`](#calculatedcolumnparent) - ---- +**See also:** [`CalculatedColumn`](#calculatedcolumn), [`CalculatedColumnParent`](#calculatedcolumnparent) -### CalculatedColumnParent +#### `CalculatedColumnParent` Represents a parent column group in the calculated column structure. -#### See - -[`CalculatedColumn`](#calculatedcolumn) - -#### Properties +```ts +interface CalculatedColumnParent { + readonly name: string | ReactElement; + readonly parent: CalculatedColumnParent | undefined; + readonly idx: number; + readonly colSpan: number; + readonly level: number; + readonly headerCellClass?: Maybe; +} +``` -| Property | Modifier | Type | -| ------------------ | ---------- | ---------------------------------------------------------------------------------------- | -| `name` | `readonly` | \| `string` \| `ReactElement`\<`unknown`, `string` \| `JSXElementConstructor`\<`any`\>\> | -| `parent` | `readonly` | \| [`CalculatedColumnParent`](#calculatedcolumnparent)\<`R`, `SR`\> \| `undefined` | -| `idx` | `readonly` | `number` | -| `colSpan` | `readonly` | `number` | -| `level` | `readonly` | `number` | -| `headerCellClass?` | `readonly` | [`Maybe`](#maybe)\<`string`\> | +**See also:** [`CalculatedColumn`](#calculatedcolumn) ---- +#### `CellCopyArgs` -### CellCopyArgs +Arguments passed to `onCellCopy`. ```ts type CellCopyArgs = CellCopyPasteArgs; ``` -Arguments passed to `onCellCopy`. - -#### See - -[`onCellCopy`](#oncellcopy) prop on `` +**See also:** [`onCellCopy`](#oncellcopy) prop on `` ---- +#### `CellKeyboardEvent` -### CellKeyboardEvent +Extends `React.KeyboardEvent` with grid-specific methods. ```ts type CellKeyboardEvent = CellEvent>; ``` -Extends `React.KeyboardEvent` with grid-specific methods. - -#### See +**See also:** [`onCellKeyDown`](#oncellkeydown) prop on `` -[`onCellKeyDown`](#oncellkeydown) prop on `` +#### `CellKeyDownArgs` ---- - -### CellKeyDownArgs +Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. ```ts type CellKeyDownArgs = ActiveCellKeyDownArgs | EditCellKeyDownArgs; ``` -Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. - -#### Example +**Example:** ```tsx import type { CellKeyboardEvent, CellKeyDownArgs } from 'react-data-grid'; @@ -1639,17 +1593,26 @@ function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { } ``` -#### See - -[`onCellKeyDown`](#oncellkeydown) prop on `` - ---- +**See also:** [`onCellKeyDown`](#oncellkeydown) prop on `` -### CellMouseArgs +#### `CellMouseArgs` Arguments passed to cell mouse event handlers. -#### Example +```ts +interface CellMouseArgs { + /** The column object of the cell. */ + column: CalculatedColumn; + /** The row object of the cell. */ + row: R; + /** The row index of the cell. */ + rowIdx: number; + /** Function to manually focus the cell. Pass `true` to immediately start editing. */ + setActivePosition: (enableEditor?: boolean) => void; +} +``` + +**Example:** ```tsx import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; @@ -1660,30 +1623,17 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { } ``` -#### See - -[`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` +**See also:** [`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` -#### Properties +#### `CellMouseEvent` -| Property | Type | Description | -| ------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------ | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | The column object of the cell. | -| `row` | `R` | The row object of the cell. | -| `rowIdx` | `number` | The row index of the cell. | -| `setActivePosition` | (`enableEditor?`: `boolean`) => `void` | Function to manually focus the cell. Pass `true` to immediately start editing. | - ---- - -### CellMouseEvent +Extends `React.MouseEvent` with grid-specific methods. ```ts type CellMouseEvent = CellEvent>; ``` -Extends `React.MouseEvent` with grid-specific methods. - -#### Example +**Example:** ```tsx import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; @@ -1695,46 +1645,38 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { } ``` -#### See - -[`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` +**See also:** [`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` ---- +#### `CellPasteArgs` -### CellPasteArgs +Arguments passed to `onCellPaste`. ```ts type CellPasteArgs = CellCopyPasteArgs; ``` -Arguments passed to `onCellPaste`. - -#### See +**See also:** [`onCellPaste`](#oncellpaste) prop on `` -[`onCellPaste`](#oncellpaste) prop on `` +#### `ColSpanArgs` ---- - -### ColSpanArgs +Arguments passed to the `colSpan` function. ```ts type ColSpanArgs = | { - type: 'HEADER'; + readonly type: 'HEADER'; } | { - type: 'ROW'; - row: R; + readonly type: 'ROW'; + readonly row: R; } | { - type: 'SUMMARY'; - row: SR; + readonly type: 'SUMMARY'; + readonly row: SR; }; ``` -Arguments passed to the `colSpan` function. - -#### Example +**Example:** ```tsx import type { Column } from 'react-data-grid'; @@ -1753,37 +1695,27 @@ const columns: readonly Column[] = [ ]; ``` -#### See +**See also:** [`column.colSpan`](#colspan) -[`column.colSpan`](#colspan) - ---- - -### Column +#### `Column` Defines the configuration for a column in the grid. -#### See - -[`columns`](#columns) prop on `` - -#### Extended by - -- [`CalculatedColumn`](#calculatedcolumn) +```ts +interface Column { … } +``` -#### Properties +**See also:** [`columns`](#columns) prop on `` -##### name +##### `name` ```ts -readonly name: - | string -| ReactElement>; +readonly name: string | ReactElement; ``` The name of the column. Displayed in the header cell by default. -##### key +##### `key` ```ts readonly key: string; @@ -1791,10 +1723,10 @@ readonly key: string; A unique key to distinguish each column. -##### width? +##### `width?` ```ts -readonly width?: Maybe; +readonly width?: Maybe; ``` Width can be any valid CSS grid column value. If not specified, it will be determined automatically based on grid width and specified widths of other columns. @@ -1833,11 +1765,9 @@ width: 'minmax(100px, max-content)', `max-content` can be used to expand the column to show all the content. Note that the grid is only able to calculate column width for visible rows. -###### Default Value - -`auto` +**Default:** `auto` -##### minWidth? +##### `minWidth?` ```ts readonly minWidth?: Maybe; @@ -1845,11 +1775,9 @@ readonly minWidth?: Maybe; Minimum column width in pixels. -###### Default Value +**Default:** `50` pixels -`50` pixels - -##### maxWidth? +##### `maxWidth?` ```ts readonly maxWidth?: Maybe; @@ -1857,7 +1785,7 @@ readonly maxWidth?: Maybe; Maximum column width in pixels. -##### cellClass? +##### `cellClass?` ```ts readonly cellClass?: Maybe Maybe)>; @@ -1895,7 +1823,7 @@ const columns: Column[] = [ } ``` -##### headerCellClass? +##### `headerCellClass?` ```ts readonly headerCellClass?: Maybe; @@ -1903,7 +1831,7 @@ readonly headerCellClass?: Maybe; Class name(s) for the header cell. -##### summaryCellClass? +##### `summaryCellClass?` ```ts readonly summaryCellClass?: Maybe Maybe)>; @@ -1911,7 +1839,7 @@ readonly summaryCellClass?: Maybe Maybe)>; Class name(s) for summary cells. Can be a string or a function that returns a class name based on the summary row. -##### renderCell? +##### `renderCell?` ```ts readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; @@ -1919,7 +1847,7 @@ readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode> Render function to render the content of cells. -##### renderHeaderCell? +##### `renderHeaderCell?` ```ts readonly renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) => ReactNode>; @@ -1927,7 +1855,7 @@ readonly renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) = Render function to render the content of the header cell. -##### renderSummaryCell? +##### `renderSummaryCell?` ```ts readonly renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>; @@ -1935,7 +1863,7 @@ readonly renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) Render function to render the content of summary cells. -##### renderGroupCell? +##### `renderGroupCell?` ```ts readonly renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>; @@ -1943,7 +1871,7 @@ readonly renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => Render function to render the content of group cells when using `TreeDataGrid`. -##### renderEditCell? +##### `renderEditCell?` ```ts readonly renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>; @@ -1951,7 +1879,7 @@ readonly renderEditCell?: Maybe<(props: RenderEditCellContentProps) => Re Render function to render the content of edit cells. When set, the column is automatically set to be editable. -##### editable? +##### `editable?` ```ts readonly editable?: Maybe boolean)>; @@ -1959,7 +1887,7 @@ readonly editable?: Maybe boolean)>; Control whether cells can be edited with `renderEditCell`. -##### colSpan? +##### `colSpan?` ```ts readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; @@ -1967,7 +1895,7 @@ readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. See the [`ColSpanArgs`](#colspanargs) type. -###### Example +**Example:** ```tsx import type { Column } from 'react-data-grid'; @@ -1986,7 +1914,7 @@ const columns: readonly Column[] = [ ]; ``` -##### frozen? +##### `frozen?` ```ts readonly frozen?: Maybe; @@ -2006,11 +1934,9 @@ const columns: readonly Column[] = [ ]; ``` -###### Default Value - -`false` +**Default:** `false` -##### resizable? +##### `resizable?` ```ts readonly resizable?: Maybe; @@ -2018,11 +1944,9 @@ readonly resizable?: Maybe; Enable resizing of the column. -###### Default Value - -`false` +**Default:** `false` -##### sortable? +##### `sortable?` ```ts readonly sortable?: Maybe; @@ -2030,11 +1954,9 @@ readonly sortable?: Maybe; Enable sorting of the column. -###### Default Value +**Default:** `false` -`false` - -##### draggable? +##### `draggable?` ```ts readonly draggable?: Maybe; @@ -2042,11 +1964,9 @@ readonly draggable?: Maybe; Enable dragging of the column. -###### Default Value - -`false` +**Default:** `false` -##### sortDescendingFirst? +##### `sortDescendingFirst?` ```ts readonly sortDescendingFirst?: Maybe; @@ -2054,39 +1974,60 @@ readonly sortDescendingFirst?: Maybe; Sets the column sort order to be descending instead of ascending the first time the column is sorted. -###### Default Value - -`false` - -##### editorOptions? - -```ts -readonly editorOptions?: Maybe; +**Default:** `false` + +##### `editorOptions?` + +```ts +readonly editorOptions?: Maybe<{ + /** + * Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. + * By default, the cell content is not rendered when the edit cell is open. + * + * @defaultValue `false` + */ + readonly displayCellContent?: Maybe; + /** + * Commit changes when clicking outside the cell. + * + * @defaultValue `true` + */ + readonly commitOnOutsideClick?: Maybe; + /** + * Close the editor when the row value changes externally. + * + * @defaultValue `true` + */ + readonly closeOnExternalRowChange?: Maybe; + }>; ``` Options for cell editing. ---- +#### `ColumnFrozen` -### ColumnFrozen +Whether a column is frozen, and on which edge. ```ts type ColumnFrozen = boolean | 'start' | 'end'; ``` -Whether a column is frozen, and on which edge. - -#### See +**See also:** [`column.frozen`](#frozen) -[`column.frozen`](#frozen) - ---- - -### ColumnGroup +#### `ColumnGroup` Defines a group of columns that share a common header. -#### Example +```ts +interface ColumnGroup { + /** The name of the column group. It will be displayed in the header cell */ + readonly name: string | ReactElement; + readonly headerCellClass?: Maybe; + readonly children: readonly ColumnOrColumnGroup[]; +} +``` + +**Example:** ```tsx import type { ColumnOrColumnGroup } from 'react-data-grid'; @@ -2102,70 +2043,56 @@ const columns: readonly ColumnOrColumnGroup[] = [ ]; ``` -#### See +**See also:** [`ColumnOrColumnGroup`](#columnorcolumngroup) -[`ColumnOrColumnGroup`](#columnorcolumngroup) +#### `ColumnOrColumnGroup` -#### Properties - -| Property | Modifier | Type | Description | -| ------------------ | ---------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | -| `name` | `readonly` | \| `string` \| `ReactElement`\<`unknown`, `string` \| `JSXElementConstructor`\<`any`\>\> | The name of the column group. It will be displayed in the header cell | -| `headerCellClass?` | `readonly` | [`Maybe`](#maybe)\<`string`\> | - | -| `children` | `readonly` | readonly [`ColumnOrColumnGroup`](#columnorcolumngroup)\<`R`, `SR`\>[] | - | - ---- - -### ColumnOrColumnGroup +Union type representing either a `Column` or a `ColumnGroup`. ```ts type ColumnOrColumnGroup = Column | ColumnGroup; ``` -Union type representing either a `Column` or a `ColumnGroup`. - -#### See - -[`columns`](#columns) prop on `` - ---- +**See also:** [`columns`](#columns) prop on `` -### ColumnWidth +#### `ColumnWidth` Represents a single column's width. -#### See - -[`ColumnWidths`](#columnwidths-1) - -#### Properties +```ts +interface ColumnWidth { + /** `'resized'` if the user resized the column, or `'measured'` if the grid measured it */ + readonly type: 'resized' | 'measured'; + /** The width in pixels */ + readonly width: number; +} +``` -| Property | Modifier | Type | Description | -| -------- | ---------- | --------------------------- | ----------------------------------------------------------------------------------- | -| `type` | `readonly` | `"resized"` \| `"measured"` | `'resized'` if the user resized the column, or `'measured'` if the grid measured it | -| `width` | `readonly` | `number` | The width in pixels | +**See also:** [`ColumnWidths`](#columnwidths-1) ---- +#### `ColumnWidths` -### ColumnWidths +A map of column widths. ```ts type ColumnWidths = ReadonlyMap; ``` -A map of column widths. - -#### See - -[`columnWidths`](#columnwidths) and [`onColumnWidthsChange`](#oncolumnwidthschange) props on `` +**See also:** [`columnWidths`](#columnwidths) and [`onColumnWidthsChange`](#oncolumnwidthschange) props on `` ---- - -### DataGridHandle +#### `DataGridHandle` Handle type assigned to a grid's `ref` for programmatic grid control. -#### Example +```ts +interface DataGridHandle { + element: HTMLDivElement | null; + scrollToCell: (position: PartialPosition) => void; + setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +} +``` + +**Example:** ```tsx import { useRef } from 'react'; @@ -2182,21 +2109,11 @@ function MyGrid() { } ``` -#### See - -[`ref`](#ref) prop on `` +**See also:** [`ref`](#ref) prop on `` -#### Properties +#### `DefaultColumnOptions` -| Property | Type | -| ------------------- | -------------------------------------------------------------------------------------------------------------------- | -| `element` | `HTMLDivElement` \| `null` | -| `scrollToCell` | (`position`: [`PartialPosition`](#partialposition)) => `void` | -| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | - ---- - -### DefaultColumnOptions +Default options applied to all columns. ```ts type DefaultColumnOptions = Pick< @@ -2212,69 +2129,71 @@ type DefaultColumnOptions = Pick< >; ``` -Default options applied to all columns. - -#### See +**See also:** [`defaultColumnOptions`](#defaultcolumnoptions) prop on `` -[`defaultColumnOptions`](#defaultcolumnoptions) prop on `` +#### `Direction` ---- - -### Direction +Text direction of the grid. ```ts type Direction = 'ltr' | 'rtl'; ``` -Text direction of the grid. - -#### See - -[`direction`](#direction) prop on `` - ---- +**See also:** [`direction`](#direction) prop on `` -### FillEvent +#### `FillEvent` Event object for drag-fill operations. -#### See - -[`onFill`](#onfill) prop on `` - -#### Properties - -| Property | Type | -| ----------- | -------- | -| `columnKey` | `string` | -| `sourceRow` | `R` | -| `targetRow` | `R` | +```ts +interface FillEvent { + columnKey: string; + sourceRow: R; + targetRow: R; +} +``` ---- +**See also:** [`onFill`](#onfill) prop on `` -### PositionChangeArgs +#### `PositionChangeArgs` Arguments passed to `onActivePositionChange`. -#### See - -[`onActivePositionChange`](#onactivepositionchange) prop on `` - -#### Properties - -| Property | Type | Description | -| -------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `rowIdx` | `number` | row index of the active position | -| `row` | `R` \| `undefined` | row object of the active position, undefined if the active position is on a header or summary row | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> \| `undefined` | column object of the active position, undefined if the active position is a row instead of a cell | +```ts +interface PositionChangeArgs { + /** row index of the active position */ + rowIdx: number; + /** + * row object of the active position, + * undefined if the active position is on a header or summary row + */ + row: R | undefined; + /** + * column object of the active position, + * undefined if the active position is a row instead of a cell + */ + column: CalculatedColumn | undefined; +} +``` ---- +**See also:** [`onActivePositionChange`](#onactivepositionchange) prop on `` -### RenderCellContentProps +#### `RenderCellContentProps` Props passed to custom cell content renderers (`column.renderCell`). -#### Example +```ts +interface RenderCellContentProps { + column: CalculatedColumn; + row: R; + rowIdx: number; + isCellEditable: boolean; + tabIndex: number; + onRowChange: (row: R) => void; +} +``` + +**Example:** ```tsx import type { RenderCellContentProps } from 'react-data-grid'; @@ -2289,77 +2208,65 @@ function renderCell({ row, column, onRowChange }: RenderCellContentProps) } ``` -#### See - -[`column.renderCell`](#rendercell), [`renderValue`](#rendervalue) function +**See also:** [`column.renderCell`](#rendercell), [`renderValue`](#rendervalue) function -#### Properties - -| Property | Type | -| ---------------- | ---------------------------------------------------- | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | -| `row` | `R` | -| `rowIdx` | `number` | -| `isCellEditable` | `boolean` | -| `tabIndex` | `number` | -| `onRowChange` | (`row`: `R`) => `void` | - ---- - -### RenderCellProps +#### `RenderCellProps` Props passed to the cell renderer when using `renderers.renderCell`. -#### See - -[`renderers.renderCell`](#renderers), [``](#cell-) - -#### Extends - -- [`BaseRenderCellProps`](#baserendercellprops)\<`R`, `SR`\> - -#### Properties - -| Property | Type | Inherited from | -| ------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------- | -| `rowIdx` | `number` | | -| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | - | -| `row` | `R` | - | -| `colSpan` | `number` \| `undefined` | - | -| `isDraggedOver` | `boolean` | - | -| `isCellActive` | `boolean` | - | -| `onRowChange` | (`column`: [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\>, `rowIdx`: `number`, `newRow`: `R`) => `void` | - | +```ts +interface RenderCellProps extends BaseRenderCellProps { + column: CalculatedColumn; + row: R; + colSpan: number | undefined; + isDraggedOver: boolean; + isCellActive: boolean; + onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; +} +``` ---- +**See also:** [`renderers.renderCell`](#renderers), [``](#cell-) -### RenderCheckboxProps +#### `RenderCheckboxProps` Props for custom checkbox renderers. -#### See - -[`renderCheckbox`](#rendercheckbox) function, [`renderers.renderCheckbox`](#renderers), [``](#selectcheckbox-) - -#### Properties - -| Property | Type | Description | -| ------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -| `checked?` | `boolean` | Whether the checkbox is checked | -| `indeterminate?` | `boolean` | Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected | -| `disabled?` | `boolean` | Whether the checkbox is disabled | -| `onChange` | (`checked`: `boolean`, `shift`: `boolean`) => `void` | Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows | -| `tabIndex?` | `number` | `0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox | -| `aria-label?` | `string` | Accessible label for the checkbox | -| `aria-labelledby?` | `string` | ID of the element that labels the checkbox | +```ts +interface RenderCheckboxProps { + /** Whether the checkbox is checked */ + checked?: boolean | undefined; + /** Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected */ + indeterminate?: boolean | undefined; + /** Whether the checkbox is disabled */ + disabled?: boolean | undefined; + /** Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows */ + onChange: (checked: boolean, shift: boolean) => void; + /** `0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox */ + tabIndex?: number | undefined; + /** Accessible label for the checkbox */ + 'aria-label'?: string | undefined; + /** ID of the element that labels the checkbox */ + 'aria-labelledby'?: string | undefined; +} +``` ---- +**See also:** [`renderCheckbox`](#rendercheckbox) function, [`renderers.renderCheckbox`](#renderers), [``](#selectcheckbox-) -### RenderEditCellContentProps +#### `RenderEditCellContentProps` Props passed to custom editors (`column.renderEditCell`). -#### Example +```ts +interface RenderEditCellContentProps { + column: CalculatedColumn; + row: R; + rowIdx: number; + onRowChange: (row: R, commitChanges?: boolean) => void; + onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; +} +``` + +**Example:** ```tsx import type { RenderEditCellContentProps } from 'react-data-grid'; @@ -2376,189 +2283,127 @@ function renderEditor({ row, column, onRowChange, onClose }: RenderEditCellConte } ``` -#### See - -[`column.renderEditCell`](#rendereditcell), [`renderTextEditor`](#rendertexteditor) function - -#### Properties +**See also:** [`column.renderEditCell`](#rendereditcell), [`renderTextEditor`](#rendertexteditor) function -| Property | Type | -| ------------- | ------------------------------------------------------------------ | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | -| `row` | `R` | -| `rowIdx` | `number` | -| `onRowChange` | (`row`: `R`, `commitChanges?`: `boolean`) => `void` | -| `onClose` | (`commitChanges?`: `boolean`, `shouldFocus?`: `boolean`) => `void` | - ---- - -### Renderers +#### `Renderers` Custom renderer configuration for the grid. -#### See - -[`renderers`](#renderers) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) - -#### Properties - -| Property | Modifier | Type | -| ------------------- | ---------- | --------------------------------------------------------------------------------------------------------------- | -| `renderCell?` | `readonly` | [`Maybe`](#maybe)\<(`key`: `Key`, `props`: [`RenderCellProps`](#rendercellprops)\<`R`, `SR`\>) => `ReactNode`\> | -| `renderCheckbox?` | `readonly` | [`Maybe`](#maybe)\<(`props`: [`RenderCheckboxProps`](#rendercheckboxprops)) => `ReactNode`\> | -| `renderRow?` | `readonly` | [`Maybe`](#maybe)\<(`key`: `Key`, `props`: [`RenderRowProps`](#renderrowprops)\<`R`, `SR`\>) => `ReactNode`\> | -| `renderSortStatus?` | `readonly` | [`Maybe`](#maybe)\<(`props`: [`RenderSortStatusProps`](#rendersortstatusprops)) => `ReactNode`\> | -| `noRowsFallback?` | `readonly` | `ReactNode` | +```ts +interface Renderers { + readonly renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; + readonly renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>; + readonly renderRow?: Maybe<(key: Key, props: RenderRowProps) => ReactNode>; + readonly renderSortStatus?: Maybe<(props: RenderSortStatusProps) => ReactNode>; + readonly noRowsFallback?: Maybe; +} +``` ---- +**See also:** [`renderers`](#renderers) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) -### RenderGroupCellContentProps +#### `RenderGroupCellContentProps` Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. -#### See - -[`column.renderGroupCell`](#rendergroupcell), [`renderToggleGroup`](#rendertogglegroup) function, [``](#togglegroup-) - -#### Properties - -| Property | Type | -| ------------- | ---------------------------------------------------- | -| `groupKey` | `unknown` | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | -| `row` | [`GroupRow`](#grouprow)\<`R`\> | -| `childRows` | readonly `R`[] | -| `isExpanded` | `boolean` | -| `tabIndex` | `number` | -| `toggleGroup` | () => `void` | +```ts +interface RenderGroupCellContentProps { + groupKey: unknown; + column: CalculatedColumn; + row: GroupRow; + childRows: readonly R[]; + isExpanded: boolean; + tabIndex: number; + toggleGroup: () => void; +} +``` ---- +**See also:** [`column.renderGroupCell`](#rendergroupcell), [`renderToggleGroup`](#rendertogglegroup) function, [``](#togglegroup-) -### RenderHeaderCellContentProps +#### `RenderHeaderCellContentProps` Props passed to custom header cell content renderers (`column.renderHeaderCell`). -#### See - -[`column.renderHeaderCell`](#renderheadercell-1), [`renderHeaderCell`](#renderheadercell) function - -#### Properties - -| Property | Type | -| --------------- | ---------------------------------------------------- | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | -| `sortDirection` | [`SortDirection`](#sortdirection) \| `undefined` | -| `priority` | `number` \| `undefined` | -| `tabIndex` | `number` | +```ts +interface RenderHeaderCellContentProps { + column: CalculatedColumn; + sortDirection: SortDirection | undefined; + priority: number | undefined; + tabIndex: number; +} +``` ---- +**See also:** [`column.renderHeaderCell`](#renderheadercell-1), [`renderHeaderCell`](#renderheadercell) function -### RenderRowProps +#### `RenderRowProps` Props passed to custom row renderers. -#### See - -[`renderers.renderRow`](#renderers), [``](#row-) - -#### Extends - -- [`BaseRenderRowProps`](#baserenderrowprops)\<`R`, `SR`\> - -#### Properties - -| Property | Type | Inherited from | -| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------- | -| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | | -| `iterateOverViewportColumnsForRow` | [`IterateOverViewportColumnsForRow`](#iterateoverviewportcolumnsforrow)\<`R`, `SR`\> | | -| `rowIdx` | `number` | | -| `activeCellIdx` | `number` \| `undefined` | | -| `isRowSelectionDisabled` | `boolean` | | -| `isRowSelected` | `boolean` | | -| `gridRowStart` | `number` | | -| `row` | `R` | - | -| `draggedOverCellIdx` | `number` \| `undefined` | - | -| `activeCellEditor` | \| `ReactElement`\<[`EditCellProps`](#editcellprops)\<`R`, `SR`\>, `string` \| `JSXElementConstructor`\<`any`\>\> \| `undefined` | - | -| `onRowChange` | (`column`: [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\>, `rowIdx`: `number`, `newRow`: `R`) => `void` | - | -| `rowClass` | [`Maybe`](#maybe)\<(`row`: `R`, `rowIdx`: `number`) => [`Maybe`](#maybe)\<`string`\>\> | - | -| `isTreeGrid` | `boolean` | - | +```ts +interface RenderRowProps extends BaseRenderRowProps { + row: R; + draggedOverCellIdx: number | undefined; + activeCellEditor: ReactElement> | undefined; + onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; + rowClass: Maybe<(row: R, rowIdx: number) => Maybe>; + isTreeGrid: boolean; +} +``` ---- +**See also:** [`renderers.renderRow`](#renderers), [``](#row-) -### RenderSortIconProps +#### `RenderSortIconProps` Props for custom sort icon renderers. -#### See - -[`renderSortIcon`](#rendersorticon) function - -#### Extended by - -- [`RenderSortStatusProps`](#rendersortstatusprops) - -#### Properties - -| Property | Type | Description | -| --------------- | ------------------------------------------------ | -------------------------------------------------------------------- | -| `sortDirection` | [`SortDirection`](#sortdirection) \| `undefined` | The sort direction of the column, or `undefined` if it is not sorted | +```ts +interface RenderSortIconProps { + /** The sort direction of the column, or `undefined` if it is not sorted */ + sortDirection: SortDirection | undefined; +} +``` ---- +**See also:** [`renderSortIcon`](#rendersorticon) function -### RenderSortPriorityProps +#### `RenderSortPriorityProps` Props for custom sort priority renderers. -#### See - -[`renderSortPriority`](#rendersortpriority) function - -#### Extended by - -- [`RenderSortStatusProps`](#rendersortstatusprops) - -#### Properties - -| Property | Type | Description | -| ---------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------- | -| `priority` | `number` \| `undefined` | The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise | +```ts +interface RenderSortPriorityProps { + /** The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise */ + priority: number | undefined; +} +``` ---- +**See also:** [`renderSortPriority`](#rendersortpriority) function -### RenderSortStatusProps +#### `RenderSortStatusProps` Props for custom sort status renderers. -#### See - -[`renderers.renderSortStatus`](#renderers) - -#### Extends - -- [`RenderSortIconProps`](#rendersorticonprops) -- [`RenderSortPriorityProps`](#rendersortpriorityprops) +```ts +interface RenderSortStatusProps extends RenderSortIconProps, RenderSortPriorityProps {} +``` ---- +**See also:** [`renderers.renderSortStatus`](#renderers) -### RenderSummaryCellContentProps +#### `RenderSummaryCellContentProps` Props passed to summary cell content renderers (`column.renderSummaryCell`). -#### See - -[`column.renderSummaryCell`](#rendersummarycell) - -#### Properties +```ts +interface RenderSummaryCellContentProps { + column: CalculatedColumn; + row: SR; + tabIndex: number; +} +``` -| Property | Type | -| ---------- | ---------------------------------------------------- | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | -| `row` | `SR` | -| `tabIndex` | `number` | +**See also:** [`column.renderSummaryCell`](#rendersummarycell) ---- +#### `RowHeightArgs` -### RowHeightArgs +Arguments passed to `TreeDataGrid`'s `rowHeight` prop when it is a function. ```ts type RowHeightArgs = @@ -2572,9 +2417,7 @@ type RowHeightArgs = }; ``` -Arguments passed to `TreeDataGrid`'s `rowHeight` prop when it is a function. - -#### Example +**Example:** ```tsx function getRowHeight(args: RowHeightArgs): number { @@ -2587,230 +2430,166 @@ function getRowHeight(args: RowHeightArgs): number { ``` -#### See - -[`rowHeight`](#rowheight-1) prop on `` +**See also:** [`rowHeight`](#rowheight-1) prop on `` ---- - -### RowsChangeData +#### `RowsChangeData` Data provided to the `onRowsChange` callback. -#### See - -[`onRowsChange`](#onrowschange) prop on `` - -#### Properties - -| Property | Type | Description | -| --------- | ---------------------------------------------------- | ------------------------------------ | -| `indexes` | `number`[] | Indexes of the rows that changed | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | The column of the cells that changed | +```ts +interface RowsChangeData { + /** Indexes of the rows that changed */ + indexes: number[]; + /** The column of the cells that changed */ + column: CalculatedColumn; +} +``` ---- +**See also:** [`onRowsChange`](#onrowschange) prop on `` -### SelectHeaderRowEvent +#### `SelectHeaderRowEvent` Event object for header row selection changes. -#### See - -[`useHeaderRowSelection`](#useheaderrowselection) hook - -#### Properties - -| Property | Type | -| --------- | --------- | -| `checked` | `boolean` | +```ts +interface SelectHeaderRowEvent { + checked: boolean; +} +``` ---- +**See also:** [`useHeaderRowSelection`](#useheaderrowselection) hook -### SelectRowEvent +#### `SelectRowEvent` Event object for row selection changes. -#### See - -[`useRowSelection`](#userowselection) hook - -#### Properties - -| Property | Type | -| -------------- | --------- | -| `row` | `R` | -| `checked` | `boolean` | -| `isShiftClick` | `boolean` | +```ts +interface SelectRowEvent { + row: R; + checked: boolean; + isShiftClick: boolean; +} +``` ---- +**See also:** [`useRowSelection`](#userowselection) hook -### SetActivePositionOptions +#### `SetActivePositionOptions` Options for programmatically updating the grid's active position. -#### See - -[`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) - -#### Properties - -| Property | Type | -| --------------- | ------------------------------ | -| `enableEditor?` | [`Maybe`](#maybe)\<`boolean`\> | -| `shouldFocus?` | [`Maybe`](#maybe)\<`boolean`\> | +```ts +interface SetActivePositionOptions { + enableEditor?: Maybe; + shouldFocus?: Maybe; +} +``` ---- +**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) -### SortColumn +#### `SortColumn` Describes a sorted column. -#### See - -[`sortColumns`](#sortcolumns) and [`onSortColumnsChange`](#onsortcolumnschange) props on `` - -#### Properties - -| Property | Modifier | Type | -| ----------- | ---------- | --------------------------------- | -| `columnKey` | `readonly` | `string` | -| `direction` | `readonly` | [`SortDirection`](#sortdirection) | +```ts +interface SortColumn { + readonly columnKey: string; + readonly direction: SortDirection; +} +``` ---- +**See also:** [`sortColumns`](#sortcolumns) and [`onSortColumnsChange`](#onsortcolumnschange) props on `` -### SortDirection +#### `SortDirection` ```ts type SortDirection = 'ASC' | 'DESC'; ``` -#### See - -[`SortColumn`](#sortcolumn) - -## Internal Types - -### ActiveCellKeyDownArgs +**See also:** [`SortColumn`](#sortcolumn) -#### Properties +### Internal Types -| Property | Type | Description | -| ------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `mode` | `"ACTIVE"` | - | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> \| `undefined` | column object of the active position, undefined if the active position is a row instead of a cell | -| `row` | `R` | - | -| `rowIdx` | `number` | - | -| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | - | - ---- - -### BaseRenderCellProps - -#### Extends - -- [`Omit`](#omit)\<`React.ComponentProps`\<`"div"`\>, `"children"`\> -- `Pick`\<[`DataGridProps`](#datagridprops)\<`R`, `SR`\>, - \| `"onCellMouseDown"` - \| `"onCellClick"` - \| `"onCellDoubleClick"` - \| `"onCellContextMenu"`\> - -#### Extended by - -- [`RenderCellProps`](#rendercellprops) -- [`BaseRenderRowProps`](#baserenderrowprops) - -#### Properties - -| Property | Type | -| ------------------- | -------------------------------------------------------------------------------------------------------------------- | -| `rowIdx` | `number` | -| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | - ---- - -### BaseRenderRowProps - -#### Extends - -- [`BaseRenderCellProps`](#baserendercellprops)\<`R`, `SR`\> - -#### Extended by - -- [`RenderRowProps`](#renderrowprops) - -#### Properties - -| Property | Type | Overrides | Inherited from | -| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- | --------- | -------------- | -| `setActivePosition` | (`position`: [`Position`](#position), `options?`: [`SetActivePositionOptions`](#setactivepositionoptions)) => `void` | - | | -| `iterateOverViewportColumnsForRow` | [`IterateOverViewportColumnsForRow`](#iterateoverviewportcolumnsforrow)\<`R`, `SR`\> | - | - | -| `rowIdx` | `number` | | - | -| `activeCellIdx` | `number` \| `undefined` | - | - | -| `isRowSelectionDisabled` | `boolean` | - | - | -| `isRowSelected` | `boolean` | - | - | -| `gridRowStart` | `number` | - | - | - ---- - -### CellClipboardEvent +#### `ActiveCellKeyDownArgs` ```ts -type CellClipboardEvent = React.ClipboardEvent; +interface ActiveCellKeyDownArgs { + mode: 'ACTIVE'; + /** + * column object of the active position, + * undefined if the active position is a row instead of a cell + */ + column: CalculatedColumn | undefined; + row: R; + rowIdx: number; + setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +} ``` -Type alias for `React.ClipboardEvent`. Used for copy and paste events. This helper type is not exported; the shape is shown for reference. - -#### See - -[`onCellCopy`](#oncellcopy) and [`onCellPaste`](#oncellpaste) props on `` +#### `BaseRenderCellProps` ---- - -### CellCopyPasteArgs +```ts +interface BaseRenderCellProps + extends + Omit, 'children'>, + Pick< + DataGridProps, + 'onCellMouseDown' | 'onCellClick' | 'onCellDoubleClick' | 'onCellContextMenu' + > { + rowIdx: number; + setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +} +``` -#### Properties +#### `BaseRenderRowProps` -| Property | Type | -| -------- | ---------------------------------------------------- | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | -| `row` | `R` | +```ts +interface BaseRenderRowProps extends BaseRenderCellProps { + iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; + rowIdx: number; + activeCellIdx: number | undefined; + isRowSelectionDisabled: boolean; + isRowSelected: boolean; + gridRowStart: number; +} +``` ---- +#### `CellClipboardEvent` -### CellEvent +Type alias for `React.ClipboardEvent`. Used for copy and paste events. This helper type is not exported; the shape is shown for reference. ```ts -type CellEvent> = E & object; +type CellClipboardEvent = React.ClipboardEvent; ``` -Adds grid-specific methods to a React event. This helper type is not exported; the shape is shown for reference. - -#### Type Declaration +**See also:** [`onCellCopy`](#oncellcopy) and [`onCellPaste`](#oncellpaste) props on `` -##### preventGridDefault +#### `CellCopyPasteArgs` ```ts -() => void +interface CellCopyPasteArgs { + column: CalculatedColumn; + row: R; +} ``` -Prevents the default grid behavior for this event +#### `CellEvent` -##### isGridDefaultPrevented +Adds grid-specific methods to a React event. This helper type is not exported; the shape is shown for reference. ```ts -() => boolean; +type CellEvent> = E & { + /** Prevents the default grid behavior for this event */ + preventGridDefault: () => void; + /** Returns whether `preventGridDefault` was called */ + isGridDefaultPrevented: () => boolean; +}; ``` -Returns whether `preventGridDefault` was called - -#### See +**See also:** [`CellMouseEvent`](#cellmouseevent), [`CellKeyboardEvent`](#cellkeyboardevent) -[`CellMouseEvent`](#cellmouseevent), [`CellKeyboardEvent`](#cellkeyboardevent) +#### `CellMouseEventHandler` ---- - -### CellMouseEventHandler +Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. ```ts type CellMouseEventHandler = Maybe< @@ -2818,81 +2597,60 @@ type CellMouseEventHandler = Maybe< >; ``` -Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. - ---- - -### ColumnEditorOptions - -Options for cell editing. - -#### Properties +#### `DivProps` -| Property | Modifier | Type | Default value | Description | -| --------------------------- | ---------- | ------------------------------ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `displayCellContent?` | `readonly` | [`Maybe`](#maybe)\<`boolean`\> | `false` | Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. By default, the cell content is not rendered when the edit cell is open. | -| `commitOnOutsideClick?` | `readonly` | [`Maybe`](#maybe)\<`boolean`\> | `true` | Commit changes when clicking outside the cell. | -| `closeOnExternalRowChange?` | `readonly` | [`Maybe`](#maybe)\<`boolean`\> | `true` | Close the editor when the row value changes externally. | - ---- - -### EditCellKeyDownArgs - -#### Properties - -| Property | Type | -| ---------- | ------------------------------------------------------------------ | -| `mode` | `"EDIT"` | -| `column` | [`CalculatedColumn`](#calculatedcolumn)\<`R`, `SR`\> | -| `row` | `R` | -| `rowIdx` | `number` | -| `navigate` | () => `void` | -| `onClose` | (`commitChanges?`: `boolean`, `shouldFocus?`: `boolean`) => `void` | - ---- - -### EditCellProps - -#### Extends +```ts +type DivProps = React.ComponentProps<'div'>; +``` -- `Pick`\<[`RenderCellProps`](#rendercellprops)\<`R`, `SR`\>, `"column"` \| `"colSpan"` \| `"row"` \| `"rowIdx"`\> +#### `EditCellKeyDownArgs` -#### Properties +```ts +interface EditCellKeyDownArgs { + mode: 'EDIT'; + column: CalculatedColumn; + row: R; + rowIdx: number; + navigate: () => void; + onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; +} +``` -| Property | Type | -| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `onRowChange` | (`row`: `R`, `commitChanges`: `boolean`, `shouldFocus`: `boolean`) => `void` | -| `closeEditor` | (`shouldFocus`: `boolean`) => `void` | -| `navigate` | (`event`: `KeyboardEvent`\<`HTMLDivElement`\>) => `void` | -| `onKeyDown` | [`Maybe`](#maybe)\<(`args`: [`EditCellKeyDownArgs`](#editcellkeydownargs)\<`R`, `SR`\>, `event`: [`CellKeyboardEvent`](#cellkeyboardevent)) => `void`\> | +#### `EditCellProps` ---- +```ts +interface EditCellProps extends Pick< + RenderCellProps, + 'column' | 'colSpan' | 'row' | 'rowIdx' +> { + onRowChange: (row: R, commitChanges: boolean, shouldFocus: boolean) => void; + closeEditor: (shouldFocus: boolean) => void; + navigate: (event: React.KeyboardEvent) => void; + onKeyDown: Maybe<(args: EditCellKeyDownArgs, event: CellKeyboardEvent) => void>; +} +``` -### GroupRow +#### `GroupRow` Represents a group row in `TreeDataGrid`. This helper type is not exported; the shape is shown for reference. -#### See - -[`RenderGroupCellContentProps`](#rendergroupcellcontentprops), [`RowHeightArgs`](#rowheightargs), [``](#treedatagrid-) - -#### Properties - -| Property | Modifier | Type | -| --------------- | ---------- | -------------- | -| `childRows` | `readonly` | readonly `R`[] | -| `id` | `readonly` | `string` | -| `parentId` | `readonly` | `unknown` | -| `groupKey` | `readonly` | `unknown` | -| `isExpanded` | `readonly` | `boolean` | -| `level` | `readonly` | `number` | -| `posInSet` | `readonly` | `number` | -| `setSize` | `readonly` | `number` | -| `startRowIndex` | `readonly` | `number` | +```ts +interface GroupRow { + readonly childRows: readonly R[]; + readonly id: string; + readonly parentId: unknown; + readonly groupKey: unknown; + readonly isExpanded: boolean; + readonly level: number; + readonly posInSet: number; + readonly setSize: number; + readonly startRowIndex: number; +} +``` ---- +**See also:** [`RenderGroupCellContentProps`](#rendergroupcellcontentprops), [`RowHeightArgs`](#rowheightargs), [``](#treedatagrid-) -### IterateOverViewportColumnsForRow +#### `IterateOverViewportColumnsForRow` ```ts type IterateOverViewportColumnsForRow = ( @@ -2901,81 +2659,58 @@ type IterateOverViewportColumnsForRow = ( ) => IteratorObject>; ``` ---- +#### `Maybe` -### Maybe +Utility type for optional values. This helper type is not exported; the shape is shown for reference. ```ts type Maybe = T | undefined | null; ``` -Utility type for optional values. This helper type is not exported; the shape is shown for reference. - ---- - -### Omit +#### `Omit` ```ts type Omit = Pick>; ``` ---- - -### PartialPosition +#### `PartialPosition` Position for scrolling to a cell. Both fields are optional: omit `idx` to scroll to a row, or omit `rowIdx` to scroll to a column. This helper type is not exported; the shape is shown for reference. -#### See - -[`DataGridHandle`](#datagridhandle) - -#### Properties - -| Property | Modifier | Type | -| --------- | ---------- | ----------------------------- | -| `idx?` | `readonly` | [`Maybe`](#maybe)\<`number`\> | -| `rowIdx?` | `readonly` | [`Maybe`](#maybe)\<`number`\> | +```ts +interface PartialPosition { + readonly idx?: Maybe; + readonly rowIdx?: Maybe; +} +``` ---- +**See also:** [`DataGridHandle`](#datagridhandle) -### Position +#### `Position` Represents a cell position in the grid. This helper type is not exported; the shape is shown for reference. -#### See - -[`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) - -#### Properties - -| Property | Modifier | Type | Description | -| -------- | ---------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -| `idx` | `readonly` | `number` | Column index, or `-1` for the whole row in `TreeDataGrid` | -| `rowIdx` | `readonly` | `number` | Row index: `0` is the first row, header rows and top summary rows have negative indexes, and bottom summary rows come after the last row | - ---- - -### SelectCheckboxProps - -#### Extends - -- [`SharedInputProps`](#sharedinputprops) +```ts +interface Position { + /** Column index, or `-1` for the whole row in `TreeDataGrid` */ + readonly idx: number; + /** Row index: `0` is the first row, header rows and top summary rows have negative indexes, and bottom summary rows come after the last row */ + readonly rowIdx: number; +} +``` -#### Properties +**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) -| Property | Type | Description | Inherited from | -| ------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -------------- | -| `value` | `boolean` | Whether the checkbox is checked | - | -| `indeterminate?` | `boolean` | Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected | | -| `disabled?` | `boolean` | Whether the checkbox is disabled | | -| `onChange` | (`checked`: `boolean`, `shift`: `boolean`) => `void` | Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows | | -| `tabIndex?` | `number` | `0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox | | -| `aria-label?` | `string` | Accessible label for the checkbox | | -| `aria-labelledby?` | `string` | ID of the element that labels the checkbox | | +#### `SelectCheckboxProps` ---- +```ts +interface SelectCheckboxProps extends SharedInputProps { + /** Whether the checkbox is checked */ + value: boolean; +} +``` -### SharedInputProps +#### `SharedInputProps` ```ts type SharedInputProps = Pick< @@ -2984,9 +2719,7 @@ type SharedInputProps = Pick< >; ``` ---- - -### ViewportColumnWithColSpan +#### `ViewportColumnWithColSpan` ```ts type ViewportColumnWithColSpan = [ diff --git a/package-lock.json b/package-lock.json index ba98ef5ef7..609beb9494 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,6 @@ "@types/node": "^26.0.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", - "@typescript/native": "npm:typescript@beta", "@vitejs/plugin-react": "^6.1.1", "@vitest/browser-playwright": "5.0.5", "@vitest/coverage-istanbul": "5.0.5", @@ -26,15 +25,13 @@ "github-slugger": "^2.0.0", "jspdf": "^4.2.0", "jspdf-autotable": "^5.0.7", + "oxc-parser": "^0.155.0", "oxc-transform-react": "^0.154.0", "playwright": "^1.62.1", "publint": "^0.3.25", "react": "^19.3.0", "react-dom": "^19.3.0", - "typedoc": "^0.28.20", - "typedoc-plugin-markdown": "^4.14.1", - "typedoc-plugin-missing-exports": "^4.1.4", - "typescript": "npm:@typescript/typescript6@^6.0.2", + "typescript": "beta", "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0", "vite-plus": "1.3.0", "vitest": "5.0.5", @@ -476,20 +473,6 @@ "npm": ">=10" } }, - "node_modules/@gerrit0/mini-shiki": { - "version": "3.23.0", - "resolved": "https://registry.npmjs.org/@gerrit0/mini-shiki/-/mini-shiki-3.23.0.tgz", - "integrity": "sha512-bEMORlG0cqdjVyCEuU0cDQbORWX+kYCeo0kV1lbxF5bt4r7SID2l9bqsxJEM0zndaxpOUT7riCyIVEuqq/Ynxg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/engine-oniguruma": "^3.23.0", - "@shikijs/langs": "^3.23.0", - "@shikijs/themes": "^3.23.0", - "@shikijs/types": "^3.23.0", - "@shikijs/vscode-textmate": "^10.0.2" - } - }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", @@ -640,6 +623,353 @@ "dev": true, "license": "MIT" }, + "node_modules/@oxc-parser/binding-android-arm-eabi": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.155.0.tgz", + "integrity": "sha512-A6xv7hDtnTm+xlZ7utn6rRQpRMJHRhVr3gjRGqlx0RUX84mNk0pAsy6YN/wWhuOTkaZhRrrzaLxf0NfbH77j2w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-android-arm64": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm64/-/binding-android-arm64-0.155.0.tgz", + "integrity": "sha512-T1wWwH9/JI5g7Z4kEQwDOwhToxdDhRyOTklH+uuNpJ16m3MZFmGl+l2rKc0NHQdbVRG2LTOBsNjpW3h1BWytPA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-darwin-arm64": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-arm64/-/binding-darwin-arm64-0.155.0.tgz", + "integrity": "sha512-ZoRB3qJxJ8DWA41jHja+YeB0lLfjBy4T+Kr15vnN1k65X3zbJt3rPZftEwN4Ju4tmA4K/T9dWWD7Z8ewQLnrVA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-darwin-x64": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-x64/-/binding-darwin-x64-0.155.0.tgz", + "integrity": "sha512-vxtL86BtM+IgrpejA86nbTk5j0HKTIMeuaJ1fQciw6p9RfavPtIPjI7gN34owap0yG9txXBaAWpGdxokNwdqIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-freebsd-x64": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-freebsd-x64/-/binding-freebsd-x64-0.155.0.tgz", + "integrity": "sha512-tN6Ru5e0UVnWaIuiH8jEwnvxuxg7FvhWwSd3oe5oDhOD4ObsSr9/N6WfHLjilUWlPPj65ptwrSDH0Y7lzwTzmw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm-gnueabihf": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.155.0.tgz", + "integrity": "sha512-h4ozA5n6L6lwolsz9iwunEhKWnIVbmFRots5QxEix0H6nJ5ICpuDa7PuShuhfpIDFe3+Qvyscioyiv+9g+4Syg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm-musleabihf": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.155.0.tgz", + "integrity": "sha512-058/+LardpfuUlsKIvBGk/CYoakEVcMgqYx8GgyUZeOxFWTojYLlCc1Gb60/y21v3esDhHidgiY/Zbq9LpBhaQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm64-gnu": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.155.0.tgz", + "integrity": "sha512-nrOt2Y3xIAzu+lSPzH0864ieO+iCCXgoo9qFlGANE8Xh0cQ+RP8Wstfp+/wXN2YCyb98cAGzX0VruKYw7it/jw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm64-musl": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.155.0.tgz", + "integrity": "sha512-KYAayyN5hQbJPtGKtRxlyc8XYmyntOplyXSQzTDrmbz7l/GCrzQbSswvyJFBTH1LGtsZrbXOAfN52i/Kz6kLKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-ppc64-gnu": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.155.0.tgz", + "integrity": "sha512-CSuSY5hfjtsBnHXydOj8jiNfS1qHbdPZuPz1YL1cSgK7VmNYP+QlZIbG0BBYYBgX/vYEgZwbG9mBdW4YairZ5w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-riscv64-gnu": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.155.0.tgz", + "integrity": "sha512-7KCfOQm+Nz2N8trAXbQkal4TQ5756WVEmhm35y816YHvyFnEfVsICsiV5k0pEszNf/fRm4cm2i6i18SJ6/iCWg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-riscv64-musl": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.155.0.tgz", + "integrity": "sha512-JSlhgoK+/g1TGJI5NuADx2+6syhxnQNLCWLXyO5QLFyetomcr/vIxSdiNlmyAv963YXUzCuwAwRG6npZ5xyJ1A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-s390x-gnu": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.155.0.tgz", + "integrity": "sha512-WFIX+dPokWp64mi434Md3U3lJaTwNxAphvGjpltoyQjGUsdXavOIRrnp9dOS34Hd75HOAwDxAI+YwWOwqmJbtg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-x64-gnu": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.155.0.tgz", + "integrity": "sha512-g6xSDC/JpbnVOz5uafMGyK3txBVRFMQTx8opv/yHXGxqV3ZMVl3bf7W8XrSnF68dmy3gM4dgReNryuE53+WkeQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-x64-musl": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-musl/-/binding-linux-x64-musl-0.155.0.tgz", + "integrity": "sha512-6/4xlxKlZJWrQ0uwDFPc0H9+xLu7068CKhX3vIDW3SbvP/lVgnVuT5v6dyugeWskWpuxqF/WJ4WKwhxjU3pG2w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-openharmony-arm64": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-openharmony-arm64/-/binding-openharmony-arm64-0.155.0.tgz", + "integrity": "sha512-tltklL0J0XjDxIRTBXWOBhvc2mitcmES45pIxhwDWfxRyqz7Vkeu0NekTZEIxGE4f/lXgq3vZcjjffteQOVorg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-arm64-msvc": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.155.0.tgz", + "integrity": "sha512-alAb9TzjatUEsOeoncAziUnfdTDxfyswhalFZ9sC6plUgATIUx2NIZ0+bMn6aJ28AduS1OpG/OAisr/YISn4Ig==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-ia32-msvc": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.155.0.tgz", + "integrity": "sha512-yc5cbSfcGmRv/KpxDFuyk8adEBaWd/9HilWvBbQ4bFbus1V2PUh2mGB2Cfq9rqZTqLeiMT8x0skV+LKp9hOMgQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-x64-msvc": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.155.0.tgz", + "integrity": "sha512-8heq6jGq+rfpTDRDjoQiBHw0maQZf3IXkS99pdHQZPoTL5kyF5qyPS0RidUlSdnWDIqxXb5nux7GBD9cT+imUw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, "node_modules/@oxc-project/runtime": { "version": "0.154.0", "resolved": "https://registry.npmjs.org/@oxc-project/runtime/-/runtime-0.154.0.tgz", @@ -2116,55 +2446,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@shikijs/engine-oniguruma": { - "version": "3.23.0", - "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.23.0.tgz", - "integrity": "sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "3.23.0", - "@shikijs/vscode-textmate": "^10.0.2" - } - }, - "node_modules/@shikijs/langs": { - "version": "3.23.0", - "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.23.0.tgz", - "integrity": "sha512-2Ep4W3Re5aB1/62RSYQInK9mM3HsLeB91cHqznAJMuylqjzNVAVCMnNWRHFtcNHXsoNRayP9z1qj4Sq3nMqYXg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "3.23.0" - } - }, - "node_modules/@shikijs/themes": { - "version": "3.23.0", - "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.23.0.tgz", - "integrity": "sha512-5qySYa1ZgAT18HR/ypENL9cUSGOeI2x+4IvYJu4JgVJdizn6kG4ia5Q1jDEOi7gTbN4RbuYtmHh0W3eccOrjMA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "3.23.0" - } - }, - "node_modules/@shikijs/types": { - "version": "3.23.0", - "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.23.0.tgz", - "integrity": "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/vscode-textmate": "^10.0.2", - "@types/hast": "^3.0.4" - } - }, - "node_modules/@shikijs/vscode-textmate": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.1.0.tgz", - "integrity": "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ==", - "dev": true, - "license": "MIT" - }, "node_modules/@tanstack/history": { "version": "1.162.5", "resolved": "https://registry.npmjs.org/@tanstack/history/-/history-1.162.5.tgz", @@ -2562,58 +2843,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@typescript/native": { - "name": "typescript", - "version": "7.1.0-beta", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.1.0-beta.tgz", - "integrity": "sha512-cjWjZAJDsmZzsNC5GwHNlW0YPM65jZa5oR0KyQcYX3KSVIfTvtBq//vewISyatKk4OLi5grZjHhIVE9fdrw1UQ==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc" - }, - "engines": { - "node": ">=16.20.0" - }, - "optionalDependencies": { - "@typescript/typescript-aix-ppc64": "7.1.0-beta", - "@typescript/typescript-android-arm64": "7.1.0-beta", - "@typescript/typescript-darwin-arm64": "7.1.0-beta", - "@typescript/typescript-darwin-x64": "7.1.0-beta", - "@typescript/typescript-freebsd-arm64": "7.1.0-beta", - "@typescript/typescript-freebsd-x64": "7.1.0-beta", - "@typescript/typescript-linux-arm": "7.1.0-beta", - "@typescript/typescript-linux-arm64": "7.1.0-beta", - "@typescript/typescript-linux-loong64": "7.1.0-beta", - "@typescript/typescript-linux-mips64el": "7.1.0-beta", - "@typescript/typescript-linux-ppc64": "7.1.0-beta", - "@typescript/typescript-linux-riscv64": "7.1.0-beta", - "@typescript/typescript-linux-s390x": "7.1.0-beta", - "@typescript/typescript-linux-x64": "7.1.0-beta", - "@typescript/typescript-netbsd-arm64": "7.1.0-beta", - "@typescript/typescript-netbsd-x64": "7.1.0-beta", - "@typescript/typescript-openbsd-arm64": "7.1.0-beta", - "@typescript/typescript-openbsd-x64": "7.1.0-beta", - "@typescript/typescript-sunos-x64": "7.1.0-beta", - "@typescript/typescript-win32-arm64": "7.1.0-beta", - "@typescript/typescript-win32-x64": "7.1.0-beta" - } - }, - "node_modules/@typescript/old": { - "name": "typescript", - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", - "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.1.0-beta", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.1.0-beta.tgz", @@ -3934,13 +4163,6 @@ "node": ">=14" } }, - "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, - "license": "Python-2.0" - }, "node_modules/aria-query": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", @@ -4376,19 +4598,6 @@ "node": ">=14" } }, - "node_modules/entities": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, "node_modules/es-module-lexer": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", @@ -5288,26 +5497,6 @@ "url": "https://opencollective.com/parcel" } }, - "node_modules/linkify-it": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.2.tgz", - "integrity": "sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/puzrin" - }, - { - "type": "github", - "url": "https://github.com/sponsors/markdown-it" - } - ], - "license": "MIT", - "dependencies": { - "uc.micro": "^2.0.0" - } - }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -5345,13 +5534,6 @@ "yallist": "^3.0.2" } }, - "node_modules/lunr": { - "version": "2.3.9", - "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz", - "integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==", - "dev": true, - "license": "MIT" - }, "node_modules/lz-string": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", @@ -5384,34 +5566,6 @@ "source-map-js": "^1.2.1" } }, - "node_modules/markdown-it": { - "version": "14.3.3", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.3.3.tgz", - "integrity": "sha512-L//tDAkjTjJCU6pBUSBTgs3Kg4InVaZuUZog/b6V12UKhcDQ7S78877ibbCanRExwPuYP1CZD7Gd2dxSy1GXRg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/puzrin" - }, - { - "type": "github", - "url": "https://github.com/sponsors/markdown-it" - } - ], - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1", - "entities": "^4.5.0", - "linkify-it": "^5.0.2", - "mdurl": "^2.0.0", - "punycode.js": "^2.3.1", - "uc.micro": "^2.1.0" - }, - "bin": { - "markdown-it": "bin/markdown-it.mjs" - } - }, "node_modules/markdown-table": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz", @@ -5690,13 +5844,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/mdurl": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", - "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", - "dev": true, - "license": "MIT" - }, "node_modules/micromark": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", @@ -6458,6 +6605,53 @@ "node": ">= 0.8.0" } }, + "node_modules/oxc-parser": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/oxc-parser/-/oxc-parser-0.155.0.tgz", + "integrity": "sha512-C/ReSf1JUFukK/zvk6jhcNibSssvas5+ktIzK7fbKVd3CedWe59C3QwHEOrEZj/4Rt9+xg0Jeis/Jv1F/KM1mw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "^0.155.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxc-parser/binding-android-arm-eabi": "0.155.0", + "@oxc-parser/binding-android-arm64": "0.155.0", + "@oxc-parser/binding-darwin-arm64": "0.155.0", + "@oxc-parser/binding-darwin-x64": "0.155.0", + "@oxc-parser/binding-freebsd-x64": "0.155.0", + "@oxc-parser/binding-linux-arm-gnueabihf": "0.155.0", + "@oxc-parser/binding-linux-arm-musleabihf": "0.155.0", + "@oxc-parser/binding-linux-arm64-gnu": "0.155.0", + "@oxc-parser/binding-linux-arm64-musl": "0.155.0", + "@oxc-parser/binding-linux-ppc64-gnu": "0.155.0", + "@oxc-parser/binding-linux-riscv64-gnu": "0.155.0", + "@oxc-parser/binding-linux-riscv64-musl": "0.155.0", + "@oxc-parser/binding-linux-s390x-gnu": "0.155.0", + "@oxc-parser/binding-linux-x64-gnu": "0.155.0", + "@oxc-parser/binding-linux-x64-musl": "0.155.0", + "@oxc-parser/binding-openharmony-arm64": "0.155.0", + "@oxc-parser/binding-win32-arm64-msvc": "0.155.0", + "@oxc-parser/binding-win32-ia32-msvc": "0.155.0", + "@oxc-parser/binding-win32-x64-msvc": "0.155.0" + } + }, + "node_modules/oxc-parser/node_modules/@oxc-project/types": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", + "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, "node_modules/oxc-transform-react": { "version": "0.154.0", "resolved": "https://registry.npmjs.org/oxc-transform-react/-/oxc-transform-react-0.154.0.tgz", @@ -6867,16 +7061,6 @@ "node": ">=6" } }, - "node_modules/punycode.js": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", - "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/qified": { "version": "0.10.1", "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz", @@ -7227,74 +7411,42 @@ "node": ">= 0.8.0" } }, - "node_modules/typedoc": { - "version": "0.28.20", - "resolved": "https://registry.npmjs.org/typedoc/-/typedoc-0.28.20.tgz", - "integrity": "sha512-uSKqkh8Cr48vllnEy+jdaAgOeR6Y+QCBW7usgUsKj7gJEfR7stw9U/fE49LBnj2tPRKPY0c0EBJSWe9Appmplg==", + "node_modules/typescript": { + "version": "7.1.0-beta", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.1.0-beta.tgz", + "integrity": "sha512-cjWjZAJDsmZzsNC5GwHNlW0YPM65jZa5oR0KyQcYX3KSVIfTvtBq//vewISyatKk4OLi5grZjHhIVE9fdrw1UQ==", "dev": true, "license": "Apache-2.0", - "dependencies": { - "@gerrit0/mini-shiki": "^3.23.0", - "lunr": "^2.3.9", - "markdown-it": "^14.3.0", - "minimatch": "^10.2.5", - "yaml": "^2.9.0" - }, "bin": { - "typedoc": "bin/typedoc" - }, - "engines": { - "node": ">= 18", - "pnpm": ">= 10" + "tsc": "bin/tsc" }, - "peerDependencies": { - "typescript": "5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x || 5.7.x || 5.8.x || 5.9.x || 6.0.x" - } - }, - "node_modules/typedoc-plugin-markdown": { - "version": "4.14.1", - "resolved": "https://registry.npmjs.org/typedoc-plugin-markdown/-/typedoc-plugin-markdown-4.14.1.tgz", - "integrity": "sha512-24XX0oqyBsjBIBNoSH4wbgQkouci/CmgmO1ZBSaVkrcflqXFL2PQ5zFOpkz+Ewow5xQ3q2You+wrcmilNepRKg==", - "dev": true, - "license": "MIT", "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "typedoc": "0.28.x" - } - }, - "node_modules/typedoc-plugin-missing-exports": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/typedoc-plugin-missing-exports/-/typedoc-plugin-missing-exports-4.1.4.tgz", - "integrity": "sha512-tIay6z6MRb/4+mfWgKNPR6qEM5rz9S8rTiz0JWmSb/66A6AlZIl9q+1lAFygj4n8GHH1fsqKYQNt9JbNcuE0Uw==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "typedoc": "^0.28.1" - } - }, - "node_modules/typescript": { - "name": "@typescript/typescript6", - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript6/-/typescript6-6.0.2.tgz", - "integrity": "sha512-mbCddXd+jm7hfx7w2YU64/Av4/NqqeG3GoRZgxPcgoTxYjhrcfJRw9ULch71SS4G+Q3bOXFhRvPqjguN0Hyp5w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@typescript/old": "npm:typescript@^6" + "node": ">=16.20.0" }, - "bin": { - "tsc6": "bin/tsc6" + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.1.0-beta", + "@typescript/typescript-android-arm64": "7.1.0-beta", + "@typescript/typescript-darwin-arm64": "7.1.0-beta", + "@typescript/typescript-darwin-x64": "7.1.0-beta", + "@typescript/typescript-freebsd-arm64": "7.1.0-beta", + "@typescript/typescript-freebsd-x64": "7.1.0-beta", + "@typescript/typescript-linux-arm": "7.1.0-beta", + "@typescript/typescript-linux-arm64": "7.1.0-beta", + "@typescript/typescript-linux-loong64": "7.1.0-beta", + "@typescript/typescript-linux-mips64el": "7.1.0-beta", + "@typescript/typescript-linux-ppc64": "7.1.0-beta", + "@typescript/typescript-linux-riscv64": "7.1.0-beta", + "@typescript/typescript-linux-s390x": "7.1.0-beta", + "@typescript/typescript-linux-x64": "7.1.0-beta", + "@typescript/typescript-netbsd-arm64": "7.1.0-beta", + "@typescript/typescript-netbsd-x64": "7.1.0-beta", + "@typescript/typescript-openbsd-arm64": "7.1.0-beta", + "@typescript/typescript-openbsd-x64": "7.1.0-beta", + "@typescript/typescript-sunos-x64": "7.1.0-beta", + "@typescript/typescript-win32-arm64": "7.1.0-beta", + "@typescript/typescript-win32-x64": "7.1.0-beta" } }, - "node_modules/uc.micro": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", - "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", - "dev": true, - "license": "MIT" - }, "node_modules/undici-types": { "version": "8.9.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", @@ -7876,22 +8028,6 @@ "dev": true, "license": "ISC" }, - "node_modules/yaml": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", - "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", - "dev": true, - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14.6" - }, - "funding": { - "url": "https://github.com/sponsors/eemeli" - } - }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index 65660369b3..83c680deb1 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,6 @@ "@types/node": "^26.0.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", - "@typescript/native": "npm:typescript@beta", "@vitejs/plugin-react": "^6.1.1", "@vitest/browser-playwright": "5.0.5", "@vitest/coverage-istanbul": "5.0.5", @@ -47,15 +46,13 @@ "github-slugger": "^2.0.0", "jspdf": "^4.2.0", "jspdf-autotable": "^5.0.7", + "oxc-parser": "^0.155.0", "oxc-transform-react": "^0.154.0", "playwright": "^1.62.1", "publint": "^0.3.25", "react": "^19.3.0", "react-dom": "^19.3.0", - "typedoc": "^0.28.20", - "typedoc-plugin-markdown": "^4.14.1", - "typedoc-plugin-missing-exports": "^4.1.4", - "typescript": "npm:@typescript/typescript6@^6.0.2", + "typescript": "beta", "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0", "vite-plus": "1.3.0", "vitest": "5.0.5", diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index f3bf854e04..ec3e4ac981 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -1,411 +1,324 @@ import { readFile, writeFile } from 'node:fs/promises'; import GithubSlugger from 'github-slugger'; -import { - Application, - Comment, - Context, - Converter, - DeclarationReflection, - i18n, - ParameterReflection, - ReferenceType, - ReflectionGroup, - ReflectionKind, - ReflectionType, - SignatureReflection, - TSConfigReader, - Type, - TypeDocReader, - TypeParameterReflection, - type ContainerReflection, - type SomeType -} from 'typedoc'; -import { MarkdownTheme, MarkdownThemeContext } from 'typedoc-plugin-markdown'; +import { parseSync } from 'oxc-parser'; +// Generates the API reference of the README from the declarations and JSDoc comments of `lib/index.d.ts`, +// which `vp pack` bundles from the sources. + +const declarationsPath = 'lib/index.d.ts'; const readmePath = 'README.md'; -// the components of the "Components" section, without their props interfaces -const components = new Set(); const startMarker = ''; const endMarker = ''; +// the `@group` tags of the exports +const sections = ['Components', 'Hooks', 'Render Functions', 'Context', 'Other', 'Types']; -const app = await Application.bootstrapWithPlugins({}, [new TypeDocReader(), new TSConfigReader()]); +interface Doc { + summary: string; + tags: { name: string; text: string }[]; +} -// TODO: remove when TypeDoc supports TypeScript 7 -// TypeDoc identifies TypeScript's lib types, like `NoInfer`, by their package name, -// which it derives from the path of TypeScript 6: `node_modules/@typescript/old` -const { createSymbolReference } = Context.prototype; -Context.prototype.createSymbolReference = function (...args) { - const reference = createSymbolReference.apply(this, args); - if (reference.package === '@typescript/old') { - reference.package = 'typescript'; - } - return reference; -}; +interface Declaration { + name: string; + // e.g. an interface, a type alias, a function, or a variable + node: Node; + doc: Doc; +} -class ReadmeThemeContext extends MarkdownThemeContext { - constructor(...args: ConstructorParameters) { - super(...args); +// the subset of the oxc AST that is used +interface Node { + type: string; + start: number; + end: number; + id?: { name: string; typeAnnotation?: Node }; + optional?: boolean; + key?: { type: string; name?: string; value?: string }; + body?: { body: Node[] }; + params?: Node[]; + typeAnnotation?: Node; + declarations?: Node[]; +} - const { declarationTitle, groups, memberTitle, signatureTitle } = this.partials; - const { useTableFormat: isDefaultTableFormat } = this.helpers; - let isTableInterface = false; +const code = await readFile(declarationsPath, 'utf8'); +const { program, comments } = parseSync(declarationsPath, code); - // components are used as JSX elements, so show their props instead of a function signature - const getComponentProps = (signature: SignatureReflection | undefined) => { - const propsType = signature?.parameters?.[0]?.type; - return propsType === undefined ? '' : `**Props:** ${this.partials.someType(propsType)}`; - }; +const declarations = new Map(); +// exported name -> declared name, e.g. `Cell` -> `MemoCell` +const exportedNames = new Map(); - this.partials = { - ...this.partials, - memberTitle: (model) => - components.has(model) ? `\`<${model.name} />\`` : memberTitle(model), - signatureTitle: (model, options) => - components.has(model.parent) ? getComponentProps(model) : signatureTitle(model, options), - // e.g. `Row`, a memoized component - declarationTitle: (model) => - components.has(model) && model.type instanceof ReflectionType - ? getComponentProps(model.type.declaration.signatures?.[0]) - : declarationTitle(model), - // list the properties of an interface in a table, unless a property has more than a short description - groups(model: ContainerReflection, options: Parameters[1]) { - isTableInterface = - model.kindOf(ReflectionKind.Interface) && model.children?.every(hasShortComment) === true; - return groups(model, options); - }, - // the signatures already show the return types - signatureReturns: (model: SignatureReflection, options: { headingLevel: number }) => { - const returnsTag = model.comment?.getTag('@returns'); - if (returnsTag === undefined) return ''; - return `${'#'.repeat(options.headingLevel)} ${i18n.theme_returns()}\n\n${this.helpers.getCommentParts(returnsTag.content)}`; - }, - // the "Extends" sections already link to the base types - inheritance: () => '' - }; - - this.helpers = { - ...this.helpers, - useTableFormat: (key, reflectionKind) => - key === 'properties' && reflectionKind === ReflectionKind.Interface - ? isTableInterface - : isDefaultTableFormat(key, reflectionKind) +for (const statement of program.body as unknown as Node[]) { + if (statement.type === 'ExportNamedDeclaration') { + const { declaration, specifiers } = statement as unknown as { + declaration: Node | null; + specifiers: { local: { name: string }; exported: { name: string } }[]; }; + if (declaration === null) { + for (const { local, exported } of specifiers) exportedNames.set(exported.name, local.name); + } else { + const name = getDeclarationName(declaration); + exportedNames.set(name, name); + declarations.set(name, { name, node: declaration, doc: parseDoc(getComment(statement)) }); + } + } else if (statement.type !== 'ImportDeclaration') { + const name = getDeclarationName(statement); + declarations.set(name, { name, node: statement, doc: parseDoc(getComment(statement)) }); } } -class ReadmeTheme extends MarkdownTheme { - override getRenderContext( - page: Parameters['getRenderContext']>[0] - ) { - return new ReadmeThemeContext(this, page, this.application.options); +// group the exports by their `@group` tag, the remaining types are referenced by the exports +const groups = new Map(sections.map((section) => [section, []])); +for (const [name, declaredName] of exportedNames) { + const declaration = declarations.get(declaredName)!; + const group = declaration.doc.tags.find((tag) => tag.name === 'group')?.text; + const items = group === undefined ? undefined : groups.get(group); + if (items === undefined) { + throw new Error(`${name} must have a @group tag with one of: ${sections.join(', ')}`); } + items.push({ ...declaration, name }); } -app.renderer.defineTheme('readme', ReadmeTheme); -app.options.setValue('theme', 'readme'); - -// collect the public exports before typedoc-plugin-missing-exports adds the internal types, -// its listener has a priority of 1e9 -const publicNames = new Set(); -app.converter.on( - Converter.EVENT_RESOLVE_BEGIN, - ({ project }) => { - for (const child of project.children ?? []) { - publicNames.add(child.name); - } - }, - Number.POSITIVE_INFINITY +const exportedDeclarations = new Set(exportedNames.values()); +const internalTypes = [...declarations.values()].filter( + ({ name, node }) => !exportedDeclarations.has(name) && isType(node) ); -// `NoInfer` only affects type inference, show the type it wraps instead -app.converter.on(Converter.EVENT_RESOLVE_END, ({ project }) => { - for (const reflection of Object.values(project.reflections)) { - if ( - (reflection instanceof DeclarationReflection || - reflection instanceof ParameterReflection || - reflection instanceof SignatureReflection || - reflection instanceof TypeParameterReflection) && - reflection.type !== undefined - ) { - reflection.type = unwrapNoInfer(reflection.type); - } - - if (reflection instanceof TypeParameterReflection && reflection.default !== undefined) { - reflection.default = unwrapNoInfer(reflection.default); - } - - // the default values of inferred object types, like the return types of the hooks, - // are implementation details - if ( - reflection instanceof DeclarationReflection && - reflection.parent?.kindOf(ReflectionKind.TypeLiteral) === true - ) { - delete reflection.defaultValue; - } - - // TypeDoc names destructured parameters `__namedParameters` - if (reflection instanceof ParameterReflection && reflection.name === '__namedParameters') { - reflection.name = 'props'; - } +const markdown: string[] = []; +for (const [section, items] of [...groups, ['Internal Types', internalTypes] as const]) { + markdown.push(`### ${section}`); + for (const item of items.toSorted(section === 'Components' ? compareComponents : compareNames)) { + markdown.push(renderItem(item, section === 'Components' && !isType(item.node))); } -}); +} -const project = await app.convert(); +const readme = await readFile(readmePath, 'utf8'); +const startIndex = readme.indexOf(startMarker); +const endIndex = readme.indexOf(endMarker); -if (project === undefined) { - throw new Error('TypeDoc failed to convert the project'); +if (startIndex === -1 || endIndex < startIndex) { + throw new Error(`${readmePath} must contain ${startMarker} followed by ${endMarker}`); } -app.validate(project); +await writeFile( + readmePath, + resolveLinks( + `${readme.slice(0, startIndex + startMarker.length)}\n\n${markdown.join('\n\n')}\n\n${readme.slice(endIndex)}` + ) +); + +function renderItem({ name, node, doc }: Declaration, isComponent: boolean) { + const md: string[] = []; + + if (isComponent) { + md.push( + `#### \`<${name} />\``, + ...renderSummary(doc), + `**Props:** ${renderComponentProps(node)}` + ); + } else if (isType(node)) { + md.push(`#### \`${name}\``, ...renderSummary(doc)); + if (hasRichMembers(node)) { + // a heading per member, as their docs have examples, lists, or several paragraphs + md.push(codeBlock(`${source(node).slice(0, source(node).indexOf('{')).trim()} { … }`)); + } else { + md.push(codeBlock(source(node))); + } + } else { + const isFunction = node.type === 'TSDeclareFunction' || node.type === 'FunctionDeclaration'; + md.push( + `#### \`${name}${isFunction ? '()' : ''}\``, + codeBlock(source(node)), + ...renderSummary(doc) + ); + } -if (app.logger.hasErrors() || app.logger.hasWarnings()) { - throw new Error('TypeDoc reported errors or warnings'); -} + md.push(...renderTags(doc)); -// public exports must be in one of the sections of `groupOrder`, set with a `@group` tag, -// the remaining groups only contain the types that are referenced by the public API but not exported -const sections = new Set(app.options.getValue('groupOrder').filter((title) => title !== '*')); -const internalGroup = new ReflectionGroup('Internal Types', project); -const publicGroups = (project.groups ?? []).filter((group) => { - if (sections.has(group.title)) return true; - - for (const child of group.children) { - if (publicNames.has(child.name)) { - throw new Error( - `${child.name} must have a @group tag with one of: ${[...sections].join(', ')}` + if (isType(node) && hasRichMembers(node)) { + for (const member of node.body!.body) { + const memberDoc = parseDoc(getComment(member)); + md.push( + `##### \`${getMemberName(member)}${member.optional === true ? '?' : ''}\``, + codeBlock(source(member)), + ...renderSummary(memberDoc), + ...renderTags(memberDoc) ); } } - internalGroup.children.push(...group.children); - return false; -}); -internalGroup.children.sort((a, b) => a.name.localeCompare(b.name)); -project.groups = [...publicGroups, internalGroup]; - -// list the components with a props interface first, each followed by its props interface, -// e.g. `DataGrid` and `DataGridProps`, then the other components -const componentsGroup = publicGroups.find((group) => group.title === 'Components'); -if (componentsGroup !== undefined) { - const names = new Set(componentsGroup.children.map((child) => child.name)); - const getSortKey = ({ name }: { name: string }) => { - const component = name.endsWith('Props') ? name.slice(0, -'Props'.length) : name; - return names.has(`${component}Props`) ? `0 ${component} ${name}` : `1 ${name}`; - }; - componentsGroup.children.sort((a, b) => getSortKey(a).localeCompare(getSortKey(b))); + return md.join('\n\n'); +} - for (const child of componentsGroup.children) { - if (!child.kindOf(ReflectionKind.Interface)) components.add(child); - } +function renderSummary({ summary }: Doc) { + return summary === '' ? [] : [convertLinks(summary)]; } -const interfaces = project - .getReflectionsByKind(ReflectionKind.Interface) - .filter((reflection) => reflection instanceof DeclarationReflection); +function renderTags({ tags }: Doc) { + const labels: Record = { + defaultValue: '**Default:** ', + example: '**Example:**\n\n', + see: '**See also:** ', + returns: '**Returns:**\n\n' + }; + return tags + .filter(({ name }) => name in labels) + .map(({ name, text }) => `${labels[name]}${convertLinks(text)}`); +} -// only list the members that are inherited from internal types, -// the members inherited from public types are listed in their own section -const membersInheritedFromPublicTypes = interfaces.flatMap( - (reflection) => reflection.children?.filter(isInheritedFromPublicType) ?? [] -); +// e.g. "**Props:** [`DataGridProps`](#datagridprops)" +function renderComponentProps(node: Node) { + const signature = + node.type === 'VariableDeclaration' + ? node.declarations![0].id!.typeAnnotation!.typeAnnotation! + : node; + const propsType = cleanCode(source(signature.params![0].typeAnnotation!.typeAnnotation!)); + return `[\`${propsType}\`](#!${/^\w+/.exec(propsType)![0]})`; +} -for (const member of membersInheritedFromPublicTypes) { - project.removeReflection(member); +function compareNames(a: Declaration, b: Declaration) { + return a.name.localeCompare(b.name); } -for (const reflection of interfaces) { - // `removeReflection` doesn't remove the members from the groups that are rendered - const remainingMembers = new Set(reflection.children); - if (reflection.groups !== undefined) { - for (const group of reflection.groups) { - group.children = group.children.filter((child) => remainingMembers.has(child)); - } - reflection.groups = reflection.groups.filter((group) => group.children.length > 0); - } +// the components with a props interface first, each followed by its props interface, +// e.g. `DataGrid` and `DataGridProps`, then the other components +function compareComponents(a: Declaration, b: Declaration) { + return getComponentSortKey(a).localeCompare(getComponentSortKey(b)); +} - // TypeDoc copies the comments of the members a member redeclares, - // like `CalculatedColumn` redeclaring the properties of `Column` with their resolved types, - // but their descriptions and defaults don't apply to the redeclared members - for (const child of reflection.children ?? []) { - const overwrittenComment = child.overwrites?.reflection?.comment; - if ( - child.comment !== undefined && - overwrittenComment !== undefined && - Comment.combineDisplayParts(child.comment.summary) === - Comment.combineDisplayParts(overwrittenComment.summary) - ) { - delete child.comment; - } - } +function getComponentSortKey({ name }: Declaration) { + const component = name.endsWith('Props') ? name.slice(0, -'Props'.length) : name; + return exportedNames.has(`${component}Props`) ? `0 ${component} ${name}` : `1 ${name}`; } -const outputDirectory = app.options.getValue('out'); -await app.generateOutputs(project); +function isType(node: Node) { + return node.type === 'TSInterfaceDeclaration' || node.type === 'TSTypeAliasDeclaration'; +} -const api = await readFile(`${outputDirectory}/README.md`, 'utf8'); -const readme = await readFile(readmePath, 'utf8'); +// members with more than a single paragraph can't be shown as comments of a code block +function hasRichMembers(node: Node) { + return ( + node.type === 'TSInterfaceDeclaration' && + node.body!.body.some((member) => { + const { summary, tags } = parseDoc(getComment(member)); + return ( + tags.some((tag) => tag.name !== 'defaultValue') || + summary.includes('\n\n') || + summary.includes('```') || + /^\s*(?:[-*+]|\d+\.) /m.test(summary) + ); + }) + ); +} -const startIndex = readme.indexOf(startMarker); -const endIndex = readme.indexOf(endMarker); +function getDeclarationName(node: Node) { + return node.id?.name ?? node.declarations![0].id!.name; +} -if (startIndex === -1 || endIndex < startIndex) { - throw new Error(`${readmePath} must contain ${startMarker} followed by ${endMarker}`); +function getMemberName({ key }: Node) { + return key!.type === 'Identifier' ? key!.name! : key!.value!; } -await writeFile( - readmePath, - replaceAnchors( - readme.slice(0, startIndex + startMarker.length), - api.trim(), - readme.slice(endIndex) - ) -); +// the JSDoc comment directly before the node +function getComment({ start }: Node) { + const comment = comments.findLast( + (comment) => + comment.type === 'Block' && + comment.value.startsWith('*') && + comment.end <= start && + code.slice(comment.end, start).trim() === '' + ); + return comment?.value ?? ''; +} -// e.g. `extends Column` or `extends Omit` -function getPublicBaseTypes(reflection: DeclarationReflection) { - const publicBaseTypes = new Set(); - for (const type of reflection.extendedTypes ?? []) { - if (!(type instanceof ReferenceType)) continue; - const [typeArgument] = type.typeArguments ?? []; - if ( - publicNames.has(type.name) || - ((type.name === 'Omit' || type.name === 'Pick') && - typeArgument instanceof ReferenceType && - publicNames.has(typeArgument.name)) - ) { - publicBaseTypes.add(type.name); +function parseDoc(comment: string): Doc { + const summary: string[] = []; + const tags: { name: string; lines: string[] }[] = []; + + forEachLine( + comment + .split('\n') + .map((line) => line.replace(/^\s*\*\s?/, '')) + .join('\n'), + (line, isInCodeBlock) => { + const tag = isInCodeBlock ? null : /^@(\w+)\s?(.*)$/.exec(line); + if (tag === null) { + (tags.at(-1)?.lines ?? summary).push(line); + } else { + tags.push({ name: tag[1], lines: [tag[2]] }); + } } - } - return publicBaseTypes; + ); + + return { + summary: summary.join('\n').trim(), + tags: tags.map(({ name, lines }) => ({ name, text: lines.join('\n').trim() })) + }; } -// a member is inherited from a public type directly, or through internal types, -// e.g. `RenderCellProps` inherits `onCellClick` from `BaseRenderCellProps`, which picks it from `DataGridProps` -function isInheritedFromPublicType(member: DeclarationReflection): boolean { - const { inheritedFrom, parent } = member; - if (inheritedFrom === undefined) return false; - - if ( - parent instanceof DeclarationReflection && - getPublicBaseTypes(parent).has(inheritedFrom.name.split('.')[0]) - ) { - return true; - } +function source({ start, end }: Node) { + return code.slice(start, end); +} - const inheritedMember = inheritedFrom.reflection; - return ( - inheritedMember instanceof DeclarationReflection && isInheritedFromPublicType(inheritedMember) - ); +function codeBlock(text: string) { + return `\`\`\`ts\n${cleanCode(text)}\n\`\`\``; } -// a property can be listed in a table if its comment is a single paragraph -function hasShortComment(reflection: DeclarationReflection) { - const { comment } = reflection; - if (comment === undefined) return true; - const summary = Comment.combineDisplayParts(comment.summary); - return ( - comment.blockTags.every((tag) => tag.tag === '@defaultValue') && - !summary.includes('\n\n') && - !summary.includes('```') && - !/^\s*(?:[-*+]|\d+\.) /m.test(summary) +// show the declarations without the `declare` keyword, link tags, and `NoInfer`, +// which only affects type inference +function cleanCode(text: string) { + return text + .replace(/^(?:export )?declare /, '') + .replaceAll( + /\{@link(?:code)? ([^}|]+?)(?: \| ([^}]+))?\}/g, + (_, target: string, label: string | undefined) => label ?? target + ) + .replaceAll(/NoInfer<([^<>]+)>/g, '$1'); +} + +// `{@linkcode Column.width | width}` -> "[`width`](#!Column.width)", resolved by `resolveLinks` +function convertLinks(text: string) { + return text.replaceAll( + /\{@link(?:code)? ([^}|]+?)(?: \| ([^}]+))?\}/g, + (_, target: string, label: string | undefined) => `[\`${label ?? target}\`](#!${target.trim()})` ); } -// typedoc-plugin-markdown adds an HTML anchor before each heading and links to it, -// replace them with the anchors GitHub generates for the headings, -// which are numbered across the whole README, starting with the headings before the API reference. -// Links outside of the API reference can link to a member with its name as the link title, -// e.g. `[width](#width "Column.width")`, to update the anchor when the numbering changes. -function replaceAnchors(precedingMarkdown: string, api: string, followingMarkdown: string) { +// replace the links to items and members, e.g. `#!Column` and `#!Column.width`, +// with the anchors GitHub generates for their headings, which are numbered across the whole README. +// Links in the hand-written sections of the README can link to an item or member with its name as +// the link title, e.g. `[width](#width "Column.width")`, to update the anchor when the numbering changes. +function resolveLinks(markdown: string) { const slugger = new GithubSlugger(); - function slug(heading: string) { - return slugger.slug(getHeadingText(heading)); - } - - forEachLine(precedingMarkdown, (line, isInCodeBlock) => { - const heading = isInCodeBlock ? null : /^#{1,6} (.+)$/.exec(line); - if (heading !== null) slug(heading[1]); - }); - - // anchors of the plugin, and of the API reference members, e.g. `Column.width` const anchors = new Map(); - const memberAnchors = new Map(); - const lines: string[] = []; - let pendingAnchor: string | undefined; let item: string | undefined; - forEachLine(api, (line, isInCodeBlock) => { - if (!isInCodeBlock) { - const anchor = /^<\/a>$/.exec(line); - if (anchor !== null) { - pendingAnchor = anchor[1]; - return; - } - const heading = /^(#{1,6}) (.+)$/.exec(line); - if (heading !== null) { - const headingSlug = slug(heading[2]); - // e.g. `DataGrid` for ``, `renderCheckbox` for `renderCheckbox()` - const name = getHeadingText(heading[2]) - .replace(/^<(.+) \/>$/, '$1') - .replace(/(?:\(\)|\?)$/, ''); - if (heading[1].length === 3) { - item = name; - memberAnchors.set(name, headingSlug); - } else if (pendingAnchor !== undefined && item !== undefined) { - memberAnchors.set(`${item}.${name}`, headingSlug); - } - if (pendingAnchor !== undefined) { - anchors.set(pendingAnchor, headingSlug); - pendingAnchor = undefined; - } - } else if (pendingAnchor !== undefined) { - // the empty line between the anchor and its heading - if (line === '') return; - throw new Error(`The anchor #${pendingAnchor} is not followed by a heading: ${line}`); - } + forEachLine(markdown, (line, isInCodeBlock) => { + const heading = isInCodeBlock ? null : /^(#{1,6}) (.+)$/.exec(line); + if (heading === null) return; + + const text = heading[2].replaceAll('`', ''); + const anchor = slugger.slug(text); + // e.g. `DataGrid` for ``, `renderCheckbox` for `renderCheckbox()` + const name = text.replace(/^<(.+) \/>$/, '$1').replace(/(?:\(\)|\?)$/, ''); + if (heading[1].length === 4) { + item = name; + anchors.set(name, anchor); + } else if (heading[1].length === 5 && item !== undefined) { + anchors.set(`${item}.${name}`, anchor); } - - lines.push(line); }); - // the anchors of table rows have no heading to link to - const tableAnchors = new Set(); - const markdown = lines.join('\n').replaceAll(/<\/a> /g, (_, id: string) => { - tableAnchors.add(id); - return ''; - }); - - const apiMarkdown = markdown.replaceAll(/\]\(#([^)]+)\)/g, (_, id: string) => { - const anchor = anchors.get(id); - if (anchor === undefined) { - throw new Error( - tableAnchors.has(id) - ? `The link to #${id} links to a table row, which has no heading to link to` - : `The link to #${id} does not match any heading` - ); - } - return `](#${anchor})`; - }); - - const linkedPrecedingMarkdown = precedingMarkdown.replaceAll( - /\]\(#[^ )]+ "([^"]+)"\)/g, - (_, member: string) => { - const anchor = memberAnchors.get(member); - if (anchor === undefined) { - throw new Error(`The link to "${member}" does not match any API reference heading`); - } - return `](#${anchor} "${member}")`; - } - ); - - return `${linkedPrecedingMarkdown}\n\n${apiMarkdown}\n\n${followingMarkdown}`; -} + const getAnchor = (target: string) => { + // members listed in the code block of their type link to the type + const anchor = anchors.get(target) ?? anchors.get(target.split('.')[0]); + if (anchor === undefined) throw new Error(`The link to ${target} does not match any heading`); + return anchor; + }; -function getHeadingText(heading: string) { - return heading - .replaceAll(/\[([^\]]*)\]\([^)]*\)/g, '$1') - .replaceAll(/\\(.)/g, '$1') - .replaceAll('`', ''); + return markdown + .replaceAll(/\]\(#!([\w.]+)\)/g, (_, target: string) => `](#${getAnchor(target)})`) + .replaceAll( + /\]\(#[^ )]+ "([\w.]+)"\)/g, + (_, target: string) => `](#${getAnchor(target)} "${target}")` + ); } function forEachLine(markdown: string, callback: (line: string, isInCodeBlock: boolean) => void) { @@ -429,30 +342,3 @@ function forEachLine(markdown: string, callback: (line: string, isInCodeBlock: b } } } - -function unwrapNoInfer(type: SomeType): SomeType { - if ( - type instanceof ReferenceType && - type.name === 'NoInfer' && - type.typeArguments?.length === 1 - ) { - return unwrapNoInfer(type.typeArguments[0]); - } - - // `Type` is the base class of all the `SomeType` types - for (const [key, value] of Object.entries(type)) { - if (value instanceof Type) { - Reflect.set(type, key, unwrapNoInfer(value as SomeType)); - } else if (Array.isArray(value)) { - Reflect.set( - type, - key, - value.map((item: unknown) => - item instanceof Type ? unwrapNoInfer(item as SomeType) : item - ) - ); - } - } - - return type; -} diff --git a/src/DataGrid.tsx b/src/DataGrid.tsx index 3a7d986016..ff4ebb8d3c 100644 --- a/src/DataGrid.tsx +++ b/src/DataGrid.tsx @@ -148,13 +148,13 @@ export interface DataGridProps { /** * An array of column definitions and/or column groups. See the {@linkcode ColumnOrColumnGroup} type for all available options. * - * :warning: **Performance:** Passing a new `columns` array will trigger a re-render and recalculation for the entire grid. Always memoize this prop using `useMemo` or define it outside the component to avoid unnecessary re-renders. + * ⚠️ **Performance:** Passing a new `columns` array will trigger a re-render and recalculation for the entire grid. Always memoize this prop using `useMemo` or define it outside the component to avoid unnecessary re-renders. */ columns: readonly ColumnOrColumnGroup, NoInfer>[]; /** * An array of rows. The row data can be of any type. * - * :bulb: **Performance:** The grid is optimized for efficient rendering: + * 💡 **Performance:** The grid is optimized for efficient rendering: * * - **Virtualization**: Only visible rows are rendered in the DOM * - **Individual row updates**: Row components are memoized, so updating a single row object will only re-render that specific row, not all rows @@ -173,13 +173,13 @@ export interface DataGridProps { /** * Rows pinned at the top of the grid for summary purposes. * - * :warning: **Performance:** Memoize this array to prevent internal memoization invalidation. + * ⚠️ **Performance:** Memoize this array to prevent internal memoization invalidation. */ topSummaryRows?: Maybe; /** * Rows pinned at the bottom of the grid for summary purposes. * - * :warning: **Performance:** Memoize this array to prevent internal memoization invalidation. + * ⚠️ **Performance:** Memoize this array to prevent internal memoization invalidation. */ bottomSummaryRows?: Maybe; /** @@ -202,9 +202,9 @@ export interface DataGridProps { * } * ``` * - * :bulb: While optional, setting this prop is recommended for optimal performance, as the returned value is used to set the `key` prop on the row elements. + * 💡 While optional, setting this prop is recommended for optimal performance, as the returned value is used to set the `key` prop on the row elements. * - * :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. + * ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. */ rowKeyGetter?: Maybe<(row: NoInfer) => K>; /** @@ -244,7 +244,7 @@ export interface DataGridProps { * ; * ``` * - * :warning: **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. + * ⚠️ **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. * * @defaultValue `35` pixels */ @@ -638,7 +638,7 @@ export interface DataGridProps { * } * ``` * - * :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. + * ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. */ rowClass?: Maybe<(row: NoInfer, rowIdx: number) => Maybe>; /** diff --git a/src/TreeDataGrid.tsx b/src/TreeDataGrid.tsx index 0e52ff6732..7b96f598cf 100644 --- a/src/TreeDataGrid.tsx +++ b/src/TreeDataGrid.tsx @@ -95,7 +95,7 @@ export interface TreeDataGridProps extends * } * ``` * - * :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. + * ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. */ rowGrouper: ( rows: readonly NoInfer[], @@ -129,7 +129,7 @@ export interface TreeDataGridProps extends /** * Function to generate unique IDs for group rows. If not provided, a default implementation is used that concatenates parent and group keys with `__`. * - * :warning: **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. + * ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. */ groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>; } diff --git a/src/index.ts b/src/index.ts index eab00a06fa..6b999c11b0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,8 +1,3 @@ -/** - * @module - * @sortStrategy alphabetical - */ - import './style/layers.css'; export { diff --git a/src/types.ts b/src/types.ts index 0c3b950a80..ec33b88b6b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -186,32 +186,27 @@ export interface Column { */ readonly sortDescendingFirst?: Maybe; /** Options for cell editing. */ - readonly editorOptions?: Maybe; -} - -/** - * Options for cell editing. - */ -interface ColumnEditorOptions { - /** - * Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. - * By default, the cell content is not rendered when the edit cell is open. - * - * @defaultValue `false` - */ - readonly displayCellContent?: Maybe; - /** - * Commit changes when clicking outside the cell. - * - * @defaultValue `true` - */ - readonly commitOnOutsideClick?: Maybe; - /** - * Close the editor when the row value changes externally. - * - * @defaultValue `true` - */ - readonly closeOnExternalRowChange?: Maybe; + readonly editorOptions?: Maybe<{ + /** + * Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. + * By default, the cell content is not rendered when the edit cell is open. + * + * @defaultValue `false` + */ + readonly displayCellContent?: Maybe; + /** + * Commit changes when clicking outside the cell. + * + * @defaultValue `true` + */ + readonly commitOnOutsideClick?: Maybe; + /** + * Close the editor when the row value changes externally. + * + * @defaultValue `true` + */ + readonly closeOnExternalRowChange?: Maybe; + }>; } /** diff --git a/tsconfig.node.json b/tsconfig.node.json index 30a83edc1c..6eb11afae4 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -1,8 +1,7 @@ { "extends": "./tsconfig.base.json", "compilerOptions": { - // `DOM` for the `WebAssembly` types of `@shikijs/types`, a dependency of TypeDoc - "lib": ["ESNext", "DOM"], + "lib": ["ESNext"], "module": "NodeNext", "types": ["node"] }, diff --git a/typedoc.json b/typedoc.json deleted file mode 100644 index 6e3a8ba392..0000000000 --- a/typedoc.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "$schema": "https://typedoc-plugin-markdown.org/schema.json", - "entryPoints": ["src/index.ts"], - "tsconfig": "tsconfig.src.json", - "plugin": ["typedoc-plugin-markdown", "typedoc-plugin-missing-exports"], - "placeInternalsInOwningModule": true, - "out": "node_modules/.cache/typedoc", - "router": "module", - "readme": "none", - "excludeExternals": true, - "disableSources": true, - "groupOrder": ["Components", "Hooks", "Render Functions", "Context", "Other", "Types", "*"], - "sort": ["source-order"], - "notRenderedTags": [ - "@showCategories", - "@showGroups", - "@hideCategories", - "@hideGroups", - "@disableGroups", - "@expand", - "@preventExpand", - "@expandType", - "@summary", - "@group", - "@groupDescription", - "@category", - "@categoryDescription", - "@sortStrategy" - ], - "hidePageHeader": true, - "hidePageTitle": true, - "hideBreadcrumbs": true, - "useCodeBlocks": true, - "expandParameters": true, - "parametersFormat": "none", - "typeDeclarationVisibility": "compact", - "useHTMLAnchors": true -} diff --git a/vite.config.ts b/vite.config.ts index 658b0aea87..2a9867816e 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -54,8 +54,7 @@ async function dragFill( // TODO: remove when vite-plus detects TypeScript 7.1 as TypeScript 7 async function getTscPath(): Promise { - const { default: getExePath } = - await import('./node_modules/@typescript/native/lib/getExePath.js'); + const { default: getExePath } = await import('./node_modules/typescript/lib/getExePath.js'); return getExePath(); } @@ -83,9 +82,9 @@ export default defineConfig({ command: 'tsc --build', cache: false }, - // generates the API reference of the README from the JSDoc comments + // generates the API reference of the README from the declarations and JSDoc comments of `lib/index.d.ts` docs: { - command: ['node scripts/generateApiDocs.ts', 'vp fmt README.md'], + command: ['vp pack', 'node scripts/generateApiDocs.ts', 'vp fmt README.md'], // the README is both an input and the output cache: false }, @@ -125,9 +124,8 @@ export default defineConfig({ 'vp run test' ], cache: { - // `vp pack` cleans `lib/` before writing to it, - // and `vp run docs` writes its intermediate output to `node_modules/.cache/typedoc/` - input: [{ auto: true }, '!lib/**', '!node_modules/.cache/typedoc/**'] + // `vp pack` cleans `lib/` before writing to it + input: [{ auto: true }, '!lib/**'] } }, // the first step of a release, see the header of `.github/workflows/publish.yml`: @@ -574,20 +572,8 @@ copy( 'jsdoc/check-tag-names': [ 'warn', { - // TypeDoc tags: https://typedoc.org/documents/Tags.html - definedTags: [ - 'category', - 'categoryDescription', - 'defaultValue', - 'group', - 'groupDescription', - 'inline', - 'inlineType', - 'internal', - 'module', - 'sortStrategy', - 'typeParam' - ] + // TSDoc tags, and `@group`, which sets the section of the README's API reference + definedTags: ['defaultValue', 'group', 'typeParam'] } ], 'jsdoc/empty-tags': 'warn', From 19848bde31d9b23836df212f5330d5657e9da933 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 17:17:08 -0500 Subject: [PATCH 10/22] Match the layout and order of the previous README - List the items in the order they are exported from `src/index.ts`, which now exports them by name, in the order of the previous README - Title the items and members with their signatures, which keeps most of the previous anchors, and nest the props interfaces under their components - Show the documented internal types with the other types, and the undocumented ones in the code block of the types that reference them - Declare the `div` props of `DataGridProps` with React's types - Move the "Generics" section back to the end of the API reference Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- README.md | 1803 ++++++++++++++---------------------- scripts/generateApiDocs.ts | 310 +++++-- src/DataGrid.tsx | 20 +- src/index.ts | 73 +- 5 files changed, 962 insertions(+), 1246 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 818a388810..275e764644 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ website/ # demo site (Vite + TanStack Router) ## Conventions - **Public API** — all exports flow through `src/index.ts`. Keep `README.md` in sync with user-facing changes. -- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. Every export from `src/index.ts` needs a `@group` tag with one of the sections in `scripts/generateApiDocs.ts` (Components, Hooks, Render Functions, Context, Other, Types). Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tags; add new tags to `definedTags` of `jsdoc/check-tag-names` in `vite.config.ts`. In the hand-written sections of the README, give links to API members the member as title, e.g., ``[`width`](#width "Column.width")``, so `vp run docs` keeps their anchor up to date. +- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. Every export from `src/index.ts` needs a `@group` tag with one of the sections in `scripts/generateApiDocs.ts` (Components, Hooks, Render Functions, Context, Other, Types), and the order of the exports is the order of the API reference. Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tags; add new tags to `definedTags` of `jsdoc/check-tag-names` in `vite.config.ts`. In the hand-written sections of the README, give links to API members the member as title, e.g., ``[`width`](#width "Column.width")``, so `vp run docs` keeps their anchor up to date. - **Docs** — keep `AGENTS.md` in sync with tooling, conventions, or architectural changes. - **Default renderers** — `DataGridRenderersContext` allows overriding default renderers (`renderCheckbox`, `renderSortStatus`, `renderRow`, `renderCell`, `noRowsFallback`) without prop-drilling. - **TypeScript strict** with `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, `erasableSyntaxOnly`. Distinguish missing properties from `undefined` values. diff --git a/README.md b/README.md index 1f0f250bc1..9f8693eae1 100644 --- a/README.md +++ b/README.md @@ -198,7 +198,7 @@ Example of customizing colors: ### Standard Props -The DataGrid accepts standard [`className`](#classname 'DataGridProps.className') and [`style`](#style 'DataGridProps.style') props: +The DataGrid accepts standard [`className`](#classname-string--undefined 'DataGridProps.className') and [`style`](#style-reactcssproperties--undefined 'DataGridProps.style') props: ```tsx ### Components @@ -247,43 +241,25 @@ Replace default components with custom implementations using the [`renderers`](# Main API component to render a data grid of rows and columns -**Props:** [`DataGridProps`](#datagridprops) - **Example:** ```tsx ``` -#### `DataGridProps` - -```ts -interface DataGridProps { … } -``` - -##### `ref?` +##### DataGridProps -```ts -ref?: Maybe>; -``` +###### `ref?: Maybe>` Optional ref for imperative APIs like scrolling to or focusing a cell. See [`DataGridHandle`](#datagridhandle). -##### `columns` - -```ts -columns: readonly ColumnOrColumnGroup[]; -``` +###### `columns: readonly ColumnOrColumnGroup[]` -An array of column definitions and/or column groups. See the [`ColumnOrColumnGroup`](#columnorcolumngroup) type for all available options. +An array of column definitions and/or column groups. See the [`ColumnOrColumnGroup`](#columnorcolumngroupr-sr) type for all available options. ⚠️ **Performance:** Passing a new `columns` array will trigger a re-render and recalculation for the entire grid. Always memoize this prop using `useMemo` or define it outside the component to avoid unnecessary re-renders. -##### `rows` - -```ts -rows: readonly R[]; -``` +###### `rows: readonly R[]` An array of rows. The row data can be of any type. @@ -302,31 +278,19 @@ An array of rows. The row data can be of any type. setRows(rows.map((row) => ({ ...row }))); ``` -##### `topSummaryRows?` - -```ts -topSummaryRows?: Maybe; -``` +###### `topSummaryRows?: Maybe` Rows pinned at the top of the grid for summary purposes. ⚠️ **Performance:** Memoize this array to prevent internal memoization invalidation. -##### `bottomSummaryRows?` - -```ts -bottomSummaryRows?: Maybe; -``` +###### `bottomSummaryRows?: Maybe` Rows pinned at the bottom of the grid for summary purposes. ⚠️ **Performance:** Memoize this array to prevent internal memoization invalidation. -##### `rowKeyGetter?` - -```ts -rowKeyGetter?: Maybe<(row: R) => K>; -``` +###### `rowKeyGetter?: Maybe<(row: R) => K>` Function to return a unique key/identifier for each row. `rowKeyGetter` is required for row selection to work. @@ -351,16 +315,12 @@ function MyGrid() { ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. -##### `onRowsChange?` - -```ts -onRowsChange?: Maybe<(rows: R[], data: RowsChangeData) => void>; -``` +###### `onRowsChange?: Maybe<(rows: R[], data: RowsChangeData) => void>` Callback triggered when rows are changed. The first parameter is a new rows array with both the updated rows and the other untouched rows. -The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. See the [`RowsChangeData`](#rowschangedata) type. +The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. See the [`RowsChangeData`](#rowschangedatar-sr) type. ```tsx import { useState } from 'react'; @@ -373,11 +333,7 @@ function MyGrid() { } ``` -##### `rowHeight?` - -```ts -rowHeight?: Maybe number)>; -``` +###### `rowHeight?: Maybe number)>` Height of each row in pixels. A function can be used to set different row heights. @@ -397,21 +353,13 @@ function getRowHeight(row) { **Default:** `35` pixels -##### `headerRowHeight?` - -```ts -headerRowHeight?: Maybe; -``` +###### `headerRowHeight?: Maybe` Height of the header row in pixels. **Default:** `rowHeight` when it is a number, otherwise `35` pixels -##### `summaryRowHeight?` - -```ts -summaryRowHeight?: Maybe; -``` +###### `summaryRowHeight?: Maybe` Height of each summary row in pixels. @@ -428,13 +376,9 @@ Height of each summary row in pixels. **Default:** `rowHeight` when it is a number, otherwise `35` pixels -##### `columnWidths?` +###### `columnWidths?: Maybe` -```ts -columnWidths?: Maybe; -``` - -A map of column widths containing both measured and resized widths. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths-1) type. +A map of column widths containing both measured and resized widths. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths) type. ```tsx const [columnWidths, setColumnWidths] = useState((): ColumnWidths => new Map()); @@ -448,35 +392,19 @@ function addNewRow() { return ``` -##### `onColumnWidthsChange?` - -```ts -onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; -``` - -Callback triggered when column widths change. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths-1) type. +###### `onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>` -##### `selectedRows?` +Callback triggered when column widths change. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths) type. -```ts -selectedRows?: Maybe>; -``` +###### `selectedRows?: Maybe>` A set of selected row keys. `rowKeyGetter` is required for row selection to work. -##### `isRowSelectionDisabled?` - -```ts -isRowSelectionDisabled?: Maybe<(row: R) => boolean>; -``` +###### `isRowSelectionDisabled?: Maybe<(row: R) => boolean>` Function to determine if row selection is disabled for a specific row. -##### `onSelectedRowsChange?` - -```ts -onSelectedRowsChange?: Maybe<(selectedRows: Set) => void>; -``` +###### `onSelectedRowsChange?: Maybe<(selectedRows: Set) => void>` Callback triggered when the selection changes. @@ -515,21 +443,13 @@ function MyGrid() { } ``` -##### `sortColumns?` - -```ts -sortColumns?: Maybe; -``` +###### `sortColumns?: Maybe` An array of sorted columns. See the [`SortColumn`](#sortcolumn) type. Sorting is controlled: the grid does not reorder `rows` for you. Apply the sorting to your `rows` state (or derived rows) based on `sortColumns`. -##### `onSortColumnsChange?` - -```ts -onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>; -``` +###### `onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>` Callback triggered when sorting changes. @@ -570,13 +490,9 @@ function onSortColumnsChange(sortColumns: SortColumn[]) { } ``` -##### `defaultColumnOptions?` - -```ts -defaultColumnOptions?: Maybe>; -``` +###### `defaultColumnOptions?: Maybe>` -Default options applied to all columns. See the [`DefaultColumnOptions`](#defaultcolumnoptions-1) type. +Default options applied to all columns. See the [`DefaultColumnOptions`](#defaultcolumnoptionsr-sr) type. ```tsx function MyGrid() { @@ -595,13 +511,9 @@ function MyGrid() { } ``` -##### `onCellMouseDown?` +###### `onCellMouseDown?: CellMouseEventHandler` -```ts -onCellMouseDown?: CellMouseEventHandler; -``` - -Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargsr-sr) and [`CellMouseEvent`](#cellmouseevent) types. ```tsx function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { @@ -613,13 +525,9 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -##### `onCellClick?` - -```ts -onCellClick?: CellMouseEventHandler; -``` +###### `onCellClick?: CellMouseEventHandler` -Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargsr-sr) and [`CellMouseEvent`](#cellmouseevent) types. This event can be used to open the cell editor on a single click: @@ -633,13 +541,9 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -##### `onCellDoubleClick?` - -```ts -onCellDoubleClick?: CellMouseEventHandler; -``` +###### `onCellDoubleClick?: CellMouseEventHandler` -Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargsr-sr) and [`CellMouseEvent`](#cellmouseevent) types. ```tsx function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { @@ -651,13 +555,9 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -##### `onCellContextMenu?` - -```ts -onCellContextMenu?: CellMouseEventHandler; -``` +###### `onCellContextMenu?: CellMouseEventHandler` -Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargsr-sr) and [`CellMouseEvent`](#cellmouseevent) types. ```tsx function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { @@ -670,13 +570,9 @@ function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -##### `onCellKeyDown?` +###### `onCellKeyDown?: Maybe<(args: CellKeyDownArgs, event: CellKeyboardEvent) => void>` -```ts -onCellKeyDown?: Maybe<(args: CellKeyDownArgs, event: CellKeyboardEvent) => void>; -``` - -Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. See the [`CellKeyDownArgs`](#cellkeydownargs) and [`CellKeyboardEvent`](#cellkeyboardevent) types. +Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. See the [`CellKeyDownArgs`](#cellkeydownargsr-sr) and [`CellKeyboardEvent`](#cellkeyboardevent) types. **Examples** @@ -702,57 +598,33 @@ function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website/routes/CellNavigation.tsx). -##### `onCellCopy?` - -```ts -onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => void>; -``` +###### `onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => void>` -Callback triggered when a cell's content is copied. See the [`CellCopyArgs`](#cellcopyargs) type. +Callback triggered when a cell's content is copied. See the [`CellCopyArgs`](#cellcopyargsr-sr) type. -##### `onCellPaste?` - -```ts -onCellPaste?: Maybe<(args: CellPasteArgs, event: CellClipboardEvent) => R>; -``` +###### `onCellPaste?: Maybe<(args: CellPasteArgs, event: CellClipboardEvent) => R>` -Callback triggered when content is pasted into a cell. See the [`CellPasteArgs`](#cellpasteargs) type. +Callback triggered when content is pasted into a cell. See the [`CellPasteArgs`](#cellpasteargsr-sr) type. Return the updated row; the grid will call `onRowsChange` with it. -##### `onActivePositionChange?` - -```ts -onActivePositionChange?: Maybe<(args: PositionChangeArgs) => void>; -``` - -Callback triggered when the active position changes. See the [`PositionChangeArgs`](#positionchangeargs) type. - -##### `onColumnResize?` +###### `onActivePositionChange?: Maybe<(args: PositionChangeArgs) => void>` -```ts -onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void>; -``` +Callback triggered when the active position changes. See the [`PositionChangeArgs`](#positionchangeargsr-sr) type. -Callback triggered when a column is resized. The `column` parameter is the full [`CalculatedColumn`](#calculatedcolumn) object, and `width` is the new width in pixels. +###### `onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void>` -##### `onColumnsReorder?` +Callback triggered when a column is resized. The `column` parameter is the full [`CalculatedColumn`](#calculatedcolumnr-sr) object, and `width` is the new width in pixels. -```ts -onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>; -``` +###### `onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>` Callback triggered when columns are reordered. The parameters are the `key` values of the source and target columns. -##### `onFill?` - -```ts -onFill?: Maybe<(event: FillEvent) => R>; -``` +###### `onFill?: Maybe<(event: FillEvent) => R>` Callback triggered when the value of the active cell is dragged to fill other cells. When this prop is set, a drag handle is shown on the active cell if it is editable. Drag the handle up or down to fill the cells it passes over, or double-click it to fill all the cells below. -The grid calls `onFill` for each editable target cell. Return the updated target row; the grid will call `onRowsChange` with the updated rows. See the [`FillEvent`](#fillevent) type. +The grid calls `onFill` for each editable target cell. Return the updated target row; the grid will call `onRowsChange` with the updated rows. See the [`FillEvent`](#filleventr) type. ```tsx function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { @@ -762,33 +634,21 @@ function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { ; ``` -##### `onScroll?` - -```ts -onScroll?: DivProps['onScroll']; -``` +###### `onScroll?: React.UIEventHandler | undefined` Native DOM `onScroll` prop. -##### `enableVirtualization?` - -```ts -enableVirtualization?: Maybe; -``` +###### `enableVirtualization?: Maybe` This prop can be used to disable virtualization. **Default:** `true` -##### `renderers?` - -```ts -renderers?: Maybe>; -``` +###### `renderers?: Maybe>` Custom renderers for cells, rows, and other components. -See the [`Renderers`](#renderers-1) type for the full shape. +See the [`Renderers`](#renderersr-sr) type for the full shape. Example of replacing default components: @@ -845,11 +705,7 @@ function MyGrid() { } ``` -##### `rowClass?` - -```ts -rowClass?: Maybe<(row: R, rowIdx: number) => Maybe>; -``` +###### `rowClass?: Maybe<(row: R, rowIdx: number) => Maybe>` Function to apply custom class names to rows. @@ -867,11 +723,7 @@ function MyGrid() { ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. -##### `headerRowClass?` - -```ts -headerRowClass?: Maybe; -``` +###### `headerRowClass?: Maybe` Custom class name for the header row. @@ -879,13 +731,9 @@ Custom class name for the header row. ``` -##### `direction?` +###### `direction?: Maybe` -```ts -direction?: Maybe; -``` - -This property sets the text direction of the grid. It defaults to `'ltr'` (left-to-right). See the [`Direction`](#direction-1) type. +This property sets the text direction of the grid. It defaults to `'ltr'` (left-to-right). See the [`Direction`](#direction) type. Setting `direction` to `'rtl'` has the following effects: @@ -896,75 +744,39 @@ Setting `direction` to `'rtl'` has the following effects: **Default:** `'ltr'` -##### `className?` - -```ts -className?: DivProps['className']; -``` +###### `className?: string | undefined` Custom class name for the grid. -##### `style?` - -```ts -style?: DivProps['style']; -``` +###### `style?: React.CSSProperties | undefined` Custom styles for the grid. -##### `role?` - -```ts -role?: DivProps['role']; -``` +###### `role?: React.AriaRole | undefined` ARIA role for the grid container. Defaults to `grid`. -##### `aria-label?` - -```ts -'aria-label'?: DivProps['aria-label']; -``` +###### `'aria-label'?: string | undefined` The label of the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. -##### `aria-labelledby?` - -```ts -'aria-labelledby'?: DivProps['aria-labelledby']; -``` +###### `'aria-labelledby'?: string | undefined` The id of the element containing a label for the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. -##### `aria-rowcount?` - -```ts -'aria-rowcount'?: DivProps['aria-rowcount']; -``` +###### `'aria-rowcount'?: number | undefined` Total number of rows for assistive technologies. -##### `aria-description?` - -```ts -'aria-description'?: DivProps['aria-description']; -``` +###### `'aria-description'?: string | undefined` A human-readable description of the grid. -##### `aria-describedby?` - -```ts -'aria-describedby'?: DivProps['aria-describedby']; -``` +###### `'aria-describedby'?: string | undefined` If the grid has a caption or description, `aria-describedby` can be set on the grid element with a value referring to the element containing the description. -##### `data-testid?` - -```ts -'data-testid'?: Maybe; -``` +###### `'data-testid'?: Maybe` This prop can be used to add a test ID for testing. We recommend querying the grid by its `role` and `name`. @@ -979,11 +791,7 @@ test('grid', async () => { }); ``` -##### `data-cy?` - -```ts -'data-cy'?: Maybe; -``` +###### `'data-cy'?: Maybe` Optional attribute to help with Cypress (or similar) selectors. @@ -1020,29 +828,15 @@ The following `DataGrid` props are not supported in `TreeDataGrid`: - Cell copy/paste does not work on group rows - Column groups are not supported; `columns` must be `Column[]` -**Props:** [`TreeDataGridProps`](#treedatagridprops) - -#### `TreeDataGridProps` - -All [`DataGridProps`](#datagridprops) are supported except those listed above. The `columns` prop only supports `Column[]` (no column groups). When `rowHeight` is a function, it receives [`RowHeightArgs`](#rowheightargs) instead of just the row. Additional props are listed below: - -```ts -interface TreeDataGridProps extends Omit, 'columns' | 'role' | 'aria-rowcount' | 'rowHeight' | 'onFill' | 'isRowSelectionDisabled'> { … } -``` +##### TreeDataGridProps -##### `columns` - -```ts -columns: readonly Column[]; -``` +All [`DataGridProps`](#datagridprops) are supported except those listed above. The `columns` prop only supports `Column[]` (no column groups). When `rowHeight` is a function, it receives [`RowHeightArgs`](#rowheightargsr) instead of just the row. Additional props are listed below: -##### `rowHeight?` +###### `columns: readonly Column[]` -```ts -rowHeight?: Maybe) => number)>; -``` +###### `rowHeight?: Maybe) => number)>` -**Note:** Unlike `DataGrid`, the `rowHeight` function receives [`RowHeightArgs`](#rowheightargs), which includes a `type` property to distinguish between regular rows and group rows: +**Note:** Unlike `DataGrid`, the `rowHeight` function receives [`RowHeightArgs`](#rowheightargsr), which includes a `type` property to distinguish between regular rows and group rows: ```tsx function getRowHeight(args: RowHeightArgs): number { @@ -1055,11 +849,7 @@ function getRowHeight(args: RowHeightArgs): number { ``` -##### `groupBy` - -```ts -groupBy: readonly string[]; -``` +###### `groupBy: readonly string[]` **Required.** An array of column keys to group by. The order determines the grouping hierarchy (first key is the top level, second key is nested under the first, etc.). @@ -1091,11 +881,7 @@ function MyGrid() { } ``` -##### `rowGrouper` - -```ts -rowGrouper: (rows: readonly R[], columnKey: string) => Record; -``` +###### `rowGrouper: (rows: readonly R[], columnKey: string) => Record` **Required.** A function that groups rows by the specified column key. Returns an object where keys are the group values and values are arrays of rows belonging to that group. @@ -1107,11 +893,7 @@ function rowGrouper(rows: readonly Row[], columnKey: string): Record; -``` +###### `expandedGroupIds: ReadonlySet` **Required.** A set of group IDs that are currently expanded. Group IDs are generated by `groupIdGetter`. @@ -1132,35 +914,31 @@ function MyGrid() { } ``` -##### `onExpandedGroupIdsChange` - -```ts -onExpandedGroupIdsChange: (expandedGroupIds: Set) => void; -``` +###### `onExpandedGroupIdsChange: (expandedGroupIds: Set) => void` **Required.** Callback triggered when groups are expanded or collapsed. -##### `groupIdGetter?` - -```ts -groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>; -``` +###### `groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>` Function to generate unique IDs for group rows. If not provided, a default implementation is used that concatenates parent and group keys with `__`. ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. -#### `` +#### `` -The default cell component. Can be wrapped via the `renderers.renderCell` prop. +The default row component. Can be wrapped via the `renderers.renderRow` prop. -**Props:** [`RenderCellProps`](#rendercellprops) +##### Props -#### `` +[`RenderRowProps`](#renderrowpropsr-sr) -The default row component. Can be wrapped via the `renderers.renderRow` prop. +#### `` + +The default cell component. Can be wrapped via the `renderers.renderCell` prop. + +##### Props -**Props:** [`RenderRowProps`](#renderrowprops) +[`RenderCellProps`](#rendercellpropsr-sr) #### `` @@ -1168,26 +946,22 @@ A component for rendering row selection checkboxes. The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. -**Props:** [`SelectCheckboxProps`](#selectcheckboxprops) +##### Props + +`SelectCheckboxProps` #### `` Low-level component used by `renderToggleGroup` to render the expand/collapse control. Useful if you build a custom group cell renderer. -**Props:** [`RenderGroupCellContentProps`](#rendergroupcellcontentprops) +##### Props + +[`RenderGroupCellContentProps`](#rendergroupcellcontentpropsr-sr) ### Hooks #### `useHeaderRowSelection()` -```ts -function useHeaderRowSelection(): { - isIndeterminate: boolean; - isRowSelected: boolean; - onRowSelectionChange: (selectRowEvent: SelectHeaderRowEvent) => void; -}; -``` - Hook for managing header row selection state. Used within custom header cell renderers to implement custom "select all" functionality. **Returns:** @@ -1224,14 +998,6 @@ function CustomHeaderCell() { #### `useRowSelection()` -```ts -function useRowSelection(): { - isRowSelectionDisabled: boolean; - isRowSelected: boolean; - onRowSelectionChange: (selectRowEvent: SelectRowEvent) => void; -}; -``` - Hook for managing row selection state. Used within custom cell renderers to implement custom row selection. **Returns:** @@ -1265,39 +1031,7 @@ function CustomSelectCell({ row }: RenderCellContentProps) { ### Render Functions -#### `renderCheckbox()` - -```ts -function renderCheckbox({ - onChange, - indeterminate, - ...props -}: RenderCheckboxProps): import('react').JSX.Element; -``` - -Renders a checkbox input with proper styling and accessibility. - -**Example:** - -```tsx -import { DataGrid, renderCheckbox } from 'react-data-grid'; - - renderCheckbox({ ...props, 'aria-label': 'Select row' }) - }} -/>; -``` - -#### `renderHeaderCell()` - -```ts -function renderHeaderCell({ - column, - sortDirection, - priority -}: RenderHeaderCellContentProps): string | import('react').JSX.Element; -``` +#### `renderHeaderCell(props: RenderHeaderCellContentProps)` The default header cell content renderer. Renders sortable columns with sort indicators. @@ -1316,32 +1050,7 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderSortIcon()` - -```ts -function renderSortIcon({ sortDirection }: RenderSortIconProps): import('react').JSX.Element | null; -``` - -Renders the sort direction arrow icon. - -#### `renderSortPriority()` - -```ts -function renderSortPriority({ priority }: RenderSortPriorityProps): number | undefined; -``` - -Renders the sort priority number for multi-column sorting. - -#### `renderTextEditor()` - -```ts -function renderTextEditor({ - row, - column, - onRowChange, - onClose -}: RenderEditCellContentProps): import('react').JSX.Element; -``` +#### `renderTextEditor(props: RenderEditCellContentProps)` A basic text editor provided for convenience. @@ -1359,14 +1068,32 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderToggleGroup()` +#### `renderSortIcon(props: RenderSortIconProps)` -```ts -function renderToggleGroup( - props: RenderGroupCellContentProps -): import('react').JSX.Element; +Renders the sort direction arrow icon. + +#### `renderSortPriority(props: RenderSortPriorityProps)` + +Renders the sort priority number for multi-column sorting. + +#### `renderCheckbox(props: RenderCheckboxProps)` + +Renders a checkbox input with proper styling and accessibility. + +**Example:** + +```tsx +import { DataGrid, renderCheckbox } from 'react-data-grid'; + + renderCheckbox({ ...props, 'aria-label': 'Select row' }) + }} +/>; ``` +#### `renderToggleGroup(props: RenderGroupCellContentProps)` + The default group cell content renderer for the columns used for grouping (`groupBy` prop). This renders the expand/collapse toggle. **Example:** @@ -1383,11 +1110,7 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderValue()` - -```ts -function renderValue(props: RenderCellContentProps): React.ReactNode; -``` +#### `renderValue(props: RenderCellContentProps)` The default cell content renderer that renders the value of `row[column.key]`. @@ -1409,10 +1132,6 @@ const columns: readonly Column[] = [ #### `DataGridRenderersContext` -```ts -const DataGridRenderersContext: import("react").Context>>; -``` - Context for providing default renderers to DataGrids in your app. **Example:** @@ -1448,27 +1167,7 @@ function AppProvider({ children }) { ### Other -#### `SELECT_COLUMN_KEY` - -```ts -const SELECT_COLUMN_KEY = 'rdg-select-column'; -``` - -The key used for the `SelectColumn`. Useful for identifying or filtering the select column. - -**Example:** - -```tsx -import { SELECT_COLUMN_KEY } from 'react-data-grid'; - -const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN_KEY); -``` - -#### `SelectColumn` - -```ts -const SelectColumn: Column; -``` +#### `SelectColumn: Column` A pre-configured column for row selection. Includes checkbox renderers for the header row, regular rows, and group rows. @@ -1497,237 +1196,35 @@ function MyGrid() { } ``` -### Types - -#### `CalculatedColumn` - -Extends `Column` with additional computed properties used internally by the grid. This is the type passed to render functions. The `Column` properties it redeclares, like `width` and `renderCell`, are resolved to their default values when not set. - -```ts -interface CalculatedColumn extends Column { - /** The column group that contains the column, or `undefined` if the column is not in a group */ - readonly parent: CalculatedColumnParent | undefined; - /** The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` */ - readonly idx: number; - /** Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups */ - readonly level: number; - readonly width: number | string; - readonly minWidth: number; - readonly maxWidth: number | undefined; - readonly resizable: boolean; - readonly sortable: boolean; - readonly draggable: boolean; - readonly frozen: ColumnFrozen; - readonly renderCell: (props: RenderCellContentProps) => ReactNode; - readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; -} -``` - -**See also:** [`Column`](#column), [`onColumnResize`](#oncolumnresize) prop on `` - -#### `CalculatedColumnOrColumnGroup` - -Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. - -```ts -type CalculatedColumnOrColumnGroup = CalculatedColumnParent | CalculatedColumn; -``` - -**See also:** [`CalculatedColumn`](#calculatedcolumn), [`CalculatedColumnParent`](#calculatedcolumnparent) - -#### `CalculatedColumnParent` - -Represents a parent column group in the calculated column structure. - -```ts -interface CalculatedColumnParent { - readonly name: string | ReactElement; - readonly parent: CalculatedColumnParent | undefined; - readonly idx: number; - readonly colSpan: number; - readonly level: number; - readonly headerCellClass?: Maybe; -} -``` - -**See also:** [`CalculatedColumn`](#calculatedcolumn) - -#### `CellCopyArgs` - -Arguments passed to `onCellCopy`. - -```ts -type CellCopyArgs = CellCopyPasteArgs; -``` - -**See also:** [`onCellCopy`](#oncellcopy) prop on `` - -#### `CellKeyboardEvent` - -Extends `React.KeyboardEvent` with grid-specific methods. - -```ts -type CellKeyboardEvent = CellEvent>; -``` - -**See also:** [`onCellKeyDown`](#oncellkeydown) prop on `` - -#### `CellKeyDownArgs` - -Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. - -```ts -type CellKeyDownArgs = ActiveCellKeyDownArgs | EditCellKeyDownArgs; -``` - -**Example:** - -```tsx -import type { CellKeyboardEvent, CellKeyDownArgs } from 'react-data-grid'; - -function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { - if (args.mode === 'EDIT' && event.key === 'Escape') { - args.onClose(false); // Close without committing - event.preventGridDefault(); - } -} -``` - -**See also:** [`onCellKeyDown`](#oncellkeydown) prop on `` - -#### `CellMouseArgs` - -Arguments passed to cell mouse event handlers. - -```ts -interface CellMouseArgs { - /** The column object of the cell. */ - column: CalculatedColumn; - /** The row object of the cell. */ - row: R; - /** The row index of the cell. */ - rowIdx: number; - /** Function to manually focus the cell. Pass `true` to immediately start editing. */ - setActivePosition: (enableEditor?: boolean) => void; -} -``` - -**Example:** - -```tsx -import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; - -function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { - console.log('Clicked cell at row', args.rowIdx, 'column', args.column.key); - args.setActivePosition(true); // Focus and start editing -} -``` - -**See also:** [`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` - -#### `CellMouseEvent` - -Extends `React.MouseEvent` with grid-specific methods. - -```ts -type CellMouseEvent = CellEvent>; -``` - -**Example:** - -```tsx -import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; - -function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { - if (args.column.key === 'actions') { - event.preventGridDefault(); // Prevent cell focus - } -} -``` - -**See also:** [`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` - -#### `CellPasteArgs` - -Arguments passed to `onCellPaste`. - -```ts -type CellPasteArgs = CellCopyPasteArgs; -``` - -**See also:** [`onCellPaste`](#oncellpaste) prop on `` - -#### `ColSpanArgs` +#### `SELECT_COLUMN_KEY = 'rdg-select-column'` -Arguments passed to the `colSpan` function. - -```ts -type ColSpanArgs = - | { - readonly type: 'HEADER'; - } - | { - readonly type: 'ROW'; - readonly row: R; - } - | { - readonly type: 'SUMMARY'; - readonly row: SR; - }; -``` +The key used for the `SelectColumn`. Useful for identifying or filtering the select column. **Example:** ```tsx -import type { Column } from 'react-data-grid'; +import { SELECT_COLUMN_KEY } from 'react-data-grid'; -const columns: readonly Column[] = [ - { - key: 'title', - name: 'Title', - colSpan(args) { - if (args.type === 'ROW' && args.row.isFullWidth) { - return 3; // Span 3 columns - } - return undefined; - } - } -]; +const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN_KEY); ``` -**See also:** [`column.colSpan`](#colspan) +### Types -#### `Column` +#### `Column` Defines the configuration for a column in the grid. -```ts -interface Column { … } -``` - -**See also:** [`columns`](#columns) prop on `` +**See also:** [`columns`](#columns-readonly-columnorcolumngroupr-sr) prop on `` -##### `name` - -```ts -readonly name: string | ReactElement; -``` +##### `name: string | ReactElement` The name of the column. Displayed in the header cell by default. -##### `key` - -```ts -readonly key: string; -``` +##### `key: string` A unique key to distinguish each column. -##### `width?` - -```ts -readonly width?: Maybe; -``` +##### `width?: Maybe` Width can be any valid CSS grid column value. If not specified, it will be determined automatically based on grid width and specified widths of other columns. @@ -1767,29 +1264,17 @@ width: 'minmax(100px, max-content)', **Default:** `auto` -##### `minWidth?` - -```ts -readonly minWidth?: Maybe; -``` +##### `minWidth?: Maybe` Minimum column width in pixels. **Default:** `50` pixels -##### `maxWidth?` - -```ts -readonly maxWidth?: Maybe; -``` +##### `maxWidth?: Maybe` Maximum column width in pixels. -##### `cellClass?` - -```ts -readonly cellClass?: Maybe Maybe)>; -``` +##### `cellClass?: Maybe Maybe)>` Class name(s) for cells. Can be a string or a function that returns a class name based on the row. @@ -1823,77 +1308,41 @@ const columns: Column[] = [ } ``` -##### `headerCellClass?` - -```ts -readonly headerCellClass?: Maybe; -``` +##### `headerCellClass?: Maybe` Class name(s) for the header cell. -##### `summaryCellClass?` - -```ts -readonly summaryCellClass?: Maybe Maybe)>; -``` +##### `summaryCellClass?: Maybe Maybe)>` Class name(s) for summary cells. Can be a string or a function that returns a class name based on the summary row. -##### `renderCell?` - -```ts -readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; -``` +##### `renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>` Render function to render the content of cells. -##### `renderHeaderCell?` - -```ts -readonly renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) => ReactNode>; -``` +##### `renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) => ReactNode>` Render function to render the content of the header cell. -##### `renderSummaryCell?` - -```ts -readonly renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>; -``` +##### `renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>` Render function to render the content of summary cells. -##### `renderGroupCell?` - -```ts -readonly renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>; -``` +##### `renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>` Render function to render the content of group cells when using `TreeDataGrid`. -##### `renderEditCell?` - -```ts -readonly renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>; -``` +##### `renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>` Render function to render the content of edit cells. When set, the column is automatically set to be editable. -##### `editable?` - -```ts -readonly editable?: Maybe boolean)>; -``` +##### `editable?: Maybe boolean)>` Control whether cells can be edited with `renderEditCell`. -##### `colSpan?` - -```ts -readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; -``` +##### `colSpan?: Maybe<(args: ColSpanArgs) => Maybe>` -Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. See the [`ColSpanArgs`](#colspanargs) type. +Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. See the [`ColSpanArgs`](#colspanargsr-sr) type. **Example:** @@ -1914,11 +1363,7 @@ const columns: readonly Column[] = [ ]; ``` -##### `frozen?` - -```ts -readonly frozen?: Maybe; -``` +##### `frozen?: Maybe` Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. See the [`ColumnFrozen`](#columnfrozen) type. @@ -1936,89 +1381,58 @@ const columns: readonly Column[] = [ **Default:** `false` -##### `resizable?` - -```ts -readonly resizable?: Maybe; -``` +##### `resizable?: Maybe` Enable resizing of the column. **Default:** `false` -##### `sortable?` - -```ts -readonly sortable?: Maybe; -``` +##### `sortable?: Maybe` Enable sorting of the column. **Default:** `false` -##### `draggable?` - -```ts -readonly draggable?: Maybe; -``` +##### `draggable?: Maybe` Enable dragging of the column. **Default:** `false` -##### `sortDescendingFirst?` - -```ts -readonly sortDescendingFirst?: Maybe; -``` +##### `sortDescendingFirst?: Maybe` Sets the column sort order to be descending instead of ascending the first time the column is sorted. **Default:** `false` -##### `editorOptions?` - -```ts -readonly editorOptions?: Maybe<{ - /** - * Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. - * By default, the cell content is not rendered when the edit cell is open. - * - * @defaultValue `false` - */ - readonly displayCellContent?: Maybe; - /** - * Commit changes when clicking outside the cell. - * - * @defaultValue `true` - */ - readonly commitOnOutsideClick?: Maybe; - /** - * Close the editor when the row value changes externally. - * - * @defaultValue `true` - */ - readonly closeOnExternalRowChange?: Maybe; - }>; -``` +##### `editorOptions` Options for cell editing. -#### `ColumnFrozen` +###### `displayCellContent?: Maybe` -Whether a column is frozen, and on which edge. +Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. +By default, the cell content is not rendered when the edit cell is open. -```ts -type ColumnFrozen = boolean | 'start' | 'end'; -``` +**Default:** `false` + +###### `commitOnOutsideClick?: Maybe` + +Commit changes when clicking outside the cell. + +**Default:** `true` + +###### `closeOnExternalRowChange?: Maybe` -**See also:** [`column.frozen`](#frozen) +Close the editor when the row value changes externally. + +**Default:** `true` -#### `ColumnGroup` +#### `ColumnGroup` Defines a group of columns that share a common header. -```ts +```tsx interface ColumnGroup { /** The name of the column group. It will be displayed in the header cell */ readonly name: string | ReactElement; @@ -2043,79 +1457,76 @@ const columns: readonly ColumnOrColumnGroup[] = [ ]; ``` -**See also:** [`ColumnOrColumnGroup`](#columnorcolumngroup) +**See also:** [`ColumnOrColumnGroup`](#columnorcolumngroupr-sr) -#### `ColumnOrColumnGroup` +#### `ColumnOrColumnGroup` Union type representing either a `Column` or a `ColumnGroup`. -```ts +```tsx type ColumnOrColumnGroup = Column | ColumnGroup; ``` -**See also:** [`columns`](#columns) prop on `` +**See also:** [`columns`](#columns-readonly-columnorcolumngroupr-sr) prop on `` -#### `ColumnWidth` +#### `CalculatedColumn` -Represents a single column's width. +Extends `Column` with additional computed properties used internally by the grid. This is the type passed to render functions. The `Column` properties it redeclares, like `width` and `renderCell`, are resolved to their default values when not set. -```ts -interface ColumnWidth { - /** `'resized'` if the user resized the column, or `'measured'` if the grid measured it */ - readonly type: 'resized' | 'measured'; - /** The width in pixels */ - readonly width: number; +```tsx +interface CalculatedColumn extends Column { + /** The column group that contains the column, or `undefined` if the column is not in a group */ + readonly parent: CalculatedColumnParent | undefined; + /** The index of the column in the grid. Column groups are flattened and frozen columns are moved to their edge, so it can differ from the column's index in `columns` */ + readonly idx: number; + /** Header row level, counted from the bottom header row: always `0` for columns, and negative for column groups */ + readonly level: number; + readonly width: number | string; + readonly minWidth: number; + readonly maxWidth: number | undefined; + readonly resizable: boolean; + readonly sortable: boolean; + readonly draggable: boolean; + readonly frozen: ColumnFrozen; + readonly renderCell: (props: RenderCellContentProps) => ReactNode; + readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; } ``` -**See also:** [`ColumnWidths`](#columnwidths-1) - -#### `ColumnWidths` - -A map of column widths. - -```ts -type ColumnWidths = ReadonlyMap; -``` - -**See also:** [`columnWidths`](#columnwidths) and [`onColumnWidthsChange`](#oncolumnwidthschange) props on `` +**See also:** [`Column`](#columnr-sr), [`onColumnResize`](#oncolumnresize-maybecolumn-calculatedcolumnr-sr-width-number--void) prop on `` -#### `DataGridHandle` +#### `CalculatedColumnParent` -Handle type assigned to a grid's `ref` for programmatic grid control. +Represents a parent column group in the calculated column structure. -```ts -interface DataGridHandle { - element: HTMLDivElement | null; - scrollToCell: (position: PartialPosition) => void; - setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +```tsx +interface CalculatedColumnParent { + readonly name: string | ReactElement; + readonly parent: CalculatedColumnParent | undefined; + readonly idx: number; + readonly colSpan: number; + readonly level: number; + readonly headerCellClass?: Maybe; } ``` -**Example:** - -```tsx -import { useRef } from 'react'; -import { DataGrid, type DataGridHandle } from 'react-data-grid'; +**See also:** [`CalculatedColumn`](#calculatedcolumnr-sr) -function MyGrid() { - const gridRef = useRef(null); +#### `CalculatedColumnOrColumnGroup` - function scrollToTop() { - gridRef.current?.scrollToCell({ rowIdx: 0 }); - } +Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. - return ; -} +```tsx +type CalculatedColumnOrColumnGroup = CalculatedColumnParent | CalculatedColumn; ``` -**See also:** [`ref`](#ref) prop on `` +**See also:** [`CalculatedColumn`](#calculatedcolumnr-sr), [`CalculatedColumnParent`](#calculatedcolumnparentr-sr) -#### `DefaultColumnOptions` +#### `DefaultColumnOptions` Default options applied to all columns. -```ts +```tsx type DefaultColumnOptions = Pick< Column, | 'renderCell' @@ -2129,60 +1540,23 @@ type DefaultColumnOptions = Pick< >; ``` -**See also:** [`defaultColumnOptions`](#defaultcolumnoptions) prop on `` - -#### `Direction` - -Text direction of the grid. - -```ts -type Direction = 'ltr' | 'rtl'; -``` - -**See also:** [`direction`](#direction) prop on `` - -#### `FillEvent` - -Event object for drag-fill operations. - -```ts -interface FillEvent { - columnKey: string; - sourceRow: R; - targetRow: R; -} -``` - -**See also:** [`onFill`](#onfill) prop on `` +**See also:** [`defaultColumnOptions`](#defaultcolumnoptions-maybedefaultcolumnoptionsr-sr) prop on `` -#### `PositionChangeArgs` +#### `ColumnFrozen` -Arguments passed to `onActivePositionChange`. +Whether a column is frozen, and on which edge. -```ts -interface PositionChangeArgs { - /** row index of the active position */ - rowIdx: number; - /** - * row object of the active position, - * undefined if the active position is on a header or summary row - */ - row: R | undefined; - /** - * column object of the active position, - * undefined if the active position is a row instead of a cell - */ - column: CalculatedColumn | undefined; -} +```tsx +type ColumnFrozen = boolean | 'start' | 'end'; ``` -**See also:** [`onActivePositionChange`](#onactivepositionchange) prop on `` +**See also:** [`column.frozen`](#frozen-maybecolumnfrozen) -#### `RenderCellContentProps` +#### `RenderCellContentProps` Props passed to custom cell content renderers (`column.renderCell`). -```ts +```tsx interface RenderCellContentProps { column: CalculatedColumn; row: R; @@ -2208,55 +1582,28 @@ function renderCell({ row, column, onRowChange }: RenderCellContentProps) } ``` -**See also:** [`column.renderCell`](#rendercell), [`renderValue`](#rendervalue) function +**See also:** [`column.renderCell`](#rendercell-maybeprops-rendercellcontentpropsr-sr--reactnode), [`renderValue`](#rendervaluer-srprops-rendercellcontentpropsr-sr) function -#### `RenderCellProps` +#### `RenderHeaderCellContentProps` -Props passed to the cell renderer when using `renderers.renderCell`. +Props passed to custom header cell content renderers (`column.renderHeaderCell`). -```ts -interface RenderCellProps extends BaseRenderCellProps { +```tsx +interface RenderHeaderCellContentProps { column: CalculatedColumn; - row: R; - colSpan: number | undefined; - isDraggedOver: boolean; - isCellActive: boolean; - onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; -} -``` - -**See also:** [`renderers.renderCell`](#renderers), [``](#cell-) - -#### `RenderCheckboxProps` - -Props for custom checkbox renderers. - -```ts -interface RenderCheckboxProps { - /** Whether the checkbox is checked */ - checked?: boolean | undefined; - /** Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected */ - indeterminate?: boolean | undefined; - /** Whether the checkbox is disabled */ - disabled?: boolean | undefined; - /** Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows */ - onChange: (checked: boolean, shift: boolean) => void; - /** `0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox */ - tabIndex?: number | undefined; - /** Accessible label for the checkbox */ - 'aria-label'?: string | undefined; - /** ID of the element that labels the checkbox */ - 'aria-labelledby'?: string | undefined; + sortDirection: SortDirection | undefined; + priority: number | undefined; + tabIndex: number; } ``` -**See also:** [`renderCheckbox`](#rendercheckbox) function, [`renderers.renderCheckbox`](#renderers), [``](#selectcheckbox-) +**See also:** [`column.renderHeaderCell`](#renderheadercell-maybeprops-renderheadercellcontentpropsr-sr--reactnode), [`renderHeaderCell`](#renderheadercellr-srprops-renderheadercellcontentpropsr-sr) function -#### `RenderEditCellContentProps` +#### `RenderEditCellContentProps` Props passed to custom editors (`column.renderEditCell`). -```ts +```tsx interface RenderEditCellContentProps { column: CalculatedColumn; row: R; @@ -2283,29 +1630,27 @@ function renderEditor({ row, column, onRowChange, onClose }: RenderEditCellConte } ``` -**See also:** [`column.renderEditCell`](#rendereditcell), [`renderTextEditor`](#rendertexteditor) function +**See also:** [`column.renderEditCell`](#rendereditcell-maybeprops-rendereditcellcontentpropsr-sr--reactnode), [`renderTextEditor`](#rendertexteditorr-srprops-rendereditcellcontentpropsr-sr) function -#### `Renderers` +#### `RenderSummaryCellContentProps` -Custom renderer configuration for the grid. +Props passed to summary cell content renderers (`column.renderSummaryCell`). -```ts -interface Renderers { - readonly renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; - readonly renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>; - readonly renderRow?: Maybe<(key: Key, props: RenderRowProps) => ReactNode>; - readonly renderSortStatus?: Maybe<(props: RenderSortStatusProps) => ReactNode>; - readonly noRowsFallback?: Maybe; +```tsx +interface RenderSummaryCellContentProps { + column: CalculatedColumn; + row: SR; + tabIndex: number; } ``` -**See also:** [`renderers`](#renderers) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) +**See also:** [`column.renderSummaryCell`](#rendersummarycell-maybeprops-rendersummarycellcontentpropssr-r--reactnode) -#### `RenderGroupCellContentProps` +#### `RenderGroupCellContentProps` Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. -```ts +```tsx interface RenderGroupCellContentProps { groupKey: unknown; column: CalculatedColumn; @@ -2317,28 +1662,13 @@ interface RenderGroupCellContentProps { } ``` -**See also:** [`column.renderGroupCell`](#rendergroupcell), [`renderToggleGroup`](#rendertogglegroup) function, [``](#togglegroup-) - -#### `RenderHeaderCellContentProps` - -Props passed to custom header cell content renderers (`column.renderHeaderCell`). - -```ts -interface RenderHeaderCellContentProps { - column: CalculatedColumn; - sortDirection: SortDirection | undefined; - priority: number | undefined; - tabIndex: number; -} -``` - -**See also:** [`column.renderHeaderCell`](#renderheadercell-1), [`renderHeaderCell`](#renderheadercell) function +**See also:** [`column.renderGroupCell`](#rendergroupcell-maybeprops-rendergroupcellcontentpropsr-sr--reactnode), [`renderToggleGroup`](#rendertogglegroupr-srprops-rendergroupcellcontentpropsr-sr) function, [``](#togglegroup-) -#### `RenderRowProps` +#### `RenderRowProps` Props passed to custom row renderers. -```ts +```tsx interface RenderRowProps extends BaseRenderRowProps { row: R; draggedOverCellIdx: number | undefined; @@ -2347,65 +1677,369 @@ interface RenderRowProps extends BaseRenderRowProps { rowClass: Maybe<(row: R, rowIdx: number) => Maybe>; isTreeGrid: boolean; } -``` -**See also:** [`renderers.renderRow`](#renderers), [``](#row-) +interface BaseRenderRowProps extends BaseRenderCellProps { + iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; + rowIdx: number; + activeCellIdx: number | undefined; + isRowSelectionDisabled: boolean; + isRowSelected: boolean; + gridRowStart: number; +} -#### `RenderSortIconProps` +interface BaseRenderCellProps + extends + Omit, 'children'>, + Pick< + DataGridProps, + 'onCellMouseDown' | 'onCellClick' | 'onCellDoubleClick' | 'onCellContextMenu' + > { + rowIdx: number; + setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +} -Props for custom sort icon renderers. +type IterateOverViewportColumnsForRow = ( + activeIdx: number | undefined, + args?: ColSpanArgs +) => IteratorObject>; -```ts -interface RenderSortIconProps { - /** The sort direction of the column, or `undefined` if it is not sorted */ - sortDirection: SortDirection | undefined; +type ViewportColumnWithColSpan = [ + column: CalculatedColumn, + isCellActive: boolean, + colSpan: number | undefined +]; + +interface EditCellProps extends Pick< + RenderCellProps, + 'column' | 'colSpan' | 'row' | 'rowIdx' +> { + onRowChange: (row: R, commitChanges: boolean, shouldFocus: boolean) => void; + closeEditor: (shouldFocus: boolean) => void; + navigate: (event: React.KeyboardEvent) => void; + onKeyDown: Maybe<(args: EditCellKeyDownArgs, event: CellKeyboardEvent) => void>; +} + +interface EditCellKeyDownArgs { + mode: 'EDIT'; + column: CalculatedColumn; + row: R; + rowIdx: number; + navigate: () => void; + onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; } ``` -**See also:** [`renderSortIcon`](#rendersorticon) function +**See also:** [`renderers.renderRow`](#renderers-mayberenderersr-sr), [``](#row-) -#### `RenderSortPriorityProps` +#### `RenderCellProps` -Props for custom sort priority renderers. +Props passed to the cell renderer when using `renderers.renderCell`. -```ts -interface RenderSortPriorityProps { - /** The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise */ - priority: number | undefined; +```tsx +interface RenderCellProps extends BaseRenderCellProps { + column: CalculatedColumn; + row: R; + colSpan: number | undefined; + isDraggedOver: boolean; + isCellActive: boolean; + onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; +} + +interface BaseRenderCellProps + extends + Omit, 'children'>, + Pick< + DataGridProps, + 'onCellMouseDown' | 'onCellClick' | 'onCellDoubleClick' | 'onCellContextMenu' + > { + rowIdx: number; + setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; } ``` -**See also:** [`renderSortPriority`](#rendersortpriority) function +**See also:** [`renderers.renderCell`](#renderers-mayberenderersr-sr), [``](#cell-) + +#### `RenderCheckboxProps` + +Props for custom checkbox renderers. + +```tsx +interface RenderCheckboxProps { + /** Whether the checkbox is checked */ + checked?: boolean | undefined; + /** Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected */ + indeterminate?: boolean | undefined; + /** Whether the checkbox is disabled */ + disabled?: boolean | undefined; + /** Called when the checkbox is toggled. `shift` is `true` if the Shift key was held, to select a range of rows */ + onChange: (checked: boolean, shift: boolean) => void; + /** `0` when the checkbox's cell is active and `-1` otherwise, so the grid can move focus from the cell to the checkbox */ + tabIndex?: number | undefined; + /** Accessible label for the checkbox */ + 'aria-label'?: string | undefined; + /** ID of the element that labels the checkbox */ + 'aria-labelledby'?: string | undefined; +} +``` + +**See also:** [`renderCheckbox`](#rendercheckboxprops-rendercheckboxprops) function, [`renderers.renderCheckbox`](#renderers-mayberenderersr-sr), [``](#selectcheckbox-) #### `RenderSortStatusProps` Props for custom sort status renderers. -```ts +```tsx interface RenderSortStatusProps extends RenderSortIconProps, RenderSortPriorityProps {} ``` -**See also:** [`renderers.renderSortStatus`](#renderers) +**See also:** [`renderers.renderSortStatus`](#renderers-mayberenderersr-sr) -#### `RenderSummaryCellContentProps` +#### `RenderSortIconProps` -Props passed to summary cell content renderers (`column.renderSummaryCell`). +Props for custom sort icon renderers. -```ts -interface RenderSummaryCellContentProps { +```tsx +interface RenderSortIconProps { + /** The sort direction of the column, or `undefined` if it is not sorted */ + sortDirection: SortDirection | undefined; +} +``` + +**See also:** [`renderSortIcon`](#rendersorticonprops-rendersorticonprops) function + +#### `RenderSortPriorityProps` + +Props for custom sort priority renderers. + +```tsx +interface RenderSortPriorityProps { + /** The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise */ + priority: number | undefined; +} +``` + +**See also:** [`renderSortPriority`](#rendersortpriorityprops-rendersortpriorityprops) function + +#### `Renderers` + +Custom renderer configuration for the grid. + +```tsx +interface Renderers { + readonly renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; + readonly renderCheckbox?: Maybe<(props: RenderCheckboxProps) => ReactNode>; + readonly renderRow?: Maybe<(key: Key, props: RenderRowProps) => ReactNode>; + readonly renderSortStatus?: Maybe<(props: RenderSortStatusProps) => ReactNode>; + readonly noRowsFallback?: Maybe; +} +``` + +**See also:** [`renderers`](#renderers-mayberenderersr-sr) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) + +#### `CellMouseArgs` + +Arguments passed to cell mouse event handlers. + +```tsx +interface CellMouseArgs { + /** The column object of the cell. */ column: CalculatedColumn; - row: SR; - tabIndex: number; + /** The row object of the cell. */ + row: R; + /** The row index of the cell. */ + rowIdx: number; + /** Function to manually focus the cell. Pass `true` to immediately start editing. */ + setActivePosition: (enableEditor?: boolean) => void; +} +``` + +**Example:** + +```tsx +import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; + +function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { + console.log('Clicked cell at row', args.rowIdx, 'column', args.column.key); + args.setActivePosition(true); // Focus and start editing +} +``` + +**See also:** [`onCellMouseDown`](#oncellmousedown-cellmouseeventhandlerr-sr), [`onCellClick`](#oncellclick-cellmouseeventhandlerr-sr), [`onCellDoubleClick`](#oncelldoubleclick-cellmouseeventhandlerr-sr), and [`onCellContextMenu`](#oncellcontextmenu-cellmouseeventhandlerr-sr) props on `` + +#### `CellMouseEvent` + +Extends `React.MouseEvent` with grid-specific methods. + +```tsx +type CellMouseEvent = CellEvent>; +``` + +**Example:** + +```tsx +import type { CellMouseArgs, CellMouseEvent } from 'react-data-grid'; + +function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { + if (args.column.key === 'actions') { + event.preventGridDefault(); // Prevent cell focus + } +} +``` + +**See also:** [`onCellMouseDown`](#oncellmousedown-cellmouseeventhandlerr-sr), [`onCellClick`](#oncellclick-cellmouseeventhandlerr-sr), [`onCellDoubleClick`](#oncelldoubleclick-cellmouseeventhandlerr-sr), and [`onCellContextMenu`](#oncellcontextmenu-cellmouseeventhandlerr-sr) props on `` + +#### `CellKeyDownArgs` + +Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. + +```tsx +type CellKeyDownArgs = ActiveCellKeyDownArgs | EditCellKeyDownArgs; + +interface ActiveCellKeyDownArgs { + mode: 'ACTIVE'; + /** + * column object of the active position, + * undefined if the active position is a row instead of a cell + */ + column: CalculatedColumn | undefined; + row: R; + rowIdx: number; + setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; +} + +interface EditCellKeyDownArgs { + mode: 'EDIT'; + column: CalculatedColumn; + row: R; + rowIdx: number; + navigate: () => void; + onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; +} +``` + +**Example:** + +```tsx +import type { CellKeyboardEvent, CellKeyDownArgs } from 'react-data-grid'; + +function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { + if (args.mode === 'EDIT' && event.key === 'Escape') { + args.onClose(false); // Close without committing + event.preventGridDefault(); + } +} +``` + +**See also:** [`onCellKeyDown`](#oncellkeydown-maybeargs-cellkeydownargsr-sr-event-cellkeyboardevent--void) prop on `` + +#### `CellKeyboardEvent` + +Extends `React.KeyboardEvent` with grid-specific methods. + +```tsx +type CellKeyboardEvent = CellEvent>; +``` + +**See also:** [`onCellKeyDown`](#oncellkeydown-maybeargs-cellkeydownargsr-sr-event-cellkeyboardevent--void) prop on `` + +#### `CellCopyArgs` + +Arguments passed to `onCellCopy`. + +```tsx +type CellCopyArgs = CellCopyPasteArgs; + +interface CellCopyPasteArgs { + column: CalculatedColumn; + row: R; +} +``` + +**See also:** [`onCellCopy`](#oncellcopy-maybeargs-cellcopyargsr-sr-event-cellclipboardevent--void) prop on `` + +#### `CellPasteArgs` + +Arguments passed to `onCellPaste`. + +```tsx +type CellPasteArgs = CellCopyPasteArgs; + +interface CellCopyPasteArgs { + column: CalculatedColumn; + row: R; } ``` -**See also:** [`column.renderSummaryCell`](#rendersummarycell) +**See also:** [`onCellPaste`](#oncellpaste-maybeargs-cellpasteargsr-sr-event-cellclipboardevent--r) prop on `` + +#### `PositionChangeArgs` + +Arguments passed to `onActivePositionChange`. + +```tsx +interface PositionChangeArgs { + /** row index of the active position */ + rowIdx: number; + /** + * row object of the active position, + * undefined if the active position is on a header or summary row + */ + row: R | undefined; + /** + * column object of the active position, + * undefined if the active position is a row instead of a cell + */ + column: CalculatedColumn | undefined; +} +``` + +**See also:** [`onActivePositionChange`](#onactivepositionchange-maybeargs-positionchangeargsr-sr--void) prop on `` + +#### `ColSpanArgs` + +Arguments passed to the `colSpan` function. + +```tsx +type ColSpanArgs = + | { + readonly type: 'HEADER'; + } + | { + readonly type: 'ROW'; + readonly row: R; + } + | { + readonly type: 'SUMMARY'; + readonly row: SR; + }; +``` + +**Example:** + +```tsx +import type { Column } from 'react-data-grid'; + +const columns: readonly Column[] = [ + { + key: 'title', + name: 'Title', + colSpan(args) { + if (args.type === 'ROW' && args.row.isFullWidth) { + return 3; // Span 3 columns + } + return undefined; + } + } +]; +``` -#### `RowHeightArgs` +**See also:** [`column.colSpan`](#colspan-maybeargs-colspanargsr-sr--maybenumber) + +#### `RowHeightArgs` Arguments passed to `TreeDataGrid`'s `rowHeight` prop when it is a function. -```ts +```tsx type RowHeightArgs = | { type: 'ROW'; @@ -2430,13 +2064,34 @@ function getRowHeight(args: RowHeightArgs): number { ``` -**See also:** [`rowHeight`](#rowheight-1) prop on `` +**See also:** [`rowHeight`](#rowheight-maybenumber--args-rowheightargsr--number) prop on `` + +#### `SortColumn` + +Describes a sorted column. + +```tsx +interface SortColumn { + readonly columnKey: string; + readonly direction: SortDirection; +} +``` -#### `RowsChangeData` +**See also:** [`sortColumns`](#sortcolumns-maybereadonly-sortcolumn) and [`onSortColumnsChange`](#onsortcolumnschange-maybesortcolumns-sortcolumn--void) props on `` + +#### `SortDirection` + +```tsx +type SortDirection = 'ASC' | 'DESC'; +``` + +**See also:** [`SortColumn`](#sortcolumn) + +#### `RowsChangeData` Data provided to the `onRowsChange` callback. -```ts +```tsx interface RowsChangeData { /** Indexes of the rows that changed */ indexes: number[]; @@ -2445,13 +2100,27 @@ interface RowsChangeData { } ``` -**See also:** [`onRowsChange`](#onrowschange) prop on `` +**See also:** [`onRowsChange`](#onrowschange-mayberows-r-data-rowschangedatar-sr--void) prop on `` + +#### `SelectRowEvent` + +Event object for row selection changes. + +```tsx +interface SelectRowEvent { + row: R; + checked: boolean; + isShiftClick: boolean; +} +``` + +**See also:** [`useRowSelection`](#userowselection) hook #### `SelectHeaderRowEvent` Event object for header row selection changes. -```ts +```tsx interface SelectHeaderRowEvent { checked: boolean; } @@ -2459,124 +2128,114 @@ interface SelectHeaderRowEvent { **See also:** [`useHeaderRowSelection`](#useheaderrowselection) hook -#### `SelectRowEvent` +#### `FillEvent` -Event object for row selection changes. +Event object for drag-fill operations. -```ts -interface SelectRowEvent { - row: R; - checked: boolean; - isShiftClick: boolean; +```tsx +interface FillEvent { + columnKey: string; + sourceRow: R; + targetRow: R; } ``` -**See also:** [`useRowSelection`](#userowselection) hook +**See also:** [`onFill`](#onfill-maybeevent-filleventr--r) prop on `` -#### `SetActivePositionOptions` +#### `DataGridHandle` -Options for programmatically updating the grid's active position. +Handle type assigned to a grid's `ref` for programmatic grid control. -```ts -interface SetActivePositionOptions { - enableEditor?: Maybe; - shouldFocus?: Maybe; +```tsx +interface DataGridHandle { + element: HTMLDivElement | null; + scrollToCell: (position: PartialPosition) => void; + setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; } ``` -**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) +**Example:** -#### `SortColumn` +```tsx +import { useRef } from 'react'; +import { DataGrid, type DataGridHandle } from 'react-data-grid'; -Describes a sorted column. +function MyGrid() { + const gridRef = useRef(null); -```ts -interface SortColumn { - readonly columnKey: string; - readonly direction: SortDirection; + function scrollToTop() { + gridRef.current?.scrollToCell({ rowIdx: 0 }); + } + + return ; } ``` -**See also:** [`sortColumns`](#sortcolumns) and [`onSortColumnsChange`](#onsortcolumnschange) props on `` +**See also:** [`ref`](#ref-maybereactrefdatagridhandle) prop on `` -#### `SortDirection` +#### `SetActivePositionOptions` -```ts -type SortDirection = 'ASC' | 'DESC'; +Options for programmatically updating the grid's active position. + +```tsx +interface SetActivePositionOptions { + enableEditor?: Maybe; + shouldFocus?: Maybe; +} ``` -**See also:** [`SortColumn`](#sortcolumn) +**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargsr-sr) -### Internal Types +#### `ColumnWidths` -#### `ActiveCellKeyDownArgs` +A map of column widths. -```ts -interface ActiveCellKeyDownArgs { - mode: 'ACTIVE'; - /** - * column object of the active position, - * undefined if the active position is a row instead of a cell - */ - column: CalculatedColumn | undefined; - row: R; - rowIdx: number; - setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -} +```tsx +type ColumnWidths = ReadonlyMap; ``` -#### `BaseRenderCellProps` +**See also:** [`columnWidths`](#columnwidths-maybecolumnwidths) and [`onColumnWidthsChange`](#oncolumnwidthschange-maybecolumnwidths-columnwidths--void) props on `` -```ts -interface BaseRenderCellProps - extends - Omit, 'children'>, - Pick< - DataGridProps, - 'onCellMouseDown' | 'onCellClick' | 'onCellDoubleClick' | 'onCellContextMenu' - > { - rowIdx: number; - setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -} -``` +#### `ColumnWidth` -#### `BaseRenderRowProps` +Represents a single column's width. -```ts -interface BaseRenderRowProps extends BaseRenderCellProps { - iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; - rowIdx: number; - activeCellIdx: number | undefined; - isRowSelectionDisabled: boolean; - isRowSelected: boolean; - gridRowStart: number; +```tsx +interface ColumnWidth { + /** `'resized'` if the user resized the column, or `'measured'` if the grid measured it */ + readonly type: 'resized' | 'measured'; + /** The width in pixels */ + readonly width: number; } ``` -#### `CellClipboardEvent` +**See also:** [`ColumnWidths`](#columnwidths) -Type alias for `React.ClipboardEvent`. Used for copy and paste events. This helper type is not exported; the shape is shown for reference. +#### `Direction` -```ts -type CellClipboardEvent = React.ClipboardEvent; +Text direction of the grid. + +```tsx +type Direction = 'ltr' | 'rtl'; ``` -**See also:** [`onCellCopy`](#oncellcopy) and [`onCellPaste`](#oncellpaste) props on `` +**See also:** [`direction`](#direction-maybedirection) prop on `` -#### `CellCopyPasteArgs` +#### `CellClipboardEvent` (internal) -```ts -interface CellCopyPasteArgs { - column: CalculatedColumn; - row: R; -} +Type alias for `React.ClipboardEvent`. Used for copy and paste events. This helper type is not exported; the shape is shown for reference. + +```tsx +type CellClipboardEvent = React.ClipboardEvent; ``` -#### `CellEvent` +**See also:** [`onCellCopy`](#oncellcopy-maybeargs-cellcopyargsr-sr-event-cellclipboardevent--void) and [`onCellPaste`](#oncellpaste-maybeargs-cellpasteargsr-sr-event-cellclipboardevent--r) props on `` + +#### `CellEvent` (internal) Adds grid-specific methods to a React event. This helper type is not exported; the shape is shown for reference. -```ts +```tsx type CellEvent> = E & { /** Prevents the default grid behavior for this event */ preventGridDefault: () => void; @@ -2587,54 +2246,21 @@ type CellEvent> = E & { **See also:** [`CellMouseEvent`](#cellmouseevent), [`CellKeyboardEvent`](#cellkeyboardevent) -#### `CellMouseEventHandler` +#### `CellMouseEventHandler` (internal) Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. -```ts +```tsx type CellMouseEventHandler = Maybe< (args: CellMouseArgs, event: CellMouseEvent) => void >; ``` -#### `DivProps` - -```ts -type DivProps = React.ComponentProps<'div'>; -``` - -#### `EditCellKeyDownArgs` - -```ts -interface EditCellKeyDownArgs { - mode: 'EDIT'; - column: CalculatedColumn; - row: R; - rowIdx: number; - navigate: () => void; - onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; -} -``` - -#### `EditCellProps` - -```ts -interface EditCellProps extends Pick< - RenderCellProps, - 'column' | 'colSpan' | 'row' | 'rowIdx' -> { - onRowChange: (row: R, commitChanges: boolean, shouldFocus: boolean) => void; - closeEditor: (shouldFocus: boolean) => void; - navigate: (event: React.KeyboardEvent) => void; - onKeyDown: Maybe<(args: EditCellKeyDownArgs, event: CellKeyboardEvent) => void>; -} -``` - -#### `GroupRow` +#### `GroupRow` (internal) Represents a group row in `TreeDataGrid`. This helper type is not exported; the shape is shown for reference. -```ts +```tsx interface GroupRow { readonly childRows: readonly R[]; readonly id: string; @@ -2648,36 +2274,21 @@ interface GroupRow { } ``` -**See also:** [`RenderGroupCellContentProps`](#rendergroupcellcontentprops), [`RowHeightArgs`](#rowheightargs), [``](#treedatagrid-) - -#### `IterateOverViewportColumnsForRow` - -```ts -type IterateOverViewportColumnsForRow = ( - activeIdx: number | undefined, - args?: ColSpanArgs -) => IteratorObject>; -``` +**See also:** [`RenderGroupCellContentProps`](#rendergroupcellcontentpropsr-sr), [`RowHeightArgs`](#rowheightargsr), [``](#treedatagrid-) -#### `Maybe` +#### `Maybe` (internal) Utility type for optional values. This helper type is not exported; the shape is shown for reference. -```ts +```tsx type Maybe = T | undefined | null; ``` -#### `Omit` - -```ts -type Omit = Pick>; -``` - -#### `PartialPosition` +#### `PartialPosition` (internal) Position for scrolling to a cell. Both fields are optional: omit `idx` to scroll to a row, or omit `rowIdx` to scroll to a column. This helper type is not exported; the shape is shown for reference. -```ts +```tsx interface PartialPosition { readonly idx?: Maybe; readonly rowIdx?: Maybe; @@ -2686,11 +2297,11 @@ interface PartialPosition { **See also:** [`DataGridHandle`](#datagridhandle) -#### `Position` +#### `Position` (internal) Represents a cell position in the grid. This helper type is not exported; the shape is shown for reference. -```ts +```tsx interface Position { /** Column index, or `-1` for the whole row in `TreeDataGrid` */ readonly idx: number; @@ -2699,37 +2310,15 @@ interface Position { } ``` -**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) - -#### `SelectCheckboxProps` - -```ts -interface SelectCheckboxProps extends SharedInputProps { - /** Whether the checkbox is checked */ - value: boolean; -} -``` - -#### `SharedInputProps` +**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargsr-sr) -```ts -type SharedInputProps = Pick< - RenderCheckboxProps, - 'disabled' | 'tabIndex' | 'aria-label' | 'aria-labelledby' | 'indeterminate' | 'onChange' ->; -``` - -#### `ViewportColumnWithColSpan` + -```ts -type ViewportColumnWithColSpan = [ - column: CalculatedColumn, - isCellActive: boolean, - colSpan: number | undefined -]; -``` +### Generics - +- `R`: Row type +- `SR`: Summary row type +- `K`: Row key type [ci-badge]: https://github.com/Comcast/react-data-grid/actions/workflows/ci.yml/badge.svg [ci-url]: https://github.com/Comcast/react-data-grid/actions/workflows/ci.yml diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index ec3e4ac981..da690d3041 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -3,9 +3,10 @@ import GithubSlugger from 'github-slugger'; import { parseSync } from 'oxc-parser'; // Generates the API reference of the README from the declarations and JSDoc comments of `lib/index.d.ts`, -// which `vp pack` bundles from the sources. +// which `vp pack` bundles from the sources. The items are listed in the order they are exported from `src/index.ts`. const declarationsPath = 'lib/index.d.ts'; +const entryPath = 'src/index.ts'; const readmePath = 'README.md'; const startMarker = ''; const endMarker = ''; @@ -19,7 +20,6 @@ interface Doc { interface Declaration { name: string; - // e.g. an interface, a type alias, a function, or a variable node: Node; doc: Doc; } @@ -29,13 +29,20 @@ interface Node { type: string; start: number; end: number; - id?: { name: string; typeAnnotation?: Node }; + id?: Node & { name: string }; + name?: string; optional?: boolean; key?: { type: string; name?: string; value?: string }; body?: { body: Node[] }; - params?: Node[]; + members?: Node[]; + params?: Node[] | { params: Node[] }; + typeParameters?: { params: { name: { name: string } }[] } | null; typeAnnotation?: Node; + typeArguments?: { params: Node[] } | null; declarations?: Node[]; + init?: Node | null; + types?: Node[]; + elementType?: Node; } const code = await readFile(declarationsPath, 'utf8'); @@ -46,6 +53,7 @@ const declarations = new Map(); const exportedNames = new Map(); for (const statement of program.body as unknown as Node[]) { + if (statement.type === 'ImportDeclaration') continue; if (statement.type === 'ExportNamedDeclaration') { const { declaration, specifiers } = statement as unknown as { declaration: Node | null; @@ -53,21 +61,19 @@ for (const statement of program.body as unknown as Node[]) { }; if (declaration === null) { for (const { local, exported } of specifiers) exportedNames.set(exported.name, local.name); - } else { - const name = getDeclarationName(declaration); - exportedNames.set(name, name); - declarations.set(name, { name, node: declaration, doc: parseDoc(getComment(statement)) }); + continue; } - } else if (statement.type !== 'ImportDeclaration') { - const name = getDeclarationName(statement); - declarations.set(name, { name, node: statement, doc: parseDoc(getComment(statement)) }); + exportedNames.set(getDeclarationName(declaration), getDeclarationName(declaration)); + addDeclaration(declaration, statement); + } else { + addDeclaration(statement, statement); } } -// group the exports by their `@group` tag, the remaining types are referenced by the exports +// group the exports by their `@group` tag, in the order they are exported from the entry point const groups = new Map(sections.map((section) => [section, []])); -for (const [name, declaredName] of exportedNames) { - const declaration = declarations.get(declaredName)!; +for (const name of await getExportOrder()) { + const declaration = declarations.get(exportedNames.get(name)!)!; const group = declaration.doc.tags.find((tag) => tag.name === 'group')?.text; const items = group === undefined ? undefined : groups.get(group); if (items === undefined) { @@ -76,16 +82,37 @@ for (const [name, declaredName] of exportedNames) { items.push({ ...declaration, name }); } +// the types that are referenced by the exports, but not exported: +// the documented ones are listed after the exported types, +// the other ones are shown with the types that reference them const exportedDeclarations = new Set(exportedNames.values()); const internalTypes = [...declarations.values()].filter( - ({ name, node }) => !exportedDeclarations.has(name) && isType(node) + // `Omit` works like the built-in `Omit` + ({ name, node }) => !exportedDeclarations.has(name) && isType(node) && name !== 'Omit' ); +const helperTypes = new Map( + internalTypes.filter(({ doc }) => doc.summary === '').map((type) => [type.name, type]) +); +groups + .get('Types')! + .push(...internalTypes.filter(({ name }) => !helperTypes.has(name)).toSorted(compareNames)); +// the key of each generated heading, to resolve the links to it +const headingKeys: (string | undefined)[] = []; const markdown: string[] = []; -for (const [section, items] of [...groups, ['Internal Types', internalTypes] as const]) { - markdown.push(`### ${section}`); - for (const item of items.toSorted(section === 'Components' ? compareComponents : compareNames)) { - markdown.push(renderItem(item, section === 'Components' && !isType(item.node))); + +for (const [section, items] of groups) { + markdown.push(heading(3, section)); + const propsInterfaces = new Map( + items.filter(({ node }) => isType(node)).map((item) => [item.name, item]) + ); + for (const item of items) { + if (section === 'Components' && isType(item.node)) continue; + // e.g. `DataGridProps` after `DataGrid` + const propsInterface = + section === 'Components' ? propsInterfaces.get(`${item.name}Props`) : undefined; + markdown.push(renderItem(item, section, propsInterface !== undefined)); + if (propsInterface !== undefined) markdown.push(renderType(propsInterface, 5)); } } @@ -100,53 +127,82 @@ if (startIndex === -1 || endIndex < startIndex) { await writeFile( readmePath, resolveLinks( - `${readme.slice(0, startIndex + startMarker.length)}\n\n${markdown.join('\n\n')}\n\n${readme.slice(endIndex)}` + readme.slice(0, startIndex + startMarker.length), + markdown.join('\n\n'), + readme.slice(endIndex) ) ); -function renderItem({ name, node, doc }: Declaration, isComponent: boolean) { - const md: string[] = []; +function renderItem(item: Declaration, section: string, hasPropsInterface: boolean) { + const { name, node, doc } = item; + if (isType(node)) return renderType(item, 4); - if (isComponent) { - md.push( - `#### \`<${name} />\``, - ...renderSummary(doc), - `**Props:** ${renderComponentProps(node)}` - ); - } else if (isType(node)) { - md.push(`#### \`${name}\``, ...renderSummary(doc)); - if (hasRichMembers(node)) { - // a heading per member, as their docs have examples, lists, or several paragraphs - md.push(codeBlock(`${source(node).slice(0, source(node).indexOf('{')).trim()} { … }`)); - } else { - md.push(codeBlock(source(node))); - } + const md: string[] = []; + if (section === 'Components') { + md.push(heading(4, `\`<${name} />\``, name), ...renderSummary(doc), ...renderTags(doc)); + // the props interface of a component is listed after it, e.g. `DataGridProps` after `DataGrid` + if (!hasPropsInterface) md.push(heading(5, 'Props'), renderComponentProps(node)); } else { - const isFunction = node.type === 'TSDeclareFunction' || node.type === 'FunctionDeclaration'; - md.push( - `#### \`${name}${isFunction ? '()' : ''}\``, - codeBlock(source(node)), - ...renderSummary(doc) - ); + let title = name; + if (node.type !== 'VariableDeclaration') { + title += getFunctionSignature(node); + } else if (section !== 'Context') { + title = getVariableSignature(name, node); + } + md.push(heading(4, `\`${title}\``, name), ...renderSummary(doc), ...renderTags(doc)); } + return md.join('\n\n'); +} - md.push(...renderTags(doc)); - - if (isType(node) && hasRichMembers(node)) { - for (const member of node.body!.body) { - const memberDoc = parseDoc(getComment(member)); - md.push( - `##### \`${getMemberName(member)}${member.optional === true ? '?' : ''}\``, - codeBlock(source(member)), - ...renderSummary(memberDoc), - ...renderTags(memberDoc) - ); - } +function renderType({ name, node, doc }: Declaration, level: number) { + const typeParameters = node.typeParameters?.params.map((param) => param.name.name); + // the props interfaces of the components are titled by their name, e.g. `DataGridProps` + const title = + level === 4 && typeParameters !== undefined ? `${name}<${typeParameters.join(', ')}>` : name; + const isInternal = !exportedDeclarations.has(name); + const md = [ + heading(level, level === 4 ? `\`${title}\`${isInternal ? ' (internal)' : ''}` : title, name), + ...renderSummary(doc) + ]; + + if (hasRichMembers(node)) { + // a heading per member, as their docs have examples, lists, or several paragraphs + md.push(...renderTags(doc), ...renderMembers(node.body!.body, level + 1, name)); + } else { + md.push(codeBlock(getTypeDeclarations(node)), ...renderTags(doc)); } return md.join('\n\n'); } +function renderMembers(members: Node[], level: number, parent: string): string[] { + return members.flatMap((member) => { + const name = getMemberName(member); + const doc = parseDoc(getComment(member)); + const typeLiteral = findTypeLiteral(member.typeAnnotation); + // e.g. `editorOptions`, which is an object, has a heading per option + if (typeLiteral !== undefined) { + return [ + heading(level, `\`${name}\``, `${parent}.${name}`), + ...renderSummary(doc), + ...renderTags(doc), + ...renderMembers(typeLiteral.members!, Math.min(level + 1, 6), `${parent}.${name}`) + ]; + } + const signature = cleanCode(source(member)) + .replace(/^readonly /, '') + .replace(/;$/, '') + .replaceAll(/\s+/g, ' ') + .replaceAll('< ', '<') + .replaceAll(' >', '>'); + return [ + heading(level, `\`${signature}\``, `${parent}.${name}`), + ...renderSummary(doc), + ...renderTags(doc) + ]; + }); +} + function renderSummary({ summary }: Doc) { return summary === '' ? [] : [convertLinks(summary)]; } @@ -163,29 +219,62 @@ function renderTags({ tags }: Doc) { .map(({ name, text }) => `${labels[name]}${convertLinks(text)}`); } -// e.g. "**Props:** [`DataGridProps`](#datagridprops)" +// e.g. "[`RenderRowProps`](#renderrowpropsr-sr)" function renderComponentProps(node: Node) { const signature = node.type === 'VariableDeclaration' ? node.declarations![0].id!.typeAnnotation!.typeAnnotation! : node; - const propsType = cleanCode(source(signature.params![0].typeAnnotation!.typeAnnotation!)); - return `[\`${propsType}\`](#!${/^\w+/.exec(propsType)![0]})`; + const propsType = cleanCode(source(getParams(signature)[0].typeAnnotation!.typeAnnotation!)); + const typeName = /^\w+/.exec(propsType)![0]; + return helperTypes.has(typeName) ? `\`${propsType}\`` : `[\`${propsType}\`](#!${typeName})`; } -function compareNames(a: Declaration, b: Declaration) { - return a.name.localeCompare(b.name); +// e.g. `(props: RenderHeaderCellContentProps)`, without the return type +function getFunctionSignature(node: Node) { + const typeParameters = node.typeParameters?.params.map((param) => param.name.name); + const params = getParams(node).map((param) => { + // destructured parameters are named `props` + const paramName = param.type === 'Identifier' ? param.name : 'props'; + return `${paramName}: ${cleanCode(source(param.typeAnnotation!.typeAnnotation!))}`; + }); + return `${typeParameters === undefined ? '' : `<${typeParameters.join(', ')}>`}(${params.join(', ')})`; +} + +// e.g. `SelectColumn: Column` or `SELECT_COLUMN_KEY = 'rdg-select-column'` +function getVariableSignature(name: string, node: Node) { + const declarator = node.declarations![0]; + if (declarator.init !== null && declarator.init !== undefined) { + return `${name} = ${source(declarator.init).replaceAll('"', "'")}`; + } + return `${name}: ${cleanCode(source(declarator.id!.typeAnnotation!.typeAnnotation!))}`; } -// the components with a props interface first, each followed by its props interface, -// e.g. `DataGrid` and `DataGridProps`, then the other components -function compareComponents(a: Declaration, b: Declaration) { - return getComponentSortKey(a).localeCompare(getComponentSortKey(b)); +function getParams(node: Node) { + const { params } = node; + return Array.isArray(params) ? params : params!.params; } -function getComponentSortKey({ name }: Declaration) { - const component = name.endsWith('Props') ? name.slice(0, -'Props'.length) : name; - return exportedNames.has(`${component}Props`) ? `0 ${component} ${name}` : `1 ${name}`; +// the declaration of a type, followed by the declarations of the helper types it references +function getTypeDeclarations(node: Node) { + const referenced = new Set(); + const visit = (text: string) => { + for (const [name] of text.matchAll(/\b\w+\b/g)) { + const helperType = helperTypes.get(name); + if (helperType !== undefined && !referenced.has(name) && helperType.node !== node) { + referenced.add(name); + visit(source(helperType.node)); + } + } + }; + visit(source(node)); + return [node, ...[...referenced].map((name) => helperTypes.get(name)!.node)] + .map(source) + .join('\n\n'); +} + +function compareNames(a: Declaration, b: Declaration) { + return a.name.localeCompare(b.name); } function isType(node: Node) { @@ -208,6 +297,27 @@ function hasRichMembers(node: Node) { ); } +// the object type of a member, e.g. `Maybe<{ … }>` +function findTypeLiteral(node: Node | undefined): Node | undefined { + if (node === undefined) return undefined; + if (node.type === 'TSTypeLiteral') return node; + for (const child of [ + node.typeAnnotation, + node.elementType, + ...(node.types ?? []), + ...(node.typeArguments?.params ?? []) + ]) { + const typeLiteral = findTypeLiteral(child); + if (typeLiteral !== undefined) return typeLiteral; + } + return undefined; +} + +function addDeclaration(node: Node, statement: Node) { + const name = getDeclarationName(node); + declarations.set(name, { name, node, doc: parseDoc(getComment(statement)) }); +} + function getDeclarationName(node: Node) { return node.id?.name ?? node.declarations![0].id!.name; } @@ -216,6 +326,24 @@ function getMemberName({ key }: Node) { return key!.type === 'Identifier' ? key!.name! : key!.value!; } +// the exported names of the entry point, in order +async function getExportOrder() { + const entry = await readFile(entryPath, 'utf8'); + const names = (parseSync(entryPath, entry).program.body as unknown as Node[]).flatMap( + (statement) => + statement.type === 'ExportNamedDeclaration' + ? (statement as unknown as { specifiers: { exported: { name: string } }[] }).specifiers.map( + ({ exported }) => exported.name + ) + : [] + ); + for (const name of exportedNames.keys()) { + if (!names.includes(name)) + throw new Error(`${name} must be exported by name from ${entryPath}`); + } + return names; +} + // the JSDoc comment directly before the node function getComment({ start }: Node) { const comment = comments.findLast( @@ -257,15 +385,21 @@ function source({ start, end }: Node) { return code.slice(start, end); } +function heading(level: number, text: string, key?: string) { + headingKeys.push(key); + return `${'#'.repeat(level)} ${text}`; +} + function codeBlock(text: string) { - return `\`\`\`ts\n${cleanCode(text)}\n\`\`\``; + return `\`\`\`tsx\n${cleanCode(text)}\n\`\`\``; } // show the declarations without the `declare` keyword, link tags, and `NoInfer`, // which only affects type inference function cleanCode(text: string) { return text - .replace(/^(?:export )?declare /, '') + .replaceAll(/^(?:export )?declare /gm, '') + .replaceAll('import("react").', 'React.') .replaceAll( /\{@link(?:code)? ([^}|]+?)(?: \| ([^}]+))?\}/g, (_, target: string, label: string | undefined) => label ?? target @@ -285,39 +419,35 @@ function convertLinks(text: string) { // with the anchors GitHub generates for their headings, which are numbered across the whole README. // Links in the hand-written sections of the README can link to an item or member with its name as // the link title, e.g. `[width](#width "Column.width")`, to update the anchor when the numbering changes. -function resolveLinks(markdown: string) { +function resolveLinks(precedingMarkdown: string, api: string, followingMarkdown: string) { const slugger = new GithubSlugger(); const anchors = new Map(); - let item: string | undefined; - - forEachLine(markdown, (line, isInCodeBlock) => { - const heading = isInCodeBlock ? null : /^(#{1,6}) (.+)$/.exec(line); - if (heading === null) return; - - const text = heading[2].replaceAll('`', ''); - const anchor = slugger.slug(text); - // e.g. `DataGrid` for ``, `renderCheckbox` for `renderCheckbox()` - const name = text.replace(/^<(.+) \/>$/, '$1').replace(/(?:\(\)|\?)$/, ''); - if (heading[1].length === 4) { - item = name; - anchors.set(name, anchor); - } else if (heading[1].length === 5 && item !== undefined) { - anchors.set(`${item}.${name}`, anchor); - } - }); + const slugHeadings = (markdown: string, keys?: (string | undefined)[]) => { + forEachLine(markdown, (line, isInCodeBlock) => { + const match = isInCodeBlock ? null : /^#{1,6} (.+)$/.exec(line); + if (match === null) return; + const anchor = slugger.slug(match[1].replaceAll('`', '')); + const key = keys?.shift(); + if (key !== undefined) anchors.set(key, anchor); + }); + }; + + slugHeadings(precedingMarkdown); + slugHeadings(api, [...headingKeys]); + slugHeadings(followingMarkdown); const getAnchor = (target: string) => { - // members listed in the code block of their type link to the type + // the members of types shown as a code block link to their type const anchor = anchors.get(target) ?? anchors.get(target.split('.')[0]); if (anchor === undefined) throw new Error(`The link to ${target} does not match any heading`); return anchor; }; - return markdown + return `${precedingMarkdown}\n\n${api}\n\n${followingMarkdown}` .replaceAll(/\]\(#!([\w.]+)\)/g, (_, target: string) => `](#${getAnchor(target)})`) .replaceAll( - /\]\(#[^ )]+ "([\w.]+)"\)/g, - (_, target: string) => `](#${getAnchor(target)} "${target}")` + /\]\(#[^ )]+ (["'])([\w.]+)\1\)/g, + (_, quote: string, target: string) => `](#${getAnchor(target)} ${quote}${target}${quote})` ); } diff --git a/src/DataGrid.tsx b/src/DataGrid.tsx index ff4ebb8d3c..83bcca78c5 100644 --- a/src/DataGrid.tsx +++ b/src/DataGrid.tsx @@ -128,8 +128,6 @@ export interface DataGridHandle { setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; } -type DivProps = React.ComponentProps<'div'>; - /** * @typeParam R - Row type * @typeParam SR - Summary row type @@ -547,7 +545,7 @@ export interface DataGridProps { /** * Native DOM `onScroll` prop. */ - onScroll?: DivProps['onScroll']; + onScroll?: React.UIEventHandler | undefined; /** * Toggles and modes @@ -665,35 +663,35 @@ export interface DataGridProps { /** * Custom class name for the grid. */ - className?: DivProps['className']; + className?: string | undefined; /** * Custom styles for the grid. */ - style?: DivProps['style']; + style?: React.CSSProperties | undefined; /** * ARIA role for the grid container. Defaults to `grid`. */ - role?: DivProps['role']; + role?: React.AriaRole | undefined; /** * The label of the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. */ - 'aria-label'?: DivProps['aria-label']; + 'aria-label'?: string | undefined; /** * The id of the element containing a label for the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. */ - 'aria-labelledby'?: DivProps['aria-labelledby']; + 'aria-labelledby'?: string | undefined; /** * Total number of rows for assistive technologies. */ - 'aria-rowcount'?: DivProps['aria-rowcount']; + 'aria-rowcount'?: number | undefined; /** * A human-readable description of the grid. */ - 'aria-description'?: DivProps['aria-description']; + 'aria-description'?: string | undefined; /** * If the grid has a caption or description, `aria-describedby` can be set on the grid element with a value referring to the element containing the description. */ - 'aria-describedby'?: DivProps['aria-describedby']; + 'aria-describedby'?: string | undefined; /** * This prop can be used to add a test ID for testing. We recommend querying the grid by its `role` and `name`. * diff --git a/src/index.ts b/src/index.ts index 6b999c11b0..592db3a749 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,58 +1,57 @@ import './style/layers.css'; -export { - DataGrid, - type DataGridHandle, - type DataGridProps, - type DefaultColumnOptions -} from './DataGrid'; +// the order of the exports is the order of the API reference in the README + +export { DataGrid, type DataGridProps } from './DataGrid'; export { TreeDataGrid, type TreeDataGridProps } from './TreeDataGrid'; -export { DataGridRenderersContext } from './DataGridRenderersContext'; export { Row } from './Row'; export { Cell } from './Cell'; -export * from './Columns'; -export * from './cellRenderers'; -export { renderTextEditor } from './editors/renderTextEditor'; +export { SelectCheckbox, ToggleGroup } from './cellRenderers'; +export { useHeaderRowSelection, useRowSelection } from './hooks'; export { renderHeaderCell } from './renderHeaderCell'; +export { renderTextEditor } from './editors/renderTextEditor'; export { renderSortIcon, renderSortPriority } from './sortStatus'; -export { useHeaderRowSelection, useRowSelection } from './hooks'; +export { renderCheckbox, renderToggleGroup, renderValue } from './cellRenderers'; +export { DataGridRenderersContext } from './DataGridRenderersContext'; +export { SelectColumn, SELECT_COLUMN_KEY } from './Columns'; export type { - CalculatedColumn, - CalculatedColumnOrColumnGroup, - CalculatedColumnParent, - CellCopyArgs, - CellKeyboardEvent, - CellKeyDownArgs, - CellMouseArgs, - CellMouseEvent, - CellPasteArgs, - ColSpanArgs, Column, - ColumnFrozen, ColumnGroup, ColumnOrColumnGroup, - ColumnWidth, - ColumnWidths, - Direction, - FillEvent, - PositionChangeArgs, + CalculatedColumn, + CalculatedColumnParent, + CalculatedColumnOrColumnGroup +} from './types'; +export type { DefaultColumnOptions } from './DataGrid'; +export type { + ColumnFrozen, RenderCellContentProps, - RenderCellProps, - RenderCheckboxProps, + RenderHeaderCellContentProps, RenderEditCellContentProps, - Renderers, + RenderSummaryCellContentProps, RenderGroupCellContentProps, - RenderHeaderCellContentProps, RenderRowProps, + RenderCellProps, + RenderCheckboxProps, + RenderSortStatusProps, RenderSortIconProps, RenderSortPriorityProps, - RenderSortStatusProps, - RenderSummaryCellContentProps, + Renderers, + CellMouseArgs, + CellMouseEvent, + CellKeyDownArgs, + CellKeyboardEvent, + CellCopyArgs, + CellPasteArgs, + PositionChangeArgs, + ColSpanArgs, RowHeightArgs, + SortColumn, + SortDirection, RowsChangeData, - SelectHeaderRowEvent, SelectRowEvent, - SetActivePositionOptions, - SortColumn, - SortDirection + SelectHeaderRowEvent, + FillEvent } from './types'; +export type { DataGridHandle } from './DataGrid'; +export type { SetActivePositionOptions, ColumnWidths, ColumnWidth, Direction } from './types'; From bb3ba0b2a363129573605ef07f803b3e68042445 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 17:52:14 -0500 Subject: [PATCH 11/22] Use name-only headings in the API reference - Title the items and members with their name, and show their signature in a code block, so their anchors don't change with their types - Show `DataGridRenderersContext` like the other constants - Only show the helper types directly referenced by a type Co-Authored-By: Claude Opus 5.5 --- README.md | 753 ++++++++++++++++++++++++++----------- scripts/generateApiDocs.ts | 81 ++-- 2 files changed, 573 insertions(+), 261 deletions(-) diff --git a/README.md b/README.md index 9f8693eae1..686cd33d2c 100644 --- a/README.md +++ b/README.md @@ -198,7 +198,7 @@ Example of customizing colors: ### Standard Props -The DataGrid accepts standard [`className`](#classname-string--undefined 'DataGridProps.className') and [`style`](#style-reactcssproperties--undefined 'DataGridProps.style') props: +The DataGrid accepts standard [`className`](#classname 'DataGridProps.className') and [`style`](#style 'DataGridProps.style') props: ```tsx >` +###### `ref?` + +```tsx +ref?: Maybe>; +``` Optional ref for imperative APIs like scrolling to or focusing a cell. See [`DataGridHandle`](#datagridhandle). -###### `columns: readonly ColumnOrColumnGroup[]` +###### `columns` + +```tsx +columns: readonly ColumnOrColumnGroup[]; +``` -An array of column definitions and/or column groups. See the [`ColumnOrColumnGroup`](#columnorcolumngroupr-sr) type for all available options. +An array of column definitions and/or column groups. See the [`ColumnOrColumnGroup`](#columnorcolumngroup) type for all available options. ⚠️ **Performance:** Passing a new `columns` array will trigger a re-render and recalculation for the entire grid. Always memoize this prop using `useMemo` or define it outside the component to avoid unnecessary re-renders. -###### `rows: readonly R[]` +###### `rows` + +```tsx +rows: readonly R[]; +``` An array of rows. The row data can be of any type. @@ -278,19 +290,31 @@ An array of rows. The row data can be of any type. setRows(rows.map((row) => ({ ...row }))); ``` -###### `topSummaryRows?: Maybe` +###### `topSummaryRows?` + +```tsx +topSummaryRows?: Maybe; +``` Rows pinned at the top of the grid for summary purposes. ⚠️ **Performance:** Memoize this array to prevent internal memoization invalidation. -###### `bottomSummaryRows?: Maybe` +###### `bottomSummaryRows?` + +```tsx +bottomSummaryRows?: Maybe; +``` Rows pinned at the bottom of the grid for summary purposes. ⚠️ **Performance:** Memoize this array to prevent internal memoization invalidation. -###### `rowKeyGetter?: Maybe<(row: R) => K>` +###### `rowKeyGetter?` + +```tsx +rowKeyGetter?: Maybe<(row: R) => K>; +``` Function to return a unique key/identifier for each row. `rowKeyGetter` is required for row selection to work. @@ -315,12 +339,16 @@ function MyGrid() { ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. -###### `onRowsChange?: Maybe<(rows: R[], data: RowsChangeData) => void>` +###### `onRowsChange?` + +```tsx +onRowsChange?: Maybe<(rows: R[], data: RowsChangeData) => void>; +``` Callback triggered when rows are changed. The first parameter is a new rows array with both the updated rows and the other untouched rows. -The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. See the [`RowsChangeData`](#rowschangedatar-sr) type. +The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. See the [`RowsChangeData`](#rowschangedata) type. ```tsx import { useState } from 'react'; @@ -333,7 +361,11 @@ function MyGrid() { } ``` -###### `rowHeight?: Maybe number)>` +###### `rowHeight?` + +```tsx +rowHeight?: Maybe number)>; +``` Height of each row in pixels. A function can be used to set different row heights. @@ -353,13 +385,21 @@ function getRowHeight(row) { **Default:** `35` pixels -###### `headerRowHeight?: Maybe` +###### `headerRowHeight?` + +```tsx +headerRowHeight?: Maybe; +``` Height of the header row in pixels. **Default:** `rowHeight` when it is a number, otherwise `35` pixels -###### `summaryRowHeight?: Maybe` +###### `summaryRowHeight?` + +```tsx +summaryRowHeight?: Maybe; +``` Height of each summary row in pixels. @@ -376,9 +416,13 @@ Height of each summary row in pixels. **Default:** `rowHeight` when it is a number, otherwise `35` pixels -###### `columnWidths?: Maybe` +###### `columnWidths?` + +```tsx +columnWidths?: Maybe; +``` -A map of column widths containing both measured and resized widths. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths) type. +A map of column widths containing both measured and resized widths. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths-1) type. ```tsx const [columnWidths, setColumnWidths] = useState((): ColumnWidths => new Map()); @@ -392,19 +436,35 @@ function addNewRow() { return ``` -###### `onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>` +###### `onColumnWidthsChange?` -Callback triggered when column widths change. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths) type. +```tsx +onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; +``` -###### `selectedRows?: Maybe>` +Callback triggered when column widths change. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths-1) type. + +###### `selectedRows?` + +```tsx +selectedRows?: Maybe>; +``` A set of selected row keys. `rowKeyGetter` is required for row selection to work. -###### `isRowSelectionDisabled?: Maybe<(row: R) => boolean>` +###### `isRowSelectionDisabled?` + +```tsx +isRowSelectionDisabled?: Maybe<(row: R) => boolean>; +``` Function to determine if row selection is disabled for a specific row. -###### `onSelectedRowsChange?: Maybe<(selectedRows: Set) => void>` +###### `onSelectedRowsChange?` + +```tsx +onSelectedRowsChange?: Maybe<(selectedRows: Set) => void>; +``` Callback triggered when the selection changes. @@ -443,13 +503,21 @@ function MyGrid() { } ``` -###### `sortColumns?: Maybe` +###### `sortColumns?` + +```tsx +sortColumns?: Maybe; +``` An array of sorted columns. See the [`SortColumn`](#sortcolumn) type. Sorting is controlled: the grid does not reorder `rows` for you. Apply the sorting to your `rows` state (or derived rows) based on `sortColumns`. -###### `onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>` +###### `onSortColumnsChange?` + +```tsx +onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>; +``` Callback triggered when sorting changes. @@ -490,9 +558,13 @@ function onSortColumnsChange(sortColumns: SortColumn[]) { } ``` -###### `defaultColumnOptions?: Maybe>` +###### `defaultColumnOptions?` -Default options applied to all columns. See the [`DefaultColumnOptions`](#defaultcolumnoptionsr-sr) type. +```tsx +defaultColumnOptions?: Maybe>; +``` + +Default options applied to all columns. See the [`DefaultColumnOptions`](#defaultcolumnoptions-1) type. ```tsx function MyGrid() { @@ -511,9 +583,13 @@ function MyGrid() { } ``` -###### `onCellMouseDown?: CellMouseEventHandler` +###### `onCellMouseDown?` + +```tsx +onCellMouseDown?: CellMouseEventHandler; +``` -Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargsr-sr) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. ```tsx function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { @@ -525,9 +601,13 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellClick?: CellMouseEventHandler` +###### `onCellClick?` + +```tsx +onCellClick?: CellMouseEventHandler; +``` -Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargsr-sr) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. This event can be used to open the cell editor on a single click: @@ -541,9 +621,13 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellDoubleClick?: CellMouseEventHandler` +###### `onCellDoubleClick?` -Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargsr-sr) and [`CellMouseEvent`](#cellmouseevent) types. +```tsx +onCellDoubleClick?: CellMouseEventHandler; +``` + +Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. ```tsx function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { @@ -555,9 +639,13 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellContextMenu?: CellMouseEventHandler` +###### `onCellContextMenu?` + +```tsx +onCellContextMenu?: CellMouseEventHandler; +``` -Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargsr-sr) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. ```tsx function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { @@ -570,9 +658,13 @@ function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellKeyDown?: Maybe<(args: CellKeyDownArgs, event: CellKeyboardEvent) => void>` +###### `onCellKeyDown?` + +```tsx +onCellKeyDown?: Maybe<(args: CellKeyDownArgs, event: CellKeyboardEvent) => void>; +``` -Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. See the [`CellKeyDownArgs`](#cellkeydownargsr-sr) and [`CellKeyboardEvent`](#cellkeyboardevent) types. +Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. See the [`CellKeyDownArgs`](#cellkeydownargs) and [`CellKeyboardEvent`](#cellkeyboardevent) types. **Examples** @@ -598,33 +690,57 @@ function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website/routes/CellNavigation.tsx). -###### `onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => void>` +###### `onCellCopy?` -Callback triggered when a cell's content is copied. See the [`CellCopyArgs`](#cellcopyargsr-sr) type. +```tsx +onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => void>; +``` -###### `onCellPaste?: Maybe<(args: CellPasteArgs, event: CellClipboardEvent) => R>` +Callback triggered when a cell's content is copied. See the [`CellCopyArgs`](#cellcopyargs) type. -Callback triggered when content is pasted into a cell. See the [`CellPasteArgs`](#cellpasteargsr-sr) type. +###### `onCellPaste?` + +```tsx +onCellPaste?: Maybe<(args: CellPasteArgs, event: CellClipboardEvent) => R>; +``` + +Callback triggered when content is pasted into a cell. See the [`CellPasteArgs`](#cellpasteargs) type. Return the updated row; the grid will call `onRowsChange` with it. -###### `onActivePositionChange?: Maybe<(args: PositionChangeArgs) => void>` +###### `onActivePositionChange?` + +```tsx +onActivePositionChange?: Maybe<(args: PositionChangeArgs) => void>; +``` -Callback triggered when the active position changes. See the [`PositionChangeArgs`](#positionchangeargsr-sr) type. +Callback triggered when the active position changes. See the [`PositionChangeArgs`](#positionchangeargs) type. + +###### `onColumnResize?` + +```tsx +onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void>; +``` -###### `onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void>` +Callback triggered when a column is resized. The `column` parameter is the full [`CalculatedColumn`](#calculatedcolumn) object, and `width` is the new width in pixels. -Callback triggered when a column is resized. The `column` parameter is the full [`CalculatedColumn`](#calculatedcolumnr-sr) object, and `width` is the new width in pixels. +###### `onColumnsReorder?` -###### `onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>` +```tsx +onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>; +``` Callback triggered when columns are reordered. The parameters are the `key` values of the source and target columns. -###### `onFill?: Maybe<(event: FillEvent) => R>` +###### `onFill?` + +```tsx +onFill?: Maybe<(event: FillEvent) => R>; +``` Callback triggered when the value of the active cell is dragged to fill other cells. When this prop is set, a drag handle is shown on the active cell if it is editable. Drag the handle up or down to fill the cells it passes over, or double-click it to fill all the cells below. -The grid calls `onFill` for each editable target cell. Return the updated target row; the grid will call `onRowsChange` with the updated rows. See the [`FillEvent`](#filleventr) type. +The grid calls `onFill` for each editable target cell. Return the updated target row; the grid will call `onRowsChange` with the updated rows. See the [`FillEvent`](#fillevent) type. ```tsx function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { @@ -634,21 +750,33 @@ function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { ; ``` -###### `onScroll?: React.UIEventHandler | undefined` +###### `onScroll?` + +```tsx +onScroll?: React.UIEventHandler | undefined; +``` Native DOM `onScroll` prop. -###### `enableVirtualization?: Maybe` +###### `enableVirtualization?` + +```tsx +enableVirtualization?: Maybe; +``` This prop can be used to disable virtualization. **Default:** `true` -###### `renderers?: Maybe>` +###### `renderers?` + +```tsx +renderers?: Maybe>; +``` Custom renderers for cells, rows, and other components. -See the [`Renderers`](#renderersr-sr) type for the full shape. +See the [`Renderers`](#renderers-1) type for the full shape. Example of replacing default components: @@ -705,7 +833,11 @@ function MyGrid() { } ``` -###### `rowClass?: Maybe<(row: R, rowIdx: number) => Maybe>` +###### `rowClass?` + +```tsx +rowClass?: Maybe<(row: R, rowIdx: number) => Maybe>; +``` Function to apply custom class names to rows. @@ -723,7 +855,11 @@ function MyGrid() { ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. -###### `headerRowClass?: Maybe` +###### `headerRowClass?` + +```tsx +headerRowClass?: Maybe; +``` Custom class name for the header row. @@ -731,9 +867,13 @@ Custom class name for the header row. ``` -###### `direction?: Maybe` +###### `direction?` + +```tsx +direction?: Maybe; +``` -This property sets the text direction of the grid. It defaults to `'ltr'` (left-to-right). See the [`Direction`](#direction) type. +This property sets the text direction of the grid. It defaults to `'ltr'` (left-to-right). See the [`Direction`](#direction-1) type. Setting `direction` to `'rtl'` has the following effects: @@ -744,39 +884,75 @@ Setting `direction` to `'rtl'` has the following effects: **Default:** `'ltr'` -###### `className?: string | undefined` +###### `className?` + +```tsx +className?: string | undefined; +``` Custom class name for the grid. -###### `style?: React.CSSProperties | undefined` +###### `style?` + +```tsx +style?: React.CSSProperties | undefined; +``` Custom styles for the grid. -###### `role?: React.AriaRole | undefined` +###### `role?` + +```tsx +role?: React.AriaRole | undefined; +``` ARIA role for the grid container. Defaults to `grid`. -###### `'aria-label'?: string | undefined` +###### `aria-label?` + +```tsx +'aria-label'?: string | undefined; +``` The label of the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. -###### `'aria-labelledby'?: string | undefined` +###### `aria-labelledby?` + +```tsx +'aria-labelledby'?: string | undefined; +``` The id of the element containing a label for the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. -###### `'aria-rowcount'?: number | undefined` +###### `aria-rowcount?` + +```tsx +'aria-rowcount'?: number | undefined; +``` Total number of rows for assistive technologies. -###### `'aria-description'?: string | undefined` +###### `aria-description?` + +```tsx +'aria-description'?: string | undefined; +``` A human-readable description of the grid. -###### `'aria-describedby'?: string | undefined` +###### `aria-describedby?` + +```tsx +'aria-describedby'?: string | undefined; +``` If the grid has a caption or description, `aria-describedby` can be set on the grid element with a value referring to the element containing the description. -###### `'data-testid'?: Maybe` +###### `data-testid?` + +```tsx +'data-testid'?: Maybe; +``` This prop can be used to add a test ID for testing. We recommend querying the grid by its `role` and `name`. @@ -791,7 +967,11 @@ test('grid', async () => { }); ``` -###### `'data-cy'?: Maybe` +###### `data-cy?` + +```tsx +'data-cy'?: Maybe; +``` Optional attribute to help with Cypress (or similar) selectors. @@ -830,13 +1010,21 @@ The following `DataGrid` props are not supported in `TreeDataGrid`: ##### TreeDataGridProps -All [`DataGridProps`](#datagridprops) are supported except those listed above. The `columns` prop only supports `Column[]` (no column groups). When `rowHeight` is a function, it receives [`RowHeightArgs`](#rowheightargsr) instead of just the row. Additional props are listed below: +All [`DataGridProps`](#datagridprops) are supported except those listed above. The `columns` prop only supports `Column[]` (no column groups). When `rowHeight` is a function, it receives [`RowHeightArgs`](#rowheightargs) instead of just the row. Additional props are listed below: + +###### `columns` -###### `columns: readonly Column[]` +```tsx +columns: readonly Column[]; +``` + +###### `rowHeight?` -###### `rowHeight?: Maybe) => number)>` +```tsx +rowHeight?: Maybe) => number)>; +``` -**Note:** Unlike `DataGrid`, the `rowHeight` function receives [`RowHeightArgs`](#rowheightargsr), which includes a `type` property to distinguish between regular rows and group rows: +**Note:** Unlike `DataGrid`, the `rowHeight` function receives [`RowHeightArgs`](#rowheightargs), which includes a `type` property to distinguish between regular rows and group rows: ```tsx function getRowHeight(args: RowHeightArgs): number { @@ -849,7 +1037,11 @@ function getRowHeight(args: RowHeightArgs): number { ``` -###### `groupBy: readonly string[]` +###### `groupBy` + +```tsx +groupBy: readonly string[]; +``` **Required.** An array of column keys to group by. The order determines the grouping hierarchy (first key is the top level, second key is nested under the first, etc.). @@ -881,7 +1073,11 @@ function MyGrid() { } ``` -###### `rowGrouper: (rows: readonly R[], columnKey: string) => Record` +###### `rowGrouper` + +```tsx +rowGrouper: (rows: readonly R[], columnKey: string) => Record; +``` **Required.** A function that groups rows by the specified column key. Returns an object where keys are the group values and values are arrays of rows belonging to that group. @@ -893,7 +1089,11 @@ function rowGrouper(rows: readonly Row[], columnKey: string): Record` +###### `expandedGroupIds` + +```tsx +expandedGroupIds: ReadonlySet; +``` **Required.** A set of group IDs that are currently expanded. Group IDs are generated by `groupIdGetter`. @@ -914,11 +1114,19 @@ function MyGrid() { } ``` -###### `onExpandedGroupIdsChange: (expandedGroupIds: Set) => void` +###### `onExpandedGroupIdsChange` + +```tsx +onExpandedGroupIdsChange: (expandedGroupIds: Set) => void; +``` **Required.** Callback triggered when groups are expanded or collapsed. -###### `groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>` +###### `groupIdGetter?` + +```tsx +groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>; +``` Function to generate unique IDs for group rows. If not provided, a default implementation is used that concatenates parent and group keys with `__`. @@ -930,7 +1138,7 @@ The default row component. Can be wrapped via the `renderers.renderRow` prop. ##### Props -[`RenderRowProps`](#renderrowpropsr-sr) +[`RenderRowProps`](#renderrowprops) #### `` @@ -938,7 +1146,7 @@ The default cell component. Can be wrapped via the `renderers.renderCell` prop. ##### Props -[`RenderCellProps`](#rendercellpropsr-sr) +[`RenderCellProps`](#rendercellprops) #### `` @@ -956,12 +1164,20 @@ Low-level component used by `renderToggleGroup` to render the expand/collapse co ##### Props -[`RenderGroupCellContentProps`](#rendergroupcellcontentpropsr-sr) +[`RenderGroupCellContentProps`](#rendergroupcellcontentprops) ### Hooks #### `useHeaderRowSelection()` +```tsx +function useHeaderRowSelection(): { + isIndeterminate: boolean; + isRowSelected: boolean; + onRowSelectionChange: (selectRowEvent: SelectHeaderRowEvent) => void; +}; +``` + Hook for managing header row selection state. Used within custom header cell renderers to implement custom "select all" functionality. **Returns:** @@ -998,6 +1214,14 @@ function CustomHeaderCell() { #### `useRowSelection()` +```tsx +function useRowSelection(): { + isRowSelectionDisabled: boolean; + isRowSelected: boolean; + onRowSelectionChange: (selectRowEvent: SelectRowEvent) => void; +}; +``` + Hook for managing row selection state. Used within custom cell renderers to implement custom row selection. **Returns:** @@ -1031,7 +1255,13 @@ function CustomSelectCell({ row }: RenderCellContentProps) { ### Render Functions -#### `renderHeaderCell(props: RenderHeaderCellContentProps)` +#### `renderHeaderCell()` + +```tsx +function renderHeaderCell( + props: RenderHeaderCellContentProps +): string | React.JSX.Element; +``` The default header cell content renderer. Renders sortable columns with sort indicators. @@ -1050,7 +1280,11 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderTextEditor(props: RenderEditCellContentProps)` +#### `renderTextEditor()` + +```tsx +function renderTextEditor(props: RenderEditCellContentProps): React.JSX.Element; +``` A basic text editor provided for convenience. @@ -1068,15 +1302,27 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderSortIcon(props: RenderSortIconProps)` +#### `renderSortIcon()` + +```tsx +function renderSortIcon(props: RenderSortIconProps): React.JSX.Element | null; +``` Renders the sort direction arrow icon. -#### `renderSortPriority(props: RenderSortPriorityProps)` +#### `renderSortPriority()` + +```tsx +function renderSortPriority(props: RenderSortPriorityProps): number | undefined; +``` Renders the sort priority number for multi-column sorting. -#### `renderCheckbox(props: RenderCheckboxProps)` +#### `renderCheckbox()` + +```tsx +function renderCheckbox(props: RenderCheckboxProps): React.JSX.Element; +``` Renders a checkbox input with proper styling and accessibility. @@ -1092,7 +1338,11 @@ import { DataGrid, renderCheckbox } from 'react-data-grid'; />; ``` -#### `renderToggleGroup(props: RenderGroupCellContentProps)` +#### `renderToggleGroup()` + +```tsx +function renderToggleGroup(props: RenderGroupCellContentProps): React.JSX.Element; +``` The default group cell content renderer for the columns used for grouping (`groupBy` prop). This renders the expand/collapse toggle. @@ -1110,7 +1360,11 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderValue(props: RenderCellContentProps)` +#### `renderValue()` + +```tsx +function renderValue(props: RenderCellContentProps): React.ReactNode; +``` The default cell content renderer that renders the value of `row[column.key]`. @@ -1132,6 +1386,10 @@ const columns: readonly Column[] = [ #### `DataGridRenderersContext` +```tsx +const DataGridRenderersContext: React.Context>>; +``` + Context for providing default renderers to DataGrids in your app. **Example:** @@ -1167,7 +1425,11 @@ function AppProvider({ children }) { ### Other -#### `SelectColumn: Column` +#### `SelectColumn` + +```tsx +const SelectColumn: Column; +``` A pre-configured column for row selection. Includes checkbox renderers for the header row, regular rows, and group rows. @@ -1196,7 +1458,11 @@ function MyGrid() { } ``` -#### `SELECT_COLUMN_KEY = 'rdg-select-column'` +#### `SELECT_COLUMN_KEY` + +```tsx +const SELECT_COLUMN_KEY = 'rdg-select-column'; +``` The key used for the `SelectColumn`. Useful for identifying or filtering the select column. @@ -1210,21 +1476,33 @@ const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN ### Types -#### `Column` +#### `Column` Defines the configuration for a column in the grid. -**See also:** [`columns`](#columns-readonly-columnorcolumngroupr-sr) prop on `` +**See also:** [`columns`](#columns) prop on `` -##### `name: string | ReactElement` +##### `name` + +```tsx +readonly name: string | ReactElement; +``` The name of the column. Displayed in the header cell by default. -##### `key: string` +##### `key` + +```tsx +readonly key: string; +``` A unique key to distinguish each column. -##### `width?: Maybe` +##### `width?` + +```tsx +readonly width?: Maybe; +``` Width can be any valid CSS grid column value. If not specified, it will be determined automatically based on grid width and specified widths of other columns. @@ -1264,17 +1542,29 @@ width: 'minmax(100px, max-content)', **Default:** `auto` -##### `minWidth?: Maybe` +##### `minWidth?` + +```tsx +readonly minWidth?: Maybe; +``` Minimum column width in pixels. **Default:** `50` pixels -##### `maxWidth?: Maybe` +##### `maxWidth?` + +```tsx +readonly maxWidth?: Maybe; +``` Maximum column width in pixels. -##### `cellClass?: Maybe Maybe)>` +##### `cellClass?` + +```tsx +readonly cellClass?: Maybe Maybe)>; +``` Class name(s) for cells. Can be a string or a function that returns a class name based on the row. @@ -1308,41 +1598,77 @@ const columns: Column[] = [ } ``` -##### `headerCellClass?: Maybe` +##### `headerCellClass?` + +```tsx +readonly headerCellClass?: Maybe; +``` Class name(s) for the header cell. -##### `summaryCellClass?: Maybe Maybe)>` +##### `summaryCellClass?` + +```tsx +readonly summaryCellClass?: Maybe Maybe)>; +``` Class name(s) for summary cells. Can be a string or a function that returns a class name based on the summary row. -##### `renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>` +##### `renderCell?` + +```tsx +readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; +``` Render function to render the content of cells. -##### `renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) => ReactNode>` +##### `renderHeaderCell?` + +```tsx +readonly renderHeaderCell?: Maybe<(props: RenderHeaderCellContentProps) => ReactNode>; +``` Render function to render the content of the header cell. -##### `renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>` +##### `renderSummaryCell?` + +```tsx +readonly renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>; +``` Render function to render the content of summary cells. -##### `renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>` +##### `renderGroupCell?` + +```tsx +readonly renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>; +``` Render function to render the content of group cells when using `TreeDataGrid`. -##### `renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>` +##### `renderEditCell?` + +```tsx +readonly renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>; +``` Render function to render the content of edit cells. When set, the column is automatically set to be editable. -##### `editable?: Maybe boolean)>` +##### `editable?` + +```tsx +readonly editable?: Maybe boolean)>; +``` Control whether cells can be edited with `renderEditCell`. -##### `colSpan?: Maybe<(args: ColSpanArgs) => Maybe>` +##### `colSpan?` -Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. See the [`ColSpanArgs`](#colspanargsr-sr) type. +```tsx +readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; +``` + +Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. See the [`ColSpanArgs`](#colspanargs) type. **Example:** @@ -1363,7 +1689,11 @@ const columns: readonly Column[] = [ ]; ``` -##### `frozen?: Maybe` +##### `frozen?` + +```tsx +readonly frozen?: Maybe; +``` Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. See the [`ColumnFrozen`](#columnfrozen) type. @@ -1381,25 +1711,41 @@ const columns: readonly Column[] = [ **Default:** `false` -##### `resizable?: Maybe` +##### `resizable?` + +```tsx +readonly resizable?: Maybe; +``` Enable resizing of the column. **Default:** `false` -##### `sortable?: Maybe` +##### `sortable?` + +```tsx +readonly sortable?: Maybe; +``` Enable sorting of the column. **Default:** `false` -##### `draggable?: Maybe` +##### `draggable?` + +```tsx +readonly draggable?: Maybe; +``` Enable dragging of the column. **Default:** `false` -##### `sortDescendingFirst?: Maybe` +##### `sortDescendingFirst?` + +```tsx +readonly sortDescendingFirst?: Maybe; +``` Sets the column sort order to be descending instead of ascending the first time the column is sorted. @@ -1409,26 +1755,38 @@ Sets the column sort order to be descending instead of ascending the first time Options for cell editing. -###### `displayCellContent?: Maybe` +###### `displayCellContent?` + +```tsx +readonly displayCellContent?: Maybe; +``` Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. By default, the cell content is not rendered when the edit cell is open. **Default:** `false` -###### `commitOnOutsideClick?: Maybe` +###### `commitOnOutsideClick?` + +```tsx +readonly commitOnOutsideClick?: Maybe; +``` Commit changes when clicking outside the cell. **Default:** `true` -###### `closeOnExternalRowChange?: Maybe` +###### `closeOnExternalRowChange?` + +```tsx +readonly closeOnExternalRowChange?: Maybe; +``` Close the editor when the row value changes externally. **Default:** `true` -#### `ColumnGroup` +#### `ColumnGroup` Defines a group of columns that share a common header. @@ -1457,9 +1815,9 @@ const columns: readonly ColumnOrColumnGroup[] = [ ]; ``` -**See also:** [`ColumnOrColumnGroup`](#columnorcolumngroupr-sr) +**See also:** [`ColumnOrColumnGroup`](#columnorcolumngroup) -#### `ColumnOrColumnGroup` +#### `ColumnOrColumnGroup` Union type representing either a `Column` or a `ColumnGroup`. @@ -1467,9 +1825,9 @@ Union type representing either a `Column` or a `ColumnGroup`. type ColumnOrColumnGroup = Column | ColumnGroup; ``` -**See also:** [`columns`](#columns-readonly-columnorcolumngroupr-sr) prop on `` +**See also:** [`columns`](#columns) prop on `` -#### `CalculatedColumn` +#### `CalculatedColumn` Extends `Column` with additional computed properties used internally by the grid. This is the type passed to render functions. The `Column` properties it redeclares, like `width` and `renderCell`, are resolved to their default values when not set. @@ -1493,9 +1851,9 @@ interface CalculatedColumn extends Column { } ``` -**See also:** [`Column`](#columnr-sr), [`onColumnResize`](#oncolumnresize-maybecolumn-calculatedcolumnr-sr-width-number--void) prop on `` +**See also:** [`Column`](#column), [`onColumnResize`](#oncolumnresize) prop on `` -#### `CalculatedColumnParent` +#### `CalculatedColumnParent` Represents a parent column group in the calculated column structure. @@ -1510,9 +1868,9 @@ interface CalculatedColumnParent { } ``` -**See also:** [`CalculatedColumn`](#calculatedcolumnr-sr) +**See also:** [`CalculatedColumn`](#calculatedcolumn) -#### `CalculatedColumnOrColumnGroup` +#### `CalculatedColumnOrColumnGroup` Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. @@ -1520,9 +1878,9 @@ Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn type CalculatedColumnOrColumnGroup = CalculatedColumnParent | CalculatedColumn; ``` -**See also:** [`CalculatedColumn`](#calculatedcolumnr-sr), [`CalculatedColumnParent`](#calculatedcolumnparentr-sr) +**See also:** [`CalculatedColumn`](#calculatedcolumn), [`CalculatedColumnParent`](#calculatedcolumnparent) -#### `DefaultColumnOptions` +#### `DefaultColumnOptions` Default options applied to all columns. @@ -1540,7 +1898,7 @@ type DefaultColumnOptions = Pick< >; ``` -**See also:** [`defaultColumnOptions`](#defaultcolumnoptions-maybedefaultcolumnoptionsr-sr) prop on `` +**See also:** [`defaultColumnOptions`](#defaultcolumnoptions) prop on `` #### `ColumnFrozen` @@ -1550,9 +1908,9 @@ Whether a column is frozen, and on which edge. type ColumnFrozen = boolean | 'start' | 'end'; ``` -**See also:** [`column.frozen`](#frozen-maybecolumnfrozen) +**See also:** [`column.frozen`](#frozen) -#### `RenderCellContentProps` +#### `RenderCellContentProps` Props passed to custom cell content renderers (`column.renderCell`). @@ -1582,9 +1940,9 @@ function renderCell({ row, column, onRowChange }: RenderCellContentProps) } ``` -**See also:** [`column.renderCell`](#rendercell-maybeprops-rendercellcontentpropsr-sr--reactnode), [`renderValue`](#rendervaluer-srprops-rendercellcontentpropsr-sr) function +**See also:** [`column.renderCell`](#rendercell), [`renderValue`](#rendervalue) function -#### `RenderHeaderCellContentProps` +#### `RenderHeaderCellContentProps` Props passed to custom header cell content renderers (`column.renderHeaderCell`). @@ -1597,9 +1955,9 @@ interface RenderHeaderCellContentProps { } ``` -**See also:** [`column.renderHeaderCell`](#renderheadercell-maybeprops-renderheadercellcontentpropsr-sr--reactnode), [`renderHeaderCell`](#renderheadercellr-srprops-renderheadercellcontentpropsr-sr) function +**See also:** [`column.renderHeaderCell`](#renderheadercell-1), [`renderHeaderCell`](#renderheadercell) function -#### `RenderEditCellContentProps` +#### `RenderEditCellContentProps` Props passed to custom editors (`column.renderEditCell`). @@ -1630,9 +1988,9 @@ function renderEditor({ row, column, onRowChange, onClose }: RenderEditCellConte } ``` -**See also:** [`column.renderEditCell`](#rendereditcell-maybeprops-rendereditcellcontentpropsr-sr--reactnode), [`renderTextEditor`](#rendertexteditorr-srprops-rendereditcellcontentpropsr-sr) function +**See also:** [`column.renderEditCell`](#rendereditcell), [`renderTextEditor`](#rendertexteditor) function -#### `RenderSummaryCellContentProps` +#### `RenderSummaryCellContentProps` Props passed to summary cell content renderers (`column.renderSummaryCell`). @@ -1644,9 +2002,9 @@ interface RenderSummaryCellContentProps { } ``` -**See also:** [`column.renderSummaryCell`](#rendersummarycell-maybeprops-rendersummarycellcontentpropssr-r--reactnode) +**See also:** [`column.renderSummaryCell`](#rendersummarycell) -#### `RenderGroupCellContentProps` +#### `RenderGroupCellContentProps` Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. @@ -1662,9 +2020,9 @@ interface RenderGroupCellContentProps { } ``` -**See also:** [`column.renderGroupCell`](#rendergroupcell-maybeprops-rendergroupcellcontentpropsr-sr--reactnode), [`renderToggleGroup`](#rendertogglegroupr-srprops-rendergroupcellcontentpropsr-sr) function, [``](#togglegroup-) +**See also:** [`column.renderGroupCell`](#rendergroupcell), [`renderToggleGroup`](#rendertogglegroup) function, [``](#togglegroup-) -#### `RenderRowProps` +#### `RenderRowProps` Props passed to custom row renderers. @@ -1687,28 +2045,6 @@ interface BaseRenderRowProps extends BaseRenderCellProps gridRowStart: number; } -interface BaseRenderCellProps - extends - Omit, 'children'>, - Pick< - DataGridProps, - 'onCellMouseDown' | 'onCellClick' | 'onCellDoubleClick' | 'onCellContextMenu' - > { - rowIdx: number; - setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; -} - -type IterateOverViewportColumnsForRow = ( - activeIdx: number | undefined, - args?: ColSpanArgs -) => IteratorObject>; - -type ViewportColumnWithColSpan = [ - column: CalculatedColumn, - isCellActive: boolean, - colSpan: number | undefined -]; - interface EditCellProps extends Pick< RenderCellProps, 'column' | 'colSpan' | 'row' | 'rowIdx' @@ -1718,20 +2054,11 @@ interface EditCellProps extends Pick< navigate: (event: React.KeyboardEvent) => void; onKeyDown: Maybe<(args: EditCellKeyDownArgs, event: CellKeyboardEvent) => void>; } - -interface EditCellKeyDownArgs { - mode: 'EDIT'; - column: CalculatedColumn; - row: R; - rowIdx: number; - navigate: () => void; - onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; -} ``` -**See also:** [`renderers.renderRow`](#renderers-mayberenderersr-sr), [``](#row-) +**See also:** [`renderers.renderRow`](#renderers), [``](#row-) -#### `RenderCellProps` +#### `RenderCellProps` Props passed to the cell renderer when using `renderers.renderCell`. @@ -1757,7 +2084,7 @@ interface BaseRenderCellProps } ``` -**See also:** [`renderers.renderCell`](#renderers-mayberenderersr-sr), [``](#cell-) +**See also:** [`renderers.renderCell`](#renderers), [``](#cell-) #### `RenderCheckboxProps` @@ -1782,7 +2109,7 @@ interface RenderCheckboxProps { } ``` -**See also:** [`renderCheckbox`](#rendercheckboxprops-rendercheckboxprops) function, [`renderers.renderCheckbox`](#renderers-mayberenderersr-sr), [``](#selectcheckbox-) +**See also:** [`renderCheckbox`](#rendercheckbox) function, [`renderers.renderCheckbox`](#renderers), [``](#selectcheckbox-) #### `RenderSortStatusProps` @@ -1792,7 +2119,7 @@ Props for custom sort status renderers. interface RenderSortStatusProps extends RenderSortIconProps, RenderSortPriorityProps {} ``` -**See also:** [`renderers.renderSortStatus`](#renderers-mayberenderersr-sr) +**See also:** [`renderers.renderSortStatus`](#renderers) #### `RenderSortIconProps` @@ -1805,7 +2132,7 @@ interface RenderSortIconProps { } ``` -**See also:** [`renderSortIcon`](#rendersorticonprops-rendersorticonprops) function +**See also:** [`renderSortIcon`](#rendersorticon) function #### `RenderSortPriorityProps` @@ -1818,9 +2145,9 @@ interface RenderSortPriorityProps { } ``` -**See also:** [`renderSortPriority`](#rendersortpriorityprops-rendersortpriorityprops) function +**See also:** [`renderSortPriority`](#rendersortpriority) function -#### `Renderers` +#### `Renderers` Custom renderer configuration for the grid. @@ -1834,9 +2161,9 @@ interface Renderers { } ``` -**See also:** [`renderers`](#renderers-mayberenderersr-sr) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) +**See also:** [`renderers`](#renderers) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) -#### `CellMouseArgs` +#### `CellMouseArgs` Arguments passed to cell mouse event handlers. @@ -1864,7 +2191,7 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { } ``` -**See also:** [`onCellMouseDown`](#oncellmousedown-cellmouseeventhandlerr-sr), [`onCellClick`](#oncellclick-cellmouseeventhandlerr-sr), [`onCellDoubleClick`](#oncelldoubleclick-cellmouseeventhandlerr-sr), and [`onCellContextMenu`](#oncellcontextmenu-cellmouseeventhandlerr-sr) props on `` +**See also:** [`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` #### `CellMouseEvent` @@ -1886,9 +2213,9 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { } ``` -**See also:** [`onCellMouseDown`](#oncellmousedown-cellmouseeventhandlerr-sr), [`onCellClick`](#oncellclick-cellmouseeventhandlerr-sr), [`onCellDoubleClick`](#oncelldoubleclick-cellmouseeventhandlerr-sr), and [`onCellContextMenu`](#oncellcontextmenu-cellmouseeventhandlerr-sr) props on `` +**See also:** [`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` -#### `CellKeyDownArgs` +#### `CellKeyDownArgs` Arguments passed to the `onCellKeyDown` handler. The shape differs based on whether the cell is in ACTIVE or EDIT mode. @@ -1930,7 +2257,7 @@ function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { } ``` -**See also:** [`onCellKeyDown`](#oncellkeydown-maybeargs-cellkeydownargsr-sr-event-cellkeyboardevent--void) prop on `` +**See also:** [`onCellKeyDown`](#oncellkeydown) prop on `` #### `CellKeyboardEvent` @@ -1940,9 +2267,9 @@ Extends `React.KeyboardEvent` with grid-specific methods. type CellKeyboardEvent = CellEvent>; ``` -**See also:** [`onCellKeyDown`](#oncellkeydown-maybeargs-cellkeydownargsr-sr-event-cellkeyboardevent--void) prop on `` +**See also:** [`onCellKeyDown`](#oncellkeydown) prop on `` -#### `CellCopyArgs` +#### `CellCopyArgs` Arguments passed to `onCellCopy`. @@ -1955,9 +2282,9 @@ interface CellCopyPasteArgs { } ``` -**See also:** [`onCellCopy`](#oncellcopy-maybeargs-cellcopyargsr-sr-event-cellclipboardevent--void) prop on `` +**See also:** [`onCellCopy`](#oncellcopy) prop on `` -#### `CellPasteArgs` +#### `CellPasteArgs` Arguments passed to `onCellPaste`. @@ -1970,9 +2297,9 @@ interface CellCopyPasteArgs { } ``` -**See also:** [`onCellPaste`](#oncellpaste-maybeargs-cellpasteargsr-sr-event-cellclipboardevent--r) prop on `` +**See also:** [`onCellPaste`](#oncellpaste) prop on `` -#### `PositionChangeArgs` +#### `PositionChangeArgs` Arguments passed to `onActivePositionChange`. @@ -1993,9 +2320,9 @@ interface PositionChangeArgs { } ``` -**See also:** [`onActivePositionChange`](#onactivepositionchange-maybeargs-positionchangeargsr-sr--void) prop on `` +**See also:** [`onActivePositionChange`](#onactivepositionchange) prop on `` -#### `ColSpanArgs` +#### `ColSpanArgs` Arguments passed to the `colSpan` function. @@ -2033,9 +2360,9 @@ const columns: readonly Column[] = [ ]; ``` -**See also:** [`column.colSpan`](#colspan-maybeargs-colspanargsr-sr--maybenumber) +**See also:** [`column.colSpan`](#colspan) -#### `RowHeightArgs` +#### `RowHeightArgs` Arguments passed to `TreeDataGrid`'s `rowHeight` prop when it is a function. @@ -2064,7 +2391,7 @@ function getRowHeight(args: RowHeightArgs): number { ``` -**See also:** [`rowHeight`](#rowheight-maybenumber--args-rowheightargsr--number) prop on `` +**See also:** [`rowHeight`](#rowheight-1) prop on `` #### `SortColumn` @@ -2077,7 +2404,7 @@ interface SortColumn { } ``` -**See also:** [`sortColumns`](#sortcolumns-maybereadonly-sortcolumn) and [`onSortColumnsChange`](#onsortcolumnschange-maybesortcolumns-sortcolumn--void) props on `` +**See also:** [`sortColumns`](#sortcolumns) and [`onSortColumnsChange`](#onsortcolumnschange) props on `` #### `SortDirection` @@ -2087,7 +2414,7 @@ type SortDirection = 'ASC' | 'DESC'; **See also:** [`SortColumn`](#sortcolumn) -#### `RowsChangeData` +#### `RowsChangeData` Data provided to the `onRowsChange` callback. @@ -2100,9 +2427,9 @@ interface RowsChangeData { } ``` -**See also:** [`onRowsChange`](#onrowschange-mayberows-r-data-rowschangedatar-sr--void) prop on `` +**See also:** [`onRowsChange`](#onrowschange) prop on `` -#### `SelectRowEvent` +#### `SelectRowEvent` Event object for row selection changes. @@ -2128,7 +2455,7 @@ interface SelectHeaderRowEvent { **See also:** [`useHeaderRowSelection`](#useheaderrowselection) hook -#### `FillEvent` +#### `FillEvent` Event object for drag-fill operations. @@ -2140,7 +2467,7 @@ interface FillEvent { } ``` -**See also:** [`onFill`](#onfill-maybeevent-filleventr--r) prop on `` +**See also:** [`onFill`](#onfill) prop on `` #### `DataGridHandle` @@ -2171,7 +2498,7 @@ function MyGrid() { } ``` -**See also:** [`ref`](#ref-maybereactrefdatagridhandle) prop on `` +**See also:** [`ref`](#ref) prop on `` #### `SetActivePositionOptions` @@ -2184,7 +2511,7 @@ interface SetActivePositionOptions { } ``` -**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargsr-sr) +**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) #### `ColumnWidths` @@ -2194,7 +2521,7 @@ A map of column widths. type ColumnWidths = ReadonlyMap; ``` -**See also:** [`columnWidths`](#columnwidths-maybecolumnwidths) and [`onColumnWidthsChange`](#oncolumnwidthschange-maybecolumnwidths-columnwidths--void) props on `` +**See also:** [`columnWidths`](#columnwidths) and [`onColumnWidthsChange`](#oncolumnwidthschange) props on `` #### `ColumnWidth` @@ -2209,7 +2536,7 @@ interface ColumnWidth { } ``` -**See also:** [`ColumnWidths`](#columnwidths) +**See also:** [`ColumnWidths`](#columnwidths-1) #### `Direction` @@ -2219,7 +2546,7 @@ Text direction of the grid. type Direction = 'ltr' | 'rtl'; ``` -**See also:** [`direction`](#direction-maybedirection) prop on `` +**See also:** [`direction`](#direction) prop on `` #### `CellClipboardEvent` (internal) @@ -2229,9 +2556,9 @@ Type alias for `React.ClipboardEvent`. Used for copy and paste e type CellClipboardEvent = React.ClipboardEvent; ``` -**See also:** [`onCellCopy`](#oncellcopy-maybeargs-cellcopyargsr-sr-event-cellclipboardevent--void) and [`onCellPaste`](#oncellpaste-maybeargs-cellpasteargsr-sr-event-cellclipboardevent--r) props on `` +**See also:** [`onCellCopy`](#oncellcopy) and [`onCellPaste`](#oncellpaste) props on `` -#### `CellEvent` (internal) +#### `CellEvent` (internal) Adds grid-specific methods to a React event. This helper type is not exported; the shape is shown for reference. @@ -2246,7 +2573,7 @@ type CellEvent> = E & { **See also:** [`CellMouseEvent`](#cellmouseevent), [`CellKeyboardEvent`](#cellkeyboardevent) -#### `CellMouseEventHandler` (internal) +#### `CellMouseEventHandler` (internal) Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. @@ -2256,7 +2583,7 @@ type CellMouseEventHandler = Maybe< >; ``` -#### `GroupRow` (internal) +#### `GroupRow` (internal) Represents a group row in `TreeDataGrid`. This helper type is not exported; the shape is shown for reference. @@ -2274,9 +2601,9 @@ interface GroupRow { } ``` -**See also:** [`RenderGroupCellContentProps`](#rendergroupcellcontentpropsr-sr), [`RowHeightArgs`](#rowheightargsr), [``](#treedatagrid-) +**See also:** [`RenderGroupCellContentProps`](#rendergroupcellcontentprops), [`RowHeightArgs`](#rowheightargs), [``](#treedatagrid-) -#### `Maybe` (internal) +#### `Maybe` (internal) Utility type for optional values. This helper type is not exported; the shape is shown for reference. @@ -2310,7 +2637,7 @@ interface Position { } ``` -**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargsr-sr) +**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index da690d3041..a2e6be935e 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -36,8 +36,9 @@ interface Node { body?: { body: Node[] }; members?: Node[]; params?: Node[] | { params: Node[] }; - typeParameters?: { params: { name: { name: string } }[] } | null; + typeParameters?: Node | null; typeAnnotation?: Node; + returnType?: Node | null; typeArguments?: { params: Node[] } | null; declarations?: Node[]; init?: Node | null; @@ -137,31 +138,27 @@ function renderItem(item: Declaration, section: string, hasPropsInterface: boole const { name, node, doc } = item; if (isType(node)) return renderType(item, 4); - const md: string[] = []; if (section === 'Components') { - md.push(heading(4, `\`<${name} />\``, name), ...renderSummary(doc), ...renderTags(doc)); + const md = [heading(4, `\`<${name} />\``, name), ...renderSummary(doc), ...renderTags(doc)]; // the props interface of a component is listed after it, e.g. `DataGridProps` after `DataGrid` if (!hasPropsInterface) md.push(heading(5, 'Props'), renderComponentProps(node)); - } else { - let title = name; - if (node.type !== 'VariableDeclaration') { - title += getFunctionSignature(node); - } else if (section !== 'Context') { - title = getVariableSignature(name, node); - } - md.push(heading(4, `\`${title}\``, name), ...renderSummary(doc), ...renderTags(doc)); + return md.join('\n\n'); } - return md.join('\n\n'); + + const isFunction = node.type !== 'VariableDeclaration'; + return [ + heading(4, `\`${name}${isFunction ? '()' : ''}\``, name), + codeBlock(isFunction ? getFunctionSignature(name, node) : getVariableSignature(name, node)), + ...renderSummary(doc), + ...renderTags(doc) + ].join('\n\n'); } function renderType({ name, node, doc }: Declaration, level: number) { - const typeParameters = node.typeParameters?.params.map((param) => param.name.name); - // the props interfaces of the components are titled by their name, e.g. `DataGridProps` - const title = - level === 4 && typeParameters !== undefined ? `${name}<${typeParameters.join(', ')}>` : name; const isInternal = !exportedDeclarations.has(name); + // the props interfaces of the components are titled by their name, e.g. `DataGridProps` const md = [ - heading(level, level === 4 ? `\`${title}\`${isInternal ? ' (internal)' : ''}` : title, name), + heading(level, level === 4 ? `\`${name}\`${isInternal ? ' (internal)' : ''}` : name, name), ...renderSummary(doc) ]; @@ -189,14 +186,9 @@ function renderMembers(members: Node[], level: number, parent: string): string[] ...renderMembers(typeLiteral.members!, Math.min(level + 1, 6), `${parent}.${name}`) ]; } - const signature = cleanCode(source(member)) - .replace(/^readonly /, '') - .replace(/;$/, '') - .replaceAll(/\s+/g, ' ') - .replaceAll('< ', '<') - .replaceAll(' >', '>'); return [ - heading(level, `\`${signature}\``, `${parent}.${name}`), + heading(level, `\`${name}${member.optional === true ? '?' : ''}\``, `${parent}.${name}`), + codeBlock(source(member)), ...renderSummary(doc), ...renderTags(doc) ]; @@ -219,7 +211,7 @@ function renderTags({ tags }: Doc) { .map(({ name, text }) => `${labels[name]}${convertLinks(text)}`); } -// e.g. "[`RenderRowProps`](#renderrowpropsr-sr)" +// e.g. "[`RenderRowProps`](#renderrowprops)" function renderComponentProps(node: Node) { const signature = node.type === 'VariableDeclaration' @@ -230,24 +222,25 @@ function renderComponentProps(node: Node) { return helperTypes.has(typeName) ? `\`${propsType}\`` : `[\`${propsType}\`](#!${typeName})`; } -// e.g. `(props: RenderHeaderCellContentProps)`, without the return type -function getFunctionSignature(node: Node) { - const typeParameters = node.typeParameters?.params.map((param) => param.name.name); +// e.g. `function renderHeaderCell(props: RenderHeaderCellContentProps): …` +function getFunctionSignature(name: string, node: Node) { + const typeParameters = node.typeParameters == null ? '' : source(node.typeParameters); const params = getParams(node).map((param) => { // destructured parameters are named `props` const paramName = param.type === 'Identifier' ? param.name : 'props'; - return `${paramName}: ${cleanCode(source(param.typeAnnotation!.typeAnnotation!))}`; + return `${paramName}: ${source(param.typeAnnotation!.typeAnnotation!)}`; }); - return `${typeParameters === undefined ? '' : `<${typeParameters.join(', ')}>`}(${params.join(', ')})`; + const returnType = node.returnType == null ? '' : source(node.returnType); + return `function ${name}${typeParameters}(${params.join(', ')})${returnType};`; } -// e.g. `SelectColumn: Column` or `SELECT_COLUMN_KEY = 'rdg-select-column'` +// e.g. `const SelectColumn: Column;` or `const SELECT_COLUMN_KEY = 'rdg-select-column';` function getVariableSignature(name: string, node: Node) { const declarator = node.declarations![0]; if (declarator.init !== null && declarator.init !== undefined) { - return `${name} = ${source(declarator.init).replaceAll('"', "'")}`; + return `const ${name} = ${source(declarator.init).replaceAll('"', "'")};`; } - return `${name}: ${cleanCode(source(declarator.id!.typeAnnotation!.typeAnnotation!))}`; + return `const ${name}${source(declarator.id!.typeAnnotation!)};`; } function getParams(node: Node) { @@ -255,22 +248,14 @@ function getParams(node: Node) { return Array.isArray(params) ? params : params!.params; } -// the declaration of a type, followed by the declarations of the helper types it references +// the declaration of a type, followed by the declarations of the helper types it directly references function getTypeDeclarations(node: Node) { - const referenced = new Set(); - const visit = (text: string) => { - for (const [name] of text.matchAll(/\b\w+\b/g)) { - const helperType = helperTypes.get(name); - if (helperType !== undefined && !referenced.has(name) && helperType.node !== node) { - referenced.add(name); - visit(source(helperType.node)); - } - } - }; - visit(source(node)); - return [node, ...[...referenced].map((name) => helperTypes.get(name)!.node)] - .map(source) - .join('\n\n'); + const referenced = new Set( + Array.from(source(node).matchAll(/\b\w+\b/g), ([name]) => helperTypes.get(name)?.node) + ); + referenced.delete(undefined); + referenced.delete(node); + return [node, ...referenced].map((declaration) => source(declaration!)).join('\n\n'); } function compareNames(a: Declaration, b: Declaration) { From ca8ae8e862c22e6dbb87a1da7382dd26ed5dc63a Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 18:05:20 -0500 Subject: [PATCH 12/22] Merge internal base interfaces into the public interfaces in the API reference Co-Authored-By: Claude Opus 5.5 --- README.md | 51 +++++++++++++++-------------------- scripts/generateApiDocs.ts | 55 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 74 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 686cd33d2c..939d6b3edf 100644 --- a/README.md +++ b/README.md @@ -2027,32 +2027,26 @@ interface RenderGroupCellContentProps { Props passed to custom row renderers. ```tsx -interface RenderRowProps extends BaseRenderRowProps { - row: R; - draggedOverCellIdx: number | undefined; - activeCellEditor: ReactElement> | undefined; - onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; - rowClass: Maybe<(row: R, rowIdx: number) => Maybe>; - isTreeGrid: boolean; -} - -interface BaseRenderRowProps extends BaseRenderCellProps { +interface RenderRowProps + extends + Omit, 'children'>, + Pick< + DataGridProps, + 'onCellMouseDown' | 'onCellClick' | 'onCellDoubleClick' | 'onCellContextMenu' + > { + setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; iterateOverViewportColumnsForRow: IterateOverViewportColumnsForRow; rowIdx: number; activeCellIdx: number | undefined; isRowSelectionDisabled: boolean; isRowSelected: boolean; gridRowStart: number; -} - -interface EditCellProps extends Pick< - RenderCellProps, - 'column' | 'colSpan' | 'row' | 'rowIdx' -> { - onRowChange: (row: R, commitChanges: boolean, shouldFocus: boolean) => void; - closeEditor: (shouldFocus: boolean) => void; - navigate: (event: React.KeyboardEvent) => void; - onKeyDown: Maybe<(args: EditCellKeyDownArgs, event: CellKeyboardEvent) => void>; + row: R; + draggedOverCellIdx: number | undefined; + activeCellEditor: ReactElement> | undefined; + onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; + rowClass: Maybe<(row: R, rowIdx: number) => Maybe>; + isTreeGrid: boolean; } ``` @@ -2063,16 +2057,7 @@ interface EditCellProps extends Pick< Props passed to the cell renderer when using `renderers.renderCell`. ```tsx -interface RenderCellProps extends BaseRenderCellProps { - column: CalculatedColumn; - row: R; - colSpan: number | undefined; - isDraggedOver: boolean; - isCellActive: boolean; - onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; -} - -interface BaseRenderCellProps +interface RenderCellProps extends Omit, 'children'>, Pick< @@ -2081,6 +2066,12 @@ interface BaseRenderCellProps > { rowIdx: number; setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; + column: CalculatedColumn; + row: R; + colSpan: number | undefined; + isDraggedOver: boolean; + isCellActive: boolean; + onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; } ``` diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index a2e6be935e..622c667ac5 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -39,6 +39,8 @@ interface Node { typeParameters?: Node | null; typeAnnotation?: Node; returnType?: Node | null; + extends?: Node[]; + expression?: Node; typeArguments?: { params: Node[] } | null; declarations?: Node[]; init?: Node | null; @@ -248,14 +250,63 @@ function getParams(node: Node) { return Array.isArray(params) ? params : params!.params; } -// the declaration of a type, followed by the declarations of the helper types it directly references +// the declaration of a type: an interface includes the members of the helper interfaces it extends, +// e.g. `RenderRowProps` and `BaseRenderRowProps`, and a type alias is followed by the helper types it references, +// e.g. `CellKeyDownArgs` and `ActiveCellKeyDownArgs` function getTypeDeclarations(node: Node) { + if (node.type === 'TSInterfaceDeclaration') return getInterfaceDeclaration(node); + const referenced = new Set( Array.from(source(node).matchAll(/\b\w+\b/g), ([name]) => helperTypes.get(name)?.node) ); referenced.delete(undefined); referenced.delete(node); - return [node, ...referenced].map((declaration) => source(declaration!)).join('\n\n'); + return [node, ...referenced] + .map((declaration) => + declaration!.type === 'TSInterfaceDeclaration' + ? getInterfaceDeclaration(declaration!) + : source(declaration!) + ) + .join('\n\n'); +} + +function getInterfaceDeclaration(node: Node) { + if (node.extends?.every((base) => !helperTypes.has(source(base.expression!))) !== false) { + return source(node); + } + + const { heritage, members } = getInterfaceParts(node); + const typeParameters = node.typeParameters == null ? '' : source(node.typeParameters); + const extendsClause = heritage.length === 0 ? '' : ` extends ${heritage.join(', ')}`; + const body = Array.from(members.values(), (member) => ` ${member}`).join('\n'); + return `interface ${node.id!.name}${typeParameters}${extendsClause} {\n${body}\n}`; +} + +// the base types and members of an interface, with the members of the helper interfaces it extends +function getInterfaceParts(node: Node) { + const heritage: string[] = []; + const members = new Map(); + + for (const base of node.extends ?? []) { + const helperType = helperTypes.get(source(base.expression!)); + if (helperType?.node.type === 'TSInterfaceDeclaration') { + const parts = getInterfaceParts(helperType.node); + heritage.push(...parts.heritage); + for (const [name, member] of parts.members) members.set(name, member); + } else { + heritage.push(source(base)); + } + } + + for (const member of node.body!.body) { + const name = getMemberName(member); + const comment = getComment(member); + // a redeclared member replaces the inherited one + members.delete(name); + members.set(name, `${comment === '' ? '' : `/*${comment}*/\n `}${source(member)}`); + } + + return { heritage, members }; } function compareNames(a: Declaration, b: Declaration) { From c436614a6772e82efd53ca4621f898a3dada8735 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 18:24:30 -0500 Subject: [PATCH 13/22] Fail the API reference generation on unresolved links, unsupported tags, and headings in JSDoc Also describe the props of SelectCheckbox under Props again, and run `vp run docs` in place of `vp pack` in the ci task. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- scripts/generateApiDocs.ts | 88 +++++++++++++++++++++++++++----------- vite.config.ts | 6 +-- 3 files changed, 67 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 939d6b3edf..8ae27c1d55 100644 --- a/README.md +++ b/README.md @@ -1152,11 +1152,9 @@ The default cell component. Can be wrapped via the `renderers.renderCell` prop. A component for rendering row selection checkboxes. -The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. - ##### Props -`SelectCheckboxProps` +The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. #### `` diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index 622c667ac5..2636d2d647 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -10,6 +10,8 @@ const entryPath = 'src/index.ts'; const readmePath = 'README.md'; const startMarker = ''; const endMarker = ''; +// e.g. `{@linkcode Column.width | width}` +const linkTag = /\{@link(?:code|plain)?\s+([^}|]+?)\s*(?:\|\s*([^}]+?)\s*)?\}/g; // the `@group` tags of the exports const sections = ['Components', 'Hooks', 'Render Functions', 'Context', 'Other', 'Types']; @@ -18,6 +20,11 @@ interface Doc { tags: { name: string; text: string }[]; } +interface GeneratedHeading { + line: string; + key: string | undefined; +} + interface Declaration { name: string; node: Node; @@ -100,8 +107,10 @@ groups .get('Types')! .push(...internalTypes.filter(({ name }) => !helperTypes.has(name)).toSorted(compareNames)); -// the key of each generated heading, to resolve the links to it -const headingKeys: (string | undefined)[] = []; +// the generated headings, with the key to resolve the links to them +const generatedHeadings: GeneratedHeading[] = []; +// the types shown as a code block, whose members link to the type +const codeBlockTypes = new Set(); const markdown: string[] = []; for (const [section, items] of groups) { @@ -141,10 +150,29 @@ function renderItem(item: Declaration, section: string, hasPropsInterface: boole if (isType(node)) return renderType(item, 4); if (section === 'Components') { - const md = [heading(4, `\`<${name} />\``, name), ...renderSummary(doc), ...renderTags(doc)]; + const title = heading(4, `\`<${name} />\``, name); // the props interface of a component is listed after it, e.g. `DataGridProps` after `DataGrid` - if (!hasPropsInterface) md.push(heading(5, 'Props'), renderComponentProps(node)); - return md.join('\n\n'); + if (hasPropsInterface) return [title, ...renderSummary(doc), ...renderTags(doc)].join('\n\n'); + + const propsType = getComponentPropsType(node); + const typeName = /^\w+/.exec(propsType)![0]; + if (!helperTypes.has(typeName)) { + return [ + title, + ...renderSummary(doc), + ...renderTags(doc), + heading(5, 'Props'), + `[\`${propsType}\`](#!${typeName})` + ].join('\n\n'); + } + + // the props of a component with an undocumented props type are described + // by the paragraphs after the first, e.g. `SelectCheckbox` + const [description, ...props] = renderSummary(doc).join('').split('\n\n'); + if (props.length === 0) { + throw new Error(`${name} must describe its props after the first paragraph`); + } + return [title, description, ...renderTags(doc), heading(5, 'Props'), ...props].join('\n\n'); } const isFunction = node.type !== 'VariableDeclaration'; @@ -168,6 +196,7 @@ function renderType({ name, node, doc }: Declaration, level: number) { // a heading per member, as their docs have examples, lists, or several paragraphs md.push(...renderTags(doc), ...renderMembers(node.body!.body, level + 1, name)); } else { + codeBlockTypes.add(name); md.push(codeBlock(getTypeDeclarations(node)), ...renderTags(doc)); } @@ -209,19 +238,22 @@ function renderTags({ tags }: Doc) { returns: '**Returns:**\n\n' }; return tags - .filter(({ name }) => name in labels) + .filter(({ name }) => { + // `@group` sets the section, and the type parameters are described in the "Generics" section + if (name === 'group' || name === 'typeParam') return false; + if (name in labels) return true; + throw new Error(`The @${name} tag is not supported in the API reference`); + }) .map(({ name, text }) => `${labels[name]}${convertLinks(text)}`); } -// e.g. "[`RenderRowProps`](#renderrowprops)" -function renderComponentProps(node: Node) { +// e.g. `RenderRowProps` +function getComponentPropsType(node: Node) { const signature = node.type === 'VariableDeclaration' ? node.declarations![0].id!.typeAnnotation!.typeAnnotation! : node; - const propsType = cleanCode(source(getParams(signature)[0].typeAnnotation!.typeAnnotation!)); - const typeName = /^\w+/.exec(propsType)![0]; - return helperTypes.has(typeName) ? `\`${propsType}\`` : `[\`${propsType}\`](#!${typeName})`; + return cleanCode(source(getParams(signature)[0].typeAnnotation!.typeAnnotation!)); } // e.g. `function renderHeaderCell(props: RenderHeaderCellContentProps): …` @@ -422,8 +454,9 @@ function source({ start, end }: Node) { } function heading(level: number, text: string, key?: string) { - headingKeys.push(key); - return `${'#'.repeat(level)} ${text}`; + const line = `${'#'.repeat(level)} ${text}`; + generatedHeadings.push({ line, key }); + return line; } function codeBlock(text: string) { @@ -436,18 +469,15 @@ function cleanCode(text: string) { return text .replaceAll(/^(?:export )?declare /gm, '') .replaceAll('import("react").', 'React.') - .replaceAll( - /\{@link(?:code)? ([^}|]+?)(?: \| ([^}]+))?\}/g, - (_, target: string, label: string | undefined) => label ?? target - ) + .replaceAll(linkTag, (_, target: string, label: string | undefined) => label ?? target) .replaceAll(/NoInfer<([^<>]+)>/g, '$1'); } // `{@linkcode Column.width | width}` -> "[`width`](#!Column.width)", resolved by `resolveLinks` function convertLinks(text: string) { return text.replaceAll( - /\{@link(?:code)? ([^}|]+?)(?: \| ([^}]+))?\}/g, - (_, target: string, label: string | undefined) => `[\`${label ?? target}\`](#!${target.trim()})` + linkTag, + (_, target: string, label: string | undefined) => `[\`${label ?? target}\`](#!${target})` ); } @@ -458,29 +488,37 @@ function convertLinks(text: string) { function resolveLinks(precedingMarkdown: string, api: string, followingMarkdown: string) { const slugger = new GithubSlugger(); const anchors = new Map(); - const slugHeadings = (markdown: string, keys?: (string | undefined)[]) => { + const slugHeadings = (markdown: string, headings?: GeneratedHeading[]) => { forEachLine(markdown, (line, isInCodeBlock) => { const match = isInCodeBlock ? null : /^#{1,6} (.+)$/.exec(line); if (match === null) return; const anchor = slugger.slug(match[1].replaceAll('`', '')); - const key = keys?.shift(); - if (key !== undefined) anchors.set(key, anchor); + if (headings === undefined) return; + // the generated headings are matched in order + const generated = headings.shift(); + if (generated?.line !== line) { + throw new Error(`The heading "${line}" must not be in a JSDoc comment`); + } + if (generated.key !== undefined) anchors.set(generated.key, anchor); }); }; slugHeadings(precedingMarkdown); - slugHeadings(api, [...headingKeys]); + slugHeadings(api, [...generatedHeadings]); slugHeadings(followingMarkdown); const getAnchor = (target: string) => { + const [type, ...members] = target.split('.'); // the members of types shown as a code block link to their type - const anchor = anchors.get(target) ?? anchors.get(target.split('.')[0]); + const anchor = + anchors.get(target) ?? + (members.length === 1 && codeBlockTypes.has(type) ? anchors.get(type) : undefined); if (anchor === undefined) throw new Error(`The link to ${target} does not match any heading`); return anchor; }; return `${precedingMarkdown}\n\n${api}\n\n${followingMarkdown}` - .replaceAll(/\]\(#!([\w.]+)\)/g, (_, target: string) => `](#${getAnchor(target)})`) + .replaceAll(/\]\(#!([^)]+)\)/g, (_, target: string) => `](#${getAnchor(target)})`) .replaceAll( /\]\(#[^ )]+ (["'])([\w.]+)\1\)/g, (_, quote: string, target: string) => `](#${getAnchor(target)} ${quote}${target}${quote})` diff --git a/vite.config.ts b/vite.config.ts index 2a9867816e..5e1f64d2da 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -114,11 +114,11 @@ export default defineConfig({ // type check runs first, as type issues are often // the root cause of errors reported by later checks 'vp run typecheck', - 'vp run docs', - 'git diff --exit-code README.md', 'vp check', 'vp run eslint', - 'vp pack', + // runs `vp pack`, then generates the API reference from its output + 'vp run docs', + 'git diff --exit-code README.md', 'vp build', 'git diff --exit-code website/routeTree.gen.ts', 'vp run test' From 331e3844ae7f49082a613b7ff25f60ae6776783e Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 19:31:45 -0500 Subject: [PATCH 14/22] Generate the API reference with the TypeScript 7 API instead of oxc-parser Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- package-lock.json | 395 ------------------------------------- package.json | 1 - scripts/generateApiDocs.ts | 352 ++++++++++++++++----------------- 4 files changed, 173 insertions(+), 577 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 275e764644..1e93a1ed38 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,7 +55,7 @@ The project uses [Vite+](https://viteplus.dev/guide/), whose global `vp` CLI wra - `vp ` runs a built-in command, e.g., `vp dev`, `vp check`, `vp test`, `vp pack`, `vp build`. - `vp run ` runs a task from `vite.config.ts`, e.g., `vp run typecheck`, `vp run eslint`, `vp run docs`, `vp run ci`. - Run `vp install` after pulling changes. -- `vp run docs` runs `vp pack`, then `scripts/generateApiDocs.ts`, which parses the declarations and JSDoc comments of `lib/index.d.ts` with `oxc-parser`. +- `vp run docs` runs `vp pack`, then `scripts/generateApiDocs.ts`, which parses the declarations and JSDoc comments of `lib/index.d.ts` with the TypeScript 7 API (`typescript/sync`). ## Validation diff --git a/package-lock.json b/package-lock.json index 609beb9494..cace7f3650 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,7 +25,6 @@ "github-slugger": "^2.0.0", "jspdf": "^4.2.0", "jspdf-autotable": "^5.0.7", - "oxc-parser": "^0.155.0", "oxc-transform-react": "^0.154.0", "playwright": "^1.62.1", "publint": "^0.3.25", @@ -623,353 +622,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@oxc-parser/binding-android-arm-eabi": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.155.0.tgz", - "integrity": "sha512-A6xv7hDtnTm+xlZ7utn6rRQpRMJHRhVr3gjRGqlx0RUX84mNk0pAsy6YN/wWhuOTkaZhRrrzaLxf0NfbH77j2w==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-android-arm64": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm64/-/binding-android-arm64-0.155.0.tgz", - "integrity": "sha512-T1wWwH9/JI5g7Z4kEQwDOwhToxdDhRyOTklH+uuNpJ16m3MZFmGl+l2rKc0NHQdbVRG2LTOBsNjpW3h1BWytPA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-darwin-arm64": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-arm64/-/binding-darwin-arm64-0.155.0.tgz", - "integrity": "sha512-ZoRB3qJxJ8DWA41jHja+YeB0lLfjBy4T+Kr15vnN1k65X3zbJt3rPZftEwN4Ju4tmA4K/T9dWWD7Z8ewQLnrVA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-darwin-x64": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-x64/-/binding-darwin-x64-0.155.0.tgz", - "integrity": "sha512-vxtL86BtM+IgrpejA86nbTk5j0HKTIMeuaJ1fQciw6p9RfavPtIPjI7gN34owap0yG9txXBaAWpGdxokNwdqIw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-freebsd-x64": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-freebsd-x64/-/binding-freebsd-x64-0.155.0.tgz", - "integrity": "sha512-tN6Ru5e0UVnWaIuiH8jEwnvxuxg7FvhWwSd3oe5oDhOD4ObsSr9/N6WfHLjilUWlPPj65ptwrSDH0Y7lzwTzmw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-linux-arm-gnueabihf": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.155.0.tgz", - "integrity": "sha512-h4ozA5n6L6lwolsz9iwunEhKWnIVbmFRots5QxEix0H6nJ5ICpuDa7PuShuhfpIDFe3+Qvyscioyiv+9g+4Syg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-linux-arm-musleabihf": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.155.0.tgz", - "integrity": "sha512-058/+LardpfuUlsKIvBGk/CYoakEVcMgqYx8GgyUZeOxFWTojYLlCc1Gb60/y21v3esDhHidgiY/Zbq9LpBhaQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-linux-arm64-gnu": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.155.0.tgz", - "integrity": "sha512-nrOt2Y3xIAzu+lSPzH0864ieO+iCCXgoo9qFlGANE8Xh0cQ+RP8Wstfp+/wXN2YCyb98cAGzX0VruKYw7it/jw==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-linux-arm64-musl": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.155.0.tgz", - "integrity": "sha512-KYAayyN5hQbJPtGKtRxlyc8XYmyntOplyXSQzTDrmbz7l/GCrzQbSswvyJFBTH1LGtsZrbXOAfN52i/Kz6kLKg==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-linux-ppc64-gnu": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.155.0.tgz", - "integrity": "sha512-CSuSY5hfjtsBnHXydOj8jiNfS1qHbdPZuPz1YL1cSgK7VmNYP+QlZIbG0BBYYBgX/vYEgZwbG9mBdW4YairZ5w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-linux-riscv64-gnu": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.155.0.tgz", - "integrity": "sha512-7KCfOQm+Nz2N8trAXbQkal4TQ5756WVEmhm35y816YHvyFnEfVsICsiV5k0pEszNf/fRm4cm2i6i18SJ6/iCWg==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-linux-riscv64-musl": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.155.0.tgz", - "integrity": "sha512-JSlhgoK+/g1TGJI5NuADx2+6syhxnQNLCWLXyO5QLFyetomcr/vIxSdiNlmyAv963YXUzCuwAwRG6npZ5xyJ1A==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-linux-s390x-gnu": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.155.0.tgz", - "integrity": "sha512-WFIX+dPokWp64mi434Md3U3lJaTwNxAphvGjpltoyQjGUsdXavOIRrnp9dOS34Hd75HOAwDxAI+YwWOwqmJbtg==", - "cpu": [ - "s390x" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-linux-x64-gnu": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.155.0.tgz", - "integrity": "sha512-g6xSDC/JpbnVOz5uafMGyK3txBVRFMQTx8opv/yHXGxqV3ZMVl3bf7W8XrSnF68dmy3gM4dgReNryuE53+WkeQ==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-linux-x64-musl": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-musl/-/binding-linux-x64-musl-0.155.0.tgz", - "integrity": "sha512-6/4xlxKlZJWrQ0uwDFPc0H9+xLu7068CKhX3vIDW3SbvP/lVgnVuT5v6dyugeWskWpuxqF/WJ4WKwhxjU3pG2w==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-openharmony-arm64": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-openharmony-arm64/-/binding-openharmony-arm64-0.155.0.tgz", - "integrity": "sha512-tltklL0J0XjDxIRTBXWOBhvc2mitcmES45pIxhwDWfxRyqz7Vkeu0NekTZEIxGE4f/lXgq3vZcjjffteQOVorg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-win32-arm64-msvc": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.155.0.tgz", - "integrity": "sha512-alAb9TzjatUEsOeoncAziUnfdTDxfyswhalFZ9sC6plUgATIUx2NIZ0+bMn6aJ28AduS1OpG/OAisr/YISn4Ig==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-win32-ia32-msvc": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.155.0.tgz", - "integrity": "sha512-yc5cbSfcGmRv/KpxDFuyk8adEBaWd/9HilWvBbQ4bFbus1V2PUh2mGB2Cfq9rqZTqLeiMT8x0skV+LKp9hOMgQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-parser/binding-win32-x64-msvc": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.155.0.tgz", - "integrity": "sha512-8heq6jGq+rfpTDRDjoQiBHw0maQZf3IXkS99pdHQZPoTL5kyF5qyPS0RidUlSdnWDIqxXb5nux7GBD9cT+imUw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, "node_modules/@oxc-project/runtime": { "version": "0.154.0", "resolved": "https://registry.npmjs.org/@oxc-project/runtime/-/runtime-0.154.0.tgz", @@ -6605,53 +6257,6 @@ "node": ">= 0.8.0" } }, - "node_modules/oxc-parser": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/oxc-parser/-/oxc-parser-0.155.0.tgz", - "integrity": "sha512-C/ReSf1JUFukK/zvk6jhcNibSssvas5+ktIzK7fbKVd3CedWe59C3QwHEOrEZj/4Rt9+xg0Jeis/Jv1F/KM1mw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@oxc-project/types": "^0.155.0" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "funding": { - "url": "https://github.com/sponsors/oxc-project" - }, - "optionalDependencies": { - "@oxc-parser/binding-android-arm-eabi": "0.155.0", - "@oxc-parser/binding-android-arm64": "0.155.0", - "@oxc-parser/binding-darwin-arm64": "0.155.0", - "@oxc-parser/binding-darwin-x64": "0.155.0", - "@oxc-parser/binding-freebsd-x64": "0.155.0", - "@oxc-parser/binding-linux-arm-gnueabihf": "0.155.0", - "@oxc-parser/binding-linux-arm-musleabihf": "0.155.0", - "@oxc-parser/binding-linux-arm64-gnu": "0.155.0", - "@oxc-parser/binding-linux-arm64-musl": "0.155.0", - "@oxc-parser/binding-linux-ppc64-gnu": "0.155.0", - "@oxc-parser/binding-linux-riscv64-gnu": "0.155.0", - "@oxc-parser/binding-linux-riscv64-musl": "0.155.0", - "@oxc-parser/binding-linux-s390x-gnu": "0.155.0", - "@oxc-parser/binding-linux-x64-gnu": "0.155.0", - "@oxc-parser/binding-linux-x64-musl": "0.155.0", - "@oxc-parser/binding-openharmony-arm64": "0.155.0", - "@oxc-parser/binding-win32-arm64-msvc": "0.155.0", - "@oxc-parser/binding-win32-ia32-msvc": "0.155.0", - "@oxc-parser/binding-win32-x64-msvc": "0.155.0" - } - }, - "node_modules/oxc-parser/node_modules/@oxc-project/types": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", - "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/oxc-project" - } - }, "node_modules/oxc-transform-react": { "version": "0.154.0", "resolved": "https://registry.npmjs.org/oxc-transform-react/-/oxc-transform-react-0.154.0.tgz", diff --git a/package.json b/package.json index 83c680deb1..8f60fc653e 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,6 @@ "github-slugger": "^2.0.0", "jspdf": "^4.2.0", "jspdf-autotable": "^5.0.7", - "oxc-parser": "^0.155.0", "oxc-transform-react": "^0.154.0", "playwright": "^1.62.1", "publint": "^0.3.25", diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index 2636d2d647..f52db59711 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -1,6 +1,32 @@ import { readFile, writeFile } from 'node:fs/promises'; import GithubSlugger from 'github-slugger'; -import { parseSync } from 'oxc-parser'; +import { SyntaxKind } from 'typescript/ast'; +import type { + Declaration as DeclarationNode, + FunctionDeclaration, + InterfaceDeclaration, + JSDoc, + JSDocComment, + NodeArray, + Node, + ParameterDeclaration, + PropertySignatureDeclaration, + SourceFile, + TypeElement, + VariableStatement +} from 'typescript/ast'; +import { + isExportDeclaration, + isFunctionTypeNode, + isIdentifier, + isImportDeclaration, + isInterfaceDeclaration, + isJSDocText, + isTypeAliasDeclaration, + isTypeLiteralNode, + isVariableStatement +} from 'typescript/ast/is'; +import { API } from 'typescript/sync'; // Generates the API reference of the README from the declarations and JSDoc comments of `lib/index.d.ts`, // which `vp pack` bundles from the sources. The items are listed in the order they are exported from `src/index.ts`. @@ -10,8 +36,6 @@ const entryPath = 'src/index.ts'; const readmePath = 'README.md'; const startMarker = ''; const endMarker = ''; -// e.g. `{@linkcode Column.width | width}` -const linkTag = /\{@link(?:code|plain)?\s+([^}|]+?)\s*(?:\|\s*([^}]+?)\s*)?\}/g; // the `@group` tags of the exports const sections = ['Components', 'Hooks', 'Render Functions', 'Context', 'Other', 'Types']; @@ -31,58 +55,39 @@ interface Declaration { doc: Doc; } -// the subset of the oxc AST that is used -interface Node { - type: string; - start: number; - end: number; - id?: Node & { name: string }; - name?: string; - optional?: boolean; - key?: { type: string; name?: string; value?: string }; - body?: { body: Node[] }; - members?: Node[]; - params?: Node[] | { params: Node[] }; - typeParameters?: Node | null; - typeAnnotation?: Node; - returnType?: Node | null; - extends?: Node[]; - expression?: Node; - typeArguments?: { params: Node[] } | null; - declarations?: Node[]; - init?: Node | null; - types?: Node[]; - elementType?: Node; -} - -const code = await readFile(declarationsPath, 'utf8'); -const { program, comments } = parseSync(declarationsPath, code); +using api = new API(); +using declarationsFile = api.createSourceFile( + declarationsPath, + await readFile(declarationsPath, 'utf8') +); +using entryFile = api.createSourceFile(entryPath, await readFile(entryPath, 'utf8')); const declarations = new Map(); // exported name -> declared name, e.g. `Cell` -> `MemoCell` const exportedNames = new Map(); -for (const statement of program.body as unknown as Node[]) { - if (statement.type === 'ImportDeclaration') continue; - if (statement.type === 'ExportNamedDeclaration') { - const { declaration, specifiers } = statement as unknown as { - declaration: Node | null; - specifiers: { local: { name: string }; exported: { name: string } }[]; - }; - if (declaration === null) { - for (const { local, exported } of specifiers) exportedNames.set(exported.name, local.name); - continue; +for (const statement of declarationsFile.sourceFile.statements) { + if (isImportDeclaration(statement)) continue; + if (isExportDeclaration(statement)) { + for (const specifier of getExportSpecifiers(statement)) { + exportedNames.set( + specifier.name.getText(), + (specifier.propertyName ?? specifier.name).getText() + ); } - exportedNames.set(getDeclarationName(declaration), getDeclarationName(declaration)); - addDeclaration(declaration, statement); - } else { - addDeclaration(statement, statement); + continue; + } + const name = getDeclarationName(statement); + const { modifiers } = statement as InterfaceDeclaration; + if (modifiers?.some((modifier) => modifier.kind === SyntaxKind.ExportKeyword)) { + exportedNames.set(name, name); } + declarations.set(name, { name, node: statement, doc: getDoc(statement) }); } // group the exports by their `@group` tag, in the order they are exported from the entry point const groups = new Map(sections.map((section) => [section, []])); -for (const name of await getExportOrder()) { +for (const name of getExportOrder(entryFile.sourceFile)) { const declaration = declarations.get(exportedNames.get(name)!)!; const group = declaration.doc.tags.find((tag) => tag.name === 'group')?.text; const items = group === undefined ? undefined : groups.get(group); @@ -168,17 +173,21 @@ function renderItem(item: Declaration, section: string, hasPropsInterface: boole // the props of a component with an undocumented props type are described // by the paragraphs after the first, e.g. `SelectCheckbox` - const [description, ...props] = renderSummary(doc).join('').split('\n\n'); + const [description, ...props] = doc.summary.split('\n\n'); if (props.length === 0) { throw new Error(`${name} must describe its props after the first paragraph`); } return [title, description, ...renderTags(doc), heading(5, 'Props'), ...props].join('\n\n'); } - const isFunction = node.type !== 'VariableDeclaration'; + const isFunction = !isVariableStatement(node); return [ heading(4, `\`${name}${isFunction ? '()' : ''}\``, name), - codeBlock(isFunction ? getFunctionSignature(name, node) : getVariableSignature(name, node)), + codeBlock( + isFunction + ? getFunctionSignature(name, node as FunctionDeclaration) + : getVariableSignature(name, node) + ), ...renderSummary(doc), ...renderTags(doc) ].join('\n\n'); @@ -192,9 +201,9 @@ function renderType({ name, node, doc }: Declaration, level: number) { ...renderSummary(doc) ]; - if (hasRichMembers(node)) { + if (isInterfaceDeclaration(node) && hasRichMembers(node)) { // a heading per member, as their docs have examples, lists, or several paragraphs - md.push(...renderTags(doc), ...renderMembers(node.body!.body, level + 1, name)); + md.push(...renderTags(doc), ...renderMembers(node.members, level + 1, name)); } else { codeBlockTypes.add(name); md.push(codeBlock(getTypeDeclarations(node)), ...renderTags(doc)); @@ -203,23 +212,24 @@ function renderType({ name, node, doc }: Declaration, level: number) { return md.join('\n\n'); } -function renderMembers(members: Node[], level: number, parent: string): string[] { +function renderMembers(members: NodeArray, level: number, parent: string): string[] { return members.flatMap((member) => { const name = getMemberName(member); - const doc = parseDoc(getComment(member)); - const typeLiteral = findTypeLiteral(member.typeAnnotation); + const doc = getDoc(member); + const typeLiteral = findTypeLiteral(member); // e.g. `editorOptions`, which is an object, has a heading per option if (typeLiteral !== undefined) { return [ heading(level, `\`${name}\``, `${parent}.${name}`), ...renderSummary(doc), ...renderTags(doc), - ...renderMembers(typeLiteral.members!, Math.min(level + 1, 6), `${parent}.${name}`) + ...renderMembers(typeLiteral.members, Math.min(level + 1, 6), `${parent}.${name}`) ]; } + const isOptional = (member as PropertySignatureDeclaration).postfixToken !== undefined; return [ - heading(level, `\`${name}${member.optional === true ? '?' : ''}\``, `${parent}.${name}`), - codeBlock(source(member)), + heading(level, `\`${name}${isOptional ? '?' : ''}\``, `${parent}.${name}`), + codeBlock(member.getText()), ...renderSummary(doc), ...renderTags(doc) ]; @@ -227,7 +237,7 @@ function renderMembers(members: Node[], level: number, parent: string): string[] } function renderSummary({ summary }: Doc) { - return summary === '' ? [] : [convertLinks(summary)]; + return summary === '' ? [] : [summary]; } function renderTags({ tags }: Doc) { @@ -244,166 +254,163 @@ function renderTags({ tags }: Doc) { if (name in labels) return true; throw new Error(`The @${name} tag is not supported in the API reference`); }) - .map(({ name, text }) => `${labels[name]}${convertLinks(text)}`); + .map(({ name, text }) => `${labels[name]}${text}`); } // e.g. `RenderRowProps` function getComponentPropsType(node: Node) { - const signature = - node.type === 'VariableDeclaration' - ? node.declarations![0].id!.typeAnnotation!.typeAnnotation! - : node; - return cleanCode(source(getParams(signature)[0].typeAnnotation!.typeAnnotation!)); + const signature = isVariableStatement(node) ? getVariableDeclaration(node).type! : node; + if (!isFunctionTypeNode(signature) && signature.kind !== SyntaxKind.FunctionDeclaration) { + throw new Error(`${getDeclarationName(node)} must be a function component`); + } + return cleanCode((signature as FunctionDeclaration).parameters[0].type!.getText()); } // e.g. `function renderHeaderCell(props: RenderHeaderCellContentProps): …` -function getFunctionSignature(name: string, node: Node) { - const typeParameters = node.typeParameters == null ? '' : source(node.typeParameters); - const params = getParams(node).map((param) => { +function getFunctionSignature(name: string, node: FunctionDeclaration) { + const params = node.parameters.map((param: ParameterDeclaration) => { // destructured parameters are named `props` - const paramName = param.type === 'Identifier' ? param.name : 'props'; - return `${paramName}: ${source(param.typeAnnotation!.typeAnnotation!)}`; + const paramName = isIdentifier(param.name) ? param.name.text : 'props'; + return `${paramName}: ${param.type!.getText()}`; }); - const returnType = node.returnType == null ? '' : source(node.returnType); - return `function ${name}${typeParameters}(${params.join(', ')})${returnType};`; + const returnType = node.type === undefined ? '' : `: ${node.type.getText()}`; + return `function ${name}${getTypeParameters(node)}(${params.join(', ')})${returnType};`; } // e.g. `const SelectColumn: Column;` or `const SELECT_COLUMN_KEY = 'rdg-select-column';` -function getVariableSignature(name: string, node: Node) { - const declarator = node.declarations![0]; - if (declarator.init !== null && declarator.init !== undefined) { - return `const ${name} = ${source(declarator.init).replaceAll('"', "'")};`; +function getVariableSignature(name: string, node: VariableStatement) { + const { initializer, type } = getVariableDeclaration(node); + if (initializer !== undefined) { + return `const ${name} = ${initializer.getText().replaceAll('"', "'")};`; } - return `const ${name}${source(declarator.id!.typeAnnotation!)};`; + return `const ${name}: ${type!.getText()};`; } -function getParams(node: Node) { - const { params } = node; - return Array.isArray(params) ? params : params!.params; +// e.g. `` +function getTypeParameters(node: { typeParameters?: NodeArray | undefined }) { + const { typeParameters } = node; + if (typeParameters === undefined) return ''; + return `<${typeParameters.map((parameter) => parameter.getText()).join(', ')}>`; } // the declaration of a type: an interface includes the members of the helper interfaces it extends, // e.g. `RenderRowProps` and `BaseRenderRowProps`, and a type alias is followed by the helper types it references, // e.g. `CellKeyDownArgs` and `ActiveCellKeyDownArgs` function getTypeDeclarations(node: Node) { - if (node.type === 'TSInterfaceDeclaration') return getInterfaceDeclaration(node); + if (isInterfaceDeclaration(node)) return getInterfaceDeclaration(node); const referenced = new Set( - Array.from(source(node).matchAll(/\b\w+\b/g), ([name]) => helperTypes.get(name)?.node) + Array.from(node.getText().matchAll(/\b\w+\b/g), ([name]) => helperTypes.get(name)?.node) ); referenced.delete(undefined); referenced.delete(node); return [node, ...referenced] .map((declaration) => - declaration!.type === 'TSInterfaceDeclaration' - ? getInterfaceDeclaration(declaration!) - : source(declaration!) + isInterfaceDeclaration(declaration!) + ? getInterfaceDeclaration(declaration) + : declaration!.getText() ) .join('\n\n'); } -function getInterfaceDeclaration(node: Node) { - if (node.extends?.every((base) => !helperTypes.has(source(base.expression!))) !== false) { - return source(node); +function getInterfaceDeclaration(node: InterfaceDeclaration) { + if (getBaseTypes(node).every((base) => !helperTypes.has(getBaseTypeName(base)))) { + return node.getText(); } const { heritage, members } = getInterfaceParts(node); - const typeParameters = node.typeParameters == null ? '' : source(node.typeParameters); const extendsClause = heritage.length === 0 ? '' : ` extends ${heritage.join(', ')}`; const body = Array.from(members.values(), (member) => ` ${member}`).join('\n'); - return `interface ${node.id!.name}${typeParameters}${extendsClause} {\n${body}\n}`; + return `interface ${node.name.text}${getTypeParameters(node)}${extendsClause} {\n${body}\n}`; } // the base types and members of an interface, with the members of the helper interfaces it extends -function getInterfaceParts(node: Node) { +function getInterfaceParts(node: InterfaceDeclaration) { const heritage: string[] = []; const members = new Map(); - for (const base of node.extends ?? []) { - const helperType = helperTypes.get(source(base.expression!)); - if (helperType?.node.type === 'TSInterfaceDeclaration') { + for (const base of getBaseTypes(node)) { + const helperType = helperTypes.get(getBaseTypeName(base)); + if (helperType !== undefined && isInterfaceDeclaration(helperType.node)) { const parts = getInterfaceParts(helperType.node); heritage.push(...parts.heritage); for (const [name, member] of parts.members) members.set(name, member); } else { - heritage.push(source(base)); + heritage.push(base.getText()); } } - for (const member of node.body!.body) { + for (const member of node.members) { const name = getMemberName(member); - const comment = getComment(member); + const jsDoc = getJSDoc(member); // a redeclared member replaces the inherited one members.delete(name); - members.set(name, `${comment === '' ? '' : `/*${comment}*/\n `}${source(member)}`); + members.set(name, `${jsDoc === undefined ? '' : `${jsDoc.getText()}\n `}${member.getText()}`); } return { heritage, members }; } +function getBaseTypes(node: InterfaceDeclaration): readonly Node[] { + return node.heritageClauses?.flatMap((clause) => clause.types) ?? []; +} + +// e.g. `BaseRenderRowProps` for `BaseRenderRowProps` +function getBaseTypeName(base: Node) { + return /^[\w.]+/.exec(base.getText())![0]; +} + function compareNames(a: Declaration, b: Declaration) { return a.name.localeCompare(b.name); } function isType(node: Node) { - return node.type === 'TSInterfaceDeclaration' || node.type === 'TSTypeAliasDeclaration'; + return isInterfaceDeclaration(node) || isTypeAliasDeclaration(node); } // members with more than a single paragraph can't be shown as comments of a code block -function hasRichMembers(node: Node) { - return ( - node.type === 'TSInterfaceDeclaration' && - node.body!.body.some((member) => { - const { summary, tags } = parseDoc(getComment(member)); - return ( - tags.some((tag) => tag.name !== 'defaultValue') || - summary.includes('\n\n') || - summary.includes('```') || - /^\s*(?:[-*+]|\d+\.) /m.test(summary) - ); - }) - ); +function hasRichMembers(node: InterfaceDeclaration) { + return node.members.some((member) => { + const { summary, tags } = getDoc(member); + return ( + tags.some((tag) => tag.name !== 'defaultValue') || + summary.includes('\n\n') || + summary.includes('```') || + /^\s*(?:[-*+]|\d+\.) /m.test(summary) + ); + }); } // the object type of a member, e.g. `Maybe<{ … }>` -function findTypeLiteral(node: Node | undefined): Node | undefined { - if (node === undefined) return undefined; - if (node.type === 'TSTypeLiteral') return node; - for (const child of [ - node.typeAnnotation, - node.elementType, - ...(node.types ?? []), - ...(node.typeArguments?.params ?? []) - ]) { - const typeLiteral = findTypeLiteral(child); - if (typeLiteral !== undefined) return typeLiteral; - } - return undefined; +function findTypeLiteral(node: Node) { + return node.forEachChild(function find(child): DeclarationNode | undefined { + return isTypeLiteralNode(child) ? child : child.forEachChild(find); + }) as { members: NodeArray } | undefined; } -function addDeclaration(node: Node, statement: Node) { - const name = getDeclarationName(node); - declarations.set(name, { name, node, doc: parseDoc(getComment(statement)) }); +function getDeclarationName(node: Node) { + if (isVariableStatement(node)) return getVariableDeclaration(node).name.getText(); + return (node as InterfaceDeclaration).name.text; } -function getDeclarationName(node: Node) { - return node.id?.name ?? node.declarations![0].id!.name; +function getVariableDeclaration(node: VariableStatement) { + return node.declarationList.declarations[0]; +} + +function getMemberName(member: TypeElement) { + // e.g. `'aria-label'` + return (member as PropertySignatureDeclaration).name.getText().replaceAll(/^['"]|['"]$/g, ''); } -function getMemberName({ key }: Node) { - return key!.type === 'Identifier' ? key!.name! : key!.value!; +function getExportSpecifiers(node: Node) { + if (!isExportDeclaration(node) || node.exportClause?.kind !== SyntaxKind.NamedExports) return []; + return node.exportClause.elements; } // the exported names of the entry point, in order -async function getExportOrder() { - const entry = await readFile(entryPath, 'utf8'); - const names = (parseSync(entryPath, entry).program.body as unknown as Node[]).flatMap( - (statement) => - statement.type === 'ExportNamedDeclaration' - ? (statement as unknown as { specifiers: { exported: { name: string } }[] }).specifiers.map( - ({ exported }) => exported.name - ) - : [] +function getExportOrder(entry: SourceFile) { + const names = entry.statements.flatMap((statement) => + getExportSpecifiers(statement).map((specifier) => specifier.name.getText()) ); for (const name of exportedNames.keys()) { if (!names.includes(name)) @@ -413,44 +420,34 @@ async function getExportOrder() { } // the JSDoc comment directly before the node -function getComment({ start }: Node) { - const comment = comments.findLast( - (comment) => - comment.type === 'Block' && - comment.value.startsWith('*') && - comment.end <= start && - code.slice(comment.end, start).trim() === '' - ); - return comment?.value ?? ''; -} - -function parseDoc(comment: string): Doc { - const summary: string[] = []; - const tags: { name: string; lines: string[] }[] = []; - - forEachLine( - comment - .split('\n') - .map((line) => line.replace(/^\s*\*\s?/, '')) - .join('\n'), - (line, isInCodeBlock) => { - const tag = isInCodeBlock ? null : /^@(\w+)\s?(.*)$/.exec(line); - if (tag === null) { - (tags.at(-1)?.lines ?? summary).push(line); - } else { - tags.push({ name: tag[1], lines: [tag[2]] }); - } - } - ); +function getJSDoc(node: Node) { + return node.jsDoc?.at(-1) as JSDoc | undefined; +} +function getDoc(node: Node): Doc { + const jsDoc = getJSDoc(node); return { - summary: summary.join('\n').trim(), - tags: tags.map(({ name, lines }) => ({ name, text: lines.join('\n').trim() })) + summary: renderComment(jsDoc?.comment), + tags: (jsDoc?.tags ?? []).map((tag) => ({ + name: tag.tagName.text, + text: renderComment(tag.comment) + })) }; } -function source({ start, end }: Node) { - return code.slice(start, end); +// the text of a comment, with its links as "[`width`](#!Column.width)", resolved by `resolveLinks` +function renderComment(comment: NodeArray | undefined) { + if (comment === undefined) return ''; + return comment + .map((part) => { + if (isJSDocText(part)) return part.text; + const target = part.name!.getText(); + // e.g. `| width` for `{@linkcode Column.width | width}` + const label = part.text.replace(/^\s*\|/, '').trim(); + return `[\`${label === '' ? target : label}\`](#!${target})`; + }) + .join('') + .trim(); } function heading(level: number, text: string, key?: string) { @@ -469,18 +466,13 @@ function cleanCode(text: string) { return text .replaceAll(/^(?:export )?declare /gm, '') .replaceAll('import("react").', 'React.') - .replaceAll(linkTag, (_, target: string, label: string | undefined) => label ?? target) + .replaceAll( + /\{@link(?:code|plain)?\s+([^}|]+?)\s*(?:\|\s*([^}]+?)\s*)?\}/g, + (_, target: string, label: string | undefined) => label ?? target + ) .replaceAll(/NoInfer<([^<>]+)>/g, '$1'); } -// `{@linkcode Column.width | width}` -> "[`width`](#!Column.width)", resolved by `resolveLinks` -function convertLinks(text: string) { - return text.replaceAll( - linkTag, - (_, target: string, label: string | undefined) => `[\`${label ?? target}\`](#!${target})` - ); -} - // replace the links to items and members, e.g. `#!Column` and `#!Column.width`, // with the anchors GitHub generates for their headings, which are numbered across the whole README. // Links in the hand-written sections of the README can link to an item or member with its name as From 0a42091ec18706679941c1e5adfc52ed8878da2b Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 19:47:45 -0500 Subject: [PATCH 15/22] Set the sections of the API reference in `src/index.ts` instead of `@group` tags Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- scripts/generateApiDocs.ts | 58 ++++++++++++------- src/Cell.tsx | 2 - src/Columns.tsx | 4 -- src/DataGrid.tsx | 8 --- src/DataGridRenderersContext.ts | 2 - src/Row.tsx | 2 - src/TreeDataGrid.tsx | 4 -- src/cellRenderers/SelectCheckbox.tsx | 2 - src/cellRenderers/renderCheckbox.tsx | 2 - src/cellRenderers/renderToggleGroup.tsx | 4 -- src/cellRenderers/renderValue.tsx | 2 - src/editors/renderTextEditor.tsx | 2 - src/hooks/useRowSelection.ts | 4 -- src/index.ts | 13 ++++- src/renderHeaderCell.tsx | 2 - src/sortStatus.tsx | 4 -- src/types.ts | 76 ------------------------- vite.config.ts | 4 +- 19 files changed, 53 insertions(+), 144 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7e6db79177..169910773a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ website/ # demo site (Vite + TanStack Router) ## Conventions - **Public API** — all exports flow through `src/index.ts`. Keep `README.md` in sync with user-facing changes. -- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. Every export from `src/index.ts` needs a `@group` tag with one of the sections in `scripts/generateApiDocs.ts` (Components, Hooks, Render Functions, Context, Other, Types), and the order of the exports is the order of the API reference. Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tags; add new tags to `definedTags` of `jsdoc/check-tag-names` in `vite.config.ts`. In the hand-written sections of the README, give links to API members the member as title, e.g., ``[`width`](#width "Column.width")``, so `vp run docs` keeps their anchor up to date. +- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. `src/index.ts` sets the layout of the API reference: the exports are listed in their order, under the section of the comment above them, one of the sections in `scripts/generateApiDocs.ts` (`// Components`, `// Hooks`, `// Render Functions`, `// Context`, `// Other`, `// Types`). Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tags; add new tags to `definedTags` of `jsdoc/check-tag-names` in `vite.config.ts`. In the hand-written sections of the README, give links to API members the member as title, e.g., ``[`width`](#width "Column.width")``, so `vp run docs` keeps their anchor up to date. - **Docs** — keep `AGENTS.md` in sync with tooling, conventions, or architectural changes. - **Default renderers** — `DataGridRenderersContext` allows overriding default renderers (`renderCheckbox`, `renderSortStatus`, `renderRow`, `renderCell`, `noRowsFallback`) without prop-drilling. - **TypeScript strict** with `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, `erasableSyntaxOnly`. Distinguish missing properties from `undefined` values. diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index f52db59711..51dfc82cfb 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -26,6 +26,7 @@ import { isTypeLiteralNode, isVariableStatement } from 'typescript/ast/is'; +import { getLeadingCommentRanges } from 'typescript/ast/scanner'; import { API } from 'typescript/sync'; // Generates the API reference of the README from the declarations and JSDoc comments of `lib/index.d.ts`, @@ -36,7 +37,7 @@ const entryPath = 'src/index.ts'; const readmePath = 'README.md'; const startMarker = ''; const endMarker = ''; -// the `@group` tags of the exports +// the sections of the API reference, set by comments above the exports of the entry point, e.g. `// Hooks` const sections = ['Components', 'Hooks', 'Render Functions', 'Context', 'Other', 'Types']; interface Doc { @@ -85,16 +86,12 @@ for (const statement of declarationsFile.sourceFile.statements) { declarations.set(name, { name, node: statement, doc: getDoc(statement) }); } -// group the exports by their `@group` tag, in the order they are exported from the entry point +// group the exports by their section, in the order they are exported from the entry point const groups = new Map(sections.map((section) => [section, []])); -for (const name of getExportOrder(entryFile.sourceFile)) { - const declaration = declarations.get(exportedNames.get(name)!)!; - const group = declaration.doc.tags.find((tag) => tag.name === 'group')?.text; - const items = group === undefined ? undefined : groups.get(group); - if (items === undefined) { - throw new Error(`${name} must have a @group tag with one of: ${sections.join(', ')}`); - } - items.push({ ...declaration, name }); +for (const { name, section } of getExports(entryFile.sourceFile)) { + const declaration = declarations.get(exportedNames.get(name)!); + if (declaration === undefined) throw new Error(`${name} is not exported by ${declarationsPath}`); + groups.get(section)!.push({ ...declaration, name }); } // the types that are referenced by the exports, but not exported: @@ -124,7 +121,13 @@ for (const [section, items] of groups) { items.filter(({ node }) => isType(node)).map((item) => [item.name, item]) ); for (const item of items) { - if (section === 'Components' && isType(item.node)) continue; + if (section === 'Components' && isType(item.node)) { + // the props interface of a component is listed after it + if (!items.some(({ name }) => item.name === `${name}Props`)) { + throw new Error(`${item.name} must be the props of a component, or be listed under Types`); + } + continue; + } // e.g. `DataGridProps` after `DataGrid` const propsInterface = section === 'Components' ? propsInterfaces.get(`${item.name}Props`) : undefined; @@ -249,8 +252,8 @@ function renderTags({ tags }: Doc) { }; return tags .filter(({ name }) => { - // `@group` sets the section, and the type parameters are described in the "Generics" section - if (name === 'group' || name === 'typeParam') return false; + // the type parameters are described in the "Generics" section + if (name === 'typeParam') return false; if (name in labels) return true; throw new Error(`The @${name} tag is not supported in the API reference`); }) @@ -407,16 +410,31 @@ function getExportSpecifiers(node: Node) { return node.exportClause.elements; } -// the exported names of the entry point, in order -function getExportOrder(entry: SourceFile) { - const names = entry.statements.flatMap((statement) => - getExportSpecifiers(statement).map((specifier) => specifier.name.getText()) - ); +// the exported names of the entry point in order, with the section of the comment above them, e.g. `// Hooks` +function getExports(entry: SourceFile) { + const exports: { name: string; section: string }[] = []; + let section: string | undefined; + for (const statement of entry.statements) { + const specifiers = getExportSpecifiers(statement); + if (specifiers.length === 0) continue; + const comment = getLeadingCommentRanges(entry.text, statement.pos)?.at(-1); + if (comment !== undefined) { + section = entry.text.slice(comment.pos, comment.end).replace(/^\/\/\s*/, ''); + if (!sections.includes(section)) { + throw new Error(`"${section}" in ${entryPath} must be one of: ${sections.join(', ')}`); + } + } + if (section === undefined) { + throw new Error(`The exports of ${entryPath} must follow a section comment, e.g. // Hooks`); + } + for (const specifier of specifiers) exports.push({ name: specifier.name.getText(), section }); + } for (const name of exportedNames.keys()) { - if (!names.includes(name)) + if (!exports.some((item) => item.name === name)) { throw new Error(`${name} must be exported by name from ${entryPath}`); + } } - return names; + return exports; } // the JSDoc comment directly before the node diff --git a/src/Cell.tsx b/src/Cell.tsx index 4254e1c5ed..89266b7cc8 100644 --- a/src/Cell.tsx +++ b/src/Cell.tsx @@ -126,8 +126,6 @@ function Cell({ /** * The default cell component. Can be wrapped via the `renderers.renderCell` prop. - * - * @group Components */ const MemoCell = memo(Cell) as (props: RenderCellProps) => React.JSX.Element; diff --git a/src/Columns.tsx b/src/Columns.tsx index 4ffb6abe15..781eaa5159 100644 --- a/src/Columns.tsx +++ b/src/Columns.tsx @@ -16,8 +16,6 @@ import { SelectCheckbox } from './cellRenderers'; * * const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN_KEY); * ``` - * - * @group Other */ export const SELECT_COLUMN_KEY = 'rdg-select-column'; @@ -94,8 +92,6 @@ function GroupSelectCell({ row, tabIndex }: RenderGroupCellContentProps * ); * } * ``` - * - * @group Other */ // oxlint-disable-next-line typescript/no-explicit-any export const SelectColumn: Column = { diff --git a/src/DataGrid.tsx b/src/DataGrid.tsx index 42fedd36b7..35f0e7e546 100644 --- a/src/DataGrid.tsx +++ b/src/DataGrid.tsx @@ -84,8 +84,6 @@ import SummaryRow from './SummaryRow'; * Default options applied to all columns. * * @see {@linkcode DataGridProps.defaultColumnOptions | defaultColumnOptions} prop on `` - * - * @group Types */ export type DefaultColumnOptions = Pick< Column, @@ -119,8 +117,6 @@ export type DefaultColumnOptions = Pick< * ``` * * @see {@linkcode DataGridProps.ref | ref} prop on `` - * - * @group Types */ export interface DataGridHandle { element: HTMLDivElement | null; @@ -132,8 +128,6 @@ export interface DataGridHandle { * @typeParam R - Row type * @typeParam SR - Summary row type * @typeParam K - Row key type - * - * @group Components */ export interface DataGridProps { /** @@ -724,8 +718,6 @@ export interface DataGridProps { * @typeParam R - Row type * @typeParam SR - Summary row type * @typeParam K - Row key type - * - * @group Components */ export function DataGrid(props: DataGridProps) { const { diff --git a/src/DataGridRenderersContext.ts b/src/DataGridRenderersContext.ts index 4984bd05e9..7714ae40ca 100644 --- a/src/DataGridRenderersContext.ts +++ b/src/DataGridRenderersContext.ts @@ -34,8 +34,6 @@ import type { Maybe, Renderers } from './types'; * ); * } * ``` - * - * @group Context */ // oxlint-disable-next-line typescript/no-explicit-any export const DataGridRenderersContext = createContext>>(undefined); diff --git a/src/Row.tsx b/src/Row.tsx index 40fb96412b..25d3285529 100644 --- a/src/Row.tsx +++ b/src/Row.tsx @@ -88,8 +88,6 @@ function Row({ /** * The default row component. Can be wrapped via the `renderers.renderRow` prop. - * - * @group Components */ const MemoRow = memo(Row) as (props: RenderRowProps) => React.JSX.Element; diff --git a/src/TreeDataGrid.tsx b/src/TreeDataGrid.tsx index 7b96f598cf..f20e33a658 100644 --- a/src/TreeDataGrid.tsx +++ b/src/TreeDataGrid.tsx @@ -31,8 +31,6 @@ import { defaultRenderRow } from './Row'; * @typeParam R - Row type * @typeParam SR - Summary row type * @typeParam K - Row key type - * - * @group Components */ export interface TreeDataGridProps extends Omit< DataGridProps, @@ -178,8 +176,6 @@ type ReadonlyGroupByMap = ReadonlyMap>; * @typeParam R - Row type * @typeParam SR - Summary row type * @typeParam K - Row key type - * - * @group Components */ export function TreeDataGrid({ columns: rawColumns, diff --git a/src/cellRenderers/SelectCheckbox.tsx b/src/cellRenderers/SelectCheckbox.tsx index 21b1908dc2..502f0f4716 100644 --- a/src/cellRenderers/SelectCheckbox.tsx +++ b/src/cellRenderers/SelectCheckbox.tsx @@ -15,8 +15,6 @@ interface SelectCheckboxProps extends SharedInputProps { * A component for rendering row selection checkboxes. * * The same props as {@linkcode RenderCheckboxProps}, with `value: boolean` in place of `checked`. - * - * @group Components */ export function SelectCheckbox({ value, diff --git a/src/cellRenderers/renderCheckbox.tsx b/src/cellRenderers/renderCheckbox.tsx index a3ac92824c..ffde8a5ffd 100644 --- a/src/cellRenderers/renderCheckbox.tsx +++ b/src/cellRenderers/renderCheckbox.tsx @@ -35,8 +35,6 @@ const checkboxClassname = `rdg-checkbox-input ${checkbox}`; * }} * />; * ``` - * - * @group Render Functions */ export function renderCheckbox({ onChange, indeterminate, ...props }: RenderCheckboxProps) { function handleChange(e: React.ChangeEvent) { diff --git a/src/cellRenderers/renderToggleGroup.tsx b/src/cellRenderers/renderToggleGroup.tsx index 1ff6e6e12f..702fd48d4b 100644 --- a/src/cellRenderers/renderToggleGroup.tsx +++ b/src/cellRenderers/renderToggleGroup.tsx @@ -41,8 +41,6 @@ const caretClassname = `rdg-caret ${caret}`; * } * ]; * ``` - * - * @group Render Functions */ export function renderToggleGroup(props: RenderGroupCellContentProps) { return ; @@ -50,8 +48,6 @@ export function renderToggleGroup(props: RenderGroupCellContentProps({ groupKey, diff --git a/src/cellRenderers/renderValue.tsx b/src/cellRenderers/renderValue.tsx index 908cf44b55..0a10dbd3d0 100644 --- a/src/cellRenderers/renderValue.tsx +++ b/src/cellRenderers/renderValue.tsx @@ -15,8 +15,6 @@ import type { RenderCellContentProps } from '../types'; * } * ]; * ``` - * - * @group Render Functions */ export function renderValue(props: RenderCellContentProps) { return props.row?.[props.column.key as keyof R] as React.ReactNode; diff --git a/src/editors/renderTextEditor.tsx b/src/editors/renderTextEditor.tsx index 527c224bfe..90eda71805 100644 --- a/src/editors/renderTextEditor.tsx +++ b/src/editors/renderTextEditor.tsx @@ -53,8 +53,6 @@ function autoFocusAndSelect(input: HTMLInputElement | null) { * } * ]; * ``` - * - * @group Render Functions */ export function renderTextEditor({ row, diff --git a/src/hooks/useRowSelection.ts b/src/hooks/useRowSelection.ts index 407a1ecd1b..ec3d6d9031 100644 --- a/src/hooks/useRowSelection.ts +++ b/src/hooks/useRowSelection.ts @@ -46,8 +46,6 @@ RowSelectionChangeContext.displayName = 'RowSelectionChangeContext'; * ); * } * ``` - * - * @group Hooks */ export function useRowSelection() { const rowSelectionContext = use(RowSelectionContext); @@ -112,8 +110,6 @@ HeaderRowSelectionChangeContext.displayName = 'HeaderRowSelectionChangeContext'; * ); * } * ``` - * - * @group Hooks */ export function useHeaderRowSelection() { const headerRowSelectionContext = use(HeaderRowSelectionContext); diff --git a/src/index.ts b/src/index.ts index 592db3a749..d91584eef2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,19 +1,30 @@ import './style/layers.css'; -// the order of the exports is the order of the API reference in the README +// the API reference in the README lists the exports in this order, under the section of the comment above them +// Components export { DataGrid, type DataGridProps } from './DataGrid'; export { TreeDataGrid, type TreeDataGridProps } from './TreeDataGrid'; export { Row } from './Row'; export { Cell } from './Cell'; export { SelectCheckbox, ToggleGroup } from './cellRenderers'; + +// Hooks export { useHeaderRowSelection, useRowSelection } from './hooks'; + +// Render Functions export { renderHeaderCell } from './renderHeaderCell'; export { renderTextEditor } from './editors/renderTextEditor'; export { renderSortIcon, renderSortPriority } from './sortStatus'; export { renderCheckbox, renderToggleGroup, renderValue } from './cellRenderers'; + +// Context export { DataGridRenderersContext } from './DataGridRenderersContext'; + +// Other export { SelectColumn, SELECT_COLUMN_KEY } from './Columns'; + +// Types export type { Column, ColumnGroup, diff --git a/src/renderHeaderCell.tsx b/src/renderHeaderCell.tsx index 5cae692330..c51efea59b 100644 --- a/src/renderHeaderCell.tsx +++ b/src/renderHeaderCell.tsx @@ -35,8 +35,6 @@ const headerSortNameClassname = `rdg-header-sort-name ${headerSortName}`; * } * ]; * ``` - * - * @group Render Functions */ export function renderHeaderCell({ column, diff --git a/src/sortStatus.tsx b/src/sortStatus.tsx index c9bf5a4ab0..ca3a46c99a 100644 --- a/src/sortStatus.tsx +++ b/src/sortStatus.tsx @@ -25,8 +25,6 @@ export default function renderSortStatus({ sortDirection, priority }: RenderSort /** * Renders the sort direction arrow icon. - * - * @group Render Functions */ export function renderSortIcon({ sortDirection }: RenderSortIconProps) { if (sortDirection === undefined) return null; @@ -40,8 +38,6 @@ export function renderSortIcon({ sortDirection }: RenderSortIconProps) { /** * Renders the sort priority number for multi-column sorting. - * - * @group Render Functions */ export function renderSortPriority({ priority }: RenderSortPriorityProps) { return priority; diff --git a/src/types.ts b/src/types.ts index 1e507dfa36..558bc838d3 100644 --- a/src/types.ts +++ b/src/types.ts @@ -15,8 +15,6 @@ export type StateSetter = React.Dispatch>; * Defines the configuration for a column in the grid. * * @see {@linkcode DataGridProps.columns | columns} prop on `` - * - * @group Types */ export interface Column { /** The name of the column. Displayed in the header cell by default. */ @@ -213,8 +211,6 @@ export interface Column { * Extends `Column` with additional computed properties used internally by the grid. This is the type passed to render functions. Every `Column` property is set: the ones with a default value, like `width` and `renderCell`, are resolved to their default value when not set, and the others are `undefined` when not set. * * @see {@linkcode Column}, {@linkcode DataGridProps.onColumnResize | onColumnResize} prop on `` - * - * @group Types */ export interface CalculatedColumn extends Column { /** The column group that contains the column, or `undefined` if the column is not in a group */ @@ -264,8 +260,6 @@ export interface CalculatedColumn extends Column { * ``` * * @see {@linkcode ColumnOrColumnGroup} - * - * @group Types */ export interface ColumnGroup { /** The name of the column group. It will be displayed in the header cell */ @@ -278,8 +272,6 @@ export interface ColumnGroup { * Represents a parent column group in the calculated column structure. * * @see {@linkcode CalculatedColumn} - * - * @group Types */ export interface CalculatedColumnParent { readonly name: string | ReactElement; @@ -294,8 +286,6 @@ export interface CalculatedColumnParent { * Union type representing either a `Column` or a `ColumnGroup`. * * @see {@linkcode DataGridProps.columns | columns} prop on `` - * - * @group Types */ export type ColumnOrColumnGroup = Column | ColumnGroup; @@ -303,8 +293,6 @@ export type ColumnOrColumnGroup = Column | ColumnGroup = | CalculatedColumnParent @@ -340,8 +328,6 @@ export interface Position { * ``` * * @see {@linkcode Column.renderCell | column.renderCell}, {@linkcode renderValue} function - * - * @group Types */ export interface RenderCellContentProps { column: CalculatedColumn; @@ -356,8 +342,6 @@ export interface RenderCellContentProps { * Props passed to summary cell content renderers (`column.renderSummaryCell`). * * @see {@linkcode Column.renderSummaryCell | column.renderSummaryCell} - * - * @group Types */ export interface RenderSummaryCellContentProps { column: CalculatedColumn; @@ -369,8 +353,6 @@ export interface RenderSummaryCellContentProps { * Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. * * @see {@linkcode Column.renderGroupCell | column.renderGroupCell}, {@linkcode renderToggleGroup} function, {@linkcode ToggleGroup | } - * - * @group Types */ export interface RenderGroupCellContentProps { groupKey: unknown; @@ -402,8 +384,6 @@ export interface RenderGroupCellContentProps { * ``` * * @see {@linkcode Column.renderEditCell | column.renderEditCell}, {@linkcode renderTextEditor} function - * - * @group Types */ export interface RenderEditCellContentProps { column: CalculatedColumn; @@ -417,8 +397,6 @@ export interface RenderEditCellContentProps { * Props passed to custom header cell content renderers (`column.renderHeaderCell`). * * @see {@linkcode Column.renderHeaderCell | column.renderHeaderCell}, {@linkcode renderHeaderCell} function - * - * @group Types */ export interface RenderHeaderCellContentProps { column: CalculatedColumn; @@ -442,8 +420,6 @@ interface BaseRenderCellProps * Props passed to the cell renderer when using `renderers.renderCell`. * * @see {@linkcode DataGridProps.renderers | renderers.renderCell}, {@linkcode Cell | } - * - * @group Types */ export interface RenderCellProps extends BaseRenderCellProps { column: CalculatedColumn; @@ -491,8 +467,6 @@ export type CellEvent> = E & { * ``` * * @see {@linkcode DataGridProps.onCellMouseDown | onCellMouseDown}, {@linkcode DataGridProps.onCellClick | onCellClick}, {@linkcode DataGridProps.onCellDoubleClick | onCellDoubleClick}, and {@linkcode DataGridProps.onCellContextMenu | onCellContextMenu} props on `` - * - * @group Types */ export type CellMouseEvent = CellEvent>; @@ -500,8 +474,6 @@ export type CellMouseEvent = CellEvent>; * Extends `React.KeyboardEvent` with grid-specific methods. * * @see {@linkcode DataGridProps.onCellKeyDown | onCellKeyDown} prop on `` - * - * @group Types */ export type CellKeyboardEvent = CellEvent>; @@ -526,8 +498,6 @@ export type CellClipboardEvent = React.ClipboardEvent; * ``` * * @see {@linkcode DataGridProps.onCellMouseDown | onCellMouseDown}, {@linkcode DataGridProps.onCellClick | onCellClick}, {@linkcode DataGridProps.onCellDoubleClick | onCellDoubleClick}, and {@linkcode DataGridProps.onCellContextMenu | onCellContextMenu} props on `` - * - * @group Types */ export interface CellMouseArgs { /** The column object of the cell. */ @@ -577,8 +547,6 @@ export interface EditCellKeyDownArgs { * ``` * * @see {@linkcode DataGridProps.onCellKeyDown | onCellKeyDown} prop on `` - * - * @group Types */ export type CellKeyDownArgs = | ActiveCellKeyDownArgs @@ -588,8 +556,6 @@ export type CellKeyDownArgs = * Arguments passed to `onActivePositionChange`. * * @see {@linkcode DataGridProps.onActivePositionChange | onActivePositionChange} prop on `` - * - * @group Types */ export interface PositionChangeArgs { /** row index of the active position */ @@ -641,8 +607,6 @@ export interface BaseRenderRowProps extends BaseRenderCellProps * Props passed to custom row renderers. * * @see {@linkcode DataGridProps.renderers | renderers.renderRow}, {@linkcode Row | } - * - * @group Types */ export interface RenderRowProps extends BaseRenderRowProps { row: R; @@ -657,8 +621,6 @@ export interface RenderRowProps extends BaseRenderRowProps` - * - * @group Types */ export interface RowsChangeData { /** Indexes of the rows that changed */ @@ -671,8 +633,6 @@ export interface RowsChangeData { * Event object for row selection changes. * * @see {@linkcode useRowSelection} hook - * - * @group Types */ export interface SelectRowEvent { row: R; @@ -684,8 +644,6 @@ export interface SelectRowEvent { * Event object for header row selection changes. * * @see {@linkcode useHeaderRowSelection} hook - * - * @group Types */ export interface SelectHeaderRowEvent { checked: boolean; @@ -695,8 +653,6 @@ export interface SelectHeaderRowEvent { * Event object for drag-fill operations. * * @see {@linkcode DataGridProps.onFill | onFill} prop on `` - * - * @group Types */ export interface FillEvent { columnKey: string; @@ -713,16 +669,12 @@ interface CellCopyPasteArgs { * Arguments passed to `onCellCopy`. * * @see {@linkcode DataGridProps.onCellCopy | onCellCopy} prop on `` - * - * @group Types */ export type CellCopyArgs = CellCopyPasteArgs; /** * Arguments passed to `onCellPaste`. * * @see {@linkcode DataGridProps.onCellPaste | onCellPaste} prop on `` - * - * @group Types */ export type CellPasteArgs = CellCopyPasteArgs; @@ -747,8 +699,6 @@ export interface GroupRow { * Describes a sorted column. * * @see {@linkcode DataGridProps.sortColumns | sortColumns} and {@linkcode DataGridProps.onSortColumnsChange | onSortColumnsChange} props on `` - * - * @group Types */ export interface SortColumn { readonly columnKey: string; @@ -760,14 +710,10 @@ export type CellNavigationMode = 'NONE' | 'CHANGE_ROW'; * Whether a column is frozen, and on which edge. * * @see {@linkcode Column.frozen | column.frozen} - * - * @group Types */ export type ColumnFrozen = boolean | 'start' | 'end'; /** * @see {@linkcode SortColumn} - * - * @group Types */ export type SortDirection = 'ASC' | 'DESC'; @@ -793,8 +739,6 @@ export type SortDirection = 'ASC' | 'DESC'; * ``` * * @see {@linkcode Column.colSpan | column.colSpan} - * - * @group Types */ export type ColSpanArgs = | { readonly type: 'HEADER' } @@ -817,8 +761,6 @@ export type ColSpanArgs = * ``` * * @see {@linkcode TreeDataGridProps.rowHeight | rowHeight} prop on `` - * - * @group Types */ export type RowHeightArgs = { type: 'ROW'; row: R } | { type: 'GROUP'; row: GroupRow }; @@ -826,8 +768,6 @@ export type RowHeightArgs = { type: 'ROW'; row: R } | { type: 'GROUP'; row: G * Props for custom sort icon renderers. * * @see {@linkcode renderSortIcon} function - * - * @group Types */ export interface RenderSortIconProps { /** The sort direction of the column, or `undefined` if it is not sorted */ @@ -838,8 +778,6 @@ export interface RenderSortIconProps { * Props for custom sort priority renderers. * * @see {@linkcode renderSortPriority} function - * - * @group Types */ export interface RenderSortPriorityProps { /** The column's position in `sortColumns`, starting at 1, when sorting by multiple columns, or `undefined` otherwise */ @@ -850,8 +788,6 @@ export interface RenderSortPriorityProps { * Props for custom sort status renderers. * * @see {@linkcode DataGridProps.renderers | renderers.renderSortStatus} - * - * @group Types */ export interface RenderSortStatusProps extends RenderSortIconProps, RenderSortPriorityProps {} @@ -859,8 +795,6 @@ export interface RenderSortStatusProps extends RenderSortIconProps, RenderSortPr * Props for custom checkbox renderers. * * @see {@linkcode renderCheckbox} function, {@linkcode DataGridProps.renderers | renderers.renderCheckbox}, {@linkcode SelectCheckbox | } - * - * @group Types */ export interface RenderCheckboxProps { /** Whether the checkbox is checked */ @@ -883,8 +817,6 @@ export interface RenderCheckboxProps { * Custom renderer configuration for the grid. * * @see {@linkcode DataGridProps.renderers | renderers} prop on ``, {@linkcode DataGridRenderersContext} - * - * @group Types */ export interface Renderers { readonly renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; @@ -898,8 +830,6 @@ export interface Renderers { * Options for programmatically updating the grid's active position. * * @see {@linkcode DataGridHandle}, {@linkcode CellKeyDownArgs} - * - * @group Types */ export interface SetActivePositionOptions { enableEditor?: Maybe; @@ -910,8 +840,6 @@ export interface SetActivePositionOptions { * Represents a single column's width. * * @see {@linkcode ColumnWidths} - * - * @group Types */ export interface ColumnWidth { /** `'resized'` if the user resized the column, or `'measured'` if the grid measured it */ @@ -924,8 +852,6 @@ export interface ColumnWidth { * A map of column widths. * * @see {@linkcode DataGridProps.columnWidths | columnWidths} and {@linkcode DataGridProps.onColumnWidthsChange | onColumnWidthsChange} props on `` - * - * @group Types */ export type ColumnWidths = ReadonlyMap; @@ -933,8 +859,6 @@ export type ColumnWidths = ReadonlyMap; * Text direction of the grid. * * @see {@linkcode DataGridProps.direction | direction} prop on `` - * - * @group Types */ export type Direction = 'ltr' | 'rtl'; diff --git a/vite.config.ts b/vite.config.ts index 5e1f64d2da..f53130a26f 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -572,8 +572,8 @@ copy( 'jsdoc/check-tag-names': [ 'warn', { - // TSDoc tags, and `@group`, which sets the section of the README's API reference - definedTags: ['defaultValue', 'group', 'typeParam'] + // TSDoc tags + definedTags: ['defaultValue', 'typeParam'] } ], 'jsdoc/empty-tags': 'warn', From c07cfbfa17a857cedcc57bf26edb894828e5b22c Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Thu, 22 Oct 2026 20:19:45 -0500 Subject: [PATCH 16/22] Fail the API reference generation instead of dropping content in more cases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Render `@see Foo` as a link, check the links in the comments of code blocks, catch setext headings in JSDoc, fail on interfaces with a heading per member that extend undocumented types, and only show object types as nested options through `Maybe<…>` and unions. Co-Authored-By: Claude Opus 5.5 --- scripts/generateApiDocs.ts | 54 ++++++++++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 11 deletions(-) diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index 51dfc82cfb..84aa37f837 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -2,17 +2,18 @@ import { readFile, writeFile } from 'node:fs/promises'; import GithubSlugger from 'github-slugger'; import { SyntaxKind } from 'typescript/ast'; import type { - Declaration as DeclarationNode, FunctionDeclaration, InterfaceDeclaration, JSDoc, JSDocComment, + JSDocSeeTag, NodeArray, Node, ParameterDeclaration, PropertySignatureDeclaration, SourceFile, TypeElement, + TypeLiteralNode, VariableStatement } from 'typescript/ast'; import { @@ -24,6 +25,8 @@ import { isJSDocText, isTypeAliasDeclaration, isTypeLiteralNode, + isTypeReferenceNode, + isUnionTypeNode, isVariableStatement } from 'typescript/ast/is'; import { getLeadingCommentRanges } from 'typescript/ast/scanner'; @@ -113,6 +116,8 @@ groups const generatedHeadings: GeneratedHeading[] = []; // the types shown as a code block, whose members link to the type const codeBlockTypes = new Set(); +// the targets of the links in the comments of code blocks, which are shown as text but must exist +const codeBlockLinks = new Set(); const markdown: string[] = []; for (const [section, items] of groups) { @@ -206,6 +211,9 @@ function renderType({ name, node, doc }: Declaration, level: number) { if (isInterfaceDeclaration(node) && hasRichMembers(node)) { // a heading per member, as their docs have examples, lists, or several paragraphs + if (getBaseTypes(node).some((base) => helperTypes.has(getBaseTypeName(base)))) { + throw new Error(`${name} must not extend undocumented types, as their members would be lost`); + } md.push(...renderTags(doc), ...renderMembers(node.members, level + 1, name)); } else { codeBlockTypes.add(name); @@ -219,7 +227,7 @@ function renderMembers(members: NodeArray, level: number, parent: s return members.flatMap((member) => { const name = getMemberName(member); const doc = getDoc(member); - const typeLiteral = findTypeLiteral(member); + const typeLiteral = findTypeLiteral((member as PropertySignatureDeclaration).type); // e.g. `editorOptions`, which is an object, has a heading per option if (typeLiteral !== undefined) { return [ @@ -385,10 +393,11 @@ function hasRichMembers(node: InterfaceDeclaration) { } // the object type of a member, e.g. `Maybe<{ … }>` -function findTypeLiteral(node: Node) { - return node.forEachChild(function find(child): DeclarationNode | undefined { - return isTypeLiteralNode(child) ? child : child.forEachChild(find); - }) as { members: NodeArray } | undefined; +function findTypeLiteral(node: Node | undefined): TypeLiteralNode | undefined { + if (node === undefined || isTypeLiteralNode(node)) return node; + // not in function types, e.g. `(args: { … }) => void` + if (isTypeReferenceNode(node) || isUnionTypeNode(node)) return node.forEachChild(findTypeLiteral); + return undefined; } function getDeclarationName(node: Node) { @@ -446,10 +455,18 @@ function getDoc(node: Node): Doc { const jsDoc = getJSDoc(node); return { summary: renderComment(jsDoc?.comment), - tags: (jsDoc?.tags ?? []).map((tag) => ({ - name: tag.tagName.text, - text: renderComment(tag.comment) - })) + tags: (jsDoc?.tags ?? []).map((tag) => { + // e.g. `Column` for `@see Column` + const nameExpression = (tag as Partial).nameExpression?.getText(); + const text = renderComment(tag.comment); + return { + name: tag.tagName.text, + text: + nameExpression === undefined + ? text + : `[\`${nameExpression}\`](#!${nameExpression}) ${text}`.trim() + }; + }) }; } @@ -486,7 +503,10 @@ function cleanCode(text: string) { .replaceAll('import("react").', 'React.') .replaceAll( /\{@link(?:code|plain)?\s+([^}|]+?)\s*(?:\|\s*([^}]+?)\s*)?\}/g, - (_, target: string, label: string | undefined) => label ?? target + (_, target: string, label: string | undefined) => { + codeBlockLinks.add(target); + return label ?? target; + } ) .replaceAll(/NoInfer<([^<>]+)>/g, '$1'); } @@ -499,7 +519,18 @@ function resolveLinks(precedingMarkdown: string, api: string, followingMarkdown: const slugger = new GithubSlugger(); const anchors = new Map(); const slugHeadings = (markdown: string, headings?: GeneratedHeading[]) => { + let previousLine = ''; forEachLine(markdown, (line, isInCodeBlock) => { + // e.g. "Usage" followed by "---", which the generator never writes + if ( + headings !== undefined && + !isInCodeBlock && + /^ {0,3}(?:=+|-+)\s*$/.test(line) && + previousLine.trim() !== '' + ) { + throw new Error(`The heading "${previousLine}" must not be in a JSDoc comment`); + } + previousLine = isInCodeBlock ? '' : line; const match = isInCodeBlock ? null : /^#{1,6} (.+)$/.exec(line); if (match === null) return; const anchor = slugger.slug(match[1].replaceAll('`', '')); @@ -526,6 +557,7 @@ function resolveLinks(precedingMarkdown: string, api: string, followingMarkdown: if (anchor === undefined) throw new Error(`The link to ${target} does not match any heading`); return anchor; }; + for (const target of codeBlockLinks) getAnchor(target); return `${precedingMarkdown}\n\n${api}\n\n${followingMarkdown}` .replaceAll(/\]\(#!([^)]+)\)/g, (_, target: string) => `](#${getAnchor(target)})`) From 31d6b14b965ba36d1351c0f3669dce3c8eb0c890 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Tue, 27 Oct 2026 20:51:11 -0500 Subject: [PATCH 17/22] Address review comments on the API docs Document `SelectCheckboxProps` and link to it, start the hooks' `@returns` with a sentence so the list renders in editor hovers, link `` and `` to `Renderers`, and fix the anchors of the keyboard shortcuts section. Co-Authored-By: Claude Opus 5.5 --- README.md | 48 +++++++++++++++++++--------- scripts/generateApiDocs.ts | 25 ++++++--------- src/Cell.tsx | 2 +- src/Row.tsx | 2 +- src/cellRenderers/SelectCheckbox.tsx | 11 +++---- src/hooks/useRowSelection.ts | 4 +-- 6 files changed, 51 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index d9be41b7d8..959ae5c75e 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ Replace default components with custom implementations using the [`renderers`](# ## Keyboard Shortcuts -Ctrl also accepts ⌘, as macOS uses Ctrl+←/→ to switch desktops. In right-to-left grids, ← and → are swapped. See [`onCellKeyDown`](#oncellkeydown-maybeargs-cellkeydownargsr-sr-event-cellkeyboardevent--void) to customize them. +Ctrl also accepts ⌘, as macOS uses Ctrl+←/→ to switch desktops. In right-to-left grids, ← and → are swapped. See [`onCellKeyDown`](#oncellkeydown 'DataGridProps.onCellKeyDown') to customize them. ### Navigation @@ -252,26 +252,26 @@ Replace default components with custom implementations using the [`renderers`](# ### Editing -| Keys | Action | -| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Typing or Enter | Open the [editor](#rendereditcell-maybeprops-rendereditcellcontentpropstrow-tsummaryrow--reactnode) | -| Enter / Escape | Commit or discard the changes and close the editor | -| Tab / Shift+Tab | Commit the changes and move to the next or previous cell | -| Ctrl+C / Ctrl+V | Copy or paste, with [`onCellCopy`](#oncellcopy-maybeargs-cellcopyargsr-sr-event-cellclipboardevent--void) and [`onCellPaste`](#oncellpaste-maybeargs-cellpasteargsr-sr-event-cellclipboardevent--r) | +| Keys | Action | +| ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| Typing or Enter | Open the [editor](#rendereditcell 'Column.renderEditCell') | +| Enter / Escape | Commit or discard the changes and close the editor | +| Tab / Shift+Tab | Commit the changes and move to the next or previous cell | +| Ctrl+C / Ctrl+V | Copy or paste, with [`onCellCopy`](#oncellcopy 'DataGridProps.onCellCopy') and [`onCellPaste`](#oncellpaste 'DataGridProps.onCellPaste') | ### Selection -| Keys | Action | -| --------------------------------- | -------------------------------------------------------------------------------- | -| Shift+Space | Select or deselect the [row](#selectedrows-maybereadonlysetk) of the active cell | +| Keys | Action | +| --------------------------------- | ------------------------------------------------------------------------------------------- | +| Shift+Space | Select or deselect the [row](#selectedrows 'DataGridProps.selectedRows') of the active cell | ### Header Cells | Keys | Action | | ------------------------------------------------------------------- | ------------------------------------------------------------ | -| Enter / Space | [Sort](#sortable-maybeboolean) by the column | +| Enter / Space | [Sort](#sortable 'Column.sortable') by the column | | Ctrl+Enter / Ctrl+Space | Add the column to the sort, keeping the other sorted columns | -| Ctrl+← / Ctrl+→ | [Resize](#resizable-maybeboolean) the column | +| Ctrl+← / Ctrl+→ | [Resize](#resizable 'Column.resizable') the column | See [`TreeDataGrid`](#treedatagrid-) for the keys that expand and collapse groups. @@ -1189,7 +1189,7 @@ Function to generate unique IDs for group rows. If not provided, a default imple #### `` -The default row component. Can be wrapped via the `renderers.renderRow` prop. +The default row component. Can be wrapped via the [`renderers.renderRow`](#renderers-1) prop. ##### Props @@ -1197,7 +1197,7 @@ The default row component. Can be wrapped via the `renderers.renderRow` prop. #### `` -The default cell component. Can be wrapped via the `renderers.renderCell` prop. +The default cell component. Can be wrapped via the [`renderers.renderCell`](#renderers-1) prop. ##### Props @@ -1209,7 +1209,7 @@ A component for rendering row selection checkboxes. ##### Props -The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. +[`SelectCheckboxProps`](#selectcheckboxprops-internal) #### `` @@ -1235,6 +1235,8 @@ Hook for managing header row selection state. Used within custom header cell ren **Returns:** +An object with: + - `isIndeterminate: boolean` - Whether some (but not all) rows are selected - `isRowSelected: boolean` - Whether all rows are selected - `onRowSelectionChange: (event: SelectHeaderRowEvent) => void` - Callback to change selection state @@ -1279,6 +1281,8 @@ Hook for managing row selection state. Used within custom cell renderers to impl **Returns:** +An object with: + - `isRowSelectionDisabled: boolean` - Whether selection is disabled for this row - `isRowSelected: boolean` - Whether this row is selected - `onRowSelectionChange: (event: SelectRowEvent) => void` - Callback to change selection state @@ -2723,6 +2727,20 @@ interface Position { **See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) +#### `SelectCheckboxProps` (internal) + +The props of [``](#selectcheckbox-): the same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `value: boolean` in place of `checked`. + +```tsx +interface SelectCheckboxProps extends Pick< + RenderCheckboxProps, + 'disabled' | 'tabIndex' | 'aria-label' | 'aria-labelledby' | 'indeterminate' | 'onChange' +> { + /** Whether the checkbox is checked */ + value: boolean; +} +``` + ### Generics diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index 84aa37f837..893679480b 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -169,23 +169,16 @@ function renderItem(item: Declaration, section: string, hasPropsInterface: boole const propsType = getComponentPropsType(node); const typeName = /^\w+/.exec(propsType)![0]; - if (!helperTypes.has(typeName)) { - return [ - title, - ...renderSummary(doc), - ...renderTags(doc), - heading(5, 'Props'), - `[\`${propsType}\`](#!${typeName})` - ].join('\n\n'); + if (helperTypes.has(typeName)) { + throw new Error(`${typeName}, the props of ${name}, must have a JSDoc comment`); } - - // the props of a component with an undocumented props type are described - // by the paragraphs after the first, e.g. `SelectCheckbox` - const [description, ...props] = doc.summary.split('\n\n'); - if (props.length === 0) { - throw new Error(`${name} must describe its props after the first paragraph`); - } - return [title, description, ...renderTags(doc), heading(5, 'Props'), ...props].join('\n\n'); + return [ + title, + ...renderSummary(doc), + ...renderTags(doc), + heading(5, 'Props'), + `[\`${propsType}\`](#!${typeName})` + ].join('\n\n'); } const isFunction = !isVariableStatement(node); diff --git a/src/Cell.tsx b/src/Cell.tsx index 187eeb38f5..e8d10f5f62 100644 --- a/src/Cell.tsx +++ b/src/Cell.tsx @@ -129,7 +129,7 @@ function Cell({ } /** - * The default cell component. Can be wrapped via the `renderers.renderCell` prop. + * The default cell component. Can be wrapped via the {@linkcode Renderers.renderCell | renderers.renderCell} prop. */ const MemoCell = memo(Cell) as (props: RenderCellProps) => React.JSX.Element; diff --git a/src/Row.tsx b/src/Row.tsx index 4e0a602bb4..0280f291f3 100644 --- a/src/Row.tsx +++ b/src/Row.tsx @@ -89,7 +89,7 @@ function Row({ } /** - * The default row component. Can be wrapped via the `renderers.renderRow` prop. + * The default row component. Can be wrapped via the {@linkcode Renderers.renderRow | renderers.renderRow} prop. */ const MemoRow = memo(Row) as (props: RenderRowProps) => React.JSX.Element; diff --git a/src/cellRenderers/SelectCheckbox.tsx b/src/cellRenderers/SelectCheckbox.tsx index 502f0f4716..81f6e35cf5 100644 --- a/src/cellRenderers/SelectCheckbox.tsx +++ b/src/cellRenderers/SelectCheckbox.tsx @@ -1,20 +1,19 @@ import type { RenderCheckboxProps } from '../types'; import { useRenderers } from '../DataGridRenderersContext'; -type SharedInputProps = Pick< +/** + * The props of {@linkcode SelectCheckbox | }: the same props as {@linkcode RenderCheckboxProps}, with `value: boolean` in place of `checked`. + */ +interface SelectCheckboxProps extends Pick< RenderCheckboxProps, 'disabled' | 'tabIndex' | 'aria-label' | 'aria-labelledby' | 'indeterminate' | 'onChange' ->; - -interface SelectCheckboxProps extends SharedInputProps { +> { /** Whether the checkbox is checked */ value: boolean; } /** * A component for rendering row selection checkboxes. - * - * The same props as {@linkcode RenderCheckboxProps}, with `value: boolean` in place of `checked`. */ export function SelectCheckbox({ value, diff --git a/src/hooks/useRowSelection.ts b/src/hooks/useRowSelection.ts index ec3d6d9031..e2145debf1 100644 --- a/src/hooks/useRowSelection.ts +++ b/src/hooks/useRowSelection.ts @@ -19,7 +19,7 @@ RowSelectionChangeContext.displayName = 'RowSelectionChangeContext'; /** * Hook for managing row selection state. Used within custom cell renderers to implement custom row selection. * - * @returns + * @returns An object with: * * - `isRowSelectionDisabled: boolean` - Whether selection is disabled for this row * - `isRowSelected: boolean` - Whether this row is selected @@ -80,7 +80,7 @@ HeaderRowSelectionChangeContext.displayName = 'HeaderRowSelectionChangeContext'; /** * Hook for managing header row selection state. Used within custom header cell renderers to implement custom "select all" functionality. * - * @returns + * @returns An object with: * * - `isIndeterminate: boolean` - Whether some (but not all) rows are selected * - `isRowSelected: boolean` - Whether all rows are selected From 2639da588ac018f25e7430feb9cf445719c32c20 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Tue, 27 Oct 2026 22:19:55 -0500 Subject: [PATCH 18/22] Link the member mentions in the API docs Co-Authored-By: Claude Opus 5.5 --- README.md | 14 +++++++------- src/DataGrid.tsx | 2 +- src/types.ts | 12 ++++++------ 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 959ae5c75e..7e93422b31 100644 --- a/README.md +++ b/README.md @@ -857,7 +857,7 @@ const customRenderers: Renderers = { ; ``` -The default `` component can be wrapped via `renderers.renderRow` to add contexts or tweak props: +The default `` component can be wrapped via [`renderers.renderRow`](#renderers-1) to add contexts or tweak props: ```tsx import { DataGrid, Row, type RenderRowProps } from 'react-data-grid'; @@ -1983,7 +1983,7 @@ type ColumnFrozen = false | 'start' | 'end'; #### `RenderCellContentProps` -Props passed to custom cell content renderers (`column.renderCell`). +Props passed to custom cell content renderers ([`column.renderCell`](#rendercell)). ```tsx interface RenderCellContentProps { @@ -2015,7 +2015,7 @@ function renderCell({ row, column, onRowChange }: RenderCellContentProps) #### `RenderHeaderCellContentProps` -Props passed to custom header cell content renderers (`column.renderHeaderCell`). +Props passed to custom header cell content renderers ([`column.renderHeaderCell`](#renderheadercell-1)). ```tsx interface RenderHeaderCellContentProps { @@ -2030,7 +2030,7 @@ interface RenderHeaderCellContentProps { #### `RenderEditCellContentProps` -Props passed to custom editors (`column.renderEditCell`). +Props passed to custom editors ([`column.renderEditCell`](#rendereditcell)). ```tsx interface RenderEditCellContentProps { @@ -2063,7 +2063,7 @@ function renderEditor({ row, column, onRowChange, onClose }: RenderEditCellConte #### `RenderSummaryCellContentProps` -Props passed to summary cell content renderers (`column.renderSummaryCell`). +Props passed to summary cell content renderers ([`column.renderSummaryCell`](#rendersummarycell)). ```tsx interface RenderSummaryCellContentProps { @@ -2077,7 +2077,7 @@ interface RenderSummaryCellContentProps { #### `RenderGroupCellContentProps` -Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. +Props passed to group cell content renderers ([`column.renderGroupCell`](#rendergroupcell)) when using `TreeDataGrid`. ```tsx interface RenderGroupCellContentProps { @@ -2132,7 +2132,7 @@ interface RenderRowProps #### `RenderCellProps` -Props passed to the cell renderer when using `renderers.renderCell`. +Props passed to the cell renderer when using [`renderers.renderCell`](#renderers-1). ```tsx interface RenderCellProps diff --git a/src/DataGrid.tsx b/src/DataGrid.tsx index c77d2d549f..ef399a11a0 100644 --- a/src/DataGrid.tsx +++ b/src/DataGrid.tsx @@ -593,7 +593,7 @@ export interface DataGridProps { * ; * ``` * - * The default `` component can be wrapped via `renderers.renderRow` to add contexts or tweak props: + * The default `` component can be wrapped via {@linkcode Renderers.renderRow | renderers.renderRow} to add contexts or tweak props: * * ```tsx * import { DataGrid, Row, type RenderRowProps } from 'react-data-grid'; diff --git a/src/types.ts b/src/types.ts index 314cdaee0a..187620db89 100644 --- a/src/types.ts +++ b/src/types.ts @@ -317,7 +317,7 @@ export interface Position { } /** - * Props passed to custom cell content renderers (`column.renderCell`). + * Props passed to custom cell content renderers ({@linkcode Column.renderCell | column.renderCell}). * * @example * ```tsx @@ -345,7 +345,7 @@ export interface RenderCellContentProps { } /** - * Props passed to summary cell content renderers (`column.renderSummaryCell`). + * Props passed to summary cell content renderers ({@linkcode Column.renderSummaryCell | column.renderSummaryCell}). * * @see {@linkcode Column.renderSummaryCell | column.renderSummaryCell} */ @@ -356,7 +356,7 @@ export interface RenderSummaryCellContentProps { } /** - * Props passed to group cell content renderers (`column.renderGroupCell`) when using `TreeDataGrid`. + * Props passed to group cell content renderers ({@linkcode Column.renderGroupCell | column.renderGroupCell}) when using `TreeDataGrid`. * * @see {@linkcode Column.renderGroupCell | column.renderGroupCell}, {@linkcode renderToggleGroup} function, {@linkcode ToggleGroup | } */ @@ -371,7 +371,7 @@ export interface RenderGroupCellContentProps { } /** - * Props passed to custom editors (`column.renderEditCell`). + * Props passed to custom editors ({@linkcode Column.renderEditCell | column.renderEditCell}). * * @example * ```tsx @@ -400,7 +400,7 @@ export interface RenderEditCellContentProps { } /** - * Props passed to custom header cell content renderers (`column.renderHeaderCell`). + * Props passed to custom header cell content renderers ({@linkcode Column.renderHeaderCell | column.renderHeaderCell}). * * @see {@linkcode Column.renderHeaderCell | column.renderHeaderCell}, {@linkcode renderHeaderCell} function */ @@ -423,7 +423,7 @@ interface BaseRenderCellProps } /** - * Props passed to the cell renderer when using `renderers.renderCell`. + * Props passed to the cell renderer when using {@linkcode Renderers.renderCell | renderers.renderCell}. * * @see {@linkcode DataGridProps.renderers | renderers.renderCell}, {@linkcode Cell | } */ From 00a8f2a79118768d8bb46b2068f7832e15047773 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Mon, 2 Nov 2026 08:57:31 -0600 Subject: [PATCH 19/22] Use JSDoc tags for the examples, return values, defaults, and related types Co-Authored-By: Claude Opus 5.5 --- README.md | 304 +++++++++++++++++++++++++------------------ src/DataGrid.tsx | 212 +++++++++++++++--------------- src/TreeDataGrid.tsx | 25 ++-- src/types.ts | 42 +++--- 4 files changed, 331 insertions(+), 252 deletions(-) diff --git a/README.md b/README.md index d1292845ee..521ae80ffe 100644 --- a/README.md +++ b/README.md @@ -298,7 +298,9 @@ Main API component to render a data grid of rows and columns ref?: Maybe>; ``` -Optional ref for imperative APIs like scrolling to or focusing a cell. See [`DataGridHandle`](#datagridhandle). +Optional ref for imperative APIs like scrolling to or focusing a cell. + +**See also:** [`DataGridHandle`](#datagridhandle) ###### `columns` @@ -306,10 +308,12 @@ Optional ref for imperative APIs like scrolling to or focusing a cell. See [`Dat columns: readonly ColumnOrColumnGroup[]; ``` -An array of column definitions and/or column groups. See the [`ColumnOrColumnGroup`](#columnorcolumngroup) type for all available options. +An array of column definitions and/or column groups. ⚠️ **Performance:** Passing a new `columns` array will trigger a re-render and recalculation for the entire grid. Always memoize this prop using `useMemo` or define it outside the component to avoid unnecessary re-renders. +**See also:** [`ColumnOrColumnGroup`](#columnorcolumngroup) + ###### `rows` ```tsx @@ -323,15 +327,17 @@ An array of rows. The row data can be of any type. - **Virtualization**: Only visible rows are rendered in the DOM - **Individual row updates**: Row components are memoized, so updating a single row object will only re-render that specific row, not all rows - **Array reference matters**: Changing the array reference itself (e.g., `setRows([...rows])`) triggers viewport and layout recalculations, even if the row objects are unchanged -- **Best practice**: When updating rows, create a new array but reuse unchanged row objects. For example: +- **Best practice**: When updating rows, create a new array but reuse unchanged row objects. - ```tsx - // ✅ Good: Only the changed row is re-rendered - setRows(rows.map((row, idx) => (idx === targetIdx ? { ...row, updated: true } : row))); +**Example:** - // ❌ Avoid: Creates new references for all rows, causing all visible rows to re-render - setRows(rows.map((row) => ({ ...row }))); - ``` +```tsx +// ✅ Good: Only the changed row is re-rendered +setRows(rows.map((row, idx) => (idx === targetIdx ? { ...row, updated: true } : row))); + +// ❌ Avoid: Creates new references for all rows, causing all visible rows to re-render +setRows(rows.map((row) => ({ ...row }))); +``` ###### `topSummaryRows?` @@ -361,6 +367,12 @@ getRowKey?: Maybe<(row: R) => K>; Function to get a unique key for each row. Required for row selection. +💡 While optional, setting this prop is recommended for optimal performance, as the returned value is used to set the `key` prop on the row elements. + +⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. + +**Example:** + ```tsx import { DataGrid } from 'react-data-grid'; @@ -378,10 +390,6 @@ function MyGrid() { } ``` -💡 While optional, setting this prop is recommended for optimal performance, as the returned value is used to set the `key` prop on the row elements. - -⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. - ###### `onRowsChange?` ```tsx @@ -391,7 +399,9 @@ onRowsChange?: Maybe<(rows: R[], data: RowsChangeData) => void>; Callback triggered when rows are changed. The first parameter is a new rows array with both the updated rows and the other untouched rows. -The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. See the [`RowsChangeData`](#rowschangedata) type. +The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. + +**Example:** ```tsx import { useState } from 'react'; @@ -404,6 +414,8 @@ function MyGrid() { } ``` +**See also:** [`RowsChangeData`](#rowschangedata) + ###### `rowHeight?` ```tsx @@ -412,6 +424,12 @@ rowHeight?: Maybe number)>; Height of each row in pixels. A function can be used to set different row heights. +⚠️ **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. + +**Default:** `35` pixels + +**Example:** + ```tsx // Fixed height for all rows ; @@ -424,10 +442,6 @@ function getRowHeight(row) { ; ``` -⚠️ **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. - -**Default:** `35` pixels - ###### `headerRowHeight?` ```tsx @@ -446,17 +460,6 @@ summaryRowHeight?: Maybe; Height of each summary row in pixels. -```tsx - -``` - **Default:** `rowHeight` when it is a number, otherwise `35` pixels ###### `columnWidths?` @@ -465,7 +468,9 @@ Height of each summary row in pixels. columnWidths?: Maybe; ``` -A map of column widths containing both measured and resized widths. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths-1) type. +A map of column widths containing both measured and resized widths. If not provided, an internal state is used. + +**Example:** ```tsx const [columnWidths, setColumnWidths] = useState((): ColumnWidths => new Map()); @@ -479,13 +484,17 @@ function addNewRow() { return ``` +**See also:** [`ColumnWidths`](#columnwidths-1) + ###### `onColumnWidthsChange?` ```tsx onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; ``` -Callback triggered when column widths change. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths-1) type. +Callback triggered when column widths change. If not provided, an internal state is used. + +**See also:** [`ColumnWidths`](#columnwidths-1) ###### `selectedRows?` @@ -511,6 +520,8 @@ onSelectedRowsChange?: Maybe<(selectedRows: Set) => void>; Callback triggered when the selection changes. +**Example:** + ```tsx import { useState } from 'react'; import { DataGrid, SelectColumn, type Column } from 'react-data-grid'; @@ -552,10 +563,12 @@ function MyGrid() { sortColumns?: Maybe; ``` -An array of sorted columns. See the [`SortColumn`](#sortcolumn) type. +An array of sorted columns. Sorting is controlled: the grid does not reorder `rows` for you. Apply the sorting to your `rows` state (or derived rows) based on `sortColumns`. +**See also:** [`SortColumn`](#sortcolumn) + ###### `onSortColumnsChange?` ```tsx @@ -564,6 +577,10 @@ onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>; Callback triggered when sorting changes. +More than one column can be sorted via Ctrl+Click (Cmd+Click on macOS). + +**Example:** + ```tsx import { useState } from 'react'; import { DataGrid, type Column, type SortColumn } from 'react-data-grid'; @@ -593,9 +610,10 @@ function MyGrid() { } ``` -More than one column can be sorted via Ctrl+Click (Cmd+Click on macOS). To disable multi-column sorting, change the `onSortColumnsChange` function to: +**Example:** ```tsx +// Disable multi-column sorting function onSortColumnsChange(sortColumns: SortColumn[]) { setSortColumns(sortColumns.slice(-1)); } @@ -607,7 +625,9 @@ function onSortColumnsChange(sortColumns: SortColumn[]) { defaultColumnOptions?: Maybe>; ``` -Default options applied to all columns. See the [`DefaultColumnOptions`](#defaultcolumnoptions-1) type. +Default options applied to all columns. + +**Example:** ```tsx function MyGrid() { @@ -626,13 +646,17 @@ function MyGrid() { } ``` +**See also:** [`DefaultColumnOptions`](#defaultcolumnoptions-1) + ###### `onCellMouseDown?` ```tsx onCellMouseDown?: CellMouseEventHandler; ``` -Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. A handler that prevents the default behavior can activate and focus the cell itself with `args.setActivePosition({ shouldFocus: true })`. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. A handler that prevents the default behavior can activate and focus the cell itself with `args.setActivePosition({ shouldFocus: true })`. + +**Example:** ```tsx function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { @@ -644,18 +668,21 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ; ``` +**See also:** [`CellMouseArgs`](#cellmouseargs), [`CellMouseEvent`](#cellmouseevent) + ###### `onCellClick?` ```tsx onCellClick?: CellMouseEventHandler; ``` -Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a cell is clicked. -This event can be used to open the cell editor on a single click: +**Example:** ```tsx function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { + // Open the editor on a single click if (args.column.key === 'id') { args.setActivePosition({ enableEditor: true }); } @@ -664,13 +691,17 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` +**See also:** [`CellMouseArgs`](#cellmouseargs), [`CellMouseEvent`](#cellmouseevent) + ###### `onCellDoubleClick?` ```tsx onCellDoubleClick?: CellMouseEventHandler; ``` -Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. + +**Example:** ```tsx function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { @@ -682,13 +713,17 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` +**See also:** [`CellMouseArgs`](#cellmouseargs), [`CellMouseEvent`](#cellmouseevent) + ###### `onCellContextMenu?` ```tsx onCellContextMenu?: CellMouseEventHandler; ``` -Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargs) and [`CellMouseEvent`](#cellmouseevent) types. +Callback triggered when a cell is right-clicked. + +**Example:** ```tsx function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { @@ -701,39 +736,32 @@ function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { ; ``` +**See also:** [`CellMouseArgs`](#cellmouseargs), [`CellMouseEvent`](#cellmouseevent) + ###### `onCellKeyDown?` ```tsx onCellKeyDown?: Maybe<(args: CellKeyDownArgs, event: CellKeyboardEvent) => void>; ``` -Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. See the [`CellKeyDownArgs`](#cellkeydownargs) and [`CellKeyboardEvent`](#cellkeyboardevent) types. +Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. It is not called for keydown events triggered in a [`:modal`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:modal) editor, see [`renderEditCell`](#rendereditcell). -**Examples** - -- Prevent editing on `Enter` - -```tsx -function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { - if (args.mode === 'ACTIVE' && event.key === 'Enter') { - event.preventGridDefault(); - } -} -``` +See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website/routes/CellNavigation.tsx). -- Prevent navigation on `Tab` +**Example:** ```tsx function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { - if (args.mode === 'ACTIVE' && event.key === 'Tab') { + if (args.mode === 'ACTIVE' && (event.key === 'Enter' || event.key === 'Tab')) { + // Prevent editing on `Enter` and navigation on `Tab` event.preventGridDefault(); } } ``` -See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website/routes/CellNavigation.tsx). +**See also:** [`CellKeyDownArgs`](#cellkeydownargs), [`CellKeyboardEvent`](#cellkeyboardevent) ###### `onCellCopy?` @@ -741,7 +769,9 @@ See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => void>; ``` -Callback triggered when a cell's content is copied. See the [`CellCopyArgs`](#cellcopyargs) type. +Callback triggered when a cell's content is copied. + +**See also:** [`CellCopyArgs`](#cellcopyargs) ###### `onCellPaste?` @@ -749,9 +779,13 @@ Callback triggered when a cell's content is copied. See the [`CellCopyArgs`](#ce onCellPaste?: Maybe<(args: CellPasteArgs, event: CellClipboardEvent) => R>; ``` -Callback triggered when content is pasted into a cell. See the [`CellPasteArgs`](#cellpasteargs) type. +Callback triggered when content is pasted into a cell. + +**Returns:** -Return the updated row; the grid will call `onRowsChange` with it. +The updated row, which the grid passes to [`onRowsChange`](#onrowschange) + +**See also:** [`CellPasteArgs`](#cellpasteargs) ###### `onActivePositionChange?` @@ -759,7 +793,9 @@ Return the updated row; the grid will call `onRowsChange` with it. onActivePositionChange?: Maybe<(args: PositionChangeArgs) => void>; ``` -Callback triggered when the active position changes. See the [`PositionChangeArgs`](#positionchangeargs) type. +Callback triggered when the active position changes. + +**See also:** [`PositionChangeArgs`](#positionchangeargs) ###### `onColumnResize?` @@ -785,7 +821,9 @@ onFill?: Maybe<(event: FillEvent) => R>; Callback triggered when the value of the active cell is dragged to fill other cells. When this prop is set, a drag handle is shown on the active cell if it is editable. Drag the handle up or down to fill the cells it passes over, or double-click it to fill all the cells below. -The grid calls `onFill` for each editable target cell. Return the updated target row; the grid will call `onRowsChange` with the updated rows. See the [`FillEvent`](#fillevent) type. +The grid calls `onFill` for each editable target cell. + +**Example:** ```tsx function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { @@ -795,6 +833,12 @@ function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { ; ``` +**Returns:** + +The updated target row. The grid passes the updated rows to [`onRowsChange`](#onrowschange) + +**See also:** [`FillEvent`](#fillevent) + ###### `onScroll?` ```tsx @@ -821,17 +865,19 @@ renderers?: Maybe>; Custom renderers for cells, rows, and other components. -See the [`Renderers`](#renderers-1) type for the full shape. - -Example of replacing default components: +**Example:** ```tsx -import { DataGrid, type Renderers } from 'react-data-grid'; +import { DataGrid, Row, type Renderers } from 'react-data-grid'; -const customRenderers: Renderers = { - // Custom row render function +const customRenderers: Renderers = { + // Wrap the default row to add contexts or tweak props renderRow(key, props) { - return ; + return ( + + + + ); }, // Custom cell render function @@ -856,27 +902,7 @@ const customRenderers: Renderers = { ; ``` -The default `` component can be wrapped via [`renderers.renderRow`](#renderers-1) to add contexts or tweak props: - -```tsx -import { DataGrid, Row, type RenderRowProps } from 'react-data-grid'; - -interface MyRow { - id: number; -} - -function myRowRenderer(key: React.Key, props: RenderRowProps) { - return ( - - - - ); -} - -function MyGrid() { - return ; -} -``` +**See also:** [`Renderers`](#renderers-1) ###### `rowClass?` @@ -886,6 +912,10 @@ rowClass?: Maybe<(row: R, rowIdx: number) => Maybe>; Function to apply custom class names to rows. +⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. + +**Example:** + ```tsx import { DataGrid } from 'react-data-grid'; @@ -898,8 +928,6 @@ function MyGrid() { } ``` -⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. - ###### `headerRowClass?` ```tsx @@ -908,26 +936,24 @@ headerRowClass?: Maybe; Custom class name for the header row. -```tsx - -``` - ###### `direction?` ```tsx direction?: Maybe; ``` -This property sets the text direction of the grid. It defaults to `'ltr'` (left-to-right). See the [`Direction`](#direction-1) type. +This property sets the text direction of the grid. Setting `direction` to `'rtl'` has the following effects: - Columns flow from right to left - Start-frozen columns are pinned on the right, and end-frozen columns are pinned on the left -- Column resize cursor is shown on the left edge of the column -- Scrollbar is moved to the left +- Column resize is controlled on the left edge of the column +- Vertical scrollbar is moved to the left -**Default:** `'ltr'` +**Default:** `'ltr'` left-to-right + +**See also:** [`Direction`](#direction-1) ###### `className?` @@ -951,7 +977,9 @@ Custom styles for the grid. role?: React.AriaRole | undefined; ``` -ARIA role for the grid container. Defaults to `grid`. +ARIA role for the grid container. + +**Default:** `'grid'` ###### `aria-label?` @@ -1001,6 +1029,8 @@ If the grid has a caption or description, `aria-describedby` can be set on the g This prop can be used to add a test ID for testing. We recommend querying the grid by its `role` and `name`. +**Example:** + ```tsx function MyGrid() { return ; @@ -1057,6 +1087,8 @@ The following `DataGrid` props are not supported in `TreeDataGrid`: Callbacks that receive the active row receive group rows too: `onCellKeyDown` and `onActivePositionChange`. Their arguments are typed with [`TreeCellKeyDownArgs`](#treecellkeydownargs) and [`TreePositionChangeArgs`](#treepositionchangeargs); use [`isGroupRow`](#isgrouprow) to tell group rows apart from regular rows. +**Example:** + ```tsx import { isGroupRow, type CellKeyboardEvent, type TreeCellKeyDownArgs } from 'react-data-grid'; @@ -1086,7 +1118,9 @@ columns: readonly Column[]; rowHeight?: Maybe) => number)>; ``` -**Note:** Unlike `DataGrid`, the `rowHeight` function receives [`RowHeightArgs`](#rowheightargs), which includes a `type` property to distinguish between regular rows and group rows: +**Note:** Unlike `DataGrid`, the `rowHeight` function receives [`RowHeightArgs`](#rowheightargs), which includes a `type` property to distinguish between regular rows and group rows. + +**Example:** ```tsx function getRowHeight(args: RowHeightArgs): number { @@ -1105,7 +1139,9 @@ function getRowHeight(args: RowHeightArgs): number { onCellKeyDown?: Maybe<(args: TreeCellKeyDownArgs, event: CellKeyboardEvent) => void>; ``` -Callback triggered when a key is pressed in a cell or a row, including group rows. Unlike `DataGrid`, the active row in `ACTIVE` mode can be a group row: use [`isGroupRow`](#isgrouprow) to narrow it. See the [`TreeCellKeyDownArgs`](#treecellkeydownargs) type and the [`onCellKeyDown`](#oncellkeydown) prop on ``. +Callback triggered when a key is pressed in a cell or a row, including group rows. Unlike `DataGrid`, the active row in `ACTIVE` mode can be a group row: use [`isGroupRow`](#isgrouprow) to narrow it. + +**See also:** [`TreeCellKeyDownArgs`](#treecellkeydownargs), [`onCellKeyDown`](#oncellkeydown) prop on `` ###### `onActivePositionChange?` @@ -1113,7 +1149,9 @@ Callback triggered when a key is pressed in a cell or a row, including group row onActivePositionChange?: Maybe<(args: TreePositionChangeArgs) => void>; ``` -Callback triggered when the active position changes, including to a group row or a cell of one: use [`isGroupRow`](#isgrouprow) to narrow the row. See the [`TreePositionChangeArgs`](#treepositionchangeargs) type. +Callback triggered when the active position changes, including to a group row or a cell of one: use [`isGroupRow`](#isgrouprow) to narrow the row. + +**See also:** [`TreePositionChangeArgs`](#treepositionchangeargs) ###### `groupBy` @@ -1123,6 +1161,10 @@ groupBy: readonly string[]; **Required.** An array of column keys to group by. The order determines the grouping hierarchy (first key is the top level, second key is nested under the first, etc.). +⚠️ **Performance:** Define this array outside your component or memoize it with `useMemo`, otherwise all the rows are grouped again on every render. + +**Example:** + ```tsx import { TreeDataGrid, type Column } from 'react-data-grid'; @@ -1153,8 +1195,6 @@ function MyGrid() { } ``` -⚠️ **Performance:** Define this array outside your component or memoize it with `useMemo`, otherwise all the rows are grouped again on every render. - ###### `expandedGroupIds` ```tsx @@ -1163,6 +1203,8 @@ expandedGroupIds: ReadonlySet; **Required.** A set of group IDs that are currently expanded. Group IDs are generated by `getGroupId`. +**Example:** + ```tsx import { useState } from 'react'; import { TreeDataGrid } from 'react-data-grid'; @@ -1196,7 +1238,11 @@ getRowGroupKey?: Maybe<(row: R, columnKey: string) => string>; A function that returns the key of the group a row belongs to, for the specified column key. Rows sharing the same group key are grouped together, and groups are ordered by the first row that belongs to them. If not provided, a default implementation is used that stringifies the row's value for that column, i.e., `String(row[columnKey])`. -Provide your own to group on something other than the raw cell value: +Provide your own to group on something other than the raw cell value. + +⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback`, otherwise all the rows are grouped again on every render. + +**Example:** ```tsx function getRowGroupKey(row: Row, columnKey: string): string { @@ -1207,8 +1253,6 @@ function getRowGroupKey(row: Row, columnKey: string): string { } ``` -⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback`, otherwise all the rows are grouped again on every render. - ###### `getGroupId?` ```tsx @@ -1623,6 +1667,12 @@ readonly width?: Maybe; Width can be any valid CSS grid column value. If not specified, it will be determined automatically based on grid width and specified widths of other columns. +`max-content` can be used to expand the column to show all the content. Note that the grid is only able to calculate column width for visible rows. + +**Default:** `'auto'` + +**Example:** + ```tsx const columns: Column[] = [ { @@ -1640,25 +1690,17 @@ const columns: Column[] = [ }, { key: 'description', - name: 'Description' + name: 'Description', + width: 'minmax(100px, max-content)' // Fits the content, at least 100 pixels + }, + { + key: 'notes', + name: 'Notes' // No width specified - automatically sized } ]; ``` -Other examples: - -```tsx -width: 80, // pixels -width: '25%', -width: 'max-content', -width: 'minmax(100px, max-content)', -``` - -`max-content` can be used to expand the column to show all the content. Note that the grid is only able to calculate column width for visible rows. - -**Default:** `auto` - ##### `minWidth?` ```tsx @@ -1685,6 +1727,8 @@ readonly cellClass?: Maybe Maybe)>; Class name(s) for cells. Can be a string or a function that returns a class name based on the row. +**Example:** + ```tsx const columns: Column[] = [ { @@ -1763,6 +1807,8 @@ readonly renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => Render function to render the content of group cells when using `TreeDataGrid`. The group row is passed as `row`, a [`GroupRow`](#grouprow) with the group's key, rows, and expanded state. +**Example:** + ```tsx const columns: readonly Column[] = [ { @@ -1799,7 +1845,7 @@ Control whether cells can be edited with `renderEditCell`. readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; ``` -Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. The span is clamped to the start-frozen, unfrozen, or end-frozen columns, whichever the column is part of. See the [`ColSpanArgs`](#colspanargs) type. +Function to determine how many columns this cell should span. The span is clamped to the start-frozen, unfrozen, or end-frozen columns, whichever the column is part of. **Example:** @@ -1820,17 +1866,27 @@ const columns: readonly Column[] = [ ]; ``` +**Returns:** + +The number of columns to span, or `undefined` for no spanning + +**See also:** [`ColSpanArgs`](#colspanargs) + ##### `frozen?` ```tsx readonly frozen?: Maybe; ``` -Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. See the [`ColumnFrozen`](#columnfrozen) type. +Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. - `'start'` (or `true` for backward compatibility) — pins the column to the start edge (left in LTR, right in RTL). - `'end'` — pins the column to the end edge (right in LTR, left in RTL). -- `false` (default) — the column scrolls with the rest of the grid. +- `false` — the column scrolls with the rest of the grid. + +**Default:** `false` + +**Example:** ```tsx const columns: readonly Column[] = [ @@ -1840,7 +1896,7 @@ const columns: readonly Column[] = [ ]; ``` -**Default:** `false` +**See also:** [`ColumnFrozen`](#columnfrozen) ##### `resizable?` diff --git a/src/DataGrid.tsx b/src/DataGrid.tsx index fe5e0b85ac..fe873f7e94 100644 --- a/src/DataGrid.tsx +++ b/src/DataGrid.tsx @@ -130,16 +130,20 @@ export interface DataGridHandle { */ export interface DataGridProps { /** - * Optional ref for imperative APIs like scrolling to or focusing a cell. See {@linkcode DataGridHandle}. + * Optional ref for imperative APIs like scrolling to or focusing a cell. + * + * @see {@linkcode DataGridHandle} */ ref?: Maybe>; /** * Grid and data props */ /** - * An array of column definitions and/or column groups. See the {@linkcode ColumnOrColumnGroup} type for all available options. + * An array of column definitions and/or column groups. * * ⚠️ **Performance:** Passing a new `columns` array will trigger a re-render and recalculation for the entire grid. Always memoize this prop using `useMemo` or define it outside the component to avoid unnecessary re-renders. + * + * @see {@linkcode ColumnOrColumnGroup} */ columns: readonly ColumnOrColumnGroup, NoInfer>[]; /** @@ -150,15 +154,16 @@ export interface DataGridProps { * - **Virtualization**: Only visible rows are rendered in the DOM * - **Individual row updates**: Row components are memoized, so updating a single row object will only re-render that specific row, not all rows * - **Array reference matters**: Changing the array reference itself (e.g., `setRows([...rows])`) triggers viewport and layout recalculations, even if the row objects are unchanged - * - **Best practice**: When updating rows, create a new array but reuse unchanged row objects. For example: + * - **Best practice**: When updating rows, create a new array but reuse unchanged row objects. * - * ```tsx - * // ✅ Good: Only the changed row is re-rendered - * setRows(rows.map((row, idx) => (idx === targetIdx ? { ...row, updated: true } : row))); + * @example + * ```tsx + * // ✅ Good: Only the changed row is re-rendered + * setRows(rows.map((row, idx) => (idx === targetIdx ? { ...row, updated: true } : row))); * - * // ❌ Avoid: Creates new references for all rows, causing all visible rows to re-render - * setRows(rows.map((row) => ({ ...row }))); - * ``` + * // ❌ Avoid: Creates new references for all rows, causing all visible rows to re-render + * setRows(rows.map((row) => ({ ...row }))); + * ``` */ rows: readonly R[]; /** @@ -176,6 +181,11 @@ export interface DataGridProps { /** * Function to get a unique key for each row. Required for row selection. * + * 💡 While optional, setting this prop is recommended for optimal performance, as the returned value is used to set the `key` prop on the row elements. + * + * ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. + * + * @example * ```tsx * import { DataGrid } from 'react-data-grid'; * @@ -192,18 +202,15 @@ export interface DataGridProps { * return ; * } * ``` - * - * 💡 While optional, setting this prop is recommended for optimal performance, as the returned value is used to set the `key` prop on the row elements. - * - * ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. */ getRowKey?: Maybe<(row: NoInfer) => K>; /** * Callback triggered when rows are changed. * * The first parameter is a new rows array with both the updated rows and the other untouched rows. - * The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. See the {@linkcode RowsChangeData} type. + * The second parameter is an object with an `indexes` array highlighting which rows have changed by their index, and the `column` where the change happened. * + * @example * ```tsx * import { useState } from 'react'; * import { DataGrid } from 'react-data-grid'; @@ -214,6 +221,8 @@ export interface DataGridProps { * return ; * } * ``` + * + * @see {@linkcode RowsChangeData} */ onRowsChange?: Maybe<(rows: NoInfer[], data: RowsChangeData, NoInfer>) => void>; @@ -223,6 +232,11 @@ export interface DataGridProps { /** * Height of each row in pixels. A function can be used to set different row heights. * + * ⚠️ **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. + * + * @defaultValue `35` pixels + * + * @example * ```tsx * // Fixed height for all rows * ; @@ -234,10 +248,6 @@ export interface DataGridProps { * * ; * ``` - * - * ⚠️ **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. - * - * @defaultValue `35` pixels */ rowHeight?: Maybe) => number)>; /** @@ -249,23 +259,13 @@ export interface DataGridProps { /** * Height of each summary row in pixels. * - * ```tsx - * - * ``` - * * @defaultValue `rowHeight` when it is a number, otherwise `35` pixels */ summaryRowHeight?: Maybe; /** - * A map of column widths containing both measured and resized widths. If not provided, an internal state is used. See the {@linkcode ColumnWidths} type. + * A map of column widths containing both measured and resized widths. If not provided, an internal state is used. * + * @example * ```tsx * const [columnWidths, setColumnWidths] = useState((): ColumnWidths => new Map()); * @@ -277,10 +277,14 @@ export interface DataGridProps { * * return * ``` + * + * @see {@linkcode ColumnWidths} */ columnWidths?: Maybe; /** - * Callback triggered when column widths change. If not provided, an internal state is used. See the {@linkcode ColumnWidths} type. + * Callback triggered when column widths change. If not provided, an internal state is used. + * + * @see {@linkcode ColumnWidths} */ onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; @@ -298,6 +302,7 @@ export interface DataGridProps { /** * Callback triggered when the selection changes. * + * @example * ```tsx * import { useState } from 'react'; * import { DataGrid, SelectColumn, type Column } from 'react-data-grid'; @@ -335,14 +340,19 @@ export interface DataGridProps { */ onSelectedRowsChange?: Maybe<(selectedRows: Set>) => void>; /** - * An array of sorted columns. See the {@linkcode SortColumn} type. + * An array of sorted columns. * * Sorting is controlled: the grid does not reorder `rows` for you. Apply the sorting to your `rows` state (or derived rows) based on `sortColumns`. + * + * @see {@linkcode SortColumn} */ sortColumns?: Maybe; /** * Callback triggered when sorting changes. * + * More than one column can be sorted via Ctrl+Click (Cmd+Click on macOS). + * + * @example * ```tsx * import { useState } from 'react'; * import { DataGrid, type Column, type SortColumn } from 'react-data-grid'; @@ -372,9 +382,9 @@ export interface DataGridProps { * } * ``` * - * More than one column can be sorted via Ctrl+Click (Cmd+Click on macOS). To disable multi-column sorting, change the `onSortColumnsChange` function to: - * + * @example * ```tsx + * // Disable multi-column sorting * function onSortColumnsChange(sortColumns: SortColumn[]) { * setSortColumns(sortColumns.slice(-1)); * } @@ -382,8 +392,9 @@ export interface DataGridProps { */ onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>; /** - * Default options applied to all columns. See the {@linkcode DefaultColumnOptions} type. + * Default options applied to all columns. * + * @example * ```tsx * function MyGrid() { * return ( @@ -400,6 +411,8 @@ export interface DataGridProps { * ); * } * ``` + * + * @see {@linkcode DefaultColumnOptions} */ defaultColumnOptions?: Maybe, NoInfer>>; @@ -407,8 +420,9 @@ export interface DataGridProps { * Event props */ /** - * Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. A handler that prevents the default behavior can activate and focus the cell itself with `args.setActivePosition({ shouldFocus: true })`. See the {@linkcode CellMouseArgs} and {@linkcode CellMouseEvent} types. + * Callback triggered when a pointer becomes active in a cell. The default behavior is to focus the cell. Call `preventGridDefault` to prevent the default behavior. A handler that prevents the default behavior can activate and focus the cell itself with `args.setActivePosition({ shouldFocus: true })`. * + * @example * ```tsx * function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { * if (args.column.key === 'id') { @@ -418,15 +432,17 @@ export interface DataGridProps { * * ; * ``` + * + * @see {@linkcode CellMouseArgs}, {@linkcode CellMouseEvent} */ onCellMouseDown?: CellMouseEventHandler; /** - * Callback triggered when a cell is clicked. See the {@linkcode CellMouseArgs} and {@linkcode CellMouseEvent} types. - * - * This event can be used to open the cell editor on a single click: + * Callback triggered when a cell is clicked. * + * @example * ```tsx * function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { + * // Open the editor on a single click * if (args.column.key === 'id') { * args.setActivePosition({ enableEditor: true }); * } @@ -434,11 +450,14 @@ export interface DataGridProps { * * ; * ``` + * + * @see {@linkcode CellMouseArgs}, {@linkcode CellMouseEvent} */ onCellClick?: CellMouseEventHandler; /** - * Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. See the {@linkcode CellMouseArgs} and {@linkcode CellMouseEvent} types. + * Callback triggered when a cell is double-clicked. The default behavior is to open the editor if the cell is editable. Call `preventGridDefault` to prevent the default behavior. * + * @example * ```tsx * function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { * if (args.column.key === 'id') { @@ -448,11 +467,14 @@ export interface DataGridProps { * * ; * ``` + * + * @see {@linkcode CellMouseArgs}, {@linkcode CellMouseEvent} */ onCellDoubleClick?: CellMouseEventHandler; /** - * Callback triggered when a cell is right-clicked. See the {@linkcode CellMouseArgs} and {@linkcode CellMouseEvent} types. + * Callback triggered when a cell is right-clicked. * + * @example * ```tsx * function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { * if (args.column.key === 'id') { @@ -463,56 +485,54 @@ export interface DataGridProps { * * ; * ``` + * + * @see {@linkcode CellMouseArgs}, {@linkcode CellMouseEvent} */ onCellContextMenu?: CellMouseEventHandler; /** - * Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. See the {@linkcode CellKeyDownArgs} and {@linkcode CellKeyboardEvent} types. + * Callback triggered when a key is pressed in a cell. This event can be used to customize cell navigation and editing behavior. * * It is not called for keydown events triggered in a [`:modal`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:modal) editor, see {@linkcode Column.renderEditCell | renderEditCell}. * - * **Examples** - * - * - Prevent editing on `Enter` - * - * ```tsx - * function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { - * if (args.mode === 'ACTIVE' && event.key === 'Enter') { - * event.preventGridDefault(); - * } - * } - * ``` - * - * - Prevent navigation on `Tab` + * See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website/routes/CellNavigation.tsx). * + * @example * ```tsx * function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { - * if (args.mode === 'ACTIVE' && event.key === 'Tab') { + * if (args.mode === 'ACTIVE' && (event.key === 'Enter' || event.key === 'Tab')) { + * // Prevent editing on `Enter` and navigation on `Tab` * event.preventGridDefault(); * } * } * ``` * - * See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website/routes/CellNavigation.tsx). + * @see {@linkcode CellKeyDownArgs}, {@linkcode CellKeyboardEvent} */ onCellKeyDown?: Maybe< (args: CellKeyDownArgs, NoInfer>, event: CellKeyboardEvent) => void >; /** - * Callback triggered when a cell's content is copied. See the {@linkcode CellCopyArgs} type. + * Callback triggered when a cell's content is copied. + * + * @see {@linkcode CellCopyArgs} */ onCellCopy?: Maybe< (args: CellCopyArgs, NoInfer>, event: CellClipboardEvent) => void >; /** - * Callback triggered when content is pasted into a cell. See the {@linkcode CellPasteArgs} type. + * Callback triggered when content is pasted into a cell. + * + * @returns The updated row, which the grid passes to {@linkcode DataGridProps.onRowsChange | onRowsChange} * - * Return the updated row; the grid will call `onRowsChange` with it. + * @see {@linkcode CellPasteArgs} */ onCellPaste?: Maybe< (args: CellPasteArgs, NoInfer>, event: CellClipboardEvent) => NoInfer >; /** - * Callback triggered when the active position changes. See the {@linkcode PositionChangeArgs} type. + * Callback triggered when the active position changes. + * + * @see {@linkcode PositionChangeArgs} */ onActivePositionChange?: Maybe<(args: PositionChangeArgs, NoInfer>) => void>; /** @@ -526,8 +546,9 @@ export interface DataGridProps { /** * Callback triggered when the value of the active cell is dragged to fill other cells. When this prop is set, a drag handle is shown on the active cell if it is editable. Drag the handle up or down to fill the cells it passes over, or double-click it to fill all the cells below. * - * The grid calls `onFill` for each editable target cell. Return the updated target row; the grid will call `onRowsChange` with the updated rows. See the {@linkcode FillEvent} type. + * The grid calls `onFill` for each editable target cell. * + * @example * ```tsx * function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { * return { ...targetRow, [columnKey]: sourceRow[columnKey as keyof Row] }; @@ -535,6 +556,10 @@ export interface DataGridProps { * * ; * ``` + * + * @returns The updated target row. The grid passes the updated rows to {@linkcode DataGridProps.onRowsChange | onRowsChange} + * + * @see {@linkcode FillEvent} */ onFill?: Maybe<(event: FillEvent>) => NoInfer>; /** @@ -558,17 +583,18 @@ export interface DataGridProps { /** * Custom renderers for cells, rows, and other components. * - * See the {@linkcode Renderers} type for the full shape. - * - * Example of replacing default components: - * + * @example * ```tsx - * import { DataGrid, type Renderers } from 'react-data-grid'; + * import { DataGrid, Row, type Renderers } from 'react-data-grid'; * - * const customRenderers: Renderers = { - * // Custom row render function + * const customRenderers: Renderers = { + * // Wrap the default row to add contexts or tweak props * renderRow(key, props) { - * return ; + * return ( + * + * + * + * ); * }, * * // Custom cell render function @@ -593,32 +619,15 @@ export interface DataGridProps { * ; * ``` * - * The default `` component can be wrapped via {@linkcode Renderers.renderRow | renderers.renderRow} to add contexts or tweak props: - * - * ```tsx - * import { DataGrid, Row, type RenderRowProps } from 'react-data-grid'; - * - * interface MyRow { - * id: number; - * } - * - * function myRowRenderer(key: React.Key, props: RenderRowProps) { - * return ( - * - * - * - * ); - * } - * - * function MyGrid() { - * return ; - * } - * ``` + * @see {@linkcode Renderers} */ renderers?: Maybe, NoInfer>>; /** * Function to apply custom class names to rows. * + * ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. + * + * @example * ```tsx * import { DataGrid } from 'react-data-grid'; * @@ -630,29 +639,25 @@ export interface DataGridProps { * return ; * } * ``` - * - * ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to avoid re-rendering all rows on every render. */ rowClass?: Maybe<(row: NoInfer, rowIdx: number) => Maybe>; /** * Custom class name for the header row. - * - * ```tsx - * - * ``` */ headerRowClass?: Maybe; /** - * This property sets the text direction of the grid. It defaults to `'ltr'` (left-to-right). See the {@linkcode Direction} type. + * This property sets the text direction of the grid. * * Setting `direction` to `'rtl'` has the following effects: * * - Columns flow from right to left * - Start-frozen columns are pinned on the right, and end-frozen columns are pinned on the left - * - Column resize cursor is shown on the left edge of the column - * - Scrollbar is moved to the left + * - Column resize is controlled on the left edge of the column + * - Vertical scrollbar is moved to the left * - * @defaultValue `'ltr'` + * @defaultValue `'ltr'` left-to-right + * + * @see {@linkcode Direction} */ direction?: Maybe; /** @@ -664,7 +669,9 @@ export interface DataGridProps { */ style?: React.CSSProperties | undefined; /** - * ARIA role for the grid container. Defaults to `grid`. + * ARIA role for the grid container. + * + * @defaultValue `'grid'` */ role?: React.AriaRole | undefined; /** @@ -690,6 +697,7 @@ export interface DataGridProps { /** * This prop can be used to add a test ID for testing. We recommend querying the grid by its `role` and `name`. * + * @example * ```tsx * function MyGrid() { * return ; diff --git a/src/TreeDataGrid.tsx b/src/TreeDataGrid.tsx index 7fbbe89211..38cfb6a39a 100644 --- a/src/TreeDataGrid.tsx +++ b/src/TreeDataGrid.tsx @@ -46,8 +46,9 @@ export interface TreeDataGridProps extends > { columns: readonly Column, NoInfer>[]; /** - * **Note:** Unlike `DataGrid`, the `rowHeight` function receives {@linkcode RowHeightArgs | RowHeightArgs}, which includes a `type` property to distinguish between regular rows and group rows: + * **Note:** Unlike `DataGrid`, the `rowHeight` function receives {@linkcode RowHeightArgs | RowHeightArgs}, which includes a `type` property to distinguish between regular rows and group rows. * + * @example * ```tsx * function getRowHeight(args: RowHeightArgs): number { * if (args.type === 'GROUP') { @@ -61,18 +62,25 @@ export interface TreeDataGridProps extends */ rowHeight?: Maybe>) => number)>; /** - * Callback triggered when a key is pressed in a cell or a row, including group rows. Unlike `DataGrid`, the active row in `ACTIVE` mode can be a group row: use {@linkcode isGroupRow} to narrow it. See the {@linkcode TreeCellKeyDownArgs} type and the {@linkcode DataGridProps.onCellKeyDown | onCellKeyDown} prop on ``. + * Callback triggered when a key is pressed in a cell or a row, including group rows. Unlike `DataGrid`, the active row in `ACTIVE` mode can be a group row: use {@linkcode isGroupRow} to narrow it. + * + * @see {@linkcode TreeCellKeyDownArgs}, {@linkcode DataGridProps.onCellKeyDown | onCellKeyDown} prop on `` */ onCellKeyDown?: Maybe< (args: TreeCellKeyDownArgs, NoInfer>, event: CellKeyboardEvent) => void >; /** - * Callback triggered when the active position changes, including to a group row or a cell of one: use {@linkcode isGroupRow} to narrow the row. See the {@linkcode TreePositionChangeArgs} type. + * Callback triggered when the active position changes, including to a group row or a cell of one: use {@linkcode isGroupRow} to narrow the row. + * + * @see {@linkcode TreePositionChangeArgs} */ onActivePositionChange?: Maybe<(args: TreePositionChangeArgs, NoInfer>) => void>; /** * **Required.** An array of column keys to group by. The order determines the grouping hierarchy (first key is the top level, second key is nested under the first, etc.). * + * ⚠️ **Performance:** Define this array outside your component or memoize it with `useMemo`, otherwise all the rows are grouped again on every render. + * + * @example * ```tsx * import { TreeDataGrid, type Column } from 'react-data-grid'; * @@ -102,13 +110,12 @@ export interface TreeDataGridProps extends * ); * } * ``` - * - * ⚠️ **Performance:** Define this array outside your component or memoize it with `useMemo`, otherwise all the rows are grouped again on every render. */ groupBy: readonly string[]; /** * **Required.** A set of group IDs that are currently expanded. Group IDs are generated by `getGroupId`. * + * @example * ```tsx * import { useState } from 'react'; * import { TreeDataGrid } from 'react-data-grid'; @@ -134,8 +141,11 @@ export interface TreeDataGridProps extends /** * A function that returns the key of the group a row belongs to, for the specified column key. Rows sharing the same group key are grouped together, and groups are ordered by the first row that belongs to them. If not provided, a default implementation is used that stringifies the row's value for that column, i.e., `String(row[columnKey])`. * - * Provide your own to group on something other than the raw cell value: + * Provide your own to group on something other than the raw cell value. * + * ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback`, otherwise all the rows are grouped again on every render. + * + * @example * ```tsx * function getRowGroupKey(row: Row, columnKey: string): string { * if (columnKey === 'date') { @@ -144,8 +154,6 @@ export interface TreeDataGridProps extends * return String(row[columnKey]); * } * ``` - * - * ⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback`, otherwise all the rows are grouped again on every render. */ getRowGroupKey?: Maybe<(row: NoInfer, columnKey: string) => string>; /** @@ -245,6 +253,7 @@ export function isGroupRow(row: R | GroupRow): row is GroupRow { * * Callbacks that receive the active row receive group rows too: `onCellKeyDown` and `onActivePositionChange`. Their arguments are typed with {@linkcode TreeCellKeyDownArgs} and {@linkcode TreePositionChangeArgs}; use {@linkcode isGroupRow} to tell group rows apart from regular rows. * + * @example * ```tsx * import { isGroupRow, type CellKeyboardEvent, type TreeCellKeyDownArgs } from 'react-data-grid'; * diff --git a/src/types.ts b/src/types.ts index 9102654c1e..9d5003370c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -24,6 +24,11 @@ export interface Column { /** * Width can be any valid CSS grid column value. If not specified, it will be determined automatically based on grid width and specified widths of other columns. * + * `max-content` can be used to expand the column to show all the content. Note that the grid is only able to calculate column width for visible rows. + * + * @defaultValue `'auto'` + * + * @example * ```tsx * const columns: Column[] = [ * { @@ -41,24 +46,16 @@ export interface Column { * }, * { * key: 'description', - * name: 'Description' + * name: 'Description', + * width: 'minmax(100px, max-content)' // Fits the content, at least 100 pixels + * }, + * { + * key: 'notes', + * name: 'Notes' * // No width specified - automatically sized * } * ]; * ``` - * - * Other examples: - * - * ```tsx - * width: 80, // pixels - * width: '25%', - * width: 'max-content', - * width: 'minmax(100px, max-content)', - * ``` - * - * `max-content` can be used to expand the column to show all the content. Note that the grid is only able to calculate column width for visible rows. - * - * @defaultValue `auto` */ readonly width?: Maybe; /** @@ -72,6 +69,7 @@ export interface Column { /** * Class name(s) for cells. Can be a string or a function that returns a class name based on the row. * + * @example * ```tsx * const columns: Column[] = [ * { @@ -116,6 +114,7 @@ export interface Column { /** * Render function to render the content of group cells when using `TreeDataGrid`. The group row is passed as `row`, a {@linkcode GroupRow} with the group's key, rows, and expanded state. * + * @example * ```tsx * const columns: readonly Column[] = [ * { @@ -138,7 +137,7 @@ export interface Column { /** Control whether cells can be edited with `renderEditCell`. */ readonly editable?: Maybe boolean)>; /** - * Function to determine how many columns this cell should span. Returns the number of columns to span, or `undefined` for no spanning. The span is clamped to the start-frozen, unfrozen, or end-frozen columns, whichever the column is part of. See the {@linkcode ColSpanArgs} type. + * Function to determine how many columns this cell should span. The span is clamped to the start-frozen, unfrozen, or end-frozen columns, whichever the column is part of. * * @example * ```tsx @@ -157,15 +156,22 @@ export interface Column { * } * ]; * ``` + * + * @returns The number of columns to span, or `undefined` for no spanning + * + * @see {@linkcode ColSpanArgs} */ readonly colSpan?: Maybe<(args: ColSpanArgs) => Maybe>; /** - * Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. See the {@linkcode ColumnFrozen} type. + * Determines whether the column is frozen, and on which edge. Frozen columns stay in place when the grid is scrolled horizontally. * * - `'start'` (or `true` for backward compatibility) — pins the column to the start edge (left in LTR, right in RTL). * - `'end'` — pins the column to the end edge (right in LTR, left in RTL). - * - `false` (default) — the column scrolls with the rest of the grid. + * - `false` — the column scrolls with the rest of the grid. + * + * @defaultValue `false` * + * @example * ```tsx * const columns: readonly Column[] = [ * { key: 'id', name: 'ID', frozen: 'start' }, @@ -174,7 +180,7 @@ export interface Column { * ]; * ``` * - * @defaultValue `false` + * @see {@linkcode ColumnFrozen} */ readonly frozen?: Maybe; /** From 1f1e05cb153388254982a26593de10b3f68d6643 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Mon, 2 Nov 2026 09:13:11 -0600 Subject: [PATCH 20/22] Make `RenderCheckboxProps.checked` required, and `SelectCheckboxProps` an alias of `RenderCheckboxProps` Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +++------ src/cellRenderers/SelectCheckbox.tsx | 7 ++----- src/types.ts | 2 +- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 521ae80ffe..538e4cec92 100644 --- a/README.md +++ b/README.md @@ -1285,13 +1285,10 @@ A component for rendering row selection checkboxes. ##### SelectCheckboxProps -The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `checked` required. +The same props as [`RenderCheckboxProps`](#rendercheckboxprops). ```tsx -interface SelectCheckboxProps extends RenderCheckboxProps { - /** Whether the checkbox is checked */ - checked: boolean; -} +type SelectCheckboxProps = RenderCheckboxProps; ``` #### `` @@ -2318,7 +2315,7 @@ Props for custom checkbox renderers. ```tsx interface RenderCheckboxProps { /** Whether the checkbox is checked */ - checked?: boolean | undefined; + checked: boolean; /** Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected */ indeterminate?: boolean | undefined; /** Whether the checkbox is disabled */ diff --git a/src/cellRenderers/SelectCheckbox.tsx b/src/cellRenderers/SelectCheckbox.tsx index f3eff5ec09..629728cada 100644 --- a/src/cellRenderers/SelectCheckbox.tsx +++ b/src/cellRenderers/SelectCheckbox.tsx @@ -2,12 +2,9 @@ import type { RenderCheckboxProps } from '../types'; import { useRenderers } from '../DataGridRenderersContext'; /** - * The same props as {@linkcode RenderCheckboxProps}, with `checked` required. + * The same props as {@linkcode RenderCheckboxProps}. */ -export interface SelectCheckboxProps extends RenderCheckboxProps { - /** Whether the checkbox is checked */ - checked: boolean; -} +export type SelectCheckboxProps = RenderCheckboxProps; /** * A component for rendering row selection checkboxes. diff --git a/src/types.ts b/src/types.ts index 9d5003370c..b369be6a1a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -860,7 +860,7 @@ export interface RenderSortStatusProps extends RenderSortIconProps, RenderSortPr */ export interface RenderCheckboxProps { /** Whether the checkbox is checked */ - checked?: boolean | undefined; + checked: boolean; /** Whether the checkbox is in an indeterminate state, like the select all checkbox when only some rows are selected */ indeterminate?: boolean | undefined; /** Whether the checkbox is disabled */ From 26a33448caec41396973e884a7f748f304aa09e4 Mon Sep 17 00:00:00 2001 From: Nicolas Stepien Date: Fri, 6 Nov 2026 05:27:22 +0000 Subject: [PATCH 21/22] cache vp pack --- vite.config.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/vite.config.ts b/vite.config.ts index be8527e13c..b4227c137e 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -58,9 +58,17 @@ export default defineConfig({ command: 'tsc --build', cache: false }, + pack: { + command: 'vp pack', + cache: { + // `vp pack` cleans `lib/` before writing to it + input: [{ auto: true }, '!lib/**'] + } + }, // generates the API reference of the README from the declarations and JSDoc comments of `lib/index.d.ts` docs: { - command: ['vp pack', 'node scripts/generateApiDocs.ts', 'vp fmt README.md'], + dependsOn: ['pack'], + command: ['node scripts/generateApiDocs.ts', 'vp fmt README.md'], // the README is both an input and the output cache: false }, @@ -97,11 +105,7 @@ export default defineConfig({ 'vp build', 'git diff --exit-code website/routeTree.gen.ts', 'vp run test' - ], - cache: { - // `vp pack` cleans `lib/` before writing to it - input: [{ auto: true }, '!lib/**'] - } + ] }, // the first step of a release, see the header of `.github/workflows/publish.yml`: // arguments are passed to `npm version`, as `vp run` appends them to the last command From b520083d56ba69a370e5802a725f99bd3bd3b203 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Wed, 11 Nov 2026 13:27:52 -0600 Subject: [PATCH 22/22] Use the JSDoc tags `@default` and `@template`, and lint the generated API reference Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- scripts/generateApiDocs.ts | 12 ++++++------ src/DataGrid.tsx | 24 ++++++++++++------------ src/TreeDataGrid.tsx | 12 ++++++------ src/types.ts | 24 ++++++++++++------------ vite.config.ts | 19 +++---------------- 6 files changed, 40 insertions(+), 53 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b28006dd8f..5ad471569f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ website/ # demo site (TanStack Start), prerendered for GitHub Pages ## Conventions - **Public API** — all exports flow through `src/index.ts`. Keep `README.md` in sync with user-facing changes. -- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. `src/index.ts` sets the layout of the API reference: the exports are listed in their order, under the section of the comment above them, one of the sections in `scripts/generateApiDocs.ts` (`// Components`, `// Hooks`, `// Render Functions`, `// Context`, `// Other`, `// Types`). Use `@defaultValue`, `@example`, `@see`, `@typeParam`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tags; add new tags to `definedTags` of `jsdoc/check-tag-names` in `vite.config.ts`. In the hand-written sections of the README, give links to API members the member as title, e.g., ``[`width`](#width "Column.width")``, so `vp run docs` keeps their anchor up to date. +- **API docs** — JSDoc comments are the source of the README's API reference. Edit the JSDoc, then run `vp run docs` to regenerate the section between `` and ``; never edit that section by hand. `src/index.ts` sets the layout of the API reference: the exports are listed in their order, under the section of the comment above them, one of the sections in `scripts/generateApiDocs.ts` (`// Components`, `// Hooks`, `// Render Functions`, `// Context`, `// Other`, `// Types`). Use the JSDoc tags `@default`, `@example`, `@returns`, `@see`, `@template`, and `{@linkcode}` instead of writing these out in the description. Oxlint's `jsdoc` plugin checks the tag names. In the hand-written sections of the README, give links to API members the member as title, e.g., ``[`width`](#width "Column.width")``, so `vp run docs` keeps their anchor up to date. - **Docs** — keep `AGENTS.md` in sync with tooling, conventions, or architectural changes. - **Default renderers** — `DataGridRenderersContext` allows overriding default renderers (`renderCheckbox`, `renderSortStatus`, `renderRow`, `renderCell`, `noRowsFallback`) without prop-drilling. - **TypeScript strict** with `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, `erasableSyntaxOnly`. Distinguish missing properties from `undefined` values. diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts index 893679480b..d1541ac57e 100644 --- a/scripts/generateApiDocs.ts +++ b/scripts/generateApiDocs.ts @@ -62,9 +62,9 @@ interface Declaration { using api = new API(); using declarationsFile = api.createSourceFile( declarationsPath, - await readFile(declarationsPath, 'utf8') + await readFile(declarationsPath, 'utf-8') ); -using entryFile = api.createSourceFile(entryPath, await readFile(entryPath, 'utf8')); +using entryFile = api.createSourceFile(entryPath, await readFile(entryPath, 'utf-8')); const declarations = new Map(); // exported name -> declared name, e.g. `Cell` -> `MemoCell` @@ -141,7 +141,7 @@ for (const [section, items] of groups) { } } -const readme = await readFile(readmePath, 'utf8'); +const readme = await readFile(readmePath, 'utf-8'); const startIndex = readme.indexOf(startMarker); const endIndex = readme.indexOf(endMarker); @@ -246,7 +246,7 @@ function renderSummary({ summary }: Doc) { function renderTags({ tags }: Doc) { const labels: Record = { - defaultValue: '**Default:** ', + default: '**Default:** ', example: '**Example:**\n\n', see: '**See also:** ', returns: '**Returns:**\n\n' @@ -254,7 +254,7 @@ function renderTags({ tags }: Doc) { return tags .filter(({ name }) => { // the type parameters are described in the "Generics" section - if (name === 'typeParam') return false; + if (name === 'template') return false; if (name in labels) return true; throw new Error(`The @${name} tag is not supported in the API reference`); }) @@ -377,7 +377,7 @@ function hasRichMembers(node: InterfaceDeclaration) { return node.members.some((member) => { const { summary, tags } = getDoc(member); return ( - tags.some((tag) => tag.name !== 'defaultValue') || + tags.some((tag) => tag.name !== 'default') || summary.includes('\n\n') || summary.includes('```') || /^\s*(?:[-*+]|\d+\.) /m.test(summary) diff --git a/src/DataGrid.tsx b/src/DataGrid.tsx index fe873f7e94..b67ecc4bd5 100644 --- a/src/DataGrid.tsx +++ b/src/DataGrid.tsx @@ -124,9 +124,9 @@ export interface DataGridHandle { } /** - * @typeParam R - Row type - * @typeParam SR - Summary row type - * @typeParam K - Row key type + * @template R Row type + * @template SR Summary row type + * @template K Row key type */ export interface DataGridProps { /** @@ -234,7 +234,7 @@ export interface DataGridProps { * * ⚠️ **Performance:** When using a function, the heights of all rows are processed upfront. For large datasets (1000+ rows), this can cause performance issues if the identity of the function changes and invalidates internal memoization. Consider using a static function when possible, or memoize the `rowHeight` function. * - * @defaultValue `35` pixels + * @default `35` pixels * * @example * ```tsx @@ -253,13 +253,13 @@ export interface DataGridProps { /** * Height of the header row in pixels. * - * @defaultValue `rowHeight` when it is a number, otherwise `35` pixels + * @default `rowHeight` when it is a number, otherwise `35` pixels */ headerRowHeight?: Maybe; /** * Height of each summary row in pixels. * - * @defaultValue `rowHeight` when it is a number, otherwise `35` pixels + * @default `rowHeight` when it is a number, otherwise `35` pixels */ summaryRowHeight?: Maybe; /** @@ -573,7 +573,7 @@ export interface DataGridProps { /** * This prop can be used to disable virtualization. * - * @defaultValue `true` + * @default `true` */ enableVirtualization?: Maybe; @@ -655,7 +655,7 @@ export interface DataGridProps { * - Column resize is controlled on the left edge of the column * - Vertical scrollbar is moved to the left * - * @defaultValue `'ltr'` left-to-right + * @default `'ltr'` left-to-right * * @see {@linkcode Direction} */ @@ -671,7 +671,7 @@ export interface DataGridProps { /** * ARIA role for the grid container. * - * @defaultValue `'grid'` + * @default `'grid'` */ role?: React.AriaRole | undefined; /** @@ -724,9 +724,9 @@ export interface DataGridProps { * * ``` * - * @typeParam R - Row type - * @typeParam SR - Summary row type - * @typeParam K - Row key type + * @template R Row type + * @template SR Summary row type + * @template K Row key type */ export function DataGrid(props: DataGridProps) { const { diff --git a/src/TreeDataGrid.tsx b/src/TreeDataGrid.tsx index 480a129a1d..6c0c373a15 100644 --- a/src/TreeDataGrid.tsx +++ b/src/TreeDataGrid.tsx @@ -29,9 +29,9 @@ import { defaultRenderRow } from './Row'; /** * All {@linkcode DataGridProps} are supported except those listed above. The `columns` prop only supports `Column[]` (no column groups). When `rowHeight` is a function, it receives {@linkcode RowHeightArgs} instead of just the row, and `onCellKeyDown` and `onActivePositionChange` receive group rows too. Additional props are listed below: * - * @typeParam R - Row type - * @typeParam SR - Summary row type - * @typeParam K - Row key type + * @template R Row type + * @template SR Summary row type + * @template K Row key type */ export interface TreeDataGridProps extends Omit< DataGridProps, @@ -267,9 +267,9 @@ export function isGroupRow(row: R | GroupRow): row is GroupRow { * } * ``` * - * @typeParam R - Row type - * @typeParam SR - Summary row type - * @typeParam K - Row key type + * @template R Row type + * @template SR Summary row type + * @template K Row key type */ export function TreeDataGrid({ columns: rawColumns, diff --git a/src/types.ts b/src/types.ts index b369be6a1a..a4e2fb09f7 100644 --- a/src/types.ts +++ b/src/types.ts @@ -26,7 +26,7 @@ export interface Column { * * `max-content` can be used to expand the column to show all the content. Note that the grid is only able to calculate column width for visible rows. * - * @defaultValue `'auto'` + * @default `'auto'` * * @example * ```tsx @@ -61,7 +61,7 @@ export interface Column { /** * Minimum column width in pixels. * - * @defaultValue `50` pixels + * @default `50` pixels */ readonly minWidth?: Maybe; /** Maximum column width in pixels. */ @@ -169,7 +169,7 @@ export interface Column { * - `'end'` — pins the column to the end edge (right in LTR, left in RTL). * - `false` — the column scrolls with the rest of the grid. * - * @defaultValue `false` + * @default `false` * * @example * ```tsx @@ -186,25 +186,25 @@ export interface Column { /** * Enable resizing of the column. * - * @defaultValue `false` + * @default `false` */ readonly resizable?: Maybe; /** * Enable sorting of the column. * - * @defaultValue `false` + * @default `false` */ readonly sortable?: Maybe; /** * Enable dragging of the column. * - * @defaultValue `false` + * @default `false` */ readonly draggable?: Maybe; /** * Sets the column sort order to be descending instead of ascending the first time the column is sorted. * - * @defaultValue `false` + * @default `false` */ readonly sortDescendingFirst?: Maybe; /** Options for cell editing. */ @@ -213,19 +213,19 @@ export interface Column { * Render the cell content in addition to the edit cell content. Enable this option when the editor is rendered outside the grid, like a modal for example. * By default, the cell content is not rendered when the edit cell is open. * - * @defaultValue `false` + * @default `false` */ readonly displayCellContent?: Maybe; /** * Commit changes when clicking outside the cell. * - * @defaultValue `true` + * @default `true` */ readonly commitOnOutsideClick?: Maybe; /** * Close the editor when the row value changes externally. * - * @defaultValue `true` + * @default `true` */ readonly closeOnExternalRowChange?: Maybe; }>; @@ -572,7 +572,7 @@ interface EditCellKeyDownArgs { * } * ``` * - * @typeParam TActiveRow - The type of the active row in `ACTIVE` mode, `R | GroupRow` in `TreeDataGrid` + * @template TActiveRow The type of the active row in `ACTIVE` mode, `R | GroupRow` in `TreeDataGrid` * * @see {@linkcode DataGridProps.onCellKeyDown | onCellKeyDown} prop on ``, {@linkcode TreeCellKeyDownArgs} */ @@ -583,7 +583,7 @@ export type CellKeyDownArgs = /** * Arguments passed to `onActivePositionChange`. * - * @typeParam TActiveRow - The type of the active row, `R | GroupRow` in `TreeDataGrid` + * @template TActiveRow The type of the active row, `R | GroupRow` in `TreeDataGrid` * * @see {@linkcode DataGridProps.onActivePositionChange | onActivePositionChange} prop on ``, {@linkcode TreePositionChangeArgs} */ diff --git a/vite.config.ts b/vite.config.ts index 4cf358127d..fc5798f457 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -121,9 +121,10 @@ export default defineConfig({ // the root cause of errors reported by later checks 'vp run typecheck', 'vp check', - 'vp run eslint', // runs `vp pack`, then generates the API reference from its output 'vp run docs', + // after the docs, to lint the generated API reference + 'vp run eslint', 'git diff --exit-code README.md', 'vp build', 'git diff --exit-code website/routeTree.gen.ts', @@ -380,14 +381,6 @@ export default defineConfig({ builtin: true }, - settings: { - jsdoc: { - tagNamePreference: { - default: 'defaultValue' - } - } - }, - // https://oxc.rs/docs/guide/usage/linter/rules.html /* // copy all the rules from the rules table for easy pasting @@ -598,13 +591,7 @@ copy( 'eslint/yoda': 'off', 'jsdoc/check-access': 'warn', 'jsdoc/check-property-names': 'warn', - 'jsdoc/check-tag-names': [ - 'warn', - { - // TSDoc tags - definedTags: ['defaultValue', 'typeParam'] - } - ], + 'jsdoc/check-tag-names': 'warn', 'jsdoc/empty-tags': 'warn', 'jsdoc/implements-on-classes': 'warn', 'jsdoc/no-blank-blocks': 'warn',