{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "error-pages-02",
  "title": "Server error",
  "description": "A 500 with Try again, the status of the service and an error ID that copies with a check: Try again morphs into Retrying while the lights of the failing server run, falls back with a nudge the first time and turns them green on the second.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/company-mark.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/morph-button.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/recipes.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/blocks/error-pages/error-pages-02/index.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion, useAnimate } from 'motion/react';\nimport { useEffect, useRef, useState } from 'react';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport {\n  pressedQuietOf,\n  pressedSolidOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  ArrowRightIcon,\n  ArrowUpRightIcon,\n  CheckIcon,\n  CopyIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { risePresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport { FOCUS_RING } from '@/registry/ndeko/lib/recipes';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold, Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { CompanyMark } from '@/registry/ndeko/ui/company-mark';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport { ERROR_ID, INCIDENT, SITE } from './data';\nimport { ServerStack } from './server-stack';\nimport {\n  INITIAL,\n  LOOP_AFTER_MS,\n  reducer,\n  RESTING,\n  RETRY_MS,\n  SCRIPT,\n  type LoadStatus,\n  type ServerState,\n} from './session';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\nconst COPIED_FOR_MS = 1600;\n\nconst RETRY_STATE: Record<LoadStatus, MorphState> = {\n  error: 'idle',\n  retrying: 'busy',\n  recovered: 'done',\n};\n\nconst RETRY_LABELS: Record<MorphState, string> = {\n  idle: 'Try again',\n  busy: 'Retrying',\n  done: 'Loaded',\n};\n\nconst NUDGE = { x: [0, -4, 4, -2, 0] };\n\nconst NUDGE_TIMING = { duration: 0.32 };\n\nfunction titleOf(state: ServerState) {\n  if (state.status === 'recovered') {\n    return 'Back on track';\n  }\n  if (state.failures > 0) {\n    return 'Still not working';\n  }\n  return 'Something went wrong';\n}\n\nfunction leadOf(state: ServerState) {\n  if (state.status === 'recovered') {\n    return 'The page loaded this time. Nothing you entered was lost.';\n  }\n  if (state.failures > 0) {\n    return 'We tried again and got the same error. Our team has the details, and the ID below helps support find them.';\n  }\n  return 'Your invoices are safe. We could not load this page, and our team has been told.';\n}\n\nfunction codeLineOf(state: ServerState) {\n  if (state.status === 'recovered') {\n    return 'Loaded';\n  }\n  const tries = state.attempts + 1;\n  if (tries === 1) {\n    return 'Error 500';\n  }\n  return `Error 500 · tried ${tries} times`;\n}\n\n/** `@starting-style` also plays when the page loads, so the lead fades in only once it replaced another. */\nfunction leadEntranceOf(hasChanged: boolean) {\n  if (hasChanged) {\n    return 'transition-opacity duration-200 starting:opacity-0';\n  }\n  return undefined;\n}\n\nfunction useHasChanged(value: string) {\n  const [firstValue] = useState(value);\n  const [hasChanged, setHasChanged] = useState(false);\n  const isFirstChange = !hasChanged && value !== firstValue;\n  if (isFirstChange) {\n    setHasChanged(true);\n  }\n  return hasChanged;\n}\n\nfunction copyLabelOf(isCopied: boolean) {\n  if (isCopied) {\n    return 'Copied';\n  }\n  return 'Copy the error ID';\n}\n\ntype CopyIdButtonProps = {\n  isCopied: boolean;\n  isPressed: boolean;\n  onCopy: () => void;\n};\n\nfunction CopyIdButton({ isCopied, isPressed, onCopy }: CopyIdButtonProps) {\n  const glyphKey = String(isCopied);\n\n  return (\n    <Button\n      type='button'\n      variant='ghost'\n      size='icon-sm'\n      aria-label={copyLabelOf(isCopied)}\n      onClick={onCopy}\n      className={cn('text-muted-foreground', pressedQuietOf(isPressed))}\n    >\n      <Swap swapKey={glyphKey}>\n        {isCopied && <CheckIcon className='size-3.5' />}\n        {!isCopied && <CopyIcon className='size-3.5' />}\n      </Swap>\n    </Button>\n  );\n}\n\n/** The row of the button a person pressed shakes its head once when a retry fails. */\nfunction useNudgeOnFailure(failures: number) {\n  const [scope, animate] = useAnimate<HTMLDivElement>();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const seenFailures = useRef(failures);\n\n  useEffect(() => {\n    const isNewFailure = failures > seenFailures.current;\n    seenFailures.current = failures;\n    if (!isNewFailure || shouldReduceMotion) {\n      return;\n    }\n    animate(scope.current, NUDGE, NUDGE_TIMING);\n  }, [failures, shouldReduceMotion, animate, scope]);\n\n  return scope;\n}\n\nexport default function ErrorPages02() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const actionsRef = useNudgeOnFailure(state.failures);\n  const title = titleOf(state);\n  const hasTitleChanged = useHasChanged(title);\n  const isRecovered = state.status === 'recovered';\n  const isRetrying = state.status === 'retrying';\n  const message = spokenUnless(isAutoplaying, state.spoken);\n  const canReplay = isFinished && !isAutoplaying;\n  const presence = risePresenceOf(shouldReduceMotion);\n  useKeptHeight(ref);\n\n  /**\n   * The server answers a retry on its own, whoever pressed. When the page comes back, the button\n   * that held the focus leaves, so the focus goes to Continue.\n   */\n  useEffect(() => {\n    if (!isRetrying) {\n      return;\n    }\n    const attempt = state.attempts;\n    const timer = setTimeout(() => {\n      const retryButton = ref.current?.querySelector('[data-retry]');\n      const hadFocus = retryButton === document.activeElement;\n      act({ type: 'answered', attempt });\n      if (!hadFocus) {\n        return;\n      }\n      requestAnimationFrame(() => {\n        const next = ref.current?.querySelector<HTMLElement>('[data-continue]');\n        next?.focus();\n      });\n    }, RETRY_MS);\n    return () => clearTimeout(timer);\n  }, [isRetrying, state.attempts, act, ref]);\n\n  useEffect(() => {\n    if (!state.isCopied) {\n      return;\n    }\n    const timer = setTimeout(() => {\n      act({ type: 'copyReset' });\n    }, COPIED_FOR_MS);\n    return () => clearTimeout(timer);\n  }, [state.isCopied, act]);\n\n  async function copyId() {\n    try {\n      await navigator.clipboard.writeText(ERROR_ID);\n    } catch {\n      return;\n    }\n    act({ type: 'copied' });\n  }\n\n  return (\n    <ClockGate isActive={isInView}>\n      <div\n        ref={ref}\n        className='bg-background text-foreground @container flex min-h-dvh w-full flex-col'\n      >\n        <header className='flex min-h-16 items-center gap-3 px-4 @2xl:px-8'>\n          <a\n            href={SITE.homeHref}\n            className={cn(\n              'flex items-center gap-2 rounded-md text-sm font-semibold',\n              FOCUS_RING\n            )}\n          >\n            <CompanyMark seed={SITE.name} size='lg' />\n            {SITE.name}\n          </a>\n          <span className='flex-1' />\n          <ReplayButton isShown={canReplay} onReplay={restart} label='Replay' />\n        </header>\n\n        <main className='flex flex-1 flex-col items-center px-4 pt-6 pb-16 @2xl:pt-12'>\n          <div className='flex w-full max-w-md flex-col items-center gap-7'>\n            <ServerStack status={state.status} />\n\n            <div className='flex flex-col items-center gap-3 text-center'>\n              <p className='text-muted-foreground text-xs tabular-nums'>\n                {codeLineOf(state)}\n              </p>\n              <h1 className='text-2xl font-semibold @sm:text-3xl'>\n                <WordRoll text={title} />\n              </h1>\n              <p\n                key={title}\n                className={cn(\n                  'text-muted-foreground text-sm text-pretty',\n                  leadEntranceOf(hasTitleChanged)\n                )}\n              >\n                {leadOf(state)}\n              </p>\n            </div>\n\n            <div\n              ref={actionsRef}\n              className='flex flex-wrap items-center justify-center gap-2'\n            >\n              <AnimatePresence mode='popLayout' initial={false}>\n                {!isRecovered && (\n                  <motion.span\n                    key='retry'\n                    className='inline-flex'\n                    {...presence}\n                  >\n                    <MorphButton\n                      type='button'\n                      size='lg'\n                      data-retry\n                      state={RETRY_STATE[state.status]}\n                      labels={RETRY_LABELS}\n                      onClick={() => act({ type: 'retried' })}\n                      className={pressedSolidOf(pressed === 'retry')}\n                    />\n                  </motion.span>\n                )}\n                {!isRecovered && (\n                  <motion.span\n                    key='dashboard'\n                    className='inline-flex'\n                    {...presence}\n                  >\n                    <Button\n                      size='lg'\n                      variant='outline'\n                      nativeButton={false}\n                      render={<a href={SITE.homeHref} />}\n                    >\n                      Go to dashboard\n                    </Button>\n                  </motion.span>\n                )}\n                {isRecovered && (\n                  <motion.span\n                    key='continue'\n                    className='inline-flex'\n                    {...presence}\n                  >\n                    <Button\n                      size='lg'\n                      nativeButton={false}\n                      data-continue\n                      render={<a href={SITE.continueHref} />}\n                    >\n                      Continue to invoices\n                      <ArrowRightIcon />\n                    </Button>\n                  </motion.span>\n                )}\n              </AnimatePresence>\n            </div>\n\n            <Fold open={!isRecovered} className='w-full'>\n              <div className='bg-card hairline-ring ring-border dark:bg-foreground/[0.03] flex flex-col gap-1 rounded-xl p-1.5 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n                <div className='flex items-center gap-3 rounded-lg px-2.5 py-2'>\n                  <span\n                    aria-hidden='true'\n                    className='bg-warning size-2 shrink-0 rounded-full'\n                  />\n                  <div className='flex min-w-0 flex-1 flex-col'>\n                    <p className='text-[13px] font-medium'>\n                      {INCIDENT.service}\n                    </p>\n                    <p className='text-muted-foreground truncate text-xs'>\n                      {INCIDENT.note}\n                    </p>\n                  </div>\n                  <a\n                    href={SITE.statusHref}\n                    target='_blank'\n                    rel='noreferrer'\n                    className={cn(\n                      'text-primary-ink inline-flex shrink-0 items-center gap-1 rounded-sm text-xs font-medium underline-offset-4 hover:underline',\n                      FOCUS_RING\n                    )}\n                  >\n                    Status page\n                    <ArrowUpRightIcon className='size-3.5' />\n                  </a>\n                </div>\n                <div className='bg-foreground/[0.03] flex items-center gap-3 rounded-lg px-2.5 py-2'>\n                  <div className='flex min-w-0 flex-1 flex-col'>\n                    <p className='text-muted-foreground text-xs'>Error ID</p>\n                    <p className='truncate font-mono text-[13px]'>{ERROR_ID}</p>\n                  </div>\n                  <CopyIdButton\n                    isCopied={state.isCopied}\n                    isPressed={pressed === 'copy'}\n                    onCopy={copyId}\n                  />\n                </div>\n                <p className='text-muted-foreground px-2.5 pt-1.5 pb-1 text-xs text-pretty'>\n                  If it keeps happening, send this ID to{' '}\n                  <a\n                    href={SITE.supportHref}\n                    className={cn(\n                      'text-primary-ink rounded-sm font-medium underline-offset-4 hover:underline',\n                      FOCUS_RING\n                    )}\n                  >\n                    {SITE.supportAddress}\n                  </a>\n                  .\n                </p>\n              </div>\n            </Fold>\n          </div>\n        </main>\n        <LiveRegion message={message} />\n      </div>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/error-pages-02/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/error-pages/error-pages-02/server-stack.tsx",
      "content": "'use client';\n\nimport { motion, type Transition } from 'motion/react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport type { LoadStatus } from './session';\n\ntype PlateTone = 'ok' | 'error' | 'running';\n\nconst PLATE_TOPS = [14, 50, 86];\n\nconst MIDDLE_PLATE = 1;\n\nconst LIGHT_XS = [46, 56, 66];\n\nconst VENT_XS = [140, 146, 152];\n\nconst FIRST_LIGHT_FILL: Record<PlateTone, string> = {\n  ok: 'fill-success',\n  error: 'fill-destructive',\n  running: 'fill-info',\n};\n\nconst PLATE_TINT: Record<PlateTone, string> = {\n  ok: 'fill-transparent',\n  error: 'fill-destructive/[0.07]',\n  running: 'fill-info/[0.06]',\n};\n\nconst BLINK = { opacity: [0.25, 1, 0.25] };\n\nfunction blinkOf(index: number): Transition {\n  return {\n    duration: 0.9,\n    ease: 'easeInOut',\n    repeat: Infinity,\n    delay: index * 0.15,\n  };\n}\n\nfunction middleToneOf(status: LoadStatus): PlateTone {\n  if (status === 'retrying') {\n    return 'running';\n  }\n  if (status === 'recovered') {\n    return 'ok';\n  }\n  return 'error';\n}\n\nfunction toneOf(index: number, status: LoadStatus): PlateTone {\n  if (index === MIDDLE_PLATE) {\n    return middleToneOf(status);\n  }\n  return 'ok';\n}\n\n/** The lights only blink while a retry is really on its way. */\nfunction RunningLights({ y }: { y: number }) {\n  return (\n    <>\n      {LIGHT_XS.map((x, index) => (\n        <motion.circle\n          key={x}\n          cx={x}\n          cy={y}\n          r='3'\n          className='fill-info'\n          initial={{ opacity: 0.25 }}\n          animate={BLINK}\n          transition={blinkOf(index)}\n        />\n      ))}\n    </>\n  );\n}\n\nfunction StillLights({ y, tone }: { y: number; tone: PlateTone }) {\n  const [firstX, ...otherXs] = LIGHT_XS;\n\n  return (\n    <>\n      <circle\n        cx={firstX}\n        cy={y}\n        r='3'\n        className={cn('transition-[fill] duration-300', FIRST_LIGHT_FILL[tone])}\n      />\n      {otherXs.map((x) => (\n        <circle key={x} cx={x} cy={y} r='3' className='fill-foreground/15' />\n      ))}\n    </>\n  );\n}\n\nfunction Plate({ top, tone }: { top: number; tone: PlateTone }) {\n  const lightY = top + 14;\n  const ventTop = top + 9;\n  const ventBottom = top + 19;\n  const isRunning = tone === 'running';\n\n  return (\n    <g>\n      <rect\n        x='30'\n        y={top}\n        width='140'\n        height='28'\n        rx='7'\n        strokeWidth='1'\n        vectorEffect='non-scaling-stroke'\n        className='fill-card stroke-border'\n      />\n      <rect\n        x='30'\n        y={top}\n        width='140'\n        height='28'\n        rx='7'\n        className={cn('transition-[fill] duration-300', PLATE_TINT[tone])}\n      />\n      {isRunning && <RunningLights y={lightY} />}\n      {!isRunning && <StillLights y={lightY} tone={tone} />}\n      <rect\n        x='82'\n        y={lightY - 2}\n        width='40'\n        height='4'\n        rx='2'\n        className='fill-foreground/10'\n      />\n      {VENT_XS.map((x) => (\n        <line\n          key={x}\n          x1={x}\n          x2={x}\n          y1={ventTop}\n          y2={ventBottom}\n          strokeWidth='1.5'\n          strokeLinecap='round'\n          className='stroke-foreground/15'\n        />\n      ))}\n    </g>\n  );\n}\n\nexport function ServerStack({ status }: { status: LoadStatus }) {\n  return (\n    <svg\n      viewBox='0 0 200 128'\n      aria-hidden='true'\n      className='w-full max-w-[12rem] overflow-visible'\n    >\n      <ellipse\n        cx='100'\n        cy='122'\n        rx='76'\n        ry='4'\n        className='fill-foreground/[0.05]'\n      />\n      {PLATE_TOPS.map((top, index) => (\n        <Plate key={top} top={top} tone={toneOf(index, status)} />\n      ))}\n    </svg>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/error-pages-02/server-stack.tsx"
    },
    {
      "path": "registry/ndeko/blocks/error-pages/error-pages-02/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\n\nexport type LoadStatus = 'error' | 'retrying' | 'recovered';\n\nexport type ServerState = {\n  status: LoadStatus;\n  /** Retries asked for so far. The page itself was the first try. */\n  attempts: number;\n  failures: number;\n  isCopied: boolean;\n  spoken: string;\n};\n\nexport type ServerAction =\n  | { type: 'retried' }\n  | { type: 'answered'; attempt: number }\n  | { type: 'copied' }\n  | { type: 'copyReset' };\n\ntype Step = SessionStep<ServerState, ServerAction>;\n\nexport const RETRY_MS = 1500;\n\n/** The simulated server fails the first retry and answers the second. */\nconst SUCCEEDS_ON_ATTEMPT = 2;\n\nexport const INITIAL: ServerState = {\n  status: 'error',\n  attempts: 0,\n  failures: 0,\n  isCopied: false,\n  spoken: '',\n};\n\nfunction triesLineOf(attempts: number) {\n  const tries = attempts + 1;\n  return `Still not working after ${tries} tries`;\n}\n\nfunction retried(state: ServerState): ServerState {\n  if (state.status !== 'error') {\n    return state;\n  }\n  return {\n    ...state,\n    status: 'retrying',\n    attempts: state.attempts + 1,\n    spoken: 'Retrying',\n  };\n}\n\n/** An answer only counts for the retry it belongs to. */\nfunction answered(state: ServerState, attempt: number): ServerState {\n  const isWaiting = state.status === 'retrying';\n  const isCurrent = attempt === state.attempts;\n  if (!isWaiting || !isCurrent) {\n    return state;\n  }\n  if (attempt >= SUCCEEDS_ON_ATTEMPT) {\n    return { ...state, status: 'recovered', spoken: 'The page loaded' };\n  }\n  return {\n    ...state,\n    status: 'error',\n    failures: state.failures + 1,\n    spoken: triesLineOf(state.attempts),\n  };\n}\n\nexport function reducer(state: ServerState, action: ServerAction) {\n  switch (action.type) {\n    case 'retried':\n      return retried(state);\n    case 'answered':\n      return answered(state, action.attempt);\n    case 'copied':\n      return { ...state, isCopied: true, spoken: 'Error ID copied' };\n    case 'copyReset':\n      return { ...state, isCopied: false };\n  }\n}\n\n/**\n * A person tries again and gets the same error, copies the ID for support, and tries once more.\n * The server answers on its own, whoever pressed.\n */\nexport const SCRIPT: Step[] = [\n  { after: 1700, by: 'demo', press: 'retry', action: { type: 'retried' } },\n  {\n    after: RETRY_MS + 1300,\n    by: 'demo',\n    press: 'copy',\n    action: { type: 'copied' },\n  },\n  { after: 1900, by: 'demo', press: 'retry', action: { type: 'retried' } },\n];\n\n/** Under reduced motion the page shows the error after one retry that failed. */\nexport const RESTING: ServerState = {\n  status: 'error',\n  attempts: 1,\n  failures: 1,\n  isCopied: false,\n  spoken: '',\n};\n\nexport const LOOP_AFTER_MS = RETRY_MS + 3200;\n",
      "type": "registry:component",
      "target": "components/blocks/error-pages-02/session.ts"
    },
    {
      "path": "registry/ndeko/blocks/error-pages/error-pages-02/data.ts",
      "content": "export const SITE = {\n  name: 'Alderbrook',\n  homeHref: '#',\n  statusHref: 'https://status.copperleaf.example',\n  supportHref: 'mailto:help@copperleaf.example',\n  supportAddress: 'help@copperleaf.example',\n  continueHref: '#invoices',\n};\n\nexport const ERROR_ID = 'req_8f3k2q7wm4x1';\n\nexport const INCIDENT = {\n  service: 'Invoices service',\n  note: 'Slower than usual since 09:12 UTC',\n};\n",
      "type": "registry:component",
      "target": "components/blocks/error-pages-02/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "error-pages"
  ],
  "type": "registry:block"
}