An account switcher drawn as a key rack

Build a choose-an-account page in React where every saved account hangs as a key: swinging keys on springs, lifting one to sign in, and an empty hook for a new account.

5 min read

The real component. Click the picture to open it live and try it before you read how it was built.

Choosing between saved accounts is usually a list. Ours is a key rack: each account hangs as a brass key with a paper tag showing a face, a name and the workspace.

Keys that swing

Pointing at a key sets it swinging about its hook on a spring: out, back past centre and settling. Each cord has a different length so the rack hangs unevenly, like a real one.

src/registry/login/key-rack/hanging-key.tsx

"use client";

import type { PointerEvent, ReactNode } from "react";
import { motion, useAnimationControls } from "motion/react";
import { usePrefersReducedMotion } from "@/hooks/use-prefers-reduced-motion";
import { SPRING_SNAPPY } from "@/lib/motion";
import { cn } from "@/lib/utils";

// How long each key's cord is, so the rack hangs unevenly like a real one.
const CORDS = ["h-6", "h-12", "h-8", "h-14"];
// A push sets the key swinging about its hook: out, back past centre, and settling.
const SWING = [0, 9, -6, 3.5, -1.5, 0];
const SWING_SECONDS = 1.3;
// A brass key on the ring, its teeth toward the tag.
const KEY =
  "M12 2 a9 9 0 1 0 0.01 0 Z M12 7 a3 3 0 1 0 0.01 0 Z M9 19 H15 V52 L12 56 L9 52 V46 H5 V42 H9 V38 H6 V34 H9 Z";

interface HangingKeyProps {
  index: number;
  // The paper tag's contents.
  children: ReactNode;
  // Drawn without a key: the hook for an account that isn't on the rack yet.
  isEmpty?: boolean;
  isLifted?: boolean;
  isDimmed?: boolean;
  isDisabled?: boolean;
  onPick: () => void;
}

// One hook on the rack: a length of the brass rail, a hook, a cord, a ring, a key and its paper tag, all one
// button. Pointing at it pushes it from the side the pointer came in, and it swings on its hook until it settles;
// picking it lifts it off the rack.
export function HangingKey({
  index,
  children,
  isEmpty = false,
  isLifted = false,
  isDimmed = false,
  isDisabled = false,
  onPick,
}: HangingKeyProps) {
  const isReduced = usePrefersReducedMotion();
  const swing = useAnimationControls();

  const push = (event: PointerEvent<HTMLButtonElement>) => {
    if (isReduced || isLifted) return;
    const box = event.currentTarget.getBoundingClientRect();
    const side = event.clientX < box.left + box.width / 2 ? 1 : -1;
    swing.start({
      rotate: SWING.map((angle) => angle * side),
      transition: { duration: SWING_SECONDS, ease: "easeOut" },
    });
  };

  return (
    <div className="flex flex-col items-center">
      <span aria-hidden className="h-2.5 w-full bg-linear-to-b from-brass-light via-brass to-brass-deep shadow-lg" />
      <span aria-hidden className="z-10 h-3 w-1.5 rounded-b-full bg-brass-deep" />
      <motion.button
        type="button"
        onClick={onPick}
        onPointerEnter={push}
        disabled={isDisabled}
        animate={swing}
        className={cn(
          "group -mt-1 flex w-full origin-top flex-col items-center px-2 text-left text-zinc-950 transition-opacity duration-200 outline-none sm:px-3",
          isDimmed && "opacity-30",
        )}
      >
        <span aria-hidden className={cn("w-px bg-white/50", CORDS[index % CORDS.length])} />
        <span aria-hidden className="size-6 rounded-full border-2 border-brass-light" />
        <motion.span
          animate={{ y: isLifted ? -16 : 0, scale: isLifted ? 1.05 : 1 }}
          transition={SPRING_SNAPPY}
          className="relative isolate -mt-2 block w-full"
        >
          {!isEmpty && (
            <svg
              aria-hidden
              viewBox="0 0 24 58"
              className="absolute -top-4 right-2 z-10 h-16 rotate-12 fill-brass-light stroke-brass-deep drop-shadow-md"
            >
              <path d={KEY} fillRule="evenodd" />
            </svg>
          )}
          <span className="block rounded-lg bg-white p-3 pt-5 shadow-xl group-hover:shadow-2xl group-focus-visible:outline-2 group-focus-visible:outline-offset-2 group-focus-visible:outline-white">
            <span aria-hidden className="absolute top-2 left-1/2 size-2 -translate-x-1/2 rounded-full bg-red-950" />
            {children}
          </span>
        </motion.span>
      </motion.button>
    </div>
  );
}
One hook, cord, ring, key and tag

Lifting a key signs in

Picking a key lifts it off the rail and signs that account in. If sign-in fails, the key hangs back up with an error. The last hook is empty, for adding an account by email.

src/registry/login/key-rack/login-key-rack.tsx

"use client";

import { useState, type FormEvent } from "react";
import Image from "next/image";
import { Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import { LoginField } from "../shared/login-field";
import { HangingKey } from "./hanging-key";

const BUTTON =
  "inline-flex h-10 items-center justify-center rounded-md px-4 text-sm font-semibold transition-colors duration-150 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white";
const PRIMARY = "bg-brass-light text-red-950 hover:bg-white";
const QUIET = "h-11 text-sm font-medium ring-1 ring-white/25 hover:bg-white/10";

export interface RackAccount {
  id: string;
  name: string;
  email: string;
  workspace: string;
  photo: { src: string; alt: string };
}

export interface LoginKeyRackProps {
  title: string;
  description: string;
  accounts: RackAccount[];
  // {name} is replaced with the chosen account's first name.
  labels: { signingIn: string; failed: string };
  other: {
    tag: string;
    title: string;
    email: string;
    submit: string;
    sso: string;
    passkey: string;
    ssoHref: string;
    passkeyHref: string;
    action: string;
  };
  success: { title: string; description: string; action: { label: string; href: string } };
  // Signs the chosen account in. Resolve false to hang the key back up with an error. Without it every key works.
  onChoose?: (account: RackAccount) => Promise<boolean>;
  // Called with the email typed for an account that is not on the rack.
  onContinue?: (email: string) => void;
  className?: string;
}

const firstName = (account: RackAccount) => account.name.split(" ")[0];

// A choose-an-account page drawn as a key rack on an oxblood board. Every account remembered on this device hangs
// from a brass rail as a key with a paper tag: a face, a name and the workspace it opens. Keys swing when pointed
// at; picking one lifts it off the rail and signs that account in. The last hook is empty, for an account that
// isn't on the rack yet.
export function LoginKeyRack({
  title,
  description,
  accounts,
  labels,
  other,
  success,
  onChoose,
  onContinue,
  className,
}: LoginKeyRackProps) {
  const [picked, setPicked] = useState<RackAccount | null>(null);
  const [status, setStatus] = useState<"idle" | "busy" | "in" | "failed">("idle");
  const [isAdding, setIsAdding] = useState(false);
  const isBusy = status === "busy" || status === "in";

  const pick = async (account: RackAccount) => {
    setPicked(account);
    setIsAdding(false);
    setStatus("busy");
    const isIn = onChoose ? await onChoose(account) : true;
    setStatus(isIn ? "in" : "failed");
    if (!isIn) setPicked(null);
  };

  const addAccount = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    onContinue?.(String(new FormData(event.currentTarget).get("email") ?? ""));
  };

  const fill = (text: string) => text.replace("{name}", picked ? firstName(picked) : "");
  return (
    <div className={cn("flex min-h-svh flex-col bg-red-950 font-inter-tight text-orange-50", className)}>
      <main className="mx-auto flex w-full max-w-3xl flex-1 flex-col justify-center gap-10 px-5 py-16">
        <div aria-live="polite">
          <h1 className="text-3xl font-medium tracking-tight sm:text-4xl">
            {status === "in" ? fill(success.title) : title}
          </h1>
          <p className="mt-3 max-w-md text-base text-pretty text-orange-100/70">
            {status === "in" ? success.description : status === "busy" ? fill(labels.signingIn) : description}
          </p>
        </div>
        <div className="rounded-2xl bg-linear-to-b from-red-900/70 to-red-950 px-4 pt-8 pb-12 shadow-2xl ring-1 inset-shadow-sm ring-white/10 inset-shadow-white/15 sm:px-8">
          <div className="grid grid-cols-2 gap-y-10 sm:grid-cols-4">
            {accounts.map((account, index) => (
              <HangingKey
                key={account.id}
                index={index}
                isLifted={picked?.id === account.id}
                isDimmed={picked !== null && picked.id !== account.id}
                isDisabled={isBusy}
                onPick={() => pick(account)}
              >
                <Image
                  src={account.photo.src}
                  alt={account.photo.alt}
                  width={48}
                  height={48}
                  className="size-12 rounded-full object-cover"
                />
                <span className="mt-2.5 block truncate font-semibold">{account.name}</span>
                <span className="block truncate text-xs text-zinc-500">{account.workspace}</span>
                <span className="mt-1.5 block truncate font-mono text-2xs text-zinc-500">{account.email}</span>
              </HangingKey>
            ))}
            <HangingKey
              index={accounts.length}
              isEmpty
              isDimmed={picked !== null}
              isDisabled={isBusy}
              onPick={() => setIsAdding(true)}
            >
              <span className="grid size-12 place-items-center rounded-full bg-red-950 text-white">
                <Plus aria-hidden className="size-5" />
              </span>
              <span className="mt-2.5 block font-semibold">{other.tag}</span>
              <span className="block text-xs text-zinc-500">{other.action}</span>
            </HangingKey>
          </div>
        </div>
        {status === "failed" && (
          <p role="alert" className="text-sm text-red-300">
            {labels.failed}
          </p>
        )}
        {status === "in" && (
          <a href={success.action.href} className={cn(BUTTON, PRIMARY, "w-fit")}>
            {success.action.label}
          </a>
        )}
        {isAdding && (
          <form onSubmit={addAccount} className="flex max-w-lg flex-col gap-4">
            <h2 className="text-lg font-medium">{other.title}</h2>
            <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
              <LoginField
                id="rack-email"
                label={other.email}
                type="email"
                name="email"
                autoComplete="username"
                required
                autoFocus
                className="flex-1"
                inputClassName="h-12 rounded-md bg-white/10 text-white ring-1 ring-white/25 focus-visible:ring-white/70"
              />
              <button type="submit" className={cn(BUTTON, PRIMARY)}>
                {other.submit}
              </button>
            </div>
            <p className="flex flex-wrap gap-3">
              <a href={other.ssoHref} className={cn(BUTTON, QUIET)}>
                {other.sso}
              </a>
              <a href={other.passkeyHref} className={cn(BUTTON, QUIET)}>
                {other.passkey}
              </a>
            </p>
          </form>
        )}
      </main>
    </div>
  );
}
The rack and its states

More articles