Billing & Invoices
Search, filter and act on invoices in one app built from GhostVue tables, filters and overlays. Actions use sample data.
Built with
Try it with the keyboard
- Make sure the Single-key shortcuts switch in the app header is on (it turns S and M off, and remembers your choice). Then press S to focus Search invoices.
- Type
1031, then press Enter to jump to the matching invoice ID. - Press Enter to open the invoice drawer, then Esc to close it; focus returns to the invoice ID.
- Press Shift+Tab to reach the row’s checkbox, then Space to select it.
- Press M to mark the selected invoice paid.
Invoices
Review balances, collect payments, and manage refunds.
Invoices issued Aug 1 to Nov 18
Status
Issued
YYYY-MM-DD| Actions | ||||||
|---|---|---|---|---|---|---|
| Northstar Studio | Paid | $2,480.00 | ||||
| Lumen Works | Draft | $1,260.00 | ||||
| Brightwater Analytics Cooperative | Draft | $18,640.00 | ||||
| Fieldwork Labs | Draft | $3,725.00 | ||||
| Canopy Digital | Paid | $1,560.00 | ||||
| Harbor & Co. | Draft | $980.00 | ||||
| Saltmarsh Field Instruments International | Paid | $12,075.00 | ||||
| Summit Supply | Draft | $2,140.00 | ||||
| Oriel | Paid | $319.00 | ||||
| Juniper Systems | Paid | $4,230.00 |
vue
<script setup lang="ts">
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
ref,
shallowRef,
useId,
useTemplateRef,
watch,
} from 'vue'
import {
CalendarDate,
GhostBadge,
GhostButton,
GhostDataTable,
GhostDataTablePreset,
GhostDatePicker,
GhostDatePickerCalendar,
GhostDatePickerContent,
GhostDatePickerTrigger,
GhostDialog,
GhostDrawer,
GhostDropdownMenu,
GhostDropdownMenuContent,
GhostDropdownMenuItem,
GhostDropdownMenuTrigger,
GhostInput,
GhostPagination,
GhostSegmentedControl,
GhostSegmentedControlItem,
GhostSelect,
GhostSelectContent,
GhostSelectOption,
GhostSelectTrigger,
GhostSelectValue,
GhostSwitch,
defineDataTableColumns,
useGhostToast,
type DataTableRowId,
type DataTableColumnSort,
type GhostDataTableThemedExposed,
type GhostDatePickerValue,
type GhostInputExposed,
} from '@ghostvue/themes'
import InvoiceInspector from './InvoiceInspector.vue'
import InvoiceRefundDialogContent from './InvoiceRefundDialogContent.vue'
import {
formatAmount,
formatIssued,
formatIssuedRange,
initialInvoices,
invoiceCsv,
invoiceStatuses,
invoiceStatusTones,
withPayment,
withRefund,
withReminder,
type Invoice,
type InvoiceStatus,
} from './invoices'
import './billing-ops.css'
const { toast } = useGhostToast()
const invoices = shallowRef(initialInvoices)
const table =
useTemplateRef<GhostDataTableThemedExposed<Invoice>>('invoiceTable')
const searchField = useTemplateRef<GhostInputExposed>('searchField')
const workspace = useTemplateRef<HTMLElement>('workspace')
const statusSelect = useTemplateRef<HTMLElement>('statusSelect')
const statusSelectOpen = ref(false)
let statusSelectObserver: ResizeObserver | undefined
/*
* S and M are single-character shortcuts, which speech input and screen
* reader quick navigation can trigger by accident (WCAG 2.1.4). The switch in
* the header turns them off. The choice is kept in this browser so a reader
* who turned them off does not meet them again on the next visit. It starts
* on to match the server render and is corrected after mount.
*/
const SHORTCUTS_STORAGE_KEY = 'ghostvue:billing-single-key-shortcuts'
const singleKeyShortcuts = ref(true)
const search = ref('')
const sorting = ref<DataTableColumnSort[]>([])
const status = ref<string | undefined>('All')
const dateRange = shallowRef<GhostDatePickerValue>(null)
const selectedRowIds = ref<DataTableRowId[]>([])
const pagination = ref({ pageIndex: 1, pageSize: 10 })
const inspectedId = ref<string>()
const inspectorOpen = ref(false)
let inspectorOpener: HTMLElement | null = null
const refundId = ref<string>()
const refundOpen = ref(false)
const refundReason = ref('')
const prefix = useId()
const calendarToday = new CalendarDate(2026, 11, 18)
const helper = defineDataTableColumns<Invoice>()
const columns = [
helper.accessorKey('id', { header: 'Invoice' }),
helper.accessorKey('customer', { header: 'Customer' }),
helper.accessorKey('issued', { header: 'Issued' }),
helper.accessorKey('status', { header: 'Status' }),
helper.accessorKey('amountCents', { header: 'Amount' }),
helper.accessorFn('actions', {
accessorFn: () => '',
header: 'Actions',
enableSorting: false,
enableColumnFilter: false,
}),
] as const
const sortDescription = computed(() => {
const sort = sorting.value[0]
if (!sort) return undefined
const heading = columns.find((column) => column.id === sort.id)?.header
return heading
? `Sorted by ${heading}, ${sort.desc ? 'descending' : 'ascending'}`
: undefined
})
// The date button shows the committed range as its visible text, so the
// toolbar needs no From and To fields to say what is filtered.
const dateRangeText = computed(() => {
const range = dateRange.value
return range && 'start' in range
? formatIssuedRange(range.start.toString(), range.end.toString())
: 'Any date'
})
/** Invoices inside the committed Issued range, before status and search. */
const invoicesInRange = computed(() => {
const range = dateRange.value
const start = range && 'start' in range ? range.start.toString() : undefined
const end = range && 'end' in range ? range.end.toString() : undefined
return invoices.value.filter(
(invoice) =>
(start === undefined || invoice.issued >= start) &&
(end === undefined || invoice.issued <= end),
)
})
const visibleInvoices = computed(() =>
status.value === 'All'
? invoicesInRange.value
: invoicesInRange.value.filter(
(invoice) => invoice.status === status.value,
),
)
/**
* Empty-state title that names each active filter, so a zero-result table
* says what to undo: "No Past due invoices match “zzz”".
*/
const emptyTitle = computed(() => {
const statusPart = status.value === 'All' ? '' : `${String(status.value)} `
const range = dateRange.value
const issuedPart =
range && 'start' in range ? ` issued ${dateRangeText.value}` : ''
const query = search.value.trim()
const searchPart = query ? ` match “${query}”` : ''
return `No ${statusPart}invoices${issuedPart}${searchPart}`
})
/**
* Selected invoices that no filter currently shows. The selection is kept
* while filters change (clearing it on every keystroke would lose work), so
* the bulk bar says how much of it is out of view: Mark paid still acts on
* those rows.
*/
const hiddenSelectedCount = computed(() => {
const shown = new Set(
table.value?.getPrePaginationRowModel().map((entry) => entry.rowId) ?? [],
)
return selectedRowIds.value.filter((id) => !shown.has(id)).length
})
function selectionSummary(selectedCount: number): string {
const hidden = hiddenSelectedCount.value
if (!hidden) return `${String(selectedCount)} selected`
return hidden === selectedCount
? `${String(selectedCount)} selected, hidden by filters`
: `${String(selectedCount)} selected, ${String(hidden)} hidden by filters`
}
const inspected = computed(() =>
invoices.value.find((invoice) => invoice.id === inspectedId.value),
)
const refunding = computed(() =>
invoices.value.find((invoice) => invoice.id === refundId.value),
)
/**
* The period the metrics cover: the committed Issued range, or the span of
* all invoices when no range is set. Stated on screen so a total never reads
* as all-time when the table is narrowed to a few days.
*/
const metricsPeriod = computed(() => {
const range = dateRange.value
if (range && 'start' in range)
return formatIssuedRange(range.start.toString(), range.end.toString())
const dates = invoices.value.map((invoice) => invoice.issued).sort()
const first = dates[0]
const last = dates.at(-1)
return first && last ? formatIssuedRange(first, last) : 'No invoices'
})
function invoiceCount(count: number): string {
return `${String(count)} ${count === 1 ? 'invoice' : 'invoices'}`
}
/**
* Totals follow the Issued range but not the status filter or search, so
* choosing one metric never zeroes the others. Each metric is a shortcut to
* the status filter with the same value.
*/
const metrics = computed(() =>
(
[
{ label: 'Paid', status: 'Paid' },
{ label: 'Past due', status: 'Past due' },
{ label: 'Drafts', status: 'Draft' },
] as const
).map((metric) => {
const matching = invoicesInRange.value.filter(
(invoice) => invoice.status === metric.status,
)
const amount = formatAmount(
matching.reduce((sum, invoice) => sum + invoice.amountCents, 0),
)
const count = invoiceCount(matching.length)
return {
...metric,
amount,
count,
}
}),
)
const metricAnnouncement = ref('')
const payableIds = computed(() => {
const selected = new Set(selectedRowIds.value)
return invoices.value
.filter(
(invoice) =>
selected.has(invoice.id) &&
(invoice.status === 'Draft' || invoice.status === 'Past due'),
)
.map((invoice) => invoice.id)
})
watch([search, status, dateRange], () => {
if (pagination.value.pageIndex !== 1)
pagination.value = { ...pagination.value, pageIndex: 1 }
})
/**
* Applies a metric's status filter, or returns to All when that metric is
* already active, and announces the result. Focus stays on the metric.
*/
async function toggleMetric(value: InvoiceStatus): Promise<void> {
status.value = status.value === value ? 'All' : value
// Clear first so a repeated message is announced again.
metricAnnouncement.value = ''
await nextTick()
metricAnnouncement.value =
status.value === 'All'
? 'Showing all invoices'
: `Showing ${value} invoices`
}
function tone(value: InvoiceStatus) {
return invoiceStatusTones[value]
}
async function clearFilters(): Promise<void> {
search.value = ''
status.value = 'All'
dateRange.value = null
await nextTick()
searchField.value?.focus()
}
/** Removes the range and closes the calendar, which refocuses the date button. */
function clearDates(picker: { clear: () => void; close: () => void }): void {
picker.clear()
picker.close()
}
function inspect(invoice: Invoice, trigger: EventTarget | null): void {
inspectorOpener = trigger instanceof HTMLElement ? trigger : null
inspectedId.value = invoice.id
inspectorOpen.value = true
}
async function setInspectorOpen(open: boolean): Promise<void> {
inspectorOpen.value = open
if (open) return
const opener = inspectorOpener
inspectorOpener = null
await nextTick()
// A refund can remove the opener from the filtered table while the drawer
// still owns focus. Wait for the drawer to release the workspace first.
if (
!inspectorOpen.value &&
!opener?.isConnected &&
document.activeElement === document.body
) {
searchField.value?.focus()
}
}
/** Replaces the invoices whose ids are in `ids` with `change` applied. */
function updateInvoices(
ids: ReadonlySet<string>,
change: (invoice: Invoice) => Invoice,
): void {
invoices.value = invoices.value.map((invoice) =>
ids.has(invoice.id) ? change(invoice) : invoice,
)
}
function markPaid(): void {
const ids = new Set(payableIds.value)
if (!ids.size) return
updateInvoices(ids, withPayment)
toast({
title:
ids.size === 1
? 'Invoice marked paid'
: `${String(ids.size)} invoices marked paid`,
})
}
function statusOf(id: string): InvoiceStatus | undefined {
return invoices.value.find((invoice) => invoice.id === id)?.status
}
function markInvoicePaid(id: string): void {
const current = statusOf(id)
if (current !== 'Draft' && current !== 'Past due') return
updateInvoices(new Set([id]), withPayment)
toast({ title: 'Invoice marked paid', description: `Invoice ${id}` })
}
function remindInvoice(id: string): void {
const invoice = invoices.value.find((entry) => entry.id === id)
if (invoice?.status !== 'Past due') return
updateInvoices(new Set([id]), withReminder)
toast({ title: 'Reminder sent', description: `To ${invoice.email}` })
}
function refundInvoice(id: string, reason: string): void {
if (statusOf(id) !== 'Paid') return
updateInvoices(new Set([id]), (invoice) => withRefund(invoice, reason))
toast({ title: 'Refund recorded', description: `Invoice ${id}` })
}
function rowMenuTrigger(id: string): HTMLElement | null {
const trigger = document.getElementById(`${prefix}-menu-${id}`)
return trigger?.isConnected ? trigger : null
}
/**
* Runs a row menu action, then puts focus back on that row's menu button.
* The menu restores focus itself, but an action that changes the status can
* filter the row out of the table, taking the button with it. Search is the
* nearest stable control, as when a refund empties the drawer's opener.
*/
async function runRowAction(id: string, action: () => void): Promise<void> {
action()
await nextTick()
const trigger = rowMenuTrigger(id)
if (trigger) trigger.focus({ preventScroll: true })
else searchField.value?.focus()
}
/** Download PDF is a sample action: the demo has no documents to serve. */
function downloadSample(id: string): void {
toast({
title: `${id}.pdf`,
description: 'Sample only: this demo does not generate PDFs.',
})
}
/**
* Opens the refund confirmation for a Paid row. Waits for the menu to finish
* closing, so the dialog opens with focus on the row's menu button.
*/
async function openRefund(id: string): Promise<void> {
if (statusOf(id) !== 'Paid') return
await nextTick()
rowMenuTrigger(id)?.focus({ preventScroll: true })
refundId.value = id
refundReason.value = ''
refundOpen.value = true
}
function setRefundOpen(open: boolean): void {
refundOpen.value = open
}
/**
* Focus goes back to the row's menu button. A confirmed refund under the Paid
* filter removes that row, so search takes focus instead.
*/
function refundReturnFocus(): HTMLElement | null {
const id = refundId.value
return (id ? rowMenuTrigger(id) : null) ?? searchField.value?.element ?? null
}
function confirmRefund(): void {
const id = refundId.value
const reason = refundReason.value.trim()
if (!id || !reason || statusOf(id) !== 'Paid') return
refundInvoice(id, reason)
refundOpen.value = false
}
/**
* Enter in search moves to the first result's invoice ID, so a match is one
* key away instead of a dozen Tab stops past the filters and sort buttons.
* A search field outside a form has no Enter default to replace; Enter that
* confirms an IME composition is left to the IME.
*/
function focusFirstResult(event: KeyboardEvent): void {
if (event.isComposing) return
const first = workspace.value?.querySelector<HTMLElement>(
'.billing-invoice-id',
)
if (!first) return
event.preventDefault()
first.focus()
}
/** Inputs that take typed characters. Checkboxes and buttons do not. */
const nonTextInputTypes = new Set([
'button',
'checkbox',
'color',
'file',
'image',
'radio',
'range',
'reset',
'submit',
])
function takesTypedText(target: Element): boolean {
if (target instanceof HTMLInputElement)
return !nonTextInputTypes.has(target.type)
return (
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
(target instanceof HTMLElement && target.isContentEditable)
)
}
/**
* App shortcuts: S focuses search and M marks the selected invoices paid.
*
* The listener is on the document so S also works before anything has focus,
* as when a reader has just arrived. A press only counts when focus is inside
* this app or on no element at all (the body), so the docs nav, docs search,
* example toolbar and source panel keep their keys, and so do this app's
* drawer, dialog and menus: they render outside the app root, and menus use
* letters for typeahead. Letters typed into a text field stay text, and any
* press with Ctrl, Command or Alt stays with the browser and the docs, which
* own Ctrl/⌘+K and / for site search, so neither is bound here.
*/
function onShortcut(event: KeyboardEvent): void {
if (
!singleKeyShortcuts.value ||
event.defaultPrevented ||
event.isComposing ||
event.ctrlKey ||
event.metaKey ||
event.altKey
)
return
const root = workspace.value
const target = event.target
if (!root || !(target instanceof Element)) return
if (target !== document.body && !root.contains(target)) return
if (takesTypedText(target)) return
const key = event.key.toLowerCase()
if (key === 's') {
event.preventDefault()
searchField.value?.focus()
} else if (key === 'm' && payableIds.value.length) {
event.preventDefault()
void markPaidFrom(target)
}
}
/**
* Under a status filter the paid rows leave the table, and the focused
* checkbox can go with them; search is the nearest stable control.
*/
async function markPaidFrom(focused: Element): Promise<void> {
markPaid()
await nextTick()
if (!focused.isConnected) searchField.value?.focus()
}
/**
* The phone status select is hidden by a container query once the workspace
* widens, as on rotation. Its listbox is portaled outside the workspace, so
* it would stay open with its trigger gone. Closing it and moving focus to
* the checked segment keeps the open state and focus on a visible control.
*/
async function closeHiddenStatusSelect(
entries: ResizeObserverEntry[],
): Promise<void> {
if (!statusSelectOpen.value) return
if (!entries.some((entry) => entry.contentRect.width === 0)) return
statusSelectOpen.value = false
await nextTick()
const focused = document.activeElement
if (focused === document.body || statusSelect.value?.contains(focused)) {
workspace.value
?.querySelector<HTMLElement>(
'.billing-status-filter [aria-pressed="true"]',
)
?.focus()
}
}
onMounted(() => {
if (statusSelect.value && typeof ResizeObserver !== 'undefined') {
statusSelectObserver = new ResizeObserver((entries) => {
void closeHiddenStatusSelect(entries)
})
statusSelectObserver.observe(statusSelect.value)
}
// Storage can throw (blocked site data); the shortcuts then stay on.
try {
if (localStorage.getItem(SHORTCUTS_STORAGE_KEY) === 'off')
singleKeyShortcuts.value = false
} catch {
// Keep the default.
}
document.addEventListener('keydown', onShortcut)
})
watch(singleKeyShortcuts, (on) => {
try {
if (on) localStorage.removeItem(SHORTCUTS_STORAGE_KEY)
else localStorage.setItem(SHORTCUTS_STORAGE_KEY, 'off')
} catch {
// The setting still applies for this visit.
}
})
onBeforeUnmount(() => {
statusSelectObserver?.disconnect()
document.removeEventListener('keydown', onShortcut)
})
function exportInvoices(): void {
const rows =
table.value?.getPrePaginationRowModel().map((entry) => entry.row) ?? []
const url = URL.createObjectURL(
new Blob([invoiceCsv(rows)], { type: 'text/csv;charset=utf-8' }),
)
const link = document.createElement('a')
link.href = url
link.download = 'invoices.csv'
document.body.append(link)
link.click()
link.remove()
window.setTimeout(() => {
URL.revokeObjectURL(url)
}, 0)
toast({
title: 'Invoices exported',
description: `${String(rows.length)} ${rows.length === 1 ? 'invoice' : 'invoices'} in the CSV`,
})
}
</script>
<template>
<section
ref="workspace"
class="billing-workspace"
aria-labelledby="billing-workspace-title"
>
<header class="billing-workspace__heading">
<div>
<h2 id="billing-workspace-title">Invoices</h2>
<p>Review balances, collect payments, and manage refunds.</p>
</div>
<div class="billing-workspace__actions">
<div class="billing-shortcuts">
<label :for="`${prefix}-shortcuts`">Single-key shortcuts</label>
<GhostSwitch
:id="`${prefix}-shortcuts`"
v-model="singleKeyShortcuts"
size="sm"
/>
</div>
<GhostButton variant="outline" size="sm" @click="exportInvoices"
>Export CSV</GhostButton
>
</div>
</header>
<div
class="billing-metrics"
role="group"
:aria-labelledby="`${prefix}-metrics-period`"
>
<p :id="`${prefix}-metrics-period`" class="billing-metrics__period">
Invoices issued {{ metricsPeriod }}
</p>
<!--
Toggle buttons rather than a radio group: the status filter above is
already the single-choice control, and each metric is a shortcut into
it that can also be switched off again.
-->
<div class="billing-metrics__list">
<button
v-for="metric in metrics"
:key="metric.status"
type="button"
class="billing-metrics__item"
:aria-pressed="status === metric.status"
@click="toggleMetric(metric.status)"
>
<!--
The name comes from the visible text, so speech input can say what
is on screen. Each line is a block, which browsers separate with a
space; the hidden word joins the count: "Past due $6,600.00 across
2 invoices".
-->
<span class="billing-metrics__label">{{ metric.label }}</span>
<span class="billing-amount billing-metrics__amount">{{
metric.amount
}}</span>
<span class="billing-metrics__count"
><span class="billing-visually-hidden">across </span
>{{ metric.count }}</span
>
</button>
</div>
<p class="billing-visually-hidden" role="status">
{{ metricAnnouncement }}
</p>
</div>
<!--
The plain variant, because the workspace is already the app's one frame
and the table runs flush to its edges. On desktop the frame has a fixed
height and the rows scroll inside it, so the column headings stick.
-->
<GhostDataTable
ref="invoiceTable"
v-model:global-filter="search"
v-model:sorting="sorting"
v-model:pagination="pagination"
v-model:selected-row-ids="selectedRowIds"
:data="visibleInvoices"
:columns="columns"
:get-row-id="(row) => row.id"
enable-row-selection
size="sm"
sticky-header
aria-label="Invoices"
>
<GhostDataTablePreset
:columns="columns"
:layout-slots="['toolbarStart', 'toolbarEnd', 'bulkActions', 'footer']"
contain-horizontal
scroll-label="Invoices table scroll region"
:empty-title="emptyTitle"
>
<template #toolbarStart>
<GhostSegmentedControl
v-model="status"
class="billing-status-filter"
:deselectable="false"
aria-label="Invoice status"
>
<GhostSegmentedControlItem
v-for="value in invoiceStatuses"
:key="value"
:value="value"
>
{{ value }}
</GhostSegmentedControlItem>
</GhostSegmentedControl>
<!--
On a phone four equal segments are too narrow for "Past due", so
the stylesheet swaps the segmented control for this select. Only
one of the two is displayed at a time, and both write the same
status, so the hidden one is out of the tab order and the
accessibility tree.
-->
<div ref="statusSelect" class="billing-status-select">
<span :id="`${prefix}-status-label`">Status</span>
<GhostSelect v-model="status" v-model:open="statusSelectOpen">
<GhostSelectTrigger :aria-labelledby="`${prefix}-status-label`">
<GhostSelectValue />
</GhostSelectTrigger>
<GhostSelectContent placement="bottom-start" :offset="6">
<GhostSelectOption
v-for="value in invoiceStatuses"
:key="value"
:value="value"
>{{ value }}</GhostSelectOption
>
</GhostSelectContent>
</GhostSelect>
</div>
</template>
<template #search="{ value, setValue, disabled }">
<label class="billing-search">
<span>Search invoices</span>
<GhostInput
ref="searchField"
type="search"
:model-value="value"
:disabled="disabled"
placeholder="Invoice or customer"
:aria-keyshortcuts="singleKeyShortcuts ? 'S' : undefined"
@update:model-value="setValue"
@keydown.enter="focusFirstResult"
/>
</label>
</template>
<template #toolbarEnd>
<GhostDatePicker
v-slot="picker"
v-model="dateRange"
selection-mode="range"
:today="calendarToday"
>
<div class="billing-date-filter">
<span :id="`${prefix}-issued-label`">Issued</span>
<!--
The name comes from the visible label and range text, so speech
input can say what is on screen. The trigger still reports
aria-haspopup="dialog" and its expanded state, and the calendar
anchors to it because the picker has no text inputs.
-->
<GhostDatePickerTrigger
class="billing-date-button"
:aria-labelledby="`${prefix}-issued-label ${prefix}-issued-value`"
>
<svg
aria-hidden="true"
focusable="false"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
stroke-width="1.5"
>
<rect x="2" y="3" width="12" height="11" rx="1.5" />
<path d="M2 6.5h12M5.5 1.5v3M10.5 1.5v3" />
</svg>
<span :id="`${prefix}-issued-value`">{{ dateRangeText }}</span>
</GhostDatePickerTrigger>
</div>
<GhostDatePickerContent>
<GhostDatePickerCalendar />
<!--
Without text fields, the calendar is the only place to remove
the range. Closing returns focus to the date button.
-->
<div v-if="picker.value" class="billing-date-actions">
<GhostButton
variant="ghost"
tone="neutral"
size="sm"
@click="clearDates(picker)"
>Clear dates</GhostButton
>
</div>
</GhostDatePickerContent>
</GhostDatePicker>
</template>
<template #bulkActions="{ selectedCount, clearSelection }">
<span>{{ selectionSummary(selectedCount) }}</span>
<GhostButton
variant="outline"
size="sm"
:aria-disabled="!payableIds.length"
:aria-keyshortcuts="singleKeyShortcuts ? 'M' : undefined"
@click="markPaid"
>Mark paid</GhostButton
>
<GhostButton variant="ghost" size="sm" @click="clearSelection"
>Clear selection</GhostButton
>
</template>
<template #id="{ row, value }">
<GhostButton
class="billing-invoice-id"
variant="ghost"
size="sm"
aria-haspopup="dialog"
@click="inspect(row, $event.currentTarget)"
>
{{ value }}
</GhostButton>
</template>
<template #issued="{ value }">
<time :datetime="value" class="billing-issued">{{
formatIssued(value)
}}</time>
</template>
<template #status="{ value }">
<GhostBadge
:tone="tone(value)"
variant="soft"
size="sm"
class="billing-status"
>{{ value }}</GhostBadge
>
</template>
<template #amountCents="{ value }">
<span class="billing-amount billing-cell-amount">{{
formatAmount(value)
}}</span>
</template>
<template #actions="{ row }">
<!--
Each item fits the row's status. Inspect stays on the invoice ID,
so the menu holds only actions. The trigger is an icon button; its
name carries the invoice ID so each row's button is distinct.
-->
<GhostDropdownMenu>
<GhostDropdownMenuTrigger
:id="`${prefix}-menu-${row.id}`"
:as="GhostButton"
variant="ghost"
tone="neutral"
size="sm"
icon-only
:aria-label="`Actions for ${row.id}`"
>
<svg
data-part="icon"
aria-hidden="true"
focusable="false"
viewBox="0 0 16 16"
fill="currentColor"
>
<circle cx="3" cy="8" r="1.5" />
<circle cx="8" cy="8" r="1.5" />
<circle cx="13" cy="8" r="1.5" />
</svg>
</GhostDropdownMenuTrigger>
<GhostDropdownMenuContent placement="bottom-end">
<GhostDropdownMenuItem
v-if="row.status === 'Past due'"
@select="runRowAction(row.id, () => remindInvoice(row.id))"
>Send reminder</GhostDropdownMenuItem
>
<GhostDropdownMenuItem
v-if="row.status === 'Draft' || row.status === 'Past due'"
@select="runRowAction(row.id, () => markInvoicePaid(row.id))"
>Mark paid</GhostDropdownMenuItem
>
<GhostDropdownMenuItem
@select="runRowAction(row.id, () => downloadSample(row.id))"
>Download PDF</GhostDropdownMenuItem
>
<!-- Refund confirms in a dialog before anything changes. -->
<GhostDropdownMenuItem
v-if="row.status === 'Paid'"
aria-haspopup="dialog"
@select="openRefund(row.id)"
>Refund…</GhostDropdownMenuItem
>
</GhostDropdownMenuContent>
</GhostDropdownMenu>
</template>
<template
#footer="{ pagination: page, pageCount, rowCount, setPageIndex }"
>
<span class="billing-footer-count" role="status"
>{{ rowCount }} {{ rowCount === 1 ? 'invoice' : 'invoices' }}
<span v-if="sortDescription"> · {{ sortDescription }}</span></span
>
<GhostButton
v-if="rowCount === 0"
variant="outline"
size="sm"
@click="clearFilters"
>Clear filters</GhostButton
>
<GhostPagination
v-else
:model-value="page.pageIndex"
:page-count="pageCount"
size="sm"
aria-label="Invoice pages"
@update:model-value="setPageIndex"
/>
</template>
</GhostDataTablePreset>
</GhostDataTable>
<GhostDrawer :open="inspectorOpen" @update:open="setInspectorOpen">
<InvoiceInspector
v-if="inspected"
:invoice="inspected"
@refund="refundInvoice"
@mark-paid="markInvoicePaid"
@remind="remindInvoice"
/>
</GhostDrawer>
<!-- The row menu's refund, the same confirmation the drawer uses. -->
<GhostDialog :open="refundOpen" @update:open="setRefundOpen">
<InvoiceRefundDialogContent
v-if="refunding"
v-model:reason="refundReason"
:invoice="refunding"
:return-focus="refundReturnFocus"
@confirm="confirmRefund"
/>
</GhostDialog>
</section>
</template>vue
<script setup lang="ts">
import { computed, nextTick, ref, useId } from 'vue'
import {
GhostAvatar,
GhostBadge,
GhostButton,
GhostDialog,
GhostDialogTrigger,
GhostDrawerClose,
GhostDrawerContent,
GhostDrawerDescription,
GhostDrawerOverlay,
GhostDrawerTitle,
GhostTable,
} from '@ghostvue/themes'
import {
GhostTableBody,
GhostTableCell,
GhostTableFoot,
GhostTableHead,
GhostTableHeaderCell,
GhostTableRow,
} from '@ghostvue/vue'
import {
formatAmount,
formatIssued,
formatLineQuantity,
formatTaxRate,
invoiceActivity,
invoiceStatusTones,
paymentMethodLabel,
paymentMethodNote,
type Invoice,
} from './invoices'
import InvoiceRefundDialogContent from './InvoiceRefundDialogContent.vue'
const props = defineProps<{ invoice: Invoice }>()
const emit = defineEmits<{
refund: [invoiceId: string, reason: string]
markPaid: [invoiceId: string]
remind: [invoiceId: string]
}>()
const refundOpen = ref(false)
const reason = ref('')
const ids = {
close: useId(),
customer: useId(),
lines: useId(),
payment: useId(),
activity: useId(),
}
const activity = computed(() => invoiceActivity(props.invoice))
/** The dates that matter for the current status, beside the issue date. */
const summary = computed(() => {
const { invoice } = props
const issued = formatIssued(invoice.issued)
if (invoice.refund)
return `Issued ${issued} · Refunded ${formatIssued(invoice.refund.on)}`
if (invoice.paidOn)
return invoice.sentOn
? `Issued ${issued} · Paid ${formatIssued(invoice.paidOn)}`
: `Dated ${issued} · Paid ${formatIssued(invoice.paidOn)}`
if (!invoice.sentOn) return `Draft dated ${issued} · Not sent yet`
return `Issued ${issued} · Due ${formatIssued(invoice.due)}`
})
function closeButton(): HTMLElement | null {
return document.getElementById(ids.close)
}
/**
* The footer's primary action belongs to the status, so an action that
* changes the status removes the button that has focus. Close is the one
* control every status keeps, so focus moves there.
*/
async function focusCloseAfterStatusChange(): Promise<void> {
await nextTick()
closeButton()?.focus()
}
function markPaid(): void {
if (props.invoice.status !== 'Draft') return
emit('markPaid', props.invoice.id)
void focusCloseAfterStatusChange()
}
function remind(): void {
if (props.invoice.status !== 'Past due') return
emit('remind', props.invoice.id)
}
function setRefundOpen(open: boolean): void {
if (open && props.invoice.status !== 'Paid') return
if (open) reason.value = ''
refundOpen.value = open
}
/**
* The refund dialog normally returns focus to Issue refund. A confirmed
* refund removes that button, so focus goes to Close instead.
*/
function refundReturnFocus(): HTMLElement | null {
return props.invoice.status === 'Paid' ? null : closeButton()
}
function refund(): void {
const text = reason.value.trim()
if (props.invoice.status !== 'Paid' || !text) return
emit('refund', props.invoice.id, text)
refundOpen.value = false
}
</script>
<template>
<GhostDrawerOverlay />
<GhostDrawerContent class="billing-inspector">
<header class="billing-inspector__header">
<div class="billing-inspector__heading">
<GhostDrawerTitle class="billing-inspector__title"
>Invoice {{ invoice.id }}</GhostDrawerTitle
>
<GhostBadge :tone="invoiceStatusTones[invoice.status]" variant="soft">
{{ invoice.status }}
</GhostBadge>
</div>
<GhostDrawerDescription>{{ summary }}</GhostDrawerDescription>
<p class="billing-inspector__total billing-amount">
{{ formatAmount(invoice.amountCents) }}
</p>
</header>
<section class="billing-inspector__section" :aria-labelledby="ids.customer">
<h3 :id="ids.customer">Billed to</h3>
<div class="billing-inspector__customer">
<GhostAvatar :name="invoice.customer" aria-hidden="true" />
<!--
Plain text rather than a hover card or mail link: the drawer has room
for everything, and keeping the body free of controls leaves Close as
the first stop when the drawer opens.
-->
<div class="billing-inspector__customer-text">
<p class="billing-inspector__customer-name">{{ invoice.customer }}</p>
<p>Billing contact: {{ invoice.contact }}</p>
<p>{{ invoice.email }}</p>
</div>
</div>
</section>
<section class="billing-inspector__section" :aria-labelledby="ids.lines">
<h3 :id="ids.lines">Line items</h3>
<GhostTable
class="billing-inspector__lines"
aria-label="Invoice line items"
>
<GhostTableHead>
<GhostTableRow>
<GhostTableHeaderCell scope="col">Description</GhostTableHeaderCell>
<GhostTableHeaderCell scope="col" class="billing-amount"
>Amount</GhostTableHeaderCell
>
</GhostTableRow>
</GhostTableHead>
<GhostTableBody>
<GhostTableRow v-for="line in invoice.lines" :key="line.description">
<GhostTableCell>
<span class="billing-line__description">{{
line.description
}}</span>
<span
v-if="formatLineQuantity(line)"
class="billing-line__quantity"
>{{ formatLineQuantity(line) }}</span
>
</GhostTableCell>
<GhostTableCell class="billing-amount">{{
formatAmount(line.amountCents)
}}</GhostTableCell>
</GhostTableRow>
</GhostTableBody>
<GhostTableFoot>
<GhostTableRow>
<GhostTableHeaderCell scope="row">Subtotal</GhostTableHeaderCell>
<GhostTableCell class="billing-amount">{{
formatAmount(invoice.subtotalCents)
}}</GhostTableCell>
</GhostTableRow>
<GhostTableRow>
<GhostTableHeaderCell scope="row">{{
formatTaxRate(invoice.taxBasisPoints)
}}</GhostTableHeaderCell>
<GhostTableCell class="billing-amount">{{
formatAmount(invoice.taxCents)
}}</GhostTableCell>
</GhostTableRow>
<GhostTableRow class="billing-line__total">
<GhostTableHeaderCell scope="row">Total</GhostTableHeaderCell>
<GhostTableCell class="billing-amount">{{
formatAmount(invoice.amountCents)
}}</GhostTableCell>
</GhostTableRow>
</GhostTableFoot>
</GhostTable>
</section>
<section class="billing-inspector__section" :aria-labelledby="ids.payment">
<h3 :id="ids.payment">Payment method</h3>
<p>{{ paymentMethodLabel(invoice.payment) }}</p>
<p class="billing-inspector__note">
{{ paymentMethodNote(invoice.payment) }}
</p>
</section>
<section class="billing-inspector__section" :aria-labelledby="ids.activity">
<h3 :id="ids.activity">Activity</h3>
<ol class="billing-activity">
<li
v-for="(event, index) in activity"
:key="`${event.on}-${String(index)}`"
>
<span>{{ event.label }}</span>
<time :datetime="event.on">{{ formatIssued(event.on) }}</time>
</li>
</ol>
</section>
<!--
Close comes first in the footer, and nothing above it takes focus, so it
is where focus lands when the drawer opens. The primary action follows
it and depends on the status; a Refunded invoice has none.
-->
<footer class="billing-inspector__footer">
<GhostDrawerClose
:id="ids.close"
:as="GhostButton"
variant="outline"
tone="neutral"
>Close</GhostDrawerClose
>
<GhostButton v-if="invoice.status === 'Past due'" @click="remind"
>Send reminder</GhostButton
>
<GhostButton v-else-if="invoice.status === 'Draft'" @click="markPaid"
>Mark paid</GhostButton
>
<!--
The dialog stays mounted for every status so it can finish closing,
and hand focus back, after a refund removes its trigger.
-->
<GhostDialog :open="refundOpen" @update:open="setRefundOpen">
<GhostDialogTrigger
v-if="invoice.status === 'Paid'"
:as="GhostButton"
tone="danger"
>
Issue refund
</GhostDialogTrigger>
<InvoiceRefundDialogContent
v-model:reason="reason"
:invoice="invoice"
:return-focus="refundReturnFocus"
@confirm="refund"
/>
</GhostDialog>
</footer>
</GhostDrawerContent>
</template>ts
export type InvoiceStatus = 'Paid' | 'Past due' | 'Draft' | 'Refunded'
/** One billed line. Seat and environment lines carry a quantity and unit price. */
export interface InvoiceLine {
description: string
quantity?: { count: number; unit: string; unitCents: number }
amountCents: number
}
/**
* How a customer pays. Card customers are charged when the invoice is sent,
* bank debits settle a few days later, and bank transfers arrive whenever the
* customer's finance team pays them.
*/
export type PaymentMethod =
| { kind: 'card'; brand: string; last4: string }
| { kind: 'debit'; last4: string }
| { kind: 'transfer' }
export interface InvoiceRefund {
on: string
reason: string
}
export interface Invoice {
id: string
customer: string
email: string
/** The person at the customer who receives and pays invoices. */
contact: string
issued: string
/** Two weeks after `issued`. An unpaid invoice is past due after this day. */
due: string
amountCents: number
status: InvoiceStatus
lines: readonly InvoiceLine[]
subtotalCents: number
/** Sales tax rate in basis points; 0 means the customer is tax exempt. */
taxBasisPoints: number
taxCents: number
payment: PaymentMethod
/** Unset while the invoice is a Draft. */
sentOn?: string
viewedOn?: string
paidOn?: string
/** True when someone recorded the payment by hand in this demo. */
markedPaid?: boolean
reminders: readonly string[]
refund?: InvoiceRefund
}
/**
* Badge tone for each status. Every status gets its own tone so the column
* stays readable in Mono, where accent is close to neutral grey. A refund is
* money going back out, so it takes the cautionary tone rather than reading as
* settled.
*/
export const invoiceStatusTones = {
Paid: 'success',
'Past due': 'danger',
Draft: 'neutral',
Refunded: 'warning',
} as const satisfies Record<InvoiceStatus, string>
export const invoiceStatuses = ['All', 'Paid', 'Past due', 'Draft'] as const
/**
* The showcase calendar treats this day as today. Nothing in the data happens
* after it, and actions taken in the demo are dated on it.
*/
export const showcaseToday = '2026-11-18'
/** Adds whole days to an ISO date, in UTC so no time zone shifts the day. */
export function addDays(iso: string, days: number): string {
const date = new Date(`${iso}T00:00:00Z`)
date.setUTCDate(date.getUTCDate() + days)
return date.toISOString().slice(0, 10)
}
function earliest(a: string, b: string): string {
return a < b ? a : b
}
interface LineSpec {
description: string
count: number
unit: string
unitCents: number
}
interface CustomerProfile {
name: string
email: string
contact: string
payment: PaymentMethod
/** Days from sending to payment. Cards are charged the same day. */
paysAfterDays: number
taxBasisPoints: number
/** Fixed lines, billed the same every month. */
fixed: readonly LineSpec[]
/** The metered line, which takes whatever the subtotal leaves over. */
usage: string
}
const plan = {
starter: (count: number): LineSpec => ({
description: 'Starter plan',
count,
unit: 'seats',
unitCents: 4500,
}),
team: (count: number): LineSpec => ({
description: 'Team plan',
count,
unit: 'seats',
unitCents: 9000,
}),
growth: (count: number): LineSpec => ({
description: 'Growth plan',
count,
unit: 'seats',
unitCents: 11000,
}),
enterprise: (): LineSpec => ({
description: 'Enterprise plan',
count: 1,
unit: 'workspace',
unitCents: 900000,
}),
}
const addOn = {
support: {
description: 'Priority support',
count: 1,
unit: 'month',
unitCents: 25000,
},
retention: {
description: 'Log retention, 90 days',
count: 1,
unit: 'month',
unitCents: 12000,
},
previews: (count: number): LineSpec => ({
description: 'Preview environments',
count,
unit: 'environments',
unitCents: 4000,
}),
region: (name: string, unitCents: number): LineSpec => ({
description: `Dedicated region, ${name}`,
count: 1,
unit: 'month',
unitCents,
}),
auditExport: {
description: 'Audit log export',
count: 1,
unit: 'month',
unitCents: 40000,
},
premiumSupport: {
description: 'Premium support',
count: 1,
unit: 'month',
unitCents: 150000,
},
} as const
/**
* Customers by key, with each billing contact. The first ten come from the
* demo world (docs/contributing/demo-world.md); the last four widen the range
* of name lengths so the Customer column shows very short and very long names.
* Each customer has a plan, a payment method and a tax rate that stay the same
* every month, so the inspector reads like one account's history.
*/
const customers = {
northstar: {
name: 'Northstar Studio',
email: 'billing@northstar.example',
contact: 'Maya Okafor',
payment: { kind: 'card', brand: 'Visa', last4: '4242' },
paysAfterDays: 0,
taxBasisPoints: 825,
fixed: [plan.team(18), addOn.support],
usage: 'Build minutes',
},
fieldwork: {
name: 'Fieldwork Labs',
email: 'billing@fieldwork.example',
contact: 'Daniel Reyes',
payment: { kind: 'transfer' },
paysAfterDays: 8,
taxBasisPoints: 0,
fixed: [plan.growth(25), addOn.previews(10)],
usage: 'API requests',
},
canopy: {
name: 'Canopy Digital',
email: 'accounts@canopy.example',
contact: 'Priya Natarajan',
payment: { kind: 'card', brand: 'Mastercard', last4: '5100' },
paysAfterDays: 0,
taxBasisPoints: 600,
fixed: [plan.team(12)],
usage: 'Bandwidth',
},
harbor: {
name: 'Harbor & Co.',
email: 'billing@harbor.example',
contact: 'Tom Whitfield',
payment: { kind: 'transfer' },
paysAfterDays: 11,
taxBasisPoints: 0,
fixed: [plan.team(9)],
usage: 'Build minutes',
},
summit: {
name: 'Summit Supply',
email: 'accounts@summit.example',
contact: 'Elena Petrova',
payment: { kind: 'debit', last4: '6021' },
paysAfterDays: 3,
taxBasisPoints: 725,
fixed: [plan.growth(14), addOn.support],
usage: 'API requests',
},
lumen: {
name: 'Lumen Works',
email: 'accounts@lumen.example',
contact: 'Sam Lindqvist',
payment: { kind: 'card', brand: 'Amex', last4: '1005' },
paysAfterDays: 0,
taxBasisPoints: 0,
fixed: [plan.starter(8)],
usage: 'API requests',
},
juniper: {
name: 'Juniper Systems',
email: 'billing@juniper.example',
contact: 'Grace Liu',
payment: { kind: 'debit', last4: '3318' },
paysAfterDays: 3,
taxBasisPoints: 850,
fixed: [
plan.growth(22),
addOn.support,
addOn.previews(15),
addOn.retention,
],
usage: 'Build minutes',
},
meridian: {
name: 'Meridian Design',
email: 'accounts@meridian.example',
contact: 'Omar Haddad',
payment: { kind: 'transfer' },
paysAfterDays: 9,
taxBasisPoints: 0,
fixed: [plan.team(16), addOn.previews(5)],
usage: 'Bandwidth',
},
arcade: {
name: 'Arcade Creative',
email: 'billing@arcade.example',
contact: 'Jules Moreau',
payment: { kind: 'transfer' },
paysAfterDays: 6,
taxBasisPoints: 600,
fixed: [plan.team(6)],
usage: 'Bandwidth',
},
atlas: {
name: 'Atlas Research',
email: 'accounts@atlas.example',
contact: 'Hannah Becker',
payment: { kind: 'transfer' },
paysAfterDays: 10,
taxBasisPoints: 0,
fixed: [plan.growth(18), addOn.retention],
usage: 'API requests',
},
brightwater: {
name: 'Brightwater Analytics Cooperative',
email: 'billing@brightwater.example',
contact: 'Kwame Mensah',
payment: { kind: 'transfer' },
paysAfterDays: 12,
taxBasisPoints: 0,
fixed: [
plan.enterprise(),
addOn.region('eu-west', 250000),
addOn.premiumSupport,
addOn.auditExport,
],
usage: 'Bandwidth',
},
saltmarsh: {
name: 'Saltmarsh Field Instruments International',
email: 'accounts@saltmarsh.example',
contact: 'Isabel Ortega',
payment: { kind: 'debit', last4: '7742' },
paysAfterDays: 3,
taxBasisPoints: 0,
fixed: [plan.enterprise(), addOn.region('ap-southeast', 180000)],
usage: 'Bandwidth',
},
fenlark: {
name: 'Fenlark',
email: 'billing@fenlark.example',
contact: 'Ari Cohen',
payment: { kind: 'card', brand: 'Visa', last4: '0077' },
paysAfterDays: 0,
taxBasisPoints: 825,
fixed: [plan.starter(6), addOn.retention],
usage: 'Build minutes',
},
oriel: {
name: 'Oriel',
email: 'accounts@oriel.example',
contact: 'Noor Rahman',
payment: { kind: 'card', brand: 'Mastercard', last4: '8890' },
paysAfterDays: 0,
taxBasisPoints: 0,
fixed: [plan.starter(5)],
usage: 'API requests',
},
} as const satisfies Record<string, CustomerProfile>
type CustomerKey = keyof typeof customers
/** Why each seeded refund was given, shown in the inspector's activity. */
const refundReasons: Readonly<Record<string, string>> = {
'INV-1030': 'Billed twice for the October region fee',
'INV-1024': 'Seats removed before the billing date',
'INV-1022': 'Usage spike from a misconfigured client',
'INV-1004': 'Downgraded to fewer seats mid-cycle',
}
/**
* Four monthly billing cycles, August to November 2026, newest first. Nothing
* is issued after {@link showcaseToday}. Each customer is billed on the same
* day each month, and ids count up with the issue date. Past due invoices are
* unpaid two weeks after they were issued; Drafts are this month's bills that
* have not been sent.
*/
const invoiceRows: readonly (readonly [
id: string,
customer: CustomerKey,
issued: string,
amountCents: number,
status: InvoiceStatus,
])[] = [
['INV-1050', 'northstar', '2026-11-18', 248000, 'Paid'],
['INV-1049', 'lumen', '2026-11-17', 126000, 'Draft'],
['INV-1048', 'brightwater', '2026-11-16', 1864000, 'Draft'],
['INV-1047', 'fieldwork', '2026-11-15', 372500, 'Draft'],
['INV-1046', 'canopy', '2026-11-14', 156000, 'Paid'],
['INV-1045', 'harbor', '2026-11-12', 98000, 'Draft'],
['INV-1044', 'saltmarsh', '2026-11-11', 1207500, 'Paid'],
['INV-1043', 'summit', '2026-11-10', 214000, 'Draft'],
['INV-1042', 'oriel', '2026-11-09', 31900, 'Paid'],
['INV-1041', 'juniper', '2026-11-08', 423000, 'Paid'],
['INV-1040', 'fenlark', '2026-11-06', 64000, 'Paid'],
['INV-1039', 'meridian', '2026-11-05', 189500, 'Paid'],
['INV-1038', 'arcade', '2026-11-03', 74000, 'Past due'],
['INV-1037', 'atlas', '2026-11-01', 268000, 'Past due'],
['INV-1036', 'northstar', '2026-10-18', 245500, 'Paid'],
['INV-1035', 'lumen', '2026-10-17', 119500, 'Paid'],
['INV-1034', 'brightwater', '2026-10-16', 1920000, 'Past due'],
['INV-1033', 'fieldwork', '2026-10-15', 380000, 'Past due'],
['INV-1032', 'canopy', '2026-10-14', 153000, 'Paid'],
['INV-1031', 'harbor', '2026-10-12', 103000, 'Past due'],
['INV-1030', 'saltmarsh', '2026-10-11', 1195500, 'Refunded'],
['INV-1029', 'summit', '2026-10-10', 216000, 'Paid'],
['INV-1028', 'juniper', '2026-10-08', 410500, 'Paid'],
['INV-1027', 'fenlark', '2026-10-06', 61000, 'Paid'],
['INV-1026', 'meridian', '2026-10-05', 197000, 'Past due'],
['INV-1025', 'arcade', '2026-10-03', 74000, 'Paid'],
['INV-1024', 'atlas', '2026-10-01', 257500, 'Refunded'],
['INV-1023', 'northstar', '2026-09-18', 240500, 'Paid'],
['INV-1022', 'lumen', '2026-09-17', 131000, 'Refunded'],
['INV-1021', 'brightwater', '2026-09-16', 1882500, 'Paid'],
['INV-1020', 'fieldwork', '2026-09-15', 372500, 'Paid'],
['INV-1019', 'canopy', '2026-09-14', 150000, 'Paid'],
['INV-1018', 'harbor', '2026-09-12', 101000, 'Past due'],
['INV-1017', 'saltmarsh', '2026-09-11', 1171500, 'Paid'],
['INV-1016', 'summit', '2026-09-10', 212000, 'Paid'],
['INV-1015', 'juniper', '2026-09-08', 402000, 'Paid'],
['INV-1014', 'meridian', '2026-09-05', 193500, 'Paid'],
['INV-1013', 'arcade', '2026-09-03', 72500, 'Paid'],
['INV-1012', 'atlas', '2026-09-01', 281500, 'Paid'],
['INV-1011', 'northstar', '2026-08-18', 235500, 'Paid'],
['INV-1010', 'lumen', '2026-08-17', 128500, 'Paid'],
['INV-1009', 'brightwater', '2026-08-16', 1845500, 'Paid'],
['INV-1008', 'fieldwork', '2026-08-15', 365000, 'Paid'],
['INV-1007', 'canopy', '2026-08-14', 164000, 'Paid'],
['INV-1006', 'harbor', '2026-08-12', 99000, 'Paid'],
['INV-1005', 'summit', '2026-08-10', 207500, 'Paid'],
['INV-1004', 'juniper', '2026-08-08', 440000, 'Refunded'],
['INV-1003', 'meridian', '2026-08-05', 189500, 'Paid'],
['INV-1002', 'arcade', '2026-08-03', 71000, 'Paid'],
['INV-1001', 'atlas', '2026-08-01', 276000, 'Paid'],
]
function taxOn(subtotalCents: number, basisPoints: number): number {
return Math.round((subtotalCents * basisPoints) / 10000)
}
/**
* The pre-tax subtotal whose tax, rounded to the cent, brings it to `total`.
* Rounding skips a few totals at each rate, so the data test checks that
* every row has one.
*/
function subtotalFor(totalCents: number, basisPoints: number): number {
const estimate = Math.round((totalCents * 10000) / (10000 + basisPoints))
for (const offset of [0, -1, 1, -2, 2]) {
const subtotal = estimate + offset
if (subtotal + taxOn(subtotal, basisPoints) === totalCents) return subtotal
}
return estimate
}
/**
* Builds one invoice from its row and the customer's profile. The total is
* fixed by the row, so tax is worked back out of it, the fixed lines come
* from the plan, and metered usage takes the rest of the subtotal.
*/
function buildInvoice([
id,
key,
issued,
amountCents,
status,
]: (typeof invoiceRows)[number]): Invoice {
const profile: CustomerProfile = customers[key]
const subtotalCents = subtotalFor(amountCents, profile.taxBasisPoints)
const fixed: InvoiceLine[] = profile.fixed.map(
({ description, count, unit, unitCents }) => ({
description,
quantity: { count, unit, unitCents },
amountCents: count * unitCents,
}),
)
const fixedCents = fixed.reduce((sum, line) => sum + line.amountCents, 0)
const due = addDays(issued, 14)
const invoice: Invoice = {
id,
customer: profile.name,
email: profile.email,
contact: profile.contact,
issued,
due,
amountCents,
status,
lines: [
...fixed,
{ description: profile.usage, amountCents: subtotalCents - fixedCents },
],
subtotalCents,
taxBasisPoints: profile.taxBasisPoints,
taxCents: amountCents - subtotalCents,
payment: profile.payment,
reminders:
status === 'Past due'
? [3, 17]
.map((days) => addDays(due, days))
.filter((day) => day <= showcaseToday)
: [],
}
if (status === 'Draft') return invoice
invoice.sentOn = issued
const settled = status === 'Paid' || status === 'Refunded'
if (settled)
invoice.paidOn = earliest(
addDays(issued, profile.paysAfterDays),
showcaseToday,
)
// Card payments are taken when the invoice is sent, so nobody needs to
// open those invoices to pay them.
if (profile.payment.kind !== 'card')
invoice.viewedOn = earliest(
addDays(issued, 1),
invoice.paidOn ?? showcaseToday,
)
if (status === 'Refunded' && invoice.paidOn)
invoice.refund = {
on: earliest(addDays(invoice.paidOn, 6), showcaseToday),
reason: refundReasons[id] ?? 'Requested by the customer',
}
return invoice
}
export const initialInvoices: readonly Invoice[] = invoiceRows.map(buildInvoice)
/** Records a payment taken outside the app, dated today in the demo. */
export function withPayment(invoice: Invoice): Invoice {
return {
...invoice,
status: 'Paid',
paidOn: showcaseToday,
markedPaid: true,
}
}
export function withRefund(invoice: Invoice, reason: string): Invoice {
return {
...invoice,
status: 'Refunded',
refund: { on: showcaseToday, reason },
}
}
export function withReminder(invoice: Invoice): Invoice {
return { ...invoice, reminders: [...invoice.reminders, showcaseToday] }
}
export function paymentMethodLabel(payment: PaymentMethod): string {
switch (payment.kind) {
case 'card':
return `${payment.brand} ending in ${payment.last4}`
case 'debit':
return `Bank debit, account ending in ${payment.last4}`
case 'transfer':
return 'Bank transfer'
}
}
export function paymentMethodNote(payment: PaymentMethod): string {
switch (payment.kind) {
case 'card':
return 'Charged automatically when the invoice is sent.'
case 'debit':
return 'Debited a few days after the invoice is sent.'
case 'transfer':
return 'The customer pays by transfer within 14 days.'
}
}
export interface InvoiceActivity {
on: string
label: string
}
/**
* The invoice's history, oldest first, worked out from its dates. Events on
* the same day keep the order they happen in.
*/
export function invoiceActivity(invoice: Invoice): InvoiceActivity[] {
const events: InvoiceActivity[] = [
{
on: invoice.issued,
label: invoice.sentOn ? 'Invoice created' : 'Draft created',
},
]
if (invoice.sentOn)
events.push({ on: invoice.sentOn, label: `Sent to ${invoice.email}` })
if (invoice.viewedOn)
events.push({ on: invoice.viewedOn, label: `Viewed by ${invoice.contact}` })
// An invoice that was sent became past due on its due date unless it was
// paid first, even if it has been paid since.
if (
invoice.sentOn &&
invoice.due <= showcaseToday &&
(invoice.paidOn === undefined || invoice.paidOn > invoice.due)
)
events.push({ on: invoice.due, label: 'Payment past due' })
for (const day of invoice.reminders)
events.push({ on: day, label: 'Payment reminder sent' })
if (invoice.paidOn)
events.push({ on: invoice.paidOn, label: paidLabel(invoice) })
if (invoice.refund)
events.push({
on: invoice.refund.on,
label: `Refunded: ${invoice.refund.reason}`,
})
// Array sort is stable, so same-day events keep the order pushed above.
return events.sort((a, b) => (a.on < b.on ? -1 : a.on > b.on ? 1 : 0))
}
function paidLabel(invoice: Invoice): string {
if (invoice.markedPaid) return 'Marked paid'
switch (invoice.payment.kind) {
case 'card':
return `Charged to ${paymentMethodLabel(invoice.payment)}`
case 'debit':
return `Debited from account ending in ${invoice.payment.last4}`
case 'transfer':
return 'Bank transfer received'
}
}
export function formatLineQuantity(line: InvoiceLine): string | undefined {
if (!line.quantity) return undefined
const { count, unit, unitCents } = line.quantity
return count === 1
? `${formatAmount(unitCents)} per ${unit}`
: `${String(count)} ${unit} × ${formatAmount(unitCents)}`
}
export function formatTaxRate(basisPoints: number): string {
return basisPoints === 0
? 'Tax exempt'
: `Tax (${String(basisPoints / 100)}%)`
}
const currency = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})
const date = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
timeZone: 'UTC',
})
export function formatAmount(cents: number): string {
return currency.format(cents / 100)
}
export function formatIssued(issued: string): string {
return date.format(new Date(`${issued}T00:00:00Z`))
}
const day = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
timeZone: 'UTC',
})
/**
* Short text for an inclusive range of ISO dates, such as "Nov 1 to Nov 30".
* Years are shown only when the two ends fall in different years, and a
* one-day range shows that day once.
*/
export function formatIssuedRange(start: string, end: string): string {
const format = start.slice(0, 4) === end.slice(0, 4) ? day : date
const at = (iso: string) => format.format(new Date(`${iso}T00:00:00Z`))
return start === end ? at(start) : `${at(start)} to ${at(end)}`
}
export function invoiceCsv(invoices: readonly Invoice[]): string {
const header = 'Invoice,Customer,Issued,Status,Amount (USD)'
const rows = invoices.map((invoice) =>
[
invoice.id,
invoice.customer,
invoice.issued,
invoice.status,
(invoice.amountCents / 100).toFixed(2),
]
.map((value) => `"${value.replaceAll('"', '""')}"`)
.join(','),
)
return [header, ...rows].join('\r\n')
}css
.billing-gallery {
inline-size: min(100% - 2rem, 72rem);
margin-inline: auto;
padding-block: clamp(1.75rem, 5vw, 4rem) 4rem;
color: var(--ghost-surface-fg);
}
.billing-gallery__header {
display: grid;
gap: var(--ghost-space-gap-sm);
margin-block-end: var(--ghost-space-inset-lg);
}
.billing-gallery__header p {
color: var(--ghost-text-muted);
}
.billing-workspace__heading p {
color: var(--ghost-text-muted);
font-size: var(--ghost-type-size-sm);
max-inline-size: 52ch;
}
/*
* The app's one frame. Its sections carry their own inset and are divided by
* hairlines, so nothing inside draws a second card, and the table runs flush
* to the frame's edges.
*/
.billing-workspace {
--billing-frame-inline: var(--ghost-space-inset-md);
display: grid;
min-inline-size: 0;
background: var(--ghost-elevation-1-bg);
border: 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);
container: billing-workspace / inline-size;
}
/*
* Desktop only: the frame keeps a fixed height, like an app window, and the
* invoice rows scroll inside it between the toolbar and the footer. A short
* window shrinks the frame so its footer stays reachable. Phones keep the
* natural height, so the page is the only vertical scroller there.
*/
@media (min-width: 48rem) {
.billing-workspace {
display: flex;
flex-direction: column;
block-size: clamp(28rem, 100dvh - 6rem, 45rem);
}
.billing-workspace > * {
flex: none;
}
.billing-workspace > .ghost-data-table {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-block-size: 0;
}
.billing-workspace .ghost-data-table-preset > * {
flex: none;
}
.billing-workspace .ghost-data-table-preset > .ghost-table-scroll-container {
flex: 1 1 auto;
min-block-size: 0;
overflow: auto;
}
}
.billing-workspace__heading {
padding: var(--ghost-space-inset-sm) var(--billing-frame-inline);
border-block-end: var(--ghost-border-hairline-width) solid
var(--ghost-border-default);
}
.billing-workspace__heading,
.billing-refund__actions {
display: flex;
align-items: center;
flex-wrap: wrap;
justify-content: space-between;
gap: var(--ghost-space-gap-sm);
}
.billing-workspace__actions,
.billing-shortcuts {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--ghost-space-gap-sm);
}
.billing-workspace__actions {
column-gap: var(--ghost-space-gap-md);
}
.billing-shortcuts label {
color: var(--ghost-text-muted);
font-size: 0.875rem;
}
.billing-workspace__heading h2 {
font-size: 1.25rem;
font-weight: 650;
}
.billing-metrics {
position: relative;
display: grid;
gap: var(--ghost-space-gap-xs);
padding: var(--ghost-space-inset-sm) var(--billing-frame-inline) 0;
border-block-end: var(--ghost-border-hairline-width) solid
var(--ghost-border-default);
}
/*
* A plain summary row: hairlines between the figures and no fill, so the
* metrics read as live numbers rather than disabled boxes.
*/
.billing-metrics__list {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
}
/*
* Each metric is still a toggle button. The pressed one gains a bar along its
* bottom edge, a shape cue that does not depend on hue alone; at rest the bar
* is transparent, so pressing does not shift the row.
*/
.billing-metrics__item {
position: relative;
display: grid;
gap: 0;
min-inline-size: 0;
padding: var(--ghost-space-inset-xs) clamp(0.5rem, 2vw, 1rem)
var(--ghost-space-inset-sm);
border: 0;
border-block-end: 3px solid transparent;
border-radius: var(--ghost-radius-sm) var(--ghost-radius-sm) 0 0;
background: transparent;
color: inherit;
font: inherit;
text-align: start;
cursor: pointer;
}
.billing-metrics__item:first-child {
padding-inline-start: 0;
}
.billing-metrics__item + .billing-metrics__item {
border-inline-start: var(--ghost-border-hairline-width) solid
var(--ghost-border-muted);
}
.billing-metrics__item:hover {
background: var(--ghost-surface-subtle-bg);
}
.billing-metrics__item[aria-pressed='true'] {
border-block-end-color: var(--ghost-action-primary-bg);
}
/* Inset, so the ring stays inside the frame and off the next metric. */
.billing-metrics__item:focus-visible {
outline: var(--ghost-focus-ring-width) solid var(--ghost-focus-ring-color);
outline-offset: calc(-1 * var(--ghost-focus-ring-width));
}
@media (forced-colors: active) {
.billing-metrics__item {
border-block-end-color: Canvas;
}
.billing-metrics__item[aria-pressed='true'] {
border-block-end-color: Highlight;
}
}
.billing-metrics__period,
.billing-metrics__label,
.billing-metrics__count,
.billing-search,
.billing-status-select,
.billing-date-filter,
.billing-footer-count {
color: var(--ghost-text-muted);
font-size: var(--ghost-type-size-sm);
}
.billing-metrics__period {
margin: 0;
}
.billing-metrics__amount {
font-size: clamp(0.9rem, 2.5vw, 1.5rem);
font-weight: 650;
}
/*
* Read by assistive technology but never shown: metric separators and the
* metric filter announcement.
*/
.billing-visually-hidden {
position: absolute;
inline-size: 1px;
block-size: 1px;
margin: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.billing-search,
.billing-status-select,
.billing-date-filter {
display: grid;
gap: var(--ghost-space-gap-xs);
}
.billing-search {
max-inline-size: 100%;
/* The input's intrinsic width must not hold the column open past the part. */
grid-template-columns: minmax(0, 1fr);
}
/* The frame's hairlines divide the table's parts, so they need no gap. */
.billing-workspace .ghost-data-table {
gap: 0;
}
.billing-workspace .ghost-data-table-preset > [data-part='header'],
.billing-workspace .ghost-data-table-preset > [data-part='bulk-actions'],
.billing-workspace .ghost-data-table-preset > [data-part='footer'] {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--ghost-space-gap-sm);
padding: var(--ghost-space-inset-sm) var(--billing-frame-inline);
}
.billing-workspace .ghost-data-table-preset > [data-part='bulk-actions'] {
border-block-end: var(--ghost-border-hairline-width) solid
var(--ghost-border-default);
}
.billing-workspace .ghost-data-table-preset > [data-part='header'] {
align-items: end;
border-block-end: var(--ghost-border-hairline-width) solid
var(--ghost-border-default);
}
.billing-workspace
.ghost-data-table-preset
> [data-part='header']
> [data-part='search'] {
flex: 1 1 12rem;
/* Lets the field shrink to its basis so the date button stays on the row. */
min-inline-size: 0;
}
/*
* The search field already grows into the free space, so the date filter
* starts where it wraps instead of being pushed to the far edge of a new row.
*/
.billing-workspace
.ghost-data-table-preset
> [data-part='header']
> [data-part='toolbar-end'] {
margin-inline-start: 0;
}
.billing-status-filter {
white-space: nowrap;
}
/* Shown instead of the segmented control on a phone; see the query below. */
.billing-status-select {
display: none;
}
@media (max-width: 22rem) {
.billing-workspace .ghost-data-table-preset > [data-part='header'] > * {
min-inline-size: 0;
max-inline-size: 100%;
}
}
.billing-workspace .ghost-data-table-preset button[data-part='sort-button'] {
cursor: pointer;
}
.billing-workspace
.ghost-data-table-preset
button[data-part='sort-button']:is(:hover, :focus-visible) {
text-decoration: underline;
text-underline-offset: 0.2em;
}
/*
* The themed trigger is a square icon button. Here it also shows the range,
* so it takes the padding and type of a medium control, which keeps it the
* same height as the search field beside it.
*/
.billing-date-button {
gap: var(--ghost-space-gap-xs);
justify-content: flex-start;
padding-block: 0;
padding-inline: var(--ghost-control-size-md-padding-inline);
font-family: var(--ghost-type-family-sans);
font-feature-settings: var(--ghost-type-feature-default);
font-size: var(--ghost-control-size-md-font);
line-height: var(--ghost-type-line-normal);
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.billing-date-button > svg {
flex: none;
color: var(--ghost-text-muted);
}
.billing-date-actions {
display: flex;
justify-content: flex-end;
padding-block-start: var(--ghost-space-gap-xs);
}
.billing-workspace .ghost-data-table-preset > [data-part='footer'] {
justify-content: space-between;
border-block-start: var(--ghost-border-hairline-width) solid
var(--ghost-border-default);
}
.billing-amount,
.billing-issued,
.billing-invoice-id {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.billing-cell-amount {
display: block;
text-align: end;
}
/*
* Amount is the column before Actions. The preset puts no per-column hook on
* its header cells, so the heading is matched by position and ends on the same
* edge as the amounts below it.
*/
.billing-workspace
.ghost-data-table-preset
.ghost-table-head
.ghost-table-header-cell:nth-last-child(2) {
text-align: end;
}
.billing-workspace
.ghost-data-table-preset
.ghost-table-head
.ghost-table-header-cell:nth-last-child(2)
> button[data-part='sort-button'] {
justify-content: flex-end;
}
/*
* A ghost button has no visible edge at rest. Pulling it out by its own
* padding and border puts its label on the column's text edge, under the
* heading.
*/
.billing-workspace .ghost-table-cell .ghost-button[data-variant='ghost'] {
margin-inline-start: calc(
-1 *
(
var(--ghost-control-size-sm-padding-inline) +
var(--ghost-border-hairline-width)
)
);
}
.billing-status {
white-space: nowrap;
}
/*
* The theme's side panel is 42ch wide. The invoice view widens it so a line
* description and its amount share a row, and phones still keep the inset
* the theme leaves beside the panel. A flex column lets the footer sit at the
* bottom edge when the invoice is short and stick there when it scrolls.
*/
.billing-inspector {
display: flex;
flex-direction: column;
inline-size: min(calc(100dvw - 2 * var(--ghost-space-inset-lg)), 34rem);
padding-block-end: 0;
}
.billing-inspector > * {
flex: none;
}
.billing-inspector p {
margin: 0;
}
.billing-inspector__header,
.billing-inspector__section {
display: grid;
gap: var(--ghost-space-gap-xs);
min-inline-size: 0;
}
.billing-inspector__heading {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--ghost-space-gap-sm);
}
/*
* The title sits in a row with its badge, so the theme's rule for a title
* that is a direct child of the drawer does not reach it.
*/
.billing-inspector__title {
margin: 0;
font-size: var(--ghost-type-size-lg);
font-weight: var(--ghost-type-weight-semibold);
line-height: var(--ghost-type-line-snug);
}
.billing-inspector__total {
font-size: 1.75rem;
font-weight: 650;
letter-spacing: -0.02em;
line-height: var(--ghost-type-line-tight);
}
.billing-inspector__section h3 {
font-size: var(--ghost-type-size-sm);
font-weight: var(--ghost-type-weight-semibold);
line-height: var(--ghost-type-line-snug);
}
.billing-inspector__customer {
display: flex;
align-items: flex-start;
gap: var(--ghost-space-gap-sm);
}
.billing-inspector__customer-text {
display: grid;
min-inline-size: 0;
overflow-wrap: anywhere;
}
.billing-inspector__customer-name {
font-weight: var(--ghost-type-weight-semibold);
}
.billing-inspector__customer-text > p + p,
.billing-inspector__note,
.billing-line__quantity {
color: var(--ghost-text-muted);
font-size: var(--ghost-type-size-sm);
}
/* Like the title, the description is not a direct child of the drawer. */
.billing-inspector__header > [data-part='description'] {
color: var(--ghost-text-muted);
font-size: var(--ghost-type-size-sm);
}
/*
* Descriptions start on the cell edge, so the table needs no outer inset, and
* tighter rows keep a five-line invoice and its totals in one screen.
*/
.billing-inspector__lines :is(.ghost-table-header-cell, .ghost-table-cell) {
padding-block: var(--ghost-space-inset-xs);
padding-inline: 0;
}
.billing-inspector__lines .billing-amount {
padding-inline-start: var(--ghost-space-inset-md);
text-align: end;
}
.billing-line__description,
.billing-line__quantity {
display: block;
}
/* Subtotal and tax read as plain rows; only the total keeps the weight. */
.billing-inspector__lines
.ghost-table-foot
.ghost-table-row:not(.billing-line__total)
> * {
font-weight: var(--ghost-type-weight-regular);
}
.billing-inspector__lines
.ghost-table-foot
.ghost-table-row:not(:first-child)
> * {
border-block-start: 0;
}
.billing-line__total > * {
font-size: var(--ghost-type-size-md);
}
/*
* A dot per event on a hairline. The dots are rings drawn with a border, so
* they keep showing in forced colors, where backgrounds are dropped.
*/
.billing-activity {
display: grid;
margin: 0;
padding: 0;
list-style: none;
font-size: var(--ghost-type-size-sm);
}
.billing-activity li {
position: relative;
display: flex;
justify-content: space-between;
gap: var(--ghost-space-gap-sm);
padding-block: var(--ghost-space-inset-xs);
padding-inline-start: 1.25rem;
}
.billing-activity li::before {
content: '';
position: absolute;
inset-block-start: calc(var(--ghost-space-inset-xs) + 0.5lh - 0.3125rem);
inset-inline-start: 0.125rem;
box-sizing: border-box;
inline-size: 0.625rem;
block-size: 0.625rem;
border: 2px solid var(--ghost-border-strong);
border-radius: 50%;
background: var(--ghost-elevation-4-bg);
}
.billing-activity li:last-child::before {
border-color: var(--ghost-text-muted);
background: var(--ghost-text-muted);
}
.billing-activity li:not(:last-child)::after {
content: '';
position: absolute;
/* From under this dot to the top of the next one. */
inset-block: calc(var(--ghost-space-inset-xs) + 0.5lh + 0.3125rem)
calc(-1 * (var(--ghost-space-inset-xs) + 0.5lh - 0.3125rem));
inset-inline-start: calc(0.4375rem - var(--ghost-border-hairline-width) / 2);
border-inline-start: var(--ghost-border-hairline-width) solid
var(--ghost-border-default);
}
.billing-activity span {
min-inline-size: 0;
overflow-wrap: anywhere;
}
.billing-activity time {
flex: none;
color: var(--ghost-text-muted);
font-variant-numeric: tabular-nums;
}
/*
* The footer spans the panel's full width and sticks to its bottom edge, so
* Close and the status action stay in reach on a long invoice.
*/
.billing-inspector__footer {
position: sticky;
inset-block-end: 0;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: var(--ghost-space-gap-sm);
margin-block-start: auto;
margin-inline: calc(-1 * var(--ghost-space-inset-lg));
padding: var(--ghost-space-inset-md) var(--ghost-space-inset-lg);
border-block-start: var(--ghost-border-hairline-width) solid
var(--ghost-border-default);
background: var(--ghost-elevation-4-bg);
}
.billing-refund form {
display: grid;
gap: var(--ghost-space-gap-sm);
}
.billing-refund__actions {
justify-content: end;
}
.billing-gallery__source {
margin-block-start: var(--ghost-space-inset-lg);
min-inline-size: 0;
}
.billing-gallery__source summary {
display: list-item;
cursor: pointer;
font-weight: 650;
}
/* The workspace already pads the page, so both source surfaces stay inside it. */
.billing-gallery__source .vp-code-group .tabs,
.billing-gallery__source .vp-code-group div[class*='language-'] {
margin-inline: 0;
}
.billing-gallery__source .vp-code-group input:focus-visible + label {
outline: var(--ghost-focus-ring-width) solid var(--ghost-focus-ring-color);
outline-offset: calc(-1 * var(--ghost-focus-ring-width));
}
/*
* Phone layout. Below the width the six columns need (about 39rem of
* workspace, roughly a 690px viewport), the table would scroll sideways and
* hide Status, Amount and Actions. Each invoice row becomes a two-line card
* instead: customer, amount and the actions menu on top; invoice ID, issued
* date and status below; the checkbox beside both lines.
*
* The rows stay table rows in the DOM, so the table keeps its row and cell
* semantics and DOM order, which is also the Tab order (checkbox, ID, actions).
* Columns are matched by position because the preset puts no per-column hook
* on its cells. The `:has` guard leaves any full-width row, such as the empty
* state, in table layout.
*/
@container billing-workspace (max-width: 39rem) {
.billing-status-filter {
display: none;
}
.billing-status-select {
display: grid;
}
/* Wide enough for "Past due" beside the chevron at any status. */
.billing-status-select .ghost-select-trigger {
min-inline-size: 8rem;
}
.billing-workspace .ghost-data-table-preset .ghost-table {
--billing-row-select: 2rem;
display: block;
}
.billing-workspace
.ghost-data-table-preset
:is(.ghost-table-head, .ghost-table-body) {
display: block;
}
/*
* The sort buttons stay available as one wrapping row that starts on the
* same edge as the row text, with Select all over the row checkboxes. The
* Actions heading has no control, so it is hidden visually but still names
* the column.
*/
.billing-workspace
.ghost-data-table-preset
.ghost-table-head
> .ghost-table-row {
position: relative;
display: flex;
flex-wrap: wrap;
align-items: center;
padding-inline-start: var(--billing-row-select);
border-block-end: var(--ghost-border-hairline-width) solid
var(--ghost-border-default);
/*
* The sticky header fills each heading cell; wrapped cells leave gaps, so
* the row takes the same fill behind them.
*/
background: var(--ghost-surface-muted-bg);
}
.billing-workspace
.ghost-data-table-preset
.ghost-table-head
> .ghost-table-row
> .ghost-table-header-cell {
display: block;
border-block-end: 0;
padding: var(--ghost-space-inset-2xs) var(--ghost-space-inset-xs);
}
.billing-workspace
.ghost-data-table-preset
.ghost-table-head
> .ghost-table-row
> .ghost-table-header-cell:first-child {
position: absolute;
inset-block: 0;
inset-inline-start: 0;
display: flex;
align-items: center;
justify-content: center;
inline-size: var(--billing-row-select);
padding: 0;
}
.billing-workspace
.ghost-data-table-preset
.ghost-table-head
> .ghost-table-row
> .ghost-table-header-cell:last-child {
position: absolute;
inline-size: 1px;
block-size: 1px;
padding: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
/*
* The checkbox cell is pinned over the row's start padding beside both
* lines, and the other cells leave no gaps, so the theme's per-cell hover
* and selection backgrounds still cover the whole row. The row draws the
* divider the cells drew in table layout.
*/
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7)) {
position: relative;
display: flex;
flex-wrap: wrap;
align-items: center;
padding-inline-start: var(--billing-row-select);
border-block-end: var(--ghost-border-hairline-width) solid
var(--ghost-border-muted);
}
/* Ends the first line after the actions menu. */
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))::after {
content: '';
order: 4;
flex-basis: 100%;
}
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
> .ghost-table-cell {
display: block;
align-self: stretch;
border-block-end: 0;
padding-inline: var(--ghost-space-inset-xs);
}
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
> .ghost-table-cell:first-child {
position: absolute;
inset-block: 0;
inset-inline-start: 0;
display: flex;
align-items: center;
justify-content: center;
inline-size: var(--billing-row-select);
padding: 0;
}
/*
* The actions menu ends the first line, so the second line can run the
* full width under it. The icon button is not on a column text edge.
*/
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
> .ghost-table-cell:last-child {
order: 3;
display: flex;
align-items: center;
padding: 0;
}
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
> .ghost-table-cell:last-child
.ghost-button {
margin-inline-start: 0;
}
/* Customer, amount and the actions menu on the first line. */
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
> .ghost-table-cell:nth-child(3) {
order: 1;
flex: 1 1 0;
min-inline-size: 0;
padding-block-end: 0;
font-weight: var(--ghost-type-weight-medium);
overflow-wrap: anywhere;
}
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
> .ghost-table-cell:nth-child(6) {
order: 2;
padding-block-end: 0;
font-weight: var(--ghost-type-weight-medium);
}
/*
* ID, issued date and status on the second line, in the smaller type of a
* secondary line so all three fit beside each other at 360px.
*/
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
> .ghost-table-cell:is(:nth-child(2), :nth-child(4), :nth-child(5)) {
order: 5;
display: flex;
align-items: center;
padding-block-start: 0;
padding-inline: 0 var(--ghost-space-inset-2xs);
font-size: var(--ghost-type-size-xs);
}
/* The ID label still starts on the customer's text edge. */
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
> .ghost-table-cell:nth-child(2) {
padding-inline-start: var(--ghost-space-inset-xs);
}
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
.billing-invoice-id {
/* Smaller type only; the button keeps its touch target height. */
font-size: inherit;
}
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
> .ghost-table-cell:nth-child(4) {
color: var(--ghost-text-muted);
}
/* Status takes the rest of the second line, so no row background gaps. */
.billing-workspace
.ghost-data-table-preset
.ghost-table-body
> .ghost-table-row:has(> :nth-child(7))
> .ghost-table-cell:nth-child(5) {
flex-grow: 1;
}
}