diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7a3380ef..af2cda28 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -99,6 +99,8 @@ jobs: VERSION="${{ steps.version.outputs.value }}" # Extract everything between the ## X.Y.Z heading and the next --- or ## heading NOTES=$(awk "/^## ${VERSION}$/{found=1; next} found && /^(---|## )/{exit} found{print}" CHANGELOG.md) + # GitHub Releases resolve root-relative links against github.com, so absolutize the docs links + NOTES=$(echo "$NOTES" | sed -E 's#\]\(/#](https://reactdatatable.com/#g') echo "content<> $GITHUB_OUTPUT echo "$NOTES" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT diff --git a/CHANGELOG.md b/CHANGELOG.md index c2e464c2..2e6cffb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,32 @@ A summary of notable changes per release. For the full commit history see the [repository on GitHub](https://github.com/jbetancur/react-data-table-component/commits/master). +## 8.10.0 + +### New features + +- **`column.filterOptions`** — per-column set filter settings. `values` supplies the checklist instead of deriving it from the loaded rows, so a column can offer values the current page does not hold. Takes an array or a function of the rows. → [Filtering](/docs/filtering#supplying-set-values) ([#1372](https://github.com/jbetancur/react-data-table-component/issues/1372)) +- **`column.filterOptions.separator`** — splits a set filter cell holding several values, so a column formatted as "React, TypeScript" offers each tag in the checklist rather than the whole string. A row matches when any of its parts is selected. → [Filtering](/docs/filtering#multi-value-cells) + +### Behavior changes + +- Context menu items now show icons for the built-in actions. Custom actions without an `icon` still align with the ones that have one. → [Context menu](/docs/context-menu) +- The column filter panel and the context menu now fade in rather than appearing instantly, and share one set of popup styles so they stay visually consistent. Respects `prefers-reduced-motion`. → [Context menu](/docs/context-menu) +- Both popups' drop shadow reads from the new `--rdt-shadow-popup` variable instead of a hardcoded value, so dark themes can set their own. The filter panel previously had no variable at all. → [Theming](/docs/themes) +- The column filter button now reports `aria-expanded` and `aria-haspopup="dialog"` instead of `aria-pressed`, which described it as a toggle rather than something that opens a panel. → [Filtering](/docs/filtering) + +### Bug fixes + +- Set filter checkboxes now use the table's own checkbox styling instead of the browser's native control, so they match the row selection checkboxes and follow the theme. → [Filtering](/docs/filtering) +- Keyboard focus in the context menu is now distinguishable from mouse hover. Both painted the same background, so arrowing through the menu while the pointer rested on another item highlighted two items at once. → [Context menu](/docs/context-menu) +- Checkboxes now show a focus ring when tabbed to. The styled checkbox hides the real input and draws its own box, which had no focus style, so keyboard users tabbing through row selection or a set filter checklist could not see where they were. → [Row selection](/docs/selection) +- Tab no longer escapes an open column filter panel. Focus now cycles within it, so a keyboard user could not end up behind an open panel with no way back. → [Filtering](/docs/filtering) +- A disabled context menu item's icon is no longer nearly invisible. The icon was muted with an opacity that multiplied with the already-dimmed disabled color. → [Context menu](/docs/context-menu) +- A set filter's `(Select all)` now announces that it acts on the search results while a search narrows the list. New `selectAllFilteredAriaLabel` localization string. → [Filtering](/docs/filtering) +- The column filter popup now aligns to the right edge of its button in RTL, matching the context menu. It always aligned its left edge to the button, so in RTL the panel opened across the wrong side of the column it belongs to. → [RTL](/docs/rtl) ([#1388](https://github.com/jbetancur/react-data-table-component/issues/1388)) + +--- + ## 8.9.1 ### Bug fixes @@ -131,7 +157,7 @@ A summary of notable changes per release. For the full commit history see the [r ### Bug fixes - Fixed RTL support across resizing, pinning, and separators: resize handles sit on the correct edge and widen as in LTR, pinned columns stick to logical edges with mirrored shadows, the pinned horizontal scrollbar accounts for RTL scroll coordinates, and column/group-header separators plus small chrome (filter dot, select arrows, pagination chevron) mirror correctly. Applies to `direction={Direction.RTL}` and inherited `dir="rtl"`. → [RTL support](/docs/rtl) -- Fixed row and table backgrounds cutting off at the initial container width when the table scrolls horizontally, leaving scrolled-into columns unpainted. → [Theming](/docs/theming) +- Fixed row and table backgrounds cutting off at the initial container width when the table scrolls horizontally, leaving scrolled-into columns unpainted. → [Theming](/docs/themes) - Fixed `fixedHeader` with `responsive={false}` not creating a scroll container, letting rows spill over content below the table. `fixedHeader` now always creates one. - Fixed the pinned-columns scrollbar failing to appear or going stale when content width changed without a container resize (async rows, resizing or toggling columns), and when columns were pinned with `responsive={false}`. → [Column pinning](/docs/column-pinning) - Fixed resize handles being clipped for right-pinned columns and the last column, which cut their hit areas down to a sliver. → [Resizable columns](/docs/resizable) diff --git a/apps/docs/public/llms.txt b/apps/docs/public/llms.txt index 39d502d5..78081a18 100644 --- a/apps/docs/public/llms.txt +++ b/apps/docs/public/llms.txt @@ -35,7 +35,7 @@ const columns = [ - [Column Resizing](https://reactdatatable.com/docs/resizable): drag column edges by mouse or touch, persist widths - [Column Pinning](https://reactdatatable.com/docs/column-pinning): pin columns left or right - [Column Separators](https://reactdatatable.com/docs/column-separators): vertical divider lines between header and body columns -- [Column Filtering](https://reactdatatable.com/docs/filtering): per-column text, number, date, datetime, and time-of-day filters with operator selection and two-condition AND/OR logic, plus set filters that pick from a checklist of a column's distinct values, and a filterServer option for backend filtering +- [Column Filtering](https://reactdatatable.com/docs/filtering): per-column text, number, date, datetime, and time-of-day filters with operator selection and two-condition AND/OR logic, plus set filters that pick from a checklist of a column's distinct values or a supplied list, optionally splitting cells that hold several values, and a filterServer option for backend filtering - [Sorting](https://reactdatatable.com/docs/sorting): client-side and server-side sorting ## Rows diff --git a/apps/docs/src/components/demos/RTLDemo.tsx b/apps/docs/src/components/demos/RTLDemo.tsx index 19ac8e69..eece92d6 100644 --- a/apps/docs/src/components/demos/RTLDemo.tsx +++ b/apps/docs/src/components/demos/RTLDemo.tsx @@ -62,6 +62,7 @@ export default function RTLDemo() { name: isRTL ? 'الاسم' : 'Name', selector: r => (isRTL ? r.nameAr : r.name), sortable: true, + filterable: true, width: '200px', minWidth: '120px', reorder: true, @@ -70,6 +71,7 @@ export default function RTLDemo() { name: isRTL ? 'القسم' : 'Department', selector: r => (isRTL ? r.departmentAr : r.department), sortable: true, + filterable: true, minWidth: '140px', reorder: true, }, @@ -79,6 +81,8 @@ export default function RTLDemo() { format: r => `$${r.salary.toLocaleString()}`, right: true, sortable: true, + filterable: true, + filterType: 'number', width: '140px', reorder: true, }, @@ -115,6 +119,7 @@ export default function RTLDemo() { highlightOnHover striped resizable + contextMenu /> ); diff --git a/apps/docs/src/components/demos/RowPinningDemo.tsx b/apps/docs/src/components/demos/RowPinningDemo.tsx index 78df36d2..c91a9787 100644 --- a/apps/docs/src/components/demos/RowPinningDemo.tsx +++ b/apps/docs/src/components/demos/RowPinningDemo.tsx @@ -148,7 +148,7 @@ export default function RowPinningDemo() {

Click the 📌 icon on any row to pin it. Pinned rows stay at the top regardless of how you sort. Sort any column - to see the behaviour. + to see the behavior.

t.status === 'Active' || t.status === 'Pending'); + +const columns: TableColumn[] = [ + { id: 'subject', name: 'Subject', selector: r => r.subject, grow: 2 }, + { + id: 'status', + name: 'Status', + selector: r => r.status, + filterable: true, + filterType: 'set', + filterOptions: { values: STATUSES }, + }, +]; + +export default function SetFilterOptionsDemo() { + const [rows, setRows] = React.useState(firstPage); + const [filters, setFilters] = React.useState>({}); + const [loading, setLoading] = React.useState(false); + + function handleFilterChange(columnId: string | number, next: FilterState) { + setFilters(prev => ({ ...prev, [columnId]: next })); + + // What a real fetch would do: send the selection, render whatever comes back. + setLoading(true); + const selected = next.values; + window.setTimeout(() => { + setRows(selected === undefined ? firstPage : everything.filter(t => selected.includes(t.status))); + setLoading(false); + }, 300); + } + + const selected = filters.status?.values; + + return ( +
+
+ {selected === undefined + ? 'no filter applied. Open the Status filter: all four statuses are listed, though only Active and Pending are loaded' + : `requested [${selected.join(', ')}] from the server`} +
+ + +
+ ); +} diff --git a/apps/docs/src/components/demos/SetFilterSeparatorDemo.tsx b/apps/docs/src/components/demos/SetFilterSeparatorDemo.tsx new file mode 100644 index 00000000..550371f1 --- /dev/null +++ b/apps/docs/src/components/demos/SetFilterSeparatorDemo.tsx @@ -0,0 +1,57 @@ +import React from 'react'; +import DataTable from '../ThemedDataTable'; +import { type TableColumn, type FilterState } from 'react-data-table-component'; + +interface Project { + id: number; + name: string; + stack: string; +} + +// The stack is stored the way it reads in the cell: one string, comma separated. +const projects: Project[] = [ + { id: 1, name: 'Checkout rewrite', stack: 'React, TypeScript' }, + { id: 2, name: 'Billing service', stack: 'Go, Postgres' }, + { id: 3, name: 'Design system', stack: 'React, Storybook, TypeScript' }, + { id: 4, name: 'Data pipeline', stack: 'Python, Postgres' }, + { id: 5, name: 'Marketing site', stack: 'Astro, TypeScript' }, + { id: 6, name: 'Internal scripts', stack: '' }, +]; + +const columns: TableColumn[] = [ + { id: 'name', name: 'Project', selector: r => r.name, grow: 2 }, + { + id: 'stack', + name: 'Stack', + selector: r => r.stack, + filterable: true, + filterType: 'set', + filterOptions: { separator: ',' }, + }, +]; + +export default function SetFilterSeparatorDemo() { + const [filters, setFilters] = React.useState>({}); + + const selected = filters.stack?.values; + + return ( +
+
+ {selected === undefined + ? 'no filter applied. Open the Stack filter: each technology is listed on its own, not as "React, TypeScript"' + : selected.length === 0 + ? 'nothing selected, so no rows match' + : `showing projects using any of [${selected.join(', ')}]`} +
+ + setFilters(prev => ({ ...prev, [columnId]: next }))} + highlightOnHover + /> +
+ ); +} diff --git a/apps/docs/src/data/props.ts b/apps/docs/src/data/props.ts index 0aca8dd2..75cff694 100644 --- a/apps/docs/src/data/props.ts +++ b/apps/docs/src/data/props.ts @@ -835,7 +835,7 @@ export const dataTableProps: PropDef[] = [ { name: 'onRowMiddleClicked', type: c('(row, event) => void'), - description: `Called when a row is middle-clicked (scroll-click). Use with ${c('onRowClicked')} to implement open-in-new-tab behaviour.`, + description: `Called when a row is middle-clicked (scroll-click). Use with ${c('onRowClicked')} to implement open-in-new-tab behavior.`, group: 'Row events', features: ['row-events'], }, @@ -926,6 +926,16 @@ export const dataTableProps: PropDef[] = [ group: 'Column features', features: ['filtering'], }, + { + name: 'column.filterOptions', + on: 'column', + type: c('{ values?: string[] | ((rows: T[]) => string[]); separator?: string | RegExp }'), + default: '-', + description: `Per-column filter settings, only read by ${c("filterType: 'set'")}. ${c('values')} supplies the checklist instead of deriving it from the rows: use it when the column has a known domain the loaded rows may not cover, such as a status the server holds but the current page does not. Order is kept as given, and blanks are only offered if the list contains an empty string. ${c('separator')} splits a cell holding several values, so a column formatted as "React, TypeScript" lists each tag separately and a row matches when any of its parts is selected. See Filtering and multi-value cells.`, + brief: `Per-column set filter settings. ${c('values')} supplies the checklist, ${c('separator')} splits multi-value cells.`, + group: 'Column features', + features: ['filtering'], + }, { name: 'onColumnOrderChange', type: c('(columns: TableColumn<T>[]) => void'), diff --git a/apps/docs/src/pages/docs/api.astro b/apps/docs/src/pages/docs/api.astro index 578934d3..ac9c3eb6 100644 --- a/apps/docs/src/pages/docs/api.astro +++ b/apps/docs/src/pages/docs/api.astro @@ -230,7 +230,7 @@ interface CustomCellEditorContext { rows={[ ['--rdt-color-cell-edit-bg', '8% primary on bg', 'Background of the cell while editing.'], ['--rdt-color-cell-edit-hover', '6% primary', 'Background of an editable cell on hover.'], - ['--rdt-color-cell-edit-hover-border', '40% primary', 'Dashed underline colour on editable cell hover.'], + ['--rdt-color-cell-edit-hover-border', '40% primary', 'Dashed underline color on editable cell hover.'], ]} /> diff --git a/apps/docs/src/pages/docs/column-groups.astro b/apps/docs/src/pages/docs/column-groups.astro index 879695b3..fb761007 100644 --- a/apps/docs/src/pages/docs/column-groups.astro +++ b/apps/docs/src/pages/docs/column-groups.astro @@ -136,7 +136,7 @@ export default function App() {

Group label cells carry the CSS class rdt_groupCell. Target it directly - to override colours, font, or spacing without needing customStyles: + to override colors, font, or spacing without needing customStyles:

-// Body separators — subtle inset (60% height, centred) +// Body separators — subtle inset (60% height, centered) // Body separators — full-height @@ -45,8 +45,8 @@ import ColumnSeparatorsDemo from '../../components/demos/ColumnSeparatorsDemo.ts headers={['Value', 'Effect']} rows={[ ['false', 'No separators'], - ['true / "subtle"', '60%-height inset line, centred vertically'], - ['"full"', "Full-height line using the theme's divider colour"], + ['true / "subtle"', '60%-height inset line, centered vertically'], + ['"full"', "Full-height line using the theme's divider color"], ]} /> diff --git a/apps/docs/src/pages/docs/columns.astro b/apps/docs/src/pages/docs/columns.astro index f7c6a27b..b9c3f57f 100644 --- a/apps/docs/src/pages/docs/columns.astro +++ b/apps/docs/src/pages/docs/columns.astro @@ -11,7 +11,7 @@ import ColumnsDemo from '../../components/demos/ColumnsDemo.tsx';

Columns are defined as an array of TableColumn<T> objects. - Each column controls its header label, data accessor, sort behaviour, rendering, and layout. + Each column controls its header label, data accessor, sort behavior, rendering, and layout.

[ hide-column, reset. Use different ids for custom actions.

-

Accessibility and behaviour

+

Accessibility and behavior

  • The menu renders with role="menu" / role="menuitem"; Arrow keys, Home, and End move focus, Escape closes and returns focus to the trigger.
  • Menu buttons carry aria-haspopup="menu" and localizable labels; row menu buttons appear on hover/focus and are always visible on touch devices.
  • On filterable columns the header menu button renders after the filter icon, so it is always the outermost control — mirrored automatically in RTL.
  • The menu flips above the pointer near the bottom edge and clamps within the viewport; it closes on outside click, scroll, and resize.
  • +
  • The built-in actions carry icons. If any item in a menu has one, items without an icon still reserve the space, so every label starts at the same offset.
  • +
  • The menu fades in on open, and holds still when prefers-reduced-motion: reduce is set.
  • In RTL the button-anchored menu aligns to the button's opposite edge automatically.
  • All labels can be translated via localization.contextMenu — see Localization. The bundled locales include translations.
@@ -162,7 +164,7 @@ const rowActions = (row: Task): ContextMenuAction[] => [ ['id', 'string', 'Identifier passed to onContextMenuAction. Built-in ids are reserved.'], ['label', 'ReactNode', 'Item content.'], ['disabled', 'boolean', 'Renders the item disabled.'], - ['icon', 'ReactNode', 'Optional icon rendered before the label.'], + ['icon', 'ReactNode', 'Optional icon rendered before the label. Built-in actions supply their own; omit it and the item still aligns with those that have one.'], ]} /> diff --git a/apps/docs/src/pages/docs/filtering.astro b/apps/docs/src/pages/docs/filtering.astro index e8be9488..7d2f44f3 100644 --- a/apps/docs/src/pages/docs/filtering.astro +++ b/apps/docs/src/pages/docs/filtering.astro @@ -5,6 +5,8 @@ import CodeBlock from '../../components/CodeBlock.astro'; import FilteringDemo from '../../components/demos/FilteringDemo.tsx'; import TimeFilterDemo from '../../components/demos/TimeFilterDemo.tsx'; import SetFilterDemo from '../../components/demos/SetFilterDemo.tsx'; +import SetFilterOptionsDemo from '../../components/demos/SetFilterOptionsDemo.tsx'; +import SetFilterSeparatorDemo from '../../components/demos/SetFilterSeparatorDemo.tsx'; import DocsTable from '../../components/DocsTable.astro'; import PropsTable from '../../components/PropsTable.astro'; --- @@ -112,7 +114,7 @@ export default function App() { ]} /> -

A few types have behaviour worth knowing before you pick one:

+

A few types have behavior worth knowing before you pick one:

  • @@ -189,7 +191,13 @@ export default function App() {
    • Values are derived from the rows you pass in, sorted naturally. The list is the column’s - full distinct set and does not change as you filter other columns. + full distinct set and does not change as you filter other columns. Set + filterOptions.values on the column to supply the list instead. +
    • +
    • + One cell can hold several values. A column of tags or a stack, formatted as + React, TypeScript, lists each part separately once you set + filterOptions.separator.
    • A search box narrows long lists, and (Select all) acts on what the search @@ -206,12 +214,137 @@ export default function App() {
    -
    - Set filters build the checklist from the rows the table is holding. With paginationServer that is - only the current page, so the checklist lists just the values present on that page. Until a prop for supplying - the full value list lands, drive the filter yourself, as in Server-side filtering - below. -
    +

    Supplying the checklist values

    + +

    + Deriving values from the rows only works when the rows already contain every value worth filtering on. A + column whose domain is fixed and known, a status or a priority, is usually the opposite case: the list is + something you know up front, and the loaded rows are just a sample of it. Set + filterOptions.values on the column to supply the list yourself. +

    + +

    + This matters most with server-side data. The table only holds the current page, so a status the server knows + about but the page does not would never appear in the checklist, and the user could not ask for it. That is + circular: the value only becomes selectable once rows carrying it are loaded, but loading them is the whole + point of selecting it. Supplying the list breaks the loop. +

    + +

    + The demo below holds only Active and Pending tickets, as though the first + page had just come back from a server. All four statuses are still listed, and picking + Closed or Archived refetches. +

    + + [] = [ + { id: 'subject', name: 'Subject', selector: r => r.subject, grow: 2 }, + { + id: 'status', + name: 'Status', + selector: r => r.status, + filterable: true, + filterType: 'set', + filterOptions: { values: STATUSES }, + }, +]; + + { + setFilters(prev => ({ ...prev, [columnId]: next })); + fetchFromServer(next.values); // undefined means nothing is selected yet + }} +/>;`} + > + + + +

    + Pair it with filterServer, which is implied by paginationServer, so the built-in + matcher does not run a second time against rows the server already filtered. See + Server-side filtering below. +

    + +
      +
    • + Order is kept as given. Derived values are sorted naturally, but a supplied list is + authored, so ['Low', 'Medium', 'High'] stays in that order rather than being alphabetized. +
    • +
    • + Blanks are only offered if you ask for one. Include an empty string in the list to get a + (Blanks) entry. Derived lists add one whenever a row has an empty cell. +
    • +
    • + values also takes a function, receiving the rows the table is holding, so a fixed domain can be + merged with whatever else turned up: + {`{ values: rows => [...new Set([...STATUSES, ...rows.map(r => r.status)])] }`}. +
    • +
    • + The column still needs a selector. filterOptions.values supplies the checklist, but + client-side matching reads cell values through the selector. +
    • +
    + +

    Cells holding several values

    + +

    + A column sometimes holds more than one thing per cell: a list of tags, a stack, the labels on an issue. Left + alone, a set filter treats the whole cell as one value, so a row reading React, TypeScript offers + exactly that string in the checklist and nothing for React on its own. Set + filterOptions.separator to split the cell into its parts. +

    + +

    + Each part becomes its own checklist entry, and a row matches when any of its parts is + selected. Checking React and Postgres shows every project using either, + which is how a tag filter is normally read. +

    + + [] = [ + { id: 'name', name: 'Project', selector: r => r.name, grow: 2 }, + { + id: 'stack', + name: 'Stack', + selector: r => r.stack, + filterable: true, + filterType: 'set', + filterOptions: { separator: ',' }, + }, +];`} + > + + + +
      +
    • + Parts are trimmed, and empty ones dropped. 'React, , TypeScript,' yields two + values, so ragged data does not litter the checklist with blanks. +
    • +
    • + A cell left with nothing counts as blank. An empty cell, or one holding only separators, + still reaches the (Blanks) entry. +
    • +
    • + A RegExp works too, for data that is not consistently delimited: + {`{ separator: /\s*[,|]\s*/ }`}. +
    • +
    • + Pair it with filterOptions.values to supply the parts yourself rather than deriving them from + the loaded rows. The two are independent: values sets the checklist, + separator governs how cells are matched against it. +
    • +

    Two conditions per column

    @@ -221,13 +354,37 @@ export default function App() { function. Set filters have no operators, so they show the checklist instead of this link.

    -

    Apply / Clear behaviour

    +

    Apply / Clear behavior

    Filters apply only when the user clicks Apply. Typing does not immediately re-filter. This avoids jarring mid-keystroke changes on large datasets. Clicking Clear resets the column's filter and applies immediately.

    +

    Keyboard and accessibility

    +
      +
    • + The filter button carries aria-haspopup="dialog" and aria-expanded, and the panel + is a role="dialog" labelled for screen readers. +
    • +
    • + Opening the panel moves focus into it. Tab and Shift+Tab cycle within the panel rather than escaping behind + it, and Escape closes it and returns focus to the filter button. +
    • +
    • + In a set filter, Tab moves through the search box, (Select all), each value, then Clear and + Apply; Space toggles the focused checkbox. Checkboxes show a focus ring, and the focused row is highlighted. +
    • +
    • + While a search narrows the checklist, (Select all) acts only on the matches, and announces + that to screen readers. +
    • +
    • + The panel flips above its button near the bottom edge, clamps within the viewport, and scrolls internally + when it cannot fit. It fades in on open, and holds still under prefers-reduced-motion: reduce. +
    • +
    +

    Filter state

    You can ignore this section until you need to read or write filters yourself, which comes up when you persist diff --git a/apps/docs/src/pages/docs/headless.astro b/apps/docs/src/pages/docs/headless.astro index 78e319c1..89cfab39 100644 --- a/apps/docs/src/pages/docs/headless.astro +++ b/apps/docs/src/pages/docs/headless.astro @@ -105,7 +105,7 @@ graph TD

    • You have a design system and can't override the default styles far enough
    • -
    • You're building inside a heavily customised UI (e.g. a design system component library)
    • +
    • You're building inside a heavily customized UI (e.g. a design system component library)
    • You want the table logic but need to render it inside something other than a standard <table> or flex layout
    • You want to compose only some hooks (e.g. sorting + pagination) and handle the rest yourself
    diff --git a/apps/docs/src/pages/docs/inline-editing.astro b/apps/docs/src/pages/docs/inline-editing.astro index a5d81651..88d3470f 100644 --- a/apps/docs/src/pages/docs/inline-editing.astro +++ b/apps/docs/src/pages/docs/inline-editing.astro @@ -414,7 +414,7 @@ const columns: TableColumn[] = [ A column can have both a custom cell renderer and an editor. The cell renderer is used for display; clicking the cell switches to the inline editor. This is the pattern shown in the demo above. Status renders as a - coloured badge but edits as a dropdown. + colored badge but edits as a dropdown.

  • Initial load (no data yet): shimmer skeleton rows fill the body so the layout doesn't collapse.
  • -
  • Re-fetch (rows already shown): existing rows stay in place, dim to 40% opacity, and a spinner overlays the centre. The header and pagination never disappear.
  • +
  • Re-fetch (rows already shown): existing rows stay in place, dim to 40% opacity, and a spinner overlays the center. The header and pagination never disappear.

@@ -64,7 +64,7 @@ export default function UsersTable() {

The default progressComponent is a CSS spinner circle. Pass any React node to replace it: - your node is centred in the overlay during re-fetches. On initial load the skeleton rows show instead; + your node is centered in the overlay during re-fetches. On initial load the skeleton rows show instead; set progressSkeleton={false} to show your progressComponent there too.

diff --git a/apps/docs/src/pages/docs/localization.astro b/apps/docs/src/pages/docs/localization.astro index 6c9eaf98..a06651ad 100644 --- a/apps/docs/src/pages/docs/localization.astro +++ b/apps/docs/src/pages/docs/localization.astro @@ -139,6 +139,7 @@ const custom: Localization = { andLabel?: string; // default: 'AND' orLabel?: string; // default: 'OR' selectAllLabel?: string; // default: '(Select all)' + selectAllFilteredAriaLabel?: string; // default: '(Select all) search results' blanksLabel?: string; // default: '(Blanks)' searchPlaceholder?: string; // default: 'Search' searchAriaLabel?: string; // default: 'Search filter values' diff --git a/apps/docs/src/pages/docs/migration.md b/apps/docs/src/pages/docs/migration.md index 4e1c36ca..3ecfd1dc 100644 --- a/apps/docs/src/pages/docs/migration.md +++ b/apps/docs/src/pages/docs/migration.md @@ -241,7 +241,7 @@ const ref = useRef(null); ``` -### Behavioural fix: `createTheme` shape +### Behavioral fix: `createTheme` shape If you were following old examples that wrapped theme tokens in a `colors` object, that wrapper was never a real API. Pass tokens at the top level: diff --git a/apps/docs/src/pages/docs/row-interactions.astro b/apps/docs/src/pages/docs/row-interactions.astro index caab8597..365f2e54 100644 --- a/apps/docs/src/pages/docs/row-interactions.astro +++ b/apps/docs/src/pages/docs/row-interactions.astro @@ -68,7 +68,7 @@ export default function App() {

Use onRowMiddleClicked to handle middle-click (scroll-click). Combined with - onRowClicked, you get full NavLink behaviour: left-click navigates in the same tab, + onRowClicked, you get full NavLink behavior: left-click navigates in the same tab, middle-click or Ctrl/⌘+click opens in a new tab.

diff --git a/apps/docs/src/pages/docs/rtl.astro b/apps/docs/src/pages/docs/rtl.astro index fd2b41c7..5ab7df40 100644 --- a/apps/docs/src/pages/docs/rtl.astro +++ b/apps/docs/src/pages/docs/rtl.astro @@ -17,10 +17,10 @@ import PropsTable from '../../components/PropsTable.astro'; ;`} +;`} > @@ -28,7 +28,7 @@ import PropsTable from '../../components/PropsTable.astro';

Direction values

Direction.LTR / "ltr"', 'Forces left-to-right regardless of the page\'s dir attribute.'], ['Direction.RTL / "rtl"', 'Forces right-to-left. Pagination arrows flip; dir="rtl" is set on the wrapper.'], @@ -66,6 +66,7 @@ import PropsTable from '../../components/PropsTable.astro';
  • Pagination first/prev/next/last buttons have their icons reversed via .rdt_paginationButtonRTL.
  • Column right: true alignment continues to work as expected. Align numbers relative to the reading direction of the cell content, not the page.
  • With resizable, the resize handle moves to each column's left (end) edge and drag direction mirrors, so dragging away from the column widens it just like in LTR.
  • +
  • Popups anchored to a button, the column filter panel and the context menu, align their right edge to the button instead of their left, so they open across the column they belong to. Both are still clamped to stay inside the viewport.
  • Pairing with localization

    diff --git a/apps/docs/src/pages/docs/selection.astro b/apps/docs/src/pages/docs/selection.astro index f70afe37..89933eea 100644 --- a/apps/docs/src/pages/docs/selection.astro +++ b/apps/docs/src/pages/docs/selection.astro @@ -109,7 +109,7 @@ export default function App() { selection is enabled by default; opt out with selectableRowsRange={false}.

    - The behaviour respects selectableRowDisabled — disabled rows in the range are + The behavior respects selectableRowDisabled — disabled rows in the range are skipped, not toggled. It also stays within the current page when pagination is enabled.

    <input type="checkbox"> — DataTable sets .indeterminate on the node directly for the partial-selection state on the header checkbox. Keep the input in the DOM and style a sibling element off it, rather than replacing it, so keyboard and screen - reader behaviour still work. + reader behavior still work.

    ( ({ accent = '#7c3aed', checked, disabled, ...rest }, ref) => (
    @@ -309,7 +316,11 @@ export default function ColumnFilter({ const rect = panel.getBoundingClientRect(); const anchor = button.getBoundingClientRect(); const margin = 8; - const left = Math.max(margin, Math.min(anchor.left, window.innerWidth - rect.width - margin)); + // Read the direction off the panel rather than take it as a prop: it picks up `dir` + // set anywhere up the tree, and ColumnFilter renders too far down to reach useRTL. + const isRTL = getComputedStyle(panel).direction === 'rtl'; + const anchored = isRTL ? anchor.right - rect.width : anchor.left; + const left = Math.max(margin, Math.min(anchored, window.innerWidth - rect.width - margin)); let top = anchor.bottom + 4; if (top + rect.height > window.innerHeight - margin) { const flipped = anchor.top - rect.height - 4; @@ -318,6 +329,9 @@ export default function ColumnFilter({ panel.style.left = `${left}px`; panel.style.top = `${Math.max(margin, top)}px`; panel.style.visibility = 'visible'; + // Idempotent: this effect re-measures on every render, and re-adding a class the + // element already carries does not restart the animation. + panel.classList.add('rdt_popupVisible'); }); React.useEffect(() => { @@ -343,6 +357,30 @@ export default function ColumnFilter({ if (e.key === 'Escape') { setOpen(false); buttonRef.current?.focus(); + return; + } + // A dialog keeps focus inside it: tabbing off the last control would otherwise + // land behind an open panel, with no way back except the mouse. + if (e.key !== 'Tab' || !panelRef.current) { + return; + } + const focusable = panelRef.current.querySelectorAll( + 'select, input:not([disabled]), button:not([disabled])', + ); + if (focusable.length === 0) { + return; + } + + const first = focusable[0]; + const last = focusable[focusable.length - 1]; + const active = document.activeElement; + + if (e.shiftKey && active === first) { + e.preventDefault(); + last.focus(); + } else if (!e.shiftKey && active === last) { + e.preventDefault(); + first.focus(); } } // The panel is position: fixed, so any scroll (page or the table's own @@ -447,7 +485,8 @@ export default function ColumnFilter({ ? (options.filterActiveAriaLabel ?? 'Filter active') : (options.filterColumnAriaLabel ?? 'Filter column') } - aria-pressed={open} + aria-haspopup="dialog" + aria-expanded={open} onClick={e => { e.stopPropagation(); toggleOpen(); @@ -460,7 +499,7 @@ export default function ColumnFilter({ {open && panelPos && (
    { @@ -65,7 +66,7 @@ export default function ContextMenu({ } } // The menu is position: fixed, so any scroll moves the anchor out from under it — - // close rather than track (same behaviour as the column filter panel). + // close rather than track (same behavior as the column filter panel). function handleScroll(e: Event) { if (menuRef.current && e.target instanceof Node && menuRef.current.contains(e.target)) { return; @@ -122,11 +123,14 @@ export default function ContextMenu({ }; const renderedGroups = groups.filter(g => g.length > 0); + // If anything in the menu has an icon, icon-less items still get the slot so every + // label starts at the same offset. + const hasIcons = renderedGroups.some(g => g.some(a => a.icon)); return (
    onSelect(action)} > - {action.icon && ( + {(action.icon || hasIcons) && ( diff --git a/src/hooks/useColumnFilter.ts b/src/hooks/useColumnFilter.ts index 8e526fa9..031a8b33 100644 --- a/src/hooks/useColumnFilter.ts +++ b/src/hooks/useColumnFilter.ts @@ -48,6 +48,19 @@ function setValueOf(raw: string): string { return isBlank(raw) ? '' : raw; } +// The parts of a cell under a column's `separator`, or the whole cell when it has none. +// Parts are trimmed and empties dropped, so "React, , TypeScript" yields two values and a +// cell of only separators folds to a single blank rather than vanishing from the checklist. +function splitCellValue(cellValue: string, separator: string | RegExp | undefined): string[] { + if (separator === undefined) { + return [setValueOf(cellValue)]; + } + + const parts = cellValue.split(separator).filter(part => !isBlank(part)); + + return parts.length > 0 ? parts.map(part => part.trim()) : ['']; +} + // Cached by array identity so the set is built once per filter pass, not per row. const selectedSetCache = new WeakMap>(); function selectedSetOf(values: string[]): Set { @@ -278,7 +291,10 @@ function rowMatchesFilter(row: T, filter: FilterState, col: TableColumn): if (!col.selector) { return true; } - return isValueSelected(setValueOf(cellValue), filter.values, filter.knownValues); + // Any part matching keeps the row: checking a tag shows every row carrying it. + return splitCellValue(cellValue, col.filterOptions?.separator).some(value => + isValueSelected(value, filter.values, filter.knownValues), + ); } // Only active conditions participate — an empty condition1 must not force-match @@ -429,6 +445,13 @@ export default function useColumnFilter( const { columnsById: cols, rows: allRows } = distinctSource.current; const col = cols.get(String(columnId)); + const values = col?.filterOptions?.values; + if (values) { + const supplied = typeof values === 'function' ? values(allRows) : values; + + return [...new Set(supplied.map(setValueOf))]; + } + if (!col?.selector) { return []; } @@ -436,7 +459,9 @@ export default function useColumnFilter( const seen = new Set(); for (const row of allRows) { - seen.add(setValueOf(String(col.selector(row) ?? ''))); + for (const value of splitCellValue(String(col.selector(row) ?? ''), col.filterOptions?.separator)) { + seen.add(value); + } } // Blanks sort last so the checklist opens on real values. diff --git a/src/hooks/useContextMenu.ts b/src/hooks/useContextMenu.tsx similarity index 95% rename from src/hooks/useContextMenu.ts rename to src/hooks/useContextMenu.tsx index 70dba03c..f3f1e5b0 100644 --- a/src/hooks/useContextMenu.ts +++ b/src/hooks/useContextMenu.tsx @@ -2,6 +2,16 @@ import * as React from 'react'; import { equalizeId } from '../util'; import { emptyFilterState } from './useColumnFilter'; import { SortOrder } from '../types'; +import { + ClearSortIcon, + HideColumnIcon, + PinLeftIcon, + PinRightIcon, + ResetIcon, + SortAscIcon, + SortDescIcon, + UnpinIcon, +} from '../icons/MenuIcons'; import type { ColumnGroup, ContextMenuAction, @@ -206,9 +216,14 @@ export default function useContextMenu({ if (column.sortable) { groups.push([ - { id: 'sort-asc', label: localization.sortAscLabel ?? 'Sort ascending' }, - { id: 'sort-desc', label: localization.sortDescLabel ?? 'Sort descending' }, - { id: 'clear-sort', label: localization.clearSortLabel ?? 'Clear sort', disabled: sortColumns.length === 0 }, + { id: 'sort-asc', label: localization.sortAscLabel ?? 'Sort ascending', icon: }, + { id: 'sort-desc', label: localization.sortDescLabel ?? 'Sort descending', icon: }, + { + id: 'clear-sort', + label: localization.clearSortLabel ?? 'Clear sort', + disabled: sortColumns.length === 0, + icon: , + }, ]); } @@ -217,13 +232,13 @@ export default function useContextMenu({ // header group — omit pin actions when column groups are in play. if (!columnGroups?.length) { if (column.pinned !== 'left') { - columnGroup.push({ id: 'pin-left', label: localization.pinLeftLabel ?? 'Pin left' }); + columnGroup.push({ id: 'pin-left', label: localization.pinLeftLabel ?? 'Pin left', icon: }); } if (column.pinned !== 'right') { - columnGroup.push({ id: 'pin-right', label: localization.pinRightLabel ?? 'Pin right' }); + columnGroup.push({ id: 'pin-right', label: localization.pinRightLabel ?? 'Pin right', icon: }); } if (column.pinned) { - columnGroup.push({ id: 'unpin', label: localization.unpinLabel ?? 'Unpin' }); + columnGroup.push({ id: 'unpin', label: localization.unpinLabel ?? 'Unpin', icon: }); } } const visibleCount = tableColumns.filter(c => !c.omit).length; @@ -231,9 +246,10 @@ export default function useContextMenu({ id: 'hide-column', label: localization.hideColumnLabel ?? 'Hide column', disabled: visibleCount <= 1, + icon: , }); groups.push(columnGroup); - groups.push([{ id: 'reset', label: localization.resetLabel ?? 'Reset table' }]); + groups.push([{ id: 'reset', label: localization.resetLabel ?? 'Reset table', icon: }]); const custom = typeof contextMenuActions?.header === 'function' ? contextMenuActions.header(column) : contextMenuActions?.header; diff --git a/src/hooks/useSorting.ts b/src/hooks/useSorting.ts index b9586df5..5aaf1376 100644 --- a/src/hooks/useSorting.ts +++ b/src/hooks/useSorting.ts @@ -6,7 +6,7 @@ import type { SortOrder, SortAction, SortColumn } from '../types'; * `sortColumns` changes identity on every sort interaction — that is legitimate * (headers must re-render); TableCol's memo does per-column checks inside the * slice to keep unaffected columns from re-rendering. The remaining fields are - * config that also feeds the SORT_CHANGE action (selection-clearing behaviour). + * config that also feeds the SORT_CHANGE action (selection-clearing behavior). */ export type SortingSlice = { sortDirection: SortOrder; diff --git a/src/icons/MenuIcons.tsx b/src/icons/MenuIcons.tsx new file mode 100644 index 00000000..af835b8d --- /dev/null +++ b/src/icons/MenuIcons.tsx @@ -0,0 +1,45 @@ +import React from 'react'; + +type IconProps = { + size?: number; +}; + +function icon(path: React.ReactNode) { + const Icon: React.FC = ({ size = 14 }) => ( + + ); + + return Icon; +} + +export const SortAscIcon = icon(); + +export const SortDescIcon = icon(); + +export const ClearSortIcon = icon( + , +); + +export const PinLeftIcon = icon(); + +export const PinRightIcon = icon(); + +export const UnpinIcon = icon( + , +); + +export const HideColumnIcon = icon( + , +); + +export const ResetIcon = icon(); diff --git a/src/index.ts b/src/index.ts index 8976977d..1d7ce620 100644 --- a/src/index.ts +++ b/src/index.ts @@ -56,6 +56,7 @@ export type { FilterOperator, FilterCondition, FilterState, + SetFilterOptions, CellEditor, CellEditCallback, CellValidateResult, diff --git a/src/types.ts b/src/types.ts index d0c3b976..9637c098 100644 --- a/src/types.ts +++ b/src/types.ts @@ -46,6 +46,25 @@ export type FilterState = { knownValues?: string[]; }; +/** Per-column filter settings. Only read by `filterType: "set"`. */ +export type SetFilterOptions = { + /** + * The checklist values, replacing the ones derived from the rows. Use it when the column has a + * known domain the loaded rows may not cover, such as a status the server holds but the current + * page does not. Order is kept as given, and blanks are only offered if the list contains an + * empty string. The function form receives the rows the table is holding, so a fixed domain can + * be merged with whatever else turned up. + */ + values?: string[] | ((rows: T[]) => string[]); + /** + * Splits a cell holding several values into its parts, so a column formatted as + * "React, TypeScript" offers each tag in the checklist rather than the whole string. A row + * matches when any of its parts is selected. Parts are trimmed and empty ones dropped, so a + * cell is blank only when nothing is left after the split. + */ + separator?: string | RegExp; +}; + export enum SortOrder { ASC = 'asc', DESC = 'desc', @@ -483,6 +502,8 @@ export interface TableColumn extends TableColumnBase { sortFunction?: ColumnSortFunction; /** Custom filter function — overrides built-in operator logic. Receives the full FilterState so both conditions are available. */ filterFunction?: (row: T, filter: FilterState) => boolean; + /** Settings for this column's filter. Only read by `filterType: "set"`. */ + filterOptions?: SetFilterOptions; /** Called when the user commits an inline edit (blur or Enter). Only fires when editable: true. */ onCellEdit?: CellEditCallback; /** @@ -650,6 +671,9 @@ export interface Localization { orLabel?: string; /** Label for the select-all checkbox in a "set" filter. Default: "(Select all)" */ selectAllLabel?: string; + /** aria-label for the select-all checkbox while a search is narrowing the list, where it + * acts only on the matches. Default: "(Select all) search results" */ + selectAllFilteredAriaLabel?: string; /** Label for the blank-values entry in a "set" filter. Default: "(Blanks)" */ blanksLabel?: string; /** Placeholder for the search box in a "set" filter. Default: "Search" */ @@ -867,13 +891,13 @@ export interface Theme { /** Checkbox appearance — controls the CSS variables for the built-in CSS checkbox. */ checkbox?: { size?: string; borderRadius?: string }; /** - * Default header column separator behaviour for this theme. + * Default header column separator behavior for this theme. * The `headerSeparator` prop overrides this when explicitly passed. * Omitting both falls back to `'subtle'`. */ headerSeparator?: boolean | 'subtle' | 'full'; /** - * Default body column separator behaviour for this theme. + * Default body column separator behavior for this theme. * The `columnSeparator` prop overrides this when explicitly passed. * Omitting both falls back to `false` (no separator). */