Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(quill): add resizable table columns and a filter menu (#128617)

Adam Leitha1e648295384
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d1018b5f8cf7..503cc34eda44 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11303,9 +11303,9 @@ snapshots:
scenes-app-error-tracking-insights-panels--key-metrics-narrow-scene--light:
hash: v1.k794b7964.0d3fc071e8be5b6d23cb78ba681159b03b7974eb264134001ec5818ef1e9ee2b.u3DSMAooGY0uRKI06__c5pIsNrkkLXBBE-7frOYWccI
scenes-app-error-tracking-insights-panels--release-list--dark:
- hash: v1.k794b7964.9499e2d132106a167a5b80083e7fde8d87dc505c10b88df6f7da33caf58b1924._7etlGW7P7rPphXSm92I9LNAZvzApU4zTuA3bDkpNbM
+ hash: v1.k794b7964.747b3e7d4e8820cab9ef3ebe55dd1d9af1415474f0316d059b722ee3e1993c8b.r67vG20ey8XYE6dLEkKAjzr0iGA26uwAXxI-LRQV8wk
scenes-app-error-tracking-insights-panels--release-list--light:
- hash: v1.k794b7964.f348be5ccd7694090ebd0e41d249917849bbd92cfd08545726f3372ab6d5388c.km2n6GFkB2Qo5BFRYLm8Y1lzK0TPeDG2VxuUxjDx-wQ
+ hash: v1.k794b7964.057faaca6be748cdbaec4925947447995019b1829062837cf9224f9334655063.-_wKm6EC3p6WpTX18C-RQjPguVCb2Pz_6eI78sul9No
scenes-app-errortracking--group-page--dark:
hash: v1.k794b7964.4d4f9857e72e215c43df3eb4377b1cc32e11ac73c04c2968384f583b14b3c66a.KqPWU1tVezxvdcskSRZ0D63VLL8qXBRSMFQ2l1wd2yc
scenes-app-errortracking--group-page--light:
diff --git a/packages/quill/packages/components/AGENTS.md b/packages/quill/packages/components/AGENTS.md
index 7e6ebeb19dd6..797d9683feda 100644
--- a/packages/quill/packages/components/AGENTS.md
+++ b/packages/quill/packages/components/AGENTS.md
@@ -5,6 +5,7 @@ Quick-reference for AI agents using `@posthog/quill-components` — composed com
## Exports
- `DataTable` — TanStack Table wired onto quill `Table` + `Pagination`
+- `FilterMenuTrigger`, `FilterRadioSubMenu`, `FilterCheckboxSubMenu`, `FilterSearchSubMenu`, `FilterSubMenu`, `FilterClearItem`, `filterSummary` — the parts of a list's one filter menu
- `DateTimePicker` — calendar range picker with quick-range presets (`quickRanges`, `CUSTOM_RANGE`)
- `DatePicker` — single-date picker (one calendar, optional time, no quick ranges)
- `useCalendar` — headless calendar grid hook (`Day`, `Month` enums)
@@ -39,12 +40,54 @@ Rules:
- Column defs are standard TanStack `ColumnDef`s; quill-specific options go in `meta`: `align: 'left' | 'center' | 'right'` (header + cells) and `expand: true` (absorb leftover width).
- `fullWidth` needs exactly one column with `meta: { expand: true }` to decide which column stretches.
-- Sorting is client-side and on by default — click header toggles asc → desc → off. Opt out per column with `enableSorting: false`.
+- Sorting is client-side and on by default — click header toggles asc → desc → off. Opt out per column with `enableSorting: false`. A column needs an `accessorKey` or `accessorFn` to sort.
+- A list sorted on the server passes `sorting` and `onSortingChange`. The table then keeps the rows in the order of `data`, only reports the clicks, and has no "off" state. Use `sortDescFirst` on a column to start at desc. `meta: { sortDataAttr }` sets the `data-attr` of the column's sort button.
+- `resizableColumns` lets the user drag a column's edge, or focus it and use the arrow keys. Its line shows while the header is hovered, and its handle while that header cell is. Columns fit their content until the first resize, then stay fixed. Bound a column with `minSize` and `maxSize` (the default minimum is 64px), and opt it out with `enableResizing: false`, as an actions column should. `columnSizing` and `onColumnSizingChange` control the widths, in pixels by column id, so a caller can save and restore them. A drag never renders: the handle moves the column in the DOM and `onColumnSizingChange` fires once, when it ends, so a table of any size stays smooth. A double click on an edge resets that column. A resize changes the dragged column and no other, including an `expand` column, which stops stretching at the first resize. A `fullWidth` table fills any space left over with an empty column, and scrolls once the columns no longer fit. Touch screens have no resizing.
+- `viewportRef` reaches the scrolling viewport, and `viewportEndRef` a marker at the end of it. Observe the marker, with the viewport as the root, to load more rows near the end.
- Pagination is opt-in via `pageSize`; the component owns page state, reports user navigation through `onPageChange`, and resets to page 0 when `pageSize` changes. The pager is suppressed when the table has no rows — an empty table shows only its empty state, never a "0–0 of 0" pager.
- Custom empty state via the `empty` prop (ReactNode); default is a minimal "No results".
- `onRowClick` makes non-interactive parts of each row clickable and keyboard accessible. Links, buttons, form controls, editable content, and custom controls keep their own behavior. Add `data-row-click-ignore` to a custom descendant that must not activate the row.
- Don't rebuild tables from `Table` primitives when the data is row/column shaped and needs sorting or pagination — that's what DataTable is for. Drop to the `Table` primitive only for fully custom layouts.
+## FilterMenu
+
+A list's sort, filters and display choices live in one `DropdownMenu`, opened by a funnel button beside its search field.
+
+```tsx
+<DropdownMenu>
+ <FilterMenuTrigger active={active} dataAttr="my-list-filter" />
+ <DropdownMenuContent align="start" className="min-w-64">
+ <FilterRadioSubMenu label="Sort by" options={sorts} value={sort} onChange={setSort} />
+ <DropdownMenuSeparator />
+ <FilterCheckboxSubMenu
+ label="Type"
+ allLabel="All types"
+ pluralNoun="types"
+ options={types}
+ selected={picked}
+ onChange={setPicked}
+ />
+ <FilterSearchSubMenu
+ label="Tags"
+ allLabel="Any tag"
+ pluralNoun="tags"
+ options={tags}
+ selected={tagged}
+ onChange={setTagged}
+ searchPlaceholder="Search tags"
+ emptyText="No tag matches"
+ />
+ <FilterClearItem active={active} onClear={clear} />
+ </DropdownMenuContent>
+</DropdownMenu>
+```
+
+Rules:
+
+- One choice → `FilterRadioSubMenu`. Several from a short list → `FilterCheckboxSubMenu`. Several from a long list → `FilterSearchSubMenu`.
+- An empty selection means all of them. Pass `defaultValue` on a radio filter so that a change takes the primary color. Leave it out on a row that isn't a filter, such as a sort.
+- `active` covers filters only. A sort, a display choice or the search text never lights the dot.
+
## DateTimePicker
```tsx
diff --git a/packages/quill/packages/components/src/data-table.stories.tsx b/packages/quill/packages/components/src/data-table.stories.tsx
index cf836e507f04..480ca5dba7b3 100644
--- a/packages/quill/packages/components/src/data-table.stories.tsx
+++ b/packages/quill/packages/components/src/data-table.stories.tsx
@@ -1,5 +1,5 @@
import type { Meta, StoryObj } from '@storybook/react'
-import { type ColumnDef } from '@tanstack/react-table'
+import { type ColumnDef, type ColumnSizingState, type SortingState } from '@tanstack/react-table'
import * as React from 'react'
import { Badge, Checkbox, Field, Label } from '@posthog/quill-primitives'
@@ -178,6 +178,62 @@ export const ClickableRows: Story = {
// Client-side pagination — pass `pageSize` to page the data and render a pager
// below the table. `pageSizeOptions` adds a rows-per-page selector.
+// The caller owns the sort, as a paged list sorted on the server must. The table only reports the clicks.
+export const ControlledSorting: Story = {
+ render: function Render() {
+ const [sorting, setSorting] = React.useState<SortingState>([{ id: 'name', desc: true }])
+ const [sort] = sorting
+ const sorted = [...people].sort((a, b) => (sort ? a.name.localeCompare(b.name) * (sort.desc ? -1 : 1) : 0))
+ return (
+ <DataTable
+ columns={[
+ { accessorKey: 'name', header: 'Name', sortDescFirst: true },
+ { accessorKey: 'email', header: 'Email', enableSorting: false },
+ ]}
+ data={sorted}
+ sorting={sorting}
+ onSortingChange={setSorting}
+ />
+ )
+ },
+} satisfies Story
+
+// Hover the header to see the column edges, and a header cell to see its handle. The columns fit their content until
+// the first drag, and a drag only ever changes the dragged column. A double click on an edge resets the column.
+export const ResizableColumns: Story = {
+ render: () => (
+ <DataTable
+ columns={[
+ { accessorKey: 'name', header: 'Name', minSize: 120, meta: { expand: true } },
+ { accessorKey: 'email', header: 'Email', maxSize: 400 },
+ { accessorKey: 'role', header: 'Role' },
+ { accessorKey: 'status', header: 'Status', enableResizing: false },
+ ]}
+ data={people}
+ fullWidth
+ resizableColumns
+ className="max-w-3xl rounded-md border border-[var(--border)]"
+ />
+ ),
+} satisfies Story
+
+// `columnSizing` restores saved widths from the first paint, and `onColumnSizingChange` is where to save them.
+export const SavedColumnWidths: Story = {
+ render: function Render() {
+ const [columnSizing, setColumnSizing] = React.useState<ColumnSizingState>({ email: 320 })
+ return (
+ <DataTable
+ columns={columns}
+ data={people}
+ resizableColumns
+ columnSizing={columnSizing}
+ onColumnSizingChange={setColumnSizing}
+ className="rounded-md border border-[var(--border)]"
+ />
+ )
+ },
+} satisfies Story
+
export const Paginated: Story = {
render: () => (
<DataTable
diff --git a/packages/quill/packages/components/src/data-table.test.tsx b/packages/quill/packages/components/src/data-table.test.tsx
index 383dd277f0f6..ac1917311463 100644
--- a/packages/quill/packages/components/src/data-table.test.tsx
+++ b/packages/quill/packages/components/src/data-table.test.tsx
@@ -1,5 +1,5 @@
import { type ColumnDef } from '@tanstack/react-table'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { DataTable } from './data-table'
@@ -57,4 +57,249 @@ describe('DataTable', () => {
expect(onPageChange).toHaveBeenCalledWith(1, 2)
})
+
+ describe('resizable columns', () => {
+ afterEach(cleanup)
+
+ const columns: ColumnDef<TestRow>[] = [
+ { accessorKey: 'name', header: 'Name', minSize: 100, maxSize: 110 },
+ { id: 'actions', header: '', enableResizing: false, cell: () => null },
+ ]
+ const resizer = (): HTMLElement => screen.getByLabelText('Resize Name column')
+ const columnWidth = (index: number): string =>
+ (screen.getByRole('table').querySelectorAll('col')[index] as HTMLElement).style.width
+
+ it('has no resizer until asked for', () => {
+ render(<DataTable columns={columns} data={data} />)
+
+ expect(screen.queryByRole('separator')).toBeNull()
+ })
+
+ it('leaves out a column that opts out', () => {
+ render(<DataTable columns={columns} data={data} resizableColumns />)
+
+ expect(screen.getAllByRole('separator')).toHaveLength(1)
+ })
+
+ it('keeps the content layout until the first resize', () => {
+ render(<DataTable columns={columns} data={data} resizableColumns />)
+ expect(screen.getByRole('table').getAttribute('data-layout')).toBeNull()
+
+ fireEvent.keyDown(resizer(), { key: 'ArrowRight' })
+
+ expect(screen.getByRole('table').getAttribute('data-layout')).toBe('fixed')
+ })
+
+ it.each([
+ ['grows', 104, 'ArrowRight', 110],
+ ['shrinks', 106, 'ArrowLeft', 100],
+ ['stops at the maximum', 110, 'ArrowRight', 110],
+ ['stops at the minimum', 100, 'ArrowLeft', 100],
+ ])('%s with the arrow keys', (_name, start, key, expected) => {
+ const onColumnSizingChange = jest.fn()
+ render(
+ <DataTable
+ columns={columns}
+ data={data}
+ resizableColumns
+ columnSizing={{ name: start }}
+ onColumnSizingChange={onColumnSizingChange}
+ />
+ )
+
+ fireEvent.keyDown(resizer(), { key })
+
+ expect(onColumnSizingChange).toHaveBeenCalledWith({ name: expected })
+ })
+
+ it('applies restored widths without a resize', () => {
+ render(<DataTable columns={columns} data={data} resizableColumns columnSizing={{ name: 105 }} />)
+
+ expect(screen.getByRole('table').getAttribute('data-layout')).toBe('fixed')
+ expect(columnWidth(0)).toBe('105px')
+ })
+
+ // pinned: rendering the rows on each move takes far longer than a frame in a large table.
+ describe('while dragging', () => {
+ beforeEach(() => {
+ jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({ width: 200 } as DOMRect)
+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
+ callback(0)
+ return 0
+ })
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ const drag = (grip: HTMLElement, moves: number[]): void => {
+ act(() => {
+ grip.dispatchEvent(new MouseEvent('pointerdown', { button: 0, clientX: 0, bubbles: true }))
+ })
+ for (const clientX of moves) {
+ act(() => {
+ grip.dispatchEvent(new MouseEvent('pointermove', { clientX, bubbles: true }))
+ })
+ }
+ act(() => {
+ grip.dispatchEvent(new MouseEvent('pointerup', { bubbles: true }))
+ })
+ }
+
+ it('never renders the rows, and reports the width once at the end', () => {
+ const renderCell = jest.fn(() => null)
+ const onColumnSizingChange = jest.fn()
+ const counted: ColumnDef<TestRow>[] = [
+ { accessorKey: 'name', header: 'Name', cell: renderCell },
+ { id: 'owner', header: 'Owner', cell: () => null },
+ ]
+ render(
+ <DataTable
+ columns={counted}
+ data={data}
+ fullWidth
+ resizableColumns
+ onColumnSizingChange={onColumnSizingChange}
+ />
+ )
+ renderCell.mockClear()
+
+ drag(screen.getByLabelText('Resize Name column'), [10, 20, 30])
+
+ expect(renderCell).not.toHaveBeenCalled()
+ expect(onColumnSizingChange).toHaveBeenCalledTimes(1)
+ expect(onColumnSizingChange).toHaveBeenCalledWith({ name: 230 })
+ expect(columnWidth(0)).toBe('230px')
+ })
+
+ it('moves the column in the DOM before the drag ends', () => {
+ const onColumnSizingChange = jest.fn()
+ render(
+ <DataTable
+ columns={columns}
+ data={data}
+ resizableColumns
+ columnSizing={{ name: 105 }}
+ onColumnSizingChange={onColumnSizingChange}
+ />
+ )
+ const grip = screen.getByLabelText('Resize Name column')
+
+ act(() => {
+ grip.dispatchEvent(new MouseEvent('pointerdown', { button: 0, clientX: 0, bubbles: true }))
+ })
+ act(() => {
+ grip.dispatchEvent(new MouseEvent('pointermove', { clientX: 2, bubbles: true }))
+ })
+
+ expect(columnWidth(0)).toBe('107px')
+ expect(onColumnSizingChange).not.toHaveBeenCalled()
+ })
+
+ it('keeps a drag from leaving a width behind that holds the other columns back', () => {
+ render(<DataTable columns={columns} data={data} resizableColumns columnSizing={{ name: 105 }} />)
+
+ drag(screen.getByLabelText('Resize Name column'), [2])
+
+ expect(screen.getByRole('table').style.minWidth).toBe('0')
+ })
+
+ it('leaves the layout alone on a click with no drag', () => {
+ render(<DataTable columns={columns} data={data} resizableColumns />)
+
+ drag(screen.getByLabelText('Resize Name column'), [])
+
+ expect(screen.getByRole('table').getAttribute('data-layout')).toBeNull()
+ })
+ })
+
+ // pinned: a resize changes the dragged column and no other. Never let another column absorb the difference.
+ describe('changes only the dragged column', () => {
+ const threeColumns: ColumnDef<TestRow>[] = [
+ { accessorKey: 'name', header: 'Name', meta: { expand: true } },
+ { id: 'owner', header: 'Owner', cell: () => null },
+ { id: 'created', header: 'Created', cell: () => null },
+ ]
+ const widths = (): Record<string, string> =>
+ Object.fromEntries(['Name', 'Owner', 'Created'].map((name, index) => [name, columnWidth(index)]))
+
+ beforeEach(() => {
+ jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({
+ width: 200,
+ } as DOMRect)
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it.each([
+ ['shrinks the expand column', 'Name', 'ArrowLeft', { Name: '184px', Owner: '200px', Created: '200px' }],
+ ['grows the expand column', 'Name', 'ArrowRight', { Name: '216px', Owner: '200px', Created: '200px' }],
+ ['shrinks a middle column', 'Owner', 'ArrowLeft', { Name: '200px', Owner: '184px', Created: '200px' }],
+ ['grows a middle column', 'Owner', 'ArrowRight', { Name: '200px', Owner: '216px', Created: '200px' }],
+ ])('%s', (_name, column, key, expected) => {
+ render(<DataTable columns={threeColumns} data={data} fullWidth resizableColumns />)
+
+ fireEvent.keyDown(screen.getByLabelText(`Resize ${column} column`), { key })
+
+ expect(widths()).toEqual(expected)
+ })
+
+ it('sets the table to the sum of its columns, so nothing has to give', () => {
+ render(<DataTable columns={threeColumns} data={data} resizableColumns />)
+
+ fireEvent.keyDown(screen.getByLabelText('Resize Owner column'), { key: 'ArrowLeft' })
+
+ expect(screen.getByRole('table').style.width).toBe('584px')
+ })
+
+ it('fills the space left in a full-width table with an empty column', () => {
+ render(<DataTable columns={threeColumns} data={data} fullWidth resizableColumns />)
+
+ fireEvent.keyDown(screen.getByLabelText('Resize Owner column'), { key: 'ArrowLeft' })
+
+ expect(screen.getByRole('table').style.minWidth).toBe('584px')
+ expect(screen.getAllByRole('presentation')).toHaveLength(2)
+ })
+ })
+
+ it('measures again when the set of columns changes', () => {
+ jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({ width: 200 } as DOMRect)
+ const { rerender } = render(<DataTable columns={columns} data={data} resizableColumns />)
+ fireEvent.keyDown(resizer(), { key: 'ArrowRight' })
+ expect(screen.getByRole('table').querySelectorAll('col')).toHaveLength(2)
+
+ rerender(
+ <DataTable
+ columns={[...columns, { id: 'added', header: 'Added', cell: () => null }]}
+ data={data}
+ resizableColumns
+ columnSizing={{ name: 105 }}
+ />
+ )
+
+ expect(screen.getByRole('table').querySelectorAll('col')).toHaveLength(3)
+ expect(columnWidth(2)).toBe('200px')
+ jest.restoreAllMocks()
+ })
+
+ it('removes a column from the widths on a double click', () => {
+ const onColumnSizingChange = jest.fn()
+ render(
+ <DataTable
+ columns={columns}
+ data={data}
+ resizableColumns
+ columnSizing={{ name: 105, other: 200 }}
+ onColumnSizingChange={onColumnSizingChange}
+ />
+ )
+
+ fireEvent.doubleClick(resizer())
+
+ expect(onColumnSizingChange).toHaveBeenCalledWith({ other: 200 })
+ })
+ })
})
diff --git a/packages/quill/packages/components/src/data-table.tsx b/packages/quill/packages/components/src/data-table.tsx
index 811099b00123..4765cd62e319 100644
--- a/packages/quill/packages/components/src/data-table.tsx
+++ b/packages/quill/packages/components/src/data-table.tsx
@@ -1,7 +1,11 @@
import {
type ColumnDef,
+ type ColumnSizingState,
type PaginationState,
+ type Row,
type RowData,
+ type Header,
+ type OnChangeFn,
type SortingState,
type Table as TanstackTable,
flexRender,
@@ -34,14 +38,18 @@ import {
SelectItem,
SelectTrigger,
SelectValue,
+ MIN_TABLE_COLUMN_WIDTH,
Table,
TableBody,
TableCell,
+ TableColumnResizer,
TableHead,
TableHeader,
TableRow,
} from '@posthog/quill-primitives'
+import { useColumnWidths } from './use-column-widths'
+
// Per-column extras read off `columnDef.meta`. `align` drives intra-cell
// alignment on both the header and its body cells; `expand` makes the column
// soak up leftover width in a `fullWidth` table.
@@ -50,6 +58,8 @@ declare module '@tanstack/react-table' {
interface ColumnMeta<TData extends RowData, TValue> {
align?: 'left' | 'center' | 'right'
expand?: boolean
+ /** `data-attr` for the column's sort button. */
+ sortDataAttr?: string
}
}
@@ -106,6 +116,26 @@ export interface DataTableProps<TData, TValue> {
className?: string
/** Sticky header mode, forwarded to the Table primitive. `'page'` sticks to document scroll. */
stickyHeader?: boolean | 'page'
+ /** Ref to the scrolling viewport, forwarded to the Table primitive. */
+ viewportRef?: React.Ref<HTMLDivElement>
+ /** Ref to a marker after the table, inside the viewport. Observe it to load more rows near the end. */
+ viewportEndRef?: React.Ref<HTMLDivElement>
+ /**
+ * Controls the sort. The rows then stay in the order of `data`, so the caller must sort them, for example on the
+ * server. Without this prop, the table sorts its rows on the client.
+ */
+ sorting?: SortingState
+ /** Called with the next sort when the user clicks a sortable header. */
+ onSortingChange?: (sorting: SortingState) => void
+ /**
+ * Lets the user drag the edge of a column to resize it, with the arrow keys as well. Columns fit their content until
+ * the first resize. Use `minSize` and `maxSize` on a column to bound it, and `enableResizing: false` to opt it out.
+ */
+ resizableColumns?: boolean
+ /** Controls the widths of the resized columns, in pixels by column id. Pass a saved value to restore them. */
+ columnSizing?: ColumnSizingState
+ /** Called with the next widths when a resize ends. A double click on an edge removes that column's width. */
+ onColumnSizingChange?: (columnSizing: ColumnSizingState) => void
/**
* Stretch the table to fill its container (forwarded to the Table primitive).
* Mark a column with `meta: { expand: true }` to choose which one absorbs the
@@ -237,13 +267,173 @@ function DataTablePagination<TData>({
)
}
+// State a caller may control: its value wins when given, and either way the caller hears about each change.
+function useControllable<T>(
+ controlled: T | undefined,
+ onChange: ((next: T) => void) | undefined,
+ initial: T
+): [T, OnChangeFn<T>] {
+ const [internal, setInternal] = React.useState<T>(initial)
+ const value = controlled ?? internal
+ return [
+ value,
+ (updater) => {
+ const next = typeof updater === 'function' ? (updater as (old: T) => T)(value) : updater
+ setInternal(next)
+ onChange?.(next)
+ },
+ ]
+}
+
+function DataTableHead<TData>({
+ header,
+ resizable,
+ width,
+ onResizeStart,
+}: {
+ header: Header<TData, unknown>
+ resizable: boolean
+ width: number | undefined
+ onResizeStart: () => void
+}): React.ReactElement {
+ const { column, isPlaceholder } = header
+ const sorted = column.getIsSorted()
+ const { align, expand, sortDataAttr } = column.columnDef.meta ?? {}
+ const label = isPlaceholder ? null : flexRender(column.columnDef.header, header.getContext())
+ const title = column.columnDef.header
+ return (
+ <TableHead
+ colSpan={header.colSpan}
+ align={align}
+ expand={expand}
+ aria-sort={sorted ? ARIA_SORT[sorted] : undefined}
+ // While the columns fit their content, this is what holds an expand column at its minimum.
+ style={expand && resizable ? { minWidth: column.columnDef.minSize } : undefined}
+ >
+ {column.getCanSort() && !isPlaceholder ? (
+ <Button
+ size="sm"
+ // The Button's built-in selected styling (fill-selected, with
+ // hover preserved via its own :not(:hover) rule) marks the
+ // active sort. Real semantics live in aria-sort on the <th>.
+ aria-selected={sorted ? true : undefined}
+ data-attr={sortDataAttr}
+ className={cn('gap-1.5', sorted && 'text-foreground', !sorted && 'hover:bg-fill-hover/50')}
+ onClick={column.getToggleSortingHandler()}
+ >
+ {label}
+ {sorted === 'asc' ? (
+ <ArrowUp className="size-3" />
+ ) : sorted === 'desc' ? (
+ <ArrowDown className="size-3" />
+ ) : (
+ <ChevronsUpDown className="size-3 opacity-50" />
+ )}
+ </Button>
+ ) : (
+ label
+ )}
+ {resizable ? (
+ <TableColumnResizer
+ value={width}
+ min={column.columnDef.minSize}
+ max={column.columnDef.maxSize}
+ aria-label={typeof title === 'string' ? `Resize ${title} column` : undefined}
+ onResizeStart={onResizeStart}
+ onValueCommitted={(next) =>
+ header.getContext().table.setColumnSizing((sizes) => ({ ...sizes, [column.id]: next }))
+ }
+ onReset={() => column.resetSize()}
+ />
+ ) : null}
+ </TableHead>
+ )
+}
+
+// Memoized so that a resize, which ends by setting a width on the table, does not render every row again. For the same
+// reason, a caller with its own state should keep `columns`, `onRowClick` and `empty` stable between renders.
+function DataTableBodyInner<TData, TValue>({
+ rows,
+ columns,
+ filler,
+ onRowClick,
+ empty,
+}: {
+ rows: Row<TData>[]
+ columns: ColumnDef<TData, TValue>[]
+ filler: boolean
+ onRowClick?: (row: TData) => void
+ empty: React.ReactNode
+}): React.ReactElement {
+ return (
+ <TableBody>
+ {rows.length ? (
+ rows.map((row) => (
+ <TableRow
+ key={row.id}
+ data-state={row.getIsSelected() ? 'selected' : undefined}
+ className={
+ onRowClick
+ ? 'cursor-pointer focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring'
+ : undefined
+ }
+ tabIndex={onRowClick ? 0 : undefined}
+ onClick={
+ onRowClick
+ ? (event) => {
+ if (!shouldIgnoreRowClick(event.target, event.currentTarget)) {
+ onRowClick(row.original)
+ }
+ }
+ : undefined
+ }
+ onKeyDown={
+ onRowClick
+ ? (event) => {
+ if (
+ event.target === event.currentTarget &&
+ (event.key === 'Enter' || event.key === ' ')
+ ) {
+ event.preventDefault()
+ onRowClick(row.original)
+ }
+ }
+ : undefined
+ }
+ >
+ {row.getVisibleCells().map((cell) => (
+ <TableCell
+ key={cell.id}
+ align={cell.column.columnDef.meta?.align}
+ expand={cell.column.columnDef.meta?.expand}
+ >
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ ))}
+ {filler ? <TableCell filler /> : null}
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell colSpan={columns.length + (filler ? 1 : 0)} className="p-2 hover:bg-transparent">
+ {empty}
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ )
+}
+
+const DataTableBody = React.memo(DataTableBodyInner) as typeof DataTableBodyInner
+
/**
* Headless TanStack Table wired onto the quill Table primitive — client-side
* sorting out of the box (sortable columns render a sort button + indicator and
* set `aria-sort`), selection reflected via the row's `data-state`, optional
* pagination, and an empty state. Pass `enableSorting: false` on a column to opt
- * it out, `meta: { align }` to align a column's header and cells, or
- * `fullWidth` + `meta: { expand: true }` to stretch one column to fill.
+ * it out, `meta: { align }` to align a column's header and cells,
+ * `fullWidth` + `meta: { expand: true }` to stretch one column to fill, or
+ * `resizableColumns` to let the user drag a column's edge.
*/
function DataTable<TData, TValue>({
columns,
@@ -251,7 +441,14 @@ function DataTable<TData, TValue>({
onRowClick,
className,
stickyHeader,
- fullWidth,
+ viewportRef,
+ viewportEndRef,
+ sorting: controlledSorting,
+ onSortingChange,
+ resizableColumns = false,
+ columnSizing: controlledColumnSizing,
+ onColumnSizingChange,
+ fullWidth = false,
size,
empty = DEFAULT_EMPTY,
pageSize,
@@ -259,7 +456,12 @@ function DataTable<TData, TValue>({
onPageChange,
}: DataTableProps<TData, TValue>): React.ReactElement {
const paginated = pageSize != null
- const [sorting, setSorting] = React.useState<SortingState>([])
+ const [sorting, setSorting] = useControllable<SortingState>(controlledSorting, onSortingChange, [])
+ const [columnSizing, setColumnSizing] = useControllable<ColumnSizingState>(
+ controlledColumnSizing,
+ onColumnSizingChange,
+ {}
+ )
const [pagination, setPagination] = React.useState<PaginationState>({ pageIndex: 0, pageSize: pageSize ?? 10 })
// Keep the page size in sync when the prop changes at runtime — reset to the
// first page so the new size applies from a consistent offset.
@@ -271,120 +473,61 @@ function DataTable<TData, TValue>({
const table = useReactTable({
data,
columns,
- state: { sorting, ...(paginated ? { pagination } : {}) },
+ enableColumnResizing: resizableColumns,
+ defaultColumn: { minSize: MIN_TABLE_COLUMN_WIDTH, maxSize: Infinity },
+ state: { sorting, columnSizing, ...(paginated ? { pagination } : {}) },
+ onColumnSizingChange: setColumnSizing,
+ manualSorting: controlledSorting !== undefined,
+ // A list sorted on the server always has an order, so its headers have no "off" state.
+ enableSortingRemoval: controlledSorting === undefined,
onSortingChange: setSorting,
...(paginated ? { onPaginationChange: setPagination } : {}),
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
...(paginated ? { getPaginationRowModel: getPaginationRowModel() } : {}),
})
- const rows = table.getRowModel().rows
+ const tableRef = React.useRef<HTMLTableElement>(null)
+ const { columnWidths, columnWidth, fixColumnWidths } = useColumnWidths(table, tableRef, resizableColumns)
+ // A resize changes the dragged column and no other, so once widths are fixed no column absorbs the difference, not
+ // even an `expand` one. In a full-width table an empty column fills whatever space the others leave.
+ const hasFiller = resizableColumns && fullWidth
+ const headerGroups = table.getHeaderGroups()
const tableElement = (
- <Table className={className} stickyHeader={stickyHeader} fullWidth={fullWidth} size={size}>
+ <Table
+ ref={tableRef}
+ columnWidths={columnWidths}
+ className={className}
+ stickyHeader={stickyHeader}
+ viewportRef={viewportRef}
+ viewportEndRef={viewportEndRef}
+ fullWidth={fullWidth}
+ size={size}
+ >
<TableHeader>
- {table.getHeaderGroups().map((headerGroup) => (
+ {headerGroups.map((headerGroup, index) => (
<TableRow key={headerGroup.id}>
- {headerGroup.headers.map((header) => {
- const sorted = header.column.getIsSorted()
- const { align, expand } = header.column.columnDef.meta ?? {}
- const label = header.isPlaceholder
- ? null
- : flexRender(header.column.columnDef.header, header.getContext())
- return (
- <TableHead
- key={header.id}
- colSpan={header.colSpan}
- align={align}
- expand={expand}
- aria-sort={sorted ? ARIA_SORT[sorted] : undefined}
- >
- {header.column.getCanSort() && !header.isPlaceholder ? (
- <Button
- size="sm"
- // The Button's built-in selected styling (fill-selected, with
- // hover preserved via its own :not(:hover) rule) marks the
- // active sort. Real semantics live in aria-sort on the <th>.
- aria-selected={sorted ? true : undefined}
- className={cn(
- 'gap-1.5',
- sorted && 'text-foreground',
- !sorted && 'hover:bg-fill-hover/50'
- )}
- onClick={header.column.getToggleSortingHandler()}
- >
- {label}
- {sorted === 'asc' ? (
- <ArrowUp className="size-3" />
- ) : sorted === 'desc' ? (
- <ArrowDown className="size-3" />
- ) : (
- <ChevronsUpDown className="size-3 opacity-50" />
- )}
- </Button>
- ) : (
- label
- )}
- </TableHead>
- )
- })}
+ {headerGroup.headers.map((header) => (
+ <DataTableHead
+ key={header.id}
+ header={header}
+ // Only the last row of headers lines up one to one with the columns.
+ resizable={index === headerGroups.length - 1 && header.column.getCanResize()}
+ width={columnWidth(header.column.id)}
+ onResizeStart={fixColumnWidths}
+ />
+ ))}
+ {hasFiller ? <TableHead filler /> : null}
</TableRow>
))}
</TableHeader>
- <TableBody>
- {rows.length ? (
- rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() ? 'selected' : undefined}
- className={
- onRowClick
- ? 'cursor-pointer focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring'
- : undefined
- }
- tabIndex={onRowClick ? 0 : undefined}
- onClick={
- onRowClick
- ? (event) => {
- if (!shouldIgnoreRowClick(event.target, event.currentTarget)) {
- onRowClick(row.original)
- }
- }
- : undefined
- }
- onKeyDown={
- onRowClick
- ? (event) => {
- if (
- event.target === event.currentTarget &&
- (event.key === 'Enter' || event.key === ' ')
- ) {
- event.preventDefault()
- onRowClick(row.original)
- }
- }
- : undefined
- }
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell
- key={cell.id}
- align={cell.column.columnDef.meta?.align}
- expand={cell.column.columnDef.meta?.expand}
- >
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="p-2 hover:bg-transparent">
- {empty}
- </TableCell>
- </TableRow>
- )}
- </TableBody>
+ <DataTableBody
+ rows={table.getRowModel().rows}
+ columns={columns}
+ filler={hasFiller}
+ onRowClick={onRowClick}
+ empty={empty}
+ />
</Table>
)
diff --git a/packages/quill/packages/components/src/filter-menu.stories.tsx b/packages/quill/packages/components/src/filter-menu.stories.tsx
new file mode 100644
index 000000000000..363b5bd4a1f5
--- /dev/null
+++ b/packages/quill/packages/components/src/filter-menu.stories.tsx
@@ -0,0 +1,75 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import * as React from 'react'
+
+import { DropdownMenu, DropdownMenuContent, DropdownMenuSeparator } from '@posthog/quill-primitives'
+
+import {
+ FilterCheckboxSubMenu,
+ FilterClearItem,
+ FilterMenuTrigger,
+ FilterRadioSubMenu,
+ FilterSearchSubMenu,
+} from './filter-menu'
+
+const meta = {
+ title: 'Components/FilterMenu',
+ tags: ['autodocs'],
+} satisfies Meta
+
+export default meta
+type Story = StoryObj<typeof meta>
+
+const SORTS = [
+ { value: 'created', label: 'Created' },
+ { value: 'viewed', label: 'Last viewed' },
+]
+const TYPES = [
+ { value: 'dashboard', label: 'Dashboards' },
+ { value: 'insight', label: 'Insights' },
+ { value: 'notebook', label: 'Notebooks' },
+]
+const TAGS = ['finance', 'growth', 'onboarding', 'weekly'].map((tag) => ({ value: tag, label: tag }))
+
+// The list's whole set of controls: sort first, then a row per filter, with Clear filters last. Sort never lights the dot.
+export const Default: Story = {
+ render: function Render() {
+ const [sort, setSort] = React.useState('created')
+ const [types, setTypes] = React.useState<string[]>(['insight'])
+ const [tags, setTags] = React.useState<string[]>([])
+ const active = types.length > 0 || tags.length > 0
+ return (
+ <DropdownMenu>
+ <FilterMenuTrigger active={active} />
+ <DropdownMenuContent align="start" className="min-w-64">
+ <FilterRadioSubMenu label="Sort by" options={SORTS} value={sort} onChange={setSort} />
+ <DropdownMenuSeparator />
+ <FilterCheckboxSubMenu
+ label="Type"
+ allLabel="All types"
+ pluralNoun="types"
+ options={TYPES}
+ selected={types}
+ onChange={setTypes}
+ />
+ <FilterSearchSubMenu
+ label="Tags"
+ allLabel="Any tag"
+ pluralNoun="tags"
+ options={TAGS}
+ selected={tags}
+ onChange={setTags}
+ searchPlaceholder="Search tags"
+ emptyText="No tag matches"
+ />
+ <FilterClearItem
+ active={active}
+ onClear={() => {
+ setTypes([])
+ setTags([])
+ }}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ },
+}
diff --git a/packages/quill/packages/components/src/filter-menu.test.tsx b/packages/quill/packages/components/src/filter-menu.test.tsx
new file mode 100644
index 000000000000..35e9c5fa4b14
--- /dev/null
+++ b/packages/quill/packages/components/src/filter-menu.test.tsx
@@ -0,0 +1,111 @@
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@posthog/quill-primitives'
+
+import { FilterSearchSubMenu } from './filter-menu'
+
+describe('FilterSearchSubMenu', () => {
+ afterEach(cleanup)
+
+ it('keeps the selection when Escape dismisses the submenu', async () => {
+ const onChange = jest.fn()
+ render(
+ <DropdownMenu defaultOpen>
+ <DropdownMenuTrigger>Filters</DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <FilterSearchSubMenu
+ label="Tags"
+ allLabel="Any tag"
+ pluralNoun="tags"
+ options={[
+ { value: 'growth', label: 'growth' },
+ { value: 'revenue', label: 'revenue' },
+ ]}
+ selected={['growth']}
+ onChange={onChange}
+ searchPlaceholder="Search tags"
+ emptyText="No tag matches"
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+
+ await act(async () => {
+ fireEvent.click(await screen.findByText('Tags'))
+ })
+ const input = await screen.findByLabelText('Search tags')
+
+ fireEvent.keyDown(input, { key: 'Escape' })
+
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ it('calls onOpen when the submenu opens', async () => {
+ const onOpen = jest.fn()
+ render(
+ <DropdownMenu defaultOpen>
+ <DropdownMenuTrigger>Filters</DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <FilterSearchSubMenu
+ label="Tags"
+ allLabel="Any tag"
+ pluralNoun="tags"
+ options={[]}
+ selected={[]}
+ onChange={jest.fn()}
+ onOpen={onOpen}
+ searchPlaceholder="Search tags"
+ emptyText="No tag matches"
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ const row = await screen.findByText('Tags')
+ expect(onOpen).not.toHaveBeenCalled()
+
+ await act(async () => {
+ fireEvent.click(row)
+ })
+
+ expect(onOpen).toHaveBeenCalledTimes(1)
+ })
+
+ it('caps the rows until a search narrows them', async () => {
+ render(
+ <DropdownMenu defaultOpen>
+ <DropdownMenuTrigger>Filters</DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <FilterSearchSubMenu
+ label="Tags"
+ allLabel="Any tag"
+ pluralNoun="tags"
+ options={Array.from({ length: 300 }, (_, index) => ({
+ value: `tag-${index}`,
+ label: `tag-${index}`,
+ }))}
+ selected={[]}
+ onChange={jest.fn()}
+ searchPlaceholder="Search tags"
+ emptyText="No tag matches"
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+
+ await act(async () => {
+ fireEvent.click(await screen.findByText('Tags'))
+ })
+ const input = await screen.findByLabelText('Search tags')
+
+ expect(screen.getAllByRole('option')).toHaveLength(200)
+ expect(screen.getByText('Keep typing to see more')).toBeTruthy()
+ expect(screen.queryByText('tag-299')).toBeNull()
+
+ await act(async () => {
+ fireEvent.change(input, { target: { value: 'tag-299' } })
+ })
+
+ expect(screen.getByText('tag-299')).toBeTruthy()
+ expect(screen.queryByText('Keep typing to see more')).toBeNull()
+ })
+})
diff --git a/packages/quill/packages/components/src/filter-menu.tsx b/packages/quill/packages/components/src/filter-menu.tsx
new file mode 100644
index 000000000000..1aaa6e4f900b
--- /dev/null
+++ b/packages/quill/packages/components/src/filter-menu.tsx
@@ -0,0 +1,351 @@
+import { ListFilter } from 'lucide-react'
+import * as React from 'react'
+
+import {
+ Button,
+ cn,
+ Combobox,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ DropdownMenuCheckboxItem,
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ useComboboxFilteredItems,
+} from '@posthog/quill-primitives'
+
+export interface FilterOption<Value extends string = string> {
+ value: Value
+ label: string
+ icon?: React.ReactNode
+ /** A muted note after the label, such as "(you)". */
+ hint?: string
+}
+
+/** What a filter row shows for several values: the default, up to two labels, or a count, such as "3 tags". */
+export function filterSummary(labels: string[], allLabel: string, pluralNoun: string): string {
+ if (labels.length === 0) {
+ return allLabel
+ }
+ return labels.length > 2 ? `${labels.length} ${pluralNoun}` : labels.join(', ')
+}
+
+/** The funnel button that opens a list's filter menu. A dot says a filter narrows the list. */
+export function FilterMenuTrigger({ active, dataAttr }: { active: boolean; dataAttr?: string }): React.ReactElement {
+ const label = active ? 'Filters on' : 'Filter'
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ delay={0}
+ render={
+ <DropdownMenuTrigger
+ render={
+ <Button
+ size="icon"
+ aria-label={label}
+ indicator={active ? 'default' : undefined}
+ className={cn('text-muted-foreground', active && 'bg-fill-selected text-foreground')}
+ data-attr={dataAttr}
+ />
+ }
+ />
+ }
+ >
+ <ListFilter />
+ </TooltipTrigger>
+ <TooltipContent>{label}</TooltipContent>
+ </Tooltip>
+ )
+}
+
+interface FilterSubMenuRowProps {
+ label: string
+ /** The choice in force, shown beside the label. */
+ value: string
+ /** The choice differs from the default, so the value takes the primary color. */
+ active?: boolean
+ dataAttr?: string
+}
+
+function FilterSubMenuRow({ label, value, active = false, dataAttr }: FilterSubMenuRowProps): React.ReactElement {
+ return (
+ <DropdownMenuSubTrigger data-attr={dataAttr}>
+ <span>{label}</span>
+ <span
+ title={value}
+ className={cn('flex-1 truncate pl-4 text-right', active ? 'text-primary' : 'text-muted-foreground')}
+ >
+ {value}
+ </span>
+ </DropdownMenuSubTrigger>
+ )
+}
+
+/** One filter in the menu: its label, the choice in force, and a submenu of the options. */
+export function FilterSubMenu({
+ children,
+ ...row
+}: FilterSubMenuRowProps & { children: React.ReactNode }): React.ReactElement {
+ return (
+ <DropdownMenuSub>
+ <FilterSubMenuRow {...row} />
+ <DropdownMenuSubContent>{children}</DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )
+}
+
+/** A filter with one choice. Leave out `defaultValue` for a row that never counts as a filter, such as a sort. */
+export function FilterRadioSubMenu<Value extends string>({
+ label,
+ options,
+ value,
+ defaultValue,
+ onChange,
+ dataAttr,
+ optionDataAttr,
+}: {
+ label: string
+ options: readonly FilterOption<Value>[]
+ value: Value
+ defaultValue?: Value
+ onChange: (value: Value) => void
+ dataAttr?: string
+ optionDataAttr?: string
+}): React.ReactElement {
+ return (
+ <FilterSubMenu
+ label={label}
+ value={options.find((option) => option.value === value)?.label ?? ''}
+ active={defaultValue !== undefined && value !== defaultValue}
+ dataAttr={dataAttr}
+ >
+ <DropdownMenuRadioGroup value={value} onValueChange={(next) => onChange(next as Value)}>
+ {options.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value} data-attr={optionDataAttr}>
+ {option.icon}
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </FilterSubMenu>
+ )
+}
+
+/** A filter with several choices from a short list. An empty selection means all of them. */
+export function FilterCheckboxSubMenu<Value extends string>({
+ label,
+ allLabel,
+ allIcon,
+ pluralNoun,
+ options,
+ selected,
+ onChange,
+ dataAttr,
+ optionDataAttr,
+}: {
+ label: string
+ allLabel: string
+ allIcon?: React.ReactNode
+ pluralNoun: string
+ options: readonly FilterOption<Value>[]
+ selected: readonly Value[]
+ onChange: (selected: Value[]) => void
+ dataAttr?: string
+ optionDataAttr?: string
+}): React.ReactElement {
+ const labels = options.filter((option) => selected.includes(option.value)).map((option) => option.label)
+ return (
+ <FilterSubMenu
+ label={label}
+ value={filterSummary(labels, allLabel, pluralNoun)}
+ active={selected.length > 0}
+ dataAttr={dataAttr}
+ >
+ <DropdownMenuCheckboxItem
+ checked={selected.length === 0}
+ closeOnClick={false}
+ onCheckedChange={() => onChange([])}
+ data-attr={optionDataAttr}
+ >
+ {allIcon}
+ {allLabel}
+ </DropdownMenuCheckboxItem>
+ <DropdownMenuSeparator />
+ {options.map((option) => (
+ <DropdownMenuCheckboxItem
+ key={option.value}
+ checked={selected.includes(option.value)}
+ closeOnClick={false}
+ onCheckedChange={(checked) =>
+ onChange(
+ checked ? [...selected, option.value] : selected.filter((value) => value !== option.value)
+ )
+ }
+ data-attr={optionDataAttr}
+ >
+ {option.icon}
+ {option.label}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </FilterSubMenu>
+ )
+}
+
+// The search field and rows sit in the menu's popup, whose own key and click handling would close the menu or steal them.
+const stopPropagation = (event: React.SyntheticEvent): void => event.stopPropagation()
+
+type SearchOption = FilterOption<string> | { value: null; label: string; icon?: undefined; hint?: undefined }
+
+// Each row is a mounted component, and opening the menu slows past a few hundred of them.
+const SEARCH_OPTION_LIMIT = 200
+
+function SearchLimitHint(): React.ReactElement | null {
+ const reachedLimit = useComboboxFilteredItems().length >= SEARCH_OPTION_LIMIT
+ return reachedLimit ? <div className="p-2 text-xs text-muted-foreground">Keep typing to see more</div> : null
+}
+
+/** A filter with several choices from a long list, such as people or tags. An empty selection means all of them. */
+export function FilterSearchSubMenu({
+ label,
+ allLabel,
+ pluralNoun,
+ options,
+ selected,
+ onChange,
+ loading,
+ searchPlaceholder,
+ emptyText,
+ onOpen,
+ dataAttr,
+ optionDataAttr,
+}: {
+ label: string
+ allLabel: string
+ pluralNoun: string
+ options: readonly FilterOption[]
+ selected: readonly string[]
+ onChange: (selected: string[]) => void
+ loading?: boolean
+ searchPlaceholder: string
+ emptyText: string
+ /** Called when the submenu opens, to load its options only once someone wants them. */
+ onOpen?: () => void
+ dataAttr?: string
+ optionDataAttr?: string
+}): React.ReactElement {
+ const allOption: SearchOption = { value: null, label: allLabel }
+ // Values the options do not know yet, such as a tag from the URL before the list loads, still count as picked.
+ const unknown = selected.filter((value) => !options.some((option) => option.value === value))
+ const known: FilterOption[] = [...options, ...unknown.map((value) => ({ value, label: value }))]
+ const picked = known.filter((option) => selected.includes(option.value))
+ return (
+ <DropdownMenuSub onOpenChange={(open) => open && onOpen?.()}>
+ <FilterSubMenuRow
+ label={label}
+ value={filterSummary(
+ picked.map((option) => option.label),
+ allLabel,
+ pluralNoun
+ )}
+ active={selected.length > 0}
+ dataAttr={dataAttr}
+ />
+ {/* Flush because the list scrolls on its own, under a search field that stays put. */}
+ <DropdownMenuSubContent flush className="w-64">
+ <Combobox<SearchOption, true>
+ multiple
+ // The submenu is the popup, so the list is always open and a pick resets the search.
+ inline
+ autoHighlight
+ limit={SEARCH_OPTION_LIMIT}
+ items={[allOption, ...known]}
+ itemToStringValue={(option) => option.label}
+ isItemEqualToValue={(option, other) => option.value === other.value}
+ value={picked.length > 0 ? picked : [allOption]}
+ onValueChange={(next, { reason }) => {
+ // The list counts as closed while inline, so Base UI treats Escape as a request to clear.
+ if (reason === 'escape-key') {
+ return
+ }
+ // While nothing is picked, "all" is the ticked row, so ticking a value also carries it along.
+ const allTicked = next.some((option) => option.value === null)
+ onChange(
+ allTicked && selected.length > 0
+ ? []
+ : next.flatMap((option) => (option.value === null ? [] : [option.value]))
+ )
+ }}
+ >
+ <div className="p-1">
+ <ComboboxInput
+ autoFocus
+ showTrigger={false}
+ placeholder={searchPlaceholder}
+ aria-label={searchPlaceholder}
+ data-compact=""
+ onClick={stopPropagation}
+ onKeyDown={(event) => {
+ if (event.key !== 'Escape') {
+ event.stopPropagation()
+ }
+ }}
+ />
+ </div>
+ <ComboboxEmpty>{emptyText}</ComboboxEmpty>
+ <ComboboxList>
+ {(option: SearchOption) => (
+ <ComboboxItem
+ key={option.value ?? 'all'}
+ value={option}
+ title={option.label}
+ onClick={stopPropagation}
+ data-attr={optionDataAttr}
+ >
+ {option.icon}
+ <span className="truncate">{option.label}</span>
+ {option.hint && (
+ <span className="ml-auto text-xs text-muted-foreground">{option.hint}</span>
+ )}
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+ <SearchLimitHint />
+ {loading && <div className="p-2 text-xs text-muted-foreground">Loading…</div>}
+ </Combobox>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )
+}
+
+/** The last row of the menu, after a separator. It only shows while a filter is on. */
+export function FilterClearItem({
+ active,
+ onClear,
+ dataAttr,
+}: {
+ active: boolean
+ onClear: () => void
+ dataAttr?: string
+}): React.ReactElement | null {
+ if (!active) {
+ return null
+ }
+ return (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={onClear} data-attr={dataAttr}>
+ Clear filters
+ </DropdownMenuItem>
+ </>
+ )
+}
diff --git a/packages/quill/packages/components/src/index.ts b/packages/quill/packages/components/src/index.ts
index 200f11f7de99..af086a17b066 100644
--- a/packages/quill/packages/components/src/index.ts
+++ b/packages/quill/packages/components/src/index.ts
@@ -9,6 +9,16 @@
// in every app.
export { DataTable, type DataTableProps } from './data-table'
+export {
+ FilterCheckboxSubMenu,
+ FilterClearItem,
+ FilterMenuTrigger,
+ type FilterOption,
+ FilterRadioSubMenu,
+ FilterSearchSubMenu,
+ FilterSubMenu,
+ filterSummary,
+} from './filter-menu'
export { DateTimePicker, type DateTimePickerProps, type DateTimeValue, type DateFormatOrder } from './date-time-picker'
export { DatePicker, type DatePickerProps } from './date-picker'
export { quickRanges, CUSTOM_RANGE, type DateTimeRange, type DateTimeRangeName } from './date-time-ranges'
diff --git a/packages/quill/packages/components/src/use-column-widths.ts b/packages/quill/packages/components/src/use-column-widths.ts
new file mode 100644
index 000000000000..34b6055e33d6
--- /dev/null
+++ b/packages/quill/packages/components/src/use-column-widths.ts
@@ -0,0 +1,60 @@
+import { type ColumnSizingState, type Table } from '@tanstack/react-table'
+import * as React from 'react'
+
+/**
+ * The widths for a `Table`'s `columnWidths`. The columns fit their content until the first resize, or until there are
+ * saved widths to apply. Then every column is fixed, each at its saved width or else at the width it had on screen, so
+ * that a resize changes the dragged column and no other. A change in the set of columns measures them again.
+ */
+export function useColumnWidths<TData>(
+ table: Table<TData>,
+ tableRef: React.RefObject<HTMLTableElement | null>,
+ enabled: boolean
+): {
+ columnWidths: 'content' | number[] | undefined
+ /** Fixes the columns at their widths on screen, if they still fit their content. */
+ fixColumnWidths: () => void
+ columnWidth: (columnId: string) => number | undefined
+} {
+ const leafColumns = table.getVisibleLeafColumns()
+ const columnKey = leafColumns.map((column) => column.id).join()
+ const [measured, setMeasured] = React.useState<{ columnKey: string; widths: ColumnSizingState } | null>(null)
+ const measuredWidths = measured?.columnKey === columnKey ? measured.widths : null
+
+ const fixColumnWidths = (): void => {
+ if (measuredWidths) {
+ return
+ }
+ const heads = tableRef.current?.querySelectorAll('thead tr:last-child th')
+ setMeasured({
+ columnKey,
+ widths: Object.fromEntries(
+ leafColumns.map((column, index) => [column.id, heads?.[index]?.getBoundingClientRect().width ?? 0])
+ ),
+ })
+ }
+
+ const sizing = table.getState().columnSizing
+ const hasRows = table.getRowModel().rows.length > 0
+ const hasSavedWidths = Object.keys(sizing).length > 0
+ // Before paint, so that saved widths apply from the first frame. It waits for rows to measure the others against.
+ React.useLayoutEffect(() => {
+ if (enabled && hasRows && hasSavedWidths) {
+ fixColumnWidths()
+ }
+ })
+
+ if (!enabled) {
+ return { columnWidths: undefined, fixColumnWidths, columnWidth: () => undefined }
+ }
+ if (!measuredWidths) {
+ return { columnWidths: 'content', fixColumnWidths, columnWidth: () => undefined }
+ }
+ const widthOf = (id: string): number =>
+ id in sizing ? (table.getColumn(id)?.getSize() ?? 0) : (measuredWidths[id] ?? 0)
+ return {
+ columnWidths: leafColumns.map((column) => widthOf(column.id)),
+ fixColumnWidths,
+ columnWidth: widthOf,
+ }
+}
diff --git a/packages/quill/packages/primitives/AGENTS.md b/packages/quill/packages/primitives/AGENTS.md
index 1a426d7e7372..43a256db1f97 100644
--- a/packages/quill/packages/primitives/AGENTS.md
+++ b/packages/quill/packages/primitives/AGENTS.md
@@ -135,22 +135,22 @@ Don't hand-roll `<p className="text-xs text-muted-foreground">` when `<Text size
## Component Catalog
-| Component | Variants | Sizes | Notes |
-| ------------ | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Button | default, primary, secondary, outline, destructive, destructive-outline, link, link-muted | default, xs, sm, lg, icon, icon-xs, icon-sm, icon-lg, row, inline | `loading` overlays a centered spinner and disables the button (width stays stable). `row` is the full-width, regular-weight list row that menu, combobox and autocomplete items render. `inline` is a link inside a sentence: no height or padding, and it inherits the sentence's font size and line height. `elevated` adds heavy CTA chrome — see Elevated button. `tooltip` adds a hover and focus tooltip. `indicator="default"` puts a dot on the top-right corner for something waiting behind the button (`"warning"` or `"destructive"` for a problem); say what it means in the `aria-label`, and set `--quill-button-indicator-ring` when the button sits off the app background. `disabledReason` disables the button and shows the reason in that tooltip. A `render` that carries a link destination (`to`, `href`) or is a non-button element turns off `nativeButton` by itself; a disabled button drops that destination. |
-| Badge | default, info, destructive, warning, success, completed | — | Semantic status |
-| Toggle | default, outline | default, sm, lg, icon | `ToggleGroupItem` takes `disabledReason`, which disables the item and shows the reason in a tooltip on hover. Arrow keys in a `ToggleGroup` skip disabled items, so the reason is hover-only. |
-| Chip | outline | sm | Use with ChipClose |
-| Separator | — | — | orientation: horizontal/vertical |
-| Spinner | — | — | SVG, accepts svg props |
-| Skeleton | — | — | Pulsing placeholder div |
-| SkeletonText | — | — | lines, minWidth, maxWidth |
-| Progress | — | — | value: 0-100 |
-| Slider | — | — | value, min, max |
-| Avatar | — | lg, default, sm, xs | Compose `Avatar > AvatarImage + AvatarFallback`; image errors fall back to initials/icon |
-| ChatGlobe | — | — | Sweeping globe for "browsing the web"; sizes from its container. Still globe under reduced motion |
-| AvatarGroup | — | default, sm, xs | Row of Avatars; `stacked` overlaps + spreads on hover (no reflow), `reverse` spreads left; `size` forwards to children |
-| IconStack | — | — | Fanned colored icon tiles (`IconStackItem`, `color` per product, grey default); spreads on hover. The Empty icon, or a trailing set of items after text |
+| Component | Variants | Sizes | Notes |
+| ------------ | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| Button | default, primary, secondary, outline, destructive, destructive-outline, link, link-foreground, link-muted | default, xs, sm, lg, icon, icon-xs, icon-sm, icon-lg, row, inline | `loading` overlays a centered spinner and disables the button (width stays stable). `row` is the full-width, regular-weight list row that menu, combobox and autocomplete items render. `inline` is a link inside a sentence: no height or padding, and it inherits the sentence's font size and line height. `elevated` adds heavy CTA chrome — see Elevated button. `tooltip` adds a hover and focus tooltip. `indicator="default"` puts a dot on the top-right corner for something waiting behind the button (`"warning"` or `"destructive"` for a problem); say what it means in the `aria-label`, and set `--quill-button-indicator-ring` when the button sits off the app background. `disabledReason` disables the button and shows the reason in that tooltip. A `render` that carries a link destination (`to`, `href`) or is a non-button element turns off `nativeButton` by itself; a disabled button drops that destination. |
+| Badge | default, info, destructive, warning, success, completed | — | Semantic status |
+| Toggle | default, outline | default, sm, lg, icon | `ToggleGroupItem` takes `disabledReason`, which disables the item and shows the reason in a tooltip on hover. Arrow keys in a `ToggleGroup` skip disabled items, so the reason is hover-only. |
+| Chip | outline | sm | Use with ChipClose |
+| Separator | — | — | orientation: horizontal/vertical |
+| Spinner | — | — | SVG, accepts svg props |
+| Skeleton | — | — | Pulsing placeholder div |
+| SkeletonText | — | — | lines, minWidth, maxWidth |
+| Progress | — | — | value: 0-100 |
+| Slider | — | — | value, min, max |
+| Avatar | — | lg, default, sm, xs | Compose `Avatar > AvatarImage + AvatarFallback`; image errors fall back to initials/icon |
+| ChatGlobe | — | — | Sweeping globe for "browsing the web"; sizes from its container. Still globe under reduced motion |
+| AvatarGroup | — | default, sm, xs | Row of Avatars; `stacked` overlaps + spreads on hover (no reflow), `reverse` spreads left; `size` forwards to children |
+| IconStack | — | — | Fanned colored icon tiles (`IconStackItem`, `color` per product, grey default); spreads on hover. The Empty icon, or a trailing set of items after text |
---
@@ -382,7 +382,7 @@ Attached panel outside the popup: pass `popupSibling` on `SelectContent` — ren
</Combobox>
```
-`ComboboxItem` takes `tooltip` and `disabledReason` like the menu items. Never hand-wrap a disabled `ComboboxItem` in a Tooltip. Pass `action` on a row that runs an action instead of picking a value, such as "New project": it is never selected, so it drops the check mark's gutter. The selection check in `Combobox` and `Select` takes lucide's stroke of 2. An app whose row icons draw thinner lines sets `--quill-indicator-stroke-width` to match them.
+A Combobox in a `DropdownMenuSubContent` takes `inline` and no `ComboboxContent`: the submenu is its popup, and its items keep the check mark's gutter. `ComboboxItem` takes `tooltip` and `disabledReason` like the menu items. Never hand-wrap a disabled `ComboboxItem` in a Tooltip. Pass `action` on a row that runs an action instead of picking a value, such as "New project": it is never selected, so it drops the check mark's gutter. The selection check in `Combobox` and `Select` takes lucide's stroke of 2. An app whose row icons draw thinner lines sets `--quill-indicator-stroke-width` to match them.
Something attached to the popup's edge, such as a resize handle: pass `popupSibling` on `ComboboxContent`, as on `SelectContent`. It renders in the positioner beside the popup, outside the popup's overflow, so it can sit across the edge. Position it absolute so it never resizes the popup.
@@ -1082,7 +1082,7 @@ Reduced motion shows the finished highlight at once.
</ResizablePanelGroup>
```
-For an edge that resizes something outside a panel group, such as a popup, use `ResizeGrip`. It has the handle's look and no behavior: the caller runs the drag. It forwards its ref, so it can be a `TooltipTrigger` render target. Set `--quill-resizable-hit-size` to widen the hit area, and pass `className="bg-transparent"` when a border already draws the line.
+For an edge that resizes something outside a panel group, such as a popup, use `ResizeGrip`. `size="sm"` is a shorter, thinner handle for a tight edge. It has the handle's look and no behavior: the caller runs the drag. It forwards its ref, so it can be a `TooltipTrigger` render target. Set `--quill-resizable-hit-size` to widen the hit area, and pass `className="bg-transparent"` when a border already draws the line.
### Scroll Area
@@ -1133,6 +1133,8 @@ const range = getPaginationRange(pageCount, pageIndex)
Compose `Table > TableHeader/TableBody/TableFooter > TableRow > TableHead/TableCell`. Per-cell options on `TableHead`/`TableCell`: `sticky="left" | "right"` (frozen column), `align="left" | "center" | "right"` (horizontal), `valign="top" | "middle" | "bottom"` (vertical), `expand` (absorb leftover width). `align` also positions an inline-flex header Button. On `Table`: `stickyHeader` (or `"page"`) for a sticky header, `fullWidth` to fill the container — pair `fullWidth` with `expand` on one column to choose which one stretches, `size="sm"` to tighten head/cell inline padding to `0.75rem` (from `1rem`) for dense tables and to align edge columns with a `Card size="sm"`.
+For resizable columns, pass `columnWidths` on `Table`, one width in pixels per column, and put a `TableColumnResizer` last in each `TableHead`: `<Table columnWidths={[width, 200]}><TableHead>Name<TableColumnResizer value={width} onValueCommitted={setWidth} min={80} /></TableHead>`. `Table` owns the rest: the `<col>` widths, the table's width as their sum, clipping the cells, and moving the column on each frame of a drag. A drag never renders: `onValueCommitted` reports the width once, when it ends, and the `columnWidths` you pass must then follow it. `onReset` runs on a double click. In a `fullWidth` table, end each row with `<TableCell filler />` and the header with `<TableHead filler />`, to fill the space the columns leave. `columnWidths="content"` keeps the columns fitting their content until you pass the array. A `DataTable` does all of this with `resizableColumns`, so reach for this only in a table built from the primitives.
+
**Backgrounds: transparent by default, opaque when sticky.** Plain cells and headers are transparent, so a `Table` inherits whatever surface it sits on (inside a `Card`, a tinted panel). Sticky parts (`stickyHeader`, `stickyHeader="page"`, `sticky="left"/"right"`) get an opaque background automatically — they'd otherwise bleed scrolled-under content — so you don't add `bg-background` yourself. It defaults to the app background; if the table sits on a different surface, override the inherited `--quill-table-sticky-bg` custom property on the `Table` so the frozen cells match — e.g. inside a `Card`, `className="[--quill-table-sticky-bg:var(--card)]"`.
**Bounding the height — `h-*` or `max-h-*` both scroll.** A height class on the `Table` (it lands on the root wrapper) makes the body scroll past that height; pair it with `stickyHeader` to freeze the header. Both a definite height (`h-96`) and a bare cap (`max-h-[44rem]`) work — the scroll viewport reads the cap through `max-height: inherit`, so `max-h-*` no longer clips rows without a scrollbar.
diff --git a/packages/quill/packages/primitives/src/button.css b/packages/quill/packages/primitives/src/button.css
index 52df43844288..4ad5f8de41a6 100644
--- a/packages/quill/packages/primitives/src/button.css
+++ b/packages/quill/packages/primitives/src/button.css
@@ -269,7 +269,7 @@
}
/* =========================================================================
- Variant: link / link-muted
+ Variant: link / link-foreground / link-muted
========================================================================= */
.quill-button--variant-link {
color: var(--primary);
@@ -281,6 +281,15 @@
text-decoration: underline;
}
+ .quill-button--variant-link-foreground {
+ color: var(--foreground);
+ }
+
+ .quill-button--variant-link-foreground:not(:disabled, [aria-disabled='true']):hover,
+ .quill-button--variant-link-foreground[data-popup-open] {
+ background-color: var(--fill-hover);
+ }
+
.quill-button--variant-link-muted {
color: var(--muted-foreground);
text-underline-offset: 4px;
@@ -624,6 +633,10 @@
color: var(--primary);
}
+ .quill-button--variant-link-foreground[data-loading] > .quill-spinner {
+ color: var(--foreground);
+ }
+
.quill-button--variant-link-muted[data-loading] > .quill-spinner {
color: var(--muted-foreground);
}
diff --git a/packages/quill/packages/primitives/src/button.stories.tsx b/packages/quill/packages/primitives/src/button.stories.tsx
index 2b87bb0c223f..483be1082dcf 100644
--- a/packages/quill/packages/primitives/src/button.stories.tsx
+++ b/packages/quill/packages/primitives/src/button.stories.tsx
@@ -20,6 +20,7 @@ const meta = {
'destructive',
'destructive-outline',
'link',
+ 'link-foreground',
'link-muted',
],
},
diff --git a/packages/quill/packages/primitives/src/button.tsx b/packages/quill/packages/primitives/src/button.tsx
index 5d69b0526ccf..1e6fbb06f338 100644
--- a/packages/quill/packages/primitives/src/button.tsx
+++ b/packages/quill/packages/primitives/src/button.tsx
@@ -20,6 +20,7 @@ const buttonVariants = cva(
destructive: 'quill-button--variant-destructive',
'destructive-outline': 'quill-button--variant-destructive-outline',
link: 'quill-button--variant-link',
+ 'link-foreground': 'quill-button--variant-link-foreground',
'link-muted': 'quill-button--variant-link-muted',
},
size: {
diff --git a/packages/quill/packages/primitives/src/combobox.css b/packages/quill/packages/primitives/src/combobox.css
index b755cc0555b8..df5eacff03fb 100644
--- a/packages/quill/packages/primitives/src/combobox.css
+++ b/packages/quill/packages/primitives/src/combobox.css
@@ -132,8 +132,10 @@
* keeps Button's own padding. The gutter is the row's padding, an icon and
* the item's gap, so an option's content starts exactly where an action
* row's label does. The gap lives in one variable, so the two cannot drift.
+ * A Combobox can also sit in a menu's submenu, with no popup of its own.
*/
- .quill-combobox__content .quill-combobox__item:not([data-action]) {
+ :is(.quill-combobox__content, .quill-menu__content, .quill-menu__sub-content)
+ .quill-combobox__item:not([data-action]) {
/* Button's row padding and row icon size, then the item's gap. */
padding-inline-start: calc(0.5rem + 0.875rem + var(--quill-combobox-item-gap));
}
diff --git a/packages/quill/packages/primitives/src/combobox.tsx b/packages/quill/packages/primitives/src/combobox.tsx
index bf922870add0..aaa869df8d56 100644
--- a/packages/quill/packages/primitives/src/combobox.tsx
+++ b/packages/quill/packages/primitives/src/combobox.tsx
@@ -27,6 +27,8 @@ function Combobox<Value, Multiple extends boolean | undefined = false>({
)
}
+const useComboboxFilteredItems = ComboboxPrimitive.useFilteredItems
+
function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props): React.ReactElement {
return <ComboboxPrimitive.Value data-slot="combobox-value" {...props} />
}
@@ -354,6 +356,7 @@ function useComboboxAnchor(): React.RefObject<HTMLDivElement> {
}
export {
+ useComboboxFilteredItems,
Combobox,
ComboboxInput,
ComboboxContent,
diff --git a/packages/quill/packages/primitives/src/dropdown-menu.tsx b/packages/quill/packages/primitives/src/dropdown-menu.tsx
index 48b013db2314..9a9523722ef1 100644
--- a/packages/quill/packages/primitives/src/dropdown-menu.tsx
+++ b/packages/quill/packages/primitives/src/dropdown-menu.tsx
@@ -34,8 +34,6 @@ function withItemTooltip(
return withTooltip(item, content, { target: 'block', side: 'inline-end' })
}
-
-
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props): React.ReactElement {
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
@@ -53,9 +51,12 @@ const DropdownMenuTrigger = React.forwardRef<HTMLButtonElement, MenuPrimitive.Tr
const DropdownMenuContent = React.forwardRef<
React.ComponentRef<typeof MenuPrimitive.Popup>,
MenuPrimitive.Popup.Props &
- Pick<MenuPrimitive.Positioner.Props, 'align' | 'alignOffset' | 'side' | 'sideOffset' | 'anchor'>
+ Pick<MenuPrimitive.Positioner.Props, 'align' | 'alignOffset' | 'side' | 'sideOffset' | 'anchor'> & {
+ /** Drops the padding and scrolling, for content that lays out and scrolls on its own. */
+ flush?: boolean
+ }
>(function DropdownMenuContent(
- { align = 'start', alignOffset = 0, side = 'bottom', sideOffset = 4, className, anchor, children, ...props },
+ { align = 'start', alignOffset = 0, side = 'bottom', sideOffset = 4, className, anchor, flush, children, ...props },
ref
) {
return (
@@ -73,7 +74,11 @@ const DropdownMenuContent = React.forwardRef<
<MenuPrimitive.Popup
ref={ref}
data-slot="dropdown-menu-content"
- className={cn('quill-menu__content w-max min-w-(--anchor-width) max-w-(--available-width)', className)}
+ data-flush={flush ? '' : undefined}
+ className={cn(
+ 'quill-menu__content w-max min-w-(--anchor-width) max-w-(--available-width)',
+ className
+ )}
{...props}
>
<div className="quill-menu__scroller scroll-mask-y-4 scroll-py-4">{children}</div>
diff --git a/packages/quill/packages/primitives/src/index.ts b/packages/quill/packages/primitives/src/index.ts
index 179b5ed10484..ec358f7be31a 100644
--- a/packages/quill/packages/primitives/src/index.ts
+++ b/packages/quill/packages/primitives/src/index.ts
@@ -125,6 +125,7 @@ export {
ComboboxTrigger,
ComboboxValue,
useComboboxAnchor,
+ useComboboxFilteredItems,
} from './combobox'
export {
ContextMenu,
@@ -346,6 +347,7 @@ export {
TableEmpty,
TableCaption,
} from './table'
+export { MIN_TABLE_COLUMN_WIDTH, TableColumnResizer } from './table-column-resizer'
export { Tabs, TabsContent, TabsList, TabsTrigger } from './tabs'
export { Text, textVariants } from './text'
export { Textarea } from './textarea'
diff --git a/packages/quill/packages/primitives/src/menu.css b/packages/quill/packages/primitives/src/menu.css
index a4a9c5992574..f9c96e0d6f10 100644
--- a/packages/quill/packages/primitives/src/menu.css
+++ b/packages/quill/packages/primitives/src/menu.css
@@ -60,6 +60,11 @@
overflow: hidden auto;
}
+ .quill-menu__content[data-flush] .quill-menu__scroller {
+ padding: 0;
+ overflow: hidden;
+ }
+
.quill-menu__content[data-closed] .quill-menu__scroller,
.quill-menu__sub-content[data-closed] .quill-menu__scroller {
overflow: hidden;
diff --git a/packages/quill/packages/primitives/src/resizable.css b/packages/quill/packages/primitives/src/resizable.css
index b684adcd2d11..df4fd843de57 100644
--- a/packages/quill/packages/primitives/src/resizable.css
+++ b/packages/quill/packages/primitives/src/resizable.css
@@ -62,6 +62,11 @@
border-radius: var(--radius-lg);
}
+ .quill-resizable__handle[data-size='sm'] > div {
+ width: 0.1875rem;
+ height: 1rem;
+ }
+
.quill-resizable__handle[aria-orientation='horizontal'] > div {
rotate: 90deg;
}
diff --git a/packages/quill/packages/primitives/src/resizable.tsx b/packages/quill/packages/primitives/src/resizable.tsx
index cca7601334c3..470e2ba5ad8b 100644
--- a/packages/quill/packages/primitives/src/resizable.tsx
+++ b/packages/quill/packages/primitives/src/resizable.tsx
@@ -1,8 +1,9 @@
+import './resizable.css'
+
import * as React from 'react'
import * as ResizablePrimitive from 'react-resizable-panels'
import { cn } from './lib/utils'
-import './resizable.css'
function ResizablePanelGroup({ className, ...props }: ResizablePrimitive.GroupProps): React.ReactElement {
return (
@@ -61,14 +62,20 @@ function ResizableHandle({
*/
const ResizeGrip = React.forwardRef<
HTMLDivElement,
- React.ComponentProps<'div'> & { orientation?: 'vertical' | 'horizontal'; withHandle?: boolean }
->(function ResizeGrip({ orientation = 'vertical', withHandle = true, className, ...props }, ref) {
+ React.ComponentProps<'div'> & {
+ orientation?: 'vertical' | 'horizontal'
+ withHandle?: boolean
+ /** `sm` is a shorter, thinner handle for a tight edge, such as a table header. */
+ size?: 'default' | 'sm'
+ }
+>(function ResizeGrip({ orientation = 'vertical', withHandle = true, size = 'default', className, ...props }, ref) {
return (
<div
ref={ref}
role="separator"
aria-orientation={orientation}
data-slot="resize-grip"
+ data-size={size}
className={cn(
'quill-resizable__handle flex items-center justify-center',
orientation === 'vertical' ? 'cursor-col-resize' : 'cursor-row-resize',
diff --git a/packages/quill/packages/primitives/src/table-column-resizer.tsx b/packages/quill/packages/primitives/src/table-column-resizer.tsx
new file mode 100644
index 000000000000..4ccf5230ec2e
--- /dev/null
+++ b/packages/quill/packages/primitives/src/table-column-resizer.tsx
@@ -0,0 +1,144 @@
+import { mergeProps } from '@base-ui/react/merge-props'
+import * as React from 'react'
+
+import { cn } from './lib/utils'
+import { ResizeGrip } from './resizable'
+import { previewTableColumnWidth } from './table'
+
+// Enough for a short label and its sort icon.
+export const MIN_TABLE_COLUMN_WIDTH = 64
+const KEYBOARD_STEP = 16
+
+type TableColumnResizerProps = Omit<React.ComponentProps<'div'>, 'children' | 'defaultValue'> & {
+ /** The column's width in pixels, for assistive technology. Omit it while the column still fits its content. */
+ value?: number
+ /** Called once with the final width in pixels, when a drag ends or on a press of an arrow key. Set your state here. */
+ onValueCommitted: (width: number) => void
+ /** Smallest width in pixels. */
+ min?: number
+ /** Largest width in pixels. */
+ max?: number
+ /** Called before the first change of a drag or key press, for a table that fixes its widths only then. */
+ onResizeStart?: () => void
+ /** Called on a double click, to give the column back its default width. */
+ onReset?: () => void
+}
+
+/**
+ * The edge of a column, for a `TableHead` to hold as its last child, in a `Table` with `columnWidths`: a line that shows
+ * while the header is hovered, and a handle that shows while its own header cell is. Drags with the pointer and moves
+ * with the arrow keys.
+ *
+ * A drag moves the column through the `Table`, once per frame, and only reports the result when it ends. Rendering on
+ * every move would render every row, which takes far longer than a frame in a large table.
+ */
+const TableColumnResizer = React.forwardRef<HTMLDivElement, TableColumnResizerProps>(function TableColumnResizer(
+ {
+ className,
+ value,
+ onValueCommitted,
+ min = MIN_TABLE_COLUMN_WIDTH,
+ max = Infinity,
+ onResizeStart,
+ onReset,
+ 'aria-label': ariaLabel = 'Resize column',
+ ...props
+ },
+ ref
+) {
+ const [resizing, setResizing] = React.useState(false)
+ const clamp = (width: number): number => Math.round(Math.min(max, Math.max(min, width)))
+ const currentWidth = (element: Element): number =>
+ value ?? element.closest('th')?.getBoundingClientRect().width ?? min
+ // The right edge of a column is its left edge in a right-to-left table, so a drag runs the other way.
+ const inlineDirection = (element: Element): number => (getComputedStyle(element).direction === 'rtl' ? -1 : 1)
+
+ const onPointerDown = (event: React.PointerEvent<HTMLDivElement>): void => {
+ if (event.button !== 0) {
+ return
+ }
+ const grip = event.currentTarget
+ const head = grip.closest('th')
+ const table = grip.closest('table')
+ const startX = event.clientX
+ const startWidth = currentWidth(grip)
+ const direction = inlineDirection(grip)
+ let width = startWidth
+ let started = false
+ let frame = 0
+
+ const applyWidth = (): void => {
+ frame = 0
+ if (table && head) {
+ previewTableColumnWidth(table, head.cellIndex, width)
+ }
+ grip.setAttribute('aria-valuenow', String(width))
+ }
+
+ const onMove = (move: PointerEvent): void => {
+ if (!started) {
+ started = true
+ onResizeStart?.()
+ }
+ width = clamp(startWidth + (move.clientX - startX) * direction)
+ frame ||= requestAnimationFrame(applyWidth)
+ }
+
+ const onEnd = (): void => {
+ grip.removeEventListener('pointermove', onMove)
+ grip.removeEventListener('pointerup', onEnd)
+ grip.removeEventListener('pointercancel', onEnd)
+ cancelAnimationFrame(frame)
+ setResizing(false)
+ if (started) {
+ applyWidth()
+ onValueCommitted(width)
+ }
+ }
+
+ grip.setPointerCapture?.(event.pointerId)
+ setResizing(true)
+ grip.addEventListener('pointermove', onMove)
+ grip.addEventListener('pointerup', onEnd)
+ grip.addEventListener('pointercancel', onEnd)
+ }
+
+ const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') {
+ return
+ }
+ event.preventDefault()
+ const step = (event.key === 'ArrowLeft' ? -KEYBOARD_STEP : KEYBOARD_STEP) * inlineDirection(event.currentTarget)
+ onResizeStart?.()
+ onValueCommitted(clamp(currentWidth(event.currentTarget) + step))
+ }
+
+ return (
+ <ResizeGrip
+ ref={ref}
+ size="sm"
+ data-slot="table-column-resizer"
+ data-resizing={resizing ? '' : undefined}
+ tabIndex={0}
+ aria-label={ariaLabel}
+ aria-valuenow={value}
+ aria-valuemin={min}
+ aria-valuemax={max === Infinity ? undefined : max}
+ className={cn('quill-table__resizer', className)}
+ {...mergeProps<'div'>(
+ {
+ onPointerDown,
+ // Stops a drag selecting the header text. It also keeps focus, and its ring, away from a pointer drag.
+ onMouseDown: (event) => event.preventDefault(),
+ onKeyDown,
+ onDoubleClick: () => onReset?.(),
+ },
+ props
+ )}
+ />
+ )
+})
+
+TableColumnResizer.displayName = 'TableColumnResizer'
+
+export { TableColumnResizer }
diff --git a/packages/quill/packages/primitives/src/table.css b/packages/quill/packages/primitives/src/table.css
index b19cb1442922..00867ce14160 100644
--- a/packages/quill/packages/primitives/src/table.css
+++ b/packages/quill/packages/primitives/src/table.css
@@ -11,6 +11,9 @@
--tbl-edge-shadow: rgb(0 0 0 / 12%);
--tbl-row-hover: color-mix(in oklab, var(--muted) 40%, var(--background));
+ /* Above a sticky header cell (2) and a sticky header column (3). */
+ --tbl-z-resizer: 4;
+
position: relative;
width: 100%;
@@ -127,6 +130,34 @@
min-width: 0;
}
+ /* Fixed layout: only the widths on the <col> elements decide the columns, so neither
+ the content nor a min or max width on a cell can hold a column back from a drag. */
+ .quill-table[data-layout='fixed'] {
+ table-layout: fixed;
+ }
+
+ /* Resizable columns. These hang off an attribute that is set from the first render and never
+ changes, because a rule that reaches every cell off an attribute that flips at the first drag
+ restyles them all, which is a visible pause in a large table. */
+
+ /* A head clips past its edge only by what its resizer needs. */
+ .quill-table[data-resizable] .quill-table__head {
+ overflow: clip;
+ overflow-clip-margin: 0.5rem;
+ }
+
+ /* While the columns fit their content, the expand column truncates its own and leaves the others alone. */
+ .quill-table[data-resizable] :is(.quill-table__head, .quill-table__cell)[data-expand] {
+ max-width: 0;
+ }
+
+ /* Keeps long content in its own column, and gives each cell its own layout and paint work,
+ so that moving a column does not repaint its neighbours. This cuts the cost of a frame
+ of a drag by about 40%. */
+ .quill-table[data-resizable] .quill-table__cell {
+ contain: layout paint style;
+ }
+
/* =========================================================================
Head / body / footer rows
========================================================================= */
@@ -257,6 +288,18 @@
letter-spacing: inherit;
}
+ /* A borderless Button in a left-aligned cell keeps its label in line with the
+ column header, the same as a header Button does. */
+ .quill-table__cell:not([data-align='center'], [data-align='right'])
+ > :is(
+ .quill-button--variant-default,
+ .quill-button--variant-link,
+ .quill-button--variant-link-foreground,
+ .quill-button--variant-link-muted
+ ):not([data-size^='icon']) {
+ margin-inline-start: -0.5rem;
+ }
+
/* =========================================================================
Sticky header + columns. Frozen edges are delineated by borders only; the
generic viewport-edge shadows above still signal off-screen overflow.
@@ -318,4 +361,80 @@
.quill-table[data-sticky-header] .quill-table__head[data-sticky] {
z-index: 3;
}
+
+ /* An empty column that fills the space a fixed table's columns leave. It is always in the
+ DOM, so that fixing the layout at the start of a drag does not have to render every row. */
+ .quill-table [data-filler] {
+ padding: 0;
+ }
+
+ .quill-table:not([data-layout='fixed']) [data-filler] {
+ display: none;
+ }
+
+ /* =========================================================================
+ Column resizer. The line shows while the header is hovered, the handle while
+ its own header cell is. A keyboard user and a drag in progress see both.
+ ========================================================================= */
+ .quill-table__head:has(> .quill-table__resizer) {
+ position: relative;
+ }
+
+ /* The handle and hit target sit across the edge, so they reach over the next header cell. A head paints under the
+ next one, so it rises while the pointer is on either side of the edge. Hovering the next head is what lifts the
+ hit target under a pointer coming from the right, so this head has to outrank that head's own rise. */
+ .quill-table__head:has(> .quill-table__resizer):hover,
+ .quill-table__head:has(> .quill-table__resizer:focus-visible) {
+ z-index: var(--tbl-z-resizer);
+ }
+
+ .quill-table__head:has(> .quill-table__resizer):has(+ .quill-table__head:hover) {
+ z-index: calc(var(--tbl-z-resizer) + 1);
+ }
+
+ .quill-table__head > .quill-table__resizer {
+ --quill-resizable-hit-size: 0.75rem;
+
+ position: absolute;
+ inset-block: 0;
+ inset-inline-end: 0;
+ touch-action: none;
+ opacity: 0;
+ transition: opacity 0.1s;
+ }
+
+ .quill-table__head > .quill-table__resizer > div {
+ opacity: 0;
+ transition: opacity 0.1s;
+ }
+
+ [data-slot='table-header']:hover .quill-table__resizer,
+ [data-slot='table-header']:has(.quill-table__resizer[data-resizing]) .quill-table__resizer,
+ .quill-table__head > .quill-table__resizer:focus-visible {
+ opacity: 1;
+ }
+
+ .quill-table__head:hover > .quill-table__resizer > div,
+ .quill-table__head > .quill-table__resizer[data-resizing] > div,
+ .quill-table__head > .quill-table__resizer:focus-visible > div {
+ opacity: 1;
+ }
+
+ /* While a drag is on, only its own handle shows, whichever cell the pointer crosses. */
+ [data-slot='table-header']:has(.quill-table__resizer[data-resizing])
+ .quill-table__resizer:not([data-resizing])
+ > div {
+ opacity: 0;
+ }
+
+ .quill-table__head > .quill-table__resizer[data-resizing] > div {
+ background-color: color-mix(in oklab, var(--primary) 80%, transparent);
+ }
+
+ /* A touch screen has no hover to reveal the handle, and a drag along the header scrolls the table. */
+ @media (hover: none) {
+ .quill-table__head > .quill-table__resizer {
+ display: none;
+ }
+ }
}
diff --git a/packages/quill/packages/primitives/src/table.stories.tsx b/packages/quill/packages/primitives/src/table.stories.tsx
index ac61fd76b67b..7d03c1cfd1f3 100644
--- a/packages/quill/packages/primitives/src/table.stories.tsx
+++ b/packages/quill/packages/primitives/src/table.stories.tsx
@@ -26,6 +26,7 @@ import {
TableHeader,
TableRow,
} from './table'
+import { TableColumnResizer } from './table-column-resizer'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './tooltip'
const meta = {
@@ -620,6 +621,142 @@ export const RowActions: Story = {
// Empty state: TableEmpty renders the full-span cell for you (no manual colSpan,
// no height juggling) and centers its content. Give the Table a height (here a
// fixed `h-80`) and the empty cell fills the body.
+// A link in a cell is a small link Button, so every table's links share a height and hover.
+function CellLink({
+ href,
+ variant = 'link-foreground',
+ children,
+}: {
+ href: string
+ variant?: 'link-foreground' | 'link-muted'
+ children: React.ReactNode
+}): React.ReactElement {
+ return (
+ <Button
+ variant={variant}
+ size="sm"
+ nativeButton={false}
+ // A story has no router; a plain anchor stands in for the host router's Link.
+ // eslint-disable-next-line react/forbid-elements
+ render={<a href={href} />}
+ left
+ className="max-w-full shrink"
+ >
+ <span className="truncate">{children}</span>
+ </Button>
+ )
+}
+
+// The record's name is a `link-foreground`; a secondary link, like its email, is a `link-muted`.
+export const WithLinks: Story = {
+ render: () => (
+ <Table className="max-w-2xl rounded-md border border-(--border)">
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead>Email</TableHead>
+ <TableHead>Role</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {manyRows.slice(0, 6).map((row) => (
+ <TableRow key={row.id}>
+ <TableCell>
+ <CellLink href={`#user-${row.id}`}>{row.name}</CellLink>
+ </TableCell>
+ <TableCell>
+ <CellLink href={`mailto:${row.email}`} variant="link-muted">
+ {row.email}
+ </CellLink>
+ </TableCell>
+ <TableCell>{row.role}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ ),
+} satisfies Story
+
+// A name too long for its column truncates inside the link, with the Button still at its small size.
+export const WithTruncatedLinks: Story = {
+ render: () => (
+ <Card size="sm" flush className="max-w-xl">
+ <CardContent>
+ <Table size="sm" fullWidth>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="max-w-56">Title</TableHead>
+ <TableHead>Owner</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {[
+ 'Revenue overview',
+ 'Weekly activation funnel broken down by plan, region and signup source',
+ 'Q4 experiment plan and the follow-up questions from the last review meeting',
+ ].map((title, index) => (
+ <TableRow key={title}>
+ <TableCell className="max-w-56">
+ <CellLink href={`#report-${index}`}>{title}</CellLink>
+ </TableCell>
+ <TableCell>{manyRows[index].name}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ </Card>
+ ),
+} satisfies Story
+
+// Hover the header to see the column edges, and a header cell to see its handle. Drag it, focus it and use the arrow
+// keys, or double click it to reset. Only the dragged column changes.
+export const ResizableColumns: Story = {
+ render: function Render() {
+ const [nameWidth, setNameWidth] = React.useState(200)
+ const [emailWidth, setEmailWidth] = React.useState(260)
+ const roleWidth = 160
+ return (
+ <Table columnWidths={[nameWidth, emailWidth, roleWidth]} className="rounded-md border border-(--border)">
+ <TableHeader>
+ <TableRow>
+ <TableHead>
+ Name
+ <TableColumnResizer
+ value={nameWidth}
+ onValueCommitted={setNameWidth}
+ onReset={() => setNameWidth(200)}
+ min={100}
+ aria-label="Resize Name column"
+ />
+ </TableHead>
+ <TableHead>
+ Email
+ <TableColumnResizer
+ value={emailWidth}
+ onValueCommitted={setEmailWidth}
+ onReset={() => setEmailWidth(260)}
+ min={100}
+ aria-label="Resize Email column"
+ />
+ </TableHead>
+ <TableHead>Role</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {manyRows.slice(0, 6).map((row) => (
+ <TableRow key={row.id}>
+ <TableCell>{row.name}</TableCell>
+ <TableCell>{row.email}</TableCell>
+ <TableCell>{row.role}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )
+ },
+} satisfies Story
+
export const EmptyState: Story = {
render: () => (
<Table fullWidth className="h-80 rounded-md border border-(--border)">
diff --git a/packages/quill/packages/primitives/src/table.tsx b/packages/quill/packages/primitives/src/table.tsx
index 49db339ffe6e..09f7a9407bb4 100644
--- a/packages/quill/packages/primitives/src/table.tsx
+++ b/packages/quill/packages/primitives/src/table.tsx
@@ -18,6 +18,11 @@ type CellLayout = {
valign?: VAlign
/** Absorb remaining width in a `fullWidth` table. Mark one column per table. */
expand?: boolean
+ /**
+ * An empty last cell in each row of a `fullWidth` table with resizable columns. It fills the space the columns
+ * leave, and shows only once their widths are fixed.
+ */
+ filler?: boolean
}
// Sets each ref (object or callback) to the same node — lets the viewport carry
@@ -71,6 +76,27 @@ function useScrollEdges(
}, [rootRef, viewportRef])
}
+function sumWidths(widths: number[]): number {
+ return widths.reduce((total, width) => total + width, 0)
+}
+
+/**
+ * Moves a column to a width straight in the DOM, for each frame of a drag, because rendering there would render every
+ * row. It does nothing until the table's widths are fixed.
+ */
+function previewTableColumnWidth(table: HTMLTableElement, index: number, width: number): void {
+ const cols = Array.from(table.querySelector('colgroup')?.children ?? []) as HTMLElement[]
+ const col = cols[index]
+ if (!col?.style.width) {
+ return
+ }
+ col.style.width = `${width}px`
+ // A full-width table's last `col` is the filler, which has no width.
+ const total = sumWidths(cols.map((c) => parseFloat(c.style.width) || 0))
+ // The same property the render sets: React leaves alone a style it thinks has not changed.
+ table.style[table.hasAttribute('data-full-width') ? 'minWidth' : 'width'] = `${total}px`
+}
+
type TableProps = React.ComponentProps<'table'> & {
/**
* `true` — header sticks within the table's own scroll viewport (needs a
@@ -91,16 +117,36 @@ type TableProps = React.ComponentProps<'table'> & {
* `0.75rem` inline padding. Pair with `Card size="sm" flush`.
*/
size?: 'default' | 'sm'
+ /**
+ * Makes the columns resizable, with a `TableColumnResizer` in each `TableHead`. `'content'` — the columns still fit
+ * their content. An array — one width in pixels per column, and only these decide the widths from then on, so a
+ * cell can be narrower than what it holds. The table's width is their sum. Pass the array as the widths change.
+ */
+ columnWidths?: 'content' | number[]
/** Classes for the inner `<table>`. Size/scroll go on the container via `className`. */
tableClassName?: string
/** Ref to the scrolling viewport — for scroll-to-row, virtualization, IntersectionObservers, etc. */
viewportRef?: React.Ref<HTMLDivElement>
+ /** Ref to a marker after the table, inside the viewport. Observe it to load more rows near the end. */
+ viewportEndRef?: React.Ref<HTMLDivElement>
}
// The forwarded ref points at the `<table>` element (consistent with `...props`,
// which also land there). The scroll container is reached via `viewportRef`.
const Table = React.forwardRef<HTMLTableElement, TableProps>(function Table(
- { className, tableClassName, stickyHeader = false, fullWidth = false, size = 'default', viewportRef, ...props },
+ {
+ className,
+ tableClassName,
+ stickyHeader = false,
+ fullWidth = false,
+ size = 'default',
+ columnWidths,
+ viewportRef,
+ viewportEndRef,
+ style,
+ children,
+ ...props
+ },
ref
) {
const rootRef = React.useRef<HTMLDivElement | null>(null)
@@ -110,6 +156,7 @@ const Table = React.forwardRef<HTMLTableElement, TableProps>(function Table(
(node: HTMLDivElement | null): void => setRefs(node, innerViewportRef, viewportRef),
[viewportRef]
)
+ const widths = Array.isArray(columnWidths) ? columnWidths : null
// `className` sizes the non-scrolling root (which clips + hosts the fixed edge
// shadows); the inner viewport owns the scroll. Sticky header/columns position
// against the viewport.
@@ -128,9 +175,33 @@ const Table = React.forwardRef<HTMLTableElement, TableProps>(function Table(
data-sticky-header={stickyHeader ? '' : undefined}
data-full-width={fullWidth ? '' : undefined}
data-size={size}
+ data-resizable={columnWidths ? '' : undefined}
+ data-layout={widths ? 'fixed' : undefined}
className={cn('quill-table', tableClassName)}
+ style={
+ widths
+ ? {
+ ...style,
+ // A full-width table fills its container, and only grows past it.
+ ...(fullWidth ? {} : { width: sumWidths(widths) }),
+ minWidth: fullWidth ? sumWidths(widths) : 0,
+ }
+ : style
+ }
{...props}
- />
+ >
+ {/* In the DOM from the first render: inserting it beside the rows at the first drag restyles them all. */}
+ {columnWidths ? (
+ <colgroup>
+ {widths?.map((width, index) => (
+ <col key={index} style={{ width }} />
+ ))}
+ {widths && fullWidth ? <col /> : null}
+ </colgroup>
+ ) : null}
+ {children}
+ </table>
+ {viewportEndRef ? <div ref={viewportEndRef} aria-hidden /> : null}
</div>
</div>
)
@@ -166,7 +237,7 @@ const TableRow = React.forwardRef<HTMLTableRowElement, React.ComponentProps<'tr'
const TableHead = React.forwardRef<HTMLTableCellElement, React.ComponentProps<'th'> & { sticky?: Sticky } & CellLayout>(
// `scope="col"` by default (the common case); override to "row" for row headers.
- function TableHead({ className, sticky, align, valign, expand, scope = 'col', ...props }, ref) {
+ function TableHead({ className, sticky, align, valign, expand, filler, scope = 'col', ...props }, ref) {
return (
<th
ref={ref}
@@ -175,6 +246,8 @@ const TableHead = React.forwardRef<HTMLTableCellElement, React.ComponentProps<'t
data-align={align}
data-valign={valign}
data-expand={expand ? '' : undefined}
+ data-filler={filler ? '' : undefined}
+ role={filler ? 'presentation' : undefined}
scope={scope}
className={cn('quill-table__head', className)}
{...props}
@@ -184,7 +257,7 @@ const TableHead = React.forwardRef<HTMLTableCellElement, React.ComponentProps<'t
)
const TableCell = React.forwardRef<HTMLTableCellElement, React.ComponentProps<'td'> & { sticky?: Sticky } & CellLayout>(
- function TableCell({ className, sticky, align, valign, expand, ...props }, ref) {
+ function TableCell({ className, sticky, align, valign, expand, filler, ...props }, ref) {
return (
<td
ref={ref}
@@ -193,6 +266,8 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.ComponentProps<'t
data-align={align}
data-valign={valign}
data-expand={expand ? '' : undefined}
+ data-filler={filler ? '' : undefined}
+ role={filler ? 'presentation' : undefined}
className={cn('quill-table__cell', className)}
{...props}
/>
@@ -237,4 +312,15 @@ TableCell.displayName = 'TableCell'
TableEmpty.displayName = 'TableEmpty'
TableCaption.displayName = 'TableCaption'
-export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableEmpty, TableCaption }
+export {
+ Table,
+ TableHeader,
+ TableBody,
+ TableFooter,
+ TableHead,
+ TableRow,
+ TableCell,
+ TableEmpty,
+ TableCaption,
+ previewTableColumnWidth,
+}