Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .changeset/data-table-column-align.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
"@tailor-platform/app-shell": minor
---

Add `align: "left" | "right"` to `DataTable` `Column`. When set to `"right"`, the header label, body cell, and loading-skeleton bar are right-aligned together — eliminating the inline `<span className="text-right">` wrappers callers were adding inside `render` for numeric columns (Amount, Score, Total).

`align` is **auto-defaulted to `"right"` for `type: "number"` and `type: "money"`** so the common case Just Works without extra config. Other types default to `"left"`. Pass `"left"` explicitly to opt a numeric column out.

```tsx
// Auto-aligned right — no `align` needed
column({
label: "Total",
type: "money",
accessor: (row) => row.total,
typeOptions: { currency: "USD" },
});

// Explicit alignment for a custom-render column
column({
label: "Amount",
align: "right",
render: (row) => formatMoney(row.amount),
});
```
33 changes: 17 additions & 16 deletions docs/components/data-table.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,15 +217,16 @@ A column definition passed to `useDataTable`. `Column<TRow>` is a discriminated

### Shared fields

| Property | Type | Description |
| ---------- | -------------------------- | ------------------------------------------------------------------------------------------ |
| `label` | `string` | Column header text. Omit for icon-only columns. |
| `render` | `(row: TRow) => ReactNode` | Renders the cell content. Optional — overrides the built-in `type` renderer when set. |
| `id` | `string` | Stable identifier for column visibility and React key. Falls back to `label` when omitted. |
| `width` | `number` | Fixed column width in pixels. Optional. |
| Property | Type | Description |
| ---------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `label` | `string` | Column header text. Omit for icon-only columns. |
| `render` | `(row: TRow) => ReactNode` | Renders the cell content. Optional — overrides the built-in `type` renderer when set. |
| `id` | `string` | Stable identifier for column visibility and React key. Falls back to `label` when omitted. |
| `width` | `number` | Fixed column width in pixels. Optional. |
| `align` | `"left" \| "right"` | Horizontal alignment. Defaults to `"right"` for `type: "number"` and `type: "money"`; `"left"` otherwise. Pass `"left"` to opt a numeric column out. |
| `accessor` | _(narrowed per `type`)_ | Extracts the raw value. The return type is narrowed per `type` branch — returning an array or a plain object is a compile error on a typed column. Untyped columns (`type` omitted) retain `unknown`. `null` and `undefined` are always allowed. |
| `sort` | `SortConfig` | Sort configuration. When set, the column header becomes clickable (Asc → Desc → off). |
| `filter` | `FilterConfig` | Filter configuration. When set, the column appears as an option in `DataTable.Filters`. |
| `sort` | `SortConfig` | Sort configuration. When set, the column header becomes clickable (Asc → Desc → off). |
| `filter` | `FilterConfig` | Filter configuration. When set, the column appears as an option in `DataTable.Filters`. |

### `type`-specific fields

Expand All @@ -252,14 +253,14 @@ column({
});
```

| `type` | Accessor return type | Value handling | Options interface |
| -------- | ----------------------------------------------------------------- | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `text` | `string \| number \| boolean \| bigint \| null \| undefined` | `String(value)` — falls back to `—` when nullish. | _(no options)_ |
| `number` | `number \| null \| undefined` | `Intl.NumberFormat`. `—` for nullish / NaN. | `NumberCellOptions`: `minDecimals`, `maxDecimals`, `locale` |
| `money` | `number \| null \| undefined` | `Intl.NumberFormat` currency. `—` for nullish. | `MoneyCellOptions<TRow>`: `currency` (string or `(row) => string`), `maxDecimals`, `locale` |
| `date` | `Date \| string \| number \| null \| undefined` | `Intl.DateTimeFormat`. Accepts `Date`/ISO/epoch. | `DateCellOptions`: `dateFormat` (`"short"` \| `"long"` \| `"datetime"`), `locale` |
| `badge` | `string \| number \| boolean \| null \| undefined` | `<Badge>` keyed off the stringified value. | `BadgeCellOptions`: `badgeVariantMap`, `badgeLabelMap`, `defaultBadgeVariant` (defaults to `"neutral"`) |
| `link` | `string \| number \| boolean \| null \| undefined` | app-shell `<Link>` to `typeOptions.href(row)`. | `LinkCellOptions<TRow>`: `href: (row) => string \| null \| undefined` (returning nullish renders plain text; **required**) |
| `type` | Accessor return type | Value handling | Options interface |
| -------- | ------------------------------------------------------------ | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `text` | `string \| number \| boolean \| bigint \| null \| undefined` | `String(value)` — falls back to `—` when nullish. | _(no options)_ |
| `number` | `number \| null \| undefined` | `Intl.NumberFormat`. `—` for nullish / NaN. | `NumberCellOptions`: `minDecimals`, `maxDecimals`, `locale` |
| `money` | `number \| null \| undefined` | `Intl.NumberFormat` currency. `—` for nullish. | `MoneyCellOptions<TRow>`: `currency` (string or `(row) => string`), `maxDecimals`, `locale` |
| `date` | `Date \| string \| number \| null \| undefined` | `Intl.DateTimeFormat`. Accepts `Date`/ISO/epoch. | `DateCellOptions`: `dateFormat` (`"short"` \| `"long"` \| `"datetime"`), `locale` |
| `badge` | `string \| number \| boolean \| null \| undefined` | `<Badge>` keyed off the stringified value. | `BadgeCellOptions`: `badgeVariantMap`, `badgeLabelMap`, `defaultBadgeVariant` (defaults to `"neutral"`) |
| `link` | `string \| number \| boolean \| null \| undefined` | app-shell `<Link>` to `typeOptions.href(row)`. | `LinkCellOptions<TRow>`: `href: (row) => string \| null \| undefined` (returning nullish renders plain text; **required**) |

Empty values (`null`, `undefined`, `""`) render a muted `—` placeholder for every type. Use `render` for custom empty-state handling.

Expand Down
135 changes: 135 additions & 0 deletions packages/core/src/components/data-table/data-table.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,141 @@ describe("DataTable", () => {
});
});

// -------------------------------------------------------------------------
// Column alignment
// -------------------------------------------------------------------------
describe("column alignment", () => {
const alignedColumns: Column<TestRow>[] = [
{ label: "Name", render: (row) => row.name },
{ label: "Amount", render: (row) => row.status, align: "right" },
];

it("applies text-right to the header cell when align=right", () => {
const { container } = render(<TestDataTable columns={alignedColumns} />, { wrapper });
const heads = container.querySelectorAll('[data-slot="data-table-header"] th');
expect(heads[0]?.className).not.toContain("text-right");
expect(heads[1]?.className).toContain("text-right");
});

it("applies text-right to body cells when align=right", () => {
const { container } = render(<TestDataTable columns={alignedColumns} />, { wrapper });
const firstRow = container.querySelector('[data-slot="data-table-row"]');
const cells = firstRow?.querySelectorAll('[data-slot="data-table-cell"]') ?? [];
expect(cells[0]?.className).not.toContain("text-right");
expect(cells[1]?.className).toContain("text-right");
});

it("right-aligns the skeleton bar so it doesn't shift on load", () => {
const { container } = render(
<TestDataTable columns={alignedColumns} data={undefined} loading />,
{ wrapper },
);
const firstSkeleton = container.querySelector('[data-datatable-state="loading"]');
const skeletonCells = firstSkeleton?.querySelectorAll("td") ?? [];
const rightCellBar = skeletonCells[1]?.querySelector("div");
expect(rightCellBar?.className).toContain("ml-auto");
const leftCellBar = skeletonCells[0]?.querySelector("div");
expect(leftCellBar?.className).not.toContain("ml-auto");
});

it("defaults to left alignment when align is unset", () => {
const { container } = render(<TestDataTable />, { wrapper });
const heads = container.querySelectorAll('[data-slot="data-table-header"] th');
heads.forEach((th) => {
expect(th.className).not.toContain("text-right");
});
});

it("auto-aligns number columns to the right", () => {
type NumRow = { id: string; count: number };
const numRows: NumRow[] = [{ id: "1", count: 42 }];
const cols: Column<NumRow>[] = [{ label: "Count", type: "number", accessor: (r) => r.count }];
function Harness() {
const table = useDataTable<NumRow>({ columns: cols, data: { rows: numRows } });
return (
<DataTable.Root value={table}>
<DataTable.Table />
</DataTable.Root>
);
}
const { container } = render(<Harness />, { wrapper });
const head = container.querySelector('[data-slot="data-table-header"] th');
const cell = container.querySelector('[data-slot="data-table-cell"]');
expect(head?.className).toContain("text-right");
expect(cell?.className).toContain("text-right");
});

it("auto-aligns money columns to the right", () => {
type MoneyRow = { id: string; total: number };
const moneyRows: MoneyRow[] = [{ id: "1", total: 100 }];
const cols: Column<MoneyRow>[] = [
{
label: "Total",
type: "money",
accessor: (r) => r.total,
typeOptions: { currency: "USD" },
},
];
function Harness() {
const table = useDataTable<MoneyRow>({ columns: cols, data: { rows: moneyRows } });
return (
<DataTable.Root value={table}>
<DataTable.Table />
</DataTable.Root>
);
}
const { container } = render(<Harness />, { wrapper });
const head = container.querySelector('[data-slot="data-table-header"] th');
const cell = container.querySelector('[data-slot="data-table-cell"]');
expect(head?.className).toContain("text-right");
expect(cell?.className).toContain("text-right");
});

it("does not auto-align non-numeric typed columns (text, date, badge, link)", () => {
type Row = { id: string; v: string };
const rows: Row[] = [{ id: "1", v: "x" }];
const cols: Column<Row>[] = [
{ label: "Text", type: "text", accessor: (r) => r.v },
{ label: "Date", type: "date", accessor: (r) => r.v },
{ label: "Badge", type: "badge", accessor: (r) => r.v },
{ label: "Link", type: "link", accessor: (r) => r.v, typeOptions: { href: () => "/x" } },
];
function Harness() {
const table = useDataTable<Row>({ columns: cols, data: { rows } });
return (
<MemoryRouter>
<DataTable.Root value={table}>
<DataTable.Table />
</DataTable.Root>
</MemoryRouter>
);
}
const { container } = render(<Harness />, { wrapper });
container.querySelectorAll('[data-slot="data-table-header"] th').forEach((th) => {
expect(th.className).not.toContain("text-right");
});
});

it("explicit align=left overrides the numeric-type auto-default", () => {
type NumRow = { id: string; count: number };
const numRows: NumRow[] = [{ id: "1", count: 42 }];
const cols: Column<NumRow>[] = [
{ label: "Count", type: "number", accessor: (r) => r.count, align: "left" },
];
function Harness() {
const table = useDataTable<NumRow>({ columns: cols, data: { rows: numRows } });
return (
<DataTable.Root value={table}>
<DataTable.Table />
</DataTable.Root>
);
}
const { container } = render(<Harness />, { wrapper });
const head = container.querySelector('[data-slot="data-table-header"] th');
expect(head?.className).not.toContain("text-right");
});
});

// -------------------------------------------------------------------------
// Row selection (DOM)
// -------------------------------------------------------------------------
Expand Down
28 changes: 25 additions & 3 deletions packages/core/src/components/data-table/data-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ export type { DataTablePaginationProps } from "./pagination";
// Fallback row count when no pageSize is configured (static / uncontrolled tables)
const DEFAULT_ROWS = 5;

// Resolve the effective horizontal alignment for a column. Numeric `type`
// values default to `"right"` so digits line up along their decimal place;
// everything else defaults to `"left"`. Explicit `col.align` always wins.
function resolveAlign<TRow extends Record<string, unknown>>(col: Column<TRow>): "left" | "right" {
if (col.align) return col.align;
if (col.type === "number" || col.type === "money") return "right";
return "left";
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels right!


// =============================================================================
// DataTableLoaderRows (internal)
// =============================================================================
Expand Down Expand Up @@ -59,7 +68,10 @@ function DataTableLoaderRows<TRow extends Record<string, unknown>>({
className="astw:h-13.25"
>
<div
className="astw:h-4 astw:rounded astw:bg-muted astw:animate-pulse"
className={cn(
"astw:h-4 astw:rounded astw:bg-muted astw:animate-pulse",
resolveAlign(col) === "right" && "astw:ml-auto",
)}
style={{ width: `${skeletonWidth}%` }}
/>
</Table.Cell>
Expand Down Expand Up @@ -252,14 +264,23 @@ function DataTableHeaders({ className }: { className?: string }) {
onSort(col.sort.field, nextDirection);
};

const align = resolveAlign(col);
return (
<Table.Head
key={key}
style={col.width ? { width: col.width } : undefined}
className={cn(isSortable && "astw:cursor-pointer astw:select-none")}
className={cn(
isSortable && "astw:cursor-pointer astw:select-none",
align === "right" && "astw:text-right",
)}
onClick={isSortable ? handleClick : undefined}
>
<span className="astw:inline-flex astw:items-center astw:gap-1">
<span
className={cn(
"astw:inline-flex astw:items-center astw:gap-1",
align === "right" && "astw:justify-end",
)}
>
{label}
{currentSort && <SortIndicator direction={currentSort.direction} />}
</span>
Expand Down Expand Up @@ -400,6 +421,7 @@ function DataTableBody({ className }: { className?: string }) {
key={key}
data-slot="data-table-cell"
style={col.width ? { width: col.width } : undefined}
className={cn(resolveAlign(col) === "right" && "astw:text-right")}
>
{content}
</Table.Cell>
Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/components/data-table/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ export interface ColumnBase<TRow extends Record<string, unknown>> {
id?: string;
/** Fixed column width in pixels. When omitted the column sizes naturally. */
width?: number;
/**
* Horizontal alignment for the header and body cell. When omitted, numeric
* `type` values (`"number"` and `"money"`) default to `"right"` so digits
* align along their decimal place; everything else defaults to `"left"`.
* Pass `"left"` explicitly to opt a numeric column out.
*/
align?: "left" | "right";
/**
* Sort configuration. When set, the column header becomes clickable and
* cycles through `Asc → Desc → undefined`.
Expand Down
Loading