GhostDataTable specification
Status: Approved for GHO-35. Option A (composable + native GhostTable; see ADR 0014, accepted) is the phase-one architecture. specStatus: approved was recorded with the first implementation step (GHO-233); Zac approved in chat on 2026-11-23; recorded in PR #272.
Approved themed
0.1.0addendum (#316/GHO-249): Following the2026-11-25roadmap review, the single-sort themed wrapper in@ghostvue/themesand companionGhostDataTablePresetlayout slots in@ghostvue/vueare specified in the ThemedGhostDataTableaddendum below (decoupled from multi-column sort #317, which stays deferred to0.3.0). Zac recorded approval in PR #374.
Approved amendment, no target release yet: an opt-in header control beside the label and sort button of both default renderers is specified in the Header filter-control amendment.
Approved amendment, no target release yet: opt-in query-wide server selection (every row matching the committed server filters, minus excluded ids) is specified in the Query-wide server selection amendment.
Purpose and user problems
GhostDataTable is the interactive data grid for application admin surfaces: sortable columns, filters, pagination, row selection, and expandable detail rows. It targets teams that already own REST or GraphQL row records and want Vue-idiomatic composition without surrendering data ownership or adopting a spreadsheet interaction model. Product goal (Zac): deliver a DataTable that is better than PrimeVue — stricter typing, explicit server contracts, and superior default behavior — not a behavioral clone with more markup.
Sighted users get familiar table chrome built on GhostTable semantics. Assistive technology encounters a native table with sort buttons, checkbox selection, and stable header/body relationships—not a roving grid with cell-level tabindex.
Immediate consumers: paged admin lists, selectable bulk-action tables, and expandable row detail patterns that compose GhostPagination, GhostCheckbox, GhostInput / GhostSelect for filters, and GhostEmptyState for zero-result states.
Non-goals
Phase one explicitly excludes:
- Row virtualization, frozen columns, and scroll-synced footers (separate future specs; see Child work decomposition). Phase one also excluded sticky headers; opt-in CSS
stickyHeaderon themedGhostDataTable(0.1.0) is specified in the ThemedGhostDataTableaddendum. role="grid",role="treegrid", arrow-key cell navigation, and single-Tab-stop roving row focus (deferred grid-navigation spec).- Multi-column sort in phase one and
0.1.0(deferred to0.3.0in #317; single primary sort column only. See the approved Multi-column sort specification (GHO-250)). - Themed
GhostDataTablein phase one (headless examples and docs shipped first;0.1.0single-sort@ghostvue/themeswrapper and preset layout slots are specified in the ThemedGhostDataTableaddendum for #316 / #333). - Resolving a query-wide selection to row ids, authorizing a bulk action, or running it. The table records an opt-in query selection (amendment); the server owns membership and execution.
- Column resize/reorder drag handles, grouping, pivoting, aggregation, and built-in query builders.
- Data fetching, caching, SWR, optimistic updates, and error UI (consumer-owned).
- Built-in filter debouncing (consumer-owned).
- Cloning or deep-watching the consumer
dataarray; mutating row objects. - A shared table engine singleton, global registry, or cross-route table state store.
Public API
Types (exact contracts)
These types are the phase-one public TypeScript contracts. Names live in @ghostvue/vue (exact export paths chosen at implementation).
/** Stable primary key for selection, expansion, and reactivity-safe maps */
type DataTableRowId = string | number
type DataTableSortDirection = 'asc' | 'desc' | false
interface DataTableColumnSort {
id: string
desc: boolean
}
interface DataTableColumnFilter {
id: string
value: unknown
}
interface DataTablePaginationState {
/** 1-based page index (matches GhostPagination) */
pageIndex: number
pageSize: number
}
/** Snapshot of every dimension that can trigger a server refetch */
interface DataTableQueryState {
sorting: DataTableColumnSort[]
columnFilters: DataTableColumnFilter[]
globalFilter: unknown
pagination: DataTablePaginationState
}
interface DataTableColumnDef<TData> {
id: string
header?: string
accessorKey?: keyof TData & string
accessorFn?: (row: TData, index: number) => unknown
/** Headless render hook; Vue accepts VNodeChild from setup render functions */
/** Render hook: invoke as `cell(context)` — not a Vue component (`<component :is>`) */
cell?: (context: DataTableCellContext<TData>) => import('vue').VNodeChild
enableSorting?: boolean
enableColumnFilter?: boolean
sortUndefined?: 'first' | 'last' | false
sortFn?: (rowA: TData, rowB: TData, columnId: string) => number
filterFn?: (row: TData, columnId: string, filterValue: unknown) => boolean
meta?: Record<string, unknown>
}
interface DataTableCellContext<TData> {
row: TData
rowId: DataTableRowId
rowIndex: number
column: DataTableColumnDef<TData>
/** Runtime value is unknown; use accessorKey for typed access in templates */
getValue: () => unknown
}
type DataTableGetRowId<TData> = (row: TData, index: number) => DataTableRowId
interface DataTableStateChangePayload {
/** Monotonic id; pair with useGhostDataTableServerRequest */
requestId: number
/** What the user last changed */
trigger: keyof DataTableQueryState
/** Full query after reset/coalescence rules; sole source for server fetches */
query: DataTableQueryState
}getValue() typing policy: DataTableCellContext.getValue() stays () => unknown in generic/shared slots (any column). Column definitions should use defineDataTableColumns<TData>() so cell / column slots receive a typed value and getValue(): TValue for that column.
/** Factory; no runtime state */
function defineDataTableColumns<TData>(): {
accessorKey: <K extends keyof TData & string>(
key: K,
column: Omit<DataTableColumnDef<TData>, 'accessorKey' | 'id' | 'cell'> & {
id?: string
cell?: (
ctx: Omit<DataTableCellContext<TData>, 'getValue'> & {
value: TData[K]
getValue: () => TData[K]
},
) => import('vue').VNodeChild
},
) => DataTableColumnDef<TData>
accessorFn: <TValue>(
id: string,
column: Omit<DataTableColumnDef<TData>, 'accessorFn' | 'id' | 'cell'> & {
accessorFn: (row: TData, index: number) => TValue
cell?: (
ctx: Omit<DataTableCellContext<TData>, 'getValue'> & {
value: TValue
getValue: () => TValue
},
) => import('vue').VNodeChild
},
) => DataTableColumnDef<TData>
}Type-test acceptance (required in CI): for accessorKey: 'amount' on Invoice, inside cell, value.toFixed(2) compiles, value.toUpperCase() is a type error, and renaming Invoice.amount breaks the column; the same three checks for an accessorFn column returning number.
Default comparators (when local sorting runs): locale-aware strings, numeric subtract, Date#getTime, sortUndefined default 'last'.
Default filtering contract (approved)
Applies when the corresponding manualFiltering flag is false and the composable runs local filtering. Approved by Zac (PR #265, fourth review).
| Rule | Default |
|---|---|
| Global filter participation | A column participates iff it has an accessor (accessorKey or accessorFn) and enableColumnFilter !== false (default true when an accessor exists). Columns with enableColumnFilter: false are ignored by the global filter. |
| Global filter match | When globalFilter is a string, a row matches if any participating column’s cell value matches (logical OR). Skip columns whose value is null or undefined (do not coerce with String). Otherwise case-insensitive substring on String(value) ('acme' matches 'ACME Corp'). |
| Global filter non-string | Non-string globalFilter values use strict equality (===) against each participating column’s cell value (logical OR across columns). Skip null / undefined cell values. |
| Clear global filter | undefined, null, or '' (empty string) means no global filter; all rows pass the global stage. |
| Column filter clear | A columnFilters entry is inactive when value is undefined, null, or ''. Inactive entries do not constrain rows. |
Column filter default filterFn | When filterFn is omitted and the filter value is a non-empty string: case-insensitive substring on String(cellValue) unless cellValue is null or undefined (row fails the column filter for that value). Non-string filter values: strict equality; skip null / undefined cells. |
| Pipeline order | Global filter stage, then per-column filters (logical AND across active column filters). |
Required tests when implemented: global case-insensitivity; OR across columns; AND across column filters; clear sentinels; omitted filterFn on a column; column excluded via enableColumnFilter: false; row with missing customer does not match global 'un' (null/undefined skip).
Manual-processing matrix
manualPagination | manualSorting | manualFiltering | data contents | rowCount | Composable processing |
|---|---|---|---|---|---|
false | false | false | Full local set | filtered.length (derived) | Global sort → global filter → slice page |
false | * | * | Full local set | derived | Sort/filter per manual flags on full set |
true | false | false | One server page | required prop | Page-local sort then page-local filter on data only |
true | true | false | One server page | required | Page-local filter only |
true | false | true | One server page | required | Page-local sort only |
true | true | true | One server page | required | No reorder/filter; display data as-is |
Row lists: getPrePaginationRowModel() is sort + filter on the processing input (before pagination). getRowModel() is the paginated slice used for tbody rendering only when local pagination applies (server page: typically the processed page slice). Select-all scope (see below): local — getPrePaginationRowModel(); server — getRowModel(). Example (server page + page-local filter): 25 loaded, 3 visible after filter → body shows 3; select-all toggles those 3; ids on other pages remain in selectedRowIds.
pageCount override: optional. When omitted, pageCount = max(1, ceil(rowCount / pageSize)). pageIndex clamping (recorded; see Decisions recorded): after any derived pageCount change, if pagination.pageIndex > pageCount, set pageIndex to pageCount. When rowCount === 0 (query-wide empty, including server total), pageCount is 1 and effective pagination.pageIndex is 1 (matches GhostPagination). When rowCount > 0 but getRowModel() is empty after page-local processing, keep pageIndex (recorded acceptance: server page 4 + filter → 0 visible rows stays on page 4).
Props and configuration
Headless GhostDataTable / useGhostDataTable options:
| Option | Type | Default | Contract |
|---|---|---|---|
data | readonly TData[] | required | Consumer-owned rows. Reference change triggers reset rules. |
columns | DataTableColumnDef<TData>[] | required | Not mutated by the library. |
getRowId | DataTableGetRowId<TData> | required | Required in every build; no production fallback. |
manualSorting | boolean | false | When true, composable does not sort data for server-global sort. |
manualFiltering | boolean | false | When true, composable does not filter for server-global filter. |
manualPagination | boolean | false | When true, data is one page; rowCount required. |
rowCount | number | derived | Required iff manualPagination; total matching query on server. |
pageCount | number | derived | Optional override; otherwise from rowCount and pageSize. |
enableRowSelection | boolean | false | When false, selection APIs are inert. |
enableRowExpansion | boolean | false | When false, expansion APIs are inert. |
allowMultipleExpanded | boolean | true | When false, opening one row collapses others. |
loading | boolean | false | Sets aria-busy on the table region. |
disabled | boolean | false | Disables sort, selection, expansion. |
Named exports (phase one): GhostDataTable, GhostDataTableTable, GhostDataTablePreset, useGhostDataTable, useGhostDataTableServerRequest, defineDataTableColumns, interaction helpers (getDataTableSortButtonProps, …), and types above. enableMultiSort is not part of phase one.
Default rendering convenience (GhostDataTablePreset)
GhostDataTableTable maps columns to a minimal GhostTable* body (example (a)). GhostDataTablePreset is the batteries-included headless preset for the #269 invoice surface: global search field, selection + expansion columns, sort buttons, empty row, and detail <tr> — wired with the interaction prop helpers and a11y rules below.
| Concern | Contract |
|---|---|
| Placement | Default child of GhostDataTable (same slot as manual composition). Mutually exclusive with a custom #default render in one tree (consumer picks preset or manual). |
| Props | emptyTitle?: string (maps to GhostEmptyState #title); searchLabel?: string; selectionHeaderLabel?, expansionHeaderLabel?; showGlobalFilter?: boolean (default true when any column filterable). Passes through disabled / loading from parent context. |
| Slots | #${columnId} typed cell overrides (same as GhostDataTableTable); #detail="{ row, rowId, rowIndex }"; #toolbar before the table; optional #search to replace the default search control. |
| Escape hatches | (1) GhostDataTableTable only — sort/page cells, no selection toolbar. (2) Manual #default slot + GhostTable* (example (b)). (3) useGhostDataTable without GhostDataTable for non-table layouts. |
| Line-count target | Feature-equivalent to PrimeVue fixture (sort, filter, paginate, select, expand) with defineDataTableColumns must be ≤ 95 non-blank consumer lines (PrimeVue baseline in FINDINGS.md). Verified on the spec example below (~44 non-blank lines). |
Phase one includes GhostDataTableTable and GhostDataTablePreset as unstyled @ghostvue/vue exports (not @ghostvue/themes). See the Themed GhostDataTable addendum for the 0.1.0 preset layout-slot additions (#toolbarStart, #toolbarEnd, #bulkActions, #footer) and @ghostvue/themes wrappers (#316 / #333).
Examples (same invoice table)
Two documented paths share Invoice rows and defineDataTableColumns:
(a) Basic — sort, paginate, custom currency cell
Short on-ramp: no manual <thead> / <tbody> shell. Consumer adds a currency format only via the #amount slot.
<script setup lang="ts">
import { computed, ref } from 'vue'
import {
GhostDataTable,
GhostDataTableTable,
GhostPagination,
defineDataTableColumns,
} from '@ghostvue/vue'
type Invoice = { id: string; customer: string; amount: number }
const helper = defineDataTableColumns<Invoice>()
const columns = [
helper.accessorKey('customer', { header: 'Customer', enableSorting: true }),
helper.accessorKey('amount', { header: 'Amount', enableSorting: true }),
]
const data = ref<Invoice[]>([
{ id: 'inv-1', customer: 'ACME Corp', amount: 1200 },
{ id: 'inv-2', customer: 'Globex', amount: 980.5 },
])
const pagination = ref({ pageIndex: 1, pageSize: 25 })
const sorting = ref<{ id: string; desc: boolean }[]>([])
const pageCount = computed(() =>
Math.max(1, Math.ceil(data.value.length / pagination.value.pageSize)),
)
</script>
<template>
<GhostDataTable
v-model:pagination="pagination"
v-model:sorting="sorting"
:data="data"
:columns="columns"
:get-row-id="(row) => row.id"
>
<GhostDataTableTable :columns="columns">
<template #amount="{ value }">{{ value.toFixed(2) }} USD</template>
</GhostDataTableTable>
<GhostPagination v-model="pagination.pageIndex" :page-count="pageCount" />
</GhostDataTable>
</template>:columns="columns" on GhostDataTableTable is what types value as a number in #amount (GHO-241): a child in the root's default slot cannot see the root's column types. Without it the renderer still renders every root column and value is unknown. Executable copy: examples/data-table/basic-invoices.vue.
Without GhostDataTableTable, this shape is not achievable in a short example—the renderless default slot would force every consumer to recreate the table shell (see (c) / (b)).
(a′) Preset — invoice parity under PrimeVue LOC (target)
Same features as the #269 Ghost prototype (search, sort, pagination, selection, expansion, currency column) with typed columns. Spec example: ~44 non-blank lines (target ≤ 95 vs PrimeVue).
<script setup lang="ts">
import { computed, ref } from 'vue'
import {
GhostDataTable,
GhostDataTablePreset,
GhostPagination,
defineDataTableColumns,
} from '@ghostvue/vue'
type Invoice = { id: string; customer: string; amount: number }
const columns = defineDataTableColumns<Invoice>()
const columnDefs = [
columns.accessorKey('customer', { header: 'Customer', enableSorting: true }),
columns.accessorKey('amount', { header: 'Amount', enableSorting: true }),
]
const data = ref<Invoice[]>([
{ id: 'inv-1', customer: 'ACME Corp', amount: 1200 },
{ id: 'inv-2', customer: 'Globex', amount: 980.5 },
{ id: 'inv-3', customer: 'Initech', amount: 42 },
])
const globalFilter = ref('')
const selectedRowIds = ref<string[]>([])
const pagination = ref({ pageIndex: 1, pageSize: 25 })
const pageCount = computed(() =>
Math.max(1, Math.ceil(data.value.length / pagination.value.pageSize)),
)
</script>
<template>
<GhostDataTable
ref="table"
v-model:global-filter="globalFilter"
v-model:selected-row-ids="selectedRowIds"
v-model:pagination="pagination"
:data="data"
:columns="columnDefs"
:get-row-id="(row) => row.id"
:enable-row-selection="true"
:enable-row-expansion="true"
>
<GhostDataTablePreset :columns="columnDefs" empty-title="No invoices">
<template #amount="{ value }">{{ value.toFixed(2) }} USD</template>
<template #detail="{ rowId }">Details for {{ rowId }}</template>
</GhostDataTablePreset>
<GhostPagination v-model="pagination.pageIndex" :page-count="pageCount" />
</GhostDataTable>
</template>Implementation must ship GhostDataTablePreset so this path is real, not spec-only.
Shipped (GHO-246). As with GhostDataTableTable, pass the same array to the preset's columns prop to type value in #amount and row in #detail. Executable copy: examples/data-table/preset-invoices.vue (6 invoices, 5 per page; the pager binds pagination, pageCount, and setPageIndex from the root's default slot, per GhostPagination wiring). It is 82 non-blank lines including its layout CSS, and tests/integration/data-table-preset-invoices-example.test.ts fails if it exceeds 95. Implementation notes:
- Additive props for localized control names:
selectAllLabel('Select all rows'),rowSelectionLabel(rowId)(Select row …), androwExpansionLabel(rowId)(Show details for …).emptyHeadingLevel(default3) sets theGhostEmptyStatetitle level so the empty state fits the page outline (axeheading-order). - The selection
<th>is named byaria-label(it holds only the select-all checkbox); the expansion<th>holds visually hidden text, so axeempty-table-headerpasses. Expand buttons show anaria-hiddenglyph and are named byaria-labelon the button. - The default search is a labelled
GhostInput type="search"that commits through the root'ssetGlobalFilter(server filtering resets to page 1 with onestateChange). Use#searchto debounce. The field is disabled while the root isdisabled. detail,toolbar, andsearchare reserved slot names; do not use them as column ids. Attributes on the preset land onGhostTable.- Tests:
GhostDataTablePreset.test.ts(unit), the example and SSR hydration tests,type-tests/GhostDataTablePresetConsumer.vue, and a Playwright test intests/e2e/ghost-data-table.spec.tsthat runs sort, select, expand, page, and empty filter from the keyboard with zero axe violations on the table, search field, and co-located pager.
(b) Full composition — approval and accessibility fixture
Manual GhostTable* composition for selection, expansion, filters, and custom headers. This is the gate for freezing interaction bindings and the approval fixture. Manual script without reload:
- Focus the Amount sort button; press
SpaceorEnterto sort. Spaceon row inv-2 checkbox to toggle selection (inv-2 starts selected).Spaceon inv-2 expand button (getRowExpandButtonProps) to collapse the open detail row;Spaceagain on the same button to reopen it.- Type a global filter that matches no rows; header row stays mounted; body shows
GhostEmptyStatewith visible #title textNo invoices.
<script setup lang="ts">
import { ref } from 'vue'
import {
GhostDataTable,
GhostTable,
GhostTableBody,
GhostTableCell,
GhostTableHead,
GhostTableHeaderCell,
GhostTableRow,
GhostCheckbox,
GhostEmptyState,
type DataTableColumnDef,
type DataTableRowId,
} from '@ghostvue/vue'
type Invoice = {
id: string
customer: string
amount: number
}
const columns: DataTableColumnDef<Invoice>[] = [
{
id: 'customer',
header: 'Customer',
accessorKey: 'customer',
enableSorting: true,
},
{
id: 'amount',
header: 'Amount',
accessorKey: 'amount',
enableSorting: true,
cell: ({ row }) => `${row.amount.toFixed(2)} USD (${row.customer})`,
},
]
const data = ref<Invoice[]>([
{ id: 'inv-1', customer: 'ACME Corp', amount: 1200 },
{ id: 'inv-2', customer: 'Globex', amount: 980.5 },
{ id: 'inv-3', customer: 'Initech', amount: 42 },
])
const globalFilter = ref('')
const selectedRowIds = ref<DataTableRowId[]>(['inv-2'])
const expandedRowIds = ref<DataTableRowId[]>(['inv-2'])
</script>
<template>
<GhostDataTable
ref="table"
v-model:global-filter="globalFilter"
v-model:selected-row-ids="selectedRowIds"
v-model:expanded-row-ids="expandedRowIds"
:data="data"
:columns="columns"
:get-row-id="(row) => row.id"
:enable-row-selection="true"
:enable-row-expansion="true"
>
<template
#default="{
tableRootProps,
headers,
getHeaderCellProps,
getRowProps,
rows,
getBodyCellContext,
getSortButtonProps,
getRowSelectionCheckboxProps,
getHeaderSelectionCheckboxProps,
getRowExpandButtonProps,
headerSelectionState,
toggleAllRowsSelected,
}"
>
<label>
Search
<input v-model="globalFilter" type="search" />
</label>
<GhostTable v-bind="tableRootProps">
<GhostTableHead>
<GhostTableRow>
<GhostTableHeaderCell scope="col" aria-label="Selection">
<GhostCheckbox
v-bind="
getHeaderSelectionCheckboxProps({
label: 'Select all invoices matching filters',
})
"
:model-value="headerSelectionState.allSelected"
:indeterminate="headerSelectionState.someSelected"
@update:model-value="toggleAllRowsSelected"
/>
</GhostTableHeaderCell>
<GhostTableHeaderCell scope="col">Details</GhostTableHeaderCell>
<GhostTableHeaderCell
v-for="header in headers"
:key="header.id"
v-bind="getHeaderCellProps(header.id)"
>
<button
v-if="header.canSort"
v-bind="
getSortButtonProps(header.id, {
label: `${header.column.header} sort`,
})
"
@click="header.toggleSort"
>
{{ header.column.header }}
</button>
<template v-else>{{ header.column.header }}</template>
</GhostTableHeaderCell>
</GhostTableRow>
</GhostTableHead>
<GhostTableBody>
<GhostTableRow v-if="rows.length === 0">
<GhostTableCell :colspan="headers.length + 2">
<GhostEmptyState>
<template #title>No invoices</template>
</GhostEmptyState>
</GhostTableCell>
</GhostTableRow>
<template v-for="row in rows" :key="row.rowId">
<GhostTableRow v-bind="getRowProps(row.rowId)">
<GhostTableCell>
<GhostCheckbox
v-bind="
getRowSelectionCheckboxProps(row.rowId, {
label: `Select invoice ${row.rowId}`,
})
"
:model-value="row.isSelected"
@update:model-value="row.toggleSelected"
/>
</GhostTableCell>
<GhostTableCell>
<button
v-bind="
getRowExpandButtonProps(row.rowId, {
label: `Show details for ${row.rowId}`,
})
"
@click="row.toggleExpanded"
>
Details
</button>
</GhostTableCell>
<GhostTableCell v-for="cell in row.cells" :key="cell.column.id">
<template v-if="cell.column.cell">
{{
cell.column.cell(
getBodyCellContext(row.rowId, cell.column.id),
)
}}
</template>
<template v-else>
{{ getBodyCellContext(row.rowId, cell.column.id).getValue() }}
</template>
</GhostTableCell>
</GhostTableRow>
<GhostTableRow v-if="row.isExpanded" v-bind="row.detailRowProps">
<GhostTableCell :colspan="headers.length + 2">
Details for {{ row.rowId }}
</GhostTableCell>
</GhostTableRow>
</template>
</GhostTableBody>
</GhostTable>
</template>
</GhostDataTable>
</template>headers is independent of body rows so the head remains when getRowModel() is empty. Gate the sort button on header.canSort, not column.enableSorting: sorting defaults on for any column with an accessor or sortFn, so enableSorting is often omitted (GHO-242). Row inv-2 is selected and expanded in the initial fixture. Writable ref v-models accept composable updates. Column cell hooks are functions — call cell.column.cell(context); when the hook returns a VNode, GhostDataTableTable normalizes rendering (manual composition may use a small DataTableCell helper).
Renderless root slot bindings
| Binding | Host | Contract |
|---|---|---|
tableRootProps | GhostTable root wrapper or <table> | aria-busy when loading; data-ghost-data-table; optional aria-labelledby / aria-label from consumer |
getHeaderCellProps(columnId) | GhostTableHeaderCell | scope: 'col'; aria-sort on the sorted column only: ascending or descending; omitted when unsorted (phase-one single sort); data-sort for styling |
getRowProps(rowId) | GhostTableRow (data row) | data-selected="true" when selected; data-expanded="true" when expanded (boolean data attributes, independent) |
headers | — | Column header models (column, toggleSort, …) independent of body row count |
detailRowProps | expansion <tr> via GhostTableRow | Keeps GhostTableRow data-part="row"; adds data-detail-row="true" (consumer merge must not overwrite data-part; see below) |
rows | — | Rows from getRowModel() with cells, selection helpers, etc. |
headerSelectionState | header GhostCheckbox | { allSelected, someSelected } over the select-all target (local: getPrePaginationRowModel() ids; server: getRowModel() ids) |
toggleAllRowsSelected | header checkbox | Toggles every id in that same target set (not the current page only when local) |
getSortButtonProps(columnId, options?) | sort button in <th> | type="button"; aria-label on the button; does not set aria-sort (parent <th> via getHeaderCellProps) |
getRowSelectionCheckboxProps(rowId, options?) | row GhostCheckbox | aria-label merged onto the focusable checkbox control (not wrapper-only) |
getHeaderSelectionCheckboxProps(options?) | header GhostCheckbox | aria-label on the header checkbox input; pair with headerSelectionState. Icon-only <th> also needs a column name (aria-label on <th> or visible text). |
getRowExpandButtonProps(rowId, options?) | expand button | aria-label and aria-expanded on the button; aria-controls → detail row id; Space toggles when focused |
pagination, pageCount, rowCount | GhostPagination | Effective (clamped) pagination, pager page count, and query-wide row count (Pagination) |
setPageIndex(pageIndex) | GhostPagination update:modelValue | Commits a page: clamps, writes the pagination v-model, one stateChange with manualPagination |
Sort direction on headers is single-column in phase one (at most one entry in sorting).
Standalone interaction helpers (GHO-236): the slot getters above delegate to exported pure functions that take a useGhostDataTable return as their first argument, for layouts without the root: getDataTableHeaderCellProps(table, columnId), getDataTableSortButtonProps(table, columnId, options?), getDataTableRowSelectionCheckboxProps(table, rowId, options?), getDataTableHeaderSelectionCheckboxProps(table, options?), and getDataTableRowExpandButtonProps(table, rowId, options?) (options add id and detailRowId; the root fills both). They return attributes only, never listeners. The root's expand button props carry a generated id; it is the focus-restore target for focus on collapse, so keep it when spreading. Focus restore belongs to the root; standalone layouts own their own focus handling.
GhostDataTableTable slots: for each column id, optional #${columnId}="{ row, rowId, rowIndex, value, getValue, column }" with value typed when the column came from defineDataTableColumns and the same array is passed to the renderer's optional columns prop. columns also picks and orders the rendered columns by id (ids the root lacks are skipped); it defaults to every root column. A slot wins over the column cell hook, which wins over the plain value. Header text falls back to the column id, so no <th> is empty. Sortable columns (canSort) get a native sort button named by the header text; aria-sort stays on the <th>. The renderer reads the same bindings as the default slot (provided by the root), and attributes such as class or contain-horizontal fall through to GhostTable.
v-model contracts
| State | Prop | Emit | Uncontrolled initial |
|---|---|---|---|
| Sorting | sorting | update:sorting | defaultSorting (DataTableColumnSort[], max length 1) |
| Column filters | columnFilters | update:columnFilters | defaultColumnFilters |
| Global filter | globalFilter | update:globalFilter | defaultGlobalFilter |
| Pagination | pagination | update:pagination | defaultPagination |
| Row selection | selectedRowIds | update:selectedRowIds | defaultSelectedRowIds |
| Expansion | expandedRowIds | update:expandedRowIds | defaultExpandedRowIds |
All use useControllableState.
Reset rules (applied before any stateChange emit):
| Event | Sorting | Filters | Pagination reset |
|---|---|---|---|
globalFilter change | kept | updated | manualFiltering: true: page → 1 (server refetch). manualFiltering: false: keep pageIndex, then clamp (full-local and page-local). Recorded (Zac): page-local on server page stays on page 4 without refetch. |
columnFilters change | kept | updated | Same as globalFilter. |
pagination.pageSize change | kept | kept | page → 1 |
data reference change | kept | kept | manualPagination: false: keep index, clamp (no unconditional reset). manualPagination: true: keep index when only the page slice was replaced. |
sorting change | updated | kept | kept (then clamp if pageCount shrinks) |
Selection / expansion on filter/pagination events: kept (pruning rules below).
Pagination reset acceptance:
| Setup | Action on page 4 | Expected pagination | stateChange / server requests |
|---|---|---|---|
manualPagination: true, manualFiltering: false (page-local filter) | Change global/column filter | Stay on page 4 | Zero (no server refetch) |
manualPagination: true, manualFiltering: true (server filter) | Change filter | page → 1 | Exactly one fetch with new filter |
Comparison note (PrimeVue): Prime’s paginator commonly resets the page on filter. GhostVue manualPagination + !manualFiltering keeps page 4 with zero requests when filtering page-locally — deliberate (PR #269 parity harness).
Selection / expansion pruning:
Automatic pruning runs only when the input is the full collection the table owns end-to-end: manualPagination: false and manualFiltering: false. On data reference change, drop ids that no longer appear among source rows in the new array (keyed by getRowId). Do not prune because a row is hidden by filter, pagination slice, or a transient server response.
| Mode | Prune on filter hiding a row? | Prune when server data omits a selected id? |
|---|---|---|
Local full (manualPagination + manualFiltering both false) | No (hidden ≠ removed from source) | N/A |
Server filter, local pagination (manualFiltering: true, manualPagination: false) | No | No — preserve ids across filtered responses until consumer replaces full source or user clears selection |
Server page (manualPagination: true) | No | No — ids stay when changing pages or filtered page payloads |
Required tests:
- Local: select A, filter hides A, refresh
datawith same entities, clear filter → A still selected. - Server filter + local pagination: select A → server response excludes A → clear filter → A still selected.
Events, callbacks, slots, and exposed methods
stateChange—DataTableStateChangePayload. Fired once per user action after coalesced updates (e.g. server filter on page 4 → one emit withquery.pagination.pageIndex === 1and new filter; page-local filter on page 4 → nostateChange). Server consumers should fetch frompayload.queryonly, not from separate v-model handlers.- Filter + pagination coalescing: When
manualFiltering: trueresetspageIndexto 1, emit exactly onestateChangewhosequerycarries both the new filter andpagination.pageIndex === 1, withtrigger: 'globalFilter' | 'columnFilters'. Do not emit a secondstateChange(or pagination-only server fetch) for the automatic page reset in the same user action. update:*— still emitted for each affected v-model (same tick ordering as combinatorial updates; tests assert single fetch).- Default slot — bindings in table above.
header,cell,expandedRowslots — optional overrides.- Exposed:
toggleAllRowsSelected,toggleRowSelected,toggleRowExpanded,resetRowSelection,retry()(re-emitsstateChangewith the currentqueryand a fresh composable-mintedrequestId; consumers must not invent ids), etc.
useGhostDataTableServerRequest — { begin(requestId), isLatest(requestId) } (combobox async pattern), exported from @ghostvue/vue with its return type UseGhostDataTableServerRequestReturn (GHO-239). It holds a plain number (no reactivity or lifecycle); create one per table instance. begin records the id as given, because ids are monotonic only within one useGhostDataTable call and restart at 1 when the table remounts.
Select-all behavior
Header checkbox and headerSelectionState use the same row-id set as toggleAllRowsSelected.
| Mode | Select-all target | Effect |
|---|---|---|
Local (manualPagination: false) | getPrePaginationRowModel() | All rows matching current filters/sort across pages (not only the current page). |
Server (manualPagination: true) | getRowModel() | Visible subset of the loaded page after page-local processing (e.g. 3 of 25). Cross-page ids stay in selectedRowIds. |
Header mixed state uses indeterminate on GhostCheckbox (checkbox-spec).
Acceptance (local): 100 rows, page size 25, filter matches 40 → select-all adds 40 ids (including rows not on the current page); navigating pages does not drop them.
Acceptance (server + page-local filter): load 25 rows, filter to 3 visible, select-all selects exactly those 3; clear filter; prior cross-page selections unchanged.
Comparison note (PrimeVue, PR #269):PrimeVue DataTable header select-all is page-scoped by default. GhostVue’s local rule — all ids in getPrePaginationRowModel() across pages — is intentional and matches Zac’s recorded decision, not Prime’s default.
Derived models
| Model | Definition |
|---|---|
getPrePaginationRowModel() | After sort + filter on the processing input (data or full local set per matrix); before pagination slice. |
getRowModel() | Rows rendered in the body (rows in the default slot) — after matrix processing and pagination slice when local pagination applies. Select-all uses this set only in server mode. |
getPaginationRowModel() | Alias of getRowModel() in phase one (same reference; no second row list). |
getSelectedRowModel() | Objects for ids in selectedRowIds that appear in the current getRowModel() (for display only; full id list may be larger on server). |
State model
Sorting
- Phase one: at most one
DataTableColumnSortentry. - Tri-state: none → asc → desc → none.
aria-sortonly on the sorted column's<th>.
Filtering
Follow Default filtering contract when local filtering runs.
Debouncing: consumer-owned (composable updates on every bound filter change).
Empty
getRowModel(): head + filters remain; body shows empty state row.Page after a filter change (GHO-237):
Mode pageIndexafter the filter changestateChangemanualFiltering: true(server filter)1, written in the same action One, triggerglobalFilter/columnFilters,query.pagination.pageIndex: 1; no follow-upFull local ( manualPaginationand filtering false)Kept; clamped to the last valid page when the filtered count shrinks None Page-local ( manualPagination: trueonly)Kept, even when the visible slice is empty None Widening a filter never restores an earlier page. Server filtering never prunes selection or expansion, so ids selected on any page survive a filter → clear cycle.
Toolbar composition and consumer-owned debouncing
The composable applies every filter write immediately; with manualFiltering: true every committed value is one stateChange (one fetch). Debounce before committing, and commit clears immediately. Commit user edits through the table's actions (setGlobalFilter, setColumnFilter, setColumnFilters on the template ref): they apply the page-reset rule above and emit stateChange. A parent writing the bound v-model ref directly is a state restore, like URL hydration: the rows re-filter but no page reset or stateChange happens. Until docs/components/data-table.md ships (GHO-247), this is the reference composition; packages/vue/src/GhostDataTable.toolbar-filter.test.ts mounts the same structure.
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, useTemplateRef } from 'vue'
import {
GhostButton,
GhostDataTable,
GhostInput,
GhostToolbar,
type DataTableColumnFilter,
type GhostDataTableExposed,
} from '@ghostvue/vue'
const table = useTemplateRef<GhostDataTableExposed<Invoice>>('table')
const search = ref('') // what the field shows, updated on every keystroke
const globalFilter = ref('') // what the table filters by (v-model mirror)
const columnFilters = ref<DataTableColumnFilter[]>([])
let timer: ReturnType<typeof setTimeout> | undefined
function onSearch(value: string): void {
search.value = value
clearTimeout(timer)
timer = setTimeout(() => table.value?.setGlobalFilter(value), 250)
}
onBeforeUnmount(() => {
clearTimeout(timer)
})
const paidOnly = computed(() =>
columnFilters.value.some((f) => f.id === 'status' && f.value === 'paid'),
)
function togglePaid(): void {
table.value?.setColumnFilter('status', paidOnly.value ? '' : 'paid')
}
function clearFilters(): void {
clearTimeout(timer) // a pending keystroke must not re-apply the old text
search.value = ''
table.value?.setGlobalFilter('')
table.value?.setColumnFilters([])
}
</script>
<template>
<div class="invoice-filters">
<label>
Search invoices
<GhostInput
:model-value="search"
type="search"
@update:model-value="onSearch"
/>
</label>
<GhostToolbar label="Invoice filters">
<GhostButton :aria-pressed="paidOnly" @click="togglePaid"
>Paid only</GhostButton
>
<GhostButton @click="clearFilters">Clear filters</GhostButton>
</GhostToolbar>
</div>
<GhostDataTable
ref="table"
v-model:global-filter="globalFilter"
v-model:column-filters="columnFilters"
:data="invoices"
:columns="columns"
:get-row-id="(row) => row.id"
aria-label="Invoices"
>
<!-- GhostTable composition as in example (b) -->
</GhostDataTable>
</template>- Search field beside, not inside,
GhostToolbar. Roving arrow keys are ignored in text fields (the caret owns them), so a field insiderole="toolbar"is an arrow-key dead end inside the toolbar's singleTabstop. Keep the labelled field its ownTabstop and put buttons and toggles in the toolbar. - Server mode: add
manual-filtering(andmanual-pagination/row-countas needed) and fetch from@state-change; each debounced commit produces one request for page 1. Unchanged writes are no-ops, so Clear filters emits one request per dimension it actually clears. Stale responses are rejected byrequestId(see Async behavior), so debouncing reduces traffic but is not the race guard. - The library ships no debounce option: delay, leading/trailing edge,
Enter-to-search, and IME handling stay app decisions (Zac, PR #265).
Pagination
- Shared 1-based
pageIndexwithGhostPagination. - Whenever
pageIndex > pageCount, clamp topageCount(Zac approved). rowCount === 0:pageCount1,pageIndex1 (query-wide empty).rowCount > 0with emptygetRowModel(): keeppageIndex(page-local filter on a server page does not coerce page 1).- Which
rowCount(GHO-238): withmanualPaginationit is therowCountprop (the server total for the query), never the loaded page length; otherwise the filtered local row count. - When the clamp runs: whenever the derived
pageCountchanges (filter shrink, localdatareference change, serverrowCountorpageCountchange). The clamp writes thepaginationv-model once. WithmanualPaginationit also emits exactly onestateChange(trigger: 'pagination', clampedquery.pagination) so the consumer fetches the page it now shows; the parent's v-model echo emits nothing more. Apaginationvalue restored out of range (URL hydration, first render) is clamped on read only: no write and nostateChange.
GhostPagination wiring
Co-locate GhostPagination in the root's default slot and bind it to the root, not to data.length. Only the root knows the filtered count, the server rowCount, the pageCount override, and the empty → page 1 rule, and only setPageIndex emits the server stateChange:
<GhostDataTable v-model:pagination="pagination" aria-label="Invoices" ...>
<template #default="{ pagination: page, pageCount, setPageIndex, ...table }">
<GhostTable v-bind="table.tableRootProps"><!-- rows --></GhostTable>
<GhostPagination
:model-value="page.pageIndex"
:page-count="pageCount"
aria-label="Invoice pages"
@update:model-value="setPageIndex"
/>
</template>
</GhostDataTable>- Give the pager its own name (
aria-label) when the page has more than onenavigationlandmark. v-model="pagination.pageIndex"(examples (a) and (a′)) mutates the bound object in place. It is fine for local tables with no filter, but it bypassessetPageIndex, so a server table emits nostateChangefor the click.- Executable reference:
examples/data-table/paginated-invoices.vue(local search clamps the page; zero matches show page 1 of 1). The Playwright spectests/e2e/ghost-data-table-pagination.spec.tsruns axe on it with the pager on several pages and empty (zero violations).
Selection
Cross-page server selection is explicit (user toggles rows on each visited page). Required acceptance test:
- Server mode, page 1: select row A.
- Navigate to page 2: select row B.
- Navigate back to page 1: row A still selected; page 2 visit retained B.
Expansion
- Same no server prune rule as selection.
- Detail
<tr>immediately after data<tr>.
Loading, empty, disabled, read-only, and error states
| State | Behavior |
|---|---|
loading | aria-busy="true" via tableRootProps |
| Empty body | GhostEmptyState when getRowModel() has no rows. rowCount === 0: pageCount 1, pageIndex 1. rowCount > 0 with an empty visible slice (page-local filter on server page 4): keep pageIndex, zero stateChange (aligned with recorded pagination reset acceptance). |
disabled | No emits from controls |
Async behavior
- User action → coalesced v-models + one
stateChange. - Consumer:
loading = true;begin(payload.requestId). - Apply
data/rowCount/erroronly ifisLatest(requestId). finallyblocks from stale requests must not clearloading, rows, totals, or error state for a newer in-flight or completed request (tie-break withrequestId, not wall-clock alone).
const request = useGhostDataTableServerRequest()
async function onStateChange({
requestId,
query,
}: DataTableStateChangePayload) {
request.begin(requestId) // synchronously, before any await
loading.value = true
try {
const page = await fetchInvoices(query)
if (!request.isLatest(requestId)) return
data.value = page.rows
rowCount.value = page.total
error.value = undefined
} catch (cause) {
if (request.isLatest(requestId)) error.value = cause
} finally {
if (request.isLatest(requestId)) loading.value = false
}
}Unit race tests for this loop (deferred responses resolved out of order, stale failure and stale finally, retry() superseding a pending request, and the filter-on-page-4 acceptance below) live in packages/vue/src/use-ghost-data-table.server-request.test.ts.
Required acceptance tests:
- With
manualFiltering: trueand server pagination on page 4, changing a filter produces exactly one fetch for page 1 with the new filter (stale page-4 response rejected). - With
manualFiltering: false(page-local) on page 4, changing a filter keeps page 4 and emits nostateChange.
Server state, URL, Back, and Retry
Consumer-owned fetching; the composable owns query state and request identity only. Pattern aligned with PrimeVue stateful tables.
| Concern | Contract |
|---|---|
| URL hydration | Applying sorting / columnFilters / globalFilter / pagination from a route or history.state on mount does not emit stateChange (no echo loop). Consumer may fetch once explicitly when the route is first entered. |
| One request per committed query | Each user-driven commit that changes the effective server query emits one stateChange → one consumer fetch. Retries are explicit consumer actions, not automatic duplicate emits. |
| Browser Back | While a fetch is pending, Back restores prior query props; composable bumps requestId; stale responses must not apply; only the latest requestId may mutate data, rowCount, loading, or error UI. |
| Retry | Call exposed retry() on the table/composable: re-emits stateChange with the same query and a new internal requestId (consumers cannot mint ids). Failed state stays visible until a successful response. |
Executable example: examples/data-table/server-invoices-router.vue — query string encoding sort, status filter, and page, read and written through a small router-style URL adapter (window.history by default; with Vue Router, read route.query and write with router.push). The workspace has no router dependency, so the example does not add one. It demonstrates open filtered URL → change sort → Back during pending request → Retry after error. Applying URL state is silent; the example fetches the restored query once through retry(), so Back mints a newer requestId and the pending response cannot apply. Tests: tests/integration/data-table-server-invoices-router-example.test.ts (single fetch per action, no hydration stateChange, both stale orders after Back, retry, server filter on page 4 → page 1 + one request) and tests/e2e/ghost-data-table-server-router.spec.ts (real browser Back). manualFiltering is table-wide, so the page-local filter case (page 4 → stay) is covered by the unit race tests rather than this server-filtered example.
Required tests: URL restore silent; sort+Back race; retry does not double-fetch; stale finally does not clear newest spinner; page-local vs server filter pagination.
Consumer data
getRowIdis required in all builds (development and production).- Prefer
accessorKey/accessorFn; optionalcellhook for custom VNodes. - Column
metais opaque to the composable.
Row identity
Stable getRowId across reorder, filter, and server page swaps. Server page changes must not clear ids merely because rows left the slice.
Accessibility contract
Semantics
- Native
<table>viaGhostTable. - Sort control:
button type="button"in header;aria-sorton<th>. - Selection:
GhostCheckboxper row and header; labels viaaria-label.
Keyboard interaction
| Key | Context | Behavior |
|---|---|---|
Space | GhostCheckbox | Toggle checked (checkbox-spec); Enter does not toggle |
Enter / Space | Sort button | Activate sort |
Enter / Space | Expand button | Toggle expansion |
Tab | Table | Between focusable controls |
Phase one: single-column sort only (no multi-sort chord).
Customization survival (PrimeVue accessibility notes): required browser test with a custom sort header (non-default label/icon): after Enter, focus remains on the sort button, parent <th> reflects new aria-sort. Expansion and selection use the typed prop helpers above so custom labels stay localized without dropping ARIA. aria-label, aria-expanded, and checkbox naming must land on the focusable control (native input / button), not wrapper-only — icon-only header cells need an accessible column name (prototype axe findings).
Focus when detail row collapses: if focus lies inside a detail row that collapses (toggle, filter, or allowMultipleExpanded), move focus to that row’s expansion button (the control from getRowExpandButtonProps). Required test with Playwright toBeFocused().
Assistive technology
- Mixed select-all: DOM
indeterminateon header checkbox (see checkbox spec). - Optional live region for async refetch: consumer-owned.
Rendering and customization
GhostTabledata-parthooks unchanged.- Header sort styling:
data-sort="asc" | "desc". - Selected row:
data-selected="true"onGhostTableRow(notdata-state). - Expanded data row:
data-expanded="true"on data<tr>. - Detail row:
GhostTableRowkeepsdata-part="row"frommergeGhostTablePartAttrs(consumer attrs cannot replacedata-part);detailRowPropsaddsdata-detail-row="true"for styling (.ghost-table-row[data-detail-row]). Do not setdata-part="detail"alone. - Selected and expanded may both be true on the data row.
Environment behavior
SSR and hydration
Deterministic markup for a given props snapshot; checkbox indeterminate via post-mount effect per checkbox spec.
Mobile and touch
GhostTable.containHorizontal for overflow.
Performance
- Local 10k-row processing with paginated DOM (O(pageSize) rows).
- Benchmark file:
tests/bench/data-table-processing.bench.ts. Run it withpnpm bench:data-table(not part ofpnpm verify). It times the sort and filter stages, the composable pipeline, and a mounted 25-row page at 1k, 5k, and 10k rows. - Proposed p95 < 25ms and heap delta < 5MB: informational until CI variance is understood; not a gate in phase one.
Deterministic regression checks (required in unit/integration tests):
| Scenario | Assertion |
|---|---|
| Page change after local sort | Comparator / sortFn not invoked again (zero additional sort passes). |
| Toggle selection on one visible row | Zero sort or filter callback invocations. |
These counters live in packages/vue/src/use-ghost-data-table.counters.test.ts (whole sort and filter passes, including the default comparator) and packages/vue/src/use-ghost-data-table.test.ts (consumer sortFn, filterFn, and accessor callbacks).
Proposed later task (not this PR): production-browser comparison on identical 10k Invoice rows, same three columns and page size, GhostVue vs PrimeVue DataTable, measuring input-to-paint for sort, filter, and row selection. Document methodology in docs/contributing/data-table-benchmark-comparison.md when scheduled; no PrimeVue dependency in the GhostVue repo.
Composition
Reuses GhostTable*, GhostPagination, GhostCheckbox, GhostEmptyState, useControllableState. Phase one shipped headless only; 0.1.0 themed wrappers in @ghostvue/themes compose over these exact headless primitives per the Themed GhostDataTable addendum.
Test plan
- Unit: manual-processing matrix, empty
rowCountpagination, coalescedstateChange, page-local vs global sort semantics. - Unit:
manualFiltering: truefilter on server page 4 → onestateChangeonly (triggerfilter +pageIndex: 1inquery); no follow-up paginationstateChangein the same action. - Unit: default filter contract (case, clear, OR/AND, omitted
filterFn, null cell skip). - Unit: server filter + local pagination selection survives filter cycle.
- Acceptance: local select-all over pre-pagination set (100 rows, page 25, 40 matches filter).
- Unit: server select-all uses
getRowModel()only (3-of-25 page-local filter). - Unit: local pruning uses source
datarows, not filtered view (select A, filter out A, refreshdata, clear filter). - Acceptance: cross-page selection test (pages 1 → 2 → 1).
- Playwright (approval fixture b): sort Amount;
Spaceon inv-2 checkbox;Spaceon inv-2 expand button (collapse then reopen); filter to zero;getByRole('heading', { name: 'No invoices' })visible; headers mounted. - Acceptance: filter on page 4 → single page-1 fetch; stale page-4 response ignored.
- Acceptance: server router example (URL hydrate, Back while pending, Retry).
- Unit:
useGhostDataTableServerRequestraces; stalefinallycannot clear loading. - Unit: performance regressions (page after sort, selection without sort/filter).
- Vue: basic (a) + full (b) examples hydrate;
GhostDataTableTableslot types. - Browser: custom sort header +
Enter; focus restore on detail collapse. - Acceptance (implementation gate): reference fixture ((b) and the preset (a′),
data-table/preset-invoices) — zero axe violations on the table scope (@axe-core/playwright), including labeled icon-only header/selection cells, sort buttons, expansion controls, search input, and co-locatedGhostPagination(no empty<th>, no wrapper-onlyaria-*without focusable names). - Type:
defineDataTableColumnsacceptance trio (toFixed,toUpperCaseerror, rename break). - Type: generic slot contexts still expose
getValue(): unknown.
Documentation plan
docs/components/data-table.mdwith (a) basic and (b) full paths first.examples/data-table/basic-invoices.vue,preset-invoices.vue,full-invoices.vue,server-invoices-router.vue.- Link ADR 0014 and prerequisites.
Compatibility and release impact
- Phase one exported from
@ghostvue/vueonly; the0.1.0themed addendum (#316 → #333) adds opt-in layout slots to@ghostvue/vueGhostDataTablePresetand themed exports in@ghostvue/themeswithout breaking phase-one consumers. - Changesets for
@ghostvue/vueand@ghostvue/themesship with Wave 2 implementation (#333); docs-only spec revisions (#316) have no runtime impact.
Themed GhostDataTable addendum
Status Approved by Zac in PR #374. Wave 2 implementation is tracked in #333.
Architectural decisions (2026-11-25 roadmap review, Zac)
- Single-sort scope for
0.1.0(decoupled from#317): ThemedGhostDataTableships in0.1.0on today's phase-one single-sort headless contract (aria-sort="ascending" | "descending"plusdata-sort="asc" | "desc"on the active<th>only, paired withgetSortButtonProps(columnId)on the native<button type="button">). Multi-column sort (#317) remains deferred to0.3.0on its independent spec track and no longer blocks#316or#333; any multi-sort priority badge in0.3.0will layer additively inside the sort header button without breaking0.1.0selectors or DOM contracts. - Composable themed architecture (ADR 0003 & ADR 0004):
- Headless preset layout slots (
@ghostvue/vue):GhostDataTablePresetgains camelCase layout slots#toolbarStart,#toolbarEnd,#bulkActions, and#footeralongside#search,#toolbar,#<columnId>, and#detail, with per-preset opt-in vialayoutSlotsinpackages/vue/src/ghost-data-table-preset.ts.@ghostvue/vueowns all layout structure, state wiring, and focus restoration; it never imports@ghostvue/themes. - Themed wrappers (
@ghostvue/themes): Exports themedGhostDataTable(size?: 'sm' | 'md',variant?: 'plain' | 'card',stickyHeader?: boolean),GhostDataTableTable, andGhostDataTablePreset(plus convenience re-exports ofdefineDataTableColumns,useGhostDataTable,useGhostDataTableServerRequest, the fivegetDataTable*Propshelpers, and public DataTable types) backed bypackages/themes/src/ghost-data-table.cssinside@layer ghostvue-theme. Per ADR 0004, visual customization uses ordinary props, slots,class/stylefallthrough,data-*hooks, and--ghost-*semantic tokens — neverptpassthrough style maps.
- Headless preset layout slots (
Headless GhostDataTablePreset layout slots (@ghostvue/vue)
Exact TypeScript contracts (packages/vue/src/ghost-data-table-preset.ts)
/** Props passed to `#bulkActions` while at least one row id is selected. */
export interface GhostDataTablePresetBulkActionsSlotProps {
/**
* Authoritative selected row ids from the parent `GhostDataTable` (includes
* preserved cross-page selections when `manualPagination` is `true`).
*/
selectedRowIds: readonly DataTableRowId[]
/** `selectedRowIds.length`. Always `>= 1` while `#bulkActions` renders. */
selectedCount: number
/**
* Clears every selected row id through the root's `resetRowSelection()`.
* Inert (no-op) while the parent `GhostDataTable` is `disabled` or
* `enableRowSelection` is `false`.
*/
clearSelection: () => void
}
/** Props passed to `#footer`, mirroring the root's pagination slot bindings. */
export interface GhostDataTablePresetFooterSlotProps {
/** Effective pagination (`pageIndex` 1-based, clamped to `[1, pageCount]`). */
pagination: DataTablePaginationState
/** Effective page count (`1` when `rowCount === 0`). */
pageCount: number
/**
* Query-wide row count (server `rowCount` when `manualPagination` is `true`;
* filtered local count otherwise).
*/
rowCount: number
/**
* Commits a page change through the root: clamps, writes `v-model:pagination`,
* and emits one `stateChange` when `manualPagination` is `true`.
*/
setPageIndex: (pageIndex: number) => void
}
/** Select the new regions that this preset owns on this instance. */
interface GhostDataTablePresetLayoutSlots {
toolbarStart?: () => unknown
toolbarEnd?: () => unknown
bulkActions?: (props: GhostDataTablePresetBulkActionsSlotProps) => unknown
footer?: (props: GhostDataTablePresetFooterSlotProps) => unknown
/** Empty-state description while no rows render (amendment below). */
emptyDescription?: () => unknown
/** Empty-state actions while no rows render (amendment below). */
emptyActions?: () => unknown
}
type LayoutSlotName = keyof GhostDataTablePresetLayoutSlots
// Addition to GhostDataTablePresetProps<TColumns, TLayout = never>:
// layoutSlots?: readonly TLayout[]
// Infer TLayout from this prop alone. Omission and [] opt into no regions.
export type GhostDataTablePresetSlots<
TColumns extends readonly DataTableTableColumnRef[],
TLayout extends LayoutSlotName = never,
> = Omit<GhostDataTableTableSlots<TColumns>, NoInfer<TLayout>> &
Pick<GhostDataTablePresetLayoutSlots, NoInfer<TLayout>> & {
/** Content of an expanded row's detail `<tr>` (one cell spanning the row). */
detail?: (
props: GhostDataTablePresetDetailSlotProps<
DataTableColumnRow<TColumns[number]>
>,
) => unknown
/** Unopinionated region rendered before the header bar and table. */
toolbar?: () => unknown
/** Replaces the default search field (for example to debounce input). */
search?: (props: GhostDataTablePresetSearchSlotProps) => unknown
}Root context and slot ownership
GhostDataTableContext(packages/vue/src/ghost-data-table-table.ts) addsselectedRowIds: () => readonly DataTableRowId[]andresetRowSelection: () => voidfrom the rootuseGhostDataTableinstance;#footerreadspagination,pageCount,rowCount, andsetPageIndexthrough the existingwithBindingsbridge so manual#defaultand preset#footercan never drift.- By default the preset owns only
detail,toolbar, andsearch. Each of the layout names remains available to the existing cell renderer. For example, a column namedfootercalls#footer="{ value }"once per row, including after a reorder, an empty result, or an asynchronous column insert. - To supply layout content, opt into its names on the preset, e.g.
:layout-slots="['toolbarEnd', 'bulkActions']". These two names belong to layout on this instance, leaving#footeravailable for cells. An enabled name is reserved even while its region is hidden or its slot is absent. For a column with that same id, use itscellhook or ordinary value fallback. A slot function is invoked in exactly one role. - Resolve ownership from the opt-in list before testing slot presence for chrome and before cell lookup. Row count, column visibility, order, and selection never change that decision. Both presets expose the same prop and slot types.
Preset DOM order and conditional regions
GhostDataTablePreset renders only the chrome regions that have active content, in strict top-to-bottom DOM order. Below, layout contains only the slots selected by layoutSlots and supplied by the consumer:
- Legacy pre-header slot (
#toolbar): rendered as-is before the header bar when$slots.toolbaris present, preserving exact phase-one markup order for existing consumers. - Header bar (
<div data-part="header" class="ghost-data-table-header">): rendered iffsearchVisible || layout.toolbarStart || layout.toolbarEnd.<div v-if="layout.toolbarStart" data-part="toolbar-start">wrapping<slot name="toolbarStart" />.<div v-if="searchVisible" data-part="search">wrapping<slot name="search" v-bind="searchSlotProps">(default labelledGhostInput type="search"). Keeping[data-part="search"]as a sibling of[data-part="toolbar-start"]and[data-part="toolbar-end"]preserves the phase-one accessibility invariant: the search input remains its ownTabstop outside any consumerGhostToolbar(role="toolbar").<div v-if="layout.toolbarEnd" data-part="toolbar-end">wrapping<slot name="toolbarEnd" />.
- Bulk-actions bar (
<div data-part="bulk-actions" class="ghost-data-table-bulk-actions">): rendered iffrowSelectionEnabled && selectedCount > 0 && layout.bulkActions, wrapping<slot name="bulkActions" v-bind="bulkActionsSlotProps" />. Norole="alert"oraria-liveis placed on this container (row and header checkboxes already announce checked state changes). - Table (
<GhostTable v-bind="tableProps">): fallthrough attributes (class,style,contain-horizontal,scroll-label,aria-label) onGhostDataTablePresetcontinue to forward ontoGhostTableexactly as in phase one. Sortable headers in bothGhostDataTableTableandGhostDataTablePresetexpose the native button viadata-part="sort-button". The headless button renders its header label and retains its focus and interaction bindings. Its accessible name is the same in either package. Row expand buttons inGhostDataTablePresetadddata-part="expand-button". - Footer bar (
<div data-part="footer" class="ghost-data-table-footer">): rendered ifflayout.footeris present, wrapping<slot name="footer" v-bind="footerSlotProps" />.
Empty-state layout slots (amendment, approved)
Important
Approved amendment. This subsection adds emptyDescription and emptyActions to the layout slots above. The maintainer @zprue743 approved it in PR review on 2026-12-03.
Apps need to put a description and recovery actions, such as Clear filters, in the preset's empty row, not only the emptyTitle string. Column ids are slot names on the preset, so a bare #empty slot would collide with a column named empty. The two names follow the layout-slot rule instead:
emptyDescription?: () => unknownandemptyActions?: () => unknownjoinGhostDataTablePresetLayoutSlotsand take no slot props. They are available only when listed inlayoutSlots. Without the opt-in, a column with idemptyDescriptionoremptyActionskeeps its typed cell slot, and the empty row renders exactly as before.- While
rows.length === 0, the single body row keeps its one<td colspan>spanning every rendered column, holding oneGhostEmptyState. Its #title is stillemptyTitleatemptyHeadingLevel, so the row has exactly one heading. An enabled, suppliedemptyDescriptionrenders into the empty state's #description (data-part="description") andemptyActionsinto #actions (data-part="actions"). An enabled name without a slot leaves that part unmounted. - The slots are invoked only while the empty row renders. Focus inside them follows DOM order after the header controls. When an action brings rows back, the empty row and its content unmount; the consumer moves focus to a control that stays mounted (the docs example focuses the search field).
- GhostEmptyState itself is unchanged. The themed preset forwards both slots unchanged and styles them through the existing themed empty-state parts.
Themed wrappers and exports (@ghostvue/themes)
Public exports
@ghostvue/themes exports:
| Export | Source | Contract |
|---|---|---|
GhostDataTable | packages/themes/src/ghost-data-table.ts | Generic <TData> themed root wrapper adding size, variant, and stickyHeader over headless GhostDataTable. |
GhostDataTableTable | packages/themes/src/ghost-data-table-table.ts | Generic <TColumns> themed table mapper preserving typed #<columnId> slots. |
GhostDataTablePreset | packages/themes/src/ghost-data-table-preset.ts | Generic <TColumns> themed preset preserving typed #<columnId>, #detail, and all camelCase layout slots. |
defineDataTableColumns | re-export from @ghostvue/vue | Single-import convenience for typed column definitions. |
useGhostDataTable | re-export from @ghostvue/vue | Headless state composable for custom layouts alongside themed parts. |
useGhostDataTableServerRequest | re-export from @ghostvue/vue | Monotonic requestId guard for async server tables. |
getDataTable*Props (all 5 interaction helpers) | re-export from @ghostvue/vue | Attribute helpers for manual GhostTable* composition inside themed GhostDataTable. |
GhostDataTableSize, GhostDataTableVariant, … | packages/themes + @ghostvue/vue type exports | Visual prop unions, GhostDataTableThemedProps<TData>, GhostDataTableThemedExposed<TData>, and DataTable*. |
Themed GhostDataTable props and host contract
export type GhostDataTableSize = 'sm' | 'md'
export type GhostDataTableVariant = 'plain' | 'card'
export interface GhostDataTableThemedProps<
TData,
> extends GhostDataTableProps<TData> {
/**
* Cell padding, typography, and embedded control density. Default `'md'`
* omits `data-size` so CSS treats an absent hook as `'md'`.
* @default 'md'
*/
size?: GhostDataTableSize
/**
* Outer surface treatment. `'plain'` omits `data-variant` (flush rules only);
* `'card'` sets `data-variant="card"` for an elevated bordered container.
* @default 'plain'
*/
variant?: GhostDataTableVariant
/**
* Pins column headers (`thead th`) to the block start of the nearest scroll
* container (`data-sticky-header` when `true`, omitted when `false`).
* @default false
*/
stickyHeader?: boolean
}
export interface GhostDataTableThemedExposed<
TData,
> extends GhostDataTableExposed<TData> {
/** Outer `.ghost-data-table` wrapper element after mount. */
readonly element: HTMLElement | null
}Wrapper invariants:
- Real host element for visual hooks: Headless
GhostDataTableis renderless (<slot v-bind="slotProps" />), whereas themedGhostDataTablerenders a single outer<div class="ghost-data-table ghost-themed-scope" data-part="root" data-themed>around the headless root. Including.ghost-themed-scopeon the host automatically themes every nested Ghost primitive rendered inside the table (GhostTable,GhostCheckbox,GhostInput,GhostEmptyState, and a co-locatedGhostPagination) without requiring@ghostvue/vueto import@ghostvue/themes. ariaLabel/ariaLabelledbyrouting (axearia-prohibited-attrguard):ariaLabelandariaLabelledbyare declared props forwarded exclusively to the inner headlessGhostDataTable(landing on the native<table>viatableRootProps). They must never be duplicated onto the outer generic<div class="ghost-data-table">, which has no ARIA role.- Attribute merge and generics: Consumer
class,style, and other non-prop attributes merge onto.ghost-data-tablewithout overwritingghost-data-table,ghost-themed-scope,data-part="root", ordata-themed. GenericdefineComponentsignatures inpackages/themes/src/ghost-data-table*.tsmust preserve<TData>onGhostDataTableand<TColumns extends readonly DataTableTableColumnRef[]>onGhostDataTableTableandGhostDataTablePresetundertscdeclaration emit andvue-tsc. - Standalone themed child wrappers: Themed
GhostDataTableTableand themedGhostDataTablePresetalso wrap or mark their output with.ghost-themed-scope(display: contentswhen wrapping) anddata-themed=""so they render themed even when placed inside a headlessGhostDataTablefrom@ghostvue/vue.
Worked themed example
<script setup lang="ts">
import { ref } from 'vue'
import {
GhostButton,
GhostDataTable,
GhostDataTablePreset,
GhostPagination,
defineDataTableColumns,
type DataTableRowId,
} from '@ghostvue/themes'
interface Invoice {
id: string
customer: string
amount: number
}
const helper = defineDataTableColumns<Invoice>()
const columns = [
helper.accessorKey('customer', { header: 'Customer' }),
helper.accessorKey('amount', { header: 'Amount' }),
]
const invoices = ref<Invoice[]>([
{ id: 'inv-1', customer: 'ACME Corp', amount: 1200 },
{ id: 'inv-2', customer: 'Globex', amount: 980.5 },
])
const globalFilter = ref('')
const selectedRowIds = ref<DataTableRowId[]>([])
const pagination = ref({ pageIndex: 1, pageSize: 10 })
</script>
<template>
<GhostDataTable
v-model:global-filter="globalFilter"
v-model:selected-row-ids="selectedRowIds"
v-model:pagination="pagination"
:data="invoices"
:columns="columns"
:get-row-id="(row) => row.id"
enable-row-selection
enable-row-expansion
variant="card"
size="sm"
sticky-header
aria-label="Invoices"
>
<GhostDataTablePreset
:columns="columns"
:layout-slots="['toolbarEnd', 'bulkActions', 'footer']"
empty-title="No matching invoices"
search-label="Search invoices"
>
<template #toolbarEnd>
<GhostButton size="sm" variant="outline" tone="neutral">
Export CSV
</GhostButton>
</template>
<template #bulkActions="{ selectedCount, clearSelection }">
<span>{{ selectedCount }} selected</span>
<GhostButton
size="sm"
variant="ghost"
tone="neutral"
@click="clearSelection"
>
Clear selection
</GhostButton>
</template>
<template #amount="{ value }">{{ value.toFixed(2) }} USD</template>
<template #detail="{ row }">Invoice {{ row.id }} line items</template>
<template
#footer="{ pagination: page, pageCount, rowCount, setPageIndex }"
>
<span>{{ rowCount }} total</span>
<GhostPagination
size="sm"
:model-value="page.pageIndex"
:page-count="pageCount"
aria-label="Invoice pages"
@update:model-value="setPageIndex"
/>
</template>
</GhostDataTablePreset>
</GhostDataTable>
</template>Styling hooks and CSS architecture (packages/themes/src/ghost-data-table.css)
Complete data-* and ARIA styling-hook map
| Surface | Selector / attribute | Condition / values |
|---|---|---|
| Themed root container | .ghost-data-table[data-themed], data-part="root" | Always on themed GhostDataTable; carries .ghost-themed-scope |
| Root density | data-size="sm" | Set when size === 'sm'; omitted for default 'md' |
| Root surface variant | data-variant="card" | Set when variant === 'card'; omitted for default 'plain' |
| Root sticky header | data-sticky-header="" | Set when stickyHeader === true; omitted when false |
| Root disabled state | data-state="disabled" | Set on themed root when disabled === true; omitted otherwise |
| Preset header bar | .ghost-data-table-header, data-part="header" | Rendered for visible search or a supplied, enabled toolbar slot |
| Preset header slots | data-part="toolbar-start", "search", "toolbar-end" | Direct children of [data-part="header"] when respective slot/search on |
| Preset bulk-actions bar | .ghost-data-table-bulk-actions, data-part="bulk-actions" | Rendered for enabled bulkActions with a slot and a nonempty enabled selection |
| Preset footer bar | .ghost-data-table-footer, data-part="footer" | Rendered when footer is enabled and supplied |
| Table root | table.ghost-table[data-ghost-data-table], data-part="root" | Native <table> (aria-busy="true" while loading, omitted otherwise) |
| Column header cell | th.ghost-table-header-cell, data-part="header-cell" | scope="col"; aria-sort + data-sort="asc" | "desc" on sorted column |
| Sort button | button[data-part="sort-button"] | Sortable <th> control in GhostDataTableTable / GhostDataTablePreset |
| Default sort indicator | Themed sort button ::after | Decorative CSS mark painted by @ghostvue/themes |
| Expand button | button[data-part="expand-button"] | Row disclosure toggle (aria-expanded="true" | "false") |
| Selected data row | tr.ghost-table-row[data-selected="true"] | Boolean hook on selected body row (omitted when unselected) |
| Expanded data row | tr.ghost-table-row[data-expanded="true"] | Boolean hook on expanded body row (independent of data-selected) |
| Detail row | tr.ghost-table-row[data-detail-row="true"] | Expansion detail <tr> (data-part="row" retained) |
Cascade layer, opt-in scoping, and child-combinator isolation
- Zero specificity inside
@layer ghostvue-theme: Every rule inpackages/themes/src/ghost-data-table.csssits inside@layer ghostvue-themewrapped in:where(...)(keeping pseudo-elements such as::afteroutside:where(...)so LightningCSS preserves them). Consumer classes and scoped styles win without!important. - Headless isolation: Rules must key off
.ghost-data-table[data-themed],.ghost-data-table-preset[data-themed],.ghost-table[data-ghost-data-table][data-themed], or.ghost-theme .ghost-data-table— never bare[data-ghost-data-table]— because@ghostvue/themesCSS loads globally on docs and playground pages that also render unstyled headless DataTable examples. - Child-combinator part targeting: Table section, row, cell, and header button selectors must step through direct child combinators (
> .ghost-table,> :is(.ghost-table-scroll-container) > .ghost-table,> .ghost-table-head > .ghost-table-row > .ghost-table-header-cell,> .ghost-table-body > .ghost-table-row > :is(.ghost-table-cell, .ghost-table-header-cell)). A nestedGhostTablerendered inside an expanded#detailpanel or custom cell must not inherit outerdata-selected,data-sticky-header,data-size="sm", or sort-header rules. - Variant and density token mapping:
variant="plain"(default): vertical flex/grid stack (gap: var(--ghost-space-gap-md)), flush borders fromghost-table.css.variant="card"([data-variant='card']):--ghost-elevation-1-bg,var(--ghost-border-hairline-width) solid var(--ghost-elevation-1-border),border-radius: var(--ghost-radius-lg),box-shadow: var(--ghost-elevation-1-shadow), var(--ghost-elevation-1-highlight).[data-part="header"],[data-part="bulk-actions"], and[data-part="footer"]use inset padding (--ghost-space-inset-sm/--ghost-space-inset-md) and hairline block dividers (--ghost-border-default) flush with the table edges.size="sm"([data-size='sm']): table font-size--ghost-type-size-sm, header/body cell padding--ghost-space-inset-xsblock and--ghost-space-inset-sminline, and--ghost-control-size-sm-*sizing on sort/expand controls and default preset search input (preserving--ghost-control-touch-minon coarse pointers).stickyHeader([data-sticky-header]): setsposition: sticky; inset-block-start: 0; z-index: 1on column header cells (thead > .ghost-table-row > .ghost-table-header-cell) with opaque--ghost-surface-muted-bg(Canvasinforced-colors: active) and an inset block-end hairlinebox-shadow(inset 0 calc(-1 * var(--ghost-border-hairline-width)) 0 var(--ghost-border-default)) so header dividers stay visible over scrolled rows underborder-collapse: collapse.
Single-sort header button indicator (0.1.0)
- Interactive target:
.ghost-table-header-cell > button(covering both[data-part="sort-button"]inGhostDataTableTable/GhostDataTablePresetand manual<button v-bind="getSortButtonProps(id)">compositions) fills the header cell inline axis (display: inline-flex,align-items: center,gap: var(--ghost-space-gap-xs)) with the label and the mark packed together at the start. The button overhangs the cell's content box by its own inline padding (inline-size: calc(100% + 2 * var(--ghost-space-inset-xs)),margin-inline: calc(-1 * var(--ghost-space-inset-xs))), so the label starts on the same edge as the column's cell text. It inherits semibold header typography, resets native button chrome (appearance: none; border: 0; background: transparent), and applies a hover state layer (color-mix(in oklch, var(--ghost-surface-fg) calc(100% * var(--ghost-state-layer-hover)), transparent)) when:not(:disabled). - Focus ring:
:focus-visibledrawsoutline: var(--ghost-focus-ring-width) solid var(--ghost-focus-ring-color)withoutline-offset: calc(-1 * var(--ghost-focus-ring-width))inside the button box so adjacent<th>borders,overflow-x: autoscroll containers, andstickyHeader: truenever clip the indicator. - Default artwork belongs to
@ghostvue/themes(ADR 0013). In the themed table scope, paint a decorative mark on the sort button's::afterwith empty CSS content andcurrentColor. Use the parentth[data-sort]to distinguish the unsorted bidirectional mark from the ascending and descending chevrons. Size it with--ghost-action-icon-size. The unsorted mark uses--ghost-text-subtleand strengthens on hover or focus. Sorted headers use--ghost-surface-fgtext, a--ghost-text-primarymark, and an accent bottom border. In forced colors keep the direction visible inButtonText(GrayTextwhen disabled) and draw the focus outline inHighlight. The header'saria-sortcommunicates direction to assistive technology. The CSS adds no text to the button's accessible name. - Apply the default only to a sort control with the
data-part="sort-button"hook. Manual compositions can opt in on their button. A consumer-supplied decorative child markeddata-part="sort-indicator"suppresses the default on that button. Bare headless renderers supply the hook and label only. Loading the stylesheet outside a themed scope leaves them unadorned.
Row selection wash and forced-colors SelectedItem mapping
- Standard light and dark mode wash:
- Applied to direct cells of selected data rows (
> .ghost-table-body > .ghost-table-row[data-selected='true'] > :is(.ghost-table-cell, .ghost-table-header-cell)):background-color: color-mix(in oklch, var(--ghost-action-primary-bg) calc(100% * var(--ghost-state-mix-soft)), var(--ghost-surface-bg))withcolor: var(--ghost-surface-fg). Pairing--ghost-surface-fgagainst the soft primary mix preserves WCAG 2 AA (>= 4.5:1) text contrast acrossdefault,calm,vibrant, andmonoin both light and dark modes. - Hover layering: Unselected body rows (
:not([data-selected='true']):not([data-detail-row])) apply--ghost-surface-subtle-bgon:hover(when the table is not disabled). Selected rows deepen slightly on:hoverby combining--ghost-state-mix-softwith--ghost-state-layer-hoverso pointer tracking remains visible across selected runs. - Non-color distinction: Selection is never conveyed by row tint alone: the checked
GhostCheckboxprovides explicit state and shape, and the first cell (:first-child) carries an inset inline-start accent bar (box-shadow: inset var(--ghost-focus-ring-width) 0 0 var(--ghost-border-primary)in LTR; mirrored in RTL via logicalborder-inline-startordir-aware inset shadow without shifting cell width). - Bulk-actions bar & detail rows:
[data-part="bulk-actions"]uses the same soft primary surface tint (--ghost-surface-muted-bg/ soft primary mix with--ghost-surface-fgtext). Detail rows (tr.ghost-table-row[data-detail-row='true'] > .ghost-table-cell) use--ghost-surface-subtle-bgso expanded content reads as an inset panel distinct from selected data rows.
- Applied to direct cells of selected data rows (
@media (forced-colors: active)(SelectedItem/SelectedItemText):- Windows Contrast Themes strip
color-mix(...)washes back toCanvas. To preserve row-level selection visibility across wide tables, direct cells of selected data rows (> .ghost-table-body > .ghost-table-row[data-selected='true'] > :is(.ghost-table-cell, .ghost-table-header-cell)) map explicitly to CSS Color 4 system selection colors:background-color: SelectedItem;color: SelectedItemText;border-block-end-color: CanvasText;forced-color-adjust: none;on the selected cell surface so the user agent does not backplate cell text withCanvas.
- Nested interactive controls inside
SelectedItemrows: Interactive descendants inside selected cells (button,input,select,textarea,a[href],[tabindex]:not([tabindex='-1'])) restore system control painting (forced-color-adjust: auto, or explicitButtonFace/ButtonTexton themed buttons/checkboxes andLinkTexton links), and:focus-visibleoutlines drawn directly against aSelectedItemcell background useoutline-color: SelectedItemTextso keyboard focus never disappears into the selected row fill.
- Windows Contrast Themes strip
[aria-busy="true"] loading behavior
- Semantic contract: Passing
:loading="true"toGhostDataTablesetsaria-busy="true"on<table data-ghost-data-table>viatableRootProps(omitted whenloadingisfalse). - In-place visual feedback without focus loss:
- While
table[data-ghost-data-table][aria-busy='true']is present, mounted<thead>and<tbody>rows stay in the DOM at their current geometry (zero height collapse or column reflow). - Keep body text, backgrounds, and enabled controls at their resting contrast throughout loading. Keep the body at full opacity in every theme and mode. Show progress with a block-end accent hairline on the header. It may animate under
prefers-reduced-motion: no-preference. Keep it static underprefers-reduced-motion: reduceand useHighlightin forced colors.
- While
- Interaction invariant during
loading:aria-busy="true"must not setdisabled,inert, orpointer-events: noneon sort buttons, search inputs, checkboxes, expand buttons, or pagination controls unless:disabled="true"is also passed. Keeping controls focusable and operable while a fetch is in flight prevents focus from dropping to<body>after a keyboard sort/filter commit and preserves superseding queries guarded byuseGhostDataTableServerRequest()(including Browser Back andretry()). - Initial empty load & live announcements: For first-load empty tables (
data.length === 0 && loading), consumers may renderGhostSkeletonrows in manual compositions (perGhostSkeleton), whileGhostDataTablePresetkeeps<thead>mounted witharia-busy="true"on<table>. Async completion announcements remain a consumer-owned polite live region (role="status"), neveraria-liveon<table>or<tbody>.
Keyboard, focus parity, RTL, touch, and motion
- Exact keyboard parity with headless
@ghostvue/vue: Native<table>semantics only (norole="grid"or arrow-key cell roving).Tab/Shift+Tabtraverses in DOM order:#toolbarStart→#search(independentTabstop) →#toolbarEnd→#bulkActions(whenselectedCount > 0) → named horizontal scroll container (only whencontainHorizontalistrue) → header select-allGhostCheckbox→ sortable header<button>s → body row checkboxes, expand<button>s, cell controls, and expanded#detailcontrols →#footer(GhostPagination).Spacetoggles checkboxes (Enterdoes not);EnterandSpaceactivate sort and expand buttons. - Focus restoration invariants (both required in browser tests):
- Detail row collapse: When an expanded row collapses while
document.activeElementis inside its#detailrow, focus moves to that row's expand<button>(useDataTableDetailRowFocus). - Bulk-actions dismissal: When
[data-part="bulk-actions"]unmounts becauseselectedCounttransitions from> 0to0(for example, the user activates a "Clear selection" button wired toclearSelection()) whiledocument.activeElementis inside[data-part="bulk-actions"],GhostDataTablePresetmoves focus onnextTickto the table's header select-all checkbox input (when mounted and not disabled) so focus is never stranded ondocument.body.
- Detail row collapse: When an expanded row collapses while
- RTL, touch targets, and reduced motion:
ghost-data-table.cssuses CSS logical properties (inline-size,block-size,padding-inline,padding-block,border-block-end,border-inline-start,inset-block-start,text-align: start) sodir="rtl"mirrors layout, sort-button alignment, and selection indicators with zero physicalleft/rightoverrides.- Sort buttons, expand buttons, checkboxes, and default preset inputs respect
--ghost-control-touch-min(2.75remon coarse pointers via semantic control tokens). - Transitions use
--ghost-action-duration/--ghost-motion-fade-durationand disable non-essential motion under@media (prefers-reduced-motion: reduce).
Wave 2 (#333) acceptance tests and component-gate checklist
Wave 2 implementation (#333) must satisfy every check below alongside existing phase-one tests:
- Headless
GhostDataTablePresetunit & type tests (@ghostvue/vue):- Enable each layout slot being exercised through
layoutSlots.#toolbarStartand#toolbarEndrender inside[data-part="header"]before and after[data-part="search"];[data-part="header"]omits when search is hidden and both toolbar slots are absent; default search stays outside anyrole="toolbar". #bulkActionsstays unmounted whenselectedCount === 0orenableRowSelection === false, mounts whenselectedCount > 0, receives{ selectedRowIds, selectedCount, clearSelection }(including cross-page ids whenmanualPagination: true),clearSelection()clears selection (and is a no-op whendisabled: true), and activatingclearSelection()while focused inside[data-part="bulk-actions"]moves focus to the header select-all checkbox.#footerreceives{ pagination, pageCount, rowCount, setPageIndex }andsetPageIndexcommits through the root (v-model:pagination+ singlestateChangewhenmanualPagination: true).- In both presets, parameterize compatibility cases over
toolbarStart,toolbarEnd,bulkActions,footer,emptyDescription, andemptyActions. With the prop omitted, a slot matching a column id receives only its original typed cell context. Verify a legacy numeric#footer="{ value }"can callvalue.toFixed(2)and renders once per row. Start with no columns, insert the column, reorder it, then remove it. No layout region mounts or invokes that slot. - With only
bulkActionsenabled, keep the collidingfootercell slot while showing and dismissing the selection bar. Withfooterexplicitly enabled, check its typed pagination props and one footer invocation per render. A column namedfooteruses itscellhook or value fallback. Use positive and negativevue-tscfixtures for the two slot signatures.
- Enable each layout slot being exercised through
- Themed wrapper unit, SSR, export, and generic type tests (
@ghostvue/themes):GhostDataTablerenders.ghost-data-table.ghost-themed-scope[data-part="root"][data-themed]; defaults (size="md",variant="plain",stickyHeader=false,disabled=false) omitdata-size,data-variant,data-sticky-header, anddata-state; non-defaults setdata-size="sm",data-variant="card",data-sticky-header="", anddata-state="disabled".ariaLabelandariaLabelledbyrender on the native<table>only (never on.ghost-data-table).- Consumer
classandstylemerge cleanly onGhostDataTable,GhostDataTableTable, andGhostDataTablePreset; all sixv-models,stateChange, and all 16GhostDataTableExposed<TData>methods pluselementwork through a template ref. @ghostvue/themesre-exportsGhostDataTable,GhostDataTableTable,GhostDataTablePreset,defineDataTableColumns,useGhostDataTable,useGhostDataTableServerRequest, the fivegetDataTable*Propshelpers, and public types (pnpm published-exportsandpnpm exports:checkgreen).- Generic
vue-tsctype tests for@ghostvue/themesverifydefineDataTableColumns<Invoice>()column cell slot typing (value.toFixed(2)valid,@vue-expect-erroronvalue.toUpperCase()), typed#detail="{ row }",#bulkActions, and#footer. expectSsrHydrationpasses with zero warnings on themedGhostDataTable+GhostDataTablePresetwith sort, selection, expansion,#toolbarStart,#toolbarEnd,#bulkActions, and#footer.- Headless isolation check: mounting
@ghostvue/vueGhostDataTableon a page where@ghostvue/themesCSS is loaded applies no[data-themed]hook or themed wrapper element. For both headless renderers verify a sortable header has the button hook and accessible label with no default artwork. In the themed equivalents check all three visual sort states, identical accessible names, and suppression of the CSS mark when a manual sort button supplies its own decorative indicator.
- Browser (
Playwright), accessibility (@axe-core/playwright), andforced-colorstests:- Keyboard and real focus (
toBeFocused()): fullTabtraversal across#toolbarStart,#search,#toolbarEnd,#bulkActions, select-all checkbox, sort buttons, row checkboxes, expand buttons, and#footerGhostPagination;EnterandSpacecycle single-sort (none → asc → desc → none) while focus stays on the sort<button>andaria-sort/data-sortupdate on<th>;Spacetoggles row selection (data-selected="true"); collapsing an open#detailrow from inside restores focus (toBeFocused()) to the row expand button; activatingclearSelectioninside#bulkActionsrestores focus (toBeFocused()) to the header select-all checkbox. [aria-busy="true"]loading parity: toggling:loading="true"setsaria-busy="true"on<table>, keeps rows and headers mounted without droppingtoBeFocused()from an active sort button or search input, and still permits superseding query actions. In each preset theme, light and dark, measure busy-state body text and enabled control text against their composited backgrounds (at least 4.5:1 for normal text). Include a selected row and a focused control. Require at least 3:1 against adjacent colors for the visual cues identifying enabled controls and their focus. Verify the body stays at full opacity and the header cue respects reduced motion.- Forced-colors verification (
page.emulateMedia({ forcedColors: 'active' })): selected row cells (tr[data-selected="true"] > td) resolve computedbackgroundColorandcolortoSelectedItemandSelectedItemText(distinct from unselected rows), and a focused control inside a selected row retains a contrasting visible outline. - RTL verification (
dir="rtl"): logical layout and sort/selection chrome mirror without horizontal overflow or clipped focus rings. - Zero
@axe-core/playwrightviolations acrossplainandcardvariants,smandmdsizes,stickyHeader, selected + expanded rows,aria-busy="true", and empty states in light and dark modes. - Linux container visual baselines updated via
pnpm test:visual:docker.
- Keyboard and real focus (
- Manifests, registries, docs, and release metadata (
#333):- Update
docs/components/data-table-spec.mdfrontmatter (packagesadds'@ghostvue/themes',manifestsaddspackages/themes/manifests/ghost-data-table*.manifest.json, andapproval.evidencerecords Zac's#316approval). - Run
pnpm manifests:writeandpnpm registries:write; add themed examples inexamples/data-table/andpackages/vue/registry/data-table.registry.json; document themed usage and preset slots indocs/components/data-table.md; update only the DataTable row indocs/roadmap.md; include minor Changesets for@ghostvue/vueand@ghostvue/themes.
- Update
Decisions recorded (Zac, PR #265 review)
| Topic | Decision |
|---|---|
| Architecture | Option A: composable + native GhostTable |
getRowId | Required in every build |
| Filter debouncing | Consumer-owned |
Themed GhostDataTable | Not in phase one; headless examples first |
| Benchmark thresholds | Informational until repeated CI runs show variance |
Server stateChange | One emit per user action with full query |
| Local select-all | getPrePaginationRowModel() (all filtered rows, not current page only) |
| Server selection | No prune on page change; select-all = getRowModel() visible subset |
| Filtering defaults | Case-insensitive OR global / AND column; clear ''/null/undefined; skip null/undefined cell values in text match |
| Filter pagination reset | page → 1 only when manualFiltering: true; page-local filter keeps page |
| Selection pruning | Auto-prune only when both manualPagination and manualFiltering are false (source data change) |
| Full-local filter clamp | Keep pageIndex, then clamp to last valid page when filtered count shrinks (Zac, post-rebase) |
pageIndex clamping | After pageCount changes, clamp when pageIndex > pageCount; rowCount === 0 → page 1 |
Local data refresh | Clamp pageIndex on data reference change; do not reset to page 1 unconditionally |
| Server Retry | Expose retry() — one stateChange with same query, new internal requestId |
| Server clamp fetch | When server pageCount forces pageIndex down, one stateChange with clamped pagination |
| Preset LOC | GhostDataTablePreset keeps invoice-parity apps ≤ 95 non-blank consumer lines with typed columns |
| Reference axe | Zero violations on reference fixture table scope (implementation acceptance) |
Naming decisions kept before 1.0 (zprue743, 2026-12-01)
App-builder feedback on 0.2.0 flagged two names that work as specified but surprised a first-time user. Both are kept as specified, with no rename and no deprecation path. The DataTable page explains each where a reader first meets it.
| Topic | Decision |
|---|---|
| Preset toolbar slots | Kept. #toolbar stays always on; #toolbarStart and #toolbarEnd stay opt-in through layoutSlots so a column id can never collide with a layout region. A single toolbar API with namespaced column slots (#cell:status) was considered and not adopted. The preset layout slots section explains the opt-in before the first toolbar example. |
pageIndex is 1-based | Kept. pagination.pageIndex stays 1-based to match GhostPagination, and is not renamed to page or pageNumber. The guide states "1-based" where pageIndex first appears and in the pagination and defaultPagination prop descriptions. |
Open architectural questions
The benchmark thresholds remain informational until CI variance supports promoting them to gates in pnpm verify.
Side-by-side results (PrimeVue prototype)
Gate status: Exercise completed (throwaway prototype, PR #269, prototypes/datatable-primevue/FINDINGS.md). This evidence did not auto-approve the spec; Zac approved in chat on 2026-11-23 (recorded in PR #272) to promote it to specStatus: approved.
| Dimension | Finding |
|---|---|
| Consumer LOC | Manual headless (b) was 171 vs Prime 95; GhostDataTablePreset (a′) targets ≤ 95 with ~44 lines in the spec example — better than Prime on LOC when using the preset path |
| Typing | Ghost exceeds Prime: defineDataTableColumns catches amount.toFixed / rejects toUpperCase; Prime field strings do not catch renamed keys at compile time |
| Behavior | Ghost exceeds Prime: coalesced stateChange, page-local page 4, local getPrePaginationRowModel() select-all — intentional, not Prime defaults (page-scoped select-all, paginator reset on filter). |
| a11y | Keyboard approval script passes; implementation must hit zero axe on the reference fixture (stricter than prototype stub run). |
| Perf (informational) | Stub harness ~15–62ms sort/filter at 1k–10k rows; directional only, not CI gates |
Prototype uses local stubs, not shipped @ghostvue/vue; numbers validate spec intent, not production bundle performance.
Child work decomposition
| Child issue | Scope | Complexity |
|---|---|---|
| Done: GhostVue vs PrimeVue prototype (PR #269) | Evidence folded into spec; prototype PR closed unmerged | — |
| DataTable core types and local processing pipeline | useGhostDataTable, manual matrix, row models | High |
defineDataTableColumns + column type tests | Typed value / getValue, CI type tests | Medium |
GhostDataTableTable default renderer | Basic example (a), #columnId slots | Medium |
GhostDataTablePreset (invoice parity, ≤95 LOC) | Example (a′), wired a11y + interaction helpers | Medium |
| GhostDataTable headless root and GhostTable composition | Slot bindings, example (b), SSR | Medium |
| Interaction prop helpers | Sort / select / expand bindings + focus-on-collapse | Medium |
| Server router example + Back/Retry tests | server-invoices-router.vue, race tests | High |
| Column sorting UI and header a11y | Single-column sort, aria-sort | Medium |
| Filtering model and toolbar composition docs | Conditional page reset vs manualFiltering | Low |
| Pagination integration | rowCount, empty → page 1, GhostPagination | Low |
| Row selection (local + server) | Select-all rules, no server prune, cross-page tests | High |
| Row expansion rows | Detail <tr>, server no-prune | Medium |
| Server mode and async guard | Coalesced stateChange, full query, stale guard tests | Medium |
| Performance benchmark harness | Vitest bench, sort/page regression counters | Low |
| Deferred: PrimeVue 10k browser comparison | docs/contributing/data-table-benchmark-comparison.md | Medium |
| Headless docs and executable examples | data-table.md, examples/data-table/ | Medium |
Spec (0.1.0): Themed GhostDataTable addendum (#316) | Single-sort themed contract + preset layout slots (gates #333) | Medium |
Wave 2 (0.1.0): Themed GhostDataTable implementation (#333) | @ghostvue/vue preset slots + @ghostvue/themes wrappers & CSS | High |
| Approved: Multi-column sort spec (#317, GHO-250) | Approved 0.3.0 addendum specifies opt-in multi-column sorting via enableMultiSort | Medium |
| Approved: Header filter-control amendment | Opt-in headerControls and #headerControl on both renderers | Medium |
| Deferred: Virtualization spec | Scroll + a11y | High |
| Approved: Query-wide server selection amendment | Opt-in selection v-model: filter query plus excluded ids, no id download | High |
| Approved: Flat grid keyboard spec (GHO-252) | Data grid spec (approved); treegrid deferred | High |
Parent GHO-35 records specification approval at specStatus: approved (Zac approved in chat on 2026-11-23; recorded in PR #272).
Multi-column sort specification (GHO-250, approved for 0.3.0)
Important
Approved for 0.3.0. On 2026-11-29, Zac approved all five decisions below and deferred the per-column override. PR #367 introduced the proposal for #317. The default remains phase-one single-column sorting.
Purpose and scope
Real admin and financial tables frequently sort by a primary grouping key and a secondary tie-breaker (for example, status ascending, then amount descending). Phase one intentionally capped sorting: DataTableColumnSort[] at one entry (slice(0, 1)) while keeping the public array shape so multi-column sorting can be enabled additively behind enableMultiSort.
This addendum defines the 0.3.0 behavioral, API, keyboard, pointer, and assistive-technology contract when enableMultiSort is true, preserving 100% backwards compatibility when enableMultiSort is omitted or false.
Non-goals for 0.3.0 multi-sort:
- Spreadsheet
role="grid"navigation or arrow-key cell traversal (still native<table>+Taborder per ADR 0014). - Built-in multi-sort toolbar UI, drag-to-reorder sort pills, or opinionated popover sort builders (consumers can compose those via
setSorting,toggleSorting, andclearSorting). - Breaking changes to
DataTableColumnSortorDataTableQueryState.
Public API additions
All additions to @ghostvue/vue are additive and backwards-compatible with the phase-one contracts in packages/vue/src/ghost-data-table.ts.
Options and props
Additions to UseGhostDataTableBaseOptions<TData> and GhostDataTableProps<TData>:
| Option / Prop | Type | Default | Contract |
|---|---|---|---|
enableMultiSort | boolean | false | Opts the table into multi-column sorting. When false, behavior is identical to phase one (sorting capped to 1 entry; no priority badges or descriptions). |
maxMultiSortColCount | number | undefined | undefined | Optional cap (>= 1, integer) on simultaneous sorted columns when enableMultiSort is true. undefined allows sorting by any number of sortable columns. |
isMultiSortEvent | (event: MouseEvent | KeyboardEvent) => boolean | (event) => event.shiftKey | Predicate evaluated when a header sort control activates with an event. Ignored when enableMultiSort is false. |
- Invalid
maxMultiSortColCount: Values< 1or non-finite values normalize to1(minimum meaningful bound; values with fractional parts useMath.floor). WhenmaxMultiSortColCount === 1andenableMultiSort: true, at most one column may be active at a time. - No
Shift-locking requirement: Consumers wanting additive multi-sort on every click (for example, touch-first or screen-reader-heavy tables without modifier keys) can pass:is-multi-sort-event="() => true".
Localized accessibility strings (preset & default renderer)
Additions to GhostDataTableTableProps and GhostDataTablePresetProps (with defaults matching GhostVue's existing callback convention in GhostDataTablePresetProps):
interface DataTableSortDescriptionContext {
columnId: string
label: string
direction: 'asc' | 'desc'
/** 1-based priority rank (1 = primary sort) */
priority: number
/** Total active sorted columns */
total: number
}
interface DataTableSortAnnouncementEntry {
columnId: string
label: string
direction: 'asc' | 'desc'
/** 1-based priority rank */
priority: number
}| Prop | Type | Default |
|---|---|---|
sortDescriptionLabel | (ctx: DataTableSortDescriptionContext) => string | ({ direction, priority, total }) => \Sorted ${direction === 'asc' ? 'ascending' : 'descending'}, priority ${priority} of ${total}`` |
sortAnnouncementLabel | (entries: readonly DataTableSortAnnouncementEntry[]) => string | Empty: 'Sorting cleared.'; non-empty: 'Sorted by Customer ascending (1), then Amount descending (2).' |
Composable, slot, and exposed actions
Additions to UseGhostDataTableReturn<TData>, GhostDataTableSlotProps<TData>, and GhostDataTableExposed<TData>:
| Symbol | Surface | Signature / Type | Contract |
|---|---|---|---|
getSortIndex(columnId) | Composable, slot props | (columnId: string) => number | Returns 0-based priority index in sorting (0 = primary, 1 = secondary), or -1 when unsorted. |
getSortDirection(columnId) | Composable (existing) | (columnId: string) => DataTableSortDirection | Extended from sorting[0] only to search all entries in sorting ('asc' | 'desc' | false). |
toggleSorting(columnId, multi?) | Composable, exposed | (columnId: string, multi?: boolean) => void | Existing 1-arg calls stay single-column (multi = false). When enableMultiSort is true and multi === true, modifies columnId in place/appends. |
clearSorting() | Composable, slot props, exposed | () => void | Sets sorting to [] (no-op if already empty). Emits one stateChange when manualSorting is true. |
header.sortIndex | DataTableHeader<TData> | number | 0-based index in sorting, or -1 when unsorted. |
header.sortPriority | DataTableHeader<TData> | number | undefined | 1-based rank (sortIndex + 1) when sorted; undefined when unsorted. |
header.toggleSort(event?) | DataTableHeader<TData> | (event?: MouseEvent | KeyboardEvent) => void | Backwards-compatible with @click="header.toggleSort" (Vue forwards $event) and 0-arg header.toggleSort(). Calls isMultiSortEvent(event) when enableMultiSort is true. |
getHeaderCellProps(columnId) | Slot props, getDataTableHeaderCellProps | DataTableHeaderCellProps | See Secondary aria-sort and AT contract. |
getSortButtonProps(columnId, options?) | Slot props, getDataTableSortButtonProps | (columnId, options?: DataTableSortButtonOptions) => ... | Extends DataTableControlLabelOptions with optional describedById?: string (merged with existing/consumer aria-describedby, never dropped). |
sortAnnouncement | Slot props | string | Reactive polite live-region message updated only on user-driven sort actions (empty string on initial SSR/mount and silent URL hydration). |
DataTableInteractionState (read by getDataTableHeaderCellProps and getDataTableSortButtonProps) gains enableMultiSort: ComputedRef<boolean> and getSortIndex: (columnId: string) => number (while keeping getDataTable* pure attribute getters without listeners).
State model and sorting rules
Priority order and normalization
- Order = priority:
sorting[0]is primary (priority1),sorting[1]is secondary (priority2), and so on. - Deduplication: At most one
DataTableColumnSortpercolumn.id.setSorting(next)deduplicates byidkeeping the first (highest priority) occurrence. - Capacity:
- When
enableMultiSortisfalse:setSorting(next)slices tonext.slice(0, 1)(phase-one contract unchanged). - When
enableMultiSortistrueandmaxMultiSortColCountis set:setSorting(next)slices tonext.slice(0, max).
- When
- Inert when disabled or non-sortable:
toggleSorting(columnId, multi)is a no-op whendisabled.valueistrueor!canSort(columnId)(same as phase one).
Multi-sort transition rules
Let C be a sortable column (canSort(C) === true) and enableMultiSort === true:
| Action | Current state of C in sorting | Next sorting state |
|---|---|---|
Multi (multi === true) | Unsorted (index === -1) | If under maxMultiSortColCount: append { id: C, desc: false } at the end (priority sorting.length + 1). At the cap, keep the current sorts. |
Multi (multi === true) | Sorted asc at index | Replace entry at index in place with { id: C, desc: true } (priority rank unchanged). |
Multi (multi === true) | Sorted desc at index | Remove entry at index; all entries with j > index shift up by 1 (priority decreases by 1). |
Single (multi === false) | Unsorted (index === -1) | Replace entire sorting with [{ id: C, desc: false }]. |
Single (multi === false) | Sole sort (length === 1) | Phase-one cycle: asc → desc → []. |
Single (multi === false) | Primary (index === 0, len > 1) | Collapse to single-column sort and advance direction: asc → [{ id: C, desc: true }]; desc → []. |
Single (multi === false) | Secondary (index > 0, len > 1) | Collapse to single-column sort starting ascending: [{ id: C, desc: false }]. |
Local multi-column pipeline (sortRows)
When manualSorting is false:
sortRowsacceptssorting: readonly DataTableColumnSort[]andcolumnsById: ReadonlyMap<string, DataTableColumnDef<TData>>.- Single-column fast path: When
sorting.length === 1, execute the existing phase-one single-column decorate-and-sort path with zero extra allocations. - Multi-column decorate-once: For
sorting.length > 1, resolve the active sortable columns (isColumnSortable(col)). Decorate each row once with its extracted values for those active columns (O(n * k)accessor calls, neverO(n log n * k)). - Comparator chain: Compare column
0, then1, ..., thenk - 1until a non-zero result is found:- Per-column
sortUndefined('first' | 'last' | false, default'last') applies at that column's comparison tier ('first'and'last'stay absolute and do not invert withdesc, matching phase-onesortRows). - Per-column
sortFnorcompareValuesruns next, multiplied byentry.desc ? -1 : 1. - If all active columns compare equal (
0), ES2019+ stableArray.prototype.sortpreservescoreRowsinput order.
- Per-column
- Immutability & memoization: Consumer row objects and
dataremain untouched; filtering, pagination, selection, and expansion still never re-runsortRows.
Server mode, stateChange, and URL serialization
- Zero payload breaking changes:
DataTableQueryState.sortingis alreadyDataTableColumnSort[]. WithmanualSorting: true, anytoggleSorting,setSorting, orclearSortingchange emits onestateChangewithtrigger: 'sorting'and the full orderedquery.sortingarray. - Pagination reset rule: Unchanged from phase one — sorting never resets
pagination.pageIndex(thepageCountclamp still applies ifpageCountshrinks). - Recommended URL format (additive to
server-invoices-router.vue): Encode comma-separatedid:dirpairs in priority order, e.g.?sort=customer:asc,amount:desc, which remains backwards-compatible with single-column?sort=amount:desc. Hydratingsortingon mount or Browser Back remains silent (nostateChangeecho loop).
Keyboard and pointer interaction contract
The table below uses the default isMultiSortEvent predicate. With :is-multi-sort-event="() => true", plain activation uses the multi-sort rules.
| Input | Context | Behavior (enableMultiSort: false) | Behavior (enableMultiSort: true) |
|---|---|---|---|
Click (no modifier) | Sort button | Phase-one single-column cycle | Single-column cycle / collapse to single sort on this column |
Enter / Space (no mod) | Sort button | Phase-one single-column cycle | Single-column cycle / collapse to single sort on this column |
Shift+Click | Sort button | Phase-one single-column cycle | Multi-sort add / cycle in place / remove (or custom via isMultiSortEvent) |
Shift+Enter | Sort button | Phase-one single-column cycle | Multi-sort add / cycle in place / remove |
Shift+Space | Sort button | Phase-one single-column cycle | Multi-sort add / cycle in place / remove (see Shift+Space keyup guard below) |
Tab / Shift+Tab | Table header | Native focus order | Native focus order (no roving grid tabindex) |
Escape | Sort button | No-op | No-op (never clears sorts; Escape is reserved for dismissable overlays per ADR 0011) |
Shift+Space activation and focus stability
- Focus stays on the button: Activating any sort button (plain or
Shift-modified) keeps focus on that<button>(toBeFocused()), never resetting focus to<body>or the table wrapper when DOM rows reorder. Shift+Spacekeyupvskeydownhazard: Native<button>elements fireclickonEnterkeydown, but fireclickonSpacekeyup. If a keyboard user pressesShift+Spaceand releasesShifta few milliseconds before releasingSpace, the browser's synthesizedclickevent carriesshiftKey === false.- Requirement for
GhostDataTableTableandGhostDataTablePreset: Track whetherShift(orisMultiSortEvent) was active onSpacekeydownon that sort button and combine it with the resultingclickevent before callingheader.toggleSort, resetting the pending flag onblurorclick. - Preventing page scroll on
Shift+Space: Native<button>suppressesSpacescrolling, andSpacewithShifton a focused<button>must likewise never scroll the viewport.
- Requirement for
- Screen-reader & touch parity without
Shift: Screen readers in browse / virtual-cursor mode (NVDA, JAWS, VoiceOverVO+Space) and touch screen readers often synthesize a bareclickwithoutShift, and mobile touch has noShiftkey. Consumers requiring multi-sort without modifier keys should either:- Set
:is-multi-sort-event="() => true"(additive click mode paired with a consumer "Clear sorting" button callingclearSorting()), or - Compose a sort menu / priority controls using
toggleSorting(columnId, true)andsetSorting(...).
- Set
Secondary aria-sort and AT contract
WAI-ARIA 1.2 aria-sort constraint
Per WAI-ARIA 1.2 aria-sort and the ARIA Authoring Practices Guide (APG) Sortable Table pattern:
aria-sortaccepts'ascending' | 'descending' | 'other' | 'none'.aria-sortis designed for one sorted column at a time; it has no syntax to express secondary rank (priority 2 of 3), and applyingaria-sortto multiple<th>elements causes assistive technologies to announce multiple columns as equally sorted without hierarchy (or ignore secondary headers).aria-sort="other"is not used for secondary columns: WAI-ARIA defines"other"for non-alphanumeric custom algorithms, so announcing"sorted other"for an ascending secondary column actively misleads screen-reader users.
Header and button attribute contract
When enableMultiSort is true:
- Primary sorted column (
sorting[0],sortPriority === 1):<th>(getHeaderCellProps):scope="col",aria-sort="ascending" | "descending",data-sort="asc" | "desc",data-sort-priority="1".
- Secondary+ sorted columns (
sorting[1..k-1],sortPriority >= 2):<th>(getHeaderCellProps):scope="col",aria-sortomitted,data-sort="asc" | "desc",data-sort-priority="2" | "3" | ....
- Unsorted columns:
<th>(getHeaderCellProps):scope="col",aria-sortomitted,data-sortomitted,data-sort-priorityomitted.
- Sort
<button>(getSortButtonProps) — accessible name vs description:- Never put raw rank digits into the button's accessible name (do not let a visual
2badge concatenate as"Amount 2"). Keep the visual badgearia-hidden="true". - Never place a
GhostVisuallyHiddenstatus span directly inside<th>as text content: doing so alters the<th>accessible name, breaksgetByRole('columnheader', { name: 'Amount' }), and forces screen readers to re-read"Sorted descending, priority 2 of 2"on every<td>cell in that column. - Instead, keep the button's accessible name clean (
"Amount"or customoptions.label) and attacharia-describedbypointing to a visually hidden description node rendered outside<table>(for example, an indexedGhostVisuallyHiddencontainer rendered byGhostDataTableTable/GhostDataTablePreset, or consumer-wired viadescribedByIdin manual composition):- Primary when multi-sorted (
total > 1):"Sorted ascending, priority 1 of 2". - Secondary+:
"Sorted descending, priority 2 of 2". - Single-sorted (
total === 1):aria-sorton<th>already conveys direction; description is optional (or omitted so single-sort matches phase one cleanly).
- Primary when multi-sorted (
- If the consumer already passed
aria-describedby, merge ids space-separated rather than overwriting.
- Never put raw rank digits into the button's accessible name (do not let a visual
- Polite live-region announcement (
aria-live="polite"):- Because secondary columns omit
aria-sort, activatingShift+Enteron a secondary column would otherwise produce noaria-sortmutation announcement. GhostDataTableTableandGhostDataTablePresetrender aGhostVisuallyHiddennode witharia-live="polite"andaria-atomic="true"bound tosortAnnouncement(outside<table>), announcing user-driven changes whenenableMultiSortistrue— e.g."Sorted by Customer ascending (1), then Amount descending (2)."or"Sorting cleared.".- No mount/hydration spam: Initial
defaultSortingand silent URL hydration (sortingprop sync) must not populate the live region. Only user-initiated transitions (toggleSorting,clearSorting, orsetSortingtriggered by user actions) updatesortAnnouncement. - Renderless root invariant:
GhostDataTableitself remains renderless (emits zero DOM elements per ADR 0014) and exposessortAnnouncementinGhostDataTableSlotPropsfor manual#defaultcompositions.
- Because secondary columns omit
Rendering, theming, and CSS hooks
- Headless DOM invariants:
GhostTable*data-partattributes are unchanged. Every sorted<th>receivesdata-sort="asc" | "desc"and (whenenableMultiSortistrue)data-sort-priority="<1-based-rank>". - Additive layering with
@ghostvue/themes(#316): The0.1.0themedGhostDataTablewrapper ships on the single-sortdata-sortcontract. In0.3.0, themed styles can targetth[data-sort-priority]::afteror the priority badge slot usingcontent: attr(data-sort-priority)/ CSS tokens without breaking any0.1.0single-sort selectors. - Decorative indicators: Any arrow glyph or priority pill rendered inside
GhostDataTableTable/GhostDataTablePresetcarriesaria-hidden="true"and stays separated from visible text so screen readers do not concatenate glyphs into the button name.
Environment, SSR, and performance
- SSR & hydration:
sortingstate,aria-sortonsorting[0],data-sort,data-sort-priority, and deterministicuseGhostId-basedaria-describedbyids match identically between SSR and client hydration.sortAnnouncementstarts empty ("") on SSR and initial mount so hydration never mismatches or fires spurious announcements. - Mobile & touch: Touch users without a hardware keyboard rely on either
:is-multi-sort-event="() => true"or consumer-composed sort controls;GhostTable.containHorizontalbehavior is unchanged. - Performance (10k rows):
- When
sorting.length === 1, phase-onesortRowsfast path keeps zero overhead vs0.1.0. - When
sorting.length > 1, decorate-once evaluates accessorsO(n * k)times total acrossksorted columns instead of inside the comparator. - Required regression counter test (matching
use-ghost-data-table.counters.test.ts): 2-column sort over 1,000 rows calls each active column's accessor once per row (<= ncalls per sorted column), and paging or toggling row selection triggers zero comparator/accessor re-evaluations.
- When
Test plan (required for 0.3.0 implementation gate)
- Unit (
use-ghost-data-table.test.ts/data-table-processing.test.ts):- Multi-column sort ordering (2 and 3 columns, mixed
asc/desc, tie-breaking, stable fallback on total ties, per-columnsortUndefined'first' | 'last' | false, customsortFn). enableMultiSort: falseregression:setSortingstill truncates to 1,toggleSorting(id, true)stays single-sort,data-sort-priorityomitted.- Transition matrix: append, in-place
asc -> desc -> remove, priority promotion when priority 1 is removed, unmodified click collapsing>1sorts,maxMultiSortColCountenforcement,clearSorting(), deduplication insetSorting. - Server mode: single
stateChangeper multi-sort toggle with orderedquery.sorting, no page reset, URL hydration silent (nostateChangeand nosortAnnouncement). - Counter test (
use-ghost-data-table.counters.test.ts): multi-column decorate-once accessor count and zero re-sort on page/selection change.
- Multi-column sort ordering (2 and 3 columns, mixed
- Interaction helpers & Vue (
data-table-interaction.test.ts,GhostDataTableTable.test.ts,GhostDataTablePreset.test.ts, SSR):- Primary
<th>carriesaria-sortanddata-sort-priority="1"; secondary<th>omitsaria-sortand carriesdata-sort+data-sort-priority="2". - Sort button keeps clean accessible name (excludes decorative badge), exposes merged
aria-describedbypointing outside<table>, and<th>accessible name stays clean (Amount, not"Amount Sorted descending..."). sortAnnouncementlive region stays empty on SSR/mount and updates on user sort changes.- SSR hydration test with
defaultSortingof length 2 produces zero hydration mismatches.
- Primary
- Playwright keyboard, focus & axe (
tests/e2e/ghost-data-table.spec.ts):Shift+Click,Shift+Enter, andShift+Space(including releasingShiftbeforeSpacekeyup) add secondary sort, cycle secondaryasc -> desc -> remove, and preservetoBeFocused()on the activated sort button.- With the default predicate, plain
Enter/Spaceon an ascending primary leaves it descending alone. On a descending primary it clears all sorts. On a secondary or unsorted column it starts that column alone, ascending.Escapekeeps the current sorts. :is-multi-sort-event="() => true"+clearSorting()flow works without modifier keys.- Zero
@axe-core/playwrightviolations acrossthead,tbody, and visually hidden live/description nodes with 0, 1, 2, and 3 active sorted columns.
- Manual AT verification (before
stable):- Record NVDA + Firefox and VoiceOver + Safari evidence per assistive-technology-review.md, verifying primary
aria-sort, secondaryaria-describedbypriority/direction readout, clean<td>column-header announcements, and polite live-region announcements.
- Record NVDA + Firefox and VoiceOver + Safari evidence per assistive-technology-review.md, verifying primary
- Bench (
tests/bench/data-table-processing.bench.ts):- Add 2-column and 3-column 10k-row
sortRowscases to verify single-column fast path has zero regression and multi-column sort stays well within budget.
- Add 2-column and 3-column 10k-row
Approved multi-sort decisions (0.3.0)
- Q1 — Accessible sort priority. Only the primary header carries
aria-sort. In a multi-column sort, describe each active button's direction and rank usingaria-describedby, and announce user-driven changes through the polite live region. - Q2 — Plain activation with multiple sorts. With the default predicate, activating the primary column advances ascending to descending alone, or descending to an empty sort list, clearing all columns. Activating a secondary or unsorted column starts that column alone, ascending.
- Q3 — Adding a column at the cap. Ignore the addition and preserve every active direction and rank. Active columns can still cycle or be removed.
- Q4 — Modifier-free operation. Document a working example with
:is-multi-sort-event="() => true"and a visible app-provided Clear sorting button callingclearSorting(). This supports ordinary touch and assistive-technology activation. The preset needs no dedicated mode prop or built-in reset control. - Q5 — Table-level opt-in. With
enableMultiSortenabled on the table, every sortable column can participate. Defer the per-columnDataTableColumnDef.enableMultiSortoverride beyond 0.3.0.
Header filter-control amendment (approved)
Important
Approved, no target release yet. On 2026-12-01, zprue743 approved the recommended option for each contract decision. Implementation waits for a maintainer to assign a target release. Until it ships, neither renderer changes. The contract and its test plan are below. Runtime code, a public table context, and exported matcher or comparator functions stay out of scope.
Why a header control
The runnable date range filter example (data-table/toolbar-date-range) puts Issued from, Issued to, Apply, and Clear dates in the preset's opted-in #toolbarEnd. That layout works for one filter on a narrow table. The interaction it cannot serve starts at the column itself:
- The user scans the Issued column and wants to narrow it. From the Issued heading they open that column's filter, choose a range, and apply it without leaving the column.
- The heading then shows that Issued is filtered, so a user reading the headers can tell which columns constrain the rows.
- The user moves to Amount and sorts it. The filter and the sort are independent: neither control changes the other's state.
A toolbar breaks down on this task when several columns each carry a filter (the toolbar becomes a form whose fields the user has to map back to columns), and when containHorizontal scrolls the column far away from the toolbar.
Today a consumer cannot add that control through either default renderer. GhostDataTableTable and GhostDataTablePreset own each <th>: they render the header label, or the sort button that contains it, and nothing else. The only route is to drop the renderer for a manual #default composition.
Compatibility constraint. Every slot name on GhostDataTableTable, and every preset name not yet claimed by detail, toolbar, search, or an opted-in layout slot, is a cell slot for the column with that id. A new named slot collides with existing tables. For example, a consumer with a column named columnHeaderEnd can already use #columnHeaderEnd to render its cells. The preset layout slots resolved the same collision with an explicit opt-in, and this amendment follows that precedent.
Non-goals.
- Built-in filter UI: no filter menu, popover, operator picker, or filter row ships with either renderer. The consumer supplies the control.
- Filter state or commands in the header slot props (see Q3). The consumer already owns
v-model:column-filtersand the root'ssetColumnFilteraction. - A per-column renderer hook in
defineDataTableColumns, a public table context, and exported matcher or comparator functions. - Changes to unlisted columns, to
aria-sort, or to sort activation.
Public API additions
Both GhostDataTableTable and GhostDataTablePreset, headless and themed, gain one prop and one opted-in scoped slot.
| Prop | Type | Default | Contract |
|---|---|---|---|
headerControls | readonly TColumns[number]['id'][] (any string without a typed columns array) | undefined | Column ids whose header renders #headerControl. Omitted or [] keeps today's behavior, including #headerControl as a cell slot. |
/** Props of the opted-in `#headerControl` slot, called once per listed column. */
export interface GhostDataTableHeaderControlSlotProps<
TColumnId extends string = string,
> {
/** The listed column this header belongs to. */
columnId: TColumnId
/**
* The header label the sort button shows (never empty; falls back to the
* column id). Use it to name the control, for example `Filter ${label}`.
*/
label: string
/** `true` while the parent `GhostDataTable` is disabled. */
disabled: boolean
}
// Additions to GhostDataTableTableProps<TColumns, THeader = never> and
// GhostDataTablePresetProps<TColumns, TLayout = never, THeader = never>:
// headerControls?: readonly THeader[]
// THeader extends TColumns[number]['id'] and is inferred from this prop alone.
type GhostDataTableHeaderControlSlots<TColumnId extends string> = {
headerControl?: (
props: GhostDataTableHeaderControlSlotProps<TColumnId>,
) => unknown
}
// With no listed ids, the slot map is exactly today's. Once ids are listed,
// `headerControl` leaves the cell slots and takes the header signature.
export type GhostDataTableTableSlots<
TColumns extends readonly DataTableTableColumnRef[],
THeader extends string = never,
> = [THeader] extends [never]
? DataTableCellSlots<TColumns>
: Omit<DataTableCellSlots<TColumns>, 'headerControl'> &
GhostDataTableHeaderControlSlots<NoInfer<THeader>>DataTableCellSlots<TColumns> stands for today's GhostDataTableTableSlots mapping. GhostDataTablePresetSlots applies the same switch before it removes opted-in layout names.
Ownership rules (both renderers)
- Opt-in. With
headerControlsomitted or[], the renderer is unchanged. A column whose id isheaderControlkeeps calling#headerControlonce per row with its cell props. - Reservation. A non-empty
headerControlsreserves the nameheaderControlfor headers on that instance, even when none of its listed columns currently render or the slot is absent. A column with the idheaderControlthen renders through itscellhook or value fallback. A slot function is invoked in exactly one role. - Resolution order. Resolve ownership from
headerControlsbefore testing slot presence and before cell lookup. Row count, column order and visibility, selection, sorting, and filters never change the decision. - Matching. A listed id the renderer does not render is ignored, matching how the
columnsprop skips unknown ids. Listing an id twice renders one control. The slot is called once per listed, rendered column, in column order, and never for an unlisted column. - Independence from
layoutSlots. On the preset,layoutSlotsandheaderControlsare separate lists. Neither affects the other's names.
Header DOM and accessibility contract
For a listed column, the renderer emits:
<th
scope="col"
aria-sort="ascending"
data-sort="asc"
aria-label="Issued"
data-header-control=""
>
<button type="button" data-part="sort-button">Issued</button>
<span data-part="header-control"><!-- #headerControl output --></span>
</th>- Unlisted columns are unchanged. Their
<th>markup matches today's byte for byte, so existing selectors, snapshots, and visual baselines hold. aria-sortstays on the<th>.scope,aria-sort,data-sort, anddata-sort-priorityremain on the header cell exactly as the single-sort and multi-sort contracts define them. Nothing moves to the wrapper or the control.- The control is never inside the sort button. It is the sort button's next sibling, wrapped in
[data-part="header-control"]. A non-sortable column renders the label text followed by the same wrapper. The wrapper also keeps the consumer's own<button>from matching the themedth > buttonsort-button rules. - The
<th>keeps a clean name. A column header's accessible name comes from its content, so a control inside the<th>joins the name. In a Chromium accessibility tree check run while drafting this amendment, a<th>holding a sort button "Issued" and a control named "Filter Issued" was exposed as the column header "Issued Filter Issued". Witharia-label="Issued"on the<th>, it was exposed as "Issued". Screen readers repeat the column header name when moving between cells in that column, so the renderer setsaria-labelto the header label only on listed columns (see Q2). - The control names itself. The consumer gives the control an accessible name that includes the column label, for example
Filter Issued, built from the slot'slabelso localized headers stay in sync. When a filter is active, the control says so through its name oraria-describedby, for example "Filter Issued, Nov 14 to Nov 24, 2026". A popover trigger keeps theGhostPopoverTriggersemantics (aria-haspopup="dialog",aria-expanded). - Overlays leave the cell. Popover or dialog content that the control opens renders through
portal(GhostPopoverContent :portal="true"), socontainHorizontaloverflow and a sticky header cannot clip it and its content never sits inside the<th>.
Keyboard
| Input | Context | Behavior |
|---|---|---|
Tab / Shift+Tab | Header row | Native order: sort button, then the control's focusable elements, then the next column. No roving tabindex. |
Enter / Space | Header control | The control's own action (for example, opening its popover). Never reaches sort activation. |
Shift+Enter / Shift+Space | Header control | Same as without Shift. Never adds a sort, with or without enableMultiSort. |
Escape | Open control popup | Closes the popup and returns focus to its trigger (ADR 0011). Never clears a sort or a filter. |
- Prefer one trigger per header. A single trigger that opens a popover keeps the header row to two
Tabstops per listed column. Inline fields in a<th>are allowed but lengthen the header'sTabsequence. - Focus survives filtering. The header row stays mounted when a filter leaves zero rows and while
loadingsetsaria-busy, so focus returns to the trigger after the popup closes. - Disabled tables. While the parent is disabled, the slot receives
disabled: trueand the control disables or marks itselfaria-disabled, matching the disabled sort buttons.
State model
- The control commits through the existing root actions (
setColumnFilter,setColumnFilters) on the template ref, exactly as the toolbar composition does. The page-after-filter rules and consumer-owned debouncing apply unchanged. - Activating the control never changes
sorting. It calls notoggleSort, emits noupdate:sorting, and leaves multi-sort priorities and thesortAnnouncementlive region untouched. WithmanualFiltering, applying a filter emits onestateChangewithtrigger: 'columnFilters'whosequery.sortingequals the sort before the commit. - Opening, editing, or closing the control without a commit runs zero sort or filter passes.
Rendering and themes
- Hooks:
th[data-header-control]on listed header cells and[data-part="header-control"]on the wrapper. No new hook on unlisted columns. - Themed layout: the themed sort button fills its header cell today. On
th[data-header-control], the themed CSS sizes the sort button to its content and places the wrapper at the inline end with--ghost-space-gap-xs, using child-combinator selectors only. The wrapper aligns to the control-size tokens so a trigger meets the samecontrol.size.*touch target as other controls. Logical properties mirror the layout in RTL. - Themed wrappers: the
@ghostvue/themesGhostDataTableTableandGhostDataTablePresetdeclare and forwardheaderControlslikelayoutSlots, and keep the headless slot types. Slot invocation stays in the headless renderers. - Manual
#defaultcomposition already owns each<th>. It follows the same rules: keeparia-sorton the<th>, put the control beside (not inside) the sort button, and set the<th>aria-labelto the column label. No new helper is added.
Environment and performance
- SSR and hydration: ownership comes from the
headerControlsprop, thearia-labelcomes from the header label, and the renderer generates no new ids, so server and client markup match. - Mobile and touch: the trigger is a separate target from the sort button, so a tap on the filter never sorts.
containHorizontalbehavior is unchanged. - Performance: unlisted columns do no extra work. Each listed column calls the slot once per header render. No processing pass runs until a commit.
Implementation acceptance cases
These cases gate the implementation, not this amendment. Each runs against GhostDataTableTable and GhostDataTablePreset, headless and themed, unless it says otherwise. The collision cases extend the existing preset slot-ownership suite in tests/integration/ghost-data-table-themed.test.ts.
- Legacy cell slot keeps its value. A column with id
headerControland a#headerControltemplate, withoutheaderControls, receives each row's cell value (10,20) through asynchronous column insertion, reorder, and removal. No[data-part="header-control"]orth[data-header-control]renders. The same case passes with a column namedcolumnHeaderEnd. - Opt-in reserves the name. With
:header-controls="['total']"and a column whose id isheaderControl, the slot is called once with{ columnId: 'total', label: 'Total', disabled: false }and never with cell props. TheheaderControlcolumn renders itscellhook output or its value. - Unlisted and unknown ids. Unlisted headers keep today's markup. A listed id that is not rendered produces no control and no error. A duplicated id renders one control.
- Filter activation leaves single sort alone. With
Amountsorted ascending, open the Issued control with a click,Enter, andSpace, apply a range, and close it.sortingis unchanged,update:sortingis not emitted,aria-sort="ascending"stays on the Amount<th>, and focus returns to the trigger. - Filter activation leaves multi-sort priority alone. With
enableMultiSortand[customer asc, amount desc], activate the controls on Issued (unsorted) and Amount (priority 2), including withShift+EnterandShift+Space. The sort array,data-sort-priorityvalues,aria-describedbyrank text, and thesortAnnouncementlive region are unchanged. - Server mode. With
manualFiltering, applying the range emits onestateChangewithtrigger: 'columnFilters',pageIndex: 1, and the priorquery.sorting. No sortingstateChangefollows. aria-sortstays on the header. On a listed, sorted column,aria-sortis on the element with rolecolumnheader, not on the wrapper, the sort button, or the control.getByRole('columnheader', { name: 'Issued', exact: true })andgetByRole('button', { name: 'Issued', exact: true })both resolve.- Keyboard reachability (Playwright).
Tabmoves from the Issued sort button to its trigger and on to the next column's sort button;Shift+Tabreverses.Escapein the open popover closes it andtoBeFocused()holds on the trigger. Applying a range that matches no rows keeps the header mounted and focus on the trigger. - Disabled table. The slot receives
disabled: true, and the reference control cannot open. - Axe and SSR. Zero
@axe-core/playwrightviolations on the table scope with the popover open and closed. SSR hydration withheaderControlsand an active sort produces zero mismatches. - Types.
headerControlsaccepts only ids from a typedcolumnsarray.#headerControlhas the header signature only when ids are listed, and the legacy cell signature otherwise. - Manual AT before
stable. Record NVDA with Firefox and VoiceOver with Safari per assistive-technology-review.md: cells in a listed column announce the clean column name, and the trigger announces its name, active filter, and expanded state.
Documentation plan
- Add
examples/data-table/header-date-range.vue, the same invoices and range rules astoolbar-date-range, with a popover trigger in the Issued header. Keep the toolbar example unchanged. - Add a "Filter from a column header" section to
docs/components/data-table.mdcoveringheaderControls, the collision rule, naming the trigger, and the manual-composition rules above.
Compatibility
- Additive. With
headerControlsomitted or[], markup, slot routing, and types are unchanged, including tables with a column namedheaderControl. - A Changeset for
@ghostvue/vueand@ghostvue/themesships with the implementation. The spec revisions are docs-only.
Approved header filter-control decisions
zprue743 approved these on 2026-12-01.
- Q1 — API shape. Use a
headerControlsid list plus one#headerControlslot, opted in per instance with the same reservation rule aslayoutSlots. Not chosen: one slot per column (such as#header:issued), which adds many names that each still need an opt-in, and a render hook on the column definition, which replaces templates with render functions and puts header chrome in column definitions. - Q2 — Header cell name. The renderer sets
aria-labelon each listed<th>to the header label, so cells in that column keep announcing the clean column name. Not chosen:aria-labelledby, which needs an id per listed header, and leaving the name to each consumer. - Q3 — Slot props. The slot receives
{ columnId, label, disabled }only. Filter state stays with the consumer'sv-model:column-filtersand template-ref actions, and no table context becomes public. Not chosen: passing the column's filter value and a bound setter. - Q4 — Release. No target release yet. A maintainer assigns one before implementation starts.
Default expand mark amendment (proposed)
Important
Proposed. Not approved. This amendment replaces the text glyph on the themed preset's row expand button with a CSS-painted mark, under ADR 0013 rules 2 and 3. Rule 6 makes a new default mark a contract change, so it needs approval before any CSS ships. Until approval is recorded, the sections above stay authoritative and the expand button keeps the ▸ / ▾ glyph. This revision delivers the contract and acceptance cases only. The accordion disclosure mark is proposed alongside it and uses the same technique.
Why a painted mark
Consumer feedback: next to the painted sort chevrons, the expand button's ▸ / ▾ looks unfinished. It is a font glyph inside GhostDataTablePreset.vue, so its size, weight, and baseline depend on the font in use. It also ignores --ghost-action-icon-size and does not match the sort mark in the same table. The single-sort header indicator already sets the pattern for a themed mark in this component. This amendment applies the same pattern to the expand button.
Proposed contract
- Where it applies. A
button[data-part="expand-button"]in a direct body cell of a themed table, which is the selector the existing expand-button rule inghost-data-table.cssalready uses. That covers the themedGhostDataTablePresetand manual compositions under themedGhostDataTablethat putdata-part="expand-button"on their own button. The rule uses child combinators, so a nested table in a#detailrow is not matched. Bare headless renderers are unchanged. - Headless glyph. Headless
GhostDataTablePresetkeeps rendering thearia-hidden▸/▾span. Removing it would change headless output (ADR 0013, Existing exceptions). The span gains one styling hook,data-part="expand-glyph", and its text andaria-hiddendo not change. The themed rule hides> [data-part='expand-glyph']withdisplay: noneand paints the mark. The hook is needed because the themed preset passes slots through and cannot change the inner button content, and selecting a barespanwould make internal DOM structure the styling contract. - How it is painted. The button's
::afterwithcontent: '', an--ghost-action-icon-sizesquare (1.1em),background: currentColor, and the sameclip-pathchevron as the descending sort mark. It uses no SVG, no new token, and no per-component color. The button's existingdisplay: inline-grid; place-items: centercenters it, and the--ghost-control-size-sm-minand--ghost-control-touch-mintarget sizes do not change. - State. The button has no
data-state. The existing themed rule already readsaria-expanded, and the mark does the same, becausegetRowExpandButtonPropsalways sets it.aria-expanded="false"points the mark to the inline end (rotated -90°, or 90° under:dir(rtl)), the same direction as▸.aria-expanded="true"points it down (0°), like▾.data-expandedon the row is not used, so manual compositions that bind only the button props still work. - Motion. The 90° turn transitions
rotatewith--ghost-motion-duration-fastand--ghost-motion-easing-standardonly under@media (prefers-reduced-motion: no-preference). With reduced motion the mark changes at once, as the motion rules in Keyboard, focus parity, RTL, touch, and motion require. - Forced colors. As for the sort mark, the
::aftersetsforced-color-adjust: noneunder@media (forced-colors: active)and paints inButtonText, orGrayTextwhen the button is:disabled. In a selected row, the cell'sforced-color-adjust: autoreset already returns the button toButtonFace, soButtonTextstays visible against it.
Replacing or removing the mark
- Manual compositions. A decorative direct child of the expand button marked
data-part="expand-indicator"turns the default off for that button::not(:has(> [data-part='expand-indicator'])). This works likedata-part="sort-indicator". The consumer marks itaria-hidden="true"(andfocusable="false"on SVG). A manual composition that does not want the default mark can leavedata-part="expand-button"off its button. - Preset. ADR 0013 rule 2 requires every themed default to be replaceable by consumer content through a slot or
data-partopt-in, and CSS alone can only restyle or remove a pseudo-element. So this amendment adds one preset layout slot,#expandIndicator, with slot props{ expanded: boolean }. Like the other layout slots it is reserved per instance throughlayoutSlots, so a column with idexpandIndicatorkeeps its cell slot unless the instance opts in. When the slot is enabled and supplied, the preset renders the consumer content inside<span data-part="expand-indicator" aria-hidden="true">in place of theexpand-glyphspan. That span is a direct child of the button, so the replacement rule above turns the painted mark off in the themed preset with no extra CSS, and in a headless preset the consumer artwork simply replaces the glyph. The wrapper isaria-hidden, so the button's accessible name still comes only fromaria-label. Without the opt-in, output is exactly as described under Headless glyph. - Styling only. The rule has zero specificity in
@layer ghostvue-theme, so a consumer rule can also restyle or remove the::after(content: none) without!important. Removing the mark this way does not bring back the hidden glyph.
Accessibility
- The button's accessible name does not change. It comes from
aria-label(rowExpansionLabel(rowId), defaultShow details for <rowId>), set bygetRowExpandButtonProps. Today the glyph span is alreadyaria-hiddenandaria-labeloverrides content, so the glyph is not announced. The painted mark has no text (content: ''), so this stays true. aria-expandedandaria-controlsstill carry the state and relationship. The mark is never the only cue (ADR 0013 rule 5). Keyboard, focus, and focus return on collapse (useDataTableDetailRowFocus) do not change.- The mark uses the button's text color (
--ghost-surface-fg, or--ghost-action-disabled-fgwhen disabled), so the enabled mark meets the 3:1 non-text contrast minimum in every theme and mode.
Implementation acceptance cases
- Headless hook (unit).
GhostDataTablePresetrenders the glyph span withdata-part="expand-glyph",aria-hidden="true", and the same▸/▾text as before. - Painted (browser). In the themed preset, the glyph span is not displayed. The button's
::afterhas computedcontent"", a size equal to the resolved--ghost-action-icon-size, and a background equal to the button'scolor. A headless preset on the same page still shows the glyph and has no painted::after. - State and RTL (browser).
Enter,Space, and click flip the mark's computedrotatein step witharia-expanded. Underdir="rtl"the collapsed mark points the other way, and the expanded mark points down. - Reduced motion (browser). With
reducedMotion: 'reduce'emulated, the mark's transition duration is0s. - Forced colors (browser). With
forcedColors: 'active'emulated, the mark is painted inButtonTextin an unselected and a selected row, and inGrayTextwhen the table is disabled. - Replacement (browser). In a manual composition, a direct child with
data-part="expand-indicator"turns the default off, and a button withoutdata-part="expand-button"gets no mark. - Preset slot (unit and browser). With
layoutSlotsincludingexpandIndicatorand the slot supplied, the button contains onearia-hiddendata-part="expand-indicator"span with the consumer content and noexpand-glyphspan, the slot receivesexpandedin step witharia-expanded, and the themed button paints no::aftermark. Without the opt-in, a column with idexpandIndicatorstill receives its cell slot and the button output matches case 1. - Slot types (
vue-tsc). Positive and negative type fixtures, in the same style as the existing preset slot type tests, cover the genericGhostDataTablePresetSlots<TColumns, TLayout>contract on both the headless preset and the themed wrapper:#expandIndicatoris accepted with{ expanded: boolean }only whenlayoutSlotsincludes it; without the opt-in a column with idexpandIndicatorkeeps its cell-slot signature and the layout signature is rejected; andexpandedis typedbooleanthrough the themed pass-through. - Name and axe (browser). The expand button's accessible name equals
rowExpansionLabel(rowId)before and after toggling. The existing keyboard and axe run intests/e2e/ghost-data-table.spec.tsstill passes. - Baselines. The data table
examples-visualbaselines with expandable rows are updated withpnpm test:visual:docker.
Documentation plan
docs/components/data-table.mdStyling hooks lists the painted expand mark,data-part="expand-glyph", and theexpand-indicatoropt-out, with a manual-composition example.- The preset layout slots section adds
#expandIndicatorwith its{ expanded }props and a short example that supplies replacement artwork. - The themed manifests' styling hooks list the expand-button
::afterdefault. - A
@ghostvue/themesChangeset for the mark and a@ghostvue/vueminor Changeset for the added attribute and the opt-in slot.
Compatibility
@ghostvue/themeschanges how it renders (minor Changeset). The themed preset shows the painted chevron instead of the glyph. A manual composition that already marks its expand buttondata-part="expand-button"gains the mark next to its own content. It can adddata-part="expand-indicator"to its artwork or drop the hook. The Changeset says this.@ghostvue/vuegains one attribute on an existingaria-hiddenspan and one opt-in layout slot,#expandIndicator(minor Changeset). Without the opt-in, the span's text, the accessible name, and DOM order do not change, and a column with idexpandIndicatorkeeps its cell slot.
Query-wide server selection amendment
Important
Approved 2026-12-04, no target release yet. The maintainer approved the proposed option for each of the decisions below in PR #771, and the non-goals now carry the narrower text. This amendment defines what an operator selects when they choose every row that matches a server filter and then exclude rows across pages, without downloading the matching ids. It delivers the contract, a worked trace, and acceptance cases; runtime changes wait for a target release.
Why query-wide selection
Server tables already keep explicit selections across pages (see Selection; the cross-page and no-prune rules have regression coverage from PR #299). That works when the operator ticks rows one page at a time. It does not work for "mark every unpaid invoice as sent, except these two": with 2,300 matches and 25 rows per page, the operator would visit 92 pages, and an application that wants every id would have to download all 2,300 of them before it could act.
Query-wide selection describes the set instead of listing it: the server filters that define membership, plus the ids the operator excluded. The server resolves that description when it runs the bulk action. The table never sees, stores, or fetches the full id list.
Scope and responsibilities
| Concern | Owner |
|---|---|
| Recording the selection (query, exclusions, counts) | Table (useGhostDataTable) |
| Checked state, counts, and announcements | Table and default renderers |
| Opt-in and clear controls | Consumer markup in #bulkActions, using the slot props below |
| Sending the selection to the server | Application |
| Resolving membership, authorizing, and running the action | Server. The table never resolves a query to ids and never authorizes or runs an action. |
| Showing a rejected or partial action | Application (error UI is consumer-owned, as in the Non-goals) |
Applies only to server-filtered, server-paged tables:manualPagination: true and manualFiltering: true. Local tables already select every filtered row across pages (Select-all behavior). A server page with a page-local filter (manualFiltering: false) has no server query that matches what the operator sees, so query selection is unavailable there. When enableQuerySelection is set without both flags, the composable warns in development and the opt-in stays inert.
Replacement for the non-goal (applied on approval, 2026-12-04):
- Resolving a query-wide selection to row ids, authorizing a bulk action, or running it. The table records an opt-in query selection (amendment); the server owns membership and execution.
Public API additions
/**
* Filters that define query-selection membership. Sorting and pagination
* are left out because they do not change which rows match. A deep, frozen
* snapshot taken by `selectAllMatching()`; it never shares references with
* the committed filters.
*/
interface DataTableSelectionQuery {
/**
* Active entries of the committed `columnFilters`, in order. Values hold
* only primitives, frozen arrays, and frozen plain objects: each `Date` is
* stored as its ISO 8601 string (`toISOString()`).
*/
columnFilters: readonly DataTableColumnFilter[]
/**
* The committed `globalFilter`, with `undefined` and `''` normalized to
* `null` so the snapshot round-trips through JSON unchanged.
*/
globalFilter: unknown
}
/** Explicit ids: today's `selectedRowIds` contract. */
interface DataTableIdSelection {
mode: 'ids'
ids: readonly DataTableRowId[]
}
/** Every row matching `query` on the server, minus `excludedIds`. */
interface DataTableQuerySelection {
mode: 'query'
query: DataTableSelectionQuery
/** Rows the operator unchecked after opting in, in the order they were excluded. */
excludedIds: readonly DataTableRowId[]
/** `rowCount` when the operator opted in. Never updated afterwards. */
matchCount: number
/** `rowCountExact` when the operator opted in. */
matchCountExact: boolean
/**
* Opaque app token passed to `selectAllMatching()`, such as a request or
* audit correlation id. It must not change which rows the action touches.
*/
queryKey?: string
}
type DataTableSelection = DataTableIdSelection | DataTableQuerySelectionApplications branch on selection.mode. An ids selection is a complete list. A query selection is a description that only the server can expand. The two shapes share no field that could be read as the other, so an app cannot send a partial id list by mistake.
Root and composable options:
| Option | Type | Default | Contract |
|---|---|---|---|
enableQuerySelection | boolean | false | Turns on the selection model and selectAllMatching(). Requires enableRowSelection, manualPagination, and manualFiltering. |
selection | DataTableSelection | — | Controlled selection (v-model:selection). Read only while enableQuerySelection is true. |
defaultSelection | DataTableSelection | { mode: 'ids', ids: [] } | Uncontrolled initial selection. |
rowCountExact | boolean | true | Set to false when the server's rowCount is an estimate. Counts and default labels then avoid exact numbers. rowCount still bounds pagination, so the estimate must follow the estimate constraint. |
Events: update:selection with the next DataTableSelection. Selection changes never emit stateChange and never cause a fetch.
Exposed actions and slot bindings (root default slot, template ref, and composable return):
| Name | Contract |
|---|---|
selection | Effective DataTableSelection. |
selectedCount | ids.length in ids mode. In query mode, max(0, rowCount − excludedIds.length) using the current rowCount; how exact it is comes from selectedCountKind. |
selectedCountKind | DataTableSelectionCountKind. Always 'exact' in ids mode, whatever rowCountExact is, because ids.length is a count of explicit ids. For a query selection: 'exact' with no exclusions and rowCountExact; 'atLeast' with exclusions and rowCountExact; 'estimate' when rowCountExact is false. See counts. |
canSelectAllMatching | true when query selection is enabled and not inert, the selection is in ids mode, at least one row is visible and every visible row is selected, the committed filters can be snapshotted, and either rowCount is greater than the visible row count or rowCountExact is false (an estimate cannot prove there are no more rows). |
selectAllMatching(opts?) | opts: { queryKey?: string }. Replaces the selection with a query selection built from the committed filters, rowCount, and rowCountExact. Inert unless canSelectAllMatching. |
toggleRowSelected(id, v?) | Unchanged in ids mode. In query mode, unchecking adds id to excludedIds and checking removes it. |
toggleAllRowsSelected(v?) | Unchanged in ids mode. In query mode it acts on the visible rows only: unchecking adds their ids to excludedIds, checking removes them (QS6). Inert while a visible row has a non-finite numeric id. |
resetRowSelection() | Sets { mode: 'ids', ids: [] } from either mode. |
isRowSelected(id) | In query mode, true for a loaded row whose id is not in excludedIds. Rows in data are the server's answer to the committed query, so they match it. |
headerSelectionState | In query mode: allSelected when at least one row is visible and none is excluded, someSelected when some are, both false when all are or when no row is visible. |
getSelectedRowModel() | In query mode, the loaded rows that are not excluded (display only, as today). |
selectionAnnouncement | Polite message string, updated only by the user actions listed under Announcements. Empty on SSR, mount, and prop-driven changes. |
Default renderer additions. GhostDataTablePresetBulkActionsSlotProps gains selection, excludedCount, selectedCountKind, canSelectAllMatching, and selectAllMatching. #bulkActions renders while the selection is non-empty: ids.length > 0, or any query selection. Both GhostDataTableTable and GhostDataTablePreset gain selectionAnnouncementLabel ((context: DataTableSelectionAnnouncementContext) => string) and render the announcement in the same kind of GhostVisuallyHidden polite, atomic region as sortAnnouncement, outside <table>. The renderless root stays renderless and exposes selectionAnnouncement for manual compositions.
type DataTableSelectionCountKind = 'exact' | 'atLeast' | 'estimate'
interface DataTableSelectionAnnouncementContext {
reason: 'page-selected' | 'all-matching' | 'cleared' | 'filter-changed'
/** `selectedCount` after the action. */
count: number
/** Current `rowCount`. */
matchCount: number
/** How exact `count` is (`selectedCountKind`). */
countKind: DataTableSelectionCountKind
/** `rowCountExact`, which describes `matchCount`. */
matchCountExact: boolean
}Backwards compatibility for selectedRowIds
- With
enableQuerySelection: false(the default), nothing changes:selection,defaultSelection, androwCountExactare ignored,update:selectionis never emitted, and every existing selection test keeps passing unchanged. - With
enableQuerySelection: true,selectionis the source of truth andselectedRowIdsbecomes a read-only projection that keeps its exact meaning, explicitly selected ids:idsmode:selectedRowIdsequalsselection.ids.querymode:selectedRowIdsis[]. It never holds the loaded, non-excluded ids, because an app that readsselectedRowIdsfor a bulk action would then act on one page instead of 2,298 rows. An empty list fails safe: the app acts on nothing, and the#bulkActionscount still comes fromselectedCount.update:selectedRowIdsis still emitted whenever the projection changes. AselectedRowIdsordefaultSelectedRowIdsprop is ignored, with a development warning, so the two models cannot disagree.
#bulkActionskeepsselectedRowIdsandclearSelection. With query selection enabled,selectedCountfollows the definition above rather thanselectedRowIds.length, and the newselectionprop is what an action sends.
State model
Query identity. The query is the committed columnFilters (active entries only, per the clear sentinels) and the committed globalFilter at the moment selectAllMatching() runs. sorting and pagination are not part of the identity. queryKey is opaque to the table: it is stored and returned, never compared.
Stored query snapshot. Filter values can be mutable (a Date, a range array, a reactive object). If selection.query kept references to them, an in-place edit after the opt-in would silently change what the bulk action targets. So selectAllMatching() stores a deep snapshot: it unwraps Vue proxies with toRaw at every level, copies arrays and plain objects into new ones, converts each Date to its ISO 8601 string with toISOString(), and deep-freezes the result. The consumer's filter objects are read once and never mutated. The supported filter values are JSON-safe: strings, finite numbers, booleans, null, arrays, plain objects, and valid Dates, nested in any combination that forms an acyclic tree. Two values that fit those types still do not round-trip, so the snapshot canonicalizes them: -0 is stored as 0 (JSON.stringify writes 0), and an array hole is rejected like an unsupported value because JSON.stringify turns it into null. Every supported value survives JSON.stringify unchanged in meaning, so the request sketch below can never throw or drop part of the query. The snapshot contains no undefined: "no global filter" is stored as null, and the clear sentinels of inactive column filters are removed before the snapshot is taken.
Object.freeze does not freeze a Date's internal time, so a frozen Date could still be changed with setTime() by any code holding selection. The snapshot therefore never contains a Date or any other object with internal state: only primitives, frozen arrays, and frozen plain objects, which cannot change. The ISO string round-trips exactly (new Date(iso).getTime() equals the original time) and is what JSON.stringify sends for a Date, so a request body built from selection.query matches one built from the live filters. An app that needs a Date back calls new Date(value) on its own copy.
When a committed filter value holds anything else, at any depth, the table cannot promise a stable, sendable copy, so canSelectAllMatching is false and a development warning names the column (or globalFilter) and the value's type. That covers primitives JSON cannot carry (bigint, which makes JSON.stringify throw; symbol and undefined, which it drops; NaN, Infinity and -Infinity, which it turns into null), functions, class instances, DOM nodes, Map, Set, an invalid Date, and any array or plain object that contains itself, directly or through a descendant (a cycle, which makes JSON.stringify throw). The table detects cycles with an ancestor set while it copies, before recursing, so a cyclic value is rejected instead of overflowing the stack. An app with such a filter serializes it to a supported value first.
Row ids follow the same rule. In query mode every row id must be a string or a finite number, because JSON.stringify turns NaN, Infinity and -Infinity into null, and the server could then fail to exclude a row the operator unchecked. A loaded row with a non-finite numeric id makes canSelectAllMatching false with a development warning naming the row. If such a row arrives on a later page while a query selection is active, its checkbox is rendered disabled and toggleRowSelected is inert for it, and while such a row is visible the select-all checkbox is disabled and toggleAllRowsSelected is inert in query mode, so the id can never enter excludedIds through either path; the same warning is logged. The operator can still clear the selection or change the filter.
Live membership. A query selection means "rows that match query when the server runs the action, minus excludedIds". The table cannot take a snapshot without the ids, so it does not promise one. It records matchCount (the total the operator saw) so the server can detect drift, and it carries an app-supplied queryKey as opaque correlation metadata, for example a request or audit id. queryKey must not change which rows the action touches: the table renders rows, checkbox state and counts from the live query, so a server that pinned membership to an older snapshot would act on a different set than the operator sees. Snapshot-pinned selection is out of scope for this proposal and would need its own amendment that keeps data and counts on the same snapshot. Whether drift is acceptable is server policy.
Transitions in query mode:
| Event | Selection | Announcement |
|---|---|---|
Page change (setPageIndex) or pageSize change | Kept, including excludedIds | None |
| Sort change | Kept | None (sort has its own) |
data reference change (a new page arrives) | Kept. New rows render checked unless excluded. | None |
rowCount changes in a later response | Kept. selectedCount uses the new total; matchCount stays. | None |
Filter committed through the table, or a filter edited in place and picked up by the next stateChange | Cleared to { mode: 'ids', ids: [] } | filter-changed |
columnFilters or globalFilter prop changes (URL, Back) | Cleared to { mode: 'ids', ids: [] } | None: the app owns that navigation |
| Uncheck a row / check an excluded row | Id added to / removed from excludedIds | None: the checkbox announces |
clearSelection() or resetRowSelection() | { mode: 'ids', ids: [] } | cleared when user-initiated |
retry() | Kept (same query) | None |
disabled or enableRowSelection: false | Kept but inert, as today | None |
A filter "change" compares the effective filters with the snapshot in selection.query structurally: the same active entry ids in the same order, and values deeply equal over the supported types (primitives by Object.is after the same canonicalization the snapshot applies, so a live -0 equals the stored 0; arrays by position; plain objects by own enumerable keys), with each live Date compared through its toISOString() value and globalFilter compared after normalizing the clear sentinels. A new Date with the same time is not a change, and neither is replacing a Date with its own ISO string, because both send the same request. The comparison runs on every filter commit, every columnFilters or globalFilter prop update, and before every stateChange the table emits in query mode. The last point catches a filter object the app edited in place: the next page request would carry the edited filter, so the selection clears in the same action and that request's rows are never shown as selected. When in doubt the rule clears: losing a selection costs the operator two actions, while keeping a stale one would run an action on rows the operator never saw.
Selections in ids mode keep today's rules on filter change: explicit ids are kept and never pruned in server mode.
Opting in replaces explicit ids. selectAllMatching() discards the ids list. Ids on the current page match the query, so they are covered. Ids kept from an earlier filter may not match, and the server cannot tell them apart from matches without an includedIds list, which would bring back the unbounded list this amendment avoids. The opt-in control's label states the resulting count, so the operator sees the new scope before acting (QS7).
Estimated totals
rowCount remains required with manualPagination, and it still sets pageCount and clamps pageIndex exactly as in Pagination. This amendment does not add a separate pagination bound. With rowCountExact: false the optional pageCount override must be omitted: when one is passed it is ignored with a development warning, so the estimate alone sets the page count and the bounds below keep every row reachable. A server that only estimates its total passes the estimate and sets rowCountExact: false, which changes only selection counts and wording, so the estimate must never make a reachable row unreachable:
- the app passes at least
(pageIndex − 1) × pageSize + data.length, the rows already reached; and - while the server reports more rows after the current page, at least
pageIndex × pageSize + 1, so the pager always offers the next page.
An app that cannot meet this (a cursor API with no total) is outside this amendment; unknown-total pagination would need its own pagination amendment. An estimate never refuses the opt-in: with rowCountExact: false, canSelectAllMatching is true whenever the visible page is fully selected and the filters can be snapshotted. matchCountExact is then false, and the default labels say "about 2,300".
Counts
Membership is live, so rowCount − excludedIds.length is exact only while nothing is excluded. An excluded row can later leave the query (deleted, or edited so it no longer matches). The server's rowCount then drops, but excludedIds still holds that id, and the table cannot tell which exclusions still match without the ids. With an exact rowCount, the true count is therefore never lower than selectedCount, so selectedCountKind is 'atLeast' once any row is excluded. For a query selection with an estimated rowCount it is 'estimate'. An ids selection is always 'exact', even with rowCountExact: false, because it counts explicit ids and never reads rowCount. The table never reports a drift-prone count as exact. An app that needs an exact number asks the server to resolve the selection (for example in a confirmation step before the action) and shows that count in its own UI. A query selection never clears itself when selectedCount reaches zero; the operator or the app clears it.
Rejected actions, size, and SSR
Rejected bulk actions. The table does not observe the action. When the server rejects it (not authorized, query too broad, matchCount drifted past the server's limit, or a partial failure), the application leaves the selection unchanged so the operator can retry, narrow the filter, or exclude more rows, and it shows the reason in its own UI. It calls resetRowSelection() only after success, if it wants to. The table adds no error state, retry policy, or confirmation step of its own.
async function markSent(selection: DataTableSelection) {
const body =
selection.mode === 'ids'
? { ids: selection.ids }
: {
filter: selection.query,
excludeIds: selection.excludedIds,
expectedCount: selection.matchCount,
expectedCountExact: selection.matchCountExact,
queryKey: selection.queryKey,
}
const response = await fetch('/api/invoices/mark-sent', {
method: 'POST',
body: JSON.stringify(body),
})
if (!response.ok) {
actionError.value = await describeRejection(response) // selection kept
return
}
table.value?.resetRowSelection()
}The server resolves filter minus excludeIds itself and then uses the two count fields only as a drift check, never as the number of rows to change:
expectedCountExact: true:expectedCountis the exact total the operator saw. The server compares it with the current total forfilterand applies its own drift policy (for example, run within a tolerance, or reject and return the new total so the app can ask the operator to confirm).expectedCountExact: false:expectedCountwas an estimate. The server must not reject because the current total differs from it. It may use it only as a rough scale check, such as refusing when the resolved total is far larger than the operator could have expected.
Size. The selection grows only with excludedIds, one entry per row the operator unchecks. It does not grow with the number of matches.
SSR. A controlled selection renders checked rows and counts on the server with no announcement. The table does not check whether a controlled query selection matches the current filters; an app that restores both from a URL restores them together.
Worked trace: 2,300 matches, 25 per page
Server invoice table with enableQuerySelection, filtered to status = unpaid, rowCount: 2300, pageSize: 25 (92 pages). The default labels below assume an English locale. In step 2 the selection becomes { mode: 'query', query: { columnFilters: [{ id: 'status', value: 'unpaid' }], globalFilter: null }, excludedIds: [], matchCount: 2300, matchCountExact: true }.
| Step | Operator action | selection after | selectedRowIds | selectedCount | Select-all checkbox | Announcement |
|---|---|---|---|---|---|---|
| 1 | Page 1, Space on the select-all checkbox | { mode: 'ids', ids: [25 ids] } | 25 ids | 25 | checked | page-selected: "25 rows selected. All 2,300 matching rows can be selected." |
| 2 | Activates Select all 2,300 matching in the bar | query mode, excludedIds: [] | [] | 2,300 | checked | all-matching: "All 2,300 matching rows selected." |
| 3 | Goes to page 3 | Unchanged. One stateChange for the page, none for the selection. | [] | 2,300 | checked | None |
| 4 | Space on INV-0061's checkbox | excludedIds: ['INV-0061'] | [] | 2,299 | mixed | None (the checkbox reports "not checked") |
| 5 | Goes to page 40, unchecks INV-0987 | excludedIds: ['INV-0061', 'INV-0987'] | [] | 2,298 | mixed | None |
| 6 | Back to page 3 | Unchanged | [] | 2,298 | mixed; INV-0061 unchecked | None |
| 7 | App runs Mark sent | Unchanged. The app sends the query, both ids, expectedCount: 2300. | [] | 2,298 | mixed | App-owned result message |
| 8 | Activates Clear selection | { mode: 'ids', ids: [] } | [] | 0 | unchecked | cleared: "Selection cleared." |
From step 4 on, selectedCountKind is 'atLeast', so the bar reads "At least 2,299 selected" and then "At least 2,298 selected". In steps 1–3 it is 'exact'.
Variations from step 6:
- The server rejects step 7 (for example, the operator may not change 40 of the invoices). The selection stays as in step 6. The app shows the reason; the operator can exclude rows or narrow the filter and try again.
- The operator changes the filter to
status = overdue. OnestateChangefetches page 1. The selection clears to{ mode: 'ids', ids: [] }, the bulk-actions bar unmounts, focus stays in the filter control, and the region says "Selection cleared because the filter changed." - The operator sorts by amount. The selection and exclusions are kept.
- A later page reports
rowCount: 2310.selectedCountbecomes 2,308 ("At least 2,308 selected").matchCountstays 2,300, so the server sees the drift inexpectedCount. - The app edits the status filter object in place, then the operator changes page. Before emitting that
stateChange, the table compares the filters with the snapshot, clears the selection, and announcesfilter-changed. The stored query never changed. - The operator unchecks the select-all checkbox on page 3. The 24 page-3 ids not yet excluded join
excludedIds, andselectedCountbecomes 2,274. The selection is not cleared; Clear selection does that.
Accessibility
- Controls. The opt-in and clear controls are native
<button type="button">elements in#bulkActions, so the bar's existing place in the Tab order applies. Their visible text names the scope and count ("Select all 2,300 matching invoices", "Clear selection"). There are no new keys:EnterandSpaceactivate the buttons, andSpacestill toggles checkboxes. - Labels. Row checkbox names (
rowSelectionLabel) and the select-all name (selectAllLabel) do not change. Inquerymode the select-all checkbox still acts on visible rows, and its checked and mixed states describe only those rows. The bar's visible count tells the operator the full scope. - Counts. The bar shows
selectedCountas text, worded byselectedCountKind: "2,300 selected" ('exact'), "At least 2,298 selected" ('atLeast'), or "About 2,300 selected" ('estimate'). The count is not a live region; the announcements below cover the transitions. - Focus. The recommended pattern keeps one button mounted whose label switches between the opt-in and Clear selection, so focus never moves. If the focused control unmounts after
selectAllMatching(), the preset moves focus onnextTickto the first tabbable element in the bar. The existing bulk-actions dismissal rule still moves focus to the select-all checkbox when the bar unmounts.
Announcements
One polite, atomic region outside <table>, filled by selectionAnnouncementLabel:
page-selected: a user selection action (the select-all checkbox or checking the last unchecked visible row individually) made the visible page fully selected, andcanSelectAllMatchingistrue. This is the only cue for a screen-reader user that the opt-in exists, because the bar sits before the table in the Tab order.all-matching:selectAllMatching()ran.cleared: a user action cleared the selection throughclearSelection()orresetRowSelection().filter-changed: a filter committed through the table cleared aqueryselection. Clearing silently would drop a 2,300-row selection without notice. Keeping the selection would leave the bar describing rows that no longer match what is on screen.- Row and select-all toggles announce nothing extra; the checkbox state already does. Once the selection no longer matches the announced state (for example a row is unchecked after
page-selected), the region is emptied, so repeating the same transition with the same counts produces a fresh announcement instead of an unchanged string. Prop-driven changes (URL restore, Back), SSR, and mount announce nothing, matchingsortAnnouncement.
Default strings format numbers with Intl.NumberFormat in the runtime's default locale. They are produced only after a user action, so they cannot cause a hydration mismatch. Apps localize them through selectionAnnouncementLabel.
Implementation acceptance cases
- Opt-out parity (unit and browser). With
enableQuerySelection: false,packages/vue/src/GhostDataTable.selection.test.tsandtests/e2e/ghost-data-table-selection.spec.tspass unchanged, andupdate:selectionis never emitted. - Mode guard (unit). With
manualFiltering: falseormanualPagination: false,selectAllMatching()is inert,canSelectAllMatchingisfalse, and a development warning names the missing option. - Trace (Vue Test Utils). Steps 1–8 of the worked trace assert
selection,selectedRowIds,selectedCount, the select-all state, the announcement, and that no step emits a selection-drivenstateChange. - Transitions (unit). Every row of the transitions table, including a prop-driven filter change (cleared, no announcement), a same-content new filter value such as an equal
Date(kept), sort and page size (kept),retry()(kept), androwCountdrift (selectedCountupdates,matchCountdoes not). AfterselectAllMatching(), mutating the committedDate(setTime()), range array, or reactive filter object in place leavesselection.queryunchanged, and the nextstateChangeclears the selection before it is emitted.selection.querycontains noDateinstance (aDatefilter is stored as its ISO string), every object and array in it is frozen, andnew Date(stored).getTime()equals the original time. A function, class-instance, invalidDate,bigint,symbol, nestedundefined,NaN,Infinity, or cyclic filter value, or a loaded row with aNaNor infinite id, makescanSelectAllMatchingfalsewith a warning (and, when that row loads on a later page inquerymode, its toggle and the select-all checkbox are disabled and inert), and every supported snapshot round-trips throughJSON.stringifyandJSON.parseto an equal value, including a filter holding-0(stored as0, and a later page or sort change with that live-0keeps the selection); a sparse array makescanSelectAllMatchingfalse. - Select-all in
querymode (unit and browser). With an empty visible row set (an empty response, the last row deleted, or SSR before data), both header flags arefalseandcanSelectAllMatchingisfalse, even with explicit ids still selected. Unchecking the select-all checkbox adds only visible ids toexcludedIds, checking it removes them, and the mixed state follows exclusions on the page. - Estimated totals and counts (unit). With
rowCountExact: false, labels use the estimate wording,canSelectAllMatchingistruewhen the estimate equals the visible row count, the documented lower bounds keep the next page reachable, apageCountoverride is ignored with a warning, and excludingrowCountrows leaves thequeryselection in place. With an exactrowCount,selectedCountKindis'exact'with no exclusions and'atLeast'after one, including after a response where an excluded row has left the query. Anidsselection reports'exact'withrowCountExact: false. - Compatibility (unit and
vue-tsc).selectedRowIdsis[]inquerymode and equalsidsinidsmode; a boundselectedRowIdsprop is ignored with a warning;DataTableSelectionnarrows onmode, and readingexcludedIdswithout narrowing is a type error. - Async (unit). A stale page response that arrives after a filter change cannot bring back checked rows for the old query: the selection is already cleared, and the request guard drops the response.
- Keyboard, focus, and axe (browser). On the preset:
Spaceon the select-all checkbox,Shift+Tabto the opt-in,Enteractivates it, focus stays on the mounted button or moves into the bar, the live region text matches the trace, Clear selection returns focus to the select-all checkbox, and axe reports no violations with the bar open and closed. Checking the visible rows one by one withSpaceannouncespage-selectedexactly once, when the last unchecked visible row is checked, and not before; a unit test asserts the same for row-by-rowtoggleSelectedcalls. Repeating a transition (select the page, uncheck one row, recheck it; or clear, select one row, clear again) announces the second time too. - SSR (integration). A controlled
queryselection renders checked rows on the server, hydrates without a mismatch, and leaves the live region empty. - Example. A server invoice example whose mock server resolves query selections, including a rejected action, covered by an integration test and a browser test.
Documentation plan
docs/components/data-table.md: a "Select every matching row" section with the server example, theselectionshape, a request body sketch, and the rule that the server authorizes and runs the action.- The preset layout slots section lists the new
#bulkActionsprops and the single-button focus pattern. - Manifests describe
enableQuerySelection,selection,defaultSelection,rowCountExact,update:selection, andselectionAnnouncementLabel; generated API tables are refreshed withpnpm docs:api:write. - A
@ghostvue/vueminor Changeset, and a@ghostvue/themesChangeset if the themed wrapper forwards the new props.
Compatibility
- Additive and opt-in. Default behavior, events, DOM, and announcements do not change, so existing consumers need no migration.
- Opting in changes what
selectedRowIdsand the#bulkActionsselectedCountmean for that instance, as described in Backwards compatibility. The guide and the Changeset call this out.
Decisions for maintainer review
Resolved 2026-12-04. The maintainer approved the proposed option for each item. The alternatives not chosen stay listed as the record of what was considered.
- QS1 — Amend the non-goal. Replace it with the narrower text under Scope and responsibilities: the table records a query selection; resolving, authorizing, and running stay with the server. Not chosen: keeping the non-goal and leaving the pattern to each app.
- QS2 — Opt-in surface.
enableQuerySelection, valid only withmanualPaginationandmanualFiltering. Not chosen: always on in server mode, which would changeselectedRowIdsfor existing apps. - QS3 — Controlled state. A new
selectionv-model with a discriminated union;selectedRowIdsbecomes a read-only projection that is[]inquerymode. Not chosen: overloadingselectedRowIdswith a sentinel, or filling it with loaded rows, either of which lets an existing bulk action silently act on the wrong set. - QS4 — Query identity and snapshot. Active
columnFiltersplusglobalFilter, stored as a deep, frozen snapshot of JSON-safe values (eachDatestored as its ISO string; other values disable the opt-in) and compared structurally, including before eachstateChange;sortingandpaginationexcluded; an opaquequeryKeystored but never compared. Not chosen: keeping references (in-place edits would change the target), keeping frozenDateobjects (setTime()still works on them), handing out a defensive copy on every read (the boundselectionobject would still be mutable), epoch milliseconds (loses theJSON.stringifymatch), requiring apps to treat filters as immutable (not enforceable), or an app-supplied clone or equality callback. - QS5 — Live membership. Resolved when the server runs the action, with
matchCountrecorded for drift checks andqueryKeyas opaque correlation metadata that never changes membership. Not chosen: claiming a snapshot the table cannot enforce, or lettingqueryKeypin the action to a snapshot while rows and counts show the live query. - QS6 — Select-all checkbox in
querymode. Acts on visible rows (exclusions), keeping one meaning for that control; Clear selection clears everything. Not chosen: unchecking it clears the whole query selection. - QS7 — Opting in replaces explicit ids. Not chosen: keeping an
includedIdslist alongside the query. - QS8 — A filter change clears and announces. Not chosen: keeping the query (the bar would describe rows the operator no longer sees) or re-targeting it to the new filter (which silently changes scope). Prop-driven filter changes also clear, without an announcement.
- QS9 — Estimated totals and count wording.
rowCountExact: falseswitches counts to estimate wording and stops an estimate from refusing the opt-in;rowCountstill bounds pagination, with the documented lower bounds that keep rows reachable. Counts are'atLeast'once any row is excluded, and aqueryselection never clears itself at a zero count. Not chosen: a separate pagination bound or a nullablerowCount(both are pagination changes for their own amendment), or a required server-resolved count (an extra request on every exclusion). - QS10 — Implementation gate. Implementation starts only after this amendment merges on
masterwithspecStatus: approvedevidence that covers QS1–QS9, and a maintainer assigns a target release. The approval PR applies the non-goal text, marks this section approved, and adds animplementationGatesentry in.github/release-scope.jsonmapping the implementation issue todata-tableif that issue is public. Runtime changes, examples, manifests, and Changesets belong to the implementation work, not this amendment.