# LoadingRegion

> The area that switches from placeholder to content, with pending, refreshing and ready states, and owns the handoff between them.

A loading region decides when to switch from Dotquilt's placeholder to your content. It shows its placeholder while your data is pending, keeps your content visible while it refreshes, and hands over when it's ready. Every loader except TextLoader lives inside one.

## States

| State | The placeholder | Your content |
| --- | --- | --- |
| `pending` | shown | hidden, inert and hidden from assistive technology |
| `refreshing` | a row of marks just above the top edge, or your `refresh-indicator` | visible and usable |
| `ready` | gone, after the handoff | visible |

While pending, the region is as tall as the taller of the two: your content is laid out, hidden, so the handoff can read its shape. Once the handoff ends, and while refreshing, the placeholder takes no space and the region is as tall as your content. Give the placeholder your content's size, so nothing moves when the handoff ends.

While it refreshes, a row of marks sits just above the region's top edge and the glow drifts along it once, so your content never moves. With reduced motion or a pause the row stays still. Move it with `--dotquilt-refresh-gap` (6 px above the edge by default), style it through `::part(refresh-thread)`, or pass your own `refresh-indicator` instead.

For fast responses, `delay` and `min-display` keep the placeholder from flickering: a load shorter than `delay` never shows it, and a placeholder that did show stays for at least `min-display`. Values around 150 ms and 500 ms suit most screens.

Going from `pending` to `ready` plays the handoff. First the marks take your content's shape: skeleton lines grow or shrink to each real line of text, blocks and circles reshape to the real image or avatar, typing dots unroll into the message, and a placeholder card or bubble grows to the real one's size. Then your content wipes in along a soft front, and the marks leave where it passes them. Only what shows takes part: text that is clipped away, such as a visually hidden table header, gets no marks. It takes about a second, and right-to-left text wipes from the right. With reduced motion, a pause, or focus inside the content, it swaps at once. During a view transition it waits for the transition to end, then plays.

## Usage

**React**

```tsx title="ActivityFeed.tsx"
'use client';
import { LoadingRegion, SkeletonText } from '@dotquilt/react';
import { useCallback, useEffect, useRef, useState } from 'react';

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

export function ActivityFeed() {
  const [items, setItems] = useState<string[] | null>(null);
  const [refreshing, setRefreshing] = useState(false);
  const [failed, setFailed] = useState(false);
  const latest = useRef<AbortController | null>(null);

  const load = useCallback(() => {
    // Only the latest request may update the feed.
    latest.current?.abort();
    const request = new AbortController();
    latest.current = request;
    return fetchActivity(request.signal).then(
      (next) => {
        if (latest.current === request) setItems(next);
      },
      (error) => {
        // A newer request replaced this one; that is not a failure.
        if (!request.signal.aborted) throw error;
      },
    );
  }, []);

  useEffect(() => {
    load().catch(() => setFailed(true));
    return () => latest.current?.abort();
  }, [load]);

  function refresh() {
    setRefreshing(true);
    // A failed refresh keeps the feed you already have.
    load()
      .catch(() => {})
      .finally(() => setRefreshing(false));
  }

  return (
    <section>
      <button type="button" onClick={refresh} disabled={refreshing}>
        Refresh
      </button>
      <LoadingRegion
        aria-label="Recent activity"
        // Pending hides the content; refreshing keeps it visible and usable.
        state={
          items === null && !failed
            ? 'pending'
            : refreshing
              ? 'refreshing'
              : 'ready'
        }
        timing={failed && items === null ? { duration: 0 } : undefined}
        placeholder={<SkeletonText lines={3} />}
      >
        {failed && items === null ? (
          <p role="alert">We couldn't load activity. Try again later.</p>
        ) : (
          <ul>
            {items?.map((item) => (
              <li key={item}>{item}</li>
            ))}
          </ul>
        )}
      </LoadingRegion>
    </section>
  );
}
```

**Native**

```html title="index.html"
<button type="button" id="refresh">Refresh</button>
<dotquilt-region id="activity" state="pending" aria-label="Recent activity">
  <dotquilt-skeleton-text slot="placeholder" lines="3"></dotquilt-skeleton-text>
  <ul data-items></ul>
</dotquilt-region>
```
```ts title="activity.ts"
import { type LoadingRegion, registerLoadingRegion } from 'dotquilt/region';
import { registerSkeletonText } from 'dotquilt/skeleton';

registerLoadingRegion();
registerSkeletonText();

const region = document.getElementById('activity') as LoadingRegion | null;
const list = region?.querySelector('[data-items]');
const button = document.getElementById('refresh') as HTMLButtonElement | null;
let requests = 0;

async function load(): Promise<void> {
  if (!region || !list) return;
  const cycle = `activity-${++requests}`;
  // The first load hides the feed; later ones keep it visible and usable.
  region.update({
    state: list.children.length ? 'refreshing' : 'pending',
    cycle,
  });
  try {
    const response = await fetch('/api/activity');
    if (!response.ok) throw new Error(`Request failed: ${response.status}`);
    const items: string[] = await response.json();
    if (region.cycle !== cycle) return;
    list.replaceChildren(
      ...items.map((item) =>
        Object.assign(document.createElement('li'), { textContent: item }),
      ),
    );
    region.update({ state: 'ready' });
  } catch {
    if (region.cycle !== cycle) return;
    // A failed refresh keeps the feed you already have.
    if (!list.children.length)
      list.append(
        Object.assign(document.createElement('li'), {
          textContent: "We couldn't load activity. Try again later.",
        }),
      );
    region.update({ state: 'ready', timing: { duration: 0 } });
  }
}

button?.addEventListener('click', () => void load());
void load();
```

## Slots

| Slot | React | Holds |
| --- | --- | --- |
| `placeholder` | `placeholder` | the loader shown while pending |
| `refresh-indicator` | `refreshIndicator` | your own cue while refreshing, in place of the row of marks |
| (default) | `children` | your content |

## Options

| Attribute | React | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `state` | `state` | `pending` \| `refreshing` \| `ready` | `ready` | Whether the content is loading. |
| `cycle` | `cycle` | string | | Names one load, so a stale answer can't settle a newer one. |
| `delay` | `delay` | number (ms) | `0` | Wait this long before showing the placeholder. A response inside it shows no placeholder and no handoff, so fast loads don't flicker. A placeholder already on the page, such as server markup, is never hidden. Up to 10000. |
| `min-display` | `minDisplay` | number (ms) | `0` | Once a placeholder shows, keep it at least this long before handing over, so it never flashes. Up to 10000. |
| | `timing` | `{ duration?, easing? }` | | The handoff's length and curve. `{ duration: 0 }` swaps at once, for errors. |
| | `revealTargets` | `{ id, element }[]` | | Parts of your content that settle in turn under a custom handoff, or a TableLoader with a `targetProvider`. The default handoff doesn't need them. |
| `motion` | `motion` | `system` \| `paused` | `system` | `system` follows the visitor's reduced-motion setting; `paused` stills every loader inside. |

## Events

| Event | When |
| --- | --- |
| `dotquilt-handoff-start` | the handoff begins |
| `dotquilt-handoff-end` | it finishes; `detail.reason` is `complete`, or why it swapped at once |
| `dotquilt-handoff-cancel` | a newer state or cycle replaced it |
| `dotquilt-error` | an option was invalid or an animation failed; `detail.code` says which |

In React, use `onHandoffStart`, `onHandoffEnd`, `onHandoffCancel` and `onLoaderError`.

`dotquilt-error` doesn't repeat itself. A configuration problem, such as an invalid `speed`, reports again only after the option held a valid value in between. A failure while loading, such as an animation that throws, reports at most once per load: the next pending state or new `cycle` can report it again.

## Accessibility

- **Label every region** with `aria-label`, so people know what is loading.
- **Pending content is out of reach:** it is inert and hidden from assistive technology until it is ready.
- **Focus is kept:** if focus is inside content that becomes pending, it moves to the region; completion never moves it back by itself.
- **Status is yours:** announce loading and errors in your own words, for example with a `role="status"` element outside the region.
