diff --git a/AGENTS.md b/AGENTS.md index f7d740ea10..5ad471569f 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 (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 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. @@ -54,8 +57,9 @@ website/ # demo site (TanStack Start), prerendered for GitHub Pages 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 `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 @@ -66,4 +70,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 7572556ff4..edc591ef0b 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,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 'DataGridProps.className') and [`style`](#style 'DataGridProps.style') props: ```tsx 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 @@ -251,82 +251,128 @@ 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. ## API Reference + + ### Components #### `` +Main API component to render a data grid of rows and columns + +**Example:** + +```tsx + +``` + ##### DataGridProps -###### `columns: readonly ColumnOrColumnGroup[]` +###### `ref?` + +```tsx +ref?: Maybe>; +``` + +Optional ref for imperative APIs like scrolling to or focusing a cell. + +**See also:** [`DataGridHandle`](#datagridhandle) + +###### `columns` + +```tsx +columns: readonly ColumnOrColumnGroup[]; +``` + +An array of column definitions and/or column groups. -An array of column definitions and/or column groups. See the [`ColumnOrColumnGroup`](#columnorcolumngrouptrow-tsummaryrow) 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. -: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. +**See also:** [`ColumnOrColumnGroup`](#columnorcolumngroup) -###### `rows: readonly R[]` +###### `rows` + +```tsx +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 - **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))); -###### `ref?: Maybe>` +// ❌ Avoid: Creates new references for all rows, causing all visible rows to re-render +setRows(rows.map((row) => ({ ...row }))); +``` -Optional ref for imperative APIs like scrolling to or focusing a cell. See [`DataGridHandle`](#datagridhandle). +###### `topSummaryRows?` -###### `topSummaryRows?: Maybe` +```tsx +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?: Maybe` +```tsx +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. + +###### `getRowKey?` -###### `getRowKey?: Maybe<(row: R) => K>` +```tsx +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'; @@ -344,16 +390,18 @@ 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. +###### `onRowsChange?` -: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>` +```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`](#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. + +**Example:** ```tsx import { useState } from 'react'; @@ -366,12 +414,22 @@ function MyGrid() { } ``` -###### `rowHeight?: Maybe number)>` +**See also:** [`RowsChangeData`](#rowschangedata) -**Default:** `35` pixels +###### `rowHeight?` + +```tsx +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 ; @@ -384,34 +442,35 @@ 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?` + +```tsx +headerRowHeight?: Maybe; +``` -###### `headerRowHeight?: Maybe` +Height of the header row in pixels. **Default:** `rowHeight` when it is a number, otherwise `35` pixels -Height of the header row in pixels. +###### `summaryRowHeight?` + +```tsx +summaryRowHeight?: Maybe; +``` -###### `summaryRowHeight?: Maybe` +Height of each summary row in pixels. **Default:** `rowHeight` when it is a number, otherwise `35` pixels -Height of each summary row in pixels. +###### `columnWidths?` ```tsx - +columnWidths?: Maybe; ``` -###### `columnWidths?: Maybe` +A map of column widths containing both measured and resized widths. If not provided, an internal state is used. -A map of column widths containing both measured and resized widths. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths) type. +**Example:** ```tsx const [columnWidths, setColumnWidths] = useState((): ColumnWidths => new Map()); @@ -425,22 +484,44 @@ function addNewRow() { return ``` -###### `onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>` +**See also:** [`ColumnWidths`](#columnwidths-1) -Callback triggered when column widths change. If not provided, an internal state is used. See the [`ColumnWidths`](#columnwidths) type. +###### `onColumnWidthsChange?` -###### `selectedRows?: Maybe>` +```tsx +onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; +``` + +Callback triggered when column widths change. If not provided, an internal state is used. + +**See also:** [`ColumnWidths`](#columnwidths-1) + +###### `selectedRows?` + +```tsx +selectedRows?: Maybe>; +``` A set of selected row keys. `getRowKey` 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. +**Example:** + ```tsx import { useState } from 'react'; import { DataGrid, SelectColumn, type Column } from 'react-data-grid'; @@ -476,16 +557,30 @@ function MyGrid() { } ``` -###### `sortColumns?: Maybe` +###### `sortColumns?` -An array of sorted columns. See the [`SortColumn`](#sortcolumn) type. +```tsx +sortColumns?: Maybe; +``` + +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`. -###### `onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>` +**See also:** [`SortColumn`](#sortcolumn) + +###### `onSortColumnsChange?` + +```tsx +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'; @@ -515,17 +610,24 @@ 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)); } ``` -###### `defaultColumnOptions?: Maybe>` +###### `defaultColumnOptions?` + +```tsx +defaultColumnOptions?: Maybe>; +``` + +Default options applied to all columns. -Default options applied to all columns. See the [`DefaultColumnOptions`](#defaultcolumnoptionstrow-tsummaryrow) type. +**Example:** ```tsx function MyGrid() { @@ -544,9 +646,17 @@ function MyGrid() { } ``` -###### `onCellMouseDown?: CellMouseEventHandler` +**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 })`. -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`](#cellmouseargstrow-tsummaryrow) and [`CellMouseEvent`](#cellmouseevent) types. +**Example:** ```tsx function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { @@ -558,14 +668,21 @@ function onCellMouseDown(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellClick?: CellMouseEventHandler` +**See also:** [`CellMouseArgs`](#cellmouseargs), [`CellMouseEvent`](#cellmouseevent) + +###### `onCellClick?` -Callback triggered when a cell is clicked. See the [`CellMouseArgs`](#cellmouseargstrow-tsummaryrow) and [`CellMouseEvent`](#cellmouseevent) types. +```tsx +onCellClick?: CellMouseEventHandler; +``` + +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 }); } @@ -574,9 +691,17 @@ function onCellClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellDoubleClick?: CellMouseEventHandler` +**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. -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. +**Example:** ```tsx function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { @@ -588,9 +713,17 @@ function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellContextMenu?: CellMouseEventHandler` +**See also:** [`CellMouseArgs`](#cellmouseargs), [`CellMouseEvent`](#cellmouseevent) -Callback triggered when a cell is right-clicked. See the [`CellMouseArgs`](#cellmouseargstrow-tsummaryrow) and [`CellMouseEvent`](#cellmouseevent) types. +###### `onCellContextMenu?` + +```tsx +onCellContextMenu?: CellMouseEventHandler; +``` + +Callback triggered when a cell is right-clicked. + +**Example:** ```tsx function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { @@ -603,55 +736,94 @@ function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { ; ``` -###### `onCellKeyDown?: Maybe<(args: CellKeyDownArgs, event: CellKeyboardEvent) => void>` +**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`](#cellkeydownargstrow-tsummaryrow-tactiverow) 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-maybeprops-rendereditcellcontentpropstrow-tsummaryrow--reactnode). +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** +See [more examples](https://github.com/Comcast/react-data-grid/blob/main/website/routes/CellNavigation.tsx). -- Prevent editing on `Enter` +**Example:** ```tsx function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { - if (args.mode === 'ACTIVE' && event.key === 'Enter') { + if (args.mode === 'ACTIVE' && (event.key === 'Enter' || event.key === 'Tab')) { + // Prevent editing on `Enter` and navigation on `Tab` event.preventGridDefault(); } } ``` -- Prevent navigation on `Tab` +**See also:** [`CellKeyDownArgs`](#cellkeydownargs), [`CellKeyboardEvent`](#cellkeyboardevent) + +###### `onCellCopy?` ```tsx -function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { - if (args.mode === 'ACTIVE' && event.key === 'Tab') { - event.preventGridDefault(); - } -} +onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => void>; +``` + +Callback triggered when a cell's content is copied. + +**See also:** [`CellCopyArgs`](#cellcopyargs) + +###### `onCellPaste?` + +```tsx +onCellPaste?: Maybe<(args: CellPasteArgs, event: CellClipboardEvent) => R>; +``` + +Callback triggered when content is pasted into a cell. + +**Returns:** + +The updated row, which the grid passes to [`onRowsChange`](#onrowschange) + +**See also:** [`CellPasteArgs`](#cellpasteargs) + +###### `onActivePositionChange?` + +```tsx +onActivePositionChange?: Maybe<(args: PositionChangeArgs) => void>; ``` -See [more examples](website/routes/CellNavigation.tsx). +Callback triggered when the active position changes. -###### `onCellCopy?: Maybe<(args: CellCopyArgs, event: CellClipboardEvent) => void>` +**See also:** [`PositionChangeArgs`](#positionchangeargs) -Callback triggered when a cell's content is copied. See the [`CellCopyArgs`](#cellcopyargstrow-tsummaryrow) type. +###### `onColumnResize?` -###### `onCellPaste?: Maybe<(args: CellPasteArgs, event: CellClipboardEvent) => R>` +```tsx +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 content is pasted into a cell. See the [`CellPasteArgs`](#cellpasteargstrow-tsummaryrow) type. +###### `onColumnsReorder?` -Return the updated row; the grid will call `onRowsChange` with it. +```tsx +onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>; +``` -###### `onActivePositionChange?: Maybe<(args: PositionChangeArgs) => 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-tactiverow) type. +###### `onFill?` -###### `onFill?: Maybe<(event: FillEvent) => R>` +```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`](#filleventtrow) type. +The grid calls `onFill` for each editable target cell. + +**Example:** ```tsx function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { @@ -661,39 +833,51 @@ function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { ; ``` -###### `onScroll?: React.UIEventHandler | undefined` +**Returns:** -Native DOM `onScroll` prop. +The updated target row. The grid passes the updated rows to [`onRowsChange`](#onrowschange) -###### `onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void>` +**See also:** [`FillEvent`](#fillevent) -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. +###### `onScroll?` -###### `onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>` +```tsx +onScroll?: React.UIEventHandler | undefined; +``` -Callback triggered when columns are reordered. The parameters are the `key` values of the source and target columns. +Native DOM `onScroll` prop. -###### `enableVirtualization?: Maybe` +###### `enableVirtualization?` -**Default:** `true` +```tsx +enableVirtualization?: Maybe; +``` This prop can be used to disable virtualization. -###### `renderers?: Maybe>` +**Default:** `true` -Custom renderers for cells, rows, and other components. +###### `renderers?` + +```tsx +renderers?: Maybe>; +``` -See the [`Renderers`](#rendererstrow-tsummaryrow) type for the full shape. +Custom renderers for cells, rows, and other components. -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 @@ -718,32 +902,20 @@ const customRenderers: Renderers = { ; ``` -The default `` component can be wrapped via `renderers.renderRow` to add contexts or tweak props: +**See also:** [`Renderers`](#renderers-1) -```tsx -import { DataGrid, Row, type RenderRowProps } from 'react-data-grid'; +###### `rowClass?` -interface MyRow { - id: number; -} - -function myRowRenderer(key: React.Key, props: RenderRowProps) { - return ( - - - - ); -} - -function MyGrid() { - return ; -} +```tsx +rowClass?: Maybe<(row: R, rowIdx: number) => Maybe>; ``` -###### `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'; @@ -756,63 +928,109 @@ 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?` -###### `headerRowClass?: Maybe` +```tsx +headerRowClass?: Maybe; +``` Custom class name for the header row. +###### `direction?` + ```tsx - +direction?: Maybe; ``` -###### `direction?: Maybe<'ltr' | 'rtl'>` - -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. 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 -###### `className?: string | undefined` +**Default:** `'ltr'` left-to-right + +**See also:** [`Direction`](#direction-1) + +###### `className?` + +```tsx +className?: string | undefined; +``` Custom class name for the grid. -###### `style?: CSSProperties | undefined` +###### `style?` + +```tsx +style?: React.CSSProperties | undefined; +``` Custom styles for the grid. -###### `role?: string | undefined` +###### `role?` + +```tsx +role?: React.AriaRole | undefined; +``` + +ARIA role for the grid container. -ARIA role for the grid container. Defaults to `grid`. +**Default:** `'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`. +**Example:** + ```tsx function MyGrid() { return ; @@ -824,7 +1042,11 @@ test('grid', async () => { }); ``` -###### `'data-cy'?: Maybe` +###### `data-cy?` + +```tsx +'data-cy'?: Maybe; +``` Optional attribute to help with Cypress (or similar) selectors. @@ -863,7 +1085,9 @@ The following `DataGrid` props are not supported in `TreeDataGrid`: **Group rows in callbacks:** -Callbacks that receive the active row receive group rows too: `onCellKeyDown` and `onActivePositionChange`. Their arguments are typed with [`TreeCellKeyDownArgs`](#treecellkeydownargstrow-tsummaryrow) and [`TreePositionChangeArgs`](#treepositionchangeargstrow-tsummaryrow); use [`isGroupRow`](#isgrouprowtrowrow-trow--grouprowtrow-row-is-grouprowtrow) to tell group rows apart from regular rows. +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'; @@ -880,12 +1104,67 @@ function onCellKeyDown(args: TreeCellKeyDownArgs, event: CellKeyboardEvent) ##### 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`](#rowheightargstrow) instead of just the row, and `onCellKeyDown` and `onActivePositionChange` receive group rows too. 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, and `onCellKeyDown` and `onActivePositionChange` receive group rows too. Additional props are listed below: + +###### `columns` + +```tsx +columns: readonly Column[]; +``` + +###### `rowHeight?` + +```tsx +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. + +**Example:** + +```tsx +function getRowHeight(args: RowHeightArgs): number { + if (args.type === 'GROUP') { + return 50; // Custom height for group rows + } + return 35; // Height for regular rows +} + + +``` + +###### `onCellKeyDown?` + +```tsx +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 also:** [`TreeCellKeyDownArgs`](#treecellkeydownargs), [`onCellKeyDown`](#oncellkeydown) prop on `` -###### `groupBy: readonly string[]` +###### `onActivePositionChange?` + +```tsx +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 also:** [`TreePositionChangeArgs`](#treepositionchangeargs) + +###### `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.). +⚠️ **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'; @@ -916,12 +1195,16 @@ function MyGrid() { } ``` -:warning: **Performance:** Define this array outside your component or memoize it with `useMemo`, otherwise all the rows are grouped again on every render. +###### `expandedGroupIds` -###### `expandedGroupIds: ReadonlySet` +```tsx +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'; @@ -939,15 +1222,27 @@ function MyGrid() { } ``` -###### `onExpandedGroupIdsChange: (expandedGroupIds: Set) => void` +###### `onExpandedGroupIdsChange` + +```tsx +onExpandedGroupIdsChange: (expandedGroupIds: Set) => void; +``` **Required.** Callback triggered when groups are expanded or collapsed. -###### `getRowGroupKey?: Maybe<(row: R, columnKey: string) => string>` +###### `getRowGroupKey?` + +```tsx +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 { @@ -958,60 +1253,43 @@ function getRowGroupKey(row: Row, columnKey: string): string { } ``` -:warning: **Performance:** Define this function outside your component or memoize it with `useCallback`, otherwise all the rows are grouped again on every render. - -###### `getGroupId?: 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. - -###### `rowHeight?: Maybe) => number)>` - -**Note:** Unlike `DataGrid`, the `rowHeight` function receives [`RowHeightArgs`](#rowheightargstrow), which includes a `type` property to distinguish between regular rows and group rows: +###### `getGroupId?` ```tsx -function getRowHeight(args: RowHeightArgs): number { - if (args.type === 'GROUP') { - return 50; // Custom height for group rows - } - return 35; // Height for regular rows -} - - +getGroupId?: Maybe<(groupKey: string, parentId?: string) => string>; ``` -###### `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`](#isgrouprowtrowrow-trow--grouprowtrow-row-is-grouprowtrow) to narrow it. See the [`TreeCellKeyDownArgs`](#treecellkeydownargstrow-tsummaryrow) type and the [`onCellKeyDown`](#oncellkeydown-maybeargs-cellkeydownargsr-sr-event-cellkeyboardevent--void) prop on ``. - -###### `onActivePositionChange?: Maybe<(args: TreePositionChangeArgs) => void>` +Function to generate unique IDs for group rows. If not provided, a default implementation is used that concatenates parent and group keys with `__`. -Callback triggered when the active position changes, including to a group row or a cell of one: use [`isGroupRow`](#isgrouprowtrowrow-trow--grouprowtrow-row-is-grouprowtrow) to narrow the row. See the [`TreePositionChangeArgs`](#treepositionchangeargstrow-tsummaryrow) type. +⚠️ **Performance:** Define this function outside your component or memoize it with `useCallback` to prevent unnecessary re-renders. #### `` -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 -[`RenderRowProps`](#renderrowpropstrow-tsummaryrow) +[`RenderRowProps`](#renderrowprops) #### `` -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 -[`RenderCellProps`](#rendercellpropstrow-tsummaryrow) +[`RenderCellProps`](#rendercellprops) #### `` A component for rendering row selection checkboxes. -##### Props +##### SelectCheckboxProps + +The same props as [`RenderCheckboxProps`](#rendercheckboxprops). -The same props as [`RenderCheckboxProps`](#rendercheckboxprops), with `checked` required. +```tsx +type SelectCheckboxProps = RenderCheckboxProps; +``` #### `` @@ -1019,16 +1297,26 @@ Low-level component used by `renderToggleGroup` to render the expand/collapse co ##### Props -[`RenderGroupCellContentProps`](#rendergroupcellcontentpropstrow-tsummaryrow) +[`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:** +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 @@ -1061,10 +1349,20 @@ 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:** +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 @@ -1094,11 +1392,15 @@ function CustomSelectCell({ row }: RenderCellContentProps) { ### Render Functions -#### `renderHeaderCell(props: RenderHeaderCellContentProps)` +#### `renderHeaderCell()` -The default header cell content renderer. Renders sortable columns with sort indicators. +```tsx +function renderHeaderCell( + props: RenderHeaderCellContentProps +): string | React.JSX.Element; +``` -**Props:** [`RenderHeaderCellContentProps`](#renderheadercellcontentpropstrow-tsummaryrow) +The default header cell content renderer. Renders sortable columns with sort indicators. **Example:** @@ -1115,11 +1417,13 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderTextEditor(props: RenderEditCellContentProps)` +#### `renderTextEditor()` -A basic text editor provided for convenience. +```tsx +function renderTextEditor(props: RenderEditCellContentProps): React.JSX.Element; +``` -**Props:** [`RenderEditCellContentProps`](#rendereditcellcontentpropstrow-tsummaryrow) +A basic text editor provided for convenience. **Example:** @@ -1135,24 +1439,30 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderSortIcon(props: RenderSortIconProps)` +#### `renderSortIcon()` + +```tsx +function renderSortIcon(props: RenderSortIconProps): React.JSX.Element | null; +``` Renders the sort direction arrow icon. -**Props:** [`RenderSortIconProps`](#rendersorticonprops) +#### `renderSortPriority()` -#### `renderSortPriority(props: RenderSortPriorityProps)` +```tsx +function renderSortPriority(props: RenderSortPriorityProps): number | undefined; +``` Renders the sort priority number for multi-column sorting. -**Props:** [`RenderSortPriorityProps`](#rendersortpriorityprops) +#### `renderCheckbox()` -#### `renderCheckbox(props: RenderCheckboxProps)` +```tsx +function renderCheckbox(props: RenderCheckboxProps): React.JSX.Element; +``` Renders a checkbox input with proper styling and accessibility. -**Props:** [`RenderCheckboxProps`](#rendercheckboxprops) - **Example:** ```tsx @@ -1165,11 +1475,13 @@ import { DataGrid, renderCheckbox } from 'react-data-grid'; />; ``` -#### `renderToggleGroup(props: RenderGroupCellContentProps)` +#### `renderToggleGroup()` -The default group cell content renderer for the columns used for grouping (`groupBy` prop). This renders the group key, `row.groupKey`, and the expand/collapse toggle. +```tsx +function renderToggleGroup(props: RenderGroupCellContentProps): React.JSX.Element; +``` -**Props:** [`RenderGroupCellContentProps`](#rendergroupcellcontentpropstrow-tsummaryrow) +The default group cell content renderer for the columns used for grouping (`groupBy` prop). This renders the group key, `row.groupKey`, and the expand/collapse toggle. **Example:** @@ -1185,11 +1497,13 @@ const columns: readonly Column[] = [ ]; ``` -#### `renderValue(props: RenderCellContentProps)` +#### `renderValue()` -The default cell content renderer that renders the value of `row[column.key]`. +```tsx +function renderValue(props: RenderCellContentProps): React.ReactNode; +``` -**Props:** [`RenderCellContentProps`](#rendercellcontentpropstrow-tsummaryrow) +The default cell content renderer that renders the value of `row[column.key]`. **Example:** @@ -1209,6 +1523,10 @@ const columns: readonly Column[] = [ #### `DataGridRenderersContext` +```tsx +const DataGridRenderersContext: React.Context>>; +``` + Context for providing default renderers to DataGrids in your app. **Example:** @@ -1244,7 +1562,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. @@ -1273,7 +1595,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. @@ -1285,7 +1611,11 @@ import { SELECT_COLUMN_KEY } from 'react-data-grid'; const nonSelectColumns = columns.filter((column) => column.key !== SELECT_COLUMN_KEY); ``` -#### `isGroupRow(row: TRow | GroupRow): row is GroupRow` +#### `isGroupRow()` + +```tsx +function isGroupRow(row: R | GroupRow): row is GroupRow; +``` Returns whether a row of a `TreeDataGrid` is a group row, e.g., the active row passed to `onCellKeyDown` or `onActivePositionChange`. @@ -1300,30 +1630,46 @@ function onActivePositionChange({ row }: TreePositionChangeArgs) { } ``` -**See also:** [`GroupRow`](#grouprowtrow), [`TreeCellKeyDownArgs`](#treecellkeydownargstrow-tsummaryrow), [`TreePositionChangeArgs`](#treepositionchangeargstrow-tsummaryrow) +**See also:** [`GroupRow`](#grouprow), [`TreeCellKeyDownArgs`](#treecellkeydownargs), [`TreePositionChangeArgs`](#treepositionchangeargs) ### 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` -##### `name: string | ReactElement` +```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?` -**Default:** `auto` +```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. +`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[] = [ { @@ -1341,37 +1687,45 @@ 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: +##### `minWidth?` ```tsx -width: 80, // pixels -width: '25%', -width: 'max-content', -width: 'minmax(100px, max-content)', +readonly minWidth?: Maybe; ``` -`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` +Minimum column width in pixels. **Default:** `50` pixels -Minimum column width in pixels. +##### `maxWidth?` -##### `maxWidth?: Maybe` +```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. +**Example:** + ```tsx const columns: Column[] = [ { @@ -1402,29 +1756,55 @@ 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`. The group row is passed as `row`, a [`GroupRow`](#grouprow) with the group's key, rows, and expanded state. -Render function to render the content of group cells when using `TreeDataGrid`. The group row is passed as `row`, a [`GroupRow`](#grouprowtrow) with the group's key, rows, and expanded state. +**Example:** ```tsx const columns: readonly Column[] = [ @@ -1438,19 +1818,31 @@ const columns: readonly Column[] = [ ]; ``` -##### `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. Editors can render a [`:modal`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:modal) element, like a `` opened with `showModal()`, either in the cell or in a portal. Keydown events triggered in the modal are left to the editor: `onCellKeyDown` is not called, and the grid does not close the editor on `Escape`/`Enter` or navigate on `Tab`, so the editor must call `onClose` itself, for example in the dialog's `onClose` handler. -##### `editable?: Maybe boolean)>` +##### `editable?` + +```tsx +readonly editable?: Maybe boolean)>; +``` Control whether cells can be edited with `renderEditCell`. -##### `colSpan?: Maybe<(args: ColSpanArgs) => Maybe>` +##### `colSpan?` + +```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. The span is clamped to the start-frozen, unfrozen, or end-frozen columns, whichever the column is part of. See the [`ColSpanArgs`](#colspanargstrow-tsummaryrow) 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:** @@ -1471,15 +1863,27 @@ const columns: readonly Column[] = [ ]; ``` -##### `frozen?: Maybe` +**Returns:** -**Default:** `false` +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[] = [ @@ -1489,53 +1893,84 @@ const columns: readonly Column[] = [ ]; ``` -##### `resizable?: Maybe` +**See also:** [`ColumnFrozen`](#columnfrozen) -**Default:** `false` +##### `resizable?` -Enable resizing of the column. +```tsx +readonly resizable?: Maybe; +``` -##### `sortable?: Maybe` +Enable resizing of the column. **Default:** `false` -Enable sorting of the column. +##### `sortable?` + +```tsx +readonly sortable?: Maybe; +``` -##### `draggable?: Maybe` +Enable sorting of the column. **Default:** `false` -Enable dragging of the column. +##### `draggable?` -##### `sortDescendingFirst?: Maybe` +```tsx +readonly draggable?: Maybe; +``` + +Enable dragging of the column. **Default:** `false` +##### `sortDescendingFirst?` + +```tsx +readonly sortDescendingFirst?: Maybe; +``` + Sets the column sort order to be descending instead of ascending the first time the column is sorted. +**Default:** `false` + ##### `editorOptions` Options for cell editing. -###### `displayCellContent?: Maybe` +###### `displayCellContent?` -**Default:** `false` +```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. -###### `commitOnOutsideClick?: Maybe` +**Default:** `false` -**Default:** `true` +###### `commitOnOutsideClick?` -Commit changes when clicking outside the cell. +```tsx +readonly commitOnOutsideClick?: Maybe; +``` -###### `closeOnExternalRowChange?: Maybe` +Commit changes when clicking outside the cell. **Default:** `true` +###### `closeOnExternalRowChange?` + +```tsx +readonly closeOnExternalRowChange?: Maybe; +``` + Close the editor when the row value changes externally. -#### `ColumnGroup` +**Default:** `true` + +#### `ColumnGroup` Defines a group of columns that share a common header. @@ -1564,22 +1999,26 @@ const columns: readonly ColumnOrColumnGroup[] = [ ]; ``` -**See also:** [`ColumnOrColumnGroup`](#columnorcolumngrouptrow-tsummaryrow) +**See also:** [`ColumnOrColumnGroup`](#columnorcolumngroup) -#### `ColumnOrColumnGroup` +#### `ColumnOrColumnGroup` Union type representing either a `Column` or a `ColumnGroup`. -**See also:** [`columns`](#columns-readonly-columnorcolumngroupr-sr) prop on `` +```tsx +type ColumnOrColumnGroup = Column | ColumnGroup; +``` + +**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. 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. ```tsx -interface CalculatedColumn extends Column { +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 */ @@ -1591,27 +2030,26 @@ interface CalculatedColumn extends Column) => ReactNode; - readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; + readonly renderCell: (props: RenderCellContentProps) => ReactNode; + readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; /** Returns the number of columns that the cell spans: the clamped value returned by `colSpan`, or `1` */ - readonly getColSpan: (args: ColSpanArgs | undefined) => number; - // Always set, `undefined` when not set on the column - readonly cellClass: Column['cellClass']; - readonly headerCellClass: Column['headerCellClass']; - readonly summaryCellClass: Column['summaryCellClass']; - readonly renderSummaryCell: Column['renderSummaryCell']; - readonly renderGroupCell: Column['renderGroupCell']; - readonly renderEditCell: Column['renderEditCell']; - readonly editable: Column['editable']; - readonly colSpan: Column['colSpan']; - readonly sortDescendingFirst: Column['sortDescendingFirst']; - readonly editorOptions: Column['editorOptions']; + readonly getColSpan: (args: ColSpanArgs | undefined) => number; + readonly cellClass: Column['cellClass']; + readonly headerCellClass: Column['headerCellClass']; + readonly summaryCellClass: Column['summaryCellClass']; + readonly renderSummaryCell: Column['renderSummaryCell']; + readonly renderGroupCell: Column['renderGroupCell']; + readonly renderEditCell: Column['renderEditCell']; + readonly editable: Column['editable']; + readonly colSpan: Column['colSpan']; + readonly sortDescendingFirst: Column['sortDescendingFirst']; + readonly editorOptions: Column['editorOptions']; } ``` -**See also:** [`Column`](#columntrow-tsummaryrow), [`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. @@ -1626,9 +2064,9 @@ interface CalculatedColumnParent { } ``` -**See also:** [`CalculatedColumn`](#calculatedcolumntrow-tsummaryrow) +**See also:** [`CalculatedColumn`](#calculatedcolumn) -#### `CalculatedColumnOrColumnGroup` +#### `CalculatedColumnOrColumnGroup` Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. @@ -1636,15 +2074,15 @@ Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn type CalculatedColumnOrColumnGroup = CalculatedColumnParent | CalculatedColumn; ``` -**See also:** [`CalculatedColumn`](#calculatedcolumntrow-tsummaryrow), [`CalculatedColumnParent`](#calculatedcolumnparenttrow-tsummaryrow) +**See also:** [`CalculatedColumn`](#calculatedcolumn), [`CalculatedColumnParent`](#calculatedcolumnparent) -#### `DefaultColumnOptions` +#### `DefaultColumnOptions` Default options applied to all columns. ```tsx -type DefaultColumnOptions = Pick< - Column, +type DefaultColumnOptions = Pick< + Column, | 'renderCell' | 'renderHeaderCell' | 'width' @@ -1656,7 +2094,7 @@ type DefaultColumnOptions = Pick< >; ``` -**See also:** [`defaultColumnOptions`](#defaultcolumnoptions-maybedefaultcolumnoptionsr-sr) prop on `` +**See also:** [`defaultColumnOptions`](#defaultcolumnoptions) prop on `` #### `ColumnFrozen` @@ -1666,20 +2104,20 @@ Whether a column is frozen, and on which edge. type ColumnFrozen = false | 'start' | 'end'; ``` -**See also:** [`column.frozen`](#frozen-maybecolumnfrozen--true) +**See also:** [`column.frozen`](#frozen) -#### `RenderCellContentProps` +#### `RenderCellContentProps` -Props passed to custom cell content renderers (`column.renderCell`). +Props passed to custom cell content renderers ([`column.renderCell`](#rendercell)). ```tsx -interface RenderCellContentProps { - column: CalculatedColumn; - row: TRow; +interface RenderCellContentProps { + column: CalculatedColumn; + row: R; rowIdx: number; isCellEditable: boolean; tabIndex: number; - onRowChange: (row: TRow) => void; + onRowChange: (row: R) => void; } ``` @@ -1698,33 +2136,33 @@ function renderCell({ row, column, onRowChange }: RenderCellContentProps) } ``` -**See also:** [`column.renderCell`](#rendercell-maybeprops-rendercellcontentpropstrow-tsummaryrow--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`). +Props passed to custom header cell content renderers ([`column.renderHeaderCell`](#renderheadercell-1)). ```tsx -interface RenderHeaderCellContentProps { - column: CalculatedColumn; +interface RenderHeaderCellContentProps { + column: CalculatedColumn; sortDirection: SortDirection | undefined; priority: number | undefined; tabIndex: number; } ``` -**See also:** [`column.renderHeaderCell`](#renderheadercell-maybeprops-renderheadercellcontentpropstrow-tsummaryrow--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`). +Props passed to custom editors ([`column.renderEditCell`](#rendereditcell)). ```tsx -interface RenderEditCellContentProps { - column: CalculatedColumn; - row: TRow; +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; } ``` @@ -1746,47 +2184,47 @@ function renderEditor({ row, column, onRowChange, onClose }: RenderEditCellConte } ``` -**See also:** [`column.renderEditCell`](#rendereditcell-maybeprops-rendereditcellcontentpropstrow-tsummaryrow--reactnode), [`renderTextEditor`](#rendertexteditortrow-tsummaryrowprops-rendereditcellcontentpropstrow-tsummaryrow) function +**See also:** [`column.renderEditCell`](#rendereditcell), [`renderTextEditor`](#rendertexteditor) function -#### `RenderSummaryCellContentProps` +#### `RenderSummaryCellContentProps` -Props passed to summary cell content renderers (`column.renderSummaryCell`). +Props passed to summary cell content renderers ([`column.renderSummaryCell`](#rendersummarycell)). ```tsx -interface RenderSummaryCellContentProps { - column: CalculatedColumn; - row: TSummaryRow; +interface RenderSummaryCellContentProps { + column: CalculatedColumn; + row: SR; tabIndex: number; } ``` -**See also:** [`column.renderSummaryCell`](#rendersummarycell-maybeprops-rendersummarycellcontentpropstsummaryrow-trow--reactnode) +**See also:** [`column.renderSummaryCell`](#rendersummarycell) -#### `RenderGroupCellContentProps` +#### `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 { - column: CalculatedColumn; +interface RenderGroupCellContentProps { + column: CalculatedColumn; /** The group row: its key, rows, expanded state, level, and ID */ - row: GroupRow; + row: GroupRow; tabIndex: number; /** Expands or collapses the group */ toggleGroup: () => void; } ``` -**See also:** [`column.renderGroupCell`](#rendergroupcell-maybeprops-rendergroupcellcontentpropstrow-tsummaryrow--reactnode), [`renderToggleGroup`](#rendertogglegroupr-srprops-rendergroupcellcontentpropsr-sr) function, [``](#togglegroup-), [`GroupRow`](#grouprowtrow) +**See also:** [`column.renderGroupCell`](#rendergroupcell), [`renderToggleGroup`](#rendertogglegroup) function, [``](#togglegroup-), [`GroupRow`](#grouprow) -#### `GroupRow` +#### `GroupRow` Represents a group row in `TreeDataGrid`. ```tsx -interface GroupRow { +interface GroupRow { /** The rows of the group, including the rows of its subgroups */ - readonly childRows: readonly TRow[]; + readonly childRows: readonly R[]; /** The group's ID, returned by `getGroupId` */ readonly id: string; /** The ID of the parent group, or `undefined` on the first level */ @@ -1806,15 +2244,21 @@ interface GroupRow { } ``` -**See also:** [`RenderGroupCellContentProps`](#rendergroupcellcontentpropstrow-tsummaryrow), [`RowHeightArgs`](#rowheightargstrow), [``](#treedatagrid-) +**See also:** [`RenderGroupCellContentProps`](#rendergroupcellcontentprops), [`RowHeightArgs`](#rowheightargs), [``](#treedatagrid-) -#### `RenderRowProps` +#### `RenderRowProps` Props passed to custom row renderers. ```tsx -interface RenderRowProps { - row: TRow; +interface RenderRowProps + extends + Omit, 'children'>, + Pick< + DataGridProps, + 'onCellMouseDown' | 'onCellClick' | 'onCellDoubleClick' | 'onCellContextMenu' + > { + setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; /** * Calls `callback` for each cell to render in the row, and returns the results. * `activeIdx` is the column index of the row's active cell, if any: that cell is rendered even when it is scrolled out of view. @@ -1822,62 +2266,47 @@ interface RenderRowProps { * `colSpanArgs` is passed to `column.colSpan`, and the columns that a cell spans are skipped, even the active one. * The callback receives the cell's column, whether the cell is active, its `colSpan`, and its index in the results. */ - mapViewportColumns: MapViewportColumns; + mapViewportColumns: MapViewportColumns; rowIdx: number; activeCellIdx: number | undefined; isRowSelectionDisabled: boolean; isRowSelected: boolean; gridRowStart: number; + 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; - setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; - // ... and DOM props, cell event handlers (onCellMouseDown, onCellClick, onCellDoubleClick, onCellContextMenu) } ``` -**See also:** [`renderers.renderRow`](#renderers-mayberenderersr-sr), [``](#row-), [`MapViewportColumns`](#mapviewportcolumnstrow-tsummaryrow-internal) - -#### `MapViewportColumns` (internal) - -Type of `mapViewportColumns` in `RenderRowProps`. This helper type is not exported; the shape is shown for reference. - -```tsx -type MapViewportColumns = ( - activeIdx: number | undefined, - colSpanArgs: ColSpanArgs | undefined, - callback: ( - column: CalculatedColumn, - isCellActive: boolean, - colSpan: number, - index: number - ) => T -) => T[]; -``` - -**See also:** [`RenderRowProps`](#renderrowpropstrow-tsummaryrow), [`ColSpanArgs`](#colspanargstrow-tsummaryrow) +**See also:** [`renderers.renderRow`](#renderers), [``](#row-), [`MapViewportColumns`](#mapviewportcolumns-internal) -#### `RenderCellProps` +#### `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 { - column: CalculatedColumn; - row: TRow; +interface RenderCellProps + extends + Omit, 'children'>, + Pick< + DataGridProps, + 'onCellMouseDown' | 'onCellClick' | 'onCellDoubleClick' | 'onCellContextMenu' + > { rowIdx: number; + setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; + column: CalculatedColumn; + row: R; colSpan: number; 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) + onRowChange: (column: CalculatedColumn, rowIdx: number, newRow: R) => void; } ``` -**See also:** [`renderers.renderCell`](#renderers-mayberenderersr-sr), [``](#cell-) +**See also:** [`renderers.renderCell`](#renderers), [``](#cell-) #### `RenderCheckboxProps` @@ -1886,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 */ @@ -1902,7 +2331,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` @@ -1912,7 +2341,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` @@ -1925,7 +2354,7 @@ interface RenderSortIconProps { } ``` -**See also:** [`renderSortIcon`](#rendersorticonprops-rendersorticonprops) function +**See also:** [`renderSortIcon`](#rendersorticon) function #### `RenderSortPriorityProps` @@ -1938,34 +2367,34 @@ interface RenderSortPriorityProps { } ``` -**See also:** [`renderSortPriority`](#rendersortpriorityprops-rendersortpriorityprops) function +**See also:** [`renderSortPriority`](#rendersortpriority) function -#### `Renderers` +#### `Renderers` Custom renderer configuration for the grid. ```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; +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) +**See also:** [`renderers`](#renderers) prop on ``, [`DataGridRenderersContext`](#datagridrendererscontext) -#### `CellMouseArgs` +#### `CellMouseArgs` Arguments passed to cell mouse event handlers. ```tsx -interface CellMouseArgs { +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; /** Sets the active position to the cell. Pass `{ enableEditor: true }` to open its editor, or `{ shouldFocus: true }` to also focus it. */ @@ -1984,32 +2413,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 `` - -#### `CellMouseEventHandler` (internal) - -Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. - -```tsx -type CellMouseEventHandler = Maybe< - (args: CellMouseArgs, event: CellMouseEvent) => void ->; -``` - -#### `CellEvent` (internal) - -Adds grid-specific methods to a React event. This helper type is not exported; the shape is shown for reference. - -```tsx -type CellEvent> = E & { - /** Prevents the default grid behavior for this event */ - preventGridDefault: () => void; - /** Returns whether `preventGridDefault` was called */ - isGridDefaultPrevented: () => boolean; -}; -``` - -**See also:** [`CellMouseEvent`](#cellmouseevent), [`CellKeyboardEvent`](#cellkeyboardevent) +**See also:** [`onCellMouseDown`](#oncellmousedown), [`onCellClick`](#oncellclick), [`onCellDoubleClick`](#oncelldoubleclick), and [`onCellContextMenu`](#oncellcontextmenu) props on `` #### `CellMouseEvent` @@ -2031,45 +2435,34 @@ 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. ```tsx -/** - * @typeParam TActiveRow - The type of the active row in `ACTIVE` mode, `TRow | GroupRow` in `TreeDataGrid` - */ -type CellKeyDownArgs = - | ActiveCellKeyDownArgs - | EditCellKeyDownArgs; -``` - -**ACTIVE mode:** +type CellKeyDownArgs = + | ActiveCellKeyDownArgs + | EditCellKeyDownArgs; -```tsx -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; + column: CalculatedColumn | undefined; /** The active row. In `TreeDataGrid`, it can be a `GroupRow`, see `isGroupRow` */ row: TActiveRow; rowIdx: number; setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; } -``` -**EDIT mode:** - -```tsx -interface EditCellKeyDownArgs { +interface EditCellKeyDownArgs { mode: 'EDIT'; - column: CalculatedColumn; - row: TRow; + column: CalculatedColumn; + row: R; rowIdx: number; navigate: () => void; onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; @@ -2089,7 +2482,7 @@ function onCellKeyDown(args: CellKeyDownArgs, event: CellKeyboardEvent) { } ``` -**See also:** [`onCellKeyDown`](#oncellkeydown-maybeargs-cellkeydownargsr-sr-event-cellkeyboardevent--void) prop on ``, [`TreeCellKeyDownArgs`](#treecellkeydownargstrow-tsummaryrow) +**See also:** [`onCellKeyDown`](#oncellkeydown) prop on ``, [`TreeCellKeyDownArgs`](#treecellkeydownargs) #### `CellKeyboardEvent` @@ -2099,53 +2492,44 @@ Extends `React.KeyboardEvent` with grid-specific methods. type CellKeyboardEvent = CellEvent>; ``` -**See also:** [`onCellKeyDown`](#oncellkeydown-maybeargs-cellkeydownargsr-sr-event-cellkeyboardevent--void) prop on `` - -#### `CellClipboardEvent` (internal) - -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; -``` - -**See also:** [`onCellCopy`](#oncellcopy-maybeargs-cellcopyargsr-sr-event-cellclipboardevent--void) and [`onCellPaste`](#oncellpaste-maybeargs-cellpasteargsr-sr-event-cellclipboardevent--r) props on `` +**See also:** [`onCellKeyDown`](#oncellkeydown) prop on `` -#### `CellCopyArgs` +#### `CellCopyArgs` Arguments passed to `onCellCopy`. ```tsx -interface CellCopyArgs { - column: CalculatedColumn; - row: TRow; +type CellCopyArgs = CellCopyPasteArgs; + +interface CellCopyPasteArgs { + column: CalculatedColumn; + row: R; } ``` -**See also:** [`onCellCopy`](#oncellcopy-maybeargs-cellcopyargsr-sr-event-cellclipboardevent--void) prop on `` +**See also:** [`onCellCopy`](#oncellcopy) prop on `` -#### `CellPasteArgs` +#### `CellPasteArgs` Arguments passed to `onCellPaste`. ```tsx -interface CellPasteArgs { - column: CalculatedColumn; - row: TRow; +type CellPasteArgs = CellCopyPasteArgs; + +interface CellCopyPasteArgs { + column: CalculatedColumn; + row: R; } ``` -**See also:** [`onCellPaste`](#oncellpaste-maybeargs-cellpasteargsr-sr-event-cellclipboardevent--r) prop on `` +**See also:** [`onCellPaste`](#oncellpaste) prop on `` -#### `PositionChangeArgs` +#### `PositionChangeArgs` Arguments passed to `onActivePositionChange`. ```tsx -/** - * @typeParam TActiveRow - The type of the active row, `TRow | GroupRow` in `TreeDataGrid` - */ -interface PositionChangeArgs { +interface PositionChangeArgs { /** row index of the active position */ rowIdx: number; /** @@ -2158,51 +2542,49 @@ interface PositionChangeArgs { * column object of the active position, * undefined if the active position is a row instead of a cell */ - column: CalculatedColumn | undefined; + column: CalculatedColumn | undefined; } ``` -**See also:** [`onActivePositionChange`](#onactivepositionchange-maybeargs-positionchangeargsr-sr--void) prop on ``, [`TreePositionChangeArgs`](#treepositionchangeargstrow-tsummaryrow) +**See also:** [`onActivePositionChange`](#onactivepositionchange) prop on ``, [`TreePositionChangeArgs`](#treepositionchangeargs) -#### `TreeCellKeyDownArgs` +#### `TreeCellKeyDownArgs` Arguments passed to the `onCellKeyDown` handler of `TreeDataGrid`: the active row can be a group row. ```tsx -/** The arguments of `TreeDataGrid`'s `onCellKeyDown`, whose active row can be a `GroupRow` */ -type TreeCellKeyDownArgs = CellKeyDownArgs< - TRow, - TSummaryRow, - TRow | GroupRow ->; +type TreeCellKeyDownArgs = CellKeyDownArgs>; ``` -**See also:** [`onCellKeyDown`](#oncellkeydown-maybeargs-treecellkeydownargsr-sr-event-cellkeyboardevent--void) prop on ``, [`CellKeyDownArgs`](#cellkeydownargstrow-tsummaryrow-tactiverow), [`isGroupRow`](#isgrouprowtrowrow-trow--grouprowtrow-row-is-grouprowtrow) +**See also:** [`onCellKeyDown`](#oncellkeydown-1) prop on ``, [`CellKeyDownArgs`](#cellkeydownargs), [`isGroupRow`](#isgrouprow) -#### `TreePositionChangeArgs` +#### `TreePositionChangeArgs` Arguments passed to the `onActivePositionChange` handler of `TreeDataGrid`: the active row can be a group row. ```tsx -/** The arguments of `TreeDataGrid`'s `onActivePositionChange`, whose row can be a `GroupRow` */ -type TreePositionChangeArgs = PositionChangeArgs< - TRow, - TSummaryRow, - TRow | GroupRow ->; +type TreePositionChangeArgs = PositionChangeArgs>; ``` -**See also:** [`onActivePositionChange`](#onactivepositionchange-maybeargs-treepositionchangeargsr-sr--void) prop on ``, [`PositionChangeArgs`](#positionchangeargstrow-tsummaryrow-tactiverow), [`isGroupRow`](#isgrouprowtrowrow-trow--grouprowtrow-row-is-grouprowtrow) +**See also:** [`onActivePositionChange`](#onactivepositionchange-1) prop on ``, [`PositionChangeArgs`](#positionchangeargs), [`isGroupRow`](#isgrouprow) -#### `ColSpanArgs` +#### `ColSpanArgs` Arguments passed to the `colSpan` function. ```tsx -type ColSpanArgs = - | { readonly type: 'HEADER' } - | { readonly type: 'ROW'; readonly row: TRow } - | { readonly type: 'SUMMARY'; readonly row: TSummaryRow }; +type ColSpanArgs = + | { + readonly type: 'HEADER'; + } + | { + readonly type: 'ROW'; + readonly row: R; + } + | { + readonly type: 'SUMMARY'; + readonly row: SR; + }; ``` **Example:** @@ -2224,14 +2606,22 @@ const columns: readonly Column[] = [ ]; ``` -**See also:** [`column.colSpan`](#colspan-maybeargs-colspanargstrow-tsummaryrow--maybenumber) +**See also:** [`column.colSpan`](#colspan) -#### `RowHeightArgs` +#### `RowHeightArgs` Arguments passed to `TreeDataGrid`'s `rowHeight` prop when it is a function. ```tsx -type RowHeightArgs = { type: 'ROW'; row: TRow } | { type: 'GROUP'; row: GroupRow }; +type RowHeightArgs = + | { + type: 'ROW'; + row: R; + } + | { + type: 'GROUP'; + row: GroupRow; + }; ``` **Example:** @@ -2247,7 +2637,7 @@ function getRowHeight(args: RowHeightArgs): number { ``` -**See also:** [`rowHeight`](#rowheight-maybenumber--args-rowheightargsr--number) prop on ``, [`GroupRow`](#grouprowtrow) +**See also:** [`rowHeight`](#rowheight-1) prop on ``, [`GroupRow`](#grouprow) #### `SortColumn` @@ -2260,7 +2650,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` @@ -2270,7 +2660,7 @@ type SortDirection = 'ASC' | 'DESC'; **See also:** [`SortColumn`](#sortcolumn) -#### `RowsChangeData` +#### `RowsChangeData` Data provided to the `onRowsChange` callback. @@ -2283,15 +2673,15 @@ 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. ```tsx -interface SelectRowEvent { - row: TRow; +interface SelectRowEvent { + row: R; checked: boolean; isShiftClick: boolean; } @@ -2311,19 +2701,19 @@ interface SelectHeaderRowEvent { **See also:** [`useHeaderRowSelection`](#useheaderrowselection) hook -#### `FillEvent` +#### `FillEvent` Event object for drag-fill operations. ```tsx -interface FillEvent { +interface FillEvent { columnKey: string; - sourceRow: TRow; - targetRow: TRow; + sourceRow: R; + targetRow: R; } ``` -**See also:** [`onFill`](#onfill-maybeevent-filleventr--r) prop on `` +**See also:** [`onFill`](#onfill) prop on `` #### `DataGridHandle` @@ -2354,35 +2744,7 @@ function MyGrid() { } ``` -**See also:** [`ref`](#ref-maybereactrefdatagridhandle) prop on `` - -#### `Position` (internal) - -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 also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargstrow-tsummaryrow-tactiverow) - -#### `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. - -```tsx -interface PartialPosition { - readonly idx?: Maybe; - readonly rowIdx?: Maybe; -} -``` - -**See also:** [`DataGridHandle`](#datagridhandle) +**See also:** [`ref`](#ref) prop on `` #### `SetActivePositionOptions` @@ -2395,7 +2757,7 @@ interface SetActivePositionOptions { } ``` -**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargstrow-tsummaryrow-tactiverow) +**See also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) #### `ColumnWidths` @@ -2405,7 +2767,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` @@ -2420,7 +2782,7 @@ interface ColumnWidth { } ``` -**See also:** [`ColumnWidths`](#columnwidths) +**See also:** [`ColumnWidths`](#columnwidths-1) #### `Direction` @@ -2430,9 +2792,63 @@ Text direction of the grid. type Direction = 'ltr' | 'rtl'; ``` -**See also:** [`direction`](#direction-maybeltr--rtl) prop on `` +**See also:** [`direction`](#direction) prop on `` + +#### `CellClipboardEvent` (internal) + +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; +``` + +**See also:** [`onCellCopy`](#oncellcopy) and [`onCellPaste`](#oncellpaste) props on `` + +#### `CellEvent` (internal) + +Adds grid-specific methods to a React event. This helper type is not exported; the shape is shown for reference. + +```tsx +type CellEvent> = E & { + /** Prevents the default grid behavior for this event */ + preventGridDefault: () => void; + /** Returns whether `preventGridDefault` was called */ + isGridDefaultPrevented: () => boolean; +}; +``` + +**See also:** [`CellMouseEvent`](#cellmouseevent), [`CellKeyboardEvent`](#cellkeyboardevent) + +#### `CellMouseEventHandler` (internal) + +Handler type used by `onCellMouseDown`, `onCellClick`, `onCellDoubleClick`, and `onCellContextMenu`. This helper type is not exported; the shape is shown for reference. + +```tsx +type CellMouseEventHandler = Maybe< + (args: CellMouseArgs, event: CellMouseEvent) => void +>; +``` + +#### `MapViewportColumns` (internal) + +Type of `mapViewportColumns` in `RenderRowProps`. This helper type is not exported; the shape is shown for reference. + +```tsx +type MapViewportColumns = ( + activeIdx: number | undefined, + colSpanArgs: ColSpanArgs | undefined, + callback: ( + column: CalculatedColumn, + isCellActive: boolean, + colSpan: number, + index: number + ) => T +) => T[]; +``` + +**See also:** [`RenderRowProps`](#renderrowprops), [`ColSpanArgs`](#colspanargs) -#### `Maybe` (internal) +#### `Maybe` (internal) Utility type for optional values. This helper type is not exported; the shape is shown for reference. @@ -2440,10 +2856,40 @@ Utility type for optional values. This helper type is not exported; the shape is type Maybe = T | undefined | null; ``` +#### `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. + +```tsx +interface PartialPosition { + readonly idx?: Maybe; + readonly rowIdx?: Maybe; +} +``` + +**See also:** [`DataGridHandle`](#datagridhandle) + +#### `Position` (internal) + +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 also:** [`DataGridHandle`](#datagridhandle), [`CellKeyDownArgs`](#cellkeydownargs) + + + ### Generics -- `R`, `TRow`: Row type -- `SR`, `TSummaryRow`: Summary row type +- `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 diff --git a/package-lock.json b/package-lock.json index e62f41ff23..1f78d77d82 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,6 +22,7 @@ "clsx": "^2.1.1", "ecij": "^0.7.0", "eslint": "^10.2.1", + "github-slugger": "^2.0.0", "jspdf": "^4.2.0", "jspdf-autotable": "^5.0.7", "oxc-transform-react": "^0.157.0", diff --git a/package.json b/package.json index 650f6f2c38..72cf18553f 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "clsx": "^2.1.1", "ecij": "^0.7.0", "eslint": "^10.2.1", + "github-slugger": "^2.0.0", "jspdf": "^4.2.0", "jspdf-autotable": "^5.0.7", "oxc-transform-react": "^0.157.0", diff --git a/scripts/generateApiDocs.ts b/scripts/generateApiDocs.ts new file mode 100644 index 0000000000..d1541ac57e --- /dev/null +++ b/scripts/generateApiDocs.ts @@ -0,0 +1,583 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import GithubSlugger from 'github-slugger'; +import { SyntaxKind } from 'typescript/ast'; +import type { + FunctionDeclaration, + InterfaceDeclaration, + JSDoc, + JSDocComment, + JSDocSeeTag, + NodeArray, + Node, + ParameterDeclaration, + PropertySignatureDeclaration, + SourceFile, + TypeElement, + TypeLiteralNode, + VariableStatement +} from 'typescript/ast'; +import { + isExportDeclaration, + isFunctionTypeNode, + isIdentifier, + isImportDeclaration, + isInterfaceDeclaration, + isJSDocText, + isTypeAliasDeclaration, + isTypeLiteralNode, + isTypeReferenceNode, + isUnionTypeNode, + 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`, +// 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 = ''; +// 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 { + summary: string; + tags: { name: string; text: string }[]; +} + +interface GeneratedHeading { + line: string; + key: string | undefined; +} + +interface Declaration { + name: string; + node: Node; + doc: Doc; +} + +using api = new API(); +using declarationsFile = api.createSourceFile( + declarationsPath, + await readFile(declarationsPath, 'utf-8') +); +using entryFile = api.createSourceFile(entryPath, await readFile(entryPath, 'utf-8')); + +const declarations = new Map(); +// exported name -> declared name, e.g. `Cell` -> `MemoCell` +const exportedNames = new Map(); + +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() + ); + } + 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 section, in the order they are exported from the entry point +const groups = new Map(sections.map((section) => [section, []])); +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: +// 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( + // `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 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(); +// 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) { + 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)) { + // 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; + markdown.push(renderItem(item, section, propsInterface !== undefined)); + if (propsInterface !== undefined) markdown.push(renderType(propsInterface, 5)); + } +} + +const readme = await readFile(readmePath, 'utf-8'); +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}`); +} + +await writeFile( + readmePath, + resolveLinks( + readme.slice(0, startIndex + startMarker.length), + markdown.join('\n\n'), + readme.slice(endIndex) + ) +); + +function renderItem(item: Declaration, section: string, hasPropsInterface: boolean) { + const { name, node, doc } = item; + if (isType(node)) return renderType(item, 4); + + if (section === 'Components') { + const title = heading(4, `\`<${name} />\``, name); + // the props interface of a component is listed after it, e.g. `DataGridProps` after `DataGrid` + 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)) { + throw new Error(`${typeName}, the props of ${name}, must have a JSDoc comment`); + } + return [ + title, + ...renderSummary(doc), + ...renderTags(doc), + heading(5, 'Props'), + `[\`${propsType}\`](#!${typeName})` + ].join('\n\n'); + } + + const isFunction = !isVariableStatement(node); + return [ + heading(4, `\`${name}${isFunction ? '()' : ''}\``, name), + codeBlock( + isFunction + ? getFunctionSignature(name, node as FunctionDeclaration) + : getVariableSignature(name, node) + ), + ...renderSummary(doc), + ...renderTags(doc) + ].join('\n\n'); +} + +function renderType({ name, node, doc }: Declaration, level: number) { + 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 ? `\`${name}\`${isInternal ? ' (internal)' : ''}` : name, name), + ...renderSummary(doc) + ]; + + 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); + md.push(codeBlock(getTypeDeclarations(node)), ...renderTags(doc)); + } + + return md.join('\n\n'); +} + +function renderMembers(members: NodeArray, level: number, parent: string): string[] { + return members.flatMap((member) => { + const name = getMemberName(member); + const doc = getDoc(member); + const typeLiteral = findTypeLiteral((member as PropertySignatureDeclaration).type); + // 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 isOptional = (member as PropertySignatureDeclaration).postfixToken !== undefined; + return [ + heading(level, `\`${name}${isOptional ? '?' : ''}\``, `${parent}.${name}`), + codeBlock(member.getText()), + ...renderSummary(doc), + ...renderTags(doc) + ]; + }); +} + +function renderSummary({ summary }: Doc) { + return summary === '' ? [] : [summary]; +} + +function renderTags({ tags }: Doc) { + const labels: Record = { + default: '**Default:** ', + example: '**Example:**\n\n', + see: '**See also:** ', + returns: '**Returns:**\n\n' + }; + return tags + .filter(({ name }) => { + // the type parameters are described in the "Generics" section + if (name === 'template') 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]}${text}`); +} + +// e.g. `RenderRowProps` +function getComponentPropsType(node: Node) { + 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: FunctionDeclaration) { + const params = node.parameters.map((param: ParameterDeclaration) => { + // destructured parameters are named `props` + const paramName = isIdentifier(param.name) ? param.name.text : 'props'; + return `${paramName}: ${param.type!.getText()}`; + }); + 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: VariableStatement) { + const { initializer, type } = getVariableDeclaration(node); + if (initializer !== undefined) { + return `const ${name} = ${initializer.getText().replaceAll('"', "'")};`; + } + return `const ${name}: ${type!.getText()};`; +} + +// 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 (isInterfaceDeclaration(node)) return getInterfaceDeclaration(node); + + const referenced = new Set( + 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) => + isInterfaceDeclaration(declaration!) + ? getInterfaceDeclaration(declaration) + : declaration!.getText() + ) + .join('\n\n'); +} + +function getInterfaceDeclaration(node: InterfaceDeclaration) { + if (getBaseTypes(node).every((base) => !helperTypes.has(getBaseTypeName(base)))) { + return node.getText(); + } + + const { heritage, members } = getInterfaceParts(node); + const extendsClause = heritage.length === 0 ? '' : ` extends ${heritage.join(', ')}`; + const body = Array.from(members.values(), (member) => ` ${member}`).join('\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: InterfaceDeclaration) { + const heritage: string[] = []; + const members = new Map(); + + 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(base.getText()); + } + } + + for (const member of node.members) { + const name = getMemberName(member); + const jsDoc = getJSDoc(member); + // a redeclared member replaces the inherited one + members.delete(name); + 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 isInterfaceDeclaration(node) || isTypeAliasDeclaration(node); +} + +// members with more than a single paragraph can't be shown as comments of a code block +function hasRichMembers(node: InterfaceDeclaration) { + return node.members.some((member) => { + const { summary, tags } = getDoc(member); + return ( + tags.some((tag) => tag.name !== 'default') || + 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): 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) { + if (isVariableStatement(node)) return getVariableDeclaration(node).name.getText(); + return (node as InterfaceDeclaration).name.text; +} + +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 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, 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 (!exports.some((item) => item.name === name)) { + throw new Error(`${name} must be exported by name from ${entryPath}`); + } + } + return exports; +} + +// the JSDoc comment directly before the node +function getJSDoc(node: Node) { + return node.jsDoc?.at(-1) as JSDoc | undefined; +} + +function getDoc(node: Node): Doc { + const jsDoc = getJSDoc(node); + return { + summary: renderComment(jsDoc?.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() + }; + }) + }; +} + +// 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) { + const line = `${'#'.repeat(level)} ${text}`; + generatedHeadings.push({ line, key }); + return line; +} + +function codeBlock(text: string) { + 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 + .replaceAll(/^(?:export )?declare /gm, '') + .replaceAll('import("react").', 'React.') + .replaceAll( + /\{@link(?:code|plain)?\s+([^}|]+?)\s*(?:\|\s*([^}]+?)\s*)?\}/g, + (_, target: string, label: string | undefined) => { + codeBlockLinks.add(target); + return label ?? target; + } + ) + .replaceAll(/NoInfer<([^<>]+)>/g, '$1'); +} + +// 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(precedingMarkdown: string, api: string, followingMarkdown: string) { + 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('`', '')); + 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, [...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) ?? + (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; + }; + for (const target of codeBlockLinks) getAnchor(target); + + return `${precedingMarkdown}\n\n${api}\n\n${followingMarkdown}` + .replaceAll(/\]\(#!([^)]+)\)/g, (_, target: string) => `](#${getAnchor(target)})`) + .replaceAll( + /\]\(#[^ )]+ (["'])([\w.]+)\1\)/g, + (_, quote: string, target: string) => `](#${getAnchor(target)} ${quote}${target}${quote})` + ); +} + +function forEachLine(markdown: string, callback: (line: string, isInCodeBlock: boolean) => void) { + let fence: string | undefined; + for (const line of markdown.split('\n')) { + 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/src/Cell.tsx b/src/Cell.tsx index 89c1e300ea..531203b604 100644 --- a/src/Cell.tsx +++ b/src/Cell.tsx @@ -128,6 +128,9 @@ function Cell({ ); } +/** + * 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; export { MemoCell as Cell }; diff --git a/src/Columns.tsx b/src/Columns.tsx index 1231245f4e..13722fc51b 100644 --- a/src/Columns.tsx +++ b/src/Columns.tsx @@ -7,6 +7,16 @@ 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); + * ``` + */ export const SELECT_COLUMN_KEY = 'rdg-select-column'; function SelectAllCell({ tabIndex }: RenderHeaderCellContentProps) { @@ -56,6 +66,33 @@ 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 getRowKey(row: Row) { + * return row.id; + * } + * + * function MyGrid() { + * return ( + * + * ); + * } + * ``` + */ // 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 49d3f8d9e8..b67ecc4bd5 100644 --- a/src/DataGrid.tsx +++ b/src/DataGrid.tsx @@ -79,6 +79,11 @@ import { } from './style/core'; import SummaryRow from './SummaryRow'; +/** + * Default options applied to all columns. + * + * @see {@linkcode DataGridProps.defaultColumnOptions | defaultColumnOptions} prop on `` + */ export type DefaultColumnOptions = Pick< Column, | 'renderCell' @@ -91,140 +96,623 @@ 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 `` + */ 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' ->; - -export interface DataGridProps extends SharedDivProps { +/** + * @template R Row type + * @template SR Summary row type + * @template K Row key type + */ +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. + * + * ⚠️ **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>[]; - /** An array of rows, which can be of any type */ + /** + * An array of rows. The row data can be of any type. + * + * 💡 **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. + * + * @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. + * + * ⚠️ **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. + * + * ⚠️ **Performance:** Memoize this array to prevent internal memoization invalidation. + */ bottomSummaryRows?: Maybe; /** - * Function to get the key of each row. - * Required for row selection. - * Recommended otherwise, as the key is also used as the `key` prop of the row elements. - * @returns a unique key for the row + * 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'; + * + * interface Row { + * id: number; + * name: string; + * } + * + * function getRowKey(row: Row) { + * return row.id; + * } + * + * function MyGrid() { + * return ; + * } + * ``` */ getRowKey?: 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. + * + * @example + * ```tsx + * import { useState } from 'react'; + * import { DataGrid } from 'react-data-grid'; + * + * function MyGrid() { + * const [rows, setRows] = useState(initialRows); + * + * return ; + * } + * ``` + * + * @see {@linkcode RowsChangeData} + */ 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. + * + * ⚠️ **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 + * ; + * + * // Dynamic height per row + * function getRowHeight(row) { + * return row.isExpanded ? 100 : 35; + * } + * + * ; + * ``` */ 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. + * + * @default `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. + * + * @default `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. + * + * @example + * ```tsx + * const [columnWidths, setColumnWidths] = useState((): ColumnWidths => new Map()); + * + * function addNewRow() { + * setRows(...); + * // reset column widths after adding a new row + * setColumnWidths(new Map()); + * } + * + * return + * ``` + * + * @see {@linkcode ColumnWidths} + */ columnWidths?: Maybe; - /** Callback triggered when column widths change */ + /** + * Callback triggered when column widths change. If not provided, an internal state is used. + * + * @see {@linkcode ColumnWidths} + */ onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; /** * Feature props */ - /** A set of selected row keys */ + /** + * A set of selected row keys. `getRowKey` 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. + * + * @example + * ```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 getRowKey(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. + * + * 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 */ + /** + * 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'; + * + * const rows: readonly Row[] = [...]; + * + * const columns: readonly Column[] = [ + * { + * key: 'name', + * name: 'Name', + * sortable: true + * }, + * // other columns + * ]; + * + * function MyGrid() { + * const [sortColumns, setSortColumns] = useState([]); + * + * return ( + * + * ); + * } + * ``` + * + * @example + * ```tsx + * // Disable multi-column sorting + * 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. + * + * @example + * ```tsx + * function MyGrid() { + * return ( + * + * ); + * } + * ``` + * + * @see {@linkcode DefaultColumnOptions} + */ 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. 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') { + * event.preventGridDefault(); + * } + * } + * + * ; + * ``` + * + * @see {@linkcode CellMouseArgs}, {@linkcode CellMouseEvent} + */ onCellMouseDown?: CellMouseEventHandler; - /** Callback triggered when a cell is clicked */ + /** + * 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 }); + * } + * } + * + * ; + * ``` + * + * @see {@linkcode CellMouseArgs}, {@linkcode CellMouseEvent} + */ 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. + * + * @example + * ```tsx + * function onCellDoubleClick(args: CellMouseArgs, event: CellMouseEvent) { + * if (args.column.key === 'id') { + * event.preventGridDefault(); + * } + * } + * + * ; + * ``` + * + * @see {@linkcode CellMouseArgs}, {@linkcode CellMouseEvent} + */ onCellDoubleClick?: CellMouseEventHandler; - /** Callback triggered when a cell is right-clicked */ + /** + * Callback triggered when a cell is right-clicked. + * + * @example + * ```tsx + * function onCellContextMenu(args: CellMouseArgs, event: CellMouseEvent) { + * if (args.column.key === 'id') { + * event.preventDefault(); + * // open custom context menu + * } + * } + * + * ; + * ``` + * + * @see {@linkcode CellMouseArgs}, {@linkcode CellMouseEvent} + */ 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. + * + * 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}. + * + * 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 === 'Enter' || event.key === 'Tab')) { + * // Prevent editing on `Enter` and navigation on `Tab` + * event.preventGridDefault(); + * } + * } + * ``` + * + * @see {@linkcode CellKeyDownArgs}, {@linkcode CellKeyboardEvent} + */ 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 {@linkcode CellCopyArgs} + */ 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. + * + * @returns The updated row, which the grid passes to {@linkcode DataGridProps.onRowsChange | onRowsChange} + * + * @see {@linkcode CellPasteArgs} + */ onCellPaste?: Maybe< (args: CellPasteArgs, NoInfer>, event: CellClipboardEvent) => NoInfer >; - /** Function called whenever the active position is changed */ + /** + * Callback triggered when the active position changes. + * + * @see {@linkcode PositionChangeArgs} + */ 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. + * + * @example + * ```tsx + * function onFill({ columnKey, sourceRow, targetRow }: FillEvent): Row { + * return { ...targetRow, [columnKey]: sourceRow[columnKey as keyof Row] }; + * } + * + * ; + * ``` + * + * @returns The updated target row. The grid passes the updated rows to {@linkcode DataGridProps.onRowsChange | onRowsChange} + * + * @see {@linkcode FillEvent} + */ onFill?: Maybe<(event: FillEvent>) => NoInfer>; + /** + * Native DOM `onScroll` prop. + */ + onScroll?: React.UIEventHandler | undefined; /** * Toggles and modes */ - /** @default true */ + /** + * This prop can be used to disable virtualization. + * + * @default `true` + */ enableVirtualization?: Maybe; /** * Miscellaneous */ - /** Custom renderers for cells, rows, and other components */ + /** + * Custom renderers for cells, rows, and other components. + * + * @example + * ```tsx + * import { DataGrid, Row, type Renderers } from 'react-data-grid'; + * + * const customRenderers: Renderers = { + * // Wrap the default row to add contexts or tweak props + * 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
+ * }; + * + * ; + * ``` + * + * @see {@linkcode Renderers} + */ renderers?: Maybe, NoInfer>>; - /** Function to apply custom class names to rows */ + /** + * 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'; + * + * function rowClass(row: Row, rowIdx: number) { + * return rowIdx % 2 === 0 ? 'even' : 'odd'; + * } + * + * function MyGrid() { + * return ; + * } + * ``` + */ rowClass?: Maybe<(row: NoInfer, rowIdx: number) => Maybe>; - /** Custom class name for the header row */ + /** + * Custom class name for the header row. + */ headerRowClass?: Maybe; /** - * Text direction of the grid ('ltr' or 'rtl') - * @default 'ltr' + * 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 is controlled on the left edge of the column + * - Vertical scrollbar is moved to the left + * + * @default `'ltr'` left-to-right + * + * @see {@linkcode Direction} */ direction?: Maybe; + /** + * Custom class name for the grid. + */ + className?: string | undefined; + /** + * Custom styles for the grid. + */ + style?: React.CSSProperties | undefined; + /** + * ARIA role for the grid container. + * + * @default `'grid'` + */ + role?: React.AriaRole | undefined; + /** + * The label of the grid. We recommend providing a label using `aria-label` or `aria-labelledby`. + */ + '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'?: string | undefined; + /** + * Total number of rows for assistive technologies. + */ + 'aria-rowcount'?: number | undefined; + /** + * A human-readable description of the grid. + */ + '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'?: string | undefined; + /** + * 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 ; + * } + * + * 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; } @@ -232,8 +720,13 @@ export interface DataGridProps extends Sha * Main API component to render a data grid of rows and columns * * @example - * + * ```tsx * + * ``` + * + * @template R Row type + * @template SR Summary row type + * @template K Row key type */ export function DataGrid(props: DataGridProps) { const { diff --git a/src/DataGridRenderersContext.ts b/src/DataGridRenderersContext.ts index 32f1aa00c4..7714ae40ca 100644 --- a/src/DataGridRenderersContext.ts +++ b/src/DataGridRenderersContext.ts @@ -2,6 +2,39 @@ 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} + * ); + * } + * ``` + */ // 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 c876db0a22..0280f291f3 100644 --- a/src/Row.tsx +++ b/src/Row.tsx @@ -88,6 +88,9 @@ function Row({ ); } +/** + * 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; export { MemoRow as Row }; diff --git a/src/TreeDataGrid.tsx b/src/TreeDataGrid.tsx index 266ba615a4..6c0c373a15 100644 --- a/src/TreeDataGrid.tsx +++ b/src/TreeDataGrid.tsx @@ -26,6 +26,13 @@ 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, and `onCellKeyDown` and `onActivePositionChange` receive group rows too. Additional props are listed below: + * + * @template R Row type + * @template SR Summary row type + * @template K Row key type + */ export interface TreeDataGridProps extends Omit< DataGridProps, | 'columns' @@ -38,46 +45,151 @@ export interface TreeDataGridProps extends | 'onActivePositionChange' > { 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. + * + * @example + * ```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)>; - /** Callback triggered when a key is pressed in a cell or a row, including group rows */ + /** + * 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 >; - /** Function called whenever the active position is changed, including to a group row */ + /** + * 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'; + * + * 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' } + * ]; + * + * const groupBy = ['country', 'city']; + * + * function MyGrid() { + * return ( + * + * ); + * } + * ``` + */ groupBy: readonly string[]; - getRowGroupKey?: Maybe<(row: NoInfer, columnKey: string) => 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'; + * + * 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; + /** + * 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. + * + * ⚠️ **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') { + * return row.date.getFullYear().toString(); + * } + * return String(row[columnKey]); + * } + * ``` + */ + getRowGroupKey?: Maybe<(row: NoInfer, columnKey: 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. + */ getGroupId?: Maybe<(groupKey: string, parentId?: string) => string>; } -interface PartialGroupRow { +interface PartialGroupRow { // `undefined` for the groups on the last level, which only contain rows - readonly groups: GroupsMap | undefined; + readonly groups: GroupsMap | undefined; // all the descendant rows of the group, not just the direct children - readonly childRows: readonly TRow[]; + readonly childRows: readonly R[]; readonly startRowIndex: number; } -type GroupsMap = ReadonlyMap>; +type GroupsMap = ReadonlyMap>; // only used while the rows are being grouped -interface MutablePartialGroupRow { - readonly groups: MutableGroupsMap | undefined; - readonly childRows: TRow[]; +interface MutablePartialGroupRow { + readonly groups: MutableGroupsMap | undefined; + readonly childRows: R[]; startRowIndex: number; } -type MutableGroupsMap = Map>; +type MutableGroupsMap = Map>; -interface GroupedRows { - readonly groups: GroupsMap | undefined; +interface GroupedRows { + readonly groups: GroupsMap | undefined; readonly rowsCount: number; } -interface FlattenedRows { - readonly rows: readonly (TRow | GroupRow)[]; +interface FlattenedRows { + readonly rows: readonly (R | GroupRow)[]; // indexes of the group rows in `rows`, in ascending order readonly groupRowIndexes: readonly number[]; } @@ -87,13 +199,78 @@ interface FlattenedRows { const allGroupRows = new WeakSet(); /** - * Returns whether a row of a `TreeDataGrid` is a group row, - * e.g., the active row passed to `onCellKeyDown` or `onActivePositionChange` + * Returns whether a row of a `TreeDataGrid` is a group row, e.g., the active row passed to `onCellKeyDown` or `onActivePositionChange`. + * + * @example + * ```tsx + * import { isGroupRow, type TreePositionChangeArgs } from 'react-data-grid'; + * + * function onActivePositionChange({ row }: TreePositionChangeArgs) { + * if (row === undefined || isGroupRow(row)) return; + * console.log(row.name); + * } + * ``` + * + * @see {@linkcode GroupRow}, {@linkcode TreeCellKeyDownArgs}, {@linkcode TreePositionChangeArgs} */ -export function isGroupRow(row: TRow | GroupRow): row is GroupRow { +export function isGroupRow(row: R | GroupRow): row is GroupRow { return typeof row === 'object' && row !== null && allGroupRows.has(row); } +/** + * `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. Rows are grouped by their value for each of those columns, or by `getRowGroupKey` when provided + * 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[]` + * + * **Group rows in callbacks:** + * + * 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'; + * + * function onCellKeyDown(args: TreeCellKeyDownArgs, event: CellKeyboardEvent) { + * if (args.mode !== 'ACTIVE') return; + * if (isGroupRow(args.row)) { + * console.log(`Group ${args.row.groupKey} with ${args.row.childRows.length} rows`); + * return; + * } + * console.log(args.row.name); + * } + * ``` + * + * @template R Row type + * @template SR Summary row type + * @template K Row key type + */ export function TreeDataGrid({ columns: rawColumns, rows: rawRows, diff --git a/src/cellRenderers/SelectCheckbox.tsx b/src/cellRenderers/SelectCheckbox.tsx index 7f42d998d5..629728cada 100644 --- a/src/cellRenderers/SelectCheckbox.tsx +++ b/src/cellRenderers/SelectCheckbox.tsx @@ -1,11 +1,14 @@ import type { RenderCheckboxProps } from '../types'; import { useRenderers } from '../DataGridRenderersContext'; -export interface SelectCheckboxProps extends RenderCheckboxProps { - /** Whether the checkbox is checked */ - checked: boolean; -} +/** + * The same props as {@linkcode RenderCheckboxProps}. + */ +export type SelectCheckboxProps = RenderCheckboxProps; +/** + * A component for rendering row selection checkboxes. + */ export function SelectCheckbox(props: SelectCheckboxProps) { return useRenderers()!.renderCheckbox!(props); } diff --git a/src/cellRenderers/renderCheckbox.tsx b/src/cellRenderers/renderCheckbox.tsx index 9920c08157..ffde8a5ffd 100644 --- a/src/cellRenderers/renderCheckbox.tsx +++ b/src/cellRenderers/renderCheckbox.tsx @@ -22,6 +22,20 @@ 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' }) + * }} + * />; + * ``` + */ 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 35672c0bb9..ec302302ad 100644 --- a/src/cellRenderers/renderToggleGroup.tsx +++ b/src/cellRenderers/renderToggleGroup.tsx @@ -28,10 +28,29 @@ 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 group key, `row.groupKey`, and the expand/collapse toggle. + * + * @example + * ```tsx + * import { renderToggleGroup, type Column } from 'react-data-grid'; + * + * const columns: readonly Column[] = [ + * { + * key: 'group', + * name: 'Group', + * renderGroupCell: renderToggleGroup + * } + * ]; + * ``` + */ 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. + */ export function ToggleGroup({ row, tabIndex, diff --git a/src/cellRenderers/renderValue.tsx b/src/cellRenderers/renderValue.tsx index 070be7f904..0a10dbd3d0 100644 --- a/src/cellRenderers/renderValue.tsx +++ b/src/cellRenderers/renderValue.tsx @@ -1,5 +1,21 @@ 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 + * } + * ]; + * ``` + */ 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 bff2befbcb..6fdd967070 100644 --- a/src/editors/renderTextEditor.tsx +++ b/src/editors/renderTextEditor.tsx @@ -38,18 +38,34 @@ function autoFocusAndSelect(input: HTMLInputElement | null) { input?.select(); } -export function renderTextEditor({ +/** + * 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 + * } + * ]; + * ``` + */ +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/hooks/useRowSelection.ts b/src/hooks/useRowSelection.ts index 64f02778bc..e2145debf1 100644 --- a/src/hooks/useRowSelection.ts +++ b/src/hooks/useRowSelection.ts @@ -16,6 +16,37 @@ 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 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 + * + * @example + * ```tsx + * function CustomSelectCell({ row }: RenderCellContentProps) { + * const { isRowSelectionDisabled, isRowSelected, onRowSelectionChange } = useRowSelection(); + * + * return ( + * + * onRowSelectionChange({ + * row, + * checked: event.currentTarget.checked, + * isShiftClick: event.nativeEvent.shiftKey + * }) + * } + * /> + * ); + * } + * ``` + */ export function useRowSelection() { const rowSelectionContext = use(RowSelectionContext); const rowSelectionChangeContext = use(RowSelectionChangeContext); @@ -46,6 +77,40 @@ 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 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 + * + * @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 })} + * /> + * ); + * } + * ``` + */ 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 854d6ef397..4b5bef899c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,61 +1,72 @@ import './style/layers.css'; -export { - DataGrid, - type DataGridHandle, - type DataGridProps, - type DefaultColumnOptions -} from './DataGrid'; -export { isGroupRow, TreeDataGrid, type TreeDataGridProps } from './TreeDataGrid'; -export { DataGridRenderersContext } from './DataGridRenderersContext'; +// 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 * from './Columns'; -export * from './cellRenderers'; -export { renderTextEditor } from './editors/renderTextEditor'; +export { SelectCheckbox, type SelectCheckboxProps, 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 { useHeaderRowSelection, useRowSelection } from './hooks'; +export { renderCheckbox, renderToggleGroup, renderValue } from './cellRenderers'; + +// Context +export { DataGridRenderersContext } from './DataGridRenderersContext'; + +// Other +export { SelectColumn, SELECT_COLUMN_KEY } from './Columns'; +export { isGroupRow } from './TreeDataGrid'; + +// Types export type { - CalculatedColumn, - CalculatedColumnOrColumnGroup, - CalculatedColumnParent, - CellCopyArgs, - CellKeyboardEvent, - CellKeyDownArgs, - CellMouseArgs, - CellMouseEvent, - CellPasteArgs, - ColSpanArgs, Column, - ColumnFrozen, ColumnGroup, ColumnOrColumnGroup, - ColumnWidth, - ColumnWidths, - Direction, - FillEvent, - GroupRow, - PositionChangeArgs, + CalculatedColumn, + CalculatedColumnParent, + CalculatedColumnOrColumnGroup +} from './types'; +export type { DefaultColumnOptions } from './DataGrid'; +export type { + ColumnFrozen, RenderCellContentProps, - RenderCellProps, - RenderCheckboxProps, + RenderHeaderCellContentProps, RenderEditCellContentProps, - Renderers, + RenderSummaryCellContentProps, RenderGroupCellContentProps, - RenderHeaderCellContentProps, + GroupRow, RenderRowProps, + RenderCellProps, + RenderCheckboxProps, + RenderSortStatusProps, RenderSortIconProps, RenderSortPriorityProps, - RenderSortStatusProps, - RenderSummaryCellContentProps, + Renderers, + CellMouseArgs, + CellMouseEvent, + CellKeyDownArgs, + CellKeyboardEvent, + CellCopyArgs, + CellPasteArgs, + PositionChangeArgs, + TreeCellKeyDownArgs, + TreePositionChangeArgs, + ColSpanArgs, RowHeightArgs, - RowsChangeData, - SelectHeaderRowEvent, - SelectRowEvent, - SetActivePositionOptions, SortColumn, SortDirection, - TreeCellKeyDownArgs, - TreePositionChangeArgs + RowsChangeData, + SelectRowEvent, + SelectHeaderRowEvent, + FillEvent } from './types'; +export type { DataGridHandle } from './DataGrid'; +export type { SetActivePositionOptions, ColumnWidths, ColumnWidth, Direction } from './types'; diff --git a/src/renderHeaderCell.tsx b/src/renderHeaderCell.tsx index 7132838812..c51efea59b 100644 --- a/src/renderHeaderCell.tsx +++ b/src/renderHeaderCell.tsx @@ -19,6 +19,23 @@ 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 + * } + * ]; + * ``` + */ export function renderHeaderCell({ column, sortDirection, diff --git a/src/sortStatus.tsx b/src/sortStatus.tsx index 769aeb000b..608ffac580 100644 --- a/src/sortStatus.tsx +++ b/src/sortStatus.tsx @@ -25,6 +25,9 @@ export default function renderSortStatus({ sortDirection, priority }: RenderSort ); } +/** + * Renders the sort direction arrow icon. + */ export function renderSortIcon({ sortDirection }: RenderSortIconProps) { if (sortDirection === undefined) return null; @@ -35,6 +38,9 @@ export function renderSortIcon({ sortDirection }: RenderSortIconProps) { ); } +/** + * Renders the sort priority number for multi-column sorting. + */ export function renderSortPriority({ priority }: RenderSortPriorityProps) { return priority; } diff --git a/src/types.ts b/src/types.ts index cbe6b3b3ac..a4e2fb09f7 100644 --- a/src/types.ts +++ b/src/types.ts @@ -4,94 +4,241 @@ 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>; -export interface Column { - /** The name of the column. Displayed in the header cell by default */ +/** + * Defines the configuration for a column in the grid. + * + * @see {@linkcode DataGridProps.columns | columns} prop on `` + */ +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 */ + /** 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. + * + * `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[] = [ + * { + * 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', + * width: 'minmax(100px, max-content)' // Fits the content, at least 100 pixels + * }, + * { + * key: 'notes', + * name: 'Notes' + * // No width specified - automatically sized + * } + * ]; + * ``` */ readonly width?: Maybe; /** - * Minimum column width in pixels - * @default 50 + * Minimum column width in pixels. + * + * @default `50` pixels */ readonly minWidth?: Maybe; - /** Maximum column width in pixels */ + /** Maximum column width in pixels. */ readonly maxWidth?: Maybe; - /** Class name(s) for cells */ - readonly cellClass?: Maybe Maybe)>; - /** Class name(s) for the header cell */ + /** + * 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[] = [ + * { + * 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. */ readonly headerCellClass?: Maybe; - /** Class name(s) for summary cells */ - readonly summaryCellClass?: Maybe Maybe)>; - /** Render function to render the content of cells */ - readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; - /** 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 */ - readonly renderSummaryCell?: Maybe< - (props: RenderSummaryCellContentProps) => ReactNode - >; - /** Render function to render the content of group cells */ - 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 - >; - /** Control whether cells can be edited with `renderEditCell` */ - readonly editable?: Maybe boolean)>; + /** 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. */ + readonly renderCell?: Maybe<(props: RenderCellContentProps) => ReactNode>; + /** 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. */ + readonly renderSummaryCell?: Maybe<(props: RenderSummaryCellContentProps) => ReactNode>; + /** + * 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[] = [ + * { + * key: 'gold', + * name: 'Gold', + * renderGroupCell({ row }) { + * return row.childRows.reduce((sum, childRow) => sum + childRow.gold, 0); + * } + * } + * ]; + * ``` + */ + readonly renderGroupCell?: Maybe<(props: RenderGroupCellContentProps) => ReactNode>; /** - * Returns the number of columns that the cell spans, or `undefined` for no spanning. - * The span is clamped to the start-frozen, unfrozen, or end-frozen columns, whichever the column is part of. + * Render function to render the content of edit cells. When set, the column is automatically set to be editable. + * + * Editors can render a [`:modal`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:modal) element, like a `` opened with `showModal()`, either in the cell or in a portal. Keydown events triggered in the modal are left to the editor: `onCellKeyDown` is not called, and the grid does not close the editor on `Escape`/`Enter` or navigate on `Tab`, so the editor must call `onClose` itself, for example in the dialog's `onClose` handler. + */ + readonly renderEditCell?: Maybe<(props: RenderEditCellContentProps) => ReactNode>; + /** Control whether cells can be edited with `renderEditCell`. */ + readonly editable?: Maybe boolean)>; + /** + * 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 + * 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; + * } + * } + * ]; + * ``` + * + * @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. + * + * - `'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` — the column scrolls with the rest of the grid. + * + * @default `false` + * + * @example + * ```tsx + * const columns: readonly Column[] = [ + * { key: 'id', name: 'ID', frozen: 'start' }, + * { key: 'name', name: 'Name' }, + * { key: 'actions', name: 'Actions', frozen: 'end' } + * ]; + * ``` + * + * @see {@linkcode ColumnFrozen} */ - 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. */ readonly frozen?: Maybe; - /** Enable resizing of the column */ + /** + * Enable resizing of the column. + * + * @default `false` + */ readonly resizable?: Maybe; - /** Enable sorting of the column */ + /** + * Enable sorting of the column. + * + * @default `false` + */ readonly sortable?: Maybe; - /** Enable dragging of the column */ + /** + * Enable dragging of the column. + * + * @default `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. + * + * @default `false` + */ readonly sortDescendingFirst?: Maybe; - /** Options for cell editing */ + /** 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. + * 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 + * + * @default `false` */ readonly displayCellContent?: Maybe; /** - * Commit changes when clicking outside the cell - * @default true + * Commit changes when clicking outside the cell. + * + * @default `true` */ readonly commitOnOutsideClick?: Maybe; /** - * Close the editor when the row value changes externally - * @default true + * Close the editor when the row value changes externally. + * + * @default `true` */ readonly closeOnExternalRowChange?: Maybe; }>; } -export interface CalculatedColumn extends 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 `` + */ +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 */ @@ -103,23 +250,43 @@ export interface CalculatedColumn extends Column) => ReactNode; - readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; + readonly renderCell: (props: RenderCellContentProps) => ReactNode; + readonly renderHeaderCell: (props: RenderHeaderCellContentProps) => ReactNode; /** Returns the number of columns that the cell spans: the clamped value returned by `colSpan`, or `1` */ - readonly getColSpan: (args: ColSpanArgs | undefined) => number; + readonly getColSpan: (args: ColSpanArgs | undefined) => number; // Always set, `undefined` when not set on the column - readonly cellClass: Column['cellClass']; - readonly headerCellClass: Column['headerCellClass']; - readonly summaryCellClass: Column['summaryCellClass']; - readonly renderSummaryCell: Column['renderSummaryCell']; - readonly renderGroupCell: Column['renderGroupCell']; - readonly renderEditCell: Column['renderEditCell']; - readonly editable: Column['editable']; - readonly colSpan: Column['colSpan']; - readonly sortDescendingFirst: Column['sortDescendingFirst']; - readonly editorOptions: Column['editorOptions']; + readonly cellClass: Column['cellClass']; + readonly headerCellClass: Column['headerCellClass']; + readonly summaryCellClass: Column['summaryCellClass']; + readonly renderSummaryCell: Column['renderSummaryCell']; + readonly renderGroupCell: Column['renderGroupCell']; + readonly renderEditCell: Column['renderEditCell']; + readonly editable: Column['editable']; + readonly colSpan: Column['colSpan']; + readonly sortDescendingFirst: Column['sortDescendingFirst']; + readonly editorOptions: Column['editorOptions']; } +/** + * 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} + */ export interface ColumnGroup { /** The name of the column group. It will be displayed in the header cell */ readonly name: string | ReactElement; @@ -127,6 +294,11 @@ export interface ColumnGroup { readonly children: readonly ColumnOrColumnGroup[]; } +/** + * Represents a parent column group in the calculated column structure. + * + * @see {@linkcode CalculatedColumn} + */ export interface CalculatedColumnParent { readonly name: string | ReactElement; readonly parent: CalculatedColumnParent | undefined; @@ -136,12 +308,27 @@ export interface CalculatedColumnParent { readonly headerCellClass?: Maybe; } +/** + * Union type representing either a `Column` or a `ColumnGroup`. + * + * @see {@linkcode DataGridProps.columns | columns} prop on `` + */ export type ColumnOrColumnGroup = Column | ColumnGroup; +/** + * Union type representing either a `CalculatedColumnParent` or a `CalculatedColumn`. + * + * @see {@linkcode CalculatedColumn}, {@linkcode CalculatedColumnParent} + */ 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; @@ -149,63 +336,123 @@ export interface Position { readonly rowIdx: number; } -export interface RenderCellContentProps { - column: CalculatedColumn; - row: TRow; +/** + * Props passed to custom cell content renderers ({@linkcode Column.renderCell | 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 + */ +export interface RenderCellContentProps { + column: CalculatedColumn; + row: R; rowIdx: number; isCellEditable: boolean; tabIndex: number; - onRowChange: (row: TRow) => void; + onRowChange: (row: R) => void; } -export interface RenderSummaryCellContentProps { - column: CalculatedColumn; - row: TSummaryRow; +/** + * Props passed to summary cell content renderers ({@linkcode Column.renderSummaryCell | column.renderSummaryCell}). + * + * @see {@linkcode Column.renderSummaryCell | column.renderSummaryCell} + */ +export interface RenderSummaryCellContentProps { + column: CalculatedColumn; + row: SR; tabIndex: number; } -export interface RenderGroupCellContentProps { - column: CalculatedColumn; +/** + * 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 | }, {@linkcode GroupRow} + */ +export interface RenderGroupCellContentProps { + column: CalculatedColumn; /** The group row: its key, rows, expanded state, level, and ID */ - row: GroupRow; + row: GroupRow; tabIndex: number; /** Expands or collapses the group */ toggleGroup: () => void; } -export interface RenderEditCellContentProps { - column: CalculatedColumn; - row: TRow; +/** + * Props passed to custom editors ({@linkcode Column.renderEditCell | 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 + */ +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; } -export interface RenderHeaderCellContentProps { - column: CalculatedColumn; +/** + * Props passed to custom header cell content renderers ({@linkcode Column.renderHeaderCell | column.renderHeaderCell}). + * + * @see {@linkcode Column.renderHeaderCell | column.renderHeaderCell}, {@linkcode renderHeaderCell} function + */ +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; setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; } -export interface RenderCellProps extends BaseRenderCellProps { - column: CalculatedColumn; - row: TRow; +/** + * Props passed to the cell renderer when using {@linkcode Renderers.renderCell | renderers.renderCell}. + * + * @see {@linkcode DataGridProps.renderers | renderers.renderCell}, {@linkcode Cell | } + */ +export interface RenderCellProps extends BaseRenderCellProps { + column: CalculatedColumn; + row: R; colSpan: number; 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< @@ -218,6 +465,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; @@ -225,56 +477,117 @@ 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 `` + */ export type CellMouseEvent = CellEvent>; +/** + * Extends `React.KeyboardEvent` with grid-specific methods. + * + * @see {@linkcode DataGridProps.onCellKeyDown | onCellKeyDown} prop on `` + */ 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; -export interface 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({ enableEditor: true }); // Activate the cell and open its editor + * } + * ``` + * + * @see {@linkcode DataGridProps.onCellMouseDown | onCellMouseDown}, {@linkcode DataGridProps.onCellClick | onCellClick}, {@linkcode DataGridProps.onCellDoubleClick | onCellDoubleClick}, and {@linkcode DataGridProps.onCellContextMenu | onCellContextMenu} props on `` + */ +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; /** Sets the active position to the cell. Pass `{ enableEditor: true }` to open its editor, or `{ shouldFocus: true }` to also focus it. */ setActivePosition: (options?: SetActivePositionOptions) => 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; + column: CalculatedColumn | undefined; /** The active row. In `TreeDataGrid`, it can be a `GroupRow`, see `isGroupRow` */ row: TActiveRow; rowIdx: number; setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; } -interface EditCellKeyDownArgs { +interface EditCellKeyDownArgs { mode: 'EDIT'; - column: CalculatedColumn; - row: TRow; + column: CalculatedColumn; + row: R; rowIdx: number; navigate: () => void; onClose: (commitChanges?: boolean, shouldFocus?: boolean) => void; } /** - * @typeParam TActiveRow - The type of the active row in `ACTIVE` mode, `TRow | GroupRow` in `TreeDataGrid` + * 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(); + * } + * } + * ``` + * + * @template TActiveRow The type of the active row in `ACTIVE` mode, `R | GroupRow` in `TreeDataGrid` + * + * @see {@linkcode DataGridProps.onCellKeyDown | onCellKeyDown} prop on ``, {@linkcode TreeCellKeyDownArgs} */ -export type CellKeyDownArgs = - | ActiveCellKeyDownArgs - | EditCellKeyDownArgs; +export type CellKeyDownArgs = + | ActiveCellKeyDownArgs + | EditCellKeyDownArgs; /** - * @typeParam TActiveRow - The type of the active row, `TRow | GroupRow` in `TreeDataGrid` + * Arguments passed to `onActivePositionChange`. + * + * @template TActiveRow The type of the active row, `R | GroupRow` in `TreeDataGrid` + * + * @see {@linkcode DataGridProps.onActivePositionChange | onActivePositionChange} prop on ``, {@linkcode TreePositionChangeArgs} */ -export interface PositionChangeArgs { +export interface PositionChangeArgs { /** row index of the active position */ rowIdx: number; /** @@ -287,42 +600,47 @@ export interface PositionChangeArgs | undefined; + column: CalculatedColumn | undefined; } -/** The arguments of `TreeDataGrid`'s `onCellKeyDown`, whose active row can be a `GroupRow` */ -export type TreeCellKeyDownArgs = CellKeyDownArgs< - TRow, - TSummaryRow, - TRow | GroupRow ->; +/** + * Arguments passed to the `onCellKeyDown` handler of `TreeDataGrid`: the active row can be a group row. + * + * @see {@linkcode TreeDataGridProps.onCellKeyDown | onCellKeyDown} prop on ``, {@linkcode CellKeyDownArgs}, {@linkcode isGroupRow} + */ +export type TreeCellKeyDownArgs = CellKeyDownArgs>; -/** The arguments of `TreeDataGrid`'s `onActivePositionChange`, whose row can be a `GroupRow` */ -export type TreePositionChangeArgs = PositionChangeArgs< - TRow, - TSummaryRow, - TRow | GroupRow ->; +/** + * Arguments passed to the `onActivePositionChange` handler of `TreeDataGrid`: the active row can be a group row. + * + * @see {@linkcode TreeDataGridProps.onActivePositionChange | onActivePositionChange} prop on ``, {@linkcode PositionChangeArgs}, {@linkcode isGroupRow} + */ +export type TreePositionChangeArgs = PositionChangeArgs>; +/** + * 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 >; -export type MapViewportColumns = ( +/** + * Type of `mapViewportColumns` in `RenderRowProps`. This helper type is not exported; the shape is shown for reference. + * + * @see {@linkcode RenderRowProps}, {@linkcode ColSpanArgs} + */ +export type MapViewportColumns = ( activeIdx: number | undefined, - colSpanArgs: ColSpanArgs | undefined, + colSpanArgs: ColSpanArgs | undefined, callback: ( - column: CalculatedColumn, + column: CalculatedColumn, isCellActive: boolean, colSpan: number, index: number ) => T ) => T[]; -export interface BaseRenderRowProps extends BaseRenderCellProps< - TRow, - TSummaryRow -> { +export interface BaseRenderRowProps extends BaseRenderCellProps { /** * Calls `callback` for each cell to render in the row, and returns the results. * `activeIdx` is the column index of the row's active cell, if any: that cell is rendered even when it is scrolled out of view. @@ -330,7 +648,7 @@ export interface BaseRenderRowProps extends BaseRen * `colSpanArgs` is passed to `column.colSpan`, and the columns that a cell spans are skipped, even the active one. * The callback receives the cell's column, whether the cell is active, its `colSpan`, and its index in the results. */ - mapViewportColumns: MapViewportColumns; + mapViewportColumns: MapViewportColumns; rowIdx: number; activeCellIdx: number | undefined; isRowSelectionDisabled: boolean; @@ -338,18 +656,25 @@ export interface BaseRenderRowProps extends BaseRen gridRowStart: number; } -export interface RenderRowProps extends BaseRenderRowProps< - TRow, - TSummaryRow -> { - row: TRow; +/** + * Props passed to custom row renderers. + * + * @see {@linkcode DataGridProps.renderers | renderers.renderRow}, {@linkcode Row | }, {@linkcode MapViewportColumns} + */ +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; } +/** + * Data provided to the `onRowsChange` callback. + * + * @see {@linkcode DataGridProps.onRowsChange | onRowsChange} prop on `` + */ export interface RowsChangeData { /** Indexes of the rows that changed */ indexes: number[]; @@ -357,33 +682,63 @@ export interface RowsChangeData { column: CalculatedColumn; } -export interface SelectRowEvent { - row: TRow; +/** + * Event object for row selection changes. + * + * @see {@linkcode useRowSelection} hook + */ +export interface SelectRowEvent { + row: R; checked: boolean; isShiftClick: boolean; } +/** + * Event object for header row selection changes. + * + * @see {@linkcode useHeaderRowSelection} hook + */ export interface SelectHeaderRowEvent { checked: boolean; } -export interface FillEvent { +/** + * Event object for drag-fill operations. + * + * @see {@linkcode DataGridProps.onFill | onFill} prop on `` + */ +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; } -export type CellCopyArgs = CellCopyPasteArgs; -export type CellPasteArgs = CellCopyPasteArgs; +/** + * Arguments passed to `onCellCopy`. + * + * @see {@linkcode DataGridProps.onCellCopy | onCellCopy} prop on `` + */ +export type CellCopyArgs = CellCopyPasteArgs; +/** + * Arguments passed to `onCellPaste`. + * + * @see {@linkcode DataGridProps.onCellPaste | onCellPaste} prop on `` + */ +export type CellPasteArgs = CellCopyPasteArgs; -export interface GroupRow { +/** + * Represents a group row in `TreeDataGrid`. + * + * @see {@linkcode RenderGroupCellContentProps}, {@linkcode RowHeightArgs}, {@linkcode TreeDataGrid | } + */ +export interface GroupRow { /** The rows of the group, including the rows of its subgroups */ - readonly childRows: readonly TRow[]; + readonly childRows: readonly R[]; /** The group's ID, returned by `getGroupId` */ readonly id: string; /** The ID of the parent group, or `undefined` on the first level */ @@ -402,39 +757,110 @@ export interface GroupRow { readonly startRowIndex: number; } +/** + * Describes a sorted column. + * + * @see {@linkcode DataGridProps.sortColumns | sortColumns} and {@linkcode DataGridProps.onSortColumnsChange | onSortColumnsChange} props on `` + */ 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} + */ export type ColumnFrozen = false | 'start' | 'end'; +/** + * @see {@linkcode SortColumn} + */ export type SortDirection = 'ASC' | 'DESC'; -export type ColSpanArgs = +/** + * 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} + */ +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 }; -export type RowHeightArgs = - | { type: 'ROW'; row: TRow } - | { type: 'GROUP'; row: GroupRow }; +/** + * 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 ``, {@linkcode GroupRow} + */ +export type RowHeightArgs = { type: 'ROW'; row: R } | { type: 'GROUP'; row: GroupRow }; +/** + * Props for custom sort icon renderers. + * + * @see {@linkcode renderSortIcon} function + */ 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 + */ 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} + */ export interface RenderSortStatusProps extends RenderSortIconProps, RenderSortPriorityProps {} +/** + * Props for custom checkbox renderers. + * + * @see {@linkcode renderCheckbox} function, {@linkcode DataGridProps.renderers | renderers.renderCheckbox}, {@linkcode SelectCheckbox | } + */ 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 */ @@ -449,19 +875,34 @@ export interface RenderCheckboxProps { 'aria-labelledby'?: string | undefined; } -export interface Renderers { - readonly renderCell?: Maybe<(key: Key, props: RenderCellProps) => ReactNode>; +/** + * Custom renderer configuration for the grid. + * + * @see {@linkcode DataGridProps.renderers | renderers} prop on ``, {@linkcode DataGridRenderersContext} + */ +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; } +/** + * Options for programmatically updating the grid's active position. + * + * @see {@linkcode DataGridHandle}, {@linkcode CellKeyDownArgs} + */ export interface SetActivePositionOptions { enableEditor?: Maybe; shouldFocus?: Maybe; } +/** + * Represents a single column's width. + * + * @see {@linkcode ColumnWidths} + */ export interface ColumnWidth { /** `'resized'` if the user resized the column, or `'measured'` if the grid measured it */ readonly type: 'resized' | 'measured'; @@ -469,8 +910,18 @@ export interface ColumnWidth { readonly width: number; } +/** + * A map of column widths. + * + * @see {@linkcode DataGridProps.columnWidths | columnWidths} and {@linkcode DataGridProps.onColumnWidthsChange | onColumnWidthsChange} props on `` + */ export type ColumnWidths = ReadonlyMap; +/** + * Text direction of the grid. + * + * @see {@linkcode DataGridProps.direction | direction} prop on `` + */ export type Direction = 'ltr' | 'rtl'; export type ResizedWidth = number | 'max-content'; diff --git a/tsconfig.node.json b/tsconfig.node.json index 10fc8a24ca..6eb11afae4 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -5,5 +5,5 @@ "module": "NodeNext", "types": ["node"] }, - "include": ["eslint.config.ts"] + "include": ["eslint.config.ts", "scripts/**/*"] } diff --git a/vite.config.ts b/vite.config.ts index b311a21a40..fc5798f457 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -81,6 +81,20 @@ 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: { + dependsOn: ['pack'], + command: ['node scripts/generateApiDocs.ts', 'vp fmt README.md'], + // the README is both an input and the output + cache: false + }, 'install-browsers': { command: isCI ? 'bash .github/install-browsers.sh' : 'playwright install --no-shell', // browsers are installed outside the workspace, so they cannot be restored from the cache @@ -107,16 +121,15 @@ export default defineConfig({ // the root cause of errors reported by later checks 'vp run typecheck', 'vp check', + // 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', - 'vp pack', + 'git diff --exit-code README.md', '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 `vp pm version`, as `vp run` appends them to the last command @@ -354,7 +367,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'], jsPlugins: [{ name: 'vite-plus', specifier: 'vite-plus/oxlint-plugin' }], options: { @@ -371,7 +384,7 @@ export default defineConfig({ // 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) => [ @@ -576,6 +589,29 @@ 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', + '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',