Skip to content

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.0 addendum (#316 / GHO-249): Following the 2026-11-25 roadmap review, the single-sort themed wrapper in @ghostvue/themes and companion GhostDataTablePreset layout slots in @ghostvue/vue are specified in the Themed GhostDataTable addendum below (decoupled from multi-column sort #317, which stays deferred to 0.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 stickyHeader on themed GhostDataTable (0.1.0) is specified in the Themed GhostDataTable addendum.
  • 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 to 0.3.0 in #317; single primary sort column only. See the approved Multi-column sort specification (GHO-250)).
  • Themed GhostDataTable in phase one (headless examples and docs shipped first; 0.1.0 single-sort @ghostvue/themes wrapper and preset layout slots are specified in the Themed GhostDataTable addendum 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 data array; 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).

ts
/** 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.

ts
/** 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).

RuleDefault
Global filter participationA 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 matchWhen 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-stringNon-string globalFilter values use strict equality (===) against each participating column’s cell value (logical OR across columns). Skip null / undefined cell values.
Clear global filterundefined, null, or '' (empty string) means no global filter; all rows pass the global stage.
Column filter clearA columnFilters entry is inactive when value is undefined, null, or ''. Inactive entries do not constrain rows.
Column filter default filterFnWhen 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 orderGlobal 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 ​

manualPaginationmanualSortingmanualFilteringdata contentsrowCountComposable processing
falsefalsefalseFull local setfiltered.length (derived)Global sort → global filter → slice page
false**Full local setderivedSort/filter per manual flags on full set
truefalsefalseOne server pagerequired propPage-local sort then page-local filter on data only
truetruefalseOne server pagerequiredPage-local filter only
truefalsetrueOne server pagerequiredPage-local sort only
truetruetrueOne server pagerequiredNo 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:

OptionTypeDefaultContract
datareadonly TData[]requiredConsumer-owned rows. Reference change triggers reset rules.
columnsDataTableColumnDef<TData>[]requiredNot mutated by the library.
getRowIdDataTableGetRowId<TData>requiredRequired in every build; no production fallback.
manualSortingbooleanfalseWhen true, composable does not sort data for server-global sort.
manualFilteringbooleanfalseWhen true, composable does not filter for server-global filter.
manualPaginationbooleanfalseWhen true, data is one page; rowCount required.
rowCountnumberderivedRequired iff manualPagination; total matching query on server.
pageCountnumberderivedOptional override; otherwise from rowCount and pageSize.
enableRowSelectionbooleanfalseWhen false, selection APIs are inert.
enableRowExpansionbooleanfalseWhen false, expansion APIs are inert.
allowMultipleExpandedbooleantrueWhen false, opening one row collapses others.
loadingbooleanfalseSets aria-busy on the table region.
disabledbooleanfalseDisables 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.

ConcernContract
PlacementDefault child of GhostDataTable (same slot as manual composition). Mutually exclusive with a custom #default render in one tree (consumer picks preset or manual).
PropsemptyTitle?: 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 targetFeature-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.

vue
<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).

vue
<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 …), and rowExpansionLabel(rowId) (Show details for …). emptyHeadingLevel (default 3) sets the GhostEmptyState title level so the empty state fits the page outline (axe heading-order).
  • The selection <th> is named by aria-label (it holds only the select-all checkbox); the expansion <th> holds visually hidden text, so axe empty-table-header passes. Expand buttons show an aria-hidden glyph and are named by aria-label on the button.
  • The default search is a labelled GhostInput type="search" that commits through the root's setGlobalFilter (server filtering resets to page 1 with one stateChange). Use #search to debounce. The field is disabled while the root is disabled.
  • detail, toolbar, and search are reserved slot names; do not use them as column ids. Attributes on the preset land on GhostTable.
  • Tests: GhostDataTablePreset.test.ts (unit), the example and SSR hydration tests, type-tests/GhostDataTablePresetConsumer.vue, and a Playwright test in tests/e2e/ghost-data-table.spec.ts that 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:

  1. Focus the Amount sort button; press Space or Enter to sort.
  2. Space on row inv-2 checkbox to toggle selection (inv-2 starts selected).
  3. Space on inv-2 expand button (getRowExpandButtonProps) to collapse the open detail row; Space again on the same button to reopen it.
  4. Type a global filter that matches no rows; header row stays mounted; body shows GhostEmptyState with visible #title text No invoices.
vue
<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 ​

BindingHostContract
tableRootPropsGhostTable root wrapper or <table>aria-busy when loading; data-ghost-data-table; optional aria-labelledby / aria-label from consumer
getHeaderCellProps(columnId)GhostTableHeaderCellscope: '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
detailRowPropsexpansion <tr> via GhostTableRowKeeps 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.
headerSelectionStateheader GhostCheckbox{ allSelected, someSelected } over the select-all target (local: getPrePaginationRowModel() ids; server: getRowModel() ids)
toggleAllRowsSelectedheader checkboxToggles 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 GhostCheckboxaria-label merged onto the focusable checkbox control (not wrapper-only)
getHeaderSelectionCheckboxProps(options?)header GhostCheckboxaria-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 buttonaria-label and aria-expanded on the button; aria-controls → detail row id; Space toggles when focused
pagination, pageCount, rowCountGhostPaginationEffective (clamped) pagination, pager page count, and query-wide row count (Pagination)
setPageIndex(pageIndex)GhostPagination update:modelValueCommits 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 ​

StatePropEmitUncontrolled initial
Sortingsortingupdate:sortingdefaultSorting (DataTableColumnSort[], max length 1)
Column filterscolumnFiltersupdate:columnFiltersdefaultColumnFilters
Global filterglobalFilterupdate:globalFilterdefaultGlobalFilter
Paginationpaginationupdate:paginationdefaultPagination
Row selectionselectedRowIdsupdate:selectedRowIdsdefaultSelectedRowIds
ExpansionexpandedRowIdsupdate:expandedRowIdsdefaultExpandedRowIds

All use useControllableState.

Reset rules (applied before any stateChange emit):

EventSortingFiltersPagination reset
globalFilter changekeptupdatedmanualFiltering: 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 changekeptupdatedSame as globalFilter.
pagination.pageSize changekeptkeptpage → 1
data reference changekeptkeptmanualPagination: false: keep index, clamp (no unconditional reset). manualPagination: true: keep index when only the page slice was replaced.
sorting changeupdatedkeptkept (then clamp if pageCount shrinks)

Selection / expansion on filter/pagination events: kept (pruning rules below).

Pagination reset acceptance:

SetupAction on page 4Expected paginationstateChange / server requests
manualPagination: true, manualFiltering: false (page-local filter)Change global/column filterStay on page 4Zero (no server refetch)
manualPagination: true, manualFiltering: true (server filter)Change filterpage → 1Exactly 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.

ModePrune 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)NoNo — preserve ids across filtered responses until consumer replaces full source or user clears selection
Server page (manualPagination: true)NoNo — ids stay when changing pages or filtered page payloads

Required tests:

  • Local: select A, filter hides A, refresh data with 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 with query.pagination.pageIndex === 1 and new filter; page-local filter on page 4 → no stateChange). Server consumers should fetch from payload.query only, not from separate v-model handlers.
  • Filter + pagination coalescing: When manualFiltering: true resets pageIndex to 1, emit exactly one stateChange whose query carries both the new filter and pagination.pageIndex === 1, with trigger: 'globalFilter' | 'columnFilters'. Do not emit a second stateChange (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, expandedRow slots — optional overrides.
  • Exposed: toggleAllRowsSelected, toggleRowSelected, toggleRowExpanded, resetRowSelection, retry() (re-emits stateChange with the current query and a fresh composable-minted requestId; 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.

ModeSelect-all targetEffect
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 ​

ModelDefinition
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 DataTableColumnSort entry.
  • Tri-state: none → asc → desc → none.
  • aria-sort only 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):

    ModepageIndex after the filter changestateChange
    manualFiltering: true (server filter)1, written in the same actionOne, trigger globalFilter / columnFilters, query.pagination.pageIndex: 1; no follow-up
    Full local (manualPagination and filtering false)Kept; clamped to the last valid page when the filtered count shrinksNone
    Page-local (manualPagination: true only)Kept, even when the visible slice is emptyNone

    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.

vue
<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 inside role="toolbar" is an arrow-key dead end inside the toolbar's single Tab stop. Keep the labelled field its own Tab stop and put buttons and toggles in the toolbar.
  • Server mode: add manual-filtering (and manual-pagination / row-count as 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 by requestId (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 pageIndex with GhostPagination.
  • Whenever pageIndex > pageCount, clamp to pageCount (Zac approved).
  • rowCount === 0: pageCount 1, pageIndex 1 (query-wide empty).
  • rowCount > 0 with empty getRowModel(): keep pageIndex (page-local filter on a server page does not coerce page 1).
  • Which rowCount (GHO-238): with manualPagination it is the rowCount prop (the server total for the query), never the loaded page length; otherwise the filtered local row count.
  • When the clamp runs: whenever the derived pageCount changes (filter shrink, local data reference change, server rowCount or pageCount change). The clamp writes the pagination v-model once. With manualPagination it also emits exactly one stateChange (trigger: 'pagination', clamped query.pagination) so the consumer fetches the page it now shows; the parent's v-model echo emits nothing more. A pagination value restored out of range (URL hydration, first render) is clamped on read only: no write and no stateChange.

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:

vue
<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 one navigation landmark.
  • 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 bypasses setPageIndex, so a server table emits no stateChange for the click.
  • Executable reference: examples/data-table/paginated-invoices.vue (local search clamps the page; zero matches show page 1 of 1). The Playwright spec tests/e2e/ghost-data-table-pagination.spec.ts runs 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:

  1. Server mode, page 1: select row A.
  2. Navigate to page 2: select row B.
  3. 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 ​

StateBehavior
loadingaria-busy="true" via tableRootProps
Empty bodyGhostEmptyState 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).
disabledNo emits from controls

Async behavior ​

  1. User action → coalesced v-models + one stateChange.
  2. Consumer: loading = true; begin(payload.requestId).
  3. Apply data / rowCount / error only if isLatest(requestId).
  4. finally blocks from stale requests must not clear loading, rows, totals, or error state for a newer in-flight or completed request (tie-break with requestId, not wall-clock alone).
ts
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: true and 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 no stateChange.

Server state, URL, Back, and Retry ​

Consumer-owned fetching; the composable owns query state and request identity only. Pattern aligned with PrimeVue stateful tables.

ConcernContract
URL hydrationApplying 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 queryEach 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 BackWhile 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.
RetryCall 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 ​

  • getRowId is required in all builds (development and production).
  • Prefer accessorKey / accessorFn; optional cell hook for custom VNodes.
  • Column meta is 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> via GhostTable.
  • Sort control: button type="button" in header; aria-sort on <th>.
  • Selection: GhostCheckbox per row and header; labels via aria-label.

Keyboard interaction ​

KeyContextBehavior
SpaceGhostCheckboxToggle checked (checkbox-spec); Enter does not toggle
Enter / SpaceSort buttonActivate sort
Enter / SpaceExpand buttonToggle expansion
TabTableBetween 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 indeterminate on header checkbox (see checkbox spec).
  • Optional live region for async refetch: consumer-owned.

Rendering and customization ​

  • GhostTable data-part hooks unchanged.
  • Header sort styling: data-sort="asc" | "desc".
  • Selected row: data-selected="true" on GhostTableRow (not data-state).
  • Expanded data row: data-expanded="true" on data <tr>.
  • Detail row: GhostTableRow keeps data-part="row" from mergeGhostTablePartAttrs (consumer attrs cannot replace data-part); detailRowProps adds data-detail-row="true" for styling (.ghost-table-row[data-detail-row]). Do not set data-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 with pnpm bench:data-table (not part of pnpm 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):

ScenarioAssertion
Page change after local sortComparator / sortFn not invoked again (zero additional sort passes).
Toggle selection on one visible rowZero 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 rowCount pagination, coalesced stateChange, page-local vs global sort semantics.
  • Unit: manualFiltering: true filter on server page 4 → onestateChange only (trigger filter + pageIndex: 1 in query); no follow-up pagination stateChange in 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 data rows, not filtered view (select A, filter out A, refresh data, clear filter).
  • Acceptance: cross-page selection test (pages 1 → 2 → 1).
  • Playwright (approval fixture b): sort Amount; Space on inv-2 checkbox; Space on 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: useGhostDataTableServerRequest races; stale finally cannot clear loading.
  • Unit: performance regressions (page after sort, selection without sort/filter).
  • Vue: basic (a) + full (b) examples hydrate; GhostDataTableTable slot 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-located GhostPagination (no empty <th>, no wrapper-only aria-* without focusable names).
  • Type: defineDataTableColumns acceptance trio (toFixed, toUpperCase error, rename break).
  • Type: generic slot contexts still expose getValue(): unknown.

Documentation plan ​

  • docs/components/data-table.md with (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/vue only; the 0.1.0 themed addendum (#316 → #333) adds opt-in layout slots to @ghostvue/vue GhostDataTablePreset and themed exports in @ghostvue/themes without breaking phase-one consumers.
  • Changesets for @ghostvue/vue and @ghostvue/themes ship 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) ​

  1. Single-sort scope for 0.1.0 (decoupled from #317): Themed GhostDataTable ships in 0.1.0 on today's phase-one single-sort headless contract (aria-sort="ascending" | "descending" plus data-sort="asc" | "desc" on the active <th> only, paired with getSortButtonProps(columnId) on the native <button type="button">). Multi-column sort (#317) remains deferred to 0.3.0 on its independent spec track and no longer blocks #316 or #333; any multi-sort priority badge in 0.3.0 will layer additively inside the sort header button without breaking 0.1.0 selectors or DOM contracts.
  2. Composable themed architecture (ADR 0003 & ADR 0004):
    • Headless preset layout slots (@ghostvue/vue): GhostDataTablePreset gains camelCase layout slots #toolbarStart, #toolbarEnd, #bulkActions, and #footer alongside #search, #toolbar, #<columnId>, and #detail, with per-preset opt-in via layoutSlots in packages/vue/src/ghost-data-table-preset.ts. @ghostvue/vue owns all layout structure, state wiring, and focus restoration; it never imports @ghostvue/themes.
    • Themed wrappers (@ghostvue/themes): Exports themed GhostDataTable (size?: 'sm' | 'md', variant?: 'plain' | 'card', stickyHeader?: boolean), GhostDataTableTable, and GhostDataTablePreset (plus convenience re-exports of defineDataTableColumns, useGhostDataTable, useGhostDataTableServerRequest, the five getDataTable*Props helpers, and public DataTable types) backed by packages/themes/src/ghost-data-table.css inside @layer ghostvue-theme. Per ADR 0004, visual customization uses ordinary props, slots, class / style fallthrough, data-* hooks, and --ghost-* semantic tokens — never pt passthrough style maps.

Headless GhostDataTablePreset layout slots (@ghostvue/vue) ​

Exact TypeScript contracts (packages/vue/src/ghost-data-table-preset.ts) ​

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) adds selectedRowIds: () => readonly DataTableRowId[] and resetRowSelection: () => void from the root useGhostDataTable instance; #footer reads pagination, pageCount, rowCount, and setPageIndex through the existing withBindings bridge so manual #default and preset #footer can never drift.
  • By default the preset owns only detail, toolbar, and search. Each of the layout names remains available to the existing cell renderer. For example, a column named footer calls #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 #footer available 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 its cell hook 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:

  1. Legacy pre-header slot (#toolbar): rendered as-is before the header bar when $slots.toolbar is present, preserving exact phase-one markup order for existing consumers.
  2. Header bar (<div data-part="header" class="ghost-data-table-header">): rendered iff searchVisible || 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 labelled GhostInput 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 own Tab stop outside any consumer GhostToolbar (role="toolbar").
    • <div v-if="layout.toolbarEnd" data-part="toolbar-end"> wrapping <slot name="toolbarEnd" />.
  3. Bulk-actions bar (<div data-part="bulk-actions" class="ghost-data-table-bulk-actions">): rendered iff rowSelectionEnabled && selectedCount > 0 && layout.bulkActions, wrapping <slot name="bulkActions" v-bind="bulkActionsSlotProps" />. No role="alert" or aria-live is placed on this container (row and header checkboxes already announce checked state changes).
  4. Table (<GhostTable v-bind="tableProps">): fallthrough attributes (class, style, contain-horizontal, scroll-label, aria-label) on GhostDataTablePreset continue to forward onto GhostTable exactly as in phase one. Sortable headers in both GhostDataTableTable and GhostDataTablePreset expose the native button via data-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 in GhostDataTablePreset add data-part="expand-button".
  5. Footer bar (<div data-part="footer" class="ghost-data-table-footer">): rendered iff layout.footer is 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?: () => unknown and emptyActions?: () => unknown join GhostDataTablePresetLayoutSlots and take no slot props. They are available only when listed in layoutSlots. Without the opt-in, a column with id emptyDescription or emptyActions keeps 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 one GhostEmptyState. Its #title is still emptyTitle at emptyHeadingLevel, so the row has exactly one heading. An enabled, supplied emptyDescription renders into the empty state's #description (data-part="description") and emptyActions into #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:

ExportSourceContract
GhostDataTablepackages/themes/src/ghost-data-table.tsGeneric <TData> themed root wrapper adding size, variant, and stickyHeader over headless GhostDataTable.
GhostDataTableTablepackages/themes/src/ghost-data-table-table.tsGeneric <TColumns> themed table mapper preserving typed #<columnId> slots.
GhostDataTablePresetpackages/themes/src/ghost-data-table-preset.tsGeneric <TColumns> themed preset preserving typed #<columnId>, #detail, and all camelCase layout slots.
defineDataTableColumnsre-export from @ghostvue/vueSingle-import convenience for typed column definitions.
useGhostDataTablere-export from @ghostvue/vueHeadless state composable for custom layouts alongside themed parts.
useGhostDataTableServerRequestre-export from @ghostvue/vueMonotonic requestId guard for async server tables.
getDataTable*Props (all 5 interaction helpers)re-export from @ghostvue/vueAttribute helpers for manual GhostTable* composition inside themed GhostDataTable.
GhostDataTableSize, GhostDataTableVariant, …packages/themes + @ghostvue/vue type exportsVisual prop unions, GhostDataTableThemedProps<TData>, GhostDataTableThemedExposed<TData>, and DataTable*.

Themed GhostDataTable props and host contract ​

ts
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 GhostDataTable is renderless (<slot v-bind="slotProps" />), whereas themed GhostDataTable renders a single outer <div class="ghost-data-table ghost-themed-scope" data-part="root" data-themed> around the headless root. Including .ghost-themed-scope on the host automatically themes every nested Ghost primitive rendered inside the table (GhostTable, GhostCheckbox, GhostInput, GhostEmptyState, and a co-located GhostPagination) without requiring @ghostvue/vue to import @ghostvue/themes.
  • ariaLabel / ariaLabelledby routing (axe aria-prohibited-attr guard):ariaLabel and ariaLabelledby are declared props forwarded exclusively to the inner headless GhostDataTable (landing on the native <table> via tableRootProps). 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-table without overwriting ghost-data-table, ghost-themed-scope, data-part="root", or data-themed. Generic defineComponent signatures in packages/themes/src/ghost-data-table*.ts must preserve <TData> on GhostDataTable and <TColumns extends readonly DataTableTableColumnRef[]> on GhostDataTableTable and GhostDataTablePreset under tsc declaration emit and vue-tsc.
  • Standalone themed child wrappers: Themed GhostDataTableTable and themed GhostDataTablePreset also wrap or mark their output with .ghost-themed-scope (display: contents when wrapping) and data-themed="" so they render themed even when placed inside a headless GhostDataTable from @ghostvue/vue.

Worked themed example ​

vue
<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 ​

SurfaceSelector / attributeCondition / values
Themed root container.ghost-data-table[data-themed], data-part="root"Always on themed GhostDataTable; carries .ghost-themed-scope
Root densitydata-size="sm"Set when size === 'sm'; omitted for default 'md'
Root surface variantdata-variant="card"Set when variant === 'card'; omitted for default 'plain'
Root sticky headerdata-sticky-header=""Set when stickyHeader === true; omitted when false
Root disabled statedata-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 slotsdata-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 roottable.ghost-table[data-ghost-data-table], data-part="root"Native <table> (aria-busy="true" while loading, omitted otherwise)
Column header cellth.ghost-table-header-cell, data-part="header-cell"scope="col"; aria-sort + data-sort="asc" | "desc" on sorted column
Sort buttonbutton[data-part="sort-button"]Sortable <th> control in GhostDataTableTable / GhostDataTablePreset
Default sort indicatorThemed sort button ::afterDecorative CSS mark painted by @ghostvue/themes
Expand buttonbutton[data-part="expand-button"]Row disclosure toggle (aria-expanded="true" | "false")
Selected data rowtr.ghost-table-row[data-selected="true"]Boolean hook on selected body row (omitted when unselected)
Expanded data rowtr.ghost-table-row[data-expanded="true"]Boolean hook on expanded body row (independent of data-selected)
Detail rowtr.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 in packages/themes/src/ghost-data-table.css sits inside @layer ghostvue-theme wrapped in :where(...) (keeping pseudo-elements such as ::after outside :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/themes CSS 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 nested GhostTable rendered inside an expanded #detail panel or custom cell must not inherit outer data-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 from ghost-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-xs block and --ghost-space-inset-sm inline, and --ghost-control-size-sm-* sizing on sort/expand controls and default preset search input (preserving --ghost-control-touch-min on coarse pointers).
    • stickyHeader ([data-sticky-header]): sets position: sticky; inset-block-start: 0; z-index: 1 on column header cells (thead > .ghost-table-row > .ghost-table-header-cell) with opaque --ghost-surface-muted-bg (Canvas in forced-colors: active) and an inset block-end hairline box-shadow (inset 0 calc(-1 * var(--ghost-border-hairline-width)) 0 var(--ghost-border-default)) so header dividers stay visible over scrolled rows under border-collapse: collapse.

Single-sort header button indicator (0.1.0) ​

  • Interactive target: .ghost-table-header-cell > button (covering both [data-part="sort-button"] in GhostDataTableTable / GhostDataTablePreset and 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-visible draws outline: var(--ghost-focus-ring-width) solid var(--ghost-focus-ring-color) with outline-offset: calc(-1 * var(--ghost-focus-ring-width)) inside the button box so adjacent <th> borders, overflow-x: auto scroll containers, and stickyHeader: true never 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 ::after with empty CSS content and currentColor. Use the parent th[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-subtle and strengthens on hover or focus. Sorted headers use --ghost-surface-fg text, a --ghost-text-primary mark, and an accent bottom border. In forced colors keep the direction visible in ButtonText (GrayText when disabled) and draw the focus outline in Highlight. The header's aria-sort communicates 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 marked data-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)) with color: var(--ghost-surface-fg). Pairing --ghost-surface-fg against the soft primary mix preserves WCAG 2 AA (>= 4.5:1) text contrast across default, calm, vibrant, and mono in both light and dark modes.
    • Hover layering: Unselected body rows (:not([data-selected='true']):not([data-detail-row])) apply --ghost-surface-subtle-bg on :hover (when the table is not disabled). Selected rows deepen slightly on :hover by combining --ghost-state-mix-soft with --ghost-state-layer-hover so pointer tracking remains visible across selected runs.
    • Non-color distinction: Selection is never conveyed by row tint alone: the checked GhostCheckbox provides 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 logical border-inline-start or dir-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-fg text). Detail rows (tr.ghost-table-row[data-detail-row='true'] > .ghost-table-cell) use --ghost-surface-subtle-bg so expanded content reads as an inset panel distinct from selected data rows.
  • @media (forced-colors: active) (SelectedItem / SelectedItemText):
    • Windows Contrast Themes strip color-mix(...) washes back to Canvas. 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 with Canvas.
    • Nested interactive controls inside SelectedItem rows: Interactive descendants inside selected cells (button, input, select, textarea, a[href], [tabindex]:not([tabindex='-1'])) restore system control painting (forced-color-adjust: auto, or explicit ButtonFace / ButtonText on themed buttons/checkboxes and LinkText on links), and :focus-visible outlines drawn directly against a SelectedItem cell background use outline-color: SelectedItemText so keyboard focus never disappears into the selected row fill.

[aria-busy="true"] loading behavior ​

  • Semantic contract: Passing :loading="true" to GhostDataTable sets aria-busy="true" on <table data-ghost-data-table> via tableRootProps (omitted when loading is false).
  • 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 under prefers-reduced-motion: reduce and use Highlight in forced colors.
  • Interaction invariant during loading: aria-busy="true" must not set disabled, inert, or pointer-events: none on 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 by useGhostDataTableServerRequest() (including Browser Back and retry()).
  • Initial empty load & live announcements: For first-load empty tables (data.length === 0 && loading), consumers may render GhostSkeleton rows in manual compositions (per GhostSkeleton), while GhostDataTablePreset keeps <thead> mounted with aria-busy="true" on <table>. Async completion announcements remain a consumer-owned polite live region (role="status"), never aria-live on <table> or <tbody>.

Keyboard, focus parity, RTL, touch, and motion ​

  • Exact keyboard parity with headless @ghostvue/vue: Native <table> semantics only (no role="grid" or arrow-key cell roving). Tab / Shift+Tab traverses in DOM order: #toolbarStart → #search (independent Tab stop) → #toolbarEnd → #bulkActions (when selectedCount > 0) → named horizontal scroll container (only when containHorizontal is true) → header select-all GhostCheckbox → sortable header <button>s → body row checkboxes, expand <button>s, cell controls, and expanded #detail controls → #footer (GhostPagination). Space toggles checkboxes (Enter does not); Enter and Space activate sort and expand buttons.
  • Focus restoration invariants (both required in browser tests):
    1. Detail row collapse: When an expanded row collapses while document.activeElement is inside its #detail row, focus moves to that row's expand <button> (useDataTableDetailRowFocus).
    2. Bulk-actions dismissal: When [data-part="bulk-actions"] unmounts because selectedCount transitions from > 0 to 0 (for example, the user activates a "Clear selection" button wired to clearSelection()) while document.activeElement is inside [data-part="bulk-actions"], GhostDataTablePreset moves focus on nextTick to the table's header select-all checkbox input (when mounted and not disabled) so focus is never stranded on document.body.
  • RTL, touch targets, and reduced motion:
    • ghost-data-table.css uses CSS logical properties (inline-size, block-size, padding-inline, padding-block, border-block-end, border-inline-start, inset-block-start, text-align: start) so dir="rtl" mirrors layout, sort-button alignment, and selection indicators with zero physical left / right overrides.
    • Sort buttons, expand buttons, checkboxes, and default preset inputs respect --ghost-control-touch-min (2.75rem on coarse pointers via semantic control tokens).
    • Transitions use --ghost-action-duration / --ghost-motion-fade-duration and 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:

  1. Headless GhostDataTablePreset unit & type tests (@ghostvue/vue):
    • Enable each layout slot being exercised through layoutSlots. #toolbarStart and #toolbarEnd render 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 any role="toolbar".
    • #bulkActions stays unmounted when selectedCount === 0 or enableRowSelection === false, mounts when selectedCount > 0, receives { selectedRowIds, selectedCount, clearSelection } (including cross-page ids when manualPagination: true), clearSelection() clears selection (and is a no-op when disabled: true), and activating clearSelection() while focused inside [data-part="bulk-actions"] moves focus to the header select-all checkbox.
    • #footer receives { pagination, pageCount, rowCount, setPageIndex } and setPageIndex commits through the root (v-model:pagination + single stateChange when manualPagination: true).
    • In both presets, parameterize compatibility cases over toolbarStart, toolbarEnd, bulkActions, footer, emptyDescription, and emptyActions. With the prop omitted, a slot matching a column id receives only its original typed cell context. Verify a legacy numeric #footer="{ value }" can call value.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 bulkActions enabled, keep the colliding footer cell slot while showing and dismissing the selection bar. With footer explicitly enabled, check its typed pagination props and one footer invocation per render. A column named footer uses its cell hook or value fallback. Use positive and negative vue-tsc fixtures for the two slot signatures.
  2. Themed wrapper unit, SSR, export, and generic type tests (@ghostvue/themes):
    • GhostDataTable renders .ghost-data-table.ghost-themed-scope[data-part="root"][data-themed]; defaults (size="md", variant="plain", stickyHeader=false, disabled=false) omit data-size, data-variant, data-sticky-header, and data-state; non-defaults set data-size="sm", data-variant="card", data-sticky-header="", and data-state="disabled".
    • ariaLabel and ariaLabelledby render on the native <table> only (never on .ghost-data-table).
    • Consumer class and style merge cleanly on GhostDataTable, GhostDataTableTable, and GhostDataTablePreset; all six v-models, stateChange, and all 16 GhostDataTableExposed<TData> methods plus element work through a template ref.
    • @ghostvue/themes re-exports GhostDataTable, GhostDataTableTable, GhostDataTablePreset, defineDataTableColumns, useGhostDataTable, useGhostDataTableServerRequest, the five getDataTable*Props helpers, and public types (pnpm published-exports and pnpm exports:check green).
    • Generic vue-tsc type tests for @ghostvue/themes verify defineDataTableColumns<Invoice>() column cell slot typing (value.toFixed(2) valid, @vue-expect-error on value.toUpperCase()), typed #detail="{ row }", #bulkActions, and #footer.
    • expectSsrHydration passes with zero warnings on themed GhostDataTable + GhostDataTablePreset with sort, selection, expansion, #toolbarStart, #toolbarEnd, #bulkActions, and #footer.
    • Headless isolation check: mounting @ghostvue/vue GhostDataTable on a page where @ghostvue/themes CSS 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.
  3. Browser (Playwright), accessibility (@axe-core/playwright), and forced-colors tests:
    • Keyboard and real focus (toBeFocused()): full Tab traversal across #toolbarStart, #search, #toolbarEnd, #bulkActions, select-all checkbox, sort buttons, row checkboxes, expand buttons, and #footerGhostPagination; Enter and Space cycle single-sort (none → asc → desc → none) while focus stays on the sort <button> and aria-sort / data-sort update on <th>; Space toggles row selection (data-selected="true"); collapsing an open #detail row from inside restores focus (toBeFocused()) to the row expand button; activating clearSelection inside #bulkActions restores focus (toBeFocused()) to the header select-all checkbox.
    • [aria-busy="true"] loading parity: toggling :loading="true" sets aria-busy="true" on <table>, keeps rows and headers mounted without dropping toBeFocused() 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 computed backgroundColor and color to SelectedItem and SelectedItemText (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/playwright violations across plain and card variants, sm and md sizes, 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.
  4. Manifests, registries, docs, and release metadata (#333):
    • Update docs/components/data-table-spec.md frontmatter (packages adds '@ghostvue/themes', manifests adds packages/themes/manifests/ghost-data-table*.manifest.json, and approval.evidence records Zac's #316 approval).
    • Run pnpm manifests:write and pnpm registries:write; add themed examples in examples/data-table/ and packages/vue/registry/data-table.registry.json; document themed usage and preset slots in docs/components/data-table.md; update only the DataTable row in docs/roadmap.md; include minor Changesets for @ghostvue/vue and @ghostvue/themes.

Decisions recorded (Zac, PR #265 review) ​

TopicDecision
ArchitectureOption A: composable + native GhostTable
getRowIdRequired in every build
Filter debouncingConsumer-owned
Themed GhostDataTableNot in phase one; headless examples first
Benchmark thresholdsInformational until repeated CI runs show variance
Server stateChangeOne emit per user action with full query
Local select-allgetPrePaginationRowModel() (all filtered rows, not current page only)
Server selectionNo prune on page change; select-all = getRowModel() visible subset
Filtering defaultsCase-insensitive OR global / AND column; clear ''/null/undefined; skip null/undefined cell values in text match
Filter pagination resetpage → 1 only when manualFiltering: true; page-local filter keeps page
Selection pruningAuto-prune only when both manualPagination and manualFiltering are false (source data change)
Full-local filter clampKeep pageIndex, then clamp to last valid page when filtered count shrinks (Zac, post-rebase)
pageIndex clampingAfter pageCount changes, clamp when pageIndex > pageCount; rowCount === 0 → page 1
Local data refreshClamp pageIndex on data reference change; do not reset to page 1 unconditionally
Server RetryExpose retry() — one stateChange with same query, new internal requestId
Server clamp fetchWhen server pageCount forces pageIndex down, one stateChange with clamped pagination
Preset LOCGhostDataTablePreset keeps invoice-parity apps ≤ 95 non-blank consumer lines with typed columns
Reference axeZero 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.

TopicDecision
Preset toolbar slotsKept. #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-basedKept. 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.

DimensionFinding
Consumer LOCManual 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
TypingGhost exceeds Prime: defineDataTableColumns catches amount.toFixed / rejects toUpperCase; Prime field strings do not catch renamed keys at compile time
BehaviorGhost exceeds Prime: coalesced stateChange, page-local page 4, local getPrePaginationRowModel() select-all — intentional, not Prime defaults (page-scoped select-all, paginator reset on filter).
a11yKeyboard 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 issueScopeComplexity
Done: GhostVue vs PrimeVue prototype (PR #269)Evidence folded into spec; prototype PR closed unmerged—
DataTable core types and local processing pipelineuseGhostDataTable, manual matrix, row modelsHigh
defineDataTableColumns + column type testsTyped value / getValue, CI type testsMedium
GhostDataTableTable default rendererBasic example (a), #columnId slotsMedium
GhostDataTablePreset (invoice parity, ≤95 LOC)Example (a′), wired a11y + interaction helpersMedium
GhostDataTable headless root and GhostTable compositionSlot bindings, example (b), SSRMedium
Interaction prop helpersSort / select / expand bindings + focus-on-collapseMedium
Server router example + Back/Retry testsserver-invoices-router.vue, race testsHigh
Column sorting UI and header a11ySingle-column sort, aria-sortMedium
Filtering model and toolbar composition docsConditional page reset vs manualFilteringLow
Pagination integrationrowCount, empty → page 1, GhostPaginationLow
Row selection (local + server)Select-all rules, no server prune, cross-page testsHigh
Row expansion rowsDetail <tr>, server no-pruneMedium
Server mode and async guardCoalesced stateChange, full query, stale guard testsMedium
Performance benchmark harnessVitest bench, sort/page regression countersLow
Deferred: PrimeVue 10k browser comparisondocs/contributing/data-table-benchmark-comparison.mdMedium
Headless docs and executable examplesdata-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 & CSSHigh
Approved: Multi-column sort spec (#317, GHO-250)Approved 0.3.0 addendum specifies opt-in multi-column sorting via enableMultiSortMedium
Approved: Header filter-control amendmentOpt-in headerControls and #headerControl on both renderersMedium
Deferred: Virtualization specScroll + a11yHigh
Approved: Query-wide server selection amendmentOpt-in selection v-model: filter query plus excluded ids, no id downloadHigh
Approved: Flat grid keyboard spec (GHO-252)Data grid spec (approved); treegrid deferredHigh

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> + Tab order 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, and clearSorting).
  • Breaking changes to DataTableColumnSort or DataTableQueryState.

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 / PropTypeDefaultContract
enableMultiSortbooleanfalseOpts the table into multi-column sorting. When false, behavior is identical to phase one (sorting capped to 1 entry; no priority badges or descriptions).
maxMultiSortColCountnumber | undefinedundefinedOptional 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.shiftKeyPredicate evaluated when a header sort control activates with an event. Ignored when enableMultiSort is false.
  • Invalid maxMultiSortColCount: Values < 1 or non-finite values normalize to 1 (minimum meaningful bound; values with fractional parts use Math.floor). When maxMultiSortColCount === 1 and enableMultiSort: 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):

ts
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
}
PropTypeDefault
sortDescriptionLabel(ctx: DataTableSortDescriptionContext) => string({ direction, priority, total }) => \Sorted ${direction === 'asc' ? 'ascending' : 'descending'}, priority ${priority} of ${total}``
sortAnnouncementLabel(entries: readonly DataTableSortAnnouncementEntry[]) => stringEmpty: '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>:

SymbolSurfaceSignature / TypeContract
getSortIndex(columnId)Composable, slot props(columnId: string) => numberReturns 0-based priority index in sorting (0 = primary, 1 = secondary), or -1 when unsorted.
getSortDirection(columnId)Composable (existing)(columnId: string) => DataTableSortDirectionExtended from sorting[0] only to search all entries in sorting ('asc' | 'desc' | false).
toggleSorting(columnId, multi?)Composable, exposed(columnId: string, multi?: boolean) => voidExisting 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() => voidSets sorting to [] (no-op if already empty). Emits one stateChange when manualSorting is true.
header.sortIndexDataTableHeader<TData>number0-based index in sorting, or -1 when unsorted.
header.sortPriorityDataTableHeader<TData>number | undefined1-based rank (sortIndex + 1) when sorted; undefined when unsorted.
header.toggleSort(event?)DataTableHeader<TData>(event?: MouseEvent | KeyboardEvent) => voidBackwards-compatible with @click="header.toggleSort" (Vue forwards $event) and 0-arg header.toggleSort(). Calls isMultiSortEvent(event) when enableMultiSort is true.
getHeaderCellProps(columnId)Slot props, getDataTableHeaderCellPropsDataTableHeaderCellPropsSee 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).
sortAnnouncementSlot propsstringReactive 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 ​

  1. Order = priority: sorting[0] is primary (priority 1), sorting[1] is secondary (priority 2), and so on.
  2. Deduplication: At most one DataTableColumnSort per column.id. setSorting(next) deduplicates by id keeping the first (highest priority) occurrence.
  3. Capacity:
    • When enableMultiSort is false: setSorting(next) slices to next.slice(0, 1) (phase-one contract unchanged).
    • When enableMultiSort is true and maxMultiSortColCount is set: setSorting(next) slices to next.slice(0, max).
  4. Inert when disabled or non-sortable: toggleSorting(columnId, multi) is a no-op when disabled.value is true or !canSort(columnId) (same as phase one).

Multi-sort transition rules ​

Let C be a sortable column (canSort(C) === true) and enableMultiSort === true:

ActionCurrent state of C in sortingNext 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 indexReplace entry at index in place with { id: C, desc: true } (priority rank unchanged).
Multi (multi === true)Sorted desc at indexRemove 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:

  • sortRows accepts sorting: readonly DataTableColumnSort[] and columnsById: 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, never O(n log n * k)).
  • Comparator chain: Compare column 0, then 1, ..., then k - 1 until 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 with desc, matching phase-one sortRows).
    • Per-column sortFn or compareValues runs next, multiplied by entry.desc ? -1 : 1.
    • If all active columns compare equal (0), ES2019+ stable Array.prototype.sort preserves coreRows input order.
  • Immutability & memoization: Consumer row objects and data remain untouched; filtering, pagination, selection, and expansion still never re-run sortRows.

Server mode, stateChange, and URL serialization ​

  • Zero payload breaking changes: DataTableQueryState.sorting is already DataTableColumnSort[]. With manualSorting: true, any toggleSorting, setSorting, or clearSorting change emits one stateChange with trigger: 'sorting' and the full ordered query.sorting array.
  • Pagination reset rule: Unchanged from phase one — sorting never resets pagination.pageIndex (the pageCount clamp still applies if pageCount shrinks).
  • Recommended URL format (additive to server-invoices-router.vue): Encode comma-separated id:dir pairs in priority order, e.g. ?sort=customer:asc,amount:desc, which remains backwards-compatible with single-column ?sort=amount:desc. Hydrating sorting on mount or Browser Back remains silent (no stateChange echo 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.

InputContextBehavior (enableMultiSort: false)Behavior (enableMultiSort: true)
Click (no modifier)Sort buttonPhase-one single-column cycleSingle-column cycle / collapse to single sort on this column
Enter / Space (no mod)Sort buttonPhase-one single-column cycleSingle-column cycle / collapse to single sort on this column
Shift+ClickSort buttonPhase-one single-column cycleMulti-sort add / cycle in place / remove (or custom via isMultiSortEvent)
Shift+EnterSort buttonPhase-one single-column cycleMulti-sort add / cycle in place / remove
Shift+SpaceSort buttonPhase-one single-column cycleMulti-sort add / cycle in place / remove (see Shift+Space keyup guard below)
Tab / Shift+TabTable headerNative focus orderNative focus order (no roving grid tabindex)
EscapeSort buttonNo-opNo-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+Space keyup vs keydown hazard: Native <button> elements fire click on Enter keydown, but fire click on Space keyup. If a keyboard user presses Shift+Space and releases Shift a few milliseconds before releasing Space, the browser's synthesized click event carries shiftKey === false.
    • Requirement for GhostDataTableTable and GhostDataTablePreset: Track whether Shift (or isMultiSortEvent) was active on Space keydown on that sort button and combine it with the resulting click event before calling header.toggleSort, resetting the pending flag on blur or click.
    • Preventing page scroll on Shift+Space: Native <button> suppresses Space scrolling, and Space with Shift on a focused <button> must likewise never scroll the viewport.
  • Screen-reader & touch parity without Shift: Screen readers in browse / virtual-cursor mode (NVDA, JAWS, VoiceOver VO+Space) and touch screen readers often synthesize a bare click without Shift, and mobile touch has no Shift key. Consumers requiring multi-sort without modifier keys should either:
    1. Set :is-multi-sort-event="() => true" (additive click mode paired with a consumer "Clear sorting" button calling clearSorting()), or
    2. Compose a sort menu / priority controls using toggleSorting(columnId, true) and setSorting(...).

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:

  1. aria-sort accepts 'ascending' | 'descending' | 'other' | 'none'.
  2. aria-sort is designed for one sorted column at a time; it has no syntax to express secondary rank (priority 2 of 3), and applying aria-sort to multiple <th> elements causes assistive technologies to announce multiple columns as equally sorted without hierarchy (or ignore secondary headers).
  3. 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:

  1. Primary sorted column (sorting[0], sortPriority === 1):
    • <th> (getHeaderCellProps): scope="col", aria-sort="ascending" | "descending", data-sort="asc" | "desc", data-sort-priority="1".
  2. Secondary+ sorted columns (sorting[1..k-1], sortPriority >= 2):
    • <th> (getHeaderCellProps): scope="col", aria-sort omitted, data-sort="asc" | "desc", data-sort-priority="2" | "3" | ....
  3. Unsorted columns:
    • <th> (getHeaderCellProps): scope="col", aria-sort omitted, data-sort omitted, data-sort-priority omitted.
  4. Sort <button> (getSortButtonProps) — accessible name vs description:
    • Never put raw rank digits into the button's accessible name (do not let a visual 2 badge concatenate as "Amount 2"). Keep the visual badge aria-hidden="true".
    • Never place a GhostVisuallyHidden status span directly inside <th> as text content: doing so alters the <th> accessible name, breaks getByRole('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 custom options.label) and attach aria-describedby pointing to a visually hidden description node rendered outside <table> (for example, an indexed GhostVisuallyHidden container rendered by GhostDataTableTable / GhostDataTablePreset, or consumer-wired via describedById in 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-sort on <th> already conveys direction; description is optional (or omitted so single-sort matches phase one cleanly).
    • If the consumer already passed aria-describedby, merge ids space-separated rather than overwriting.
  5. Polite live-region announcement (aria-live="polite"):
    • Because secondary columns omit aria-sort, activating Shift+Enter on a secondary column would otherwise produce no aria-sort mutation announcement.
    • GhostDataTableTable and GhostDataTablePreset render a GhostVisuallyHidden node with aria-live="polite" and aria-atomic="true" bound to sortAnnouncement (outside <table>), announcing user-driven changes when enableMultiSort is true — e.g. "Sorted by Customer ascending (1), then Amount descending (2)." or "Sorting cleared.".
    • No mount/hydration spam: Initial defaultSorting and silent URL hydration (sorting prop sync) must not populate the live region. Only user-initiated transitions (toggleSorting, clearSorting, or setSorting triggered by user actions) update sortAnnouncement.
    • Renderless root invariant: GhostDataTable itself remains renderless (emits zero DOM elements per ADR 0014) and exposes sortAnnouncement in GhostDataTableSlotProps for manual #default compositions.

Rendering, theming, and CSS hooks ​

  • Headless DOM invariants: GhostTable* data-part attributes are unchanged. Every sorted <th> receives data-sort="asc" | "desc" and (when enableMultiSort is true) data-sort-priority="<1-based-rank>".
  • Additive layering with @ghostvue/themes (#316): The 0.1.0 themed GhostDataTable wrapper ships on the single-sort data-sort contract. In 0.3.0, themed styles can target th[data-sort-priority]::after or the priority badge slot using content: attr(data-sort-priority) / CSS tokens without breaking any 0.1.0 single-sort selectors.
  • Decorative indicators: Any arrow glyph or priority pill rendered inside GhostDataTableTable / GhostDataTablePreset carries aria-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: sorting state, aria-sort on sorting[0], data-sort, data-sort-priority, and deterministic useGhostId-based aria-describedby ids match identically between SSR and client hydration. sortAnnouncement starts 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.containHorizontal behavior is unchanged.
  • Performance (10k rows):
    • When sorting.length === 1, phase-one sortRows fast path keeps zero overhead vs 0.1.0.
    • When sorting.length > 1, decorate-once evaluates accessors O(n * k) times total across k sorted 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 (<= n calls per sorted column), and paging or toggling row selection triggers zero comparator/accessor re-evaluations.

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-column sortUndefined 'first' | 'last' | false, custom sortFn).
    • enableMultiSort: false regression: setSorting still truncates to 1, toggleSorting(id, true) stays single-sort, data-sort-priority omitted.
    • Transition matrix: append, in-place asc -> desc -> remove, priority promotion when priority 1 is removed, unmodified click collapsing >1 sorts, maxMultiSortColCount enforcement, clearSorting(), deduplication in setSorting.
    • Server mode: single stateChange per multi-sort toggle with ordered query.sorting, no page reset, URL hydration silent (no stateChange and no sortAnnouncement).
    • Counter test (use-ghost-data-table.counters.test.ts): multi-column decorate-once accessor count and zero re-sort on page/selection change.
  • Interaction helpers & Vue (data-table-interaction.test.ts, GhostDataTableTable.test.ts, GhostDataTablePreset.test.ts, SSR):
    • Primary <th> carries aria-sort and data-sort-priority="1"; secondary <th> omits aria-sort and carries data-sort + data-sort-priority="2".
    • Sort button keeps clean accessible name (excludes decorative badge), exposes merged aria-describedby pointing outside <table>, and <th> accessible name stays clean (Amount, not "Amount Sorted descending...").
    • sortAnnouncement live region stays empty on SSR/mount and updates on user sort changes.
    • SSR hydration test with defaultSorting of length 2 produces zero hydration mismatches.
  • Playwright keyboard, focus & axe (tests/e2e/ghost-data-table.spec.ts):
    • Shift+Click, Shift+Enter, and Shift+Space (including releasing Shift before Space keyup) add secondary sort, cycle secondary asc -> desc -> remove, and preserve toBeFocused() on the activated sort button.
    • With the default predicate, plain Enter / Space on 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. Escape keeps the current sorts.
    • :is-multi-sort-event="() => true" + clearSorting() flow works without modifier keys.
    • Zero @axe-core/playwright violations across thead, 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, secondary aria-describedby priority/direction readout, clean <td> column-header announcements, and polite live-region announcements.
  • Bench (tests/bench/data-table-processing.bench.ts):
    • Add 2-column and 3-column 10k-row sortRows cases to verify single-column fast path has zero regression and multi-column sort stays well within budget.

Approved multi-sort decisions (0.3.0) ​

  1. Q1 — Accessible sort priority. Only the primary header carries aria-sort. In a multi-column sort, describe each active button's direction and rank using aria-describedby, and announce user-driven changes through the polite live region.
  2. 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.
  3. 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.
  4. Q4 — Modifier-free operation. Document a working example with :is-multi-sort-event="() => true" and a visible app-provided Clear sorting button calling clearSorting(). This supports ordinary touch and assistive-technology activation. The preset needs no dedicated mode prop or built-in reset control.
  5. Q5 — Table-level opt-in. With enableMultiSort enabled on the table, every sortable column can participate. Defer the per-column DataTableColumnDef.enableMultiSort override 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:

  1. 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.
  2. The heading then shows that Issued is filtered, so a user reading the headers can tell which columns constrain the rows.
  3. 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-filters and the root's setColumnFilter action.
  • 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.

PropTypeDefaultContract
headerControlsreadonly TColumns[number]['id'][] (any string without a typed columns array)undefinedColumn ids whose header renders #headerControl. Omitted or [] keeps today's behavior, including #headerControl as a cell slot.
ts
/** 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 headerControls omitted or [], the renderer is unchanged. A column whose id is headerControl keeps calling #headerControl once per row with its cell props.
  • Reservation. A non-empty headerControls reserves the name headerControl for headers on that instance, even when none of its listed columns currently render or the slot is absent. A column with the id headerControl then renders through its cell hook or value fallback. A slot function is invoked in exactly one role.
  • Resolution order. Resolve ownership from headerControls before 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 columns prop 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, layoutSlots and headerControls are separate lists. Neither affects the other's names.

Header DOM and accessibility contract ​

For a listed column, the renderer emits:

html
<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-sort stays on the <th>. scope, aria-sort, data-sort, and data-sort-priority remain 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 themed th > button sort-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". With aria-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 sets aria-label to 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's label so localized headers stay in sync. When a filter is active, the control says so through its name or aria-describedby, for example "Filter Issued, Nov 14 to Nov 24, 2026". A popover trigger keeps the GhostPopoverTrigger semantics (aria-haspopup="dialog", aria-expanded).
  • Overlays leave the cell. Popover or dialog content that the control opens renders through portal (GhostPopoverContent :portal="true"), so containHorizontal overflow and a sticky header cannot clip it and its content never sits inside the <th>.

Keyboard

InputContextBehavior
Tab / Shift+TabHeader rowNative order: sort button, then the control's focusable elements, then the next column. No roving tabindex.
Enter / SpaceHeader controlThe control's own action (for example, opening its popover). Never reaches sort activation.
Shift+Enter / Shift+SpaceHeader controlSame as without Shift. Never adds a sort, with or without enableMultiSort.
EscapeOpen control popupCloses 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 Tab stops per listed column. Inline fields in a <th> are allowed but lengthen the header's Tab sequence.
  • Focus survives filtering. The header row stays mounted when a filter leaves zero rows and while loading sets aria-busy, so focus returns to the trigger after the popup closes.
  • Disabled tables. While the parent is disabled, the slot receives disabled: true and the control disables or marks itself aria-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 no toggleSort, emits no update:sorting, and leaves multi-sort priorities and the sortAnnouncement live region untouched. With manualFiltering, applying a filter emits one stateChange with trigger: 'columnFilters' whose query.sorting equals 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 same control.size.* touch target as other controls. Logical properties mirror the layout in RTL.
  • Themed wrappers: the @ghostvue/themes GhostDataTableTable and GhostDataTablePreset declare and forward headerControls like layoutSlots, and keep the headless slot types. Slot invocation stays in the headless renderers.
  • Manual #default composition already owns each <th>. It follows the same rules: keep aria-sort on the <th>, put the control beside (not inside) the sort button, and set the <th> aria-label to the column label. No new helper is added.

Environment and performance ​

  • SSR and hydration: ownership comes from the headerControls prop, the aria-label comes 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. containHorizontal behavior 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.

  1. Legacy cell slot keeps its value. A column with id headerControl and a #headerControl template, without headerControls, receives each row's cell value (10, 20) through asynchronous column insertion, reorder, and removal. No [data-part="header-control"] or th[data-header-control] renders. The same case passes with a column named columnHeaderEnd.
  2. Opt-in reserves the name. With :header-controls="['total']" and a column whose id is headerControl, the slot is called once with { columnId: 'total', label: 'Total', disabled: false } and never with cell props. The headerControl column renders its cell hook output or its value.
  3. 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.
  4. Filter activation leaves single sort alone. With Amount sorted ascending, open the Issued control with a click, Enter, and Space, apply a range, and close it. sorting is unchanged, update:sorting is not emitted, aria-sort="ascending" stays on the Amount <th>, and focus returns to the trigger.
  5. Filter activation leaves multi-sort priority alone. With enableMultiSort and [customer asc, amount desc], activate the controls on Issued (unsorted) and Amount (priority 2), including with Shift+Enter and Shift+Space. The sort array, data-sort-priority values, aria-describedby rank text, and the sortAnnouncement live region are unchanged.
  6. Server mode. With manualFiltering, applying the range emits one stateChange with trigger: 'columnFilters', pageIndex: 1, and the prior query.sorting. No sorting stateChange follows.
  7. aria-sort stays on the header. On a listed, sorted column, aria-sort is on the element with role columnheader, not on the wrapper, the sort button, or the control. getByRole('columnheader', { name: 'Issued', exact: true }) and getByRole('button', { name: 'Issued', exact: true }) both resolve.
  8. Keyboard reachability (Playwright). Tab moves from the Issued sort button to its trigger and on to the next column's sort button; Shift+Tab reverses. Escape in the open popover closes it and toBeFocused() holds on the trigger. Applying a range that matches no rows keeps the header mounted and focus on the trigger.
  9. Disabled table. The slot receives disabled: true, and the reference control cannot open.
  10. Axe and SSR. Zero @axe-core/playwright violations on the table scope with the popover open and closed. SSR hydration with headerControls and an active sort produces zero mismatches.
  11. Types. headerControls accepts only ids from a typed columns array. #headerControl has the header signature only when ids are listed, and the legacy cell signature otherwise.
  12. 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 as toolbar-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.md covering headerControls, the collision rule, naming the trigger, and the manual-composition rules above.

Compatibility ​

  • Additive. With headerControls omitted or [], markup, slot routing, and types are unchanged, including tables with a column named headerControl.
  • A Changeset for @ghostvue/vue and @ghostvue/themes ships with the implementation. The spec revisions are docs-only.

Approved header filter-control decisions ​

zprue743 approved these on 2026-12-01.

  1. Q1 — API shape. Use a headerControls id list plus one #headerControl slot, opted in per instance with the same reservation rule as layoutSlots. 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.
  2. Q2 — Header cell name. The renderer sets aria-label on 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.
  3. Q3 — Slot props. The slot receives { columnId, label, disabled } only. Filter state stays with the consumer's v-model:column-filters and template-ref actions, and no table context becomes public. Not chosen: passing the column's filter value and a bound setter.
  4. 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 in ghost-data-table.css already uses. That covers the themed GhostDataTablePreset and manual compositions under themed GhostDataTable that put data-part="expand-button" on their own button. The rule uses child combinators, so a nested table in a #detail row is not matched. Bare headless renderers are unchanged.
  • Headless glyph. Headless GhostDataTablePreset keeps rendering the aria-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 and aria-hidden do not change. The themed rule hides > [data-part='expand-glyph'] with display: none and paints the mark. The hook is needed because the themed preset passes slots through and cannot change the inner button content, and selecting a bare span would make internal DOM structure the styling contract.
  • How it is painted. The button's ::after with content: '', an --ghost-action-icon-size square (1.1em), background: currentColor, and the same clip-path chevron as the descending sort mark. It uses no SVG, no new token, and no per-component color. The button's existing display: inline-grid; place-items: center centers it, and the --ghost-control-size-sm-min and --ghost-control-touch-min target sizes do not change.
  • State. The button has no data-state. The existing themed rule already reads aria-expanded, and the mark does the same, because getRowExpandButtonProps always 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-expanded on the row is not used, so manual compositions that bind only the button props still work.
  • Motion. The 90° turn transitions rotate with --ghost-motion-duration-fast and --ghost-motion-easing-standard only 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 ::after sets forced-color-adjust: none under @media (forced-colors: active) and paints in ButtonText, or GrayText when the button is :disabled. In a selected row, the cell's forced-color-adjust: auto reset already returns the button to ButtonFace, so ButtonText stays 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 like data-part="sort-indicator". The consumer marks it aria-hidden="true" (and focusable="false" on SVG). A manual composition that does not want the default mark can leave data-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-part opt-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 through layoutSlots, so a column with id expandIndicator keeps 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 the expand-glyph span. 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 is aria-hidden, so the button's accessible name still comes only from aria-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), default Show details for <rowId>), set by getRowExpandButtonProps. Today the glyph span is already aria-hidden and aria-label overrides content, so the glyph is not announced. The painted mark has no text (content: ''), so this stays true.
  • aria-expanded and aria-controls still 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-fg when disabled), so the enabled mark meets the 3:1 non-text contrast minimum in every theme and mode.

Implementation acceptance cases ​

  1. Headless hook (unit). GhostDataTablePreset renders the glyph span with data-part="expand-glyph", aria-hidden="true", and the same ▸ / ▾ text as before.
  2. Painted (browser). In the themed preset, the glyph span is not displayed. The button's ::after has computed content "", a size equal to the resolved --ghost-action-icon-size, and a background equal to the button's color. A headless preset on the same page still shows the glyph and has no painted ::after.
  3. State and RTL (browser). Enter, Space, and click flip the mark's computed rotate in step with aria-expanded. Under dir="rtl" the collapsed mark points the other way, and the expanded mark points down.
  4. Reduced motion (browser). With reducedMotion: 'reduce' emulated, the mark's transition duration is 0s.
  5. Forced colors (browser). With forcedColors: 'active' emulated, the mark is painted in ButtonText in an unselected and a selected row, and in GrayText when the table is disabled.
  6. Replacement (browser). In a manual composition, a direct child with data-part="expand-indicator" turns the default off, and a button without data-part="expand-button" gets no mark.
  7. Preset slot (unit and browser). With layoutSlots including expandIndicator and the slot supplied, the button contains one aria-hidden data-part="expand-indicator" span with the consumer content and no expand-glyph span, the slot receives expanded in step with aria-expanded, and the themed button paints no ::after mark. Without the opt-in, a column with id expandIndicator still receives its cell slot and the button output matches case 1.
  8. Slot types (vue-tsc). Positive and negative type fixtures, in the same style as the existing preset slot type tests, cover the generic GhostDataTablePresetSlots<TColumns, TLayout> contract on both the headless preset and the themed wrapper: #expandIndicator is accepted with { expanded: boolean } only when layoutSlots includes it; without the opt-in a column with id expandIndicator keeps its cell-slot signature and the layout signature is rejected; and expanded is typed boolean through the themed pass-through.
  9. Name and axe (browser). The expand button's accessible name equals rowExpansionLabel(rowId) before and after toggling. The existing keyboard and axe run in tests/e2e/ghost-data-table.spec.ts still passes.
  10. Baselines. The data table examples-visual baselines with expandable rows are updated with pnpm test:visual:docker.

Documentation plan ​

  • docs/components/data-table.md Styling hooks lists the painted expand mark, data-part="expand-glyph", and the expand-indicator opt-out, with a manual-composition example.
  • The preset layout slots section adds #expandIndicator with its { expanded } props and a short example that supplies replacement artwork.
  • The themed manifests' styling hooks list the expand-button ::after default.
  • A @ghostvue/themes Changeset for the mark and a @ghostvue/vue minor Changeset for the added attribute and the opt-in slot.

Compatibility ​

  • @ghostvue/themes changes how it renders (minor Changeset). The themed preset shows the painted chevron instead of the glyph. A manual composition that already marks its expand button data-part="expand-button" gains the mark next to its own content. It can add data-part="expand-indicator" to its artwork or drop the hook. The Changeset says this.
  • @ghostvue/vue gains one attribute on an existing aria-hidden span 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 id expandIndicator keeps 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 ​

ConcernOwner
Recording the selection (query, exclusions, counts)Table (useGhostDataTable)
Checked state, counts, and announcementsTable and default renderers
Opt-in and clear controlsConsumer markup in #bulkActions, using the slot props below
Sending the selection to the serverApplication
Resolving membership, authorizing, and running the actionServer. The table never resolves a query to ids and never authorizes or runs an action.
Showing a rejected or partial actionApplication (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 ​

ts
/**
 * 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 | DataTableQuerySelection

Applications 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:

OptionTypeDefaultContract
enableQuerySelectionbooleanfalseTurns on the selection model and selectAllMatching(). Requires enableRowSelection, manualPagination, and manualFiltering.
selectionDataTableSelection—Controlled selection (v-model:selection). Read only while enableQuerySelection is true.
defaultSelectionDataTableSelection{ mode: 'ids', ids: [] }Uncontrolled initial selection.
rowCountExactbooleantrueSet 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):

NameContract
selectionEffective DataTableSelection.
selectedCountids.length in ids mode. In query mode, max(0, rowCount − excludedIds.length) using the current rowCount; how exact it is comes from selectedCountKind.
selectedCountKindDataTableSelectionCountKind. 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.
canSelectAllMatchingtrue 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.
headerSelectionStateIn 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).
selectionAnnouncementPolite 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.

ts
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, and rowCountExact are ignored, update:selection is never emitted, and every existing selection test keeps passing unchanged.
  • With enableQuerySelection: true, selection is the source of truth and selectedRowIds becomes a read-only projection that keeps its exact meaning, explicitly selected ids:
    • ids mode: selectedRowIds equals selection.ids.
    • query mode: selectedRowIds is []. It never holds the loaded, non-excluded ids, because an app that reads selectedRowIds for 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 #bulkActions count still comes from selectedCount.
    • update:selectedRowIds is still emitted whenever the projection changes. A selectedRowIds or defaultSelectedRowIds prop is ignored, with a development warning, so the two models cannot disagree.
  • #bulkActions keeps selectedRowIds and clearSelection. With query selection enabled, selectedCount follows the definition above rather than selectedRowIds.length, and the new selection prop 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:

EventSelectionAnnouncement
Page change (setPageIndex) or pageSize changeKept, including excludedIdsNone
Sort changeKeptNone (sort has its own)
data reference change (a new page arrives)Kept. New rows render checked unless excluded.None
rowCount changes in a later responseKept. 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 stateChangeCleared 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 rowId added to / removed from excludedIdsNone: the checkbox announces
clearSelection() or resetRowSelection(){ mode: 'ids', ids: [] }cleared when user-initiated
retry()Kept (same query)None
disabled or enableRowSelection: falseKept but inert, as todayNone

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.

ts
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: expectedCount is the exact total the operator saw. The server compares it with the current total for filter and 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: expectedCount was 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 }.

StepOperator actionselection afterselectedRowIdsselectedCountSelect-all checkboxAnnouncement
1Page 1, Space on the select-all checkbox{ mode: 'ids', ids: [25 ids] }25 ids25checkedpage-selected: "25 rows selected. All 2,300 matching rows can be selected."
2Activates Select all 2,300 matching in the barquery mode, excludedIds: [][]2,300checkedall-matching: "All 2,300 matching rows selected."
3Goes to page 3Unchanged. One stateChange for the page, none for the selection.[]2,300checkedNone
4Space on INV-0061's checkboxexcludedIds: ['INV-0061'][]2,299mixedNone (the checkbox reports "not checked")
5Goes to page 40, unchecks INV-0987excludedIds: ['INV-0061', 'INV-0987'][]2,298mixedNone
6Back to page 3Unchanged[]2,298mixed; INV-0061 uncheckedNone
7App runs Mark sentUnchanged. The app sends the query, both ids, expectedCount: 2300.[]2,298mixedApp-owned result message
8Activates Clear selection{ mode: 'ids', ids: [] }[]0uncheckedcleared: "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. One stateChange fetches 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. selectedCount becomes 2,308 ("At least 2,308 selected"). matchCount stays 2,300, so the server sees the drift in expectedCount.
  • 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 announces filter-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, and selectedCount becomes 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: Enter and Space activate the buttons, and Space still toggles checkboxes.
  • Labels. Row checkbox names (rowSelectionLabel) and the select-all name (selectAllLabel) do not change. In query mode 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 selectedCount as text, worded by selectedCountKind: "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 on nextTick to 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, and canSelectAllMatching is true. 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 through clearSelection() or resetRowSelection().
  • filter-changed: a filter committed through the table cleared a query selection. 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, matching sortAnnouncement.

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 ​

  1. Opt-out parity (unit and browser). With enableQuerySelection: false, packages/vue/src/GhostDataTable.selection.test.ts and tests/e2e/ghost-data-table-selection.spec.ts pass unchanged, and update:selection is never emitted.
  2. Mode guard (unit). With manualFiltering: false or manualPagination: false, selectAllMatching() is inert, canSelectAllMatching is false, and a development warning names the missing option.
  3. 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-driven stateChange.
  4. 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), and rowCount drift (selectedCount updates, matchCount does not). After selectAllMatching(), mutating the committed Date (setTime()), range array, or reactive filter object in place leaves selection.query unchanged, and the next stateChange clears the selection before it is emitted. selection.query contains no Date instance (a Date filter is stored as its ISO string), every object and array in it is frozen, and new Date(stored).getTime() equals the original time. A function, class-instance, invalid Date, bigint, symbol, nested undefined, NaN, Infinity, or cyclic filter value, or a loaded row with a NaN or infinite id, makes canSelectAllMatchingfalse with a warning (and, when that row loads on a later page in query mode, its toggle and the select-all checkbox are disabled and inert), and every supported snapshot round-trips through JSON.stringify and JSON.parse to an equal value, including a filter holding -0 (stored as 0, and a later page or sort change with that live -0 keeps the selection); a sparse array makes canSelectAllMatching false.
  5. Select-all in query mode (unit and browser). With an empty visible row set (an empty response, the last row deleted, or SSR before data), both header flags are false and canSelectAllMatching is false, even with explicit ids still selected. Unchecking the select-all checkbox adds only visible ids to excludedIds, checking it removes them, and the mixed state follows exclusions on the page.
  6. Estimated totals and counts (unit). With rowCountExact: false, labels use the estimate wording, canSelectAllMatching is true when the estimate equals the visible row count, the documented lower bounds keep the next page reachable, a pageCount override is ignored with a warning, and excluding rowCount rows leaves the query selection in place. With an exact rowCount, selectedCountKind is 'exact' with no exclusions and 'atLeast' after one, including after a response where an excluded row has left the query. An ids selection reports 'exact' with rowCountExact: false.
  7. Compatibility (unit and vue-tsc). selectedRowIds is [] in query mode and equals ids in ids mode; a bound selectedRowIds prop is ignored with a warning; DataTableSelection narrows on mode, and reading excludedIds without narrowing is a type error.
  8. 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.
  9. Keyboard, focus, and axe (browser). On the preset: Space on the select-all checkbox, Shift+Tab to the opt-in, Enter activates 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 with Space announces page-selected exactly once, when the last unchecked visible row is checked, and not before; a unit test asserts the same for row-by-row toggleSelected calls. Repeating a transition (select the page, uncheck one row, recheck it; or clear, select one row, clear again) announces the second time too.
  10. SSR (integration). A controlled query selection renders checked rows on the server, hydrates without a mismatch, and leaves the live region empty.
  11. 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, the selection shape, a request body sketch, and the rule that the server authorizes and runs the action.
  • The preset layout slots section lists the new #bulkActions props and the single-button focus pattern.
  • Manifests describe enableQuerySelection, selection, defaultSelection, rowCountExact, update:selection, and selectionAnnouncementLabel; generated API tables are refreshed with pnpm docs:api:write.
  • A @ghostvue/vue minor Changeset, and a @ghostvue/themes Changeset 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 selectedRowIds and the #bulkActionsselectedCount mean 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.

  1. 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.
  2. QS2 — Opt-in surface. enableQuerySelection, valid only with manualPagination and manualFiltering. Not chosen: always on in server mode, which would change selectedRowIds for existing apps.
  3. QS3 — Controlled state. A new selection v-model with a discriminated union; selectedRowIds becomes a read-only projection that is [] in query mode. Not chosen: overloading selectedRowIds with a sentinel, or filling it with loaded rows, either of which lets an existing bulk action silently act on the wrong set.
  4. QS4 — Query identity and snapshot. Active columnFilters plus globalFilter, stored as a deep, frozen snapshot of JSON-safe values (each Date stored as its ISO string; other values disable the opt-in) and compared structurally, including before each stateChange; sorting and pagination excluded; an opaque queryKey stored but never compared. Not chosen: keeping references (in-place edits would change the target), keeping frozen Date objects (setTime() still works on them), handing out a defensive copy on every read (the bound selection object would still be mutable), epoch milliseconds (loses the JSON.stringify match), requiring apps to treat filters as immutable (not enforceable), or an app-supplied clone or equality callback.
  5. QS5 — Live membership. Resolved when the server runs the action, with matchCount recorded for drift checks and queryKey as opaque correlation metadata that never changes membership. Not chosen: claiming a snapshot the table cannot enforce, or letting queryKey pin the action to a snapshot while rows and counts show the live query.
  6. QS6 — Select-all checkbox in query mode. Acts on visible rows (exclusions), keeping one meaning for that control; Clear selection clears everything. Not chosen: unchecking it clears the whole query selection.
  7. QS7 — Opting in replaces explicit ids. Not chosen: keeping an includedIds list alongside the query.
  8. 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.
  9. QS9 — Estimated totals and count wording. rowCountExact: false switches counts to estimate wording and stops an estimate from refusing the opt-in; rowCount still bounds pagination, with the documented lower bounds that keep rows reachable. Counts are 'atLeast' once any row is excluded, and a query selection never clears itself at a zero count. Not chosen: a separate pagination bound or a nullable rowCount (both are pagination changes for their own amendment), or a required server-resolved count (an extra request on every exclusion).
  10. QS10 — Implementation gate. Implementation starts only after this amendment merges on master with specStatus: approved evidence 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 an implementationGates entry in .github/release-scope.json mapping the implementation issue to data-table if that issue is public. Runtime changes, examples, manifests, and Changesets belong to the implementation work, not this amendment.