# Like burst

> A like button whose heart fills inside a spinning ring of sparks, which throws sparks off as it turns and closes over the heart.

A heart button with a count, at any size. Liked, the outline gives way to a small pink heart and a ring of fire opens around it: a white-hot line under a hundred and fifty short arcs racing round, with an orange glow on both sides and an edge that flickers. As it spins, sparks fly off it along the turn and fall away, cooling from white to red. Then the ring closes over the heart, throwing a last ring of faster sparks, and the heart grows past its size and settles. Unliked, it only fades back to the outline. The whole burst takes 1.2 s and is drawn on a canvas over the button, so it takes no room in the layout.

A React component by Bruno Delorence: https://brunodelorence.com/components/like-burst. MIT License, Copyright (c) 2026 Bruno Delorence.

Category: Feedback.

## Anatomy

1. **Button**: A real `<button>` with `aria-pressed`, holding the heart and the count, `size` / 4 apart. Its focus ring sits 4 px off it.
2. **Heart**: A `size` px square: the outline, 2/24 of it thick, and the fill over it. Liked shows the fill; which one shows is CSS from `data-liked`.
3. **Burst**: A canvas 3 heart sizes wide, centred on the heart and over everything near it. It is empty except during the 1.2 s after a like.
4. **Count**: Everyone else’s likes, plus one while it is liked, with thousands separators and tabular figures. It turns pink when liked.

## Properties

### Size (`size`)

1. **20**: A comment or a reply, under a line of text.
2. **24 (default)**: A post in a feed, next to reply and share.
3. **40**: A photo or a product on its own page.

Match the other actions in the row. The burst grows with the heart, so leave 1.5 heart sizes clear around it at large sizes.

### Burst (`burst`)

1. **On (default)**: The ring of fire and its sparks, around the pop.
2. **Off**: Only the heart’s pop: for dense lists, or a calmer product.

Keep it on where a like is an occasional, personal gesture; turn it off where people like many things in a row.

## When to use

- The like on a post, a photo or a comment in a feed: one tap that says “I liked this”, with a count beside it.
- A favourite or a save that should feel rewarding the first time, and is cheap to undo.
- A product with a dark interface or a playful voice, where a short burst of light suits the moment.

## When not to use

- A rating. One heart is on or off; use stars or a scale to say how much.
- Anything with a consequence, such as following, buying or sending. A celebration there reads as pressure; use a plain button.
- Long lists where many hearts can be pressed in a row, such as selecting items. Use checkboxes: a burst on each is noise.
- A tight row with no room around the heart. The burst draws 1.5 heart sizes out from its centre, over its neighbours.

### The sequence

- **0 s**: the outline leaves in 0.12 s, a small fill appears, and a ring of fire opens around it in 0.22 s, already spinning.
- **0.06 s**: sparks start to fly off the ring along the turn and fall, each living about a third of a second.
- **0.72 s**: the ring slows and closes over the heart, throwing a last ring of faster sparks, as the heart grows to 116%.
- **1.1 s**: the heart settles at its size; at 1.2 s the canvas is clear.
- **Unlike**: the fill shrinks and fades in 0.18 s while the outline springs back. No burst.

### Counting

- **Pass the others’ likes**: `count` leaves the reader’s own like out, so liking and unliking never need a round trip to show the right number.
- **Save it in the background**: call your API from `onLikedChange` and, if it fails, set `liked` back.

## Do’s and don’ts

- **Do**: Leave room around a large heart, so the burst reads as a ring and not as clutter over the text.
- **Don’t**: Put a large heart right against other controls: the burst draws over them for a moment.
- **Do**: Show the count when it helps people judge a post; leave it out in a private list of favourites.

## Content

The only words are its name and its number.

- **The name** is the action, the same liked or not: `Like`. `aria-pressed` says which.
- **The number** is the full count with separators: `1,284`, not `1.2K`.

## Installation

Install it with the shadcn CLI, into components/like-burst of any React project:

```sh
npx shadcn@latest add https://brunodelorence.com/r/like-burst.json
```

Or add the registry to components.json once, as a namespace that coding agents and the shadcn MCP server search by name:

```json
{
  "registries": {
    "@brunodelorence": "https://brunodelorence.com/r/{name}.json"
  }
}
```

```sh
npx shadcn@latest add @brunodelorence/like-burst
```

Or copy all the source files below into one folder of your project. Either way it needs React 19.2 and a bundler with CSS Modules (Next.js, Vite).

It has a dark colour scheme. Its colours are CSS light-dark() pairs, kept inside @supports so that builds which rewrite light-dark() for older browsers leave them alone: it follows your page’s color-scheme (light unless the page sets one) or its colorScheme prop, with nothing to configure. Browsers without light-dark() show it light.

## Usage

```tsx
import { useState } from 'react';
import { LikeButton } from './like-burst';

export function PostActions({ post }: { post: { id: string; likes: number; liked: boolean } }) {
  const [liked, setLiked] = useState(post.liked);

  return (
    <LikeButton
      liked={liked}
      // Everyone else's likes: the button adds one while it is liked.
      count={post.likes - (post.liked ? 1 : 0)}
      onLikedChange={(next) => {
        setLiked(next);
        fetch(`/api/posts/${post.id}/like`, { method: next ? 'PUT' : 'DELETE' });
      }}
    />
  );
}
```

## States

- **Not liked**: The grey outline and the count.
- **Spinning, at 0.45 s**: A small fill inside the ring of fire, with sparks flying off it along the turn.
- **Closing, at 0.95 s**: The ring has closed over the heart, which is at its largest; the last sparks fall away.
- **Liked**: The pink fill and a pink count, one higher.
- **Dark**: With `colorScheme="dark"`: a lighter outline, and the burst adds light instead of paint.

## How it works

- The heart is two SVGs over each other, an outline 2/24 of it thick and a fill; which one shows is plain CSS from data-liked, so a liked button rendered on the server is already right.
- One clock from the press: the outline leaves in 0.12 s, the fill appears at 56% of its size and holds at about 60% while the ring spins, grows to 116% as the ring closes at 0.88 s, and settles at 100% by 1.1 s. Its keyframes are one Web Animations API call.
- The burst is a pure function of the time since the press, in burst.ts: the canvas is redrawn each frame for 1.2 s, then cleared. Every length is a share of the heart’s size, so it scales with the button, and the same function draws any single frame as a still (freezeAt).
- The ring opens from 0.3 to 0.8 heart sizes in 0.22 s with a small overshoot, spins at 10 radians a second (about 1.6 turns), and from 0.72 s closes to 0.3 as it slows.
- It is drawn in three layers: a radial glow on both sides of the ring, a thin white-hot core line, and 150 short arcs from a seeded generator, hottest at their heads, each drifting a little ahead of or behind the ring and wavering on its radius. Two slow sine waves make the whole ring flicker.
- The sparks are a particle system with no state: 320 are born while the ring spins and 64 more as it closes, each at a set time and angle. Where one is at any moment is worked out from its launch, along the spin and slightly outward, and gravity, so a still shows exactly the frame the animation does. Each is drawn as a streak from where it was 70 ms before, cooling from white to orange to red as it fades.
- On a dark page the fire adds light (globalCompositeOperation lighter); on a light one it is painted over in deeper oranges, and every gradient fades to the fire’s own colour at no opacity, so nothing greys. The script tells the schemes apart from the canvas’s colour, a light-dark() token that is white in the dark scheme.
- The count is everyone else’s likes, plus one while liked; it rolls up or down by its own height on a change. The demo’s pointer likes, waits, unlikes and likes again while nobody touches the stage.

## API reference

- **liked** (`boolean`): Whether it is liked, if you hold it; pair it with onLikedChange.
- **defaultLiked** (`boolean`, default `false`): Whether it starts liked, when it holds it itself.
- **onLikedChange** (`(liked: boolean) => void`): Called with the new value on every press.
- **count** (`number`): Everyone else’s likes: the number shown is this, plus one while it is liked. Left out, no number shows.
- **size** (`number`, default `24 (88 in LikeBurst)`): The heart’s width in px; the burst reaches 1.5 times it out from the heart’s centre.
- **label** (`string`, default `'Like'`): The button’s accessible name; the count is read after it.
- **burst** (`boolean`, default `true`): false keeps the pop of the heart and leaves out the ring and the dashes.
- **freezeAt** (`number`): Holds a like’s animation still at this many ms, from 0 to 1200, for stills and docs.
- **autoplay** (`boolean`, default `true`): LikeBurst only: while on screen and untouched, a pointer likes and unlikes it; never under reduced motion.
- **colorScheme** (`'light' | 'dark' | 'system'`): Forces a scheme. Left out, it follows the page.
- **className** (`string`): Added to the button (or the stage).

## Accessibility

### Focus and keyboard

- It is one button: Tab reaches it, Space and Enter press it.
- The focus ring is a 2 px blue outline 4 px off the button.

### Screen readers

- It is read as a toggle with its count, such as “Like, 1,284, toggle button, pressed”.
- The heart, the canvas and the demo pointer are hidden.

### Motion

With reduced motion there is no burst, pop or roll: the fill fades in over 0.16 s, and the demo does not play.

### In this build

- A real button with aria-pressed, so it is read as a toggle: “Like, 1,284, toggle button, pressed”. Space and Enter press it.
- The heart and the canvas are hidden from screen readers; the count is plain text inside the button, read after its name.
- The focus ring is a 2 px outline 4 px off the button. The hover tint and colour need a pointer that hovers.
- Under reduced motion there is no burst, pop or roll: the fill fades in over 0.16 s, and the demo does not play.

## Source

### like-burst/like-burst.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type CSSProperties,
  type Ref,
} from 'react';
import { BURST_MS, DARK, LIGHT, REACH, drawBurst } from './burst';
import { DemoPointer, runDemo } from './demo-pointer';
import styles from './like-burst.module.css';
import { useAutoplay } from './use-autoplay';

/*
 * A like button whose heart, when liked, fills inside a spinning ring of sparks that throws
 * sparks off as it turns and closes over the heart. LikeButton is the button, at any size;
 * LikeBurst is the demo: one large button on a stage, which a pointer likes and unlikes while
 * nobody touches it.
 *
 * The heart is two SVGs over each other, the outline and the fill; which one shows is plain CSS
 * from data-liked. A like plays three animations on top: the fill's pop and the outline's exit
 * (Web Animations API), and the burst on a canvas over the heart (burst.ts), redrawn each frame
 * for 1.2 s and then cleared. An unlike only crossfades back to the outline.
 */

const HEART =
  'M12 20.6c-.3 0-.6-.1-.8-.3C8.6 18.1 3 13.6 3 9.1 3 6.3 5.1 4.2 7.7 4.2c1.8 0 3.3.9 4.3 2.4 1-1.5 2.5-2.4 4.3-2.4C18.9 4.2 21 6.3 21 9.1c0 4.5-5.6 9-8.2 11.2-.2.2-.5.3-.8.3z';

/** The fill's pop, over the burst: it appears small inside the ring and grows as it closes. */
const POP: Keyframe[] = [
  { transform: 'scale(0.2)', opacity: 0, offset: 0 },
  { transform: 'scale(0.56)', opacity: 1, offset: 0.06 },
  { transform: 'scale(0.62)', offset: 0.66 },
  { transform: 'scale(1.16)', offset: 0.8 },
  { transform: 'scale(0.95)', offset: 0.9 },
  { transform: 'scale(1)', opacity: 1, offset: 1 },
];
const POP_MS = 1100;

export type LikeButtonProps = {
  /** Whether it is liked, if you hold it; pair it with onLikedChange. */
  liked?: boolean;
  /** Whether it starts liked, when it holds it itself. */
  defaultLiked?: boolean;
  /** Called with the new value on every press. */
  onLikedChange?: (liked: boolean) => void;
  /** Everyone else's likes: the number shown is this, plus one while it is liked. */
  count?: number;
  /** The heart's width, in px. */
  size?: number;
  /** The button's accessible name; the count is read after it. */
  label?: string;
  /** false turns the burst off: the heart only pops. */
  burst?: boolean;
  /** Holds the like's animation still at this many ms (0 to 1200), for stills and docs. */
  freezeAt?: number;
  /** Forces a scheme. Left out, it follows the page. */
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
  ref?: Ref<HTMLButtonElement>;
};

const format = (n: number) => n.toLocaleString('en-US');

export function LikeButton({
  liked: likedProp,
  defaultLiked = false,
  onLikedChange,
  count,
  size = 24,
  label = 'Like',
  burst = true,
  freezeAt,
  colorScheme,
  className = '',
  ref,
}: LikeButtonProps) {
  const [own, setOwn] = useState(defaultLiked);
  const liked = freezeAt !== undefined || (likedProp ?? own);
  const canvas = useRef<HTMLCanvasElement>(null);
  const fill = useRef<SVGSVGElement>(null);
  const outline = useRef<SVGSVGElement>(null);
  const frame = useRef(0);
  const running = useRef<Animation[]>([]);
  // Which way the count last moved, for its roll; none on the first render.
  const [roll, setRoll] = useState<'up' | 'down' | null>(null);

  /** Sizes the canvas to the burst's reach and returns it ready to draw, centred on the heart. */
  const prepare = useCallback(() => {
    const element = canvas.current;
    const context = element?.getContext('2d');
    if (!element || !context) return null;
    const box = Math.ceil(size * REACH * 2);
    const ratio = Math.min(window.devicePixelRatio || 1, 3);
    if (element.width !== box * ratio) {
      element.width = box * ratio;
      element.height = box * ratio;
    }
    // The canvas's colour is a light-dark() token: white means the dark scheme.
    const dark = getComputedStyle(element).color.replace(/\s/g, '') === 'rgb(255,255,255)';
    const paint = (t: number) => {
      context.setTransform(1, 0, 0, 1, 0, 0);
      context.clearRect(0, 0, element.width, element.height);
      context.setTransform(ratio, 0, 0, ratio, (box * ratio) / 2, (box * ratio) / 2);
      drawBurst(context, t, size, dark ? DARK : LIGHT);
    };
    return paint;
  }, [size]);

  const stop = useCallback(() => {
    cancelAnimationFrame(frame.current);
    running.current.forEach((animation) => animation.cancel());
    running.current = [];
  }, []);

  const playLike = useCallback(
    (reduced: boolean) => {
      stop();
      const heart = fill.current;
      const ring = outline.current;
      if (!heart || !ring) return;
      if (reduced) {
        running.current = [heart.animate([{ opacity: 0 }, { opacity: 1 }], 160)];
        return;
      }
      running.current = [
        heart.animate(POP, { duration: POP_MS, easing: 'linear' }),
        ring.animate(
          [
            { opacity: 1, transform: 'scale(1)' },
            { opacity: 0, transform: 'scale(0.7)' },
          ],
          { duration: 120, easing: 'ease-in' },
        ),
      ];
      if (!burst) return;
      const paint = prepare();
      if (!paint) return;
      const start = performance.now();
      const tick = (now: number) => {
        const t = now - start;
        paint(Math.min(t, BURST_MS + 1));
        if (t <= BURST_MS) frame.current = requestAnimationFrame(tick);
      };
      frame.current = requestAnimationFrame(tick);
    },
    [burst, prepare, stop],
  );

  const playUnlike = useCallback(() => {
    stop();
    const heart = fill.current;
    const ring = outline.current;
    if (!heart || !ring) return;
    running.current = [
      heart.animate(
        [
          { opacity: 1, transform: 'scale(1)' },
          { opacity: 0, transform: 'scale(0.6)' },
        ],
        { duration: 180, easing: 'ease-in' },
      ),
      ring.animate(
        [
          { opacity: 0, transform: 'scale(0.8)' },
          { opacity: 1, transform: 'scale(1)' },
        ],
        { duration: 220, easing: 'cubic-bezier(0.3, 1.5, 0.6, 1)' },
      ),
    ];
    const paint = prepare();
    paint?.(-1);
  }, [prepare, stop]);

  useEffect(() => stop, [stop]);

  // A still: the burst's frame and the fill's pop held at freezeAt.
  useLayoutEffect(() => {
    if (freezeAt === undefined) return;
    stop();
    const t = Math.min(BURST_MS, Math.max(0, freezeAt));
    if (burst) prepare()?.(t);
    const heart = fill.current;
    if (heart) {
      const pop = heart.animate(POP, { duration: POP_MS, fill: 'both' });
      pop.pause();
      pop.currentTime = Math.min(t, POP_MS);
      running.current = [pop];
    }
    return stop;
  }, [freezeAt, burst, prepare, stop]);

  const press = () => {
    if (freezeAt !== undefined) return;
    const next = !liked;
    if (likedProp === undefined) setOwn(next);
    onLikedChange?.(next);
    setRoll(next ? 'up' : 'down');
    if (next) playLike(window.matchMedia('(prefers-reduced-motion: reduce)').matches);
    else playUnlike();
  };

  const shown = count === undefined ? undefined : count + (liked ? 1 : 0);

  return (
    <button
      ref={ref}
      type="button"
      className={`${styles.button} ${className}`}
      data-part="button"
      data-liked={liked}
      data-color-scheme={colorScheme}
      aria-pressed={liked}
      onClick={press}
      style={{ '--size': `${size}px`, '--reach': REACH } as CSSProperties}
    >
      <span className={styles.heart} data-part="heart" aria-hidden="true">
        <svg ref={outline} className={styles.outline} viewBox="0 0 24 24" data-part="outline">
          <path d={HEART} />
        </svg>
        <svg ref={fill} className={styles.fill} viewBox="0 0 24 24" data-part="fill">
          <path d={HEART} />
        </svg>
        <canvas ref={canvas} className={styles.canvas} data-part="burst" />
      </span>
      <span className={styles.hidden}>{label}</span>
      {shown !== undefined && (
        <span className={styles.count} data-part="count">
          <span key={shown} className={styles.digits} data-roll={roll ?? undefined}>
            {format(shown)}
          </span>
        </span>
      )}
    </button>
  );
}

export type LikeBurstProps = LikeButtonProps & {
  /** While on screen and untouched, a pointer likes and unlikes it; never under reduced motion. */
  autoplay?: boolean;
};

/** The demo: one large like button on a stage, with a pointer that plays it while it's left alone. */
export function LikeBurst({
  autoplay = true,
  size = 88,
  count = 1283,
  liked: likedProp,
  defaultLiked = false,
  onLikedChange,
  colorScheme,
  className = '',
  freezeAt,
  ...rest
}: LikeBurstProps) {
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>();
  const button = useRef<HTMLButtonElement>(null);
  const pointer = useRef<HTMLSpanElement>(null);
  const [own, setOwn] = useState(defaultLiked);
  const liked = likedProp ?? own;
  const demo = autoplay && playing && freezeAt === undefined && likedProp === undefined;

  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    const target = button.current;
    if (!demo || !stage || !arrow || !target) return;
    const heartAt = () => {
      const heart = target.querySelector('[data-part="heart"]')!.getBoundingClientRect();
      const box = stage.getBoundingClientRect();
      return {
        x: heart.left - box.left + heart.width * 0.55,
        y: heart.top - box.top + heart.height * 0.6,
      };
    };
    const tap = async (wait: (ms: number) => Promise<void>) => {
      target.dataset.pressed = 'true';
      await wait(110);
      delete target.dataset.pressed;
      target.click();
    };
    const stopDemo = runDemo(stage, arrow, async ({ wait, glide }) => {
      await wait(700);
      for (;;) {
        const at = heartAt();
        await glide(at, 900);
        await wait(250);
        // Leave it liked, then come back to unlike it, then like it again.
        if (target.getAttribute('aria-pressed') === 'true') {
          await tap(wait);
          await wait(700);
          await glide({ x: at.x + 34, y: at.y + 26 }, 500);
          await wait(500);
          await glide(at, 450);
          await wait(200);
        }
        await tap(wait);
        await wait(500);
        await glide(
          { x: at.x + stage.offsetWidth * 0.22, y: at.y + stage.offsetHeight * 0.24 },
          1000,
        );
        await wait(2400);
      }
    });
    return () => {
      stopDemo();
      delete target.dataset.pressed;
    };
  }, [demo, root]);

  return (
    <div
      ref={root}
      className={`${styles.stage} ${className}`}
      data-part="stage"
      data-color-scheme={colorScheme}
      onPointerDownCapture={take}
      onKeyDownCapture={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') take();
      }}
    >
      <LikeButton
        {...rest}
        ref={button}
        className={styles.large}
        size={size}
        count={count}
        liked={liked}
        freezeAt={freezeAt}
        onLikedChange={(next) => {
          if (likedProp === undefined) setOwn(next);
          onLikedChange?.(next);
        }}
      />
      <div className={styles.pointerLayer} aria-hidden="true">
        <DemoPointer
          ref={pointer}
          className={styles.pointer}
          arrowClass={styles.arrow}
          textClass={styles.text}
        />
      </div>
    </div>
  );
}
```

### like-burst/like-burst.module.css

```css
/* Like burst (like-burst.tsx): a heart button. The heart is --size wide; the outline is drawn
   2/24 of it thick, and the burst's canvas reaches --reach heart sizes out from its centre, over
   whatever surrounds the button, without taking any room in the layout.

   The stage is the demo's: a dark page, as on a social app at night, or a pale one by day. */

.button,
.stage {
  --stage: #f6f7f8;
  --idle: #6e7a86;
  --idle-hover: #c92a6b;
  --liked: #e0245e;
  --tint: rgb(224 36 94 / 0.1);
  --count: #56606b;
  --count-liked: #c4204f;
  --focus: #1d9bf0;
  /* Read by the script: white in the dark scheme, black in the light one. */
  --probe: #000;
}

.button {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: calc(var(--size) * 0.25);
  margin: 0;
  padding: 0;
  border: 0;
  border-radius: 999px;
  background: none;
  color: var(--count);
  font:
    500 15px / 20px -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    Inter,
    Roboto,
    sans-serif;
  font-variant-numeric: tabular-nums;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
  touch-action: manipulation;
}

@supports (color: light-dark(#fff, #000)) {
  .button,
  .stage {
    --stage: light-dark(#f6f7f8, #0e1013);
    --idle: light-dark(#6e7a86, #8b98a5);
    --idle-hover: light-dark(#c92a6b, #f0508a);
    --liked: light-dark(#e0245e, #d2316f);
    --tint: light-dark(rgb(224 36 94 / 0.1), rgb(240 80 138 / 0.12));
    --count: light-dark(#56606b, #8b98a5);
    --count-liked: light-dark(#c4204f, #e9558e);
    --focus: light-dark(#1d9bf0, #4cb0f5);
    --probe: light-dark(#000, #fff);
  }
}
@media (prefers-color-scheme: dark) {
  @supports not (color: light-dark(#fff, #000)) {
    .button,
    .stage {
      --stage: #0e1013;
      --idle: #8b98a5;
      --liked: #d2316f;
      --count: #8b98a5;
      --count-liked: #e9558e;
      --probe: #fff;
    }
  }
}
.button[data-color-scheme='light'],
.stage[data-color-scheme='light'] {
  color-scheme: light;
}
.button[data-color-scheme='dark'],
.stage[data-color-scheme='dark'] {
  color-scheme: dark;
}
.button[data-color-scheme='system'],
.stage[data-color-scheme='system'] {
  color-scheme: light dark;
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 4px;
}

.heart {
  position: relative;
  display: block;
  flex: none;
  width: var(--size);
  height: var(--size);
  transition: transform 0.16s cubic-bezier(0.3, 1.4, 0.6, 1);
}
/* The hover's tint: a soft disc behind the heart. */
.heart::before {
  content: '';
  position: absolute;
  inset: calc(var(--size) * -0.32);
  border-radius: 50%;
  background: var(--tint);
  opacity: 0;
  transform: scale(0.7);
  transition:
    opacity 0.18s ease,
    transform 0.18s ease;
}
.button:active .heart,
.button[data-pressed='true'] .heart {
  transform: scale(0.86);
  transition-duration: 0.08s;
}

.outline,
.fill {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  overflow: visible;
}
.outline {
  fill: none;
  stroke: var(--idle);
  stroke-width: 2;
  stroke-linejoin: round;
  transition: stroke 0.15s ease;
}
.fill {
  fill: var(--liked);
  opacity: 0;
}
.button[data-liked='true'] .outline {
  opacity: 0;
}
.button[data-liked='true'] .fill {
  opacity: 1;
}

.canvas {
  position: absolute;
  top: 50%;
  left: 50%;
  width: calc(var(--size) * var(--reach) * 2);
  height: calc(var(--size) * var(--reach) * 2);
  translate: -50% -50%;
  color: var(--probe);
  pointer-events: none;
}

.count {
  display: inline-grid;
  overflow: hidden;
  transition: color 0.2s ease;
}
.button[data-liked='true'] .count {
  color: var(--count-liked);
}
.digits {
  grid-area: 1 / 1;
}
.digits[data-roll='up'] {
  animation: rollUp 0.32s cubic-bezier(0.2, 0.9, 0.3, 1.2);
}
.digits[data-roll='down'] {
  animation: rollDown 0.32s cubic-bezier(0.2, 0.9, 0.3, 1.2);
}
@keyframes rollUp {
  from {
    transform: translateY(70%);
    opacity: 0;
  }
}
@keyframes rollDown {
  from {
    transform: translateY(-70%);
    opacity: 0;
  }
}

@media (hover: hover) {
  .button:hover .heart::before {
    opacity: 1;
    transform: scale(1);
  }
  .button:hover:not([data-liked='true']) .outline {
    stroke: var(--idle-hover);
  }
  .button:hover:not([data-liked='true']) .count {
    color: var(--idle-hover);
  }
}

@media (prefers-reduced-motion: reduce) {
  .heart,
  .heart::before {
    transition: none;
  }
  .digits[data-roll] {
    animation: none;
  }
}

.hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

/* The demo's stage, with the button at its middle and the count under the heart. */
.stage {
  --pointer: #111;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.25);

  position: relative;
  display: grid;
  place-items: center;
  width: 100%;
  min-height: 400px;
  overflow: hidden;
  background: var(--stage);
  isolation: isolate;
}
.large {
  flex-direction: column;
  gap: 44px;
  padding-top: 44px;
  font-size: 22px;
  line-height: 28px;
  font-weight: 600;
}

.pointerLayer {
  position: absolute;
  inset: 0;
  z-index: 5;
  pointer-events: none;
}
.pointer {
  width: 24px;
  height: 24px;
}
.text {
  visibility: hidden;
}
.pointer[data-glyph='text'] .arrow {
  visibility: hidden;
}
.pointer[data-glyph='text'] .text {
  visibility: visible;
}
```

### like-burst/burst.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The burst around a heart that has just been liked: a spinning ring of sparks, drawn on a canvas
 * as a pure function of the time since the press. `drawBurst(ctx, t, size, palette)` paints the
 * frame at `t` ms, so the component can play it frame by frame or hold any single frame still
 * (freezeAt). Every length is a share of the heart's size `s`, so it scales with the button.
 *
 *   0–220 ms    the ring opens around the heart, from 0.3 to 0.8 heart sizes, overshooting a
 *               little, already turning fast (about 1.6 turns a second).
 *   220–720 ms  it spins in place: a white-hot core line under 150 short arcs of fire that race
 *               round it, its edge flickering, while sparks fly off it along the spin and fall.
 *   720–960 ms  it closes over the heart and throws a last ring of faster sparks; the sparks
 *               still in the air finish their fall by 1.2 s.
 *
 * The sparks are a particle system with no state: each is born at a set time and angle from a
 * seeded generator, and its place at any moment is worked out from its launch (along the spin,
 * slightly outward) and gravity. So a still at 0.5 s is exactly the frame the animation shows.
 */

/** How long the whole burst lasts, in ms. */
export const BURST_MS = 1200;

/** When the ring starts to close, in ms: the heart grows as it does. */
export const CLOSE_MS = 720;

export type Palette = {
  /** The white-hot centre of the fire, its orange body, and the deep red it cools to. */
  core: string;
  fire: string;
  ember: string;
  /** The glow around the ring, at its strongest. */
  glow: string;
  /** The fire at no opacity, for the ends of the gradients: fading to it keeps them from greying. */
  clear: string;
  /** 'lighter' adds light on a dark page; on a light one the fire is painted over. */
  blend: GlobalCompositeOperation;
};

export const DARK: Palette = {
  core: 'rgb(255 247 226)',
  fire: 'rgb(255 158 46)',
  ember: 'rgb(214 70 18)',
  glow: 'rgb(255 132 30 / 0.55)',
  clear: 'rgb(255 132 30 / 0)',
  blend: 'lighter',
};

export const LIGHT: Palette = {
  core: 'rgb(255 196 84)',
  fire: 'rgb(240 112 20)',
  ember: 'rgb(196 52 12)',
  glow: 'rgb(250 140 30 / 0.3)',
  clear: 'rgb(250 140 30 / 0)',
  blend: 'source-over',
};

/** How far out the canvas reaches from the heart's centre, in heart sizes: the sparks' fall. */
export const REACH = 1.5;

/** The spin, in radians a second (clockwise on screen). */
const SPIN = 10;
/** The pull on a spark, in heart sizes a second squared, down the page. */
const GRAVITY = 2.6;

/** A small seeded generator, so the burst is the same every time and in every still. */
function seeded(seed: number) {
  let a = seed;
  return () => {
    a = (a + 0x6d2b79f5) | 0;
    let x = Math.imul(a ^ (a >>> 15), 1 | a);
    x = (x + Math.imul(x ^ (x >>> 7), 61 | x)) ^ x;
    return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
  };
}

const random = seeded(23);

/** The arcs of fire that race round the ring. */
const ARCS = Array.from({ length: 150 }, (_, i) => ({
  angle: (i / 150) * Math.PI * 2 + random() * 0.2,
  length: 0.12 + random() * 0.42,
  width: 0.006 + random() * 0.016,
  offset: (random() - 0.5) * 0.12,
  /** Each arc also drifts a little against or ahead of the ring. */
  drift: (random() - 0.5) * 2.4,
  phase: random() * Math.PI * 2,
  heat: random(),
}));

type Spark = {
  born: number;
  angle: number;
  speed: number;
  out: number;
  life: number;
  width: number;
};

/** The sparks thrown while the ring spins, then the last ring of them as it closes. */
const SPARKS: Spark[] = [
  ...Array.from({ length: 320 }, () => ({
    born: 60 + random() * (CLOSE_MS - 30),
    angle: random() * Math.PI * 2,
    speed: 1.3 + random() * 1.7,
    out: 0.1 + random() * 0.6,
    life: 200 + random() * 300,
    width: 0.011 + random() * 0.017,
  })),
  ...Array.from({ length: 64 }, (_, i) => ({
    born: CLOSE_MS + 40 + random() * 70,
    angle: (i / 64) * Math.PI * 2 + random() * 0.1,
    speed: 2.2 + random() * 1.4,
    out: 0.6 + random() * 0.9,
    life: 240 + random() * 200,
    width: 0.01 + random() * 0.014,
  })),
];

const clamp = (x: number) => Math.min(1, Math.max(0, x));
const between = (t: number, from: number, to: number) => clamp((t - from) / (to - from));
const easeIn = (x: number) => x * x * x;
/** Out with a small overshoot, for the ring opening. */
const easeOutBack = (x: number) => 1 + 2.2 * (x - 1) ** 3 + 1.2 * (x - 1) ** 2;

/** The ring's radius at `t`, in heart sizes: it opens to 0.8, spins, then closes to 0.3. */
function ringRadius(t: number) {
  const open = easeOutBack(between(t, 0, 220));
  const close = easeIn(between(t, CLOSE_MS, CLOSE_MS + 240));
  return 0.3 + 0.5 * open - 0.5 * close;
}

/** Where the spin has turned to at `t`: fast at once, slowing a little as it closes. */
const turnAt = (t: number) => (SPIN * t) / 1000 - 1.2 * easeIn(between(t, CLOSE_MS, BURST_MS));

/** Where a spark is `age` ms after its birth, in heart sizes from the heart's centre. */
function sparkAt(spark: Spark, age: number) {
  const a = spark.angle + turnAt(spark.born);
  const r = ringRadius(spark.born);
  const x0 = Math.cos(a) * r;
  const y0 = Math.sin(a) * r;
  // Along the spin (clockwise on screen, so the tangent is (-sin, cos)), a little outward.
  const vx = -Math.sin(a) * spark.speed + Math.cos(a) * spark.out;
  const vy = Math.cos(a) * spark.speed + Math.sin(a) * spark.out;
  const s = age / 1000;
  return [x0 + vx * s, y0 + vy * s + (GRAVITY * s * s) / 2] as const;
}

/** Paints the burst at `t` ms on a canvas whose origin is the heart's centre, `s` px wide. */
export function drawBurst(ctx: CanvasRenderingContext2D, t: number, s: number, palette: Palette) {
  if (t < 0 || t > BURST_MS) return;
  ctx.save();
  ctx.globalCompositeOperation = palette.blend;
  ctx.lineCap = 'round';

  const r = ringRadius(t) * s;
  const turn = turnAt(t);
  const ring = between(t, 0, 60) * (1 - between(t, CLOSE_MS + 120, CLOSE_MS + 250));
  // A flicker: the ring's strength wavers a little, frame to frame, as fire does.
  const flicker = 0.85 + 0.15 * Math.sin(t * 0.09) * Math.sin(t * 0.037 + 1);

  if (ring > 0) {
    // The glow: a soft band of orange on both sides of the ring.
    const glow = ctx.createRadialGradient(0, 0, r * 0.62, 0, 0, r * 1.38);
    glow.addColorStop(0, palette.clear);
    glow.addColorStop(0.42, palette.glow);
    glow.addColorStop(1, palette.clear);
    ctx.globalAlpha = ring * flicker;
    ctx.fillStyle = glow;
    ctx.beginPath();
    ctx.arc(0, 0, r * 1.38, 0, Math.PI * 2);
    ctx.fill();

    // The core: a thin white-hot line under the fire.
    ctx.globalAlpha = ring * 0.7 * flicker;
    ctx.strokeStyle = palette.core;
    ctx.lineWidth = Math.max(0.8, s * 0.014);
    ctx.beginPath();
    ctx.arc(0, 0, r, 0, Math.PI * 2);
    ctx.stroke();

    // The fire: short arcs racing round, hottest at their heads, each wavering on its radius.
    for (const arc of ARCS) {
      const head = arc.angle + turn + (arc.drift * t) / 1000;
      const wobble = Math.sin(t * 0.03 + arc.phase) * 0.025;
      const rr = r * (1 + arc.offset + wobble);
      const tail = head - arc.length;
      const gradient = ctx.createLinearGradient(
        Math.cos(head) * rr,
        Math.sin(head) * rr,
        Math.cos(tail) * rr,
        Math.sin(tail) * rr,
      );
      gradient.addColorStop(0, palette.core);
      gradient.addColorStop(0.3, palette.fire);
      gradient.addColorStop(1, palette.clear);
      ctx.strokeStyle = gradient;
      ctx.globalAlpha = ring * (0.45 + 0.55 * arc.heat) * flicker;
      ctx.lineWidth = Math.max(0.6, arc.width * s);
      ctx.beginPath();
      ctx.arc(0, 0, rr, tail, head);
      ctx.stroke();
    }
  }

  // The sparks: each a streak from where it was 70 ms ago to where it is, cooling from
  // white to red and fading as it falls.
  for (const spark of SPARKS) {
    const age = t - spark.born;
    if (age <= 0 || age >= spark.life) continue;
    const k = age / spark.life;
    const [hx, hy] = sparkAt(spark, age);
    const [tx, ty] = sparkAt(spark, Math.max(0, age - 70));
    const gradient = ctx.createLinearGradient(hx * s, hy * s, tx * s, ty * s);
    gradient.addColorStop(0, k < 0.4 ? palette.core : palette.fire);
    gradient.addColorStop(1, palette.clear);
    ctx.globalAlpha = 1 - easeIn(k);
    ctx.strokeStyle = k < 0.7 ? gradient : palette.ember;
    ctx.lineWidth = Math.max(0.6, spark.width * s * (1 - 0.5 * k));
    ctx.beginPath();
    ctx.moveTo(tx * s, ty * s);
    ctx.lineTo(hx * s, hy * s);
    ctx.stroke();
  }

  ctx.restore();
}
```

### like-burst/demo-pointer.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import type { CSSProperties, Ref } from 'react';

/*
 * The demo's pointer, and the steps that move it. A demo is a script of awaited steps: wait, or
 * glide the pointer somewhere. Stopping the demo (the reader takes over, or it scrolls away) ends
 * the step in progress at once: its promise rejects, which ends the script right there, and the
 * pointer fades out.
 *
 * Each glide is a curved flight played by the Web Animations API, so nothing runs frame by frame.
 * The points of the flight are handed to whoever wants to move along with it (nothing here uses
 * them yet). The arrow and the text cursor are HTML boxes
 * that swap by their visibility: a change of style inside an SVG would lay the SVG out again.
 */

export type Point = { x: number; y: number };

/** A glide's path and timing, for an animation that plays along with it. */
export type Flight = { points: Point[]; timing: KeyframeAnimationOptions };

export type Demo = {
  /** Resolves after `ms`. */
  wait: (ms: number) => Promise<void>;
  /** Glides the pointer to `to`, in the stage's own px, in `ms`; `along` gets the flight. */
  glide: (to: Point, ms: number, along?: (flight: Flight) => void) => Promise<void>;
  /** Shows the arrow, or the text cursor a field shows. */
  glyph: (name: 'arrow' | 'text') => void;
};

/** What a stopped demo's pending step rejects with. */
class Stopped extends Error {}

/** Where the arrow's tip is, as shares of its box: the point the pointer stands on. */
const TIP: Point = { x: 0.15, y: 0.1 };

/** How many points a flight is drawn through. */
const SAMPLES = 24;

/** Plays `script` with the pointer over `stage`; returns the function that stops it. */
export function runDemo(
  stage: HTMLElement,
  pointer: HTMLElement,
  script: (demo: Demo) => Promise<void>,
): () => void {
  let alive = true;
  let flight: Animation | null = null;
  // The stylesheet sizes the pointer from the stage's width; its tip is where it stands.
  const tip = { x: pointer.offsetWidth * TIP.x, y: pointer.offsetHeight * TIP.y };
  const place = ({ x, y }: Point) => `translate(${x - tip.x}px, ${y - tip.y}px)`;
  const timers = new Set<number>();
  const pending = new Set<() => void>();
  // The pointer comes in from the lower right.
  let at: Point = { x: stage.offsetWidth * 0.8, y: stage.offsetHeight * 0.9 };

  /** Settles like `promise`, or rejects as soon as the demo stops. */
  const step = (promise: Promise<unknown>) =>
    new Promise<void>((resolve, reject) => {
      if (!alive) return reject(new Stopped());
      const cancel = () => reject(new Stopped());
      pending.add(cancel);
      promise.then(
        () => {
          pending.delete(cancel);
          if (alive) resolve();
        },
        () => {
          pending.delete(cancel);
          reject(new Stopped());
        },
      );
    });

  const wait = (ms: number) =>
    step(
      new Promise<void>((resolve) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          resolve();
        }, ms);
        timers.add(timer);
      }),
    );

  const glide: Demo['glide'] = (to, ms, along) => {
    const from = at;
    at = to;
    const dx = to.x - from.x;
    const dy = to.y - from.y;
    // A gentle curve, as a hand moves: the control point sits off the straight line.
    const bend = { x: (from.x + to.x) / 2 - dy * 0.18, y: (from.y + to.y) / 2 + dx * 0.18 };
    const points: Point[] = [];
    for (let i = 0; i <= SAMPLES; i += 1) {
      const t = i / SAMPLES;
      const u = 1 - t;
      points.push({
        x: u * u * from.x + 2 * u * t * bend.x + t * t * to.x,
        y: u * u * from.y + 2 * u * t * bend.y + t * t * to.y,
      });
    }
    const timing: KeyframeAnimationOptions = {
      duration: ms,
      easing: 'cubic-bezier(0.45, 0, 0.25, 1)',
    };
    flight?.cancel();
    // Where it rests once the flight is over.
    pointer.style.transform = place(to);
    flight = pointer.animate(
      points.map((point) => ({ transform: place(point) })),
      timing,
    );
    along?.({ points, timing });
    return step(flight.finished);
  };

  const glyph: Demo['glyph'] = (name) => {
    pointer.dataset.glyph = name;
  };

  pointer.dataset.glyph = 'arrow';
  pointer.style.transform = place(at);
  pointer.style.opacity = '1';
  script({ wait, glide, glyph }).catch((error: unknown) => {
    if (!(error instanceof Stopped)) throw error;
  });

  return () => {
    if (!alive) return;
    alive = false;
    timers.forEach((timer) => window.clearTimeout(timer));
    flight?.cancel();
    pending.forEach((cancel) => cancel());
    pointer.style.opacity = '0';
  };
}

/**
 * The pointer's box: it moves, on a layer of its own. Its size comes from its class, its colours
 * from the stage's tokens (like-burst.module.css).
 */
const POINTER: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  zIndex: 2,
  display: 'block',
  pointerEvents: 'none',
  opacity: 0,
  transition: 'opacity 0.3s ease',
  filter: 'drop-shadow(0 1px 1.5px var(--pointer-shadow))',
  willChange: 'transform',
};

/** One glyph over the other, each filling the box. */
const GLYPH: CSSProperties = { position: 'absolute', inset: 0, display: 'block' };
const DRAWING: CSSProperties = {
  display: 'block',
  width: '100%',
  height: '100%',
  overflow: 'visible',
};
/** The arrow is dark on a white edge, and so is the text cursor: a dark line over a wider white one. */
const ARROW: CSSProperties = { fill: 'var(--pointer)', stroke: 'var(--pointer-edge)' };
const BEAM = 'M7 3c1.8 0 3 .7 3 2v10c0 1.3-1.2 2-3 2M13 3c-1.8 0-3 .7-3 2v10c0 1.3 1.2 2 3 2';

/**
 * The pointer the demo moves around: an arrow, or a text cursor over a field. It is
 * decorative: what it does shows on the control itself. The stylesheet shows one glyph at a time,
 * from the box's data-glyph.
 */
export function DemoPointer({
  ref,
  className,
  arrowClass,
  textClass,
}: {
  ref: Ref<HTMLSpanElement>;
  className?: string;
  arrowClass?: string;
  textClass?: string;
}) {
  return (
    <span ref={ref} className={className} style={POINTER} aria-hidden="true">
      <span className={arrowClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          <path
            d="M3 2v14.5l3.6-3.3 2.6 5.6 2.4-1.1-2.6-5.5h5.2z"
            style={ARROW}
            strokeWidth="1.3"
            strokeLinejoin="round"
          />
        </svg>
      </span>
      <span className={textClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          {/* The middle of the cursor sits where the arrow's tip is. */}
          <g fill="none" strokeLinecap="round" transform="translate(-7 -8)">
            <path d={BEAM} stroke="var(--pointer-edge)" strokeWidth="3" />
            <path d={BEAM} stroke="var(--pointer)" strokeWidth="1.3" />
          </g>
        </svg>
      </span>
    </span>
  );
}
```

### like-burst/use-autoplay.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';

/*
 * When a demo may play on its own: while part of it is on screen and the tab is visible, never
 * under reduced motion, and never again once the reader has used it: `take()` hands it to the
 * reader for good (until the component mounts again), so it can't come back on its own.
 */
export function useAutoplay<T extends HTMLElement>() {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    let onScreen = false;
    const update = () => setVisible(onScreen && !document.hidden);
    const observer = new IntersectionObserver(
      ([entry]) => {
        onScreen = entry.isIntersecting;
        update();
      },
      { threshold: 0.3 },
    );
    observer.observe(element);
    document.addEventListener('visibilitychange', update);
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const readMotion = () => setReduced(motion.matches);
    readMotion();
    motion.addEventListener('change', readMotion);
    return () => {
      observer.disconnect();
      document.removeEventListener('visibilitychange', update);
      motion.removeEventListener('change', readMotion);
    };
  }, []);

  const take = useCallback(() => setTaken(true), []);

  return { ref, take, playing: visible && !reduced && !taken };
}
```