# TableLoader

> A table skeleton loader: rows of marks shaped like your columns that gather into each cell's real text when the data arrives.

TableLoader is Dotquilt's table skeleton loader: it holds the place of a table. Each cell shows a short bar of marks shaped like what the column holds, with a glow drifting across. When the data arrives, each cell's marks gather into the text in its place, then the rows wipe in as the marks leave.

## Usage

Describe the columns and set how many rows to show. The handoff reads your real table, so it needs nothing else.

**React**

```tsx title="InvoiceTable.tsx"
'use client';
import { LoadingRegion, TableLoader } from '@dotquilt/react';
import { useEffect, useState } from 'react';
import { type Invoice, invoiceColumns } from './data';

async function fetchInvoices(signal: AbortSignal): Promise<Invoice[]> {
  const response = await fetch('/api/invoices', { signal });
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
  return response.json();
}

export function InvoiceTable() {
  const [invoices, setInvoices] = useState<Invoice[] | null>(null);
  const [failed, setFailed] = useState(false);

  useEffect(() => {
    const request = new AbortController();
    fetchInvoices(request.signal)
      .then(setInvoices)
      .catch(() => {
        if (!request.signal.aborted) setFailed(true);
      });
    return () => request.abort();
  }, []);

  // The handoff reads the real table: each cell's marks become its text.
  const ready = failed || invoices !== null;

  return (
    <LoadingRegion
      aria-label="Invoices"
      state={ready ? 'ready' : 'pending'}
      timing={failed ? { duration: 0 } : undefined}
      placeholder={
        <TableLoader rows={4} rowHeight={40} columns={invoiceColumns} />
      }
    >
      {failed ? (
        <p role="alert">We couldn't load invoices. Try again later.</p>
      ) : (
        <table className="invoices">
          <thead>
            <tr>
              <th>Customer</th>
              <th>Amount</th>
              <th>Status</th>
              <th>Due</th>
            </tr>
          </thead>
          <tbody>
            {invoices?.map((invoice) => (
              <tr key={invoice.customer}>
                <td>{invoice.customer}</td>
                <td>{invoice.amount}</td>
                <td>{invoice.status}</td>
                <td>{invoice.due}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </LoadingRegion>
  );
}
```
```ts title="data.ts"
// Shared by the docs examples and the live previews, so both draw the same.
import type { Point } from 'dotquilt/chart';
import type { TableColumn } from 'dotquilt/table';

/** Monthly revenue, in thousands. */
export const revenue: readonly number[] = [32, 41, 38, 52, 47, 61, 58, 72];

/** Each value's place in a chart `width` × `height`, with headroom on top. */
export function linePoints(
  values: readonly number[],
  width: number,
  height: number,
): Point[] {
  const top = Math.max(...values) * 1.15;
  return values.map((value, i) => ({
    x: (i / Math.max(1, values.length - 1)) * width,
    y: height - (value / top) * height,
  }));
}

/** An SVG path through the same points. */
export function linePath(
  values: readonly number[],
  width: number,
  height: number,
): string {
  return linePoints(values, width, height)
    .map(({ x, y }, i) => `${i ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`)
    .join(' ');
}

export interface Invoice {
  customer: string;
  amount: string;
  status: string;
  due: string;
}

export const invoices: readonly Invoice[] = [
  { customer: 'Northwind', amount: '$4,200', status: 'Paid', due: 'Nov 2' },
  { customer: 'Acme Labs', amount: '$1,870', status: 'Open', due: 'Nov 14' },
  { customer: 'Globex', amount: '$9,640', status: 'Overdue', due: 'Oct 28' },
  { customer: 'Initech', amount: '$3,115', status: 'Paid', due: 'Nov 20' },
];

/** The placeholder's columns: what each column holds, and its share of the width. */
export const invoiceColumns: readonly TableColumn[] = [
  { kind: 'text', width: 2 },
  { kind: 'number' },
  { kind: 'badge' },
  { kind: 'date' },
];
```

**Native**

```html title="index.html"
<dotquilt-region id="invoices" state="pending" aria-label="Invoices">
  <dotquilt-table-loader
    slot="placeholder"
    rows="4"
    row-height="40"
  ></dotquilt-table-loader>
  <table class="invoices">
    <thead>
      <tr>
        <th>Customer</th>
        <th>Amount</th>
        <th>Status</th>
        <th>Due</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</dotquilt-region>
```
```ts title="invoices.ts"
import { type LoadingRegion, registerLoadingRegion } from 'dotquilt/region';
import { registerTableLoader, type TableLoader } from 'dotquilt/table';
import { type Invoice, invoiceColumns } from './data';

registerLoadingRegion();
registerTableLoader();

const region = document.getElementById('invoices') as LoadingRegion | null;
const table = region?.querySelector('dotquilt-table-loader') as TableLoader;
const body = region?.querySelector('tbody');
// What each column holds, and its share of the width.
table.columns = invoiceColumns;

export async function showInvoices(): Promise<void> {
  if (!region || !body) return;
  region.update({ state: 'pending', cycle: 'invoices' });
  try {
    const response = await fetch('/api/invoices');
    if (!response.ok) throw new Error(`Request failed: ${response.status}`);
    const invoices: Invoice[] = await response.json();
    body.replaceChildren(
      ...invoices.map((invoice) => {
        const row = document.createElement('tr');
        for (const value of [
          invoice.customer,
          invoice.amount,
          invoice.status,
          invoice.due,
        ])
          row.append(
            Object.assign(document.createElement('td'), { textContent: value }),
          );
        return row;
      }),
    );
    // The handoff reads the real table: each cell's marks become its text.
    region.update({ state: 'ready' });
  } catch {
    const message = document.createElement('td');
    message.colSpan = 4;
    message.textContent = "We couldn't load invoices. Try again later.";
    body.replaceChildren(document.createElement('tr'));
    body.rows[0]?.append(message);
    region.update({ state: 'ready', timing: { duration: 0 } });
  }
}

void showInvoices();
```
```ts title="data.ts"
// Shared by the docs examples and the live previews, so both draw the same.
import type { Point } from 'dotquilt/chart';
import type { TableColumn } from 'dotquilt/table';

/** Monthly revenue, in thousands. */
export const revenue: readonly number[] = [32, 41, 38, 52, 47, 61, 58, 72];

/** Each value's place in a chart `width` × `height`, with headroom on top. */
export function linePoints(
  values: readonly number[],
  width: number,
  height: number,
): Point[] {
  const top = Math.max(...values) * 1.15;
  return values.map((value, i) => ({
    x: (i / Math.max(1, values.length - 1)) * width,
    y: height - (value / top) * height,
  }));
}

/** An SVG path through the same points. */
export function linePath(
  values: readonly number[],
  width: number,
  height: number,
): string {
  return linePoints(values, width, height)
    .map(({ x, y }, i) => `${i ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`)
    .join(' ');
}

export interface Invoice {
  customer: string;
  amount: string;
  status: string;
  due: string;
}

export const invoices: readonly Invoice[] = [
  { customer: 'Northwind', amount: '$4,200', status: 'Paid', due: 'Nov 2' },
  { customer: 'Acme Labs', amount: '$1,870', status: 'Open', due: 'Nov 14' },
  { customer: 'Globex', amount: '$9,640', status: 'Overdue', due: 'Oct 28' },
  { customer: 'Initech', amount: '$3,115', status: 'Paid', due: 'Nov 20' },
];

/** The placeholder's columns: what each column holds, and its share of the width. */
export const invoiceColumns: readonly TableColumn[] = [
  { kind: 'text', width: 2 },
  { kind: 'number' },
  { kind: 'badge' },
  { kind: 'date' },
];
```

With a `targetProvider`, the table uses the `rows` handoff instead: each cell's marks form its characters, glyph by glyph, and the rows you pass as the region's **reveal targets** settle in one after another.

## Options

| Attribute | React | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `rows` | `rows` | number | `5` | How many rows to show, up to 100. |
| `row-height` | `rowHeight` | number | `32` | Row height in pixels. |
| | `columns` | `{ kind, width? }[]` | three text columns | What each column holds (`text`, `number`, `badge` or `date`) and its share of the width. Up to 20. |
| `mark` | `mark` | `dot` \| `square` \| `dash` | `dot` | Dashes suit table rows well. |
| `speed` | `speed` | number | `1` | How fast the glow moves. |
| `pointer-response` | `pointerResponse` | `none` \| `lift` | `none` | `lift` lights the marks around the pointer while the placeholder shows, on devices with a fine pointer. |
| `motion` | `motion` | `system` \| `paused` | `system` | `system` follows the visitor's reduced-motion setting; `paused` stills the field. |

## Animations

Import alternatives from `dotquilt/animations/table` and pass them as `animations`.

| Phase | Default | Also available |
| --- | --- | --- |
| Idle | `tableShimmer`: still bars under a drifting glow | `typeOn`: bars grow as if being typed |
| Handoff | the marks gather into each cell's real text, then the rows wipe in | `rows` (with a `targetProvider`): cells form their characters and rows settle in 80 ms apart |

| Animation | Options (default) |
| --- | --- |
| `tableShimmer`, `typeOn` | `cadenceMs` 250–1200 (600), `cellStyle`: `auto` (from the columns), `text`, `number`, `badge`, `date`, `badge-text` or `text-badge` |
| `rows` | `staggerMs` 0–120 (80), `settlePx` 0–8 (5) |
