GhostDataTable reference
Package: @ghostvue/themes. Status: experimental (stability policy).
Theme shell for GhostDataTable with native table semantics and the headless interaction contract.
Generated from the component manifest. Edit the manifest or Vue source, then rebuild the docs.
Props
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
size | 'sm' | 'md' | "md" | No | Cell and control density. |
variant | 'plain' | 'card' | "plain" | No | Container surface. |
stickyHeader | boolean | false | No | Pins column headings to the block start of the nearest scroll container. |
Emits
None declared.
Models
None declared.
Slots
None declared.
Exposed members
| Name | Type | Description |
|---|---|---|
element | HTMLElement | null | The themed container after mount. |
Parts and data attributes
| Attribute | Value | Description |
|---|---|---|
data-part | root | The container that scopes DataTable recipes. |
CSS variables
None declared.
Accessibility
Role: table. APG pattern: https://www.w3.org/WAI/ARIA/apg/patterns/table/.
Required ARIA attributes: none.
Keyboard
None declared.
Verification
Each category is reviewed separately. Automated keyboard and axe results do not attest manual or assistive-technology review.
| Category | Status | Evidence |
|---|---|---|
| Automated keyboard | Not reviewed | No declared key is mapped to a browser test yet. |
| Manual interaction | Not reviewed | No review recorded. |
| Assistive technology | Not reviewed | No review recorded. |
Examples
data-table/themed-invoices
A themed card preset with search, sortable columns, currency amounts, past-due invoices selected for a Mark paid action, a detail row, a Clear search recovery for no results, and a pagination footer.
| Details | ||||||
|---|---|---|---|---|---|---|
| INV-1048 | Northstar Studio | Open | $2,480.00 | |||
| INV-1047 | Fieldwork Labs | Past due | $3,725.00 | |||
INV-1047 for Fieldwork Labs is due Nov 15, 2026. Billing contact: billing@fieldwork.example. | ||||||
| INV-1046 | Canopy Digital | Paid | $1,560.00 | |||
| INV-1045 | Harbor & Co. | Past due | $980.50 | |||
<script setup lang="ts">
import { computed, nextTick, ref, shallowRef, useTemplateRef } from 'vue'
import {
GhostBadge,
GhostButton,
GhostDataTable,
GhostDataTablePreset,
GhostInput,
GhostPagination,
defineDataTableColumns,
type DataTableRowId,
type GhostInputExposed,
} from '@ghostvue/themes'
type InvoiceStatus = 'Paid' | 'Open' | 'Past due'
interface Invoice {
id: string
customer: string
email: string
/** ISO date, so the column sorts chronologically as text. */
due: string
status: InvoiceStatus
/** US dollars. Format for display; sort and filter on the number. */
amount: number
}
const helper = defineDataTableColumns<Invoice>()
const columns = [
helper.accessorKey('id', { header: 'Invoice' }),
helper.accessorKey('customer', { header: 'Customer' }),
helper.accessorKey('due', { header: 'Due' }),
helper.accessorKey('status', { header: 'Status' }),
helper.accessorKey('amount', { header: 'Amount' }),
]
// Rows are replaced, never mutated, so the table sees each update.
const invoices = shallowRef<readonly Invoice[]>([
{
id: 'INV-1048',
customer: 'Northstar Studio',
email: 'billing@northstar.example',
due: '2026-12-18',
status: 'Open',
amount: 2480,
},
{
id: 'INV-1047',
customer: 'Fieldwork Labs',
email: 'billing@fieldwork.example',
due: '2026-11-15',
status: 'Past due',
amount: 3725,
},
{
id: 'INV-1046',
customer: 'Canopy Digital',
email: 'accounts@canopy.example',
due: '2026-12-14',
status: 'Paid',
amount: 1560,
},
{
id: 'INV-1045',
customer: 'Harbor & Co.',
email: 'billing@harbor.example',
due: '2026-11-12',
status: 'Past due',
amount: 980.5,
},
{
id: 'INV-1044',
customer: 'Summit Supply',
email: 'accounts@summit.example',
due: '2026-12-10',
status: 'Paid',
amount: 2140,
},
{
id: 'INV-1043',
customer: 'Lumen Works',
email: 'accounts@lumen.example',
due: '2026-12-08',
status: 'Open',
amount: 1260,
},
{
id: 'INV-1042',
customer: 'Orbit Analytics',
email: 'finance@orbit.example',
due: '2026-12-05',
status: 'Paid',
amount: 4200,
},
{
id: 'INV-1041',
customer: 'Juniper Health',
email: 'billing@juniper.example',
due: '2026-12-02',
status: 'Open',
amount: 645.75,
},
])
const currency = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})
// The due dates are calendar days, so format them in UTC to avoid a shift.
const dueDate = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
timeZone: 'UTC',
})
const globalFilter = ref('')
// Start with the two past-due invoices on page 1 selected, ready to collect.
const selectedRowIds = ref<DataTableRowId[]>(['INV-1047', 'INV-1045'])
const expandedRowIds = ref<DataTableRowId[]>(['INV-1047'])
const pagination = ref({ pageIndex: 1, pageSize: 4 })
const saving = ref(false)
const notice = ref('')
const searchField = useTemplateRef<GhostInputExposed>('searchField')
const payableIds = computed(() => {
const selected = new Set(selectedRowIds.value)
return invoices.value
.filter((invoice) => selected.has(invoice.id) && invoice.status !== 'Paid')
.map((invoice) => invoice.id)
})
function tone(status: InvoiceStatus) {
if (status === 'Paid') return 'success'
return status === 'Past due' ? 'danger' : 'neutral'
}
async function markPaid(): Promise<void> {
const ids = new Set<DataTableRowId>(payableIds.value)
if (!ids.size || saving.value) return
saving.value = true
// Stands in for a request to your billing API; `loading` marks the table busy.
await new Promise((resolve) => setTimeout(resolve, 600))
invoices.value = invoices.value.map((invoice) =>
ids.has(invoice.id) ? { ...invoice, status: 'Paid' } : invoice,
)
// Rows stay selectable while the save runs, so drop only the ids this save
// captured and keep anything picked meanwhile. When nothing remains, the
// preset returns focus to "Select all rows" as the bar closes.
selectedRowIds.value = selectedRowIds.value.filter((id) => !ids.has(id))
saving.value = false
notice.value =
ids.size === 1
? '1 invoice marked paid'
: `${String(ids.size)} invoices marked paid`
}
async function clearSearch(): Promise<void> {
globalFilter.value = ''
// The button that ran this unmounts with the empty result; keep focus.
await nextTick()
searchField.value?.focus()
}
</script>
<template>
<GhostDataTable
v-model:global-filter="globalFilter"
v-model:selected-row-ids="selectedRowIds"
v-model:expanded-row-ids="expandedRowIds"
v-model:pagination="pagination"
:data="invoices"
:columns="columns"
:get-row-id="(row) => row.id"
:loading="saving"
enable-row-selection
enable-row-expansion
sticky-header
size="sm"
variant="card"
aria-label="Invoices"
>
<GhostDataTablePreset
:columns="columns"
:layout-slots="['bulkActions', 'footer']"
contain-horizontal
scroll-label="Invoice table"
empty-title="No matching invoices"
:empty-heading-level="2"
search-label="Search invoices"
>
<template #search="{ value, setValue, label, disabled }">
<label>
<span>{{ label }}</span>
<GhostInput
ref="searchField"
type="search"
size="sm"
placeholder="Customer or invoice"
:model-value="value"
:disabled="disabled"
@update:model-value="setValue"
/>
</label>
</template>
<template #bulkActions="{ selectedCount, clearSelection }">
<span>{{ selectedCount }} selected</span>
<GhostButton
size="sm"
:loading="saving"
:disabled="!payableIds.length"
@click="markPaid"
>
Mark paid
</GhostButton>
<GhostButton
size="sm"
tone="neutral"
variant="ghost"
@click="clearSelection"
>
Clear selection
</GhostButton>
</template>
<template #due="{ value }">
<time :datetime="value">{{ dueDate.format(new Date(value)) }}</time>
</template>
<template #status="{ value }">
<GhostBadge :tone="tone(value)" variant="soft" size="sm">
{{ value }}
</GhostBadge>
</template>
<template #amount="{ value }">
<span class="invoice-amount">{{ currency.format(value) }}</span>
</template>
<template #detail="{ row, rowId }">
<div class="invoice-detail">
<span>
{{ row.id }} for {{ row.customer }} is due
{{ dueDate.format(new Date(row.due)) }}. Billing contact:
{{ row.email }}.
</span>
<GhostButton
size="sm"
variant="outline"
tone="neutral"
@click="
expandedRowIds = expandedRowIds.filter((id) => id !== rowId)
"
>
Hide details
</GhostButton>
</div>
</template>
<template
#footer="{ pagination: page, pageCount, rowCount, setPageIndex }"
>
<!-- One polite region reports search results and saved actions. -->
<span role="status">
{{ rowCount }} {{ rowCount === 1 ? 'invoice' : 'invoices' }}
<template v-if="notice">· {{ notice }}</template>
</span>
<GhostButton
v-if="rowCount === 0"
size="sm"
tone="neutral"
variant="outline"
@click="clearSearch"
>
Clear search
</GhostButton>
<GhostPagination
v-else
size="sm"
:model-value="page.pageIndex"
:page-count="pageCount"
aria-label="Invoice pages"
@update:model-value="setPageIndex"
/>
</template>
</GhostDataTablePreset>
</GhostDataTable>
</template>
<style scoped>
/* Tabular figures keep the decimal places aligned down the column. */
.invoice-amount {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.invoice-detail {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--ghost-space-gap-sm);
}
</style>
data-table/toolbar-date-range
A themed preset with start and end date pickers in the toolbarEnd slot: the issue-date column's filterFn matches inclusive, optionally open-ended bounds, Apply commits the draft through setColumnFilter, and clearing both dates commits undefined to restore every row.
| INV-2058 | Juniper Health | $645.75 | |
| INV-2057 | Orbit Analytics | $4,200.00 | |
| INV-2056 | Lumen Works | $1,260.00 | |
| INV-2055 | Summit Supply | $2,140.00 | |
| INV-2054 | Harbor & Co. | $980.50 | |
| INV-2053 | Canopy Digital | $1,560.00 | |
| INV-2052 | Fieldwork Labs | $3,725.00 | |
| INV-2051 | Northstar Studio | $2,480.00 |
<script setup lang="ts">
import { computed, ref, shallowRef, useTemplateRef } from 'vue'
import {
CalendarDate,
GhostButton,
GhostDataTable,
GhostDataTablePreset,
GhostDatePicker,
GhostDatePickerContent,
GhostDatePickerInput,
GhostDatePickerTrigger,
GhostField,
GhostFieldControl,
GhostFieldLabel,
defineDataTableColumns,
type DataTableColumnFilter,
type GhostDataTableThemedExposed,
type GhostDatePickerError,
type GhostDatePickerValue,
} from '@ghostvue/themes'
interface Invoice {
id: string
customer: string
/** ISO date, so plain string comparison is chronological. */
issued: string
/** US dollars. */
amount: number
}
/**
* The committed column-filter value. Either bound may be open (`null`), and
* both are inclusive ISO dates. Clearing both commits `undefined` instead.
*/
interface IssuedRange {
from: string | null
to: string | null
}
// Filter values are `unknown` to the table, so the predicate checks the shape
// it was given instead of asserting it.
function isIssuedRange(value: unknown): value is IssuedRange {
if (typeof value !== 'object' || value === null) return false
if (!('from' in value) || !('to' in value)) return false
const bound = (part: unknown) => part === null || typeof part === 'string'
return bound(value.from) && bound(value.to)
}
const helper = defineDataTableColumns<Invoice>()
const columns = [
helper.accessorKey('id', { header: 'Invoice' }),
helper.accessorKey('customer', { header: 'Customer' }),
helper.accessorKey('issued', {
header: 'Issued',
// Replaces the default text matcher for this column only. Both bounds are
// inclusive, so a range that starts and ends on one day keeps that day.
filterFn: (row, _columnId, value) => {
if (!isIssuedRange(value)) return true
return (
(value.from === null || row.issued >= value.from) &&
(value.to === null || row.issued <= value.to)
)
},
}),
helper.accessorKey('amount', { header: 'Amount' }),
]
// The complete source rows. The table filters them locally; the app never
// slices or copies them to apply a range.
const invoices: readonly Invoice[] = [
{
id: 'INV-2058',
customer: 'Juniper Health',
issued: '2026-12-07',
amount: 645.75,
},
{
id: 'INV-2057',
customer: 'Orbit Analytics',
issued: '2026-12-01',
amount: 4200,
},
{
id: 'INV-2056',
customer: 'Lumen Works',
issued: '2026-11-24',
amount: 1260,
},
{
id: 'INV-2055',
customer: 'Summit Supply',
issued: '2026-11-20',
amount: 2140,
},
{
id: 'INV-2054',
customer: 'Harbor & Co.',
issued: '2026-11-14',
amount: 980.5,
},
{
id: 'INV-2053',
customer: 'Canopy Digital',
issued: '2026-11-14',
amount: 1560,
},
{
id: 'INV-2052',
customer: 'Fieldwork Labs',
issued: '2026-11-09',
amount: 3725,
},
{
id: 'INV-2051',
customer: 'Northstar Studio',
issued: '2026-11-03',
amount: 2480,
},
]
const currency = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})
// Issue dates are calendar days, so format them in UTC to avoid a shift.
const issuedDate = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
timeZone: 'UTC',
})
function formatDay(iso: string): string {
return issuedDate.format(new Date(iso))
}
// A fixed "today" keeps the calendar's opening month stable on server and
// client; pass the real date in an app.
const today = new CalendarDate(2026, 12, 8)
// Drafts belong to the controls. Editing them changes nothing until Apply.
const draftFrom = shallowRef<GhostDatePickerValue>(null)
const draftTo = shallowRef<GhostDatePickerValue>(null)
const columnFilters = ref<DataTableColumnFilter[]>([])
const table =
useTemplateRef<GhostDataTableThemedExposed<Invoice>>('invoiceTable')
function isoDay(value: GhostDatePickerValue): string | null {
return value instanceof CalendarDate ? value.toString() : null
}
const draftRange = computed((): IssuedRange => ({
from: isoDay(draftFrom.value),
to: isoDay(draftTo.value),
}))
// An inverted range would silently match nothing, so Apply stays off and says why.
const rangeInverted = computed(() => {
const { from, to } = draftRange.value
return from !== null && to !== null && from > to
})
const appliedRange = computed(() => {
const value = columnFilters.value.find(
(filter) => filter.id === 'issued',
)?.value
return isIssuedRange(value) ? value : undefined
})
const appliedLabel = computed(() => {
const range = appliedRange.value
if (!range) return 'all issue dates'
const { from, to } = range
if (from !== null && to !== null) {
return from === to
? `issued ${formatDay(from)}`
: `issued ${formatDay(from)} to ${formatDay(to)}`
}
if (from !== null) return `issued on or after ${formatDay(from)}`
return to === null
? 'all issue dates'
: `issued on or before ${formatDay(to)}`
})
/**
* The parts of each picker's root slot the actions read. A picker reports
* typed text it has not committed as `pending`, and text it rejected (such as
* 2026-02-30) as `errors`; either way its `v-model` still holds the last valid
* date, so applying it would not match what the field shows.
*/
interface DraftPicker {
pending: boolean
errors: readonly GhostDatePickerError[]
clear: () => void
}
function hasUnusableText(...pickers: DraftPicker[]): boolean {
return pickers.some((picker) => picker.errors.length > 0)
}
function commitRange(range: IssuedRange): void {
const { from, to } = range
// `undefined` removes the filter, so every original row comes back.
// `setColumnFilter` writes `columnFilters`. It emits `stateChange` only
// with `manualFiltering`, so this local example filters in the browser.
table.value?.setColumnFilter(
'issued',
from === null && to === null ? undefined : { from, to },
)
}
/** Committed state that Apply cannot use: rejected text or an inverted range. */
function applyBlocked(from: DraftPicker, to: DraftPicker): boolean {
return rangeInverted.value || hasUnusableText(from, to)
}
function applyRange(from: DraftPicker, to: DraftPicker): void {
// Leaving a field commits valid text or records an error, and Vue re-renders
// before the click or Enter reaches Apply, so this reads the settled state.
// Text still pending or rejected here is not what `v-model` holds.
if (from.pending || to.pending || applyBlocked(from, to)) return
commitRange(draftRange.value)
}
function clearRange(from: DraftPicker, to: DraftPicker): void {
// `clear()` also drops typed or rejected text. Setting the models to `null`
// would not, because a model that is already `null` does not change.
from.clear()
to.clear()
commitRange({ from: null, to: null })
}
</script>
<template>
<GhostDataTable
ref="invoiceTable"
v-model:column-filters="columnFilters"
:data="invoices"
:columns="columns"
:get-row-id="(row) => row.id"
size="sm"
variant="card"
aria-label="Invoices by issue date"
>
<GhostDataTablePreset
:columns="columns"
:layout-slots="['toolbarEnd', 'footer']"
:show-global-filter="false"
contain-horizontal
scroll-label="Issued invoices"
empty-title="No invoices issued in this range"
:empty-heading-level="2"
>
<template #toolbarEnd>
<div
class="issued-range"
role="group"
aria-labelledby="issued-range-legend"
>
<span id="issued-range-legend" class="issued-range__legend">
Issue date
</span>
<!--
The pickers are renderless, so nesting adds no markup. It puts both
pickers' slot state (pending text, errors, clear) in scope for the
shared actions; each field still binds to its own picker.
-->
<GhostDatePicker
v-slot="fromPicker"
v-model="draftFrom"
:today="today"
>
<div class="issued-range__bound">
<GhostField>
<GhostFieldLabel>Issued from</GhostFieldLabel>
<GhostFieldControl v-slot="field">
<GhostDatePickerInput v-bind="field" />
</GhostFieldControl>
</GhostField>
<GhostDatePickerTrigger aria-label="Choose start date" />
</div>
<GhostDatePickerContent />
<GhostDatePicker v-slot="toPicker" v-model="draftTo" :today="today">
<div class="issued-range__bound">
<GhostField>
<GhostFieldLabel>Issued to</GhostFieldLabel>
<GhostFieldControl v-slot="field">
<GhostDatePickerInput v-bind="field" />
</GhostFieldControl>
</GhostField>
<GhostDatePickerTrigger aria-label="Choose end date" />
</div>
<GhostDatePickerContent />
<!--
Apply uses aria-disabled, not disabled, so it stays in the Tab
order. A field's error clears only when its corrected text is
committed on blur, which happens as focus moves to Apply.
-->
<div class="issued-range__actions">
<GhostButton
:aria-disabled="
applyBlocked(fromPicker, toPicker) ? 'true' : undefined
"
:aria-describedby="
applyBlocked(fromPicker, toPicker)
? 'issued-range-error'
: undefined
"
@click="applyRange(fromPicker, toPicker)"
>
Apply
</GhostButton>
<GhostButton
tone="neutral"
variant="ghost"
@click="clearRange(fromPicker, toPicker)"
>
Clear dates
</GhostButton>
</div>
<span
v-if="hasUnusableText(fromPicker, toPicker)"
id="issued-range-error"
class="issued-range__error"
>
Enter valid dates as YYYY-MM-DD, or clear them.
</span>
<span
v-else-if="rangeInverted"
id="issued-range-error"
class="issued-range__error"
>
Choose a start date on or before the end date.
</span>
</GhostDatePicker>
</GhostDatePicker>
</div>
</template>
<template #issued="{ value }">
<time :datetime="value">{{ formatDay(value) }}</time>
</template>
<template #amount="{ value }">
<span class="invoice-amount">{{ currency.format(value) }}</span>
</template>
<template #footer="{ rowCount }">
<!-- Announces each committed range, not every draft edit. -->
<span role="status">
{{ rowCount }} {{ rowCount === 1 ? 'invoice' : 'invoices' }},
{{ appliedLabel }}
</span>
</template>
</GhostDataTablePreset>
</GhostDataTable>
</template>
<style scoped>
.issued-range {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: var(--ghost-space-gap-sm);
}
.issued-range__legend,
.issued-range__error {
flex-basis: 100%;
}
.issued-range__legend {
font-weight: var(--ghost-type-weight-semibold);
}
.issued-range__error {
color: var(--ghost-status-danger-fg);
font-size: var(--ghost-type-size-sm);
}
.issued-range__bound,
.issued-range__actions {
display: flex;
align-items: end;
gap: var(--ghost-space-gap-xs);
}
/* Tabular figures keep the decimal places aligned down the column. */
.invoice-amount {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
</style>
data-table/multi-sort-invoices
A themed preset with opt-in multi-column sorting: every activation adds or cycles a column without a modifier key, rank badges and descriptions show each column's priority, and a visible Clear sorting button calls clearSorting().
| INV-1048 | Northstar Studio | Open | $2,480.00 |
| INV-1045 | Harbor & Pine | Open | $640.00 |
| INV-1044 | Fieldwork Labs | Paid | $3,725.00 |
| INV-1046 | Canopy Digital | Paid | $1,260.00 |
| INV-1047 | Fieldwork Labs | Past due | $3,725.00 |
| INV-1043 | Northstar Studio | Past due | $910.00 |
<script setup lang="ts">
import { ref } from 'vue'
import {
GhostButton,
GhostDataTable,
GhostDataTablePreset,
defineDataTableColumns,
type DataTableColumnSort,
} from '@ghostvue/themes'
interface Invoice {
id: string
customer: string
status: 'Open' | 'Paid' | 'Past due'
/** US dollars. Format for display; sort on the number. */
amount: number
}
const helper = defineDataTableColumns<Invoice>()
const columns = [
helper.accessorKey('id', { header: 'Invoice' }),
helper.accessorKey('customer', { header: 'Customer' }),
helper.accessorKey('status', { header: 'Status' }),
helper.accessorKey('amount', { header: 'Amount' }),
]
const invoices: readonly Invoice[] = [
{
id: 'INV-1048',
customer: 'Northstar Studio',
status: 'Open',
amount: 2480,
},
{
id: 'INV-1047',
customer: 'Fieldwork Labs',
status: 'Past due',
amount: 3725,
},
{ id: 'INV-1046', customer: 'Canopy Digital', status: 'Paid', amount: 1260 },
{ id: 'INV-1045', customer: 'Harbor & Pine', status: 'Open', amount: 640 },
{ id: 'INV-1044', customer: 'Fieldwork Labs', status: 'Paid', amount: 3725 },
{
id: 'INV-1043',
customer: 'Northstar Studio',
status: 'Past due',
amount: 910,
},
]
// Status first, then the largest amount within each status.
const sorting = ref<DataTableColumnSort[]>([
{ id: 'status', desc: false },
{ id: 'amount', desc: true },
])
const currency = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})
/*
* Every activation adds or cycles a column, with no modifier key, so touch
* and screen reader users can build the same sort as Shift+click. The
* visible Clear sorting button is the way back to a single column.
*/
const addsColumn = (): boolean => true
</script>
<template>
<GhostDataTable
v-model:sorting="sorting"
:data="invoices"
:columns="columns"
:get-row-id="(row) => row.id"
enable-multi-sort
:is-multi-sort-event="addsColumn"
variant="card"
size="sm"
aria-label="Invoices by status"
>
<template #default="{ clearSorting }">
<GhostDataTablePreset
:columns="columns"
:layout-slots="['toolbarEnd']"
:show-global-filter="false"
contain-horizontal
scroll-label="Invoices by status table"
>
<template #toolbarEnd>
<GhostButton
size="sm"
tone="neutral"
variant="outline"
@click="clearSorting"
>
Clear sorting
</GhostButton>
</template>
<template #amount="{ value }">
<span class="invoice-amount">{{ currency.format(value) }}</span>
</template>
</GhostDataTablePreset>
</template>
</GhostDataTable>
</template>
<style scoped>
/* Tabular figures keep the decimal places aligned down the column. */
.invoice-amount {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
</style>
data-table/empty-clear-filters
A themed preset that opts into the emptyDescription and emptyActions layout slots: when the search and a Past due only filter match nothing, the empty row explains which filters are active and offers Clear filters, which restores every row and moves focus to the search field.
No matching invoices No invoices match “Lumen” and past due only. Clear the filters to see all 5 invoices. | |||
<script setup lang="ts">
import { computed, nextTick, ref, useTemplateRef } from 'vue'
import {
GhostButton,
GhostCheckbox,
GhostDataTable,
GhostDataTablePreset,
GhostInput,
defineDataTableColumns,
type DataTableColumnFilter,
type GhostInputExposed,
} from '@ghostvue/themes'
type InvoiceStatus = 'Paid' | 'Open' | 'Past due'
interface Invoice {
id: string
customer: string
status: InvoiceStatus
/** US dollars. */
amount: number
}
const helper = defineDataTableColumns<Invoice>()
const columns = [
helper.accessorKey('id', { header: 'Invoice' }),
helper.accessorKey('customer', { header: 'Customer' }),
helper.accessorKey('status', { header: 'Status' }),
helper.accessorKey('amount', { header: 'Amount' }),
]
const invoices: readonly Invoice[] = [
{
id: 'INV-3106',
customer: 'Lumen Works',
status: 'Open',
amount: 1260,
},
{
id: 'INV-3105',
customer: 'Fieldwork Labs',
status: 'Past due',
amount: 3725,
},
{
id: 'INV-3104',
customer: 'Lumen Works',
status: 'Paid',
amount: 840,
},
{
id: 'INV-3103',
customer: 'Harbor & Co.',
status: 'Past due',
amount: 980.5,
},
{
id: 'INV-3102',
customer: 'Orbit Analytics',
status: 'Paid',
amount: 4200,
},
]
const currency = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})
// The page opens on a search and a status filter that match nothing (Lumen
// Works has no past-due invoice), so the empty state and its action show.
const globalFilter = ref('Lumen')
const columnFilters = ref<DataTableColumnFilter[]>([
{ id: 'status', value: 'Past due' },
])
const searchField = useTemplateRef<GhostInputExposed>('searchField')
const pastDueOnly = computed({
get: () => columnFilters.value.some((filter) => filter.id === 'status'),
set: (on: boolean) => {
columnFilters.value = on ? [{ id: 'status', value: 'Past due' }] : []
},
})
const activeFilters = computed(() => {
const parts: string[] = []
if (globalFilter.value) parts.push(`“${globalFilter.value}”`)
if (pastDueOnly.value) parts.push('past due only')
return parts.join(' and ')
})
async function clearFilters(): Promise<void> {
globalFilter.value = ''
pastDueOnly.value = false
// The rows come back and the empty state, with this button, unmounts.
// Move focus to the search field instead of losing it to the page.
await nextTick()
searchField.value?.focus()
}
</script>
<template>
<GhostDataTable
v-model:global-filter="globalFilter"
v-model:column-filters="columnFilters"
:data="invoices"
:columns="columns"
:get-row-id="(row) => row.id"
size="sm"
variant="card"
aria-label="Invoices"
>
<GhostDataTablePreset
:columns="columns"
:layout-slots="['toolbarEnd', 'emptyDescription', 'emptyActions']"
contain-horizontal
scroll-label="Filtered invoices"
empty-title="No matching invoices"
:empty-heading-level="2"
search-label="Search invoices"
>
<template #search="{ value, setValue, label, disabled }">
<label>
<span>{{ label }}</span>
<GhostInput
ref="searchField"
type="search"
size="sm"
:model-value="value"
:disabled="disabled"
@update:model-value="setValue"
/>
</label>
</template>
<template #toolbarEnd>
<label class="status-filter">
<GhostCheckbox v-model="pastDueOnly" />
Past due only
</label>
</template>
<template #amount="{ value }">
<span class="invoice-amount">{{ currency.format(value) }}</span>
</template>
<template #emptyDescription>
No invoices match {{ activeFilters }}. Clear the filters to see all
{{ invoices.length }} invoices.
</template>
<template #emptyActions>
<GhostButton
size="sm"
tone="neutral"
variant="outline"
@click="clearFilters"
>
Clear filters
</GhostButton>
</template>
</GhostDataTablePreset>
</GhostDataTable>
</template>
<style scoped>
.status-filter {
display: inline-flex;
align-items: center;
gap: var(--ghost-space-gap-xs);
}
/* Tabular figures keep the decimal places aligned down the column. */
.invoice-amount {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
</style>
data-table/workload-by-period
A themed preset that summarizes each person's known hours, unestimated assignments, availability and capacity rating for one planning period, with an Unassigned work row. Expanding a row lists its assignments; Edit opens the app's dialog editor, and a confirmed reassignment moves the hours and the assignment to the new owner.
Team workload
Known hours against availability for Dec 1–12.
| Assignments | Owner | Known hours | Unestimated | Available | Capacity |
|---|---|---|---|---|---|
| Maya | 14 h | None | 12 h | Over by 2 h | |
| Sam | 6 h | None | 16 h | Has room | |
| Priya | 10 h | 1 unestimated | 12 h | Near limit | |
| Unassigned work | 4 h | 1 unestimated | — |
<script setup lang="ts">
import { computed, nextTick, ref, shallowRef, useId, useTemplateRef } from 'vue'
import {
GhostBadge,
GhostButton,
GhostDataTable,
GhostDataTablePreset,
GhostDialog,
GhostDialogClose,
GhostDialogContent,
GhostDialogDescription,
GhostDialogOverlay,
GhostDialogTitle,
GhostRadioGroup,
GhostRadioGroupItem,
GhostSegmentedControl,
GhostSegmentedControlItem,
defineDataTableColumns,
type DataTableRowId,
} from '@ghostvue/themes'
type PersonId = 'maya' | 'sam' | 'priya'
/** Unassigned work is grouped like a person, but has no availability. */
type OwnerId = PersonId | 'unassigned'
type PeriodId = 'dec-1' | 'dec-15'
interface Period {
id: PeriodId
label: string
/** Hours each person can take on in this period. */
availability: Record<PersonId, number>
}
interface Assignment {
id: string
periodId: PeriodId
title: string
ownerId: OwnerId
/** Hours, or `null` while nobody has estimated it yet. */
estimate: number | null
}
interface Capacity {
label: string
tone: 'danger' | 'warning' | 'success'
}
interface WorkloadRow {
id: OwnerId
owner: string
/** Sum of the estimated assignments only. */
known: number
/** Assignments without an estimate, which `known` cannot include. */
unestimated: number
available: number | null
capacity: Capacity | null
assignments: readonly Assignment[]
}
const owners: readonly { id: OwnerId; name: string }[] = [
{ id: 'maya', name: 'Maya' },
{ id: 'sam', name: 'Sam' },
{ id: 'priya', name: 'Priya' },
{ id: 'unassigned', name: 'Unassigned work' },
]
const periods: readonly Period[] = [
{
id: 'dec-1',
label: 'Dec 1–12',
availability: { maya: 12, sam: 16, priya: 12 },
},
{
id: 'dec-15',
label: 'Dec 15–26',
availability: { maya: 8, sam: 6, priya: 10 },
},
]
// The app's record of confirmed assignments. Rows are replaced, never
// mutated, so every summary recomputes from the same source after a save.
const assignments = shallowRef<readonly Assignment[]>([
{
id: 'A-101',
periodId: 'dec-1',
title: 'Checkout copy review',
ownerId: 'maya',
estimate: 4,
},
{
id: 'A-102',
periodId: 'dec-1',
title: 'Billing API spike',
ownerId: 'maya',
estimate: 6,
},
{
id: 'A-103',
periodId: 'dec-1',
title: 'Release notes',
ownerId: 'maya',
estimate: 4,
},
{
id: 'A-104',
periodId: 'dec-1',
title: 'Onboarding emails',
ownerId: 'sam',
estimate: 6,
},
{
id: 'A-105',
periodId: 'dec-1',
title: 'Design QA',
ownerId: 'priya',
estimate: 6,
},
{
id: 'A-106',
periodId: 'dec-1',
title: 'Search tuning',
ownerId: 'priya',
estimate: 4,
},
{
id: 'A-107',
periodId: 'dec-1',
title: 'Accessibility audit',
ownerId: 'priya',
estimate: null,
},
{
id: 'A-108',
periodId: 'dec-1',
title: 'Flaky test triage',
ownerId: 'unassigned',
estimate: 4,
},
{
id: 'A-109',
periodId: 'dec-1',
title: 'Vendor contract review',
ownerId: 'unassigned',
estimate: null,
},
{
id: 'A-201',
periodId: 'dec-15',
title: 'Release retrospective',
ownerId: 'maya',
estimate: 3,
},
{
id: 'A-202',
periodId: 'dec-15',
title: 'Docs cleanup',
ownerId: 'maya',
estimate: 2,
},
{
id: 'A-203',
periodId: 'dec-15',
title: 'Billing API build',
ownerId: 'sam',
estimate: 8,
},
{
id: 'A-204',
periodId: 'dec-15',
title: 'Search tuning follow-up',
ownerId: 'priya',
estimate: 5,
},
{
id: 'A-205',
periodId: 'dec-15',
title: 'Holiday on-call handoff',
ownerId: 'unassigned',
estimate: 2,
},
])
/*
* The app's capacity policy. It rates known hours only: unestimated work is
* reported as a count next to the total instead of being guessed at.
*/
function rateCapacity(known: number, available: number): Capacity {
if (known > available) {
return { label: `Over by ${hours(known - available)}`, tone: 'danger' }
}
if (known >= available * 0.8) return { label: 'Near limit', tone: 'warning' }
return { label: 'Has room', tone: 'success' }
}
function hours(value: number): string {
return `${String(value)} h`
}
function ownerName(id: DataTableRowId): string {
return owners.find((owner) => owner.id === id)?.name ?? String(id)
}
const periodId = ref<PeriodId>('dec-1')
const period = computed(() => {
const selected = periods.find((entry) => entry.id === periodId.value)
if (!selected) throw new Error(`Unknown planning period ${periodId.value}`)
return selected
})
const rows = computed<WorkloadRow[]>(() =>
owners.map(({ id, name }) => {
const owned = assignments.value.filter(
(assignment) =>
assignment.periodId === periodId.value && assignment.ownerId === id,
)
const known = owned.reduce(
(total, assignment) => total + (assignment.estimate ?? 0),
0,
)
const available = id === 'unassigned' ? null : period.value.availability[id]
return {
id,
owner: name,
known,
unestimated: owned.filter((assignment) => assignment.estimate === null)
.length,
available,
// Unassigned work has nobody's availability to rate against.
capacity: available === null ? null : rateCapacity(known, available),
assignments: owned,
}
}),
)
// Ratings and grouped rows have no meaningful order to sort by, and sorting
// would move the unassigned row away from the people it is balanced against.
const helper = defineDataTableColumns<WorkloadRow>()
const columns = [
helper.accessorKey('owner', { header: 'Owner', enableSorting: false }),
helper.accessorKey('known', { header: 'Known hours', enableSorting: false }),
helper.accessorKey('unestimated', {
header: 'Unestimated',
enableSorting: false,
}),
helper.accessorKey('available', {
header: 'Available',
enableSorting: false,
}),
helper.accessorKey('capacity', { header: 'Capacity', enableSorting: false }),
]
// Row ids are owner ids, so an expanded person stays expanded when the
// period changes and the detail row shows that period's assignments.
const expandedRowIds = ref<DataTableRowId[]>([])
const status = ref('')
const root = useTemplateRef<HTMLElement>('root')
const ownerLabelId = useId()
const editing = ref<Assignment>()
const draftOwner = ref<string>()
const editorOpen = ref(false)
const saving = ref(false)
/** Assignment whose Edit button should take focus when the editor closes. */
const focusAfterClose = ref<string>()
function openEditor(assignment: Assignment): void {
editing.value = assignment
draftOwner.value = assignment.ownerId
focusAfterClose.value = undefined
editorOpen.value = true
}
function setEditorOpen(open: boolean): void {
// Keep the editor up until the app answers, so a save is never applied
// behind a dialog the planner already dismissed.
if (!open && saving.value) return
editorOpen.value = open
}
function isOwnerId(value: string | undefined): value is OwnerId {
return owners.some((owner) => owner.id === value)
}
async function confirmEdit(): Promise<void> {
const assignment = editing.value
const nextOwner = draftOwner.value
if (!assignment || !isOwnerId(nextOwner) || saving.value) return
if (nextOwner === assignment.ownerId) {
editorOpen.value = false
return
}
saving.value = true
// Stands in for the app's request. Totals change only after it confirms.
await new Promise((resolve) => setTimeout(resolve, 400))
assignments.value = assignments.value.map((entry) =>
entry.id === assignment.id ? { ...entry, ownerId: nextOwner } : entry,
)
// Show the assignment under its new owner, then return focus to it there:
// the Edit button that opened the editor left with the old owner's list.
if (!expandedRowIds.value.includes(nextOwner)) {
expandedRowIds.value = [...expandedRowIds.value, nextOwner]
}
status.value = `${assignment.title} moved from ${ownerName(assignment.ownerId)} to ${ownerName(nextOwner)}.`
focusAfterClose.value = assignment.id
saving.value = false
await nextTick()
editorOpen.value = false
}
function editorReturnTarget(): HTMLElement | null {
const id = focusAfterClose.value
if (!id) return null
return (
root.value?.querySelector<HTMLElement>(`[data-assignment-id="${id}"]`) ??
null
)
}
</script>
<template>
<section ref="root" class="workload" aria-labelledby="workload-title">
<div class="workload__header">
<div class="workload__intro">
<h2 id="workload-title" class="workload__title">Team workload</h2>
<p class="workload__lead">
Known hours against availability for {{ period.label }}.
</p>
</div>
<GhostSegmentedControl
v-model="periodId"
size="sm"
aria-label="Planning period"
>
<GhostSegmentedControlItem
v-for="entry in periods"
:key="entry.id"
:value="entry.id"
>
{{ entry.label }}
</GhostSegmentedControlItem>
</GhostSegmentedControl>
</div>
<GhostDataTable
v-model:expanded-row-ids="expandedRowIds"
:data="rows"
:columns="columns"
:get-row-id="(row) => row.id"
enable-row-expansion
size="sm"
variant="card"
aria-label="Workload by owner"
>
<GhostDataTablePreset
:columns="columns"
:show-global-filter="false"
:row-expansion-label="
(rowId) => `Show assignments for ${ownerName(rowId)}`
"
expansion-header-label="Assignments"
contain-horizontal
scroll-label="Workload table"
>
<template #known="{ value }">
<span class="workload__number">{{ hours(value) }}</span>
</template>
<template #unestimated="{ value }">
{{ value === 0 ? 'None' : `${String(value)} unestimated` }}
</template>
<template #available="{ value }">
<span class="workload__number">
{{ value === null ? '—' : hours(value) }}
</span>
</template>
<template #capacity="{ value }">
<GhostBadge v-if="value" :tone="value.tone" size="sm">
{{ value.label }}
</GhostBadge>
</template>
<template #detail="{ row }">
<ul
v-if="row.assignments.length"
class="workload-detail"
:aria-label="`${row.owner}, ${period.label}`"
>
<li
v-for="assignment in row.assignments"
:key="assignment.id"
class="workload-detail__item"
>
<span class="workload-detail__title">{{ assignment.title }}</span>
<span
v-if="assignment.estimate !== null"
class="workload__number"
>
{{ hours(assignment.estimate) }}
</span>
<GhostBadge v-else variant="outline" size="sm">
Not estimated
</GhostBadge>
<GhostButton
size="sm"
variant="outline"
tone="neutral"
:data-assignment-id="assignment.id"
:aria-label="`Edit ${assignment.title}`"
@click="openEditor(assignment)"
>
Edit
</GhostButton>
</li>
</ul>
<span v-else>No assignments in {{ period.label }}.</span>
</template>
</GhostDataTablePreset>
</GhostDataTable>
<p class="workload__status" role="status">{{ status }}</p>
<GhostDialog :open="editorOpen" @update:open="setEditorOpen">
<GhostDialogOverlay />
<GhostDialogContent :return-focus="editorReturnTarget">
<div class="workload-editor__header">
<GhostDialogTitle>Edit assignment</GhostDialogTitle>
<GhostDialogDescription v-if="editing">
{{ editing.title }},
{{
editing.estimate === null
? 'not estimated'
: hours(editing.estimate)
}}, {{ period.label }}. Totals update once the change is saved.
</GhostDialogDescription>
</div>
<form class="workload-editor__form" @submit.prevent="confirmEdit">
<span :id="ownerLabelId" class="workload-editor__label">Owner</span>
<GhostRadioGroup
v-model="draftOwner"
name="owner"
:aria-labelledby="ownerLabelId"
:disabled="saving"
>
<label
v-for="owner in owners"
:key="owner.id"
class="workload-editor__option"
>
<GhostRadioGroupItem :value="owner.id" />
{{ owner.name }}
</label>
</GhostRadioGroup>
<div class="workload-editor__actions">
<GhostDialogClose
:as="GhostButton"
variant="soft"
tone="neutral"
:disabled="saving"
>
Cancel
</GhostDialogClose>
<GhostButton type="submit" :loading="saving">Save</GhostButton>
</div>
</form>
</GhostDialogContent>
</GhostDialog>
</section>
</template>
<style scoped>
.workload {
display: grid;
gap: var(--ghost-space-stack-md);
}
.workload__header {
align-items: end;
display: flex;
flex-wrap: wrap;
gap: var(--ghost-space-gap-md);
justify-content: space-between;
}
.workload__intro {
display: grid;
gap: var(--ghost-space-gap-xs);
}
/* Native text picks up docs prose styles, so each element resets its own. */
.workload__title {
color: var(--ghost-text-default);
font-size: var(--ghost-type-size-lg);
font-weight: var(--ghost-type-weight-semibold);
line-height: var(--ghost-type-line-tight);
margin: 0;
}
.workload__lead,
.workload__status {
color: var(--ghost-text-muted);
font-size: var(--ghost-type-size-sm);
line-height: var(--ghost-type-line-snug);
margin: 0;
}
/* Tabular figures keep hour totals aligned down each column. */
.workload__number {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.workload-detail {
display: grid;
gap: var(--ghost-space-gap-sm);
list-style: none;
margin: 0;
padding: 0;
}
.workload-detail__item {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--ghost-space-gap-sm);
margin: 0;
}
.workload-detail__title {
flex: 1 1 10rem;
min-inline-size: 0;
}
.workload-editor__header {
display: grid;
gap: var(--ghost-space-gap-xs);
}
.workload-editor__form {
display: grid;
gap: var(--ghost-space-stack-md);
margin: 0;
}
.workload-editor__label {
color: var(--ghost-text-default);
font-size: var(--ghost-type-size-sm);
font-weight: var(--ghost-type-weight-medium);
}
.workload-editor__option {
align-items: center;
display: flex;
gap: var(--ghost-space-gap-sm);
}
.workload-editor__actions {
display: flex;
flex-wrap: wrap;
gap: var(--ghost-space-gap-sm);
justify-content: flex-end;
}
</style>
data-table/select-all-matching
A themed server table with query-wide selection: select a page, extend it to all 2,300 unpaid invoices, uncheck rows on any page, and send the filter plus the excluded ids to a Mark sent action that the server resolves. Disputed invoices show a rejected action that keeps the selection.
| Invoice | Customer | Status | Amount | |
|---|---|---|---|---|
No invoices | ||||
<script setup lang="ts">
import { computed, onMounted, ref, shallowRef, useTemplateRef } from 'vue'
import {
GhostBadge,
GhostButton,
GhostDataTable,
GhostDataTablePreset,
GhostInlineAlert,
GhostPagination,
GhostSegmentedControl,
GhostSegmentedControlItem,
defineDataTableColumns,
useGhostDataTableServerRequest,
type DataTableQueryState,
type DataTableSelection,
type DataTableSelectionCountKind,
type DataTableStateChangePayload,
type GhostDataTableThemedExposed,
} from '@ghostvue/themes'
const props = withDefaults(
defineProps<{
/** Demo server latency in milliseconds. Tests pass `0`. */
latency?: number
}>(),
{ latency: 300 },
)
type InvoiceStatus = 'unpaid' | 'disputed' | 'sent'
interface Invoice {
id: string
customer: string
status: InvoiceStatus
/** US dollars. */
amount: number
}
const STATUS_LABELS: Record<InvoiceStatus, string> = {
unpaid: 'Unpaid',
disputed: 'Disputed',
sent: 'Sent',
}
const helper = defineDataTableColumns<Invoice>()
// The server owns order and paging; this example focuses on selection.
const columns = [
helper.accessorKey('id', { header: 'Invoice', enableSorting: false }),
helper.accessorKey('customer', { header: 'Customer', enableSorting: false }),
helper.accessorKey('status', { header: 'Status', enableSorting: false }),
helper.accessorKey('amount', { header: 'Amount', enableSorting: false }),
]
/* ---------------------------------------------------------------------------
* Demo server. A real app calls its API instead. The page never downloads
* the matching ids: the bulk action sends the filter plus the exclusions,
* and the server resolves them.
* ------------------------------------------------------------------------- */
const customers = [
'Northstar Studio',
'Fieldwork Labs',
'Canopy Digital',
'Harbor & Co.',
'Summit Supply',
'Lumen Works',
]
const serverRows: Invoice[] = Array.from({ length: 2440 }, (_, index) => ({
id: `INV-${String(index + 1).padStart(4, '0')}`,
customer: customers[index % customers.length] ?? 'Northstar Studio',
// 2,300 unpaid invoices, then 140 disputed ones.
status: index < 2300 ? 'unpaid' : 'disputed',
amount: 120 + ((index * 7919) % 4800),
}))
function statusFilter(
columnFilters: readonly { id: string; value: unknown }[],
) {
return columnFilters.find((filter) => filter.id === 'status')?.value
}
function matching(status: unknown): Invoice[] {
return serverRows.filter((row) => row.status === status)
}
function wait<T>(value: () => T): Promise<T> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(value())
}, props.latency)
})
}
function fetchPage(query: DataTableQueryState) {
return wait(() => {
const rows = matching(statusFilter(query.columnFilters))
const { pageIndex, pageSize } = query.pagination
const start = (pageIndex - 1) * pageSize
return { rows: rows.slice(start, start + pageSize), total: rows.length }
})
}
type MarkSentBody =
| { ids: readonly string[] }
| {
filter: { columnFilters: readonly { id: string; value: unknown }[] }
excludeIds: readonly (string | number)[]
expectedCount: number
expectedCountExact: boolean
}
type MarkSentResult =
{ ok: true; count: number } | { ok: false; reason: string }
/** Resolves the selection on the server, authorizes it, and runs it. */
function postMarkSent(json: string): Promise<MarkSentResult> {
return wait((): MarkSentResult => {
const body = JSON.parse(json) as MarkSentBody
let targets: Invoice[]
if ('ids' in body) {
const ids = new Set(body.ids)
targets = serverRows.filter((row) => ids.has(row.id))
} else {
const excluded = new Set(body.excludeIds)
targets = matching(statusFilter(body.filter.columnFilters)).filter(
(row) => !excluded.has(row.id),
)
}
const disputed = targets.filter((row) => row.status === 'disputed').length
if (disputed > 0) {
return {
ok: false,
reason: `${count.format(disputed)} of the selected invoices are disputed. Resolve the disputes before marking them sent.`,
}
}
for (const row of targets) row.status = 'sent'
return { ok: true, count: targets.length }
})
}
/* ---------------------------------------------------------------------------
* Table state and the server loop.
* ------------------------------------------------------------------------- */
const table =
useTemplateRef<GhostDataTableThemedExposed<Invoice>>('invoiceTable')
const request = useGhostDataTableServerRequest()
const data = shallowRef<Invoice[]>([])
const rowCount = ref(0)
const loading = ref(true)
const status = ref<'unpaid' | 'disputed'>('unpaid')
const selection = ref<DataTableSelection>({ mode: 'ids', ids: [] })
const saving = ref(false)
const notice = ref('')
const actionError = ref('')
const lastRequest = ref('')
const count = new Intl.NumberFormat('en-US')
const currency = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})
async function onStateChange({
requestId,
query,
}: DataTableStateChangePayload): Promise<void> {
request.begin(requestId)
loading.value = true
const page = await fetchPage(query)
if (!request.isLatest(requestId)) return
data.value = page.rows
rowCount.value = page.total
loading.value = false
}
onMounted(() => {
// The first page loads through the same stateChange path as every other.
table.value?.retry()
})
function changeStatus(next: unknown): void {
if (next !== 'unpaid' && next !== 'disputed') return
status.value = next
notice.value = ''
actionError.value = ''
// Committed through the table, so a query selection clears and announces.
table.value?.setColumnFilter('status', next)
}
function countLabel(selected: number, kind: DataTableSelectionCountKind) {
if (kind === 'atLeast') return `At least ${count.format(selected)} selected`
if (kind === 'estimate') return `About ${count.format(selected)} selected`
return `${count.format(selected)} selected`
}
const statusLabel = computed(() =>
status.value === 'unpaid' ? 'unpaid' : 'disputed',
)
async function markSent(current: DataTableSelection): Promise<void> {
if (saving.value) return
saving.value = true
notice.value = ''
actionError.value = ''
// Branch on the mode: a query selection is a description, never a list.
const body: MarkSentBody =
current.mode === 'ids'
? { ids: current.ids.map(String) }
: {
filter: current.query,
excludeIds: current.excludedIds,
expectedCount: current.matchCount,
expectedCountExact: current.matchCountExact,
}
const json = JSON.stringify(body)
lastRequest.value = json
const result = await postMarkSent(json)
saving.value = false
if (!result.ok) {
// Keep the selection so the operator can exclude rows or narrow the filter.
actionError.value = result.reason
return
}
notice.value = `${count.format(result.count)} ${result.count === 1 ? 'invoice' : 'invoices'} marked sent`
table.value?.resetRowSelection()
table.value?.retry()
}
</script>
<template>
<div class="bulk-invoices">
<GhostSegmentedControl
:model-value="status"
size="sm"
aria-label="Invoice status"
@update:model-value="changeStatus"
>
<GhostSegmentedControlItem value="unpaid"
>Unpaid</GhostSegmentedControlItem
>
<GhostSegmentedControlItem value="disputed">
Disputed
</GhostSegmentedControlItem>
</GhostSegmentedControl>
<GhostInlineAlert
v-if="actionError"
tone="danger"
variant="outline"
data-testid="bulk-action-error"
>
<template #title>Invoices not marked sent</template>
<template #message>{{ actionError }}</template>
</GhostInlineAlert>
<GhostDataTable
ref="invoiceTable"
v-model:selection="selection"
:data="data"
:columns="columns"
:get-row-id="(row) => row.id"
:row-count="rowCount"
:default-pagination="{ pageIndex: 1, pageSize: 10 }"
:default-column-filters="[{ id: 'status', value: 'unpaid' }]"
:loading="loading || saving"
manual-pagination
manual-filtering
manual-sorting
enable-row-selection
enable-query-selection
size="sm"
variant="card"
aria-label="Invoices to send"
@state-change="onStateChange"
>
<GhostDataTablePreset
:columns="columns"
:layout-slots="['bulkActions', 'footer']"
:show-global-filter="false"
contain-horizontal
scroll-label="Invoices to send table"
empty-title="No invoices"
:empty-heading-level="2"
select-all-label="Select all invoices on this page"
:row-selection-label="(rowId) => `Select invoice ${String(rowId)}`"
>
<template
#bulkActions="{
selection: current,
selectedCount,
selectedCountKind,
canSelectAllMatching,
selectAllMatching,
clearSelection,
}"
>
<span data-testid="selected-count">{{
countLabel(selectedCount, selectedCountKind)
}}</span>
<GhostButton size="sm" :loading="saving" @click="markSent(current)">
Mark sent
</GhostButton>
<!--
One button that stays mounted and switches between the opt-in
and Clear selection, so focus never moves. It is the last control
in the bar, so Shift+Tab from the select-all checkbox reaches it
right after the table's scroll region.
-->
<GhostButton
size="sm"
tone="neutral"
variant="outline"
data-testid="selection-scope"
@click="
current.mode === 'ids' && canSelectAllMatching
? selectAllMatching()
: clearSelection()
"
>
{{
current.mode === 'ids' && canSelectAllMatching
? `Select all ${count.format(rowCount)} ${statusLabel} invoices`
: 'Clear selection'
}}
</GhostButton>
</template>
<template #status="{ value }">
<GhostBadge
:tone="value === 'disputed' ? 'danger' : 'neutral'"
variant="soft"
size="sm"
>
{{ STATUS_LABELS[value] }}
</GhostBadge>
</template>
<template #amount="{ value }">
<span class="invoice-amount">{{ currency.format(value) }}</span>
</template>
<template
#footer="{
pagination: page,
pageCount,
rowCount: total,
setPageIndex,
}"
>
<span role="status" data-testid="bulk-status">
{{ count.format(total) }} {{ statusLabel }}
{{ total === 1 ? 'invoice' : 'invoices' }}
<template v-if="notice">· {{ notice }}</template>
</span>
<GhostPagination
size="sm"
:model-value="page.pageIndex"
:page-count="pageCount"
aria-label="Invoices to send pages"
@update:model-value="setPageIndex"
/>
</template>
</GhostDataTablePreset>
</GhostDataTable>
<details v-if="lastRequest" class="bulk-invoices__request">
<summary>Last request body</summary>
<pre data-testid="last-request">{{ lastRequest }}</pre>
</details>
</div>
</template>
<style scoped>
.bulk-invoices {
display: grid;
gap: var(--ghost-space-gap-md, 1rem);
justify-items: start;
}
.bulk-invoices > .ghost-data-table {
justify-self: stretch;
}
/* Tabular figures keep the decimal places aligned down the column. */
.invoice-amount {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.bulk-invoices__request pre {
max-inline-size: 100%;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-all;
}
</style>