Reaction toggle

A pill toggle for liking, saving, starring and following, with a count that rolls. Turning it on pops the icon and throws a small burst of dots and strokes; the number rolls up or down through a two-row swap. Like fills rose, save fills amber and becomes Saved, star fills with the primary colour, and follow changes to a quieter outlined Following pill. Rapid repeat clicks settle into a single change event, and a long press (or Alt+Arrow) opens an optional tray of alternative reactions that the pill then shows. It reports its pressed state and count to screen readers, the tray is a keyboard menu that returns focus when closed, and reduced motion just switches the fill.

ButtonsComponentTailwind v4

Source

"use client";

import {
  useEffect, useId, useRef, useState,
  type ComponentType, type KeyboardEvent, type ReactNode, type SVGProps,
} from "react";
import { Bookmark, Heart, Star, UserCheck, UserPlus } from "lucide-react";
import { cn } from "@/lib/utils";

type Preset = "like" | "save" | "star" | "follow";
type Icon = ComponentType<SVGProps<SVGSVGElement> & { strokeWidth?: number | string }>;

export type Reaction = { id: string; icon: ReactNode; label: string };

export type ReactionToggleProps = {
  preset?: Preset;
  pressed?: boolean;
  defaultPressed?: boolean;
  /** Fires once after rapid clicks settle, with the final state. */
  onPressedChange?: (pressed: boolean, reaction?: Reaction) => void;
  /** The total as of the initial pressed state; it moves by one as the viewer toggles. */
  count?: number;
  formatCount?: (count: number) => string;
  /** Alternatives offered by a long press (or Alt+Arrow keys) on the pill. */
  reactions?: Reaction[];
  size?: "sm" | "md";
  showLabel?: boolean;
  className?: string;
};

const PRESETS: Record<Preset, { icon: Icon; activeIcon?: Icon; label: string; activeLabel: string; active: string; fill: boolean }> = {
  like: {
    icon: Heart, label: "Like", activeLabel: "Liked", fill: true,
    active: "border-rose-500/35 bg-rose-500/10 text-rose-600 dark:border-rose-400/35 dark:bg-rose-400/12 dark:text-rose-400",
  },
  save: {
    icon: Bookmark, label: "Save", activeLabel: "Saved", fill: true,
    active: "border-amber-500/40 bg-amber-500/12 text-amber-700 dark:border-amber-400/35 dark:bg-amber-400/12 dark:text-amber-300",
  },
  star: {
    icon: Star, label: "Star", activeLabel: "Starred", fill: true,
    active: "border-primary/35 bg-primary/10 text-primary",
  },
  follow: {
    icon: UserPlus, activeIcon: UserCheck, label: "Follow", activeLabel: "Following", fill: false,
    active: "border-border bg-transparent text-foreground",
  },
};

const DEBOUNCE_MS = 320;
const LONG_PRESS_MS = 500;

const CSS = `@keyframes chm-rt-pop{0%{transform:scale(1)}45%{transform:scale(1.25)}100%{transform:scale(1)}}
@keyframes chm-rt-fly{0%{transform:translateY(-5px) scale(1);opacity:1}100%{transform:translateY(-17px) scale(.4);opacity:0}}
@keyframes chm-rt-up{from{transform:translateY(0)}to{transform:translateY(-50%)}}
@keyframes chm-rt-down{from{transform:translateY(-50%)}to{transform:translateY(0)}}
@keyframes chm-rt-tray{from{opacity:0;transform:translateY(4px) scale(.96)}to{opacity:1;transform:none}}
.chm-rt-burst{display:none}
@media (prefers-reduced-motion:no-preference){
.chm-rt-pop{animation:chm-rt-pop .35s cubic-bezier(.3,1.5,.5,1)}
.chm-rt-burst{display:block}
.chm-rt-burst g>*{animation:chm-rt-fly .45s cubic-bezier(.2,.7,.3,1) both}
.chm-rt-roll-up{animation:chm-rt-up .28s cubic-bezier(.3,1.2,.5,1) both}
.chm-rt-roll-down{animation:chm-rt-down .28s cubic-bezier(.3,1.2,.5,1) both}
.chm-rt-tray{animation:chm-rt-tray .16s ease-out}
}`;

const compact = (n: number) => new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }).format(n);

function Burst() {
  // Ten particles around the icon: dots and short strokes, alternating, each on its own spoke.
  return (
    <svg aria-hidden="true" viewBox="-24 -24 48 48" className="chm-rt-burst pointer-events-none absolute left-1/2 top-1/2 size-12 -translate-x-1/2 -translate-y-1/2 overflow-visible">
      {Array.from({ length: 10 }, (_, i) => (
        <g key={i} transform={`rotate(${i * 36 + (i % 2 ? 8 : 0)})`}>
          {i % 2 ? (
            <line x1="0" y1="0" x2="0" y2="-4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" style={{ animationDelay: "30ms" }} />
          ) : (
            <circle r="1.6" fill="currentColor" />
          )}
        </g>
      ))}
    </svg>
  );
}

function RollingCount({ value, format }: { value: number; format: (n: number) => string }) {
  const [shown, setShown] = useState({ now: value, before: value, dir: 0, key: 0 });
  useEffect(() => {
    setShown((s) => (s.now === value ? s : { now: value, before: s.now, dir: value > s.now ? 1 : -1, key: s.key + 1 }));
  }, [value]);
  if (shown.dir === 0) return <span className="tabular-nums">{format(shown.now)}</span>;
  const up = shown.dir > 0;
  const rows = up ? [shown.before, shown.now] : [shown.now, shown.before];
  return (
    <span className="relative inline-flex h-[1lh] overflow-hidden tabular-nums">
      <span
        key={shown.key}
        className={cn("flex flex-col", up ? "chm-rt-roll-up -translate-y-1/2" : "chm-rt-roll-down translate-y-0")}
      >
        {rows.map((n, i) => <span key={i} className="block h-[1lh] text-right">{format(n)}</span>)}
      </span>
    </span>
  );
}

export function ReactionToggle({
  preset = "like", pressed: pressedProp, defaultPressed = false, onPressedChange, count, formatCount = compact,
  reactions, size = "md", showLabel = true, className,
}: ReactionToggleProps) {
  const config = PRESETS[preset];
  const [on, setOn] = useState(pressedProp ?? defaultPressed);
  const [reaction, setReaction] = useState<Reaction | undefined>(undefined);
  const [pop, setPop] = useState(0);
  const [trayOpen, setTrayOpen] = useState(false);
  const initial = useRef(pressedProp ?? defaultPressed);
  const committed = useRef(on);
  const debounce = useRef<number | undefined>(undefined);
  const longPress = useRef<number | undefined>(undefined);
  const suppressClick = useRef(false);
  const trigger = useRef<HTMLButtonElement>(null);
  const items = useRef<(HTMLButtonElement | null)[]>([]);
  const root = useRef<HTMLDivElement>(null);
  const trayId = useId();

  // A controlled value from outside wins once it changes.
  useEffect(() => {
    if (pressedProp !== undefined) { setOn(pressedProp); committed.current = pressedProp; }
  }, [pressedProp]);
  useEffect(() => () => { window.clearTimeout(debounce.current); window.clearTimeout(longPress.current); }, []);

  function schedule(next: boolean, chosen?: Reaction) {
    window.clearTimeout(debounce.current);
    debounce.current = window.setTimeout(() => {
      if (next !== committed.current || chosen) { committed.current = next; onPressedChange?.(next, chosen); }
    }, DEBOUNCE_MS);
  }

  function toggle() {
    const next = !on;
    setOn(next);
    if (next) setPop((n) => n + 1);
    else setReaction(undefined);
    schedule(next, next ? reaction : undefined);
  }

  function choose(r: Reaction) {
    setReaction(r);
    if (!on) setPop((n) => n + 1);
    setOn(true);
    schedule(true, r);
    closeTray();
  }

  function openTray() {
    if (!reactions?.length) return;
    setTrayOpen(true);
    requestAnimationFrame(() => items.current[Math.max(0, reactions.findIndex((r) => r.id === reaction?.id))]?.focus());
  }
  function closeTray(returnFocus = true) {
    setTrayOpen(false);
    if (returnFocus) trigger.current?.focus();
  }

  useEffect(() => {
    if (!trayOpen) return;
    const onDown = (event: PointerEvent) => { if (!root.current?.contains(event.target as Node)) closeTray(false); };
    document.addEventListener("pointerdown", onDown);
    return () => document.removeEventListener("pointerdown", onDown);
  }, [trayOpen]);

  function onTrayKey(event: KeyboardEvent<HTMLDivElement>) {
    const list = items.current.filter(Boolean) as HTMLButtonElement[];
    const index = list.indexOf(document.activeElement as HTMLButtonElement);
    const go = (i: number) => { event.preventDefault(); list[(i + list.length) % list.length]?.focus(); };
    if (event.key === "ArrowRight" || event.key === "ArrowDown") go(index + 1);
    else if (event.key === "ArrowLeft" || event.key === "ArrowUp") go(index - 1);
    else if (event.key === "Home") go(0);
    else if (event.key === "End") go(list.length - 1);
    else if (event.key === "Escape" || event.key === "Tab") { event.preventDefault(); closeTray(); }
  }

  const Icon = on && config.activeIcon ? config.activeIcon : config.icon;
  const label = on ? reaction?.label ?? config.activeLabel : config.label;
  const total = count === undefined ? undefined : count + (on ? 1 : 0) - (initial.current ? 1 : 0);
  const name = total === undefined ? config.label : `${config.label}, ${total.toLocaleString("en")}`;
  const follow = preset === "follow";
  const sm = size === "sm";

  return (
    <div ref={root} className={cn("relative inline-flex", className)}>
      <style href="chm-reaction-toggle" precedence="default">{CSS}</style>
      <button
        ref={trigger}
        type="button"
        aria-pressed={on}
        aria-label={reaction && on ? `${name}, reacted ${reaction.label}` : name}
        aria-haspopup={reactions?.length ? "menu" : undefined}
        aria-expanded={reactions?.length ? trayOpen : undefined}
        aria-controls={trayOpen ? trayId : undefined}
        onClick={() => { if (suppressClick.current) { suppressClick.current = false; return; } toggle(); }}
        onPointerDown={(event) => {
          if (!reactions?.length || event.button !== 0) return;
          window.clearTimeout(longPress.current);
          longPress.current = window.setTimeout(() => { suppressClick.current = true; openTray(); }, LONG_PRESS_MS);
        }}
        onPointerUp={() => window.clearTimeout(longPress.current)}
        onPointerLeave={() => window.clearTimeout(longPress.current)}
        onContextMenu={(event) => { if (reactions?.length) event.preventDefault(); }}
        onKeyDown={(event) => {
          if (reactions?.length && event.altKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
            event.preventDefault();
            openTray();
          }
        }}
        className={cn(
          "inline-flex select-none items-center rounded-full border font-medium outline-none",
          "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
          "motion-safe:transition-[background-color,border-color,color,transform] motion-safe:active:scale-95",
          sm ? "h-8 gap-1.5 px-3 text-xs" : "h-10 gap-2 px-4 text-sm",
          on
            ? config.active
            : follow
              ? "border-transparent bg-primary text-primary-foreground hover:bg-primary/90"
              : "border-border bg-background text-foreground hover:bg-accent",
        )}
      >
        <span className="relative grid place-items-center">
          {pop > 0 && on && config.fill && <Burst key={pop} />}
          <span key={pop} className={cn("grid place-items-center", pop > 0 && on && "chm-rt-pop")}>
            {reaction && on ? (
              <span aria-hidden="true" className={cn("grid place-items-center leading-none", sm ? "[&_svg]:size-3.5" : "[&_svg]:size-4")}>{reaction.icon}</span>
            ) : (
              <Icon
                aria-hidden="true"
                className={cn(sm ? "size-3.5" : "size-4", on && config.fill && "fill-current")}
                strokeWidth={2}
              />
            )}
          </span>
        </span>
        {showLabel && <span aria-hidden="true">{label}</span>}
        {total !== undefined && (
          <span aria-hidden="true" className={cn("flex items-center", showLabel && "border-l border-current/20 pl-2")}>
            <RollingCount value={total} format={formatCount} />
          </span>
        )}
      </button>

      {trayOpen && reactions?.length ? (
        <div
          id={trayId}
          role="menu"
          aria-label={`${config.label} reactions`}
          onKeyDown={onTrayKey}
          className="chm-rt-tray absolute bottom-full left-0 z-20 mb-2 flex gap-1 rounded-full border bg-popover p-1 text-popover-foreground shadow-lg"
        >
          {reactions.map((r, i) => (
            <button
              key={r.id}
              ref={(el) => { items.current[i] = el; }}
              type="button"
              role="menuitemradio"
              aria-checked={reaction?.id === r.id}
              aria-label={r.label}
              title={r.label}
              tabIndex={-1}
              onClick={() => choose(r)}
              className={cn(
                "grid size-9 place-items-center rounded-full outline-none [&_svg]:size-[18px] motion-safe:transition-transform",
                "hover:scale-110 hover:bg-accent focus-visible:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
                reaction?.id === r.id && "bg-accent",
              )}
            >
              {r.icon}
            </button>
          ))}
        </div>
      ) : null}
    </div>
  );
}