{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"uptime-bar","type":"registry:component","title":"Uptime bar","description":"Point at any day and the row's own caption tells you what happened.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/uptime-bar.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\nimport { cn } from \"@/lib/utils\";\n\nexport type Incident = {\n  // Days before today: 0 is today.\n  daysAgo: number;\n  level: \"degraded\" | \"outage\";\n  title: string;\n  minutes: number;\n};\n\nexport type Service = { name: string; incidents: Incident[] };\n\n// Status colours are data, so raw values. Healthy days are a quiet,\n// low-chroma green so two months of calm doesn't shout; amber and red keep\n// their strength, since incidents are what you came to find.\nconst COLOR = {\n  ok: \"light-dark(oklch(0.8 0.09 160), oklch(0.58 0.08 160))\",\n  degraded: \"oklch(0.8 0.15 78)\",\n  outage: \"oklch(0.64 0.2 25)\",\n} as const;\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst DAY_MINUTES = 1440;\n\nconst ago = (d: number) =>\n  d === 0 ? \"Today\" : d === 1 ? \"Yesterday\" : `${d} days ago`;\n\nconst short = (m: number) =>\n  m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`;\n\nfunction uptime(service: Service, days: number) {\n  const down = service.incidents\n    .filter((i) => i.daysAgo < days)\n    // Degraded counts at a third: slow isn't down, but it isn't fine.\n    .reduce(\n      (t, i) => t + (i.level === \"outage\" ? i.minutes : i.minutes / 3),\n      0,\n    );\n  return (100 * (1 - down / (days * DAY_MINUTES))).toFixed(2);\n}\n\ntype Spot = { row: number; day: number };\n\nexport function UptimeBar({\n  services,\n  spot: controlled,\n  className,\n}: {\n  services: Service[];\n  // Drives the highlight from outside (the card preview); null clears it.\n  spot?: Spot | null;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const root = useRef<HTMLDivElement>(null);\n  // A phone gets half the history so every day stays a real, tappable bar.\n  const [days, setDays] = useState(60);\n  const [hover, setHover] = useState<Spot | null>(null);\n  const spot = controlled !== undefined ? controlled : hover;\n\n  useLayoutEffect(() => {\n    const el = root.current;\n    if (!el) return;\n    const measure = () => setDays(el.offsetWidth < 400 ? 30 : 60);\n    measure();\n    const ro = new ResizeObserver(measure);\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  const incidentOn = (s: Service, day: number) =>\n    s.incidents.find((i) => i.daysAgo === day);\n  const operational = services.every((s) => !incidentOn(s, 0));\n\n  // Divides out any CSS scale, so the maths holds inside a scaled card.\n  const pick = (row: number, e: React.PointerEvent<HTMLDivElement>) => {\n    const el = e.currentTarget;\n    const rect = el.getBoundingClientRect();\n    const x = (e.clientX - rect.left) / (rect.width / el.offsetWidth || 1);\n    const index = Math.min(\n      days - 1,\n      Math.max(0, Math.floor((x / el.offsetWidth) * days)),\n    );\n    const day = days - 1 - index;\n    if (hover?.row !== row || hover.day !== day) setHover({ row, day });\n  };\n\n  const swap = reduceMotion\n    ? { duration: 0 }\n    : { duration: 0.2, ease: EASE_OUT };\n\n  return (\n    <div ref={root} className={cn(\"w-[min(440px,100%)]\", className)}>\n      <div className=\"flex items-center justify-between\">\n        <p className=\"flex items-center gap-2 text-[15px] font-medium text-foreground\">\n          <span\n            className=\"size-2 rounded-full\"\n            style={{ background: operational ? COLOR.ok : COLOR.degraded }}\n          />\n          {operational ? \"All systems operational\" : \"Some systems degraded\"}\n        </p>\n        <p className=\"text-[13px] text-muted-foreground tabular-nums\">\n          Last {days} days\n        </p>\n      </div>\n\n      <div className=\"mt-6 flex flex-col gap-6\">\n        {services.map((s, r) => {\n          const here = spot?.row === r ? spot : null;\n          const inc = here ? incidentOn(s, here.day) : undefined;\n          return (\n            <div key={s.name}>\n              <div className=\"mb-2.5 flex h-5 items-center justify-between gap-4 text-[14px]\">\n                <span className=\"shrink-0 font-medium text-foreground\">\n                  {s.name}\n                </span>\n                {/* The caption is the readout: point at a day and the\n                    uptime figure becomes that day's story, in place. */}\n                <span className=\"flex min-w-0 items-center justify-end gap-2 text-muted-foreground\">\n                  {here && (\n                    <span className=\"shrink-0 tabular-nums\">\n                      {ago(here.day)}\n                    </span>\n                  )}\n                  <AnimatePresence initial={false} mode=\"popLayout\">\n                    <motion.span\n                      key={here ? (inc ? inc.title : \"ok\") : \"uptime\"}\n                      initial={{ opacity: 0, y: 4, filter: \"blur(4px)\" }}\n                      animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n                      exit={{\n                        opacity: 0,\n                        y: -4,\n                        filter: \"blur(4px)\",\n                        transition: { duration: 0.12 },\n                      }}\n                      transition={swap}\n                      className=\"flex min-w-0 items-center gap-1.5\"\n                    >\n                      {here ? (\n                        <>\n                          <span\n                            className=\"size-1.5 shrink-0 rounded-full\"\n                            style={{\n                              background: inc ? COLOR[inc.level] : COLOR.ok,\n                            }}\n                          />\n                          <span\n                            className={cn(\"truncate\", inc && \"text-foreground\")}\n                          >\n                            {inc\n                              ? `${inc.title}, ${short(inc.minutes)}`\n                              : \"No downtime\"}\n                          </span>\n                        </>\n                      ) : (\n                        <span className=\"tabular-nums\">\n                          {uptime(s, days)}% uptime\n                        </span>\n                      )}\n                    </motion.span>\n                  </AnimatePresence>\n                </span>\n              </div>\n\n              <div\n                role=\"group\"\n                tabIndex={0}\n                aria-label={`${s.name}: ${uptime(s, days)}% uptime over ${days} days. Arrow keys step through days.`}\n                onPointerMove={(e) => pick(r, e)}\n                onPointerLeave={() => setHover(null)}\n                onFocus={() =>\n                  setHover((h) => (h?.row === r ? h : { row: r, day: 0 }))\n                }\n                onBlur={() => setHover(null)}\n                onKeyDown={(e) => {\n                  const step =\n                    e.key === \"ArrowLeft\" ? 1 : e.key === \"ArrowRight\" ? -1 : 0;\n                  if (e.key === \"Home\") setHover({ row: r, day: days - 1 });\n                  else if (e.key === \"End\") setHover({ row: r, day: 0 });\n                  else if (e.key === \"Escape\") setHover(null);\n                  else if (step) {\n                    e.preventDefault();\n                    setHover((h) => ({\n                      row: r,\n                      day: Math.min(\n                        days - 1,\n                        Math.max(0, (h?.row === r ? h.day : 0) + step),\n                      ),\n                    }));\n                  }\n                }}\n                className=\"flex h-7 cursor-default gap-[3px] rounded-[4px] outline-hidden focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-solid focus-visible:outline-foreground\"\n              >\n                {Array.from({ length: days }, (_, i) => {\n                  const day = days - 1 - i;\n                  const bad = incidentOn(s, day);\n                  const on = here?.day === day;\n                  return (\n                    <span\n                      key={day}\n                      className=\"h-full min-w-0 flex-1 rounded-[2px] transition-[opacity,transform] duration-150 ease-out\"\n                      style={{\n                        background: bad ? COLOR[bad.level] : COLOR.ok,\n                        // The rest of the row steps back so the day you're\n                        // on is the one that reads.\n                        opacity: here && !on ? 0.35 : 1,\n                        transform:\n                          on && !reduceMotion ? \"scaleY(1.15)\" : \"none\",\n                      }}\n                    />\n                  );\n                })}\n              </div>\n            </div>\n          );\n        })}\n      </div>\n\n      <div className=\"mt-3 flex justify-between text-[12px] text-muted-foreground\">\n        <span>{days} days ago</span>\n        <span>Today</span>\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {spot\n          ? `${services[spot.row].name}, ${ago(spot.day)}: ${(() => {\n              const inc = incidentOn(services[spot.row], spot.day);\n              return inc ? `${inc.title}, ${short(inc.minutes)}` : \"no downtime\";\n            })()}`\n          : \"\"}\n      </p>\n    </div>\n  );\n}\n\nconst SERVICES: Service[] = [\n  {\n    name: \"API\",\n    incidents: [\n      { daysAgo: 51, level: \"degraded\", title: \"Elevated errors\", minutes: 38 },\n      { daysAgo: 22, level: \"outage\", title: \"Database failover\", minutes: 72 },\n      { daysAgo: 6, level: \"degraded\", title: \"High latency\", minutes: 21 },\n    ],\n  },\n  {\n    name: \"Dashboard\",\n    incidents: [\n      { daysAgo: 40, level: \"degraded\", title: \"Slow page loads\", minutes: 44 },\n      { daysAgo: 12, level: \"degraded\", title: \"Stale charts\", minutes: 16 },\n    ],\n  },\n  {\n    name: \"Webhooks\",\n    incidents: [\n      { daysAgo: 57, level: \"degraded\", title: \"Delayed deliveries\", minutes: 30 },\n      { daysAgo: 18, level: \"outage\", title: \"Deliveries paused\", minutes: 26 },\n      { daysAgo: 17, level: \"degraded\", title: \"Retry backlog\", minutes: 55 },\n    ],\n  },\n];\n\n// The card's hover show: skimming the API row, resting on the outage, then\n// the same on webhooks. [where, how long to stay]\nconst SWEEP: [Spot, number][] = [\n  [{ row: 0, day: 30 }, 120],\n  [{ row: 0, day: 27 }, 120],\n  [{ row: 0, day: 24 }, 120],\n  [{ row: 0, day: 22 }, 1500],\n  [{ row: 2, day: 22 }, 120],\n  [{ row: 2, day: 20 }, 120],\n  [{ row: 2, day: 18 }, 1500],\n  [{ row: 2, day: 17 }, 1300],\n];\n\nexport default function UptimeBarDemo() {\n  const play = usePreviewPlay();\n  const [spot, setSpot] = useState<Spot | null>(null);\n\n  useEffect(() => {\n    if (play !== true) return;\n    let timer: ReturnType<typeof setTimeout>;\n    let i = 0;\n    const next = () => {\n      const [s, stay] = SWEEP[i % SWEEP.length];\n      setSpot(s);\n      i++;\n      timer = setTimeout(next, stay);\n    };\n    timer = setTimeout(next, 200);\n    return () => {\n      clearTimeout(timer);\n      setSpot(null);\n    };\n  }, [play]);\n\n  return (\n    <UptimeBar services={SERVICES} spot={play === null ? undefined : spot} />\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"}],"categories":["data"],"docs":"From ui lab: https://lab.xevrion.dev/lab/uptime-bar"}