{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"sudo-gate","type":"registry:component","title":"Sudo gate","description":"Wrap any dangerous button. A padlock on its corner shows how long you stay verified; when it’s locked, the button grows right where it stands into the “Confirm it’s you” card.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/code-input.json?as=dependency","https://hairlineui.com/r/status-button.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency","https://hairlineui.com/r/number-roll.json?as=dependency"],"files":[{"path":"registry/sudo-gate.tsx","type":"registry:component","content":"// Hairline UI · sudo-gate · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { SudoGateMark } from \"./sudo-gate-mark\";\nimport { SudoGatePanel, type SudoMethod, type SudoProof } from \"./sudo-gate-panel\";\nimport { TextMorph } from \"./text-morph\";\n\nexport type { SudoMethod, SudoProof } from \"./sudo-gate-panel\";\n\n/* ─────────────────────────────────────────────────────────\n * SUDO GATE: a dangerous button that knows if you're still you\n *\n *   badge     a small padlock sits on the button's corner. While\n *             you're recently verified it's open, inside a ring of\n *             the time left (\"8 min\", then \"42s\", the last minute\n *             amber); when the time is up the shackle drops shut\n *   ask       click a locked button and it grows where it stands:\n *             the button itself widens and deepens into the card\n *             \"Confirm it's you\", pushing what's around it aside,\n *             its label giving way to the question\n *   unlock    the big padlock swings open, the card folds back down\n *             into the button with the small padlock riding its\n *             corner, its ring filling, and your click goes through\n *   share     every gate on the page shares one trust window: verify\n *             once and every other badge fills up too\n *\n * Wrap the app's own button. The gate stops its click until you're\n * verified, then clicks it for you; the button, its handler and the\n * request stay the app's. Always check freshness on the server too.\n * ───────────────────────────────────────────────────────── */\n\nexport interface SudoGateProps {\n  /** The app's own button (or link). Its click is held until you're verified. */\n  children: React.ReactElement<{ \"aria-describedby\"?: string }>;\n  /** Checks the proof with your auth. Resolve to unlock (optionally with when the trust ends, as a Date or ms); throw to say why not. */\n  verify: (proof: SudoProof) => Promise<unknown>;\n  /** When the current trust ends, from your session (e.g. createdAt + freshAge). Leave out to start locked. */\n  freshUntil?: Date | number | null;\n  /** How long a verification lasts, in seconds, when verify doesn't say. */\n  trustFor?: number;\n  /** The ways to verify, first one shown first. */\n  methods?: SudoMethod[];\n  /** Sends the one-time code; called as the code view opens and on resend. */\n  sendCode?: () => Promise<unknown>;\n  /** Where the code went, e.g. \"mira@northwind.com\". */\n  codeHint?: string;\n  /** Why this action asks, shown under \"Confirm it's you\". */\n  reason?: string;\n  /** Gates with the same scope share one trust window. */\n  scope?: string;\n  /** Hide the corner badge (the gate still asks). */\n  badge?: boolean;\n  className?: string;\n}\n\n/* ── One trust window per scope, shared by every gate on the page ── */\n\nconst trust = new Map<string, number>();\n// When each window was set, so a badge whose clock last ticked before it never counts from a stale time.\nconst setAt = new Map<string, number>();\nconst listeners = new Set<() => void>();\nfunction setTrust(scope: string, until: number) {\n  if (trust.get(scope) === until) return;\n  trust.set(scope, until);\n  setAt.set(scope, Date.now());\n  listeners.forEach((l) => l());\n}\nconst subscribeTrust = (l: () => void) => {\n  listeners.add(l);\n  return () => {\n    listeners.delete(l);\n  };\n};\n\n/** Locks every gate in a scope now, e.g. when your server answers that the session isn't fresh, or on sign-out. */\nexport function expireSudo(scope = \"session\") {\n  setTrust(scope, 0);\n}\n\nconst toMs = (v: Date | number) => (typeof v === \"number\" ? v : v.getTime());\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () =>\n  React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst GROW = 520;\nconst FOLD = 440;\nconst CARD_W = 360;\nconst RADIUS = 22;\nconst METHODS: SudoMethod[] = [\"passkey\", \"code\"];\n\n/** The button's size and look, so the card can start and end as it. */\ninterface Origin {\n  width: number;\n  height: number;\n  radius: number;\n  bg: string;\n}\n\nfunction originOf(target: HTMLElement): Origin {\n  const style = getComputedStyle(target);\n  const transparent = /rgba?\\(\\s*0,\\s*0,\\s*0,\\s*0\\s*\\)|transparent/.test(style.backgroundColor);\n  return {\n    width: target.offsetWidth,\n    height: target.offsetHeight,\n    radius: Math.min(parseFloat(style.borderTopLeftRadius) || 0, target.offsetHeight / 2),\n    bg: transparent ? \"var(--background)\" : style.backgroundColor,\n  };\n}\n\n/** The padlock on the button's corner. It owns the per-second clock, so the app's button never re-renders with it. */\nfunction Badge({\n  until,\n  since,\n  trustFor,\n  reduced,\n  hidden,\n  ringRef,\n  landedRef,\n}: {\n  until: number;\n  since: number;\n  trustFor: number;\n  reduced: boolean;\n  hidden: boolean;\n  ringRef: React.RefObject<HTMLSpanElement | null>;\n  landedRef: React.RefObject<boolean>;\n}) {\n  const [now, setNow] = React.useState<number | null>(null);\n  const arcRef = React.useRef<SVGCircleElement>(null);\n\n  // Wakes once a second, on the second, only while trusted.\n  React.useEffect(() => {\n    const t0 = Date.now();\n    const delay = now === null ? 0 : until > t0 ? 1000 - (t0 % 1000) + 5 : -1;\n    if (delay < 0) return;\n    const t = window.setTimeout(() => setNow(Date.now()), delay);\n    return () => window.clearTimeout(t);\n  }, [now, until]);\n\n  const left = now === null ? 0 : Math.max(0, until - Math.max(now, since));\n  const fresh = left > 0;\n  const secs = Math.ceil(left / 1000);\n  const ending = fresh && secs < 60;\n  const shown = ending ? { n: secs, unit: \"s\" } : { n: Math.ceil(secs / 60), unit: \"min\" };\n\n  // The ring drains in one long animation; a new window fills it first (other gates), or starts it full (the one you just unlocked).\n  React.useLayoutEffect(() => {\n    const arc = arcRef.current;\n    if (!arc) return;\n    const read = parseFloat(getComputedStyle(arc).strokeDashoffset);\n    const current = Number.isNaN(read) ? 1 : read;\n    arc.getAnimations().forEach((a) => a.cancel());\n    if (!fresh) {\n      if (current < 1 && !reduced) arc.animate([{ strokeDashoffset: current }, { strokeDashoffset: 1 }], { duration: 300, easing: EASE });\n      return;\n    }\n    const rest = until - Date.now();\n    const from = 1 - Math.min(1, rest / (trustFor * 1000));\n    const fill = landedRef.current || reduced ? 0 : 600;\n    landedRef.current = false;\n    arc.animate(\n      fill\n        ? [{ strokeDashoffset: current, easing: EASE }, { strokeDashoffset: from, offset: fill / (fill + rest), easing: \"linear\" }, { strokeDashoffset: 1 }]\n        : [{ strokeDashoffset: from }, { strokeDashoffset: 1 }],\n      { duration: fill + rest, fill: \"forwards\" },\n    );\n  }, [fresh, until, trustFor, reduced, landedRef]);\n\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute -top-[11px] right-2.5 z-[1] flex h-[22px] items-center rounded-full bg-background p-px shadow-[0_0_0_1px_var(--border)]\"\n      // While the button is open as the card, its padlock is the big one inside; the badge comes back as the card folds.\n      style={{ opacity: hidden ? 0 : 1, transition: reduced ? \"none\" : `opacity ${hidden ? 120 : 240}ms ${EASE}` }}\n    >\n      {/* The time sits to the padlock's left and folds toward it, so the padlock never moves off its corner. */}\n      <span\n        className=\"grid\"\n        style={{\n          gridTemplateColumns: fresh ? \"1fr\" : \"0fr\",\n          opacity: fresh ? 1 : 0,\n          filter: fresh || reduced ? \"none\" : \"blur(3px)\",\n          transition: reduced ? \"none\" : `grid-template-columns 420ms ${EASE}, opacity ${fresh ? 320 : 160}ms ${EASE}, filter 320ms ${EASE}`,\n        }}\n      >\n        <span className=\"flex min-w-0 justify-end [clip-path:inset(-2px_0_-2px_0)]\">\n          <span className=\"flex w-max items-center pl-[7px] pr-[3px] text-[11px] font-medium leading-[14px] tabular-nums text-foreground\">\n            <NumberRoll value={shown.n} direction=\"down\" duration={700} />\n            <TextMorph className={shown.unit === \"min\" ? \"ml-[2px]\" : \"\"}>{shown.unit}</TextMorph>\n          </span>\n        </span>\n      </span>\n      <span ref={ringRef} className=\"block size-5 shrink-0\">\n        <SudoGateMark open={fresh} ending={ending} reduced={reduced} arcRef={arcRef} className=\"size-5\" />\n      </span>\n    </span>\n  );\n}\n\nexport function SudoGate({\n  children,\n  verify,\n  freshUntil,\n  trustFor = 600,\n  methods = METHODS,\n  sendCode,\n  codeHint,\n  reason = \"This action needs a recent sign-in.\",\n  scope = \"session\",\n  badge = true,\n  className = \"\",\n}: SudoGateProps) {\n  const reduced = useReducedMotion();\n  const until = React.useSyncExternalStore(subscribeTrust, () => trust.get(scope) ?? 0, () => 0);\n  const [now, setNow] = React.useState<number | null>(null);\n  const [phase, setPhase] = React.useState<\"closed\" | \"opening\" | \"open\" | \"closing\">(\"closed\");\n  const [origin, setOrigin] = React.useState<Origin | null>(null);\n  const [cardW, setCardW] = React.useState(CARD_W);\n  const [height, setHeight] = React.useState<number | null>(null);\n  const [verified, setVerified] = React.useState(false);\n  const [said, setSaid] = React.useState(\"\");\n  const [run, setRun] = React.useState(0);\n\n  const wrapRef = React.useRef<HTMLSpanElement>(null);\n  const targetRef = React.useRef<HTMLElement | null>(null);\n  const cloneRef = React.useRef<HTMLElement | null>(null);\n  const holderRef = React.useRef<HTMLSpanElement>(null);\n  const contentRef = React.useRef<HTMLDivElement>(null);\n  const markRef = React.useRef<HTMLSpanElement>(null);\n  const ringRef = React.useRef<HTMLSpanElement>(null);\n  const pass = React.useRef(false);\n  const landedRef = React.useRef(false);\n  const timers = React.useRef<number[]>([]);\n  const descId = React.useId();\n  const titleId = React.useId();\n\n  // The server's word on freshness, whenever it changes.\n  const seed = freshUntil == null ? null : toMs(freshUntil);\n  React.useEffect(() => {\n    if (seed !== null) setTrust(scope, seed);\n  }, [seed, scope]);\n\n  // The gate only needs to know when the window opens and when it runs out; the badge keeps its own clock.\n  React.useEffect(() => {\n    const t = window.setTimeout(() => setNow(Date.now()), 0);\n    return () => window.clearTimeout(t);\n  }, [until]);\n  React.useEffect(() => {\n    if (now === null || until <= now) return;\n    const t = window.setTimeout(() => setNow(Date.now()), until - now + 5);\n    return () => window.clearTimeout(t);\n  }, [now, until]);\n\n  React.useEffect(() => {\n    const list = timers.current;\n    return () => {\n      list.forEach((t) => window.clearTimeout(t));\n      if (targetRef.current) targetRef.current.style.visibility = \"\";\n    };\n  }, []);\n\n  const fresh = now !== null && until > now;\n  const isOpen = phase === \"open\";\n  const showing = phase !== \"closed\";\n\n  // Growing: one frame at the button's size, then the card's.\n  React.useLayoutEffect(() => {\n    if (phase !== \"opening\") return;\n    let f2 = 0;\n    const f1 = requestAnimationFrame(() => {\n      f2 = requestAnimationFrame(() => setPhase(\"open\"));\n    });\n    return () => {\n      cancelAnimationFrame(f1);\n      cancelAnimationFrame(f2);\n    };\n  }, [phase]);\n\n  // The button's own look sits at the top of the card while it grows, then gives way to the question.\n  React.useLayoutEffect(() => {\n    const holder = holderRef.current;\n    const clone = cloneRef.current;\n    if (!showing || !holder || !clone || holder.contains(clone)) return;\n    holder.replaceChildren(clone);\n  }, [showing]);\n\n  // The card's height follows its content (a view switch, an error line, the code boxes).\n  React.useLayoutEffect(() => {\n    const el = contentRef.current;\n    if (!showing || !el) return;\n    const measure = () => setHeight((h) => (h === el.offsetHeight ? h : el.offsetHeight));\n    measure();\n    const ro = new ResizeObserver(measure);\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [showing]);\n\n  /** Back down into the button, where it stands. */\n  const fold = React.useCallback(\n    (refocus: boolean) => {\n      const target = targetRef.current;\n      if (!target) return;\n      setPhase(\"closing\");\n      timers.current.push(\n        window.setTimeout(\n          () => {\n            setPhase(\"closed\");\n            setVerified(false);\n            setHeight(null);\n            target.style.visibility = \"\";\n            if (refocus) target.focus({ preventScroll: true });\n          },\n          reduced ? 0 : FOLD,\n        ),\n      );\n    },\n    [reduced],\n  );\n\n  // While open: Escape, a press elsewhere or focus leaving folds it back.\n  React.useEffect(() => {\n    if (phase !== \"open\") return;\n    const down = (e: PointerEvent) => {\n      if (!wrapRef.current?.contains(e.target as Node)) fold(false);\n    };\n    document.addEventListener(\"pointerdown\", down);\n    return () => document.removeEventListener(\"pointerdown\", down);\n  }, [phase, fold]);\n\n  const ask = (target: HTMLElement) => {\n    targetRef.current = target;\n    const o = originOf(target);\n    // As wide as the card wants, never wider than the screen; whatever sits around it makes room.\n    const room = window.innerWidth - 32;\n    const clone = target.cloneNode(true) as HTMLElement;\n    clone.removeAttribute(\"id\");\n    clone.querySelectorAll(\"[id]\").forEach((n) => n.removeAttribute(\"id\"));\n    clone.setAttribute(\"aria-hidden\", \"true\");\n    clone.setAttribute(\"inert\", \"\");\n    Object.assign(clone.style, { margin: \"0\", pointerEvents: \"none\", visibility: \"visible\", width: `${o.width}px`, height: `${o.height}px`, flexShrink: \"0\" });\n    cloneRef.current = clone;\n    setOrigin(o);\n    setCardW(Math.max(o.width, Math.min(CARD_W, room)));\n    setVerified(false);\n    setSaid(\"\");\n    setRun((r) => r + 1);\n    target.style.visibility = \"hidden\";\n    setPhase(reduced ? \"open\" : \"opening\");\n  };\n\n  const attempt = async (proof: SudoProof) => {\n    const result = await verify(proof);\n    const told = result instanceof Date || typeof result === \"number\" ? toMs(result) : null;\n    const nextUntil = told ?? Date.now() + trustFor * 1000;\n    setVerified(true);\n    const secs = Math.round((nextUntil - Date.now()) / 1000);\n    setSaid(`Verified. Unlocked for ${secs >= 90 ? `${Math.round(secs / 60)} minutes` : `${secs} seconds`}.`);\n    timers.current.push(\n      window.setTimeout(\n        () => {\n          const target = targetRef.current;\n          // The card folds, and the small padlock rides its corner back down, its ring filling.\n          fold(false);\n          setTrust(scope, nextUntil);\n          setNow(Date.now());\n          // With the button back, the click you made goes through to the app's own handler.\n          timers.current.push(\n            window.setTimeout(\n              () => {\n                if (!target) return;\n                target.focus({ preventScroll: true });\n                pass.current = true;\n                target.click();\n                pass.current = false;\n              },\n              reduced ? 20 : FOLD + 40,\n            ),\n          );\n        },\n        reduced ? 200 : 760,\n      ),\n    );\n  };\n\n  const onClickCapture = (e: React.MouseEvent<HTMLSpanElement>) => {\n    if (pass.current) return;\n    const t = e.target as HTMLElement;\n    const own = wrapRef.current?.firstElementChild;\n    if (!own?.contains(t)) return;\n    if (!showing && Date.now() < until) {\n      ringRef.current?.animate([{ transform: \"none\" }, { transform: \"scale(1.12)\" }, { transform: \"none\" }], { duration: 300, easing: EASE });\n      return;\n    }\n    e.preventDefault();\n    e.stopPropagation();\n    if (showing) return;\n    const target = (t.closest(\"button, a, [role='button'], input[type='submit']\") as HTMLElement | null) ?? (own as HTMLElement);\n    if (own.contains(target) || own === target) ask(target);\n  };\n\n  const describedBy = [children.props[\"aria-describedby\"], descId].filter(Boolean).join(\" \");\n  const grow = (prop: string) => `${prop} ${isOpen ? GROW : FOLD}ms ${EASE}`;\n  const size = !showing || !origin ? undefined : isOpen || (reduced && phase !== \"closing\") ? { width: cardW, height: height ?? origin.height } : { width: origin.width, height: origin.height };\n\n  return (\n    <span\n      ref={wrapRef}\n      onClickCapture={onClickCapture}\n      className={`relative inline-flex align-top ${className}`}\n      // Never squeezed by a flex row it sits in: the card takes its full size and the row makes room.\n      style={size ? { ...size, flexShrink: 0, transition: reduced ? \"none\" : `${grow(\"width\")}, ${grow(\"height\")}` } : undefined}\n    >\n      {React.cloneElement(children, { \"aria-describedby\": describedBy })}\n\n      {showing && origin && (\n        <div\n          role=\"group\"\n          aria-labelledby={titleId}\n          onKeyDown={(e) => {\n            if (e.key === \"Escape\") {\n              e.stopPropagation();\n              fold(true);\n            }\n          }}\n          onBlur={(e) => {\n            if (isOpen && !verified && document.hasFocus() && e.relatedTarget && !wrapRef.current?.contains(e.relatedTarget as Node)) fold(false);\n          }}\n          className=\"absolute inset-0 z-[1] overflow-clip text-popover-foreground\"\n          style={{\n            borderRadius: isOpen ? RADIUS : origin.radius,\n            backgroundColor: isOpen ? \"var(--popover)\" : origin.bg,\n            boxShadow: \"inset 0 0 0 1px var(--border)\",\n            transition: reduced ? \"none\" : `${grow(\"border-radius\")}, ${grow(\"background-color\")}`,\n          }}\n        >\n          {/* The button itself, at the top of the card as it grows, and back again as it folds. */}\n          <span\n            ref={holderRef}\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute left-1/2 top-0 flex\"\n            style={{\n              marginLeft: -origin.width / 2,\n              opacity: isOpen || reduced ? 0 : 1,\n              filter: isOpen && !reduced ? \"blur(4px)\" : \"none\",\n              transition: reduced ? \"none\" : isOpen ? `opacity 140ms ${EASE}, filter 140ms ${EASE}` : `opacity 200ms ${EASE} ${FOLD - 240}ms, filter 200ms ${EASE} ${FOLD - 240}ms`,\n            }}\n          />\n          <div\n            ref={contentRef}\n            className=\"absolute left-1/2 top-0\"\n            style={{\n              width: cardW,\n              marginLeft: -cardW / 2,\n              opacity: isOpen ? 1 : 0,\n              filter: isOpen || reduced ? \"none\" : \"blur(6px)\",\n              transform: isOpen || reduced ? \"none\" : \"translateY(-8px)\",\n              transition: reduced ? \"none\" : isOpen ? `opacity 300ms ${EASE} 150ms, filter 420ms ${EASE} 150ms, transform 520ms ${EASE} 120ms` : `opacity 120ms ${EASE}, filter 120ms ${EASE}, transform 200ms ${EASE}`,\n            }}\n          >\n            <SudoGatePanel\n              key={run}\n              titleId={titleId}\n              methods={methods}\n              reason={reason}\n              codeHint={codeHint}\n              sendCode={sendCode}\n              attempt={attempt}\n              onCancel={() => fold(true)}\n              verified={verified}\n              reduced={reduced}\n              markRef={markRef}\n            />\n          </div>\n        </div>\n      )}\n\n      {badge && <Badge until={until} since={setAt.get(scope) ?? 0} trustFor={trustFor} reduced={reduced} hidden={phase === \"open\" || phase === \"opening\"} ringRef={ringRef} landedRef={landedRef} />}\n\n      <span id={descId} className=\"sr-only\">\n        {fresh ? \"Unlocked: you verified recently.\" : \"Asks you to confirm it's you first.\"}\n      </span>\n      <span className=\"sr-only\" role=\"status\">\n        {said}\n      </span>\n    </span>\n  );\n}\n"},{"path":"registry/sudo-gate-panel.tsx","type":"registry:component","content":"// Hairline UI · sudo-gate · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { Fingerprint, KeyRound, Mail, X } from \"lucide-react\";\nimport { CodeInput } from \"./code-input\";\nimport { StatusButton, type ActionStatus } from \"./status-button\";\nimport { SudoGateMark } from \"./sudo-gate-mark\";\nimport { TextMorph } from \"./text-morph\";\n\n/* ─────────────────────────────────────────────────────────\n * SUDO GATE PANEL: what the button turns into when it asks\n *\n *   passkey   one button; the browser's own passkey prompt does\n *             the rest\n *   code      the code is sent as the view opens, then six boxes\n *             (one-time-code autofill, paste, resend clock)\n *   password  one field and Confirm\n *\n * Every method throws its reason back into the panel, in place;\n * the others are a click away underneath. The panel only ever\n * calls `verify` and `sendCode`: the app keeps its auth.\n * ───────────────────────────────────────────────────────── */\n\nexport type SudoMethod = \"passkey\" | \"code\" | \"password\";\nexport type SudoProof = { method: \"passkey\" } | { method: \"code\"; code: string } | { method: \"password\"; password: string };\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\nconst SWITCH: Record<SudoMethod, { label: string; icon: React.ReactNode }> = {\n  passkey: { label: \"Use a passkey\", icon: <Fingerprint /> },\n  code: { label: \"Email me a code\", icon: <Mail /> },\n  password: { label: \"Use my password\", icon: <KeyRound /> },\n};\n\nfunction message(error: unknown, fallback: string) {\n  return error instanceof Error && error.message ? error.message : fallback;\n}\n\n/** A line that crossfades whole when its text changes (sentences don't morph well). */\nfunction Line({ text, tone, reduced }: { text: string; tone: string; reduced: boolean }) {\n  const [shown, setShown] = React.useState(text);\n  const [phase, setPhase] = React.useState<\"in\" | \"out\">(\"in\");\n  if (text !== shown && phase === \"in\") setPhase(\"out\");\n  React.useEffect(() => {\n    if (phase !== \"out\") return;\n    const t = window.setTimeout(() => {\n      setShown(text);\n      setPhase(\"in\");\n    }, reduced ? 0 : 140);\n    return () => window.clearTimeout(t);\n  }, [phase, text, reduced]);\n  return (\n    <span\n      className={`block ${tone}`}\n      style={{\n        opacity: phase === \"in\" ? 1 : 0,\n        filter: phase === \"in\" || reduced ? \"none\" : \"blur(3px)\",\n        transition: reduced ? \"none\" : `opacity ${phase === \"in\" ? 260 : 140}ms ${EASE}, filter 260ms ${EASE}`,\n      }}\n    >\n      {shown}\n    </span>\n  );\n}\n\nexport interface SudoGatePanelProps {\n  methods: SudoMethod[];\n  reason: string;\n  codeHint?: string;\n  sendCode?: () => Promise<unknown>;\n  /** Resolves when the proof is accepted (with what verify returned); throws with the reason it wasn't. */\n  attempt: (proof: SudoProof) => Promise<void>;\n  onCancel: () => void;\n  verified: boolean;\n  reduced: boolean;\n  markRef: React.Ref<HTMLSpanElement>;\n  titleId: string;\n}\n\nexport function SudoGatePanel({ methods, reason, codeHint, sendCode, attempt, onCancel, verified, reduced, markRef, titleId }: SudoGatePanelProps) {\n  const [method, setMethod] = React.useState<SudoMethod>(methods[0] ?? \"passkey\");\n  const [status, setStatus] = React.useState<ActionStatus>(\"idle\");\n  const [error, setError] = React.useState(\"\");\n  const [sent, setSent] = React.useState<\"idle\" | \"sending\" | \"sent\" | \"failed\">(\"idle\");\n  const [password, setPassword] = React.useState(\"\");\n  const viewRef = React.useRef<HTMLDivElement>(null);\n  const run = React.useRef(0);\n\n  const send = React.useCallback(async () => {\n    if (!sendCode) return;\n    const mine = ++run.current;\n    setSent(\"sending\");\n    setError(\"\");\n    try {\n      await sendCode();\n      if (run.current === mine) setSent(\"sent\");\n    } catch (e) {\n      if (run.current !== mine) return;\n      setSent(\"failed\");\n      setError(message(e, \"We couldn't send a code. Try again.\"));\n    }\n  }, [sendCode]);\n\n  // The code goes out as the code view opens, the first time it opens.\n  React.useEffect(() => {\n    if (method !== \"code\" || sent !== \"idle\" || !sendCode) return;\n    const t = window.setTimeout(send, 0);\n    return () => window.clearTimeout(t);\n  }, [method, sent, sendCode, send]);\n\n  // Each view takes focus as it arrives.\n  React.useEffect(() => {\n    const t = window.setTimeout(() => {\n      viewRef.current?.querySelector<HTMLElement>(\"input, button:not([aria-disabled='true'])\")?.focus({ preventScroll: true });\n    }, 30);\n    return () => window.clearTimeout(t);\n  }, [method]);\n\n  const choose = (next: SudoMethod) => {\n    run.current++;\n    setMethod(next);\n    setStatus(\"idle\");\n    setError(\"\");\n  };\n\n  const prove = async (proof: SudoProof) => {\n    if (status === \"pending\") return;\n    const mine = ++run.current;\n    setStatus(\"pending\");\n    setError(\"\");\n    try {\n      await attempt(proof);\n      if (run.current === mine) setStatus(\"success\");\n    } catch (e) {\n      if (run.current !== mine) return;\n      setStatus(\"error\");\n      setError(message(e, proof.method === \"passkey\" ? \"The passkey didn't go through. Try again.\" : \"That didn't work. Try again.\"));\n    }\n  };\n\n  const others = methods.filter((m) => m !== method);\n  const codeLabel = sent === \"sending\" ? \"Sending a code\" : codeHint ? `Enter the code sent to ${codeHint}` : \"Enter the code we sent you\";\n\n  return (\n    <div className=\"relative px-6 pb-5 pt-7\">\n      <button\n        type=\"button\"\n        aria-label=\"Cancel\"\n        onClick={onCancel}\n        disabled={verified}\n        className={`absolute right-3 top-3 grid size-8 cursor-pointer place-items-center rounded-full text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-default disabled:opacity-0 ${FOCUS}`}\n      >\n        <X className=\"size-4\" aria-hidden=\"true\" />\n      </button>\n      <div className=\"flex flex-col items-center text-center\">\n        <span ref={markRef} className=\"block size-16 shrink-0\">\n          <SudoGateMark open={verified} level={verified ? 1 : 0} reduced={reduced} className=\"size-16\" />\n        </span>\n        <h2 id={titleId} className=\"mt-4 text-[18px] font-medium leading-6 tracking-[-0.02em] text-foreground\">\n          <TextMorph>{verified ? \"Unlocked\" : \"Confirm it's you\"}</TextMorph>\n        </h2>\n        <p className=\"mt-1 text-balance text-[13.5px] leading-[1.45] text-muted-foreground\">{reason}</p>\n      </div>\n\n      <div ref={viewRef} className=\"mt-5\">\n        {method === \"passkey\" && (\n          <StatusButton\n            status={status}\n            icon={<Fingerprint />}\n            labels={{ idle: \"Use passkey\", pending: \"Verifying\", success: \"Verified\", error: \"Try again\" }}\n            onClick={() => prove({ method: \"passkey\" })}\n            className=\"h-11! w-full text-[14px]!\"\n          />\n        )}\n\n        {method === \"code\" && (\n          <CodeInput\n            key={sent === \"sent\" ? \"sent\" : \"waiting\"}\n            className=\"text-center [&>div]:mx-auto\"\n            label={codeLabel}\n            autoFocus\n            onComplete={async (code) => {\n              try {\n                await attempt({ method: \"code\", code });\n                return true;\n              } catch {\n                // The boxes say it themselves: they shake, turn red and clear.\n                return false;\n              }\n            }}\n            onResend={sendCode && sent === \"sent\" ? send : undefined}\n          />\n        )}\n\n        {method === \"password\" && (\n          <form\n            className=\"flex items-center gap-2\"\n            onSubmit={(e) => {\n              e.preventDefault();\n              if (password) prove({ method: \"password\", password });\n            }}\n          >\n            <input\n              type=\"password\"\n              autoComplete=\"current-password\"\n              aria-label=\"Your password\"\n              placeholder=\"Your password\"\n              value={password}\n              onChange={(e) => {\n                setPassword(e.target.value);\n                if (status === \"error\") setStatus(\"idle\");\n              }}\n              className=\"h-11 min-w-0 flex-1 rounded-full bg-background px-4 text-[16px] text-foreground shadow-[inset_0_0_0_1px_var(--border)] outline-none transition-shadow duration-200 placeholder:text-muted-foreground focus-visible:shadow-[inset_0_0_0_1px_var(--ring)] sm:text-[13.5px]\"\n            />\n            <StatusButton\n              type=\"submit\"\n              status={status}\n              labels={{ idle: \"Confirm\", pending: \"Checking\", success: \"Verified\", error: \"Try again\" }}\n              className=\"h-11! shrink-0\"\n            />\n          </form>\n        )}\n\n        <div\n          className=\"grid\"\n          style={{ gridTemplateRows: error ? \"1fr\" : \"0fr\", transition: reduced ? \"none\" : `grid-template-rows 320ms ${EASE}` }}\n        >\n          <div className=\"min-h-0 overflow-clip\">\n            <p role=\"alert\" className=\"pt-2 text-center text-[12.5px] leading-snug\">\n              <Line text={error} tone=\"text-red-600 dark:text-red-400\" reduced={reduced} />\n            </p>\n            {sent === \"failed\" && method === \"code\" && (\n              <button type=\"button\" onClick={send} className={`mx-auto mt-1 block cursor-pointer rounded text-[12.5px] font-medium text-foreground underline decoration-dashed underline-offset-4 ${FOCUS}`}>\n                Send again\n              </button>\n            )}\n          </div>\n        </div>\n      </div>\n\n      {others.length > 0 && (\n        <div className=\"mt-5 flex flex-wrap items-center justify-center gap-x-1 gap-y-1 border-t border-border pt-3\">\n          {others.map((m) => (\n            <button\n              key={m}\n              type=\"button\"\n              disabled={verified}\n              onClick={() => choose(m)}\n              className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-full px-2.5 text-[12.5px] text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-default disabled:opacity-50 [&_svg]:size-3.5 ${FOCUS}`}\n            >\n              {SWITCH[m].icon}\n              {SWITCH[m].label}\n            </button>\n          ))}\n        </div>\n      )}\n    </div>\n  );\n}\n"},{"path":"registry/sudo-gate-mark.tsx","type":"registry:component","content":"// Hairline UI · sudo-gate · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\n\n/* ─────────────────────────────────────────────────────────\n * SUDO GATE MARK: a padlock inside the ring of time it has left\n *\n *   locked    the shackle is down, the ring is an empty track\n *   unlocked  the shackle lifts and swings open on its right leg;\n *             the ring is the trust left, draining clockwise\n *   ending    the last minute turns the ring amber\n *\n * `level` (0–1) sets the ring with a transition; leave it out and\n * drive the ring yourself through `arcRef` (the badge drains it\n * with one long Web Animation, so nothing re-renders per frame).\n * ───────────────────────────────────────────────────────── */\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst THROW = \"cubic-bezier(0.34,1.36,0.64,1)\";\n\nexport function SudoGateMark({\n  open,\n  level,\n  ending = false,\n  reduced = false,\n  arcRef,\n  className = \"\",\n}: {\n  open: boolean;\n  level?: number;\n  ending?: boolean;\n  reduced?: boolean;\n  arcRef?: React.Ref<SVGCircleElement>;\n  className?: string;\n}) {\n  return (\n    <svg viewBox=\"0 0 24 24\" fill=\"none\" aria-hidden=\"true\" className={`block ${className}`}>\n      <circle cx=\"12\" cy=\"12\" r=\"10.6\" strokeWidth=\"1.6\" stroke=\"color-mix(in oklab, var(--foreground) 14%, var(--border))\" />\n      <circle\n        ref={arcRef}\n        cx=\"12\"\n        cy=\"12\"\n        r=\"10.6\"\n        strokeWidth=\"1.6\"\n        pathLength={1}\n        strokeDasharray=\"1\"\n        transform=\"rotate(-90 12 12)\"\n        className={`transition-[stroke] duration-500 ${ending ? \"stroke-amber-500 dark:stroke-amber-400\" : \"stroke-emerald-500 dark:stroke-emerald-400\"}`}\n        // Shown only while open, so an empty ring never leaves a sliver at twelve o'clock.\n        style={{\n          opacity: open ? 1 : 0,\n          strokeDashoffset: level === undefined ? 1 : 1 - level,\n          transition: reduced ? \"none\" : `opacity 300ms ${EASE}, stroke 500ms${level === undefined ? \"\" : `, stroke-dashoffset 560ms ${EASE}`}`,\n        }}\n      />\n      <g\n        className={`transition-colors duration-300 ${open ? \"text-foreground\" : \"text-muted-foreground\"}`}\n      >\n        <path\n          d=\"M9.6 11.2V9.4a2.4 2.4 0 0 1 4.8 0v1.8\"\n          stroke=\"currentColor\"\n          strokeWidth=\"1.6\"\n          strokeLinecap=\"round\"\n          style={{\n            transformBox: \"view-box\",\n            transformOrigin: \"14.4px 11.2px\",\n            transform: open ? \"translateY(-1.4px) rotate(24deg)\" : \"none\",\n            transition: reduced ? \"none\" : `transform ${open ? `460ms ${THROW}` : `300ms ${EASE}`}`,\n          }}\n        />\n        <rect x=\"7.9\" y=\"11\" width=\"8.2\" height=\"6.4\" rx=\"1.7\" fill=\"currentColor\" />\n      </g>\n    </svg>\n  );\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/sudo-gate. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}