Skip to content
Browse documentation

Keep one of a batch of generations: your save runs, the others blow away in their own colours, and the one you kept grows into the space.

Used forImage generatorsLogo and icon makersProduct photo toolsAvatar apps

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/variant-pick.json

Registered the namespace? Then it’s shadcn add @hairline/variant-pick. Set it up

Templates

Need the whole page?

61 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 6 are free.

All 61 templates

Where it’s used

  • Image generators

    Pick the take to keep from a batch of four, the way Midjourney-style tools work.

  • Logo and icon makers

    Choose one of several marks before refining it.

  • Product photo tools

    Keep the background or the lighting that works.

  • Avatar apps

    Choose the portrait to use as a profile picture.

What it handles for you

Choosing from a batch is usually a click that adds a border, and the takes you didn’t want just sit there.

Instead of wiring upimage selection gridradio card groupframer-motion layout animationupscale picker
  1. Saves before it moves

    onPick runs first and the picker waits for it; if it throws, nothing goes and the reason shows under the grid.

  2. The rest really leave

    The takes you didn’t keep blow away (or shatter) in their own colours, so the choice is visible.

  3. The keeper takes the space

    The kept take grows into the grid in one 0.52s move, measured from layout, so it lands exactly.

  4. Choose again

    Plays it back: the winner returns to its place while the others gather back where they were.

  5. Controlled or not

    Use value and onValueChange, or defaultValue, so your app can hold the choice.

  6. Keyboard

    Arrow keys, Home and End move between takes; Enter or Space keeps one.

Overview

Image models return a batch, and the choice is the moment that matters. Variant pick lays two to four takes side by side; pick one and your onPick saves it while a small spinner sits on its corner. Once it resolves, the takes you didn’t keep blow away in their real colours (or shatter, if you prefer) and the one you kept grows into the space they left, in one move. Choose again plays it all back: the winner returns to its place and the others gather back where they were. If the save fails, nothing goes and the reason is shown. Arrow keys move between takes, Enter keeps one.

States

choosing
Two to four takes in a two-column grid; hover lifts the picture 3% inside its tile.
saving
A primary badge with a spinner on the picked take while onPick runs; the others are disabled.
kept
The others blow away (about 1s), then the keeper grows to fill the grid in 0.52s and carries a check. The line under it reads “Kept 2 of 4” with Choose again.
choosing again
The keeper returns to its cell while the others gather back, then the grid is open again.
save failed
Nothing moves; the error shows in red under the grid.
reduced motion
The others fade out and the keeper takes the space without travelling.

Usage

usage.tsx
import { VariantPick } from "@/components/variant-pick";<VariantPick  images={job.outputs.map((o) => ({ id: o.id, src: o.url, alt: job.prompt }))}  onPick={(id) => fetch(`/api/jobs/${job.id}/keep`, { method: "POST", body: id })}/>

Keeping one take and upscaling it

Save the choice, then start the upscale of the take you kept. The picker waits for onPick, so a failed save leaves the batch as it was.

example.tsx
"use client";import * as React from "react";import { VariantPick } from "@/components/variant-pick";type Output = { id: string; url: string };export function Batch({ jobId, prompt, outputs }: { jobId: string; prompt: string; outputs: Output[] }) {  const [kept, setKept] = React.useState<string | null>(null);  return (    <VariantPick      images={outputs.map((o, i) => ({ id: o.id, src: o.url, alt: `${prompt}, take ${i + 1}` }))}      value={kept}      onValueChange={setKept}      onPick={async (id) => {        const res = await fetch(`/api/jobs/${jobId}/keep`, { method: "POST", body: JSON.stringify({ id }) });        if (!res.ok) throw new Error("Couldn’t save your choice.");        fetch(`/api/jobs/${jobId}/upscale`, { method: "POST", body: JSON.stringify({ id }) });      }}      crossOrigin="anonymous"    />  );}

Props

images
{ id: string; src: string; alt: string }[]
Two to four takes. A new set (different ids) starts fresh.
value
string | null
The kept take’s id, controlled. null for none.
defaultValue= null
string | null
The kept take when uncontrolled.
onValueChange
(id: string | null) => void
Called with the kept id, or null after Choose again.
onPick
(id: string) => Promise<unknown> | void
Saves the choice. The picker waits for it; if it throws, nothing moves and the error’s message is shown.
away= "sand"
"sand" | "burn" | "shatter" | "drain"
How the takes you didn’t keep leave.
crossOrigin
"anonymous" | "use-credentials"
Set it when your image host sends CORS headers, so the grains carry the real colours.
labels
{ hint?, kept?, again?, failed? }
The line under the grid and its button.

Accessibility and motion

  • The takes are buttons with aria-pressed in a labelled group; one is in the tab order at a time and the arrow keys move between them.
  • The line under the grid is a polite live region: it says what was kept, or why the save failed.
  • The removals use the same engine as Sand away and friends, drawn in a layer over the page; the takes stay in the layout, hidden, so Choose again can bring them back.
  • Pictures from another origin need CORS (and crossOrigin) for their real colours; without it they are masked away in place.
  • Under reduced motion the others fade and the keeper takes the space without travelling.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

Source

"use client";/* ───────────────────────────────────────────────────────── * VARIANT PICK: keep one generation, let the rest go * * Two to four takes from one prompt, side by side. Pick one and * your onPick saves the choice (the picker waits for it); then * the takes you didn't keep blow away in their own colours and * the one you kept grows into the space they left. Choose again * plays it back: the winner returns to its place and the others * gather back. Arrow keys move between takes, Enter keeps one. * ───────────────────────────────────────────────────────── */import * as React from "react";import { Check, LoaderCircle, RotateCcw } from "lucide-react";import { playAway, undoAway, type GrainStyle } from "./image-grains";export interface VariantImage {  id: string;  src: string;  alt: string;}export interface VariantPickProps {  /** Two to four takes. */  images: VariantImage[];  /** The kept take's id (controlled), or null for none. */  value?: string | null;  defaultValue?: string | null;  onValueChange?: (id: string | null) => void;  /** Save the choice; the picker waits for it, and stays open with a message if it throws. */  onPick?: (id: string) => Promise<unknown> | void;  /** How the takes you didn't keep leave. */  away?: GrainStyle;  crossOrigin?: "anonymous" | "use-credentials";  labels?: { hint?: string; kept?: string; again?: string; failed?: string };  className?: string;}type Phase = "idle" | "saving" | "going" | "kept" | "returning";const EASE = "cubic-bezier(0.16, 1, 0.3, 1)";const GROW = 520;const reducedQuery = "(prefers-reduced-motion: reduce)";const subscribeReduced = (onChange: () => void) => {  const query = window.matchMedia(reducedQuery);  query.addEventListener("change", onChange);  return () => query.removeEventListener("change", onChange);};const useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);/** Where the winner sits when it fills the grid: as large as fits, centred, measured from layout (transforms ignored). */function fillTransform(tile: HTMLElement, grid: HTMLElement) {  const s = Math.min(grid.clientWidth / tile.offsetWidth, grid.clientHeight / tile.offsetHeight);  const x = (grid.clientWidth - tile.offsetWidth * s) / 2 - tile.offsetLeft;  const y = (grid.clientHeight - tile.offsetHeight * s) / 2 - tile.offsetTop;  return `translate(${x}px, ${y}px) scale(${s})`;}export function VariantPick({ images, value, defaultValue = null, onValueChange, onPick, away = "sand", crossOrigin, labels, className = "" }: VariantPickProps) {  const reduced = useReducedMotion();  const [own, setOwn] = React.useState<string | null>(defaultValue);  const kept = value !== undefined ? value : own;  const [phase, setPhase] = React.useState<Phase>(kept ? "kept" : "idle");  const [saving, setSaving] = React.useState<string | null>(null);  const [error, setError] = React.useState<string | null>(null);  const grid = React.useRef<HTMLDivElement>(null);  const tiles = React.useRef(new Map<string, HTMLElement>());  const applied = React.useRef<string | null>(kept);  const list = images.slice(0, 4);  // A new set of takes starts fresh.  const setKey = list.map((i) => i.id).join("|");  const [seenKey, setSeenKey] = React.useState(setKey);  if (setKey !== seenKey) {    setSeenKey(setKey);    setPhase(kept && list.some((i) => i.id === kept) ? "kept" : "idle");  }  // Plays whatever changed: keeping one, or choosing again.  React.useEffect(() => {    const from = applied.current;    if (from === kept) return;    applied.current = kept;    const box = grid.current;    let live = true;    const others = (id: string) => list.filter((i) => i.id !== id).map((i) => tiles.current.get(i.id) ?? null);    const run = async () => {      if (from) {        const winner = tiles.current.get(from);        if (live) setPhase("returning");        if (winner) {          winner.style.transition = reduced ? "none" : `transform ${GROW}ms ${EASE}`;          winner.style.transform = "";        }        await Promise.all(others(from).map((el) => undoAway(el)));        if (winner) winner.style.zIndex = "";      }      if (kept) {        if (live) setPhase("going");        await Promise.all(others(kept).map((el) => playAway(el, away)));        const winner = tiles.current.get(kept);        if (winner && box && live) {          winner.style.zIndex = "1";          winner.style.transition = reduced ? "none" : `transform ${GROW}ms ${EASE}`;          winner.style.transform = fillTransform(winner, box);        }      }      if (live) setPhase(kept ? "kept" : "idle");    };    run();    return () => {      live = false;    };    // `list` follows `setKey`.    // eslint-disable-next-line react-hooks/exhaustive-deps  }, [kept, away, reduced, setKey]);  const choose = async (id: string) => {    if (phase !== "idle") return;    setError(null);    if (onPick) {      setSaving(id);      setPhase("saving");      try {        await onPick(id);      } catch (e) {        setSaving(null);        setPhase("idle");        setError(e instanceof Error && e.message ? e.message : labels?.failed ?? "That choice wasn’t saved. Try again.");        return;      }      setSaving(null);    }    if (value === undefined) setOwn(id);    onValueChange?.(id);  };  const again = () => {    if (phase !== "kept") return;    if (value === undefined) setOwn(null);    onValueChange?.(null);  };  const move = (event: React.KeyboardEvent<HTMLButtonElement>, index: number) => {    const cols = 2;    const step = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: cols, ArrowUp: -cols, Home: -index, End: list.length - 1 - index }[event.key];    if (step === undefined) return;    event.preventDefault();    const next = list[Math.min(list.length - 1, Math.max(0, index + step))];    tiles.current.get(next.id)?.focus();  };  const keptImage = list.find((i) => i.id === kept);  return (    <div className={`flex [:where(&)]:w-full flex-col gap-3 ${className}`}>      <div ref={grid} role="group" aria-label={labels?.hint ?? "Pick the one to keep"} className="relative grid grid-cols-2 gap-2">        {list.map((image, index) => {          const isKept = kept === image.id;          const busy = saving === image.id;          return (            <button              key={image.id}              ref={(el) => {                if (el) tiles.current.set(image.id, el);                else tiles.current.delete(image.id);              }}              type="button"              aria-pressed={isKept}              aria-label={image.alt}              disabled={phase !== "idle" && !isKept}              tabIndex={phase === "kept" ? (isKept ? 0 : -1) : index === 0 ? 0 : -1}              onClick={() => choose(image.id)}              onKeyDown={(event) => move(event, index)}              className="group relative aspect-square origin-top-left cursor-pointer overflow-hidden rounded-[14px] bg-muted outline-none ring-offset-2 ring-offset-background focus-visible:ring-2 focus-visible:ring-ring/60 disabled:cursor-default"            >              {/* eslint-disable-next-line @next/next/no-img-element */}              <img src={image.src} alt="" crossOrigin={crossOrigin} draggable={false} className="size-full object-cover transition-[scale] duration-300 group-hover:scale-[1.03] group-disabled:scale-100" />              <span                aria-hidden="true"                className="absolute top-2 right-2 grid size-6 place-items-center rounded-full bg-primary text-primary-foreground transition-[opacity,scale] duration-300"                style={{ opacity: isKept || busy ? 1 : 0, scale: isKept || busy ? "1" : "0.6" }}              >                {busy ? <LoaderCircle className="size-3.5 animate-spin" /> : <Check className="size-3.5" strokeWidth={2.6} />}              </span>            </button>          );        })}      </div>      <div className="flex min-h-8 items-center justify-between gap-3 px-0.5">        <p className="min-w-0 truncate text-[12.5px] text-muted-foreground" aria-live="polite">          {error ? <span className="text-red-600 dark:text-red-400">{error}</span> : keptImage && phase === "kept" ? `${labels?.kept ?? "Kept"} ${list.indexOf(keptImage) + 1} of ${list.length}` : labels?.hint ?? "Pick the one to keep"}        </p>        <button          type="button"          onClick={again}          tabIndex={phase === "kept" ? 0 : -1}          aria-hidden={phase !== "kept"}          className={`inline-flex h-8 shrink-0 cursor-pointer items-center gap-1.5 rounded-full px-3 text-[12.5px] font-medium text-foreground ring-1 ring-border transition-[opacity,background-color] duration-200 hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 ${phase === "kept" ? "opacity-100" : "pointer-events-none opacity-0"}`}        >          <RotateCcw className="size-3.5" aria-hidden="true" />          {labels?.again ?? "Choose again"}        </button>      </div>    </div>  );}

Registry item: /r/variant-pick.json