SunUI
Founding$79 lifetime updates till Jan 11Claim a seat
FreeAnimePress

Anime Hold to Confirm

A button you press and hold to confirm something you cannot undo.

When to use it

  • Destructive or irreversible actions: delete a save, leave a guild, cancel an order
  • A sign-up or claim that should never happen by accident, such as pre-registering or redeeming a code

Watch out

  • Pass a hint that says to hold; screen readers read it with the label
  • Keep duration between about 0.8 and 2 seconds; longer feels broken
  • Return false from onConfirm when the action cannot go through (an invalid form), so it does not detonate
  • With reduced motion no effect is drawn; the trace, the squash and the state still work

Let your agent add it

One copy holds the install command, when to use it, the props and the design rules. Paste it into Claude Code, Cursor or Codex.

Install with the CLI

Uses the shadcn CLI. The source is copied into your project, so you own every line.

$ npx shadcn@latest add https://sunui.synvize.com/r/anime-hold.json

Or install manually

  1. 1. Install the dependencies.
    $ npm install clsx tailwind-merge
  2. 2. Add a cn helper at lib/utils.ts if you do not have one. Not using shadcn/ui? Also add sunui-theme.css for the colour tokens (how). Then copy the component.
    anime-hold.tsx
    "use client";
    
    import { useEffect, useId, useRef, useState, type ReactNode } from "react";
    
    import { at, burst, calm, later, onFrame, paletteOf, puff, sfx, shards, Spring, ticks, useBackLayer, type SfxLang } from "@/components/ui/anime-fx";
    import { cn } from "@/lib/utils";
    
    export type AnimeHoldProps = {
      /** The label, also the accessible name */
      children: ReactNode;
      /**
       * Called once when the hold completes. Return false when it cannot go through (a form that fails validation):
       * there is no detonation, the trace springs back and the button shakes its head.
       */
      onConfirm?: () => boolean | void;
      /** How long to hold, in milliseconds */
      duration?: number;
      /** Shown after it confirms, with a check */
      doneLabel?: ReactNode;
      /** Back to idle this many milliseconds after confirming; 0 stays confirmed */
      resetAfter?: number;
      /** Read out by screen readers with the label, so people know to hold */
      hint?: string;
      /** Read out when it confirms */
      confirmedText?: string;
      disabled?: boolean;
      /** Lettering language; defaults to <html lang> */
      lang?: SfxLang;
      /** Show the sound-effect words (the rumble while held, the impact at the end) */
      lettering?: boolean;
      className?: string;
    };
    
    const SHELL = "border-[3px] border-foreground bg-card text-foreground shadow-[4px_5px_0_color-mix(in_oklch,var(--sunui-spot,var(--primary))_38%,var(--card))]";
    
    /**
     * A button you press and hold to confirm something you cannot undo. While held, an ink line traces round its edge (the trace is
     * the progress, so it reads without effects), the button flattens under the pressure and starts to tremble, and a rumble word
     * rises. At 100% it inverts for a frame and detonates: an impact star behind it, chips from its edge, the impact word.
     * Let go early and the trace springs back. Space and Enter hold it from the keyboard.
     */
    export function AnimeHold({
      children,
      onConfirm,
      duration = 1200,
      doneLabel,
      resetAfter = 2400,
      hint = "Press and hold to confirm",
      confirmedText = "Confirmed",
      disabled,
      lang,
      lettering = true,
      className,
    }: AnimeHoldProps) {
      const ref = useRef<HTMLButtonElement>(null);
      const trace = useRef<SVGRectElement>(null);
      const back = useBackLayer(130);
      const hintId = useId();
      const [done, setDone] = useState(false);
      const [inverted, setInverted] = useState(false);
      const st = useRef({ p: new Spring(0, 140, 16), holding: false, t: 0, rumbled: false, pulled: false, shake: 0, off: null as null | (() => void), seq: 0 });
      const fire = useRef(onConfirm);
      fire.current = onConfirm;
    
      const draw = () => {
        const el = ref.current;
        const s = st.current;
        const p = Math.max(0, s.p.x);
        trace.current?.setAttribute("stroke-dashoffset", String(1 - Math.min(1, p)));
        // A round cap leaves a dot at zero length, so hide the trace when it is empty
        trace.current?.setAttribute("visibility", p > 0.002 ? "visible" : "hidden");
        if (!el) return;
        // Pressure: flatter and wider (volume kept); past 60% it trembles
        const y = 1 - 0.12 * Math.min(1, p);
        const shake = s.holding && p > 0.6 && !calm() ? Math.sin(s.t * 70) * 0.9 * (p - 0.6) * 2.5 : 0;
        // A refused hold shakes side to side, like shaking a head
        const no = s.shake > 0 ? Math.sin(s.shake * 42) * 7 * (s.shake / 0.45) : 0;
        el.style.transform = p < 0.002 && !s.holding && !no ? "" : `translateX(${no.toFixed(2)}px) rotate(${shake.toFixed(2)}deg) scale(${(1 + (1 - y) * 0.5).toFixed(4)}, ${y.toFixed(4)})`;
      };
    
      const run = () => {
        const s = st.current;
        if (s.off) return;
        s.off = onFrame((dt) => {
          s.t += dt;
          if (s.holding) {
            // Linear while held, so the trace is an honest timer
            s.p.x = Math.min(1, s.p.x + (dt * 1000) / duration);
            s.p.v = 0;
            s.p.to = s.p.x;
            beats();
            if (s.p.x >= 1) confirm();
          } else s.p.step(dt);
          s.shake = Math.max(0, s.shake - dt);
          draw();
          if (!s.holding && s.p.still && !s.shake) {
            s.off?.();
            s.off = null;
            draw();
          }
        });
      };
    
      // Anticipation beats: a rumble word at a third, wedges pulled inward at two thirds
      const beats = () => {
        const el = ref.current;
        const s = st.current;
        if (!el) return;
        const P = paletteOf(el);
        const c = at(el);
        if (!s.rumbled && s.p.x > 0.33) {
          s.rumbled = true;
          // Beside the button on its own row, not above it: whatever sits above (a title, a warning) stays readable
          if (lettering) sfx(P, "rumble", c.x + c.w / 2 + 62, c.y, { size: 44, lang, rot: -0.1, life: Math.max(0.6, (duration / 1000) * 0.7) });
        }
        if (!s.pulled && s.p.x > 0.66) {
          s.pulled = true;
          // Gravity: wedges and dust are drawn toward the button
          for (const a of [-2.6, -0.5, 2.5, 0.6]) ticks(P, c.x + Math.cos(a) * (c.w / 2 + 34), c.y + Math.sin(a) * (c.h / 2 + 30), { dir: a + Math.PI, n: 2, r: 2, len: 14, life: 0.35 });
        }
      };
    
      const confirm = () => {
        const el = ref.current;
        const s = st.current;
        if (!el) return;
        s.holding = false;
        if (fire.current?.() === false) {
          // Refused: no hit. The trace springs back and the button shakes no
          s.p.to = 0;
          s.shake = calm() ? 0 : 0.45;
          return;
        }
        s.p.x = 1;
        s.p.to = 1;
        s.p.v = 0;
        const n = ++s.seq;
        setDone(true);
        // The hit: invert for about a frame, pop past full size
        setInverted(true);
        later(180, () => n === s.seq && setInverted(false));
        const P = paletteOf(el);
        const c = at(el);
        burst(P, c.x, c.y, { r: Math.max(80, c.w * 0.8), spikes: 16, life: 0.5, layer: back.layer() });
        for (let i = 0; i < 12; i++) {
          const a = (i / 12) * Math.PI * 2 + Math.random() * 0.4;
          shards(P, c.x + Math.cos(a) * (c.w / 2 + 6), c.y + Math.sin(a) * (c.h / 2 + 6), { n: 1, dir: a, arc: 0.5, speed: 270, size: 8, life: 0.9 });
        }
        for (const dx of [-1, 1]) puff(P, c.x + dx * (c.w / 2 + 6), c.y + c.h / 2, { size: 13, vx: dx * 50, vy: -20, life: 0.85 });
        if (lettering) sfx(P, "impact", c.x + 6, c.y - c.h / 2 - 50, { size: 92, lang });
        // The trace stays full while confirmed
        if (resetAfter > 0) later(resetAfter, () => n === s.seq && reset());
        // State must not wait on the effect clock, which stops in hidden tabs
        if (resetAfter > 0) window.setTimeout(() => n === s.seq && reset(), resetAfter + 400);
      };
    
      const reset = () => {
        const s = st.current;
        s.seq++;
        s.rumbled = s.pulled = false;
        s.p.to = 0;
        setDone(false);
        run();
      };
    
      const press = () => {
        const s = st.current;
        if (disabled || done || s.holding) return;
        s.holding = true;
        s.rumbled = s.pulled = false;
        s.p.x = Math.max(0, s.p.x);
        run();
      };
    
      const release = () => {
        const s = st.current;
        if (!s.holding) return;
        s.holding = false;
        // Let go early: the trace springs back with a little overshoot
        s.p.to = 0;
        run();
      };
    
      // Fit the trace to the button (SVG rects take no calc), so it follows any size the label gives it
      useEffect(() => {
        const el = ref.current;
        const r = trace.current;
        if (!el || !r) return;
        const fit = () => {
          r.setAttribute("width", String(el.offsetWidth + 14 - 3.5));
          r.setAttribute("height", String(el.offsetHeight + 14 - 3.5));
        };
        fit();
        const ro = new ResizeObserver(fit);
        ro.observe(el);
        return () => ro.disconnect();
      }, []);
    
      useEffect(() => {
        const s = st.current;
        return () => {
          s.off?.();
          s.off = null;
        };
      }, []);
    
      return (
        <span className="relative inline-block isolate">
          <canvas {...back.props} />
          <button
            ref={ref}
            type="button"
            disabled={disabled}
            aria-describedby={hintId}
            onPointerDown={(e) => {
              if (e.button !== 0) return;
              // Keep the hold when the finger drifts off the button; capture can throw for a pointer that is already gone
              try {
                e.currentTarget.setPointerCapture(e.pointerId);
              } catch {}
              press();
            }}
            onPointerUp={release}
            onPointerCancel={release}
            onLostPointerCapture={release}
            onKeyDown={(e) => {
              if ((e.key === " " || e.key === "Enter") && !e.repeat) {
                e.preventDefault();
                press();
              }
            }}
            onKeyUp={(e) => {
              if (e.key === " " || e.key === "Enter") release();
            }}
            onBlur={release}
            onContextMenu={(e) => e.preventDefault()}
            className={cn(
              "relative inline-flex items-center justify-center gap-1.5 rounded-[14px] px-6 py-3 text-[17px] leading-none font-extrabold italic will-change-transform select-none touch-none [-webkit-touch-callout:none]",
              "outline-none focus-visible:ring-[3px] focus-visible:ring-[var(--sunui-spot,var(--primary))] focus-visible:ring-offset-2 focus-visible:ring-offset-background",
              "disabled:cursor-not-allowed disabled:opacity-45",
              SHELL,
              inverted && "bg-foreground text-background shadow-none",
              className,
            )}
          >
            {/* The trace: an ink line round the edge, as long as the hold so far */}
            <svg aria-hidden className="pointer-events-none absolute -inset-[7px] size-[calc(100%+14px)] overflow-visible">
              <rect
                ref={trace}
                x="1.75"
                y="1.75"
                rx="19"
                fill="none"
                stroke="var(--sunui-spot, var(--primary))"
                strokeWidth={3.5}
                pathLength={1}
                strokeDasharray={1}
                strokeDashoffset={1}
                strokeLinecap="round"
                visibility="hidden"
              />
            </svg>
            <span>{done && doneLabel ? doneLabel : children}</span>
            <svg viewBox="0 0 24 18" aria-hidden className="h-[15px] overflow-visible transition-[width] duration-200" style={{ width: done ? 18 : 0 }}>
              <path
                d="M3 9.5l6 6L21 2.5"
                fill="none"
                stroke="var(--sunui-success, currentColor)"
                strokeWidth={4}
                strokeLinecap="round"
                strokeLinejoin="round"
                pathLength={1}
                strokeDasharray={1}
                strokeDashoffset={done ? 0 : 1}
                style={{ transition: "stroke-dashoffset 260ms cubic-bezier(.2,.8,.2,1)" }}
              />
            </svg>
          </button>
          <span id={hintId} className="sr-only">
            {hint}
          </span>
          <span role="status" aria-live="polite" className="sr-only">
            {done ? confirmedText : ""}
          </span>
        </span>
      );
    }