# ChartLoader

> A chart loading skeleton for line, bar and scatter charts: a field of marks that glides onto your real data when it arrives.

ChartLoader is Dotquilt's chart loading skeleton: it holds the place of a line, bar or scatter chart. A faint field of marks carries a slow ridge and a drifting glow. When the data arrives, the marks glide onto your real line, turning teal, and then your chart draws in.

## Usage

Put a ChartLoader in a region's placeholder slot, sized like the chart it stands in for. Give it a **target provider**: a function that says where your real line will be, in the loader's own size. The marks glide onto it during the handoff.

**React**

```tsx title="RevenueChart.tsx"
'use client';
import { ChartLoader, LoadingRegion } from '@dotquilt/react';
import type { TargetProvider } from 'dotquilt/chart';
import { useEffect, useState } from 'react';
import { linePath, linePoints } from './data';

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

type Result =
  | { status: 'loading' }
  | { status: 'done'; series: number[] }
  | { status: 'failed' };

export function RevenueChart({ year }: { year: number }) {
  const [result, setResult] = useState<Result>({ status: 'loading' });

  useEffect(() => {
    const request = new AbortController();
    setResult({ status: 'loading' });
    fetchRevenue(year, request.signal)
      .then((series) => setResult({ status: 'done', series }))
      .catch(() => {
        if (!request.signal.aborted) setResult({ status: 'failed' });
      });
    return () => request.abort();
  }, [year]);

  // Where the real line will be, in the loader's own size: the marks glide
  // onto it before the chart draws in.
  const target: TargetProvider = ({ width, height }) =>
    result.status === 'done'
      ? {
          kind: 'line',
          points: linePoints(result.series, width, height),
          baseline: height,
        }
      : null;

  return (
    <LoadingRegion
      aria-label={`Revenue in ${year}`}
      state={result.status === 'loading' ? 'pending' : 'ready'}
      cycle={String(year)}
      timing={result.status === 'failed' ? { duration: 0 } : undefined}
      placeholder={
        <ChartLoader
          variant="line"
          targetProvider={target}
          style={{ height: 160 }}
        />
      }
    >
      {result.status === 'done' && (
        <svg
          viewBox="0 0 320 160"
          preserveAspectRatio="none"
          style={{ display: 'block', width: '100%', height: 160 }}
          role="img"
          aria-label={`Revenue in ${year}, by month`}
        >
          <path
            d={linePath(result.series, 320, 160)}
            fill="none"
            stroke="currentColor"
            strokeWidth={2}
            vectorEffect="non-scaling-stroke"
          />
        </svg>
      )}
      {result.status === 'failed' && (
        <p role="alert">We couldn't load revenue. Try again later.</p>
      )}
    </LoadingRegion>
  );
}

export function Report() {
  return <RevenueChart year={2026} />;
}
```
```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="revenue" state="pending" aria-label="Revenue in 2026">
  <dotquilt-chart-loader
    slot="placeholder"
    variant="line"
    style="height: 160px"
  ></dotquilt-chart-loader>
  <svg
    viewBox="0 0 320 160"
    preserveAspectRatio="none"
    style="display: block; width: 100%; height: 160px"
    role="img"
    aria-label="Revenue in 2026, by month"
  >
    <path
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      vector-effect="non-scaling-stroke"
    />
  </svg>
  <p class="chart-error" role="alert" hidden>
    We couldn't load revenue. Try again later.
  </p>
</dotquilt-region>
```
```ts title="revenue.ts"
import { type ChartLoader, registerChartLoader } from 'dotquilt/chart';
import { type LoadingRegion, registerLoadingRegion } from 'dotquilt/region';
import { linePath, linePoints } from './data';

registerLoadingRegion();
registerChartLoader();

const region = document.getElementById('revenue') as LoadingRegion | null;
const chart = region?.querySelector('dotquilt-chart-loader') as ChartLoader;
const line = region?.querySelector('path');

export async function showRevenue(year: number): Promise<void> {
  if (!region || !line) return;
  const cycle = String(year);
  region.update({ state: 'pending', cycle });
  try {
    const response = await fetch(`/api/revenue/${year}`);
    if (!response.ok) throw new Error(`Request failed: ${response.status}`);
    const series: number[] = await response.json();
    if (region.cycle !== cycle) return;
    line.setAttribute('d', linePath(series, 320, 160));
    // Where the real line will be, in the loader's own size: the marks glide
    // onto it before the chart draws in.
    chart.targetProvider = ({ width, height }) => ({
      kind: 'line',
      points: linePoints(series, width, height),
      baseline: height,
    });
    region.update({ state: 'ready' });
  } catch {
    if (region.cycle !== cycle) return;
    region.querySelector('.chart-error')?.removeAttribute('hidden');
    region.update({ state: 'ready', timing: { duration: 0 } });
  }
}

void showRevenue(2026);
```
```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' },
];
```

Without a target provider, or if it returns `null`, the chart fades in over the marks instead.

## Target geometry

The provider receives the loader's `width` and `height` and returns one of these, in the same pixels:

| `kind` | Fields | Use |
| --- | --- | --- |
| `line` | `points`, `baseline` | line and area charts |
| `bar` | `bars` (rects), `baseline` | bar charts |
| `scatter` | `points` | scatter plots |

## Options

| Attribute | React | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `variant` | `variant` | `line` \| `bar` \| `scatter` | `line` | The kind of chart it stands in for. |
| | `targetProvider` | function | | Where the real chart is, for the handoff. |
| `mark` | `mark` | `dot` \| `square` \| `dash` | `dot` | The shape of each mark. |
| `speed` | `speed` | number | `1` | How fast the ridge and glow move. |
| `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. |

The chart sizes like a block: it fills its width and is 12rem tall unless you set a height.

## Animations

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

| Phase | Default | Also available |
| --- | --- | --- |
| Idle | `ridge`: a soft line drifting through the field | `bars`, `scatter`: shapes for those chart types; `scan`: a band sweeps across the line; `terrain`: the field below the line is shaded like land; `cycle`: moves between line, bars and scatter |
| Handoff | `morphWipe`: marks glide onto the line, then the chart draws in | |

Each takes options, for example `scan({ bandWidth: 48 })`:

| Animation | Options (default) |
| --- | --- |
| `ridge` | `amplitude` 0–0.4 (0.24), `highlightWidth` 20–180 px (90) |
| `scan` | `amplitude` 0–0.4 (0.24), `bandWidth` 12–80 px (36), `trail` 40–240 px (160) |
| `terrain` | `amplitude` 0–0.4 (0.24), `relief` 0.4–1.4 (1) |
| `bars` | `sway` 0–0.12 (0.07) |
| `scatter` | `radius` 6–24 px (13), `spread` 0.1–0.35 (0.24), `sway` 0–0.1 (0.045) |
| `cycle` | `holdMs` 800–3200 (3200), `blendMs` 200–600 (460) |
| `morphWipe` | `morphEnd` 0.55–0.95 (0.55), `wipeStart` 0.15–0.6 (0.48), `edge` 4–80 px (40) |
