# Skeleton

> Skeleton loaders for images, text lines, avatars and paragraphs, made of marks, as native Web Components or React components.

Dotquilt's skeleton loaders hold the shape of images, text and avatars while they load. A soft glow drifts across the marks. When the region hands over, the marks take your content's real shape, then the content wipes in as they leave.

## Usage

Put a skeleton in a region's `placeholder` slot and size it with CSS like any other element: blocks fill their width and take the height you give them, and lines are two rows of marks tall. Your code owns the request; the region only needs to know whether the data is pending or ready.

**React**

```tsx title="MemberCard.tsx"
'use client';
import { LoadingRegion, SkeletonCircle, SkeletonLine } from '@dotquilt/react';
import { useEffect, useState } from 'react';

interface Member {
  name: string;
  role: string;
  bio: string;
}

async function fetchMember(id: string, signal: AbortSignal): Promise<Member> {
  const response = await fetch(`/api/members/${id}`, { signal });
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
  return response.json();
}

type Result =
  | { status: 'loading' }
  | { status: 'done'; member: Member }
  | { status: 'failed' };

export function MemberCard({ id }: { id: string }) {
  const [result, setResult] = useState<Result>({ status: 'loading' });

  useEffect(() => {
    const request = new AbortController();
    setResult({ status: 'loading' });
    fetchMember(id, request.signal)
      .then((member) => setResult({ status: 'done', member }))
      .catch(() => {
        if (!request.signal.aborted) setResult({ status: 'failed' });
      });
    // A newer id cancels this request, so a stale answer never shows.
    return () => request.abort();
  }, [id]);

  return (
    <LoadingRegion
      aria-label="Team member"
      state={result.status === 'loading' ? 'pending' : 'ready'}
      cycle={id}
      // An error replaces the placeholder at once, without the handoff.
      timing={result.status === 'failed' ? { duration: 0 } : undefined}
      placeholder={
        <div className="member-skeleton">
          <SkeletonCircle />
          <SkeletonLine />
          <SkeletonLine style={{ width: '60%' }} />
        </div>
      }
    >
      {result.status === 'done' && (
        <article className="member">
          <h3>{result.member.name}</h3>
          <p>{result.member.role}</p>
          <p>{result.member.bio}</p>
        </article>
      )}
      {result.status === 'failed' && (
        <p role="alert">We couldn't load this member. Try again later.</p>
      )}
    </LoadingRegion>
  );
}

// Use it like any other component; it loads again whenever `id` changes.
export function Team() {
  return <MemberCard id="ada" />;
}
```

**Native**

```html title="index.html"
<dotquilt-region id="member" state="pending" aria-label="Team member">
  <div slot="placeholder" class="member-skeleton">
    <dotquilt-skeleton-circle></dotquilt-skeleton-circle>
    <dotquilt-skeleton-line></dotquilt-skeleton-line>
    <dotquilt-skeleton-line style="width: 60%"></dotquilt-skeleton-line>
  </div>
  <article class="member">
    <h3 data-field="name">Team member</h3>
    <p data-field="role"></p>
    <p data-field="bio"></p>
  </article>
</dotquilt-region>
```
```ts title="member.ts"
import { type LoadingRegion, registerLoadingRegion } from 'dotquilt/region';
import {
  registerSkeletonCircle,
  registerSkeletonLine,
} from 'dotquilt/skeleton';

registerLoadingRegion();
registerSkeletonCircle();
registerSkeletonLine();

const region = document.getElementById('member') as LoadingRegion | null;

export async function showMember(id: string): Promise<void> {
  if (!region) return;
  // Each request is a new cycle; the placeholder shows until it settles.
  region.update({ state: 'pending', cycle: id });
  try {
    const response = await fetch(`/api/members/${id}`);
    if (!response.ok) throw new Error(`Request failed: ${response.status}`);
    const member: Record<string, string> = await response.json();
    // A newer request took over while this one was in flight.
    if (region.cycle !== id) return;
    for (const field of region.querySelectorAll<HTMLElement>('[data-field]'))
      field.textContent = member[field.dataset.field ?? ''] ?? '';
    region.update({ state: 'ready' });
  } catch {
    if (region.cycle !== id) return;
    const card = region.querySelector('article');
    if (card)
      card.textContent = "We couldn't load this member. Try again later.";
    // An error replaces the placeholder at once, without the handoff.
    region.update({ state: 'ready', timing: { duration: 0 } });
  }
}

void showMember('ada');
```

### Matching your text's line height

SkeletonText draws each line two rows of marks tall and spaces the lines `0.5em` apart. A line is 18 px tall with the default dots (twice the dot size plus the gap), 17 px with squares and 19 px with dashes. That holds a paragraph's shape without knowing your text's line height. To put each line where a line of text sits, so the placeholder is as tall as the same number of lines of text, set its gap and margins from `1lh`, the line height it inherits:

```css
.excerpt dotquilt-skeleton-text {
  --line: 18px; /* 17px for squares, 19px for dashes */
  gap: calc(1lh - var(--line));
  margin-block: calc((1lh - var(--line)) / 2);
}
```

Use margins rather than padding: the idle glow's copy of the lines spans the padding box, so padding moves it off the lines.

## Elements

| Element | React | Use |
| --- | --- | --- |
| `<dotquilt-skeleton-block>` | `SkeletonBlock` | images, charts and other rectangles |
| `<dotquilt-skeleton-line>` | `SkeletonLine` | one line of text |
| `<dotquilt-skeleton-circle>` | `SkeletonCircle` | avatars and icons |
| `<dotquilt-skeleton-text>` | `SkeletonText` | a paragraph of lines |

## Options

| Attribute | Type | Default | Description |
| --- | --- | --- | --- |
| `mark` | `dot` \| `dash` \| `square` | `dot` | The shape of each mark. Dashes suit text lines; squares stay crisp at small sizes. |
| `motion` | `system` \| `paused` | `system` | `system` follows the visitor's reduced-motion setting; `paused` stills the marks. |
| `speed` | number | `1` | How fast the idle glow moves, from above 0 up to 4. |
| `pointer-response` | `none` \| `lift` | `none` | `lift` lights the marks around the pointer while the placeholder shows, on devices with a fine pointer. |
| `lines` | number | `3` | SkeletonText only: how many lines, up to 50. |

In React the props have the same names in camelCase (`pointerResponse`).

## Animations

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

| Phase | Default | Also available | Options |
| --- | --- | --- | --- |
| Idle | a soft glow drifts across every 2.8 s | `pulse`: the same glow at your own pace | `periodMs` 800–4000 (2800) |
| Handoff | the marks travel to the content's real shape (each line's length, the image, the avatar), then the content wipes in as they leave | `dissolve`: marks fall away as the content fades in | `duration` ms (300), `fallPx` 0–8 (5) |

## Colours

The marks use a slate that sits inside any app, with a soft teal glow. Change them with custom properties:

```css
.profile {
  --dotquilt-color: #627467;
  --dotquilt-accent-color: #3f7f86;
}
```
